diff --git a/.circleci/requirements.txt b/.circleci/requirements.txt index a5ec74424fe..ab4c3995772 100644 --- a/.circleci/requirements.txt +++ b/.circleci/requirements.txt @@ -17,4 +17,5 @@ mcp==1.25.0 # for MCP server semantic_router==0.1.10 # for auto-routing with litellm fastuuid==0.12.0 responses==0.25.7 # for proxy client tests -pytest-retry==1.6.3 # for automatic test retries \ No newline at end of file +pytest-retry==1.6.3 # for automatic test retries +litellm-proxy-extras # for prisma migrations \ No newline at end of file diff --git a/.github/workflows/test-linting.yml b/.github/workflows/test-linting.yml index e918a71373a..fc0f84a20d4 100644 --- a/.github/workflows/test-linting.yml +++ b/.github/workflows/test-linting.yml @@ -33,10 +33,10 @@ jobs: poetry lock poetry install --with dev - - name: Run Black formatting + - name: Check Black formatting run: | cd litellm - poetry run black . + poetry run black --check --exclude '/enterprise/' . cd .. - name: Debug - Check file state diff --git a/CLAUDE.md b/CLAUDE.md index 5d62d2cdcda..5395d6d938e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -91,6 +91,10 @@ LiteLLM is a unified interface for 100+ LLM providers with two main components: - 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. +- **Use dict spread for immutable copies** — prefer `{**original, "key": new_value}` over `dict(obj)` + mutation. The spread produces the final dict in one step and makes intent clear. +- **Guard at resolution time** — when resolving an optional value through a fallback chain (`a or b or ""`), raise immediately if the resolved result being empty is an error. Don't pass empty strings or sentinel values downstream for the callee to deal with. +- **Extract complex comprehensions to named helpers** — a set/dict comprehension that calls into the DB or manager (e.g. "which of these server IDs are OAuth2?") belongs in a named helper function, not inline in the caller. +- **FastAPI parameter declarations** — mark required query/form params with `= Query(...)` / `= Form(...)` explicitly when other params in the same handler are optional. Mixing `str` (required) with `Optional[str] = None` in the same signature causes silent 422s when the required param is missing. ### Testing Strategy - Unit tests in `tests/test_litellm/` @@ -98,6 +102,8 @@ LiteLLM is a unified interface for 100+ LLM providers with two main components: - Proxy tests in `tests/proxy_unit_tests/` - Load tests in `tests/load_tests/` - **Always add tests when adding new entity types or features** — if the existing test file covers other entity types, add corresponding tests for the new one +- **Keep monkeypatch stubs in sync with real signatures** — when a function gains a new optional parameter, update every `fake_*` / `stub_*` in tests that patch it to also accept that kwarg (even as `**kwargs`). Stale stubs fail with `unexpected keyword argument` and mask real bugs. +- **Test all branches of name→ID resolution** — when adding server/resource lookup that resolves names to UUIDs, test: (1) name resolves and UUID is allowed, (2) name resolves but UUID is not allowed, (3) name does not resolve at all. The silent-fallback path is where access-control bugs hide. ### UI / Backend Consistency - When wiring a new UI entity type to an existing backend endpoint, verify the backend API contract (single value vs. array, required vs. optional params) and ensure the UI controls match — e.g., use a single-select dropdown when the backend accepts a single value, not a multi-select diff --git a/Dockerfile b/Dockerfile index 75ccff29663..4c6f22a95b7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -49,7 +49,7 @@ USER root # Install runtime dependencies (libsndfile needed for audio processing on ARM64) RUN apk add --no-cache bash openssl tzdata nodejs npm python3 py3-pip libsndfile && \ - npm install -g npm@latest tar@7.5.10 glob@11.1.0 @isaacs/brace-expansion@5.0.1 minimatch@10.2.4 diff@8.0.3 && \ + npm install -g npm@latest tar@7.5.11 glob@11.1.0 @isaacs/brace-expansion@5.0.1 minimatch@10.2.4 diff@8.0.3 && \ # SECURITY FIX: npm bundles tar, glob, and brace-expansion at multiple nested # levels inside its dependency tree. `npm install -g ` only creates a # SEPARATE global package, it does NOT replace npm's internal copies. diff --git a/deploy/charts/litellm-helm/templates/deployment.yaml b/deploy/charts/litellm-helm/templates/deployment.yaml index 51af22b7a46..3040fb45d86 100644 --- a/deploy/charts/litellm-helm/templates/deployment.yaml +++ b/deploy/charts/litellm-helm/templates/deployment.yaml @@ -20,6 +20,9 @@ spec: selector: matchLabels: {{- include "litellm.selectorLabels" . | nindent 6 }} + {{- if .Values.deploymentMinReadySeconds }} + minReadySeconds: {{ .Values.deploymentMinReadySeconds }} + {{- end }} template: metadata: annotations: diff --git a/deploy/charts/litellm-helm/tests/deployment_tests.yaml b/deploy/charts/litellm-helm/tests/deployment_tests.yaml index 2e9c48043de..0d278f25693 100644 --- a/deploy/charts/litellm-helm/tests/deployment_tests.yaml +++ b/deploy/charts/litellm-helm/tests/deployment_tests.yaml @@ -306,3 +306,16 @@ tests: - equal: path: spec.template.spec.containers[0].resources value: {} + - it: should be able to set minReadySeconds + template: deployment.yaml + set: + deploymentMinReadySeconds: 5 + asserts: + - equal: + path: spec.minReadySeconds + value: 5 + - it: should have minReadySeconds absent when deploymentMinReadySeconds is not set + template: deployment.yaml + asserts: + - notExists: + path: spec.minReadySeconds diff --git a/deploy/charts/litellm-helm/values.yaml b/deploy/charts/litellm-helm/values.yaml index f8944bddd53..690ca69e730 100644 --- a/deploy/charts/litellm-helm/values.yaml +++ b/deploy/charts/litellm-helm/values.yaml @@ -31,6 +31,8 @@ serviceAccount: # annotations for litellm deployment deploymentAnnotations: {} deploymentLabels: {} +deploymentMinReadySeconds: 0 + # annotations for litellm pods podAnnotations: {} podLabels: {} diff --git a/docker/Dockerfile.custom_ui b/docker/Dockerfile.custom_ui index 4052c7a51bc..c1bd9a383fa 100644 --- a/docker/Dockerfile.custom_ui +++ b/docker/Dockerfile.custom_ui @@ -19,7 +19,7 @@ RUN apt-get update && apt-get upgrade -y \ libgnutls30 \ libc6 && \ apt-get install -y nodejs npm && \ - npm install -g npm@latest tar@7.5.10 glob@11.1.0 @isaacs/brace-expansion@5.0.1 minimatch@10.2.4 diff@8.0.3 && \ + npm install -g npm@latest tar@7.5.11 glob@11.1.0 @isaacs/brace-expansion@5.0.1 minimatch@10.2.4 diff@8.0.3 && \ GLOBAL="$(npm root -g)" && \ find "$GLOBAL/npm" -type d -name "tar" -path "*/node_modules/tar" | while read d; do \ rm -rf "$d" && cp -rL "$GLOBAL/tar" "$d"; \ diff --git a/docker/Dockerfile.database b/docker/Dockerfile.database index 962d129e57f..b69dc049ce9 100644 --- a/docker/Dockerfile.database +++ b/docker/Dockerfile.database @@ -50,7 +50,7 @@ USER root # Install runtime dependencies RUN apk add --no-cache bash openssl tzdata nodejs npm python3 py3-pip libsndfile && \ - npm install -g npm@latest tar@7.5.10 glob@11.1.0 @isaacs/brace-expansion@5.0.1 minimatch@10.2.4 diff@8.0.3 && \ + npm install -g npm@latest tar@7.5.11 glob@11.1.0 @isaacs/brace-expansion@5.0.1 minimatch@10.2.4 diff@8.0.3 && \ GLOBAL="$(npm root -g)" && \ find "$GLOBAL/npm" -type d -name "tar" -path "*/node_modules/tar" | while read d; do \ rm -rf "$d" && cp -rL "$GLOBAL/tar" "$d"; \ diff --git a/docker/Dockerfile.dev b/docker/Dockerfile.dev index cfc4c646ba2..17fb3733b1c 100644 --- a/docker/Dockerfile.dev +++ b/docker/Dockerfile.dev @@ -75,7 +75,7 @@ RUN apt-get update && apt-get upgrade -y \ nodejs \ npm \ && rm -rf /var/lib/apt/lists/* \ - && npm install -g npm@latest tar@7.5.10 glob@11.1.0 @isaacs/brace-expansion@5.0.1 minimatch@10.2.4 diff@8.0.3 \ + && npm install -g npm@latest tar@7.5.11 glob@11.1.0 @isaacs/brace-expansion@5.0.1 minimatch@10.2.4 diff@8.0.3 \ && GLOBAL="$(npm root -g)" \ && find "$GLOBAL/npm" -type d -name "tar" -path "*/node_modules/tar" | while read d; do \ rm -rf "$d" && cp -rL "$GLOBAL/tar" "$d"; \ diff --git a/docs/my-website/blog/realtime_webrtc_http_endpoints/index.md b/docs/my-website/blog/realtime_webrtc_http_endpoints/index.md new file mode 100644 index 00000000000..04c3d3c9097 --- /dev/null +++ b/docs/my-website/blog/realtime_webrtc_http_endpoints/index.md @@ -0,0 +1,119 @@ +--- +slug: realtime_webrtc_http_endpoints +title: "Realtime WebRTC HTTP Endpoints" +date: 2026-03-12T10: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: 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: "Use the LiteLLM proxy to route OpenAI-style WebRTC realtime via HTTP: client_secrets and SDP exchange." +tags: [realtime, webrtc, proxy, openai] +hide_table_of_contents: false +--- + +import WebRTCTester from '@site/src/components/WebRTCTester'; + +Connect to the Realtime API via WebRTC from browser/mobile clients. LiteLLM handles auth and key management. + +## How it works + +![WebRTC flow: Browser, LiteLLM Proxy, and OpenAI/Azure](../../img/webrtc_flow.png) + +**Flow of generating ephemeral token** + +![Ephemeral token flow: Browser requests token, LiteLLM gets real token from OpenAI, returns encrypted token](../../img/ephemeral_token.png) + + +## Proxy Setup + +```yaml +model_list: + - model_name: gpt-4o-realtime + litellm_params: + model: openai/gpt-4o-realtime-preview-2024-12-17 + api_key: os.environ/OPENAI_API_KEY + model_info: + mode: realtime +``` + +**Azure:** use `model: azure/gpt-4o-realtime-preview`, `api_key`, `api_base`. + +```bash +litellm --config /path/to/config.yaml +``` + +## Try it live + + + +## Client Usage + +**1. Get token** - `POST /v1/realtime/client_secrets` with LiteLLM API key and `{ model }`. + +**2. WebRTC handshake** - Create `RTCPeerConnection`, add mic track, create data channel `oai-events`, send SDP offer to `POST /v1/realtime/calls` with `Authorization: Bearer ` and `Content-Type: application/sdp`. + +**3. Events** - Use the data channel for `session.update` and other events. + +
+Full code example + +```javascript +// 1. Token +const r = await fetch("http://proxy:4000/v1/realtime/client_secrets", { + method: "POST", + headers: { "Authorization": "Bearer sk-litellm-key", "Content-Type": "application/json" }, + body: JSON.stringify({ model: "gpt-4o-realtime" }), +}); +const { client_secret } = await r.json(); +const token = client_secret.value; + +// 2. WebRTC +const pc = new RTCPeerConnection(); +const audio = document.createElement("audio"); +audio.autoplay = true; +pc.ontrack = (e) => (audio.srcObject = e.streams[0]); +const ms = await navigator.mediaDevices.getUserMedia({ audio: true }); +pc.addTrack(ms.getTracks()[0]); +const dc = pc.createDataChannel("oai-events"); +const offer = await pc.createOffer(); +await pc.setLocalDescription(offer); + +const sdpRes = await fetch("http://proxy:4000/v1/realtime/calls", { + method: "POST", + headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/sdp" }, + body: offer.sdp, +}); +await pc.setRemoteDescription({ type: "answer", sdp: await sdpRes.text() }); + +// 3. Events +dc.send(JSON.stringify({ type: "session.update", session: { instructions: "..." } })); +``` + +
+ +## FAQ + +**Q: What do I do if I get a 401 Token expired error?** +A: Tokens are short-lived. Get a fresh token right before creating the WebRTC offer. + +**Q: Which key should I use for `/v1/realtime/calls`?** +A: Use the **encrypted token** from `client_secrets`, not your raw API key. + +**Q: Should I pass the `model` parameter when making the call?** +A: No, the encrypted token already encodes all routing information including model. + +**Q: How do I resolve Azure `api-version` errors?** +A: Set the correct `api_version` in `litellm_params` (or via the `AZURE_API_VERSION` environment variable), along with the right `api_base` and deployment values. + +**Q: What if I get no audio?** +A: Make sure you grant microphone permission, ensure `pc.ontrack` assigns the audio element with `autoplay` enabled, check your network/firewall for WebRTC traffic, and inspect the browser console for ICE or SDP errors. + diff --git a/docs/my-website/docs/files_endpoints.md b/docs/my-website/docs/files_endpoints.md index 30677c748a9..deb17931638 100644 --- a/docs/my-website/docs/files_endpoints.md +++ b/docs/my-website/docs/files_endpoints.md @@ -326,4 +326,10 @@ print("file content=", content.text) ### [Bedrock](./providers/bedrock_batches#4-retrieve-batch-results) +### [Anthropic](./providers/anthropic#files-api) + +:::note +Anthropic Files API has a different purpose than OpenAI's. It's **not** for Batches or Fine-tuning—it's for uploading files once and referencing them by `file_id` in multiple messages, avoiding re-uploads. File API operations are free — file content used in Messages requests is priced as input tokens. +::: + ## [Swagger API Reference](https://litellm-api.up.railway.app/#/files) diff --git a/docs/my-website/docs/providers/anthropic.md b/docs/my-website/docs/providers/anthropic.md index aa77ee7c268..50b964bd936 100644 --- a/docs/my-website/docs/providers/anthropic.md +++ b/docs/my-website/docs/providers/anthropic.md @@ -1965,6 +1965,98 @@ curl -L -X POST 'http://0.0.0.0:4000/v1/chat/completions' \ +## Files API + +Upload files once and reference them by `file_id` in multiple requests—no need to re-upload content each time. + +:::info +The `file_id` obtained from Anthropic only works with Anthropic Claude models. You cannot use it with other providers (OpenAI, Bedrock, etc.). +::: + +- **Max file size:** 500 MB | **Total storage:** 100 GB per org +- **Pricing:** File API operations are free. File content used in Messages requests is priced as input tokens. + +**Supported models by file type:** +- **Images:** All Claude 3+ models +- **PDFs:** All Claude 3.5+ models +- **Other file types** (for code execution): Claude 3.5 Haiku + all Claude 3.7+ models + +### Quick Start + +```python +import litellm +import os + +os.environ["ANTHROPIC_API_KEY"] = "sk-ant-..." + +# 1. Upload a file once +file = litellm.create_file( + file=open("document.pdf", "rb"), + purpose="messages", + custom_llm_provider="anthropic", +) + +# 2. Use file_id in messages (no re-upload needed) +response = litellm.completion( + model="anthropic/claude-sonnet-4-5-20250929", + messages=[{ + "role": "user", + "content": [ + {"type": "text", "text": "Summarize this document"}, + {"type": "file", "file": {"file_id": file.id, "format": "application/pdf"}} + ] + }] +) +``` + +### File Operations + +| Operation | Function | +|-----------|----------| +| Upload | `litellm.create_file(file, purpose="messages", custom_llm_provider="anthropic")` | +| List | `litellm.file_list(custom_llm_provider="anthropic")` | +| Retrieve | `litellm.file_retrieve(file_id, custom_llm_provider="anthropic")` | +| Delete | `litellm.file_delete(file_id, custom_llm_provider="anthropic")` | +| Download | `litellm.file_content(file_id, custom_llm_provider="anthropic")` | + +:::note +Download only works for files created by the [code execution tool](https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/code-execution-tool), not uploaded files. +::: + +### Supported Formats + +| File Type | Format Value | +|-----------|-------------| +| PDF | `application/pdf` | +| Plain text | `text/plain` | +| JPEG | `image/jpeg` | +| PNG | `image/png` | +| GIF | `image/gif` | +| WebP | `image/webp` | + +### Using Images + +```python +# Upload image +image = litellm.create_file( + file=open("photo.jpg", "rb"), + purpose="messages", + custom_llm_provider="anthropic", +) + +# Use in message +response = litellm.completion( + model="anthropic/claude-sonnet-4-5-20250929", + messages=[{ + "role": "user", + "content": [ + {"type": "text", "text": "What's in this image?"}, + {"type": "file", "file": {"file_id": image.id, "format": "image/jpeg"}} + ] + }] +) +``` + ## Usage - passing 'user_id' to Anthropic LiteLLM translates the OpenAI `user` param to Anthropic's `metadata[user_id]` param. diff --git a/docs/my-website/docs/providers/openai.md b/docs/my-website/docs/providers/openai.md index 9d557303ef2..80931ad8217 100644 --- a/docs/my-website/docs/providers/openai.md +++ b/docs/my-website/docs/providers/openai.md @@ -638,7 +638,9 @@ This is useful when you want to use [Responses API](https://platform.openai.com/ :::tip gpt-5.4 + reasoning_effort + function tools -OpenAI does not support `reasoning_effort` with function tools for `gpt-5.4` in `/v1/chat/completions`. Use the responses bridge instead: +LiteLLM drops `reasoning_effort` from `gpt-5.4` requests to `litellm.completion()` that include tools, since that combination is supported in the Responses API. + +If you need reasoning **and** tools together, use the responses bridge instead: ```python response = litellm.completion( diff --git a/docs/my-website/docs/providers/vertex_partner.md b/docs/my-website/docs/providers/vertex_partner.md index 48a116eb7a8..75ec3b93087 100644 --- a/docs/my-website/docs/providers/vertex_partner.md +++ b/docs/my-website/docs/providers/vertex_partner.md @@ -11,6 +11,7 @@ import TabItem from '@theme/TabItem'; |----------|---------------|---------------| | Anthropic (Claude) | `vertex_ai/claude-*` | [Vertex AI - Anthropic Models](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-claude) | | DeepSeek | `vertex_ai/deepseek-ai/{MODEL}` | [Vertex AI - DeepSeek Models](https://cloud.google.com/vertex-ai/generative-ai/docs/maas/deepseek) | +| ZAI (GLM) | `vertex_ai/zai-org/{MODEL}` | [Vertex AI - GLM Models](https://cloud.google.com/vertex-ai/generative-ai/docs/maas/zaiorg/glm-47) | | Meta/Llama | `vertex_ai/meta/{MODEL}` | [Vertex AI - Meta Models](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/llama) | | Mistral | `vertex_ai/mistral-*` | [Vertex AI - Mistral Models](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/mistral) | | AI21 (Jamba) | `vertex_ai/jamba-*` | [Vertex AI - AI21 Models](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/ai21) | @@ -226,6 +227,79 @@ ModelResponse( |------------------|------------------------------| | vertex_ai/deepseek-ai/deepseek-r1-0528-maas | `completion('vertex_ai/deepseek-ai/deepseek-r1-0528-maas', messages)` | +## VertexAI ZAI (GLM) + +| Property | Details | +|----------|---------| +| Provider Route | `vertex_ai/zai-org/{MODEL}` | +| Vertex Documentation | [Vertex AI - GLM Models](https://cloud.google.com/vertex-ai/generative-ai/docs/maas/zaiorg/glm-47) | + +**LiteLLM Supports all Vertex AI GLM Models.** Ensure you use the `vertex_ai/zai-org/` prefix for all Vertex AI GLM models. + +| Model Name | Usage | +|------------|-------| +| vertex_ai/zai-org/glm-4.7-maas | `completion('vertex_ai/zai-org/glm-4.7-maas', messages)` | + +#### Usage + + + + +```python +from litellm import completion +import os + +os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "" + +response = completion( + model="vertex_ai/zai-org/glm-4.7-maas", + messages=[{"role": "user", "content": "hi"}], + vertex_project="your-vertex-project", + # vertex_location routes to "global" +) +print("\nModel Response", response) +``` + + + +**1. Add to config** + +```yaml +model_list: + - model_name: glm-4.7 + litellm_params: + model: vertex_ai/zai-org/glm-4.7-maas + vertex_project: "my-project" + # vertex_location routes to "global" +``` + +**2. Start proxy** + +```bash +litellm --config /path/to/config.yaml + +# RUNNING at http://0.0.0.0:4000 +``` + +**3. Test it!** + +```bash +curl --location 'http://0.0.0.0:4000/chat/completions' \ + --header 'Authorization: Bearer sk-1234' \ + --header 'Content-Type: application/json' \ + --data '{ + "model": "glm-4.7", + "messages": [ + { + "role": "user", + "content": "what llm are you" + } + ], + }' +``` + + + ## VertexAI Meta/Llama API diff --git a/docs/my-website/docs/proxy/config_settings.md b/docs/my-website/docs/proxy/config_settings.md index ea2c1700eea..65eaf14471d 100644 --- a/docs/my-website/docs/proxy/config_settings.md +++ b/docs/my-website/docs/proxy/config_settings.md @@ -910,6 +910,7 @@ router_settings: | PILLAR_API_BASE | Base URL for Pillar API Guardrails | PILLAR_API_KEY | API key for Pillar API Guardrails | PILLAR_ON_FLAGGED_ACTION | Action to take when content is flagged ('block' or 'monitor') +| PKCE_STRICT_CACHE_MISS | When set to `true`, the SSO callback will return a 401 error if the PKCE code_verifier is not found in the cache (e.g. due to a cache miss across pods). When `false` (default), it logs a warning and continues without the code_verifier. | POD_NAME | Pod name for the server, this will be [emitted to `datadog` logs](https://docs.litellm.ai/docs/proxy/logging#datadog) as `POD_NAME` | POSTHOG_API_KEY | API key for PostHog analytics integration | POSTHOG_API_URL | Base URL for PostHog API (defaults to https://us.i.posthog.com) @@ -934,6 +935,9 @@ router_settings: | PROXY_BASE_URL | Base URL for proxy service | PROXY_BATCH_WRITE_AT | Time in seconds to wait before batch writing spend logs to the database. Default is 10 | PROXY_BATCH_POLLING_INTERVAL | Time in seconds to wait before polling a batch, to check if it's completed. Default is 6000s (1 hour) +| PROXY_BATCH_POLLING_ENABLED | Set to `false` to disable the `CheckBatchCost` and `CheckResponsesCost` background polling jobs entirely. Useful for emergency mitigation on installs with large numbers of stale managed objects. Default is `true` +| MAX_OBJECTS_PER_POLL_CYCLE | Maximum number of managed objects (batches / responses) fetched per polling cycle. Prevents OOM on installs with many stale rows. Default is `50` +| MANAGED_OBJECT_STALENESS_CUTOFF_DAYS | Managed objects older than this many days in a non-terminal state are marked `stale_expired` at the start of each poll cycle and skipped. Default is `7` | PROXY_BUDGET_RESCHEDULER_MAX_TIME | Maximum time in seconds to wait before checking database for budget resets. Default is 605 | PROXY_BUDGET_RESCHEDULER_MIN_TIME | Minimum time in seconds to wait before checking database for budget resets. Default is 597 | PYTHON_GC_THRESHOLD | GC thresholds ('gen0,gen1,gen2', e.g. '1000,50,50'); defaults to Python’s values. @@ -944,7 +948,7 @@ router_settings: | QDRANT_URL | Connection URL for Qdrant database | QDRANT_VECTOR_SIZE | Vector size for Qdrant operations. Default is 1536 | REDIS_CONNECTION_POOL_TIMEOUT | Timeout in seconds for Redis connection pool. Default is 5 -| REDIS_CLUSTER_NODES | JSON-formatted list of Redis cluster startup nodes for Redis Cluster mode. Example: '[{"host": "node1", "port": 6379}]' +| REDIS_CLUSTER_NODES | JSON-formatted list of Redis cluster startup nodes for Redis Cluster mode. Example: `[{"host": "node1", "port": 6379}]` | REDIS_HOST | Hostname for Redis server | REDIS_PASSWORD | Password for Redis service | REDIS_PORT | Port number for Redis server diff --git a/docs/my-website/docs/proxy/guardrails/guardrail_policies.md b/docs/my-website/docs/proxy/guardrails/guardrail_policies.md index e2cb839203e..f4411553c69 100644 --- a/docs/my-website/docs/proxy/guardrails/guardrail_policies.md +++ b/docs/my-website/docs/proxy/guardrails/guardrail_policies.md @@ -309,6 +309,10 @@ Response: +## Policy Flow Builder + +For conditional execution (e.g., run a second guardrail only if the first fails), use the [Policy Flow Builder](./policy_flow_builder) to define pipelines with per-step pass/fail actions. + ## Config Reference ### `policies` @@ -323,6 +327,7 @@ policies: remove: [...] condition: model: ... + pipeline: ... # optional; see Policy Flow Builder ``` | Field | Type | Description | @@ -332,6 +337,7 @@ policies: | `guardrails.add` | `list[string]` | Guardrails to enable. | | `guardrails.remove` | `list[string]` | Guardrails to disable (useful with inheritance). | | `condition.model` | `string` or `list[string]` | Optional. Only apply when model matches. Supports regex. | +| `pipeline` | `object` | Optional. Ordered guardrail execution with per-step actions. See [Policy Flow Builder](./policy_flow_builder). | ### `policy_attachments` diff --git a/docs/my-website/docs/proxy/guardrails/policy_flow_builder.md b/docs/my-website/docs/proxy/guardrails/policy_flow_builder.md new file mode 100644 index 00000000000..2a83f3768ab --- /dev/null +++ b/docs/my-website/docs/proxy/guardrails/policy_flow_builder.md @@ -0,0 +1,219 @@ +# Policy Flow Builder + +The Policy Flow Builder lets you design guardrail pipelines with **conditional execution**. Instead of running guardrails independently, you chain them into ordered steps and control what happens when each guardrail passes or fails. + +Two powerful patterns it enables: **guardrail fallbacks** (try a different guardrail when one fails) and **retrying the same guardrail** (run the same guardrail again if it fails, e.g. to handle transient errors). + +## When to use the Flow Builder + +| Approach | Use case | +|----------|----------| +| **Simple policy** (`guardrails.add`) | All guardrails run in parallel; any failure blocks the request. | +| **Flow Builder** (pipeline) | Guardrails run in sequence; you choose actions per step (next, block, allow, custom response). | + +Use the Flow Builder when you need: + +- **Guardrail fallbacks** — use `on_fail: next` to try a different guardrail when one fails (e.g., fast filter → stricter filter) +- **Retrying the same guardrail** — add the same guardrail as multiple steps; if it fails, `on_fail: next` moves to the next step, which can be the same guardrail again (useful for transient API errors or rate limits) +- **Conditional routing** — e.g., if a fast guardrail fails, run a more advanced one instead of blocking immediately +- **Custom responses** — return a specific message when a guardrail fails instead of a generic block +- **Data chaining** — pass modified data (e.g., PII-masked content) from one step to the next +- **Fine-grained control** — different actions on pass vs. fail per step + +## Concepts + +### Pipeline + +A pipeline has: + +- **Mode**: `pre_call` (before the LLM) or `post_call` (after the LLM) +- **Steps**: Ordered list of guardrail steps + +### Step actions + +Each step defines what happens when the guardrail **passes** and when it **fails**: + +| Action | Description | +|--------|-------------| +| **Next Step** | Continue to the next guardrail in the pipeline | +| **Allow** | Stop the pipeline and allow the request to proceed | +| **Block** | Stop the pipeline and block the request | +| **Custom Response** | Return a custom message instead of the default block | + +### Step options + +| Field | Type | Description | +|-------|------|--------------| +| `guardrail` | `string` | Name of the guardrail to run | +| `on_pass` | `string` | Action when guardrail passes: `next`, `allow`, `block`, `modify_response` | +| `on_fail` | `string` | Action when guardrail fails: `next`, `allow`, `block`, `modify_response` | +| `pass_data` | `boolean` | Forward modified request data (e.g., PII-masked) to the next step | +| `modify_response_message` | `string` | Custom message when using `modify_response` action | + +## Using the Flow Builder (UI) + +1. Go to **Policies** in the LiteLLM Admin UI +2. Click **+ Create New Policy** or **Edit** on an existing policy +3. Select **Flow Builder** (instead of the simple form) +4. Design your flow: + - **Trigger** — Incoming LLM request (runs when the policy matches) + - **Steps** — Add guardrails, set ON PASS and ON FAIL actions per step + - **End** — Request proceeds to the LLM +5. Use the **+** between steps to insert new steps +6. Use the **Test** panel to run sample messages through the pipeline before saving +7. Click **Save** to create or update the policy + +## Config (YAML) + +Define a pipeline in your policy config: + +```yaml showLineNumbers title="config.yaml" +guardrails: + - guardrail_name: pii_masking + litellm_params: + guardrail: presidio + mode: pre_call + + - guardrail_name: prompt_injection + litellm_params: + guardrail: lakera + mode: pre_call + +policies: + my-pipeline-policy: + description: "PII mask first, then check for prompt injection" + guardrails: + add: + - pii_masking + - prompt_injection + pipeline: + mode: pre_call + steps: + - guardrail: pii_masking + on_pass: next + on_fail: block + pass_data: true + - guardrail: prompt_injection + on_pass: allow + on_fail: block + +policy_attachments: + - policy: my-pipeline-policy + scope: "*" +``` + +## Fallbacks and retries + +### Guardrail fallbacks + +Use `on_fail: next` to fall back to another guardrail when one fails. Run a lightweight guardrail first; if it fails, escalate to a stricter or different provider: + +```yaml +policies: + fallback-policy: + guardrails: + add: + - fast_content_filter + - strict_content_filter + pipeline: + mode: pre_call + steps: + - guardrail: fast_content_filter + on_pass: allow + on_fail: next + - guardrail: strict_content_filter + on_pass: allow + on_fail: block +``` + +If `fast_content_filter` passes → allow. If it fails → run `strict_content_filter`; pass → allow, fail → block. + +### Retrying the same guardrail + +Add the same guardrail as multiple steps to retry on failure. Useful for transient errors (API timeouts, rate limits): + +```yaml +policies: + retry-policy: + guardrails: + add: + - lakera_prompt_injection + pipeline: + mode: pre_call + steps: + - guardrail: lakera_prompt_injection + on_pass: allow + on_fail: next + - guardrail: lakera_prompt_injection + on_pass: allow + on_fail: block +``` + +First attempt passes → allow. First attempt fails → retry the same guardrail; second pass → allow, second fail → block. + +## Example: Custom response on fail + +Return a branded message instead of a generic block: + +```yaml +policies: + branded-block-policy: + guardrails: + add: + - pii_detector + pipeline: + mode: pre_call + steps: + - guardrail: pii_detector + on_pass: allow + on_fail: modify_response + modify_response_message: "Your message contains sensitive information. Please remove PII and try again." +``` + +## Test a pipeline (API) + +Test a pipeline with sample messages before attaching it: + +```bash +curl -X POST "http://localhost:4000/policies/test-pipeline" \ + -H "Authorization: Bearer " \ + -H "Content-Type: application/json" \ + -d '{ + "pipeline": { + "mode": "pre_call", + "steps": [ + { + "guardrail": "pii_masking", + "on_pass": "next", + "on_fail": "block", + "pass_data": true + }, + { + "guardrail": "prompt_injection", + "on_pass": "allow", + "on_fail": "block" + } + ] + }, + "test_messages": [ + {"role": "user", "content": "What is 2+2?"}, + {"role": "user", "content": "My SSN is 123-45-6789"} + ] + }' +``` + +Response includes per-step outcomes (pass/fail/error), actions taken, and timing. + +## Pipeline vs simple policy + +When a policy has a `pipeline`, the pipeline defines execution order and actions. The `guardrails.add` list must include all guardrails used in the pipeline steps. + +| Policy type | Execution | +|-------------|-----------| +| Simple (`guardrails.add` only) | All guardrails run; any failure blocks | +| Pipeline (`pipeline` present) | Steps run in order; actions control flow | + +## Related docs + +- [Guardrail Policies](./guardrail_policies) — Policy basics, attachments, inheritance +- [Policy Templates](./policy_templates) — Pre-built policy templates diff --git a/docs/my-website/docs/proxy/realtime_webrtc.md b/docs/my-website/docs/proxy/realtime_webrtc.md new file mode 100644 index 00000000000..694f293652b --- /dev/null +++ b/docs/my-website/docs/proxy/realtime_webrtc.md @@ -0,0 +1,84 @@ +# /realtime - WebRTC Support + +Connect to the Realtime API via WebRTC from browser/mobile clients. LiteLLM handles auth; audio streams directly to OpenAI/Azure. + +**Providers:** OpenAI · Azure + +:::info **WebRTC vs WebSocket** +- **WebSocket** (`/v1/realtime`) — server-to-server +- **WebRTC** (`/v1/realtime/client_secrets` + `/v1/realtime/calls`) — browser/mobile, lower latency +::: + +## How it works + +LiteLLM issues tokens and relays SDP; audio never passes through the proxy. + +``` +Browser LiteLLM Proxy OpenAI/Azure + | | | + |-- POST client_secrets --->|-- POST sessions -------->| + |<-- encrypted_token -------|<-- ek_... ---------------| + |-- POST calls [SDP+token] ->|-- POST calls ----------->| + |<-- SDP answer ------------|<-- SDP answer -----------| + |===== audio P2P direct ===============================>| +``` + +## Proxy Setup + +```yaml +model_list: + - model_name: gpt-4o-realtime + litellm_params: + model: openai/gpt-4o-realtime-preview-2024-12-17 + api_key: os.environ/OPENAI_API_KEY + model_info: + mode: realtime +``` + +**Azure:** `model: azure/gpt-4o-realtime-preview`, `api_key`, `api_base`. + +```bash +litellm --config /path/to/config.yaml +``` + +## Client Usage + +1. **Token** — `POST /v1/realtime/client_secrets` with LiteLLM key and `{ model }`. +2. **WebRTC** — Create `RTCPeerConnection`, add mic, data channel `oai-events`, send SDP offer to `POST /v1/realtime/calls` with `Authorization: Bearer `, `Content-Type: application/sdp`. +3. **Events** — Use data channel for `session.update` and other events. + +```javascript +const r = await fetch("http://proxy:4000/v1/realtime/client_secrets", { + method: "POST", + headers: { "Authorization": "Bearer sk-litellm-key", "Content-Type": "application/json" }, + body: JSON.stringify({ model: "gpt-4o-realtime" }), +}); +const token = (await r.json()).client_secret.value; + +const pc = new RTCPeerConnection(); +const audio = document.createElement("audio"); +audio.autoplay = true; +pc.ontrack = (e) => (audio.srcObject = e.streams[0]); +const ms = await navigator.mediaDevices.getUserMedia({ audio: true }); +pc.addTrack(ms.getTracks()[0]); +const dc = pc.createDataChannel("oai-events"); +const offer = await pc.createOffer(); +await pc.setLocalDescription(offer); + +const sdpRes = await fetch("http://proxy:4000/v1/realtime/calls", { + method: "POST", + headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/sdp" }, + body: offer.sdp, +}); +await pc.setRemoteDescription({ type: "answer", sdp: await sdpRes.text() }); + +dc.send(JSON.stringify({ type: "session.update", session: { instructions: "..." } })); +``` + +## FAQ + +- **401 Token expired** — Get a fresh token right before creating the WebRTC offer. +- **Which key for `/calls`?** — Encrypted token from `client_secrets`, not raw key. +- **Pass `model`?** — No. Token encodes routing. +- **Azure `api-version`** — Set `api_version` in `litellm_params` and correct `api_base`. +- **No audio** — Grant mic; ensure `pc.ontrack` sets autoplay audio; check firewall/WebRTC; inspect console. \ No newline at end of file diff --git a/docs/my-website/docs/proxy/ui/ui_edit_logo.md b/docs/my-website/docs/proxy/ui/ui_edit_logo.md new file mode 100644 index 00000000000..c62a39c0050 --- /dev/null +++ b/docs/my-website/docs/proxy/ui/ui_edit_logo.md @@ -0,0 +1,138 @@ +import Image from '@theme/IdealImage'; + +# Customize UI Logo + +Personalize your LiteLLM dashboard by replacing the default logo with your own company branding. You can set a custom logo via the UI or the API. + +## Via the UI + +### 1. Navigate to Settings + +Click the **Settings** icon in the sidebar. + +![Navigate to Settings](https://colony-recorder.s3.amazonaws.com/files/2026-03-13/57a15404-51f7-481e-9db2-cea94566d3ce/ascreenshot_7a348567c839448bb806fd71cf4abca0_text_export.jpeg) + +### 2. Open UI Theme Settings + +Click **UI Theme** from the settings menu. + +![Open UI Theme](https://colony-recorder.s3.amazonaws.com/files/2026-03-13/30663fe1-9f78-4496-96d4-c53513cbaf82/ascreenshot_ac1eb59eda0e423fbd0e7d3a6cabd4c7_text_export.jpeg) + +### 3. Click the Logo URL Field + +Click the **Logo URL** text field to start editing. + +![Click Logo URL Field](https://colony-recorder.s3.amazonaws.com/files/2026-03-13/069e8412-8ec1-4d36-ba38-6b2e2858a45a/ascreenshot_8fc7fb4a3af74815bc1b69a8554bc110_text_export.jpeg) + +### 4. Find Your Logo Image + +Open a new browser tab and find the logo image you want to use (e.g., search Google Images for your company logo). + +![Find Logo Image](https://colony-recorder.s3.amazonaws.com/files/2026-03-13/d9b55dac-bc4e-4728-b422-4afbc21f9034/ascreenshot_2a805f39c83d4b5e95f43495a6ea4e79_text_export.jpeg) + +### 5. Right-Click on the Logo Image + +Right-click the image you want to use as your logo. + +![Right-Click Image](https://colony-recorder.s3.amazonaws.com/files/2026-03-13/9d42d13e-6028-4710-acb2-c6af04a855c7/ascreenshot_0f21f29ba0e44132afe483a4b88e8b70_text_export.jpeg) + +### 6. Copy the Image Address + +Select **Copy Image Address** from the context menu to copy the URL. + +![Copy Image Address](https://colony-recorder.s3.amazonaws.com/files/2026-03-13/c25637be-383a-498b-ad11-eb1761d52757/ascreenshot_b237ee800979462189a02c1e1942ebf1_text_export.jpeg) + +### 7. Switch Back to LiteLLM + +Navigate back to the LiteLLM UI tab (e.g., press **Cmd + Left** or click the tab). + +![Switch Back](https://colony-recorder.s3.amazonaws.com/files/2026-03-13/f0647856-679c-4591-9ff7-7fd3cfbc70b4/ascreenshot_3ce46dae64c94891ac0983f5ed8f085a_text_export.jpeg) + +### 8. Paste the Logo URL + +Paste the copied image URL into the **Logo URL** field with **Cmd + V**. + +![Paste URL](https://colony-recorder.s3.amazonaws.com/files/2026-03-13/54dd30d9-7a88-41e8-a580-a6acf707c7fa/ascreenshot_8a772218ac0743d9ae8ffd3311eccd5a_text_export.jpeg) + +### 9. Save Changes + +Click **Save Changes** to apply your new logo. + +![Save Changes](https://colony-recorder.s3.amazonaws.com/files/2026-03-13/4baf6494-d146-4600-b6f2-ef667338d580/ascreenshot_722cbcd568ec4267af5122b3958bb248_text_export.jpeg) + +Your custom logo will now appear in the LiteLLM dashboard sidebar and login page. + +## Via the API + +### Set a Custom Logo + +```bash +curl -X PATCH 'http://localhost:4000/settings/update/ui_theme_settings' \ + -H 'Authorization: Bearer ' \ + -H 'Content-Type: application/json' \ + -d '{ + "logo_url": "https://example.com/your-company-logo.png" + }' +``` + +### Set a Custom Favicon + +You can also customize the browser tab favicon: + +```bash +curl -X PATCH 'http://localhost:4000/settings/update/ui_theme_settings' \ + -H 'Authorization: Bearer ' \ + -H 'Content-Type: application/json' \ + -d '{ + "logo_url": "https://example.com/your-company-logo.png", + "favicon_url": "https://example.com/your-favicon.ico" + }' +``` + +### Get Current Theme Settings + +```bash +curl -X GET 'http://localhost:4000/settings/get/ui_theme_settings' +``` + +### Reset to Default Logo + +Send an empty `logo_url` to restore the default LiteLLM logo: + +```bash +curl -X PATCH 'http://localhost:4000/settings/update/ui_theme_settings' \ + -H 'Authorization: Bearer ' \ + -H 'Content-Type: application/json' \ + -d '{ + "logo_url": "" + }' +``` + +## Via `proxy_config.yaml` + +You can also set the logo URL in your proxy configuration file: + +```yaml +litellm_settings: + ui_theme_config: + logo_url: "https://example.com/your-company-logo.png" + favicon_url: "https://example.com/your-favicon.ico" # optional +``` + +Or set it as an environment variable: + +```yaml +environment_variables: + UI_LOGO_PATH: "https://example.com/your-company-logo.png" +``` + +## Supported Logo Formats + +| Format | Supported | +|--------|-----------| +| JPEG / JPG | Yes | +| PNG | Yes | +| SVG | Yes | +| ICO (favicon only) | Yes | +| HTTP/HTTPS URL | Yes | +| Local file path | Yes | diff --git a/docs/my-website/docs/reasoning_content.md b/docs/my-website/docs/reasoning_content.md index 5dd40122c71..8bf59f66a33 100644 --- a/docs/my-website/docs/reasoning_content.md +++ b/docs/my-website/docs/reasoning_content.md @@ -594,7 +594,9 @@ Expected Response :::tip gpt-5.4: reasoning_effort + function tools -OpenAI does not support `reasoning_effort` with function tools for `gpt-5.4` in `/v1/chat/completions`. Use `openai/responses/gpt-5.4` to route through the Responses API instead. See [Responses API Bridge](/docs/providers/openai#openai-chat-completion-to-responses-api-bridge) for details. +LiteLLM drops `reasoning_effort` from `gpt-5.4` requests to `litellm.completion()` that include tools, since that combination is supported in the Responses API. + +If you need reasoning **and** tools together, use `openai/responses/gpt-5.4` to route through the Responses API instead. See [Responses API Bridge](/docs/providers/openai#openai-chat-completion-to-responses-api-bridge) for details. ::: diff --git a/docs/my-website/img/ephemeral_token.png b/docs/my-website/img/ephemeral_token.png new file mode 100644 index 00000000000..28a05f9eb1b Binary files /dev/null and b/docs/my-website/img/ephemeral_token.png differ diff --git a/docs/my-website/img/webrtc_flow.png b/docs/my-website/img/webrtc_flow.png new file mode 100644 index 00000000000..a53ec10a7b7 Binary files /dev/null and b/docs/my-website/img/webrtc_flow.png differ diff --git a/docs/my-website/release_notes/v1.82.0.md b/docs/my-website/release_notes/v1.82.0.md index b2491875217..09967d5889b 100644 --- a/docs/my-website/release_notes/v1.82.0.md +++ b/docs/my-website/release_notes/v1.82.0.md @@ -1,5 +1,5 @@ --- -title: "[Preview] v1.82.0 - Realtime Guardrails, Projects Management, and 10+ Performance Optimizations" +title: "v1.82.0 - Realtime Guardrails, Projects Management, and 10+ Performance Optimizations" slug: "v1-82-0" date: 2026-02-28T00:00:00 authors: @@ -26,7 +26,7 @@ import TabItem from '@theme/TabItem'; docker run \ -e STORE_MODEL_IN_DB=True \ -p 4000:4000 \ -ghcr.io/berriai/litellm:main-1.82.0 +ghcr.io/berriai/litellm:main-1.82.0-stable ``` diff --git a/docs/my-website/sidebars.js b/docs/my-website/sidebars.js index d032b8ca393..d1eb331f55b 100644 --- a/docs/my-website/sidebars.js +++ b/docs/my-website/sidebars.js @@ -100,6 +100,7 @@ const sidebars = { label: "Policies", items: [ "proxy/guardrails/guardrail_policies", + "proxy/guardrails/policy_flow_builder", "proxy/guardrails/policy_templates", "proxy/guardrails/policy_tags", ], @@ -331,6 +332,7 @@ const sidebars = { label: "Setup & SSO", items: [ "proxy/admin_ui_sso", + "proxy/ui/ui_edit_logo", "proxy/custom_sso", "proxy/custom_root_ui", "tutorials/scim_litellm", @@ -668,6 +670,7 @@ const sidebars = { "rag_ingest", "rag_query", "realtime", + "proxy/realtime_webrtc", "rerank", "response_api", "response_api_compact", diff --git a/docs/my-website/src/components/WebRTCTester.jsx b/docs/my-website/src/components/WebRTCTester.jsx new file mode 100644 index 00000000000..3ade6dd7689 --- /dev/null +++ b/docs/my-website/src/components/WebRTCTester.jsx @@ -0,0 +1,83 @@ +import DashboardWebRTCTester from "../../../../ui/litellm-dashboard/src/components/WebRTCTester.jsx"; + +const LIGHT_MODE_OVERRIDES = ` +.wrt-wrap { + background: #1f2937; + border: 1px solid #334155; +} +.wrt-toggle, +.wrt-toggle:hover { + background: #111827; +} +.wrt-toggle-title, +.we-msg { + color: #e2e8f0; +} +.wrt-toggle-sub, +.wrt-label, +.wrt-field label, +.wrt-flow-box, +.wrt-flow-arrow, +.wrt-meta-row span:first-child, +.wrt-header-title, +.wrt-tab, +.we-time { + color: #94a3b8; +} +.wrt-body, +.wrt-sidebar, +.wrt-main, +.wrt-header, +.wrt-tabs, +.wrt-sdp-box, +.wrt-sdp-hdr, +.wrt-divider { + border-color: #334155; +} +.wrt-header { + background: #111827; +} +.wrt-field input, +.wrt-mic-btn, +.wrt-status-pill { + background: #0b1220; + border-color: #334155; + color: #e2e8f0; +} +.wrt-field input:focus, +.wrt-btn-ghost:hover { + border-color: #60a5fa; +} +.wrt-btn-ghost { + background: #0b1220; + border-color: #334155; + color: #e2e8f0; +} +.wrt-log::-webkit-scrollbar-thumb { + background: #475569; +} +.wrt-tab.active { + color: #93c5fd; + border-bottom-color: #93c5fd; +} +.wrt-empty, +.wrt-audio-status, +.wrt-meta-row span:last-child { + color: #cbd5e1; +} +.wrt-sdp-dot { + background: #475569; +} +.wrt-sdp-pane textarea { + color: #e2e8f0; +} +`; + +export default function WebRTCTester() { + return ( + <> + + + + ); +} 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 10f7f98b719..42a9acbfd1e 100644 --- a/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py +++ b/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py @@ -2,11 +2,15 @@ Polls LiteLLM_ManagedObjectTable to check if the batch job is complete, and if the cost has been tracked. """ -from litellm._uuid import uuid -from datetime import datetime +from datetime import datetime, timedelta, timezone from typing import TYPE_CHECKING, Optional from litellm._logging import verbose_proxy_logger +from litellm._uuid import uuid +from litellm.constants import ( + MANAGED_OBJECT_STALENESS_CUTOFF_DAYS, + MAX_OBJECTS_PER_POLL_CYCLE, +) if TYPE_CHECKING: from litellm.proxy.utils import PrismaClient, ProxyLogging @@ -29,6 +33,9 @@ class CheckBatchCost: self.proxy_logging_obj: ProxyLogging = proxy_logging_obj self.prisma_client: PrismaClient = prisma_client self.llm_router: Router = llm_router + # Cached after the first poll cycle. Once we know the column is absent we skip + # the guaranteed-failing primary query on every subsequent cycle. + self._has_batch_processed_column: bool = True async def _get_user_info(self, batch_id, user_id) -> dict: """ @@ -49,6 +56,47 @@ class CheckBatchCost: verbose_proxy_logger.error(f"CheckBatchCost: could not look up user {user_id} for batch {batch_id}: {e}") return {} + async def _cleanup_stale_managed_objects(self) -> None: + """ + Mark managed objects older than MANAGED_OBJECT_STALENESS_CUTOFF_DAYS days + in non-terminal states as 'stale_expired'. These will never complete and + should not be polled. + """ + cutoff = datetime.now(timezone.utc) - timedelta(days=MANAGED_OBJECT_STALENESS_CUTOFF_DAYS) + result = await self.prisma_client.db.litellm_managedobjecttable.update_many( + where={ + "file_purpose": "batch", + "status": {"not_in": ["completed", "complete", "failed", "expired", "cancelled", "stale_expired"]}, + "created_at": {"lt": cutoff}, + }, + data={"status": "stale_expired"}, + ) + if result > 0: + verbose_proxy_logger.warning( + f"CheckBatchCost: marked {result} stale managed objects " + f"(older than {MANAGED_OBJECT_STALENESS_CUTOFF_DAYS} days) as stale_expired" + ) + + async def _fallback_find_jobs(self) -> list: + """Query batch jobs without the batch_processed filter (for older schemas).""" + return await self.prisma_client.db.litellm_managedobjecttable.find_many( + where={ + "file_purpose": "batch", + "status": { + "not_in": [ + "failed", + "expired", + "cancelled", + "complete", + "completed", + "stale_expired", + ] + }, + }, + take=MAX_OBJECTS_PER_POLL_CYCLE, + order={"created_at": "asc"}, + ) + async def check_batch_cost(self): """ Check if the batch JOB has been tracked. @@ -70,14 +118,48 @@ class CheckBatchCost: get_model_id_from_unified_batch_id, ) - # Look for all batches that have not yet been processed by CheckBatchCost - jobs = await self.prisma_client.db.litellm_managedobjecttable.find_many( - where={ - "file_purpose": "batch", - "batch_processed" : False, - "status": {"not_in": ["failed", "expired", "cancelled"]} - } - ) + try: + await self._cleanup_stale_managed_objects() + except Exception as cleanup_err: + verbose_proxy_logger.warning( + f"CheckBatchCost: stale cleanup failed (poll will continue): {cleanup_err}" + ) + + # Look for all batches that have not yet been processed by CheckBatchCost. + # self._has_batch_processed_column is cached after the first probe so that + # older schemas don't pay a guaranteed-failing primary query + warning on + # every subsequent poll cycle. + if self._has_batch_processed_column: + try: + jobs = await self.prisma_client.db.litellm_managedobjecttable.find_many( + where={ + "file_purpose": "batch", + "batch_processed": False, + "status": { + "not_in": [ + "failed", + "expired", + "cancelled", + "complete", + "completed", + "stale_expired", + ] + }, + }, + take=MAX_OBJECTS_PER_POLL_CYCLE, + order={"created_at": "asc"}, + ) + except Exception as query_err: + if "batch_processed" not in str(query_err).lower() and "unknown column" not in str(query_err).lower() and "does not exist" not in str(query_err).lower(): + raise + # Permanent schema gap — cache the result so future cycles skip straight to fallback + self._has_batch_processed_column = False + verbose_proxy_logger.warning( + "CheckBatchCost: batch_processed column not found, querying without it" + ) + jobs = await self._fallback_find_jobs() + else: + jobs = await self._fallback_find_jobs() for job in jobs: # get the model from the job unified_object_id = job.unified_object_id @@ -163,14 +245,14 @@ class CheckBatchCost: # Access content - handle both direct attribute and method call if hasattr(_file_content, 'content'): - content_bytes = _file_content.content + content_bytes = _file_content.content # type: ignore[union-attr] elif hasattr(_file_content, 'read'): - content_bytes = await _file_content.read() + content_bytes = await _file_content.read() # type: ignore[misc] else: - content_bytes = _file_content + content_bytes = _file_content # type: ignore[assignment] file_content_as_dict = _get_file_content_as_dictionary( - content_bytes + content_bytes # type: ignore[arg-type] ) deployment_info = self.llm_router.get_deployment(model_id=model_id) @@ -195,7 +277,7 @@ class CheckBatchCost: file_content_dictionary=file_content_as_dict, custom_llm_provider=llm_provider, # type: ignore model_name=model_name, - model_info=deployment_model_info, + model_info=deployment_model_info, # type: ignore[arg-type] ) ) logging_obj = LiteLLMLogging( @@ -236,13 +318,15 @@ class CheckBatchCost: # mark the job as complete try: + update_data: dict = { + "status": "complete", + "file_object": response.model_dump_json(), + } + if self._has_batch_processed_column: + update_data["batch_processed"] = True await self.prisma_client.db.litellm_managedobjecttable.update( where={"id": job.id}, - data={ - "batch_processed": True, - "status": "complete", - "file_object": response.model_dump_json(), - }, + data=update_data, ) except Exception as db_err: verbose_proxy_logger.error( diff --git a/enterprise/litellm_enterprise/proxy/common_utils/check_responses_cost.py b/enterprise/litellm_enterprise/proxy/common_utils/check_responses_cost.py index 4ee6a89cc98..54fbc7abcc5 100644 --- a/enterprise/litellm_enterprise/proxy/common_utils/check_responses_cost.py +++ b/enterprise/litellm_enterprise/proxy/common_utils/check_responses_cost.py @@ -3,10 +3,15 @@ Polls LiteLLM_ManagedObjectTable to check if the response is complete. Cost tracking is handled automatically by litellm.aget_responses(). """ +from datetime import datetime, timedelta, timezone from typing import TYPE_CHECKING import litellm from litellm._logging import verbose_proxy_logger +from litellm.constants import ( + MANAGED_OBJECT_STALENESS_CUTOFF_DAYS, + MAX_OBJECTS_PER_POLL_CYCLE, +) if TYPE_CHECKING: from litellm.proxy.utils import PrismaClient, ProxyLogging @@ -27,6 +32,27 @@ class CheckResponsesCost: self.prisma_client: PrismaClient = prisma_client self.llm_router: Router = llm_router + async def _cleanup_stale_managed_objects(self) -> None: + """ + Mark managed objects older than MANAGED_OBJECT_STALENESS_CUTOFF_DAYS days + in non-terminal states as 'stale_expired'. These will never complete and + should not be polled. + """ + cutoff = datetime.now(timezone.utc) - timedelta(days=MANAGED_OBJECT_STALENESS_CUTOFF_DAYS) + result = await self.prisma_client.db.litellm_managedobjecttable.update_many( + where={ + "file_purpose": "response", + "status": {"not_in": ["completed", "complete", "failed", "expired", "cancelled", "stale_expired"]}, + "created_at": {"lt": cutoff}, + }, + data={"status": "stale_expired"}, + ) + if result > 0: + verbose_proxy_logger.warning( + f"CheckResponsesCost: marked {result} stale managed objects " + f"(older than {MANAGED_OBJECT_STALENESS_CUTOFF_DAYS} days) as stale_expired" + ) + async def check_responses_cost(self): """ Check if background responses are complete and track their cost. @@ -35,11 +61,20 @@ class CheckResponsesCost: - Cost is automatically tracked by litellm.aget_responses() - Mark completed/failed/cancelled responses as complete in the database """ + try: + await self._cleanup_stale_managed_objects() + except Exception as cleanup_err: + verbose_proxy_logger.warning( + f"CheckResponsesCost: stale cleanup failed (poll will continue): {cleanup_err}" + ) + jobs = await self.prisma_client.db.litellm_managedobjecttable.find_many( where={ "status": {"in": ["queued", "in_progress"]}, "file_purpose": "response", - } + }, + take=MAX_OBJECTS_PER_POLL_CYCLE, + order={"created_at": "asc"}, ) verbose_proxy_logger.debug(f"Found {len(jobs)} response jobs to check") diff --git a/litellm-js/spend-logs/package-lock.json b/litellm-js/spend-logs/package-lock.json index 1a13a76820e..b24ff0a4940 100644 --- a/litellm-js/spend-logs/package-lock.json +++ b/litellm-js/spend-logs/package-lock.json @@ -6,7 +6,7 @@ "": { "dependencies": { "@hono/node-server": "^1.10.1", - "hono": "^4.10.3" + "hono": "^4.12.7" }, "devDependencies": { "@types/node": "^20.11.17", @@ -548,9 +548,9 @@ } }, "node_modules/hono": { - "version": "4.10.6", - "resolved": "https://registry.npmjs.org/hono/-/hono-4.10.6.tgz", - "integrity": "sha512-BIdolzGpDO9MQ4nu3AUuDwHZZ+KViNm+EZ75Ae55eMXMqLVhDFqEMXxtUe9Qh8hjL+pIna/frs2j6Y2yD5Ua/g==", + "version": "4.12.7", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.7.tgz", + "integrity": "sha512-jq9l1DM0zVIvsm3lv9Nw9nlJnMNPOcAtsbsgiUhWcFzPE99Gvo6yRTlszSLLYacMeQ6quHD6hMfId8crVHvexw==", "license": "MIT", "engines": { "node": ">=16.9.0" diff --git a/litellm-js/spend-logs/package.json b/litellm-js/spend-logs/package.json index adfe49017d1..a40b0fc2a83 100644 --- a/litellm-js/spend-logs/package.json +++ b/litellm-js/spend-logs/package.json @@ -4,7 +4,7 @@ }, "dependencies": { "@hono/node-server": "^1.10.1", - "hono": "^4.10.3" + "hono": "^4.12.7" }, "devDependencies": { "@types/node": "^20.11.17", diff --git a/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.54-py3-none-any.whl b/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.54-py3-none-any.whl new file mode 100644 index 00000000000..9a5c185de28 Binary files /dev/null and b/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.54-py3-none-any.whl differ diff --git a/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.54.tar.gz b/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.54.tar.gz new file mode 100644 index 00000000000..3e4be95b519 Binary files /dev/null and b/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.54.tar.gz differ diff --git a/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.56-py3-none-any.whl b/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.56-py3-none-any.whl new file mode 100644 index 00000000000..fceb3b04cee Binary files /dev/null and b/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.56-py3-none-any.whl differ diff --git a/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.56.tar.gz b/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.56.tar.gz new file mode 100644 index 00000000000..5e7841ab0da Binary files /dev/null and b/litellm-proxy-extras/dist/litellm_proxy_extras-0.4.56.tar.gz differ diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260309115809_add_missing_indexes/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260309115809_add_missing_indexes/migration.sql deleted file mode 100644 index 7b3e6d089ec..00000000000 --- a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260309115809_add_missing_indexes/migration.sql +++ /dev/null @@ -1,13 +0,0 @@ --- SkipTransactionBlock - --- Drop invalid indexes left behind by failed CONCURRENTLY builds -DROP INDEX CONCURRENTLY IF EXISTS "LiteLLM_VerificationToken_key_alias_idx"; - --- CreateIndex -CREATE INDEX CONCURRENTLY "LiteLLM_VerificationToken_key_alias_idx" ON "LiteLLM_VerificationToken"("key_alias"); - --- Drop invalid indexes left behind by failed CONCURRENTLY builds -DROP INDEX CONCURRENTLY IF EXISTS "LiteLLM_SpendLogs_user_startTime_idx"; - --- CreateIndex -CREATE INDEX CONCURRENTLY "LiteLLM_SpendLogs_user_startTime_idx" ON "LiteLLM_SpendLogs"("user", "startTime"); diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260311180521_schema_sync/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260311180521_schema_sync/migration.sql new file mode 100644 index 00000000000..5ab834695b8 --- /dev/null +++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260311180521_schema_sync/migration.sql @@ -0,0 +1,11 @@ +-- DropIndex +DROP INDEX "LiteLLM_MCPServerTable_approval_status_idx"; + +-- AlterTable +ALTER TABLE "LiteLLM_MCPServerTable" DROP COLUMN "approval_status", +DROP COLUMN "review_notes", +DROP COLUMN "reviewed_at", +DROP COLUMN "source_url", +DROP COLUMN "submitted_at", +DROP COLUMN "submitted_by"; + diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260312124619_schema_sync/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260312124619_schema_sync/migration.sql new file mode 100644 index 00000000000..8854fd1e205 --- /dev/null +++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260312124619_schema_sync/migration.sql @@ -0,0 +1,3 @@ +-- AlterTable +ALTER TABLE "LiteLLM_ObjectPermissionTable" ADD COLUMN "models" TEXT[] DEFAULT ARRAY[]::TEXT[]; + diff --git a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma index d5d17b2bcec..ce79c2b3d52 100644 --- a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma +++ b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma @@ -267,6 +267,7 @@ model LiteLLM_ObjectPermissionTable { vector_stores String[] @default([]) agents String[] @default([]) agent_access_groups String[] @default([]) + models String[] @default([]) blocked_tools String[] @default([]) // Tool names blocked for any key/team/user with this permission teams LiteLLM_TeamTable[] projects LiteLLM_ProjectTable[] @@ -315,6 +316,11 @@ model LiteLLM_MCPServerTable { is_byok Boolean @default(false) byok_description String[] @default([]) byok_api_key_help_url String? + approval_status String @default("approved") + submitted_by String? + submitted_at DateTime? + reviewed_at DateTime? + review_notes String? } // Per-user BYOK credentials for MCP servers @@ -388,9 +394,6 @@ model LiteLLM_VerificationToken { // SELECT ... FROM "public"."LiteLLM_VerificationToken" WHERE (("public"."LiteLLM_VerificationToken"."expires" IS NULL OR "public"."LiteLLM_VerificationToken"."expires" > $1) AND "public"."LiteLLM_VerificationToken"."budget_reset_at" < $2) OFFSET $3 @@index([budget_reset_at, expires]) - - // SELECT ... FROM "public"."LiteLLM_VerificationToken" WHERE (...) ORDER BY "public"."LiteLLM_VerificationToken"."key_alias" ASC - @@index([key_alias]) } model LiteLLM_JWTKeyMapping { @@ -556,9 +559,6 @@ model LiteLLM_SpendLogs { @@index([startTime, request_id]) @@index([end_user]) @@index([session_id]) - - // SELECT ... FROM "LiteLLM_SpendLogs" WHERE ("startTime" >= $1 AND "startTime" <= $2 AND "user" = $3) GROUP BY ... - @@index([user, startTime]) } // View spend, model, api_key per request diff --git a/litellm-proxy-extras/pyproject.toml b/litellm-proxy-extras/pyproject.toml index ef80f092f1b..b65dbe45233 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.53" +version = "0.4.56" 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.53" +version = "0.4.56" version_files = [ "pyproject.toml:version", "../requirements.txt:litellm-proxy-extras==", diff --git a/litellm/__init__.py b/litellm/__init__.py index 67f675839cd..dcd4ce29096 100644 --- a/litellm/__init__.py +++ b/litellm/__init__.py @@ -81,6 +81,7 @@ from litellm.constants import ( DEFAULT_ALLOWED_FAILS, ) import httpx + # register_async_client_cleanup is lazy-loaded and called on first access litellm_mode = os.getenv("LITELLM_MODE", "DEV") # "PRODUCTION", "DEV" @@ -152,7 +153,9 @@ _known_custom_logger_compatible_callbacks: List = list( get_args(_custom_logger_compatible_callbacks_literal) ) callbacks: List[ - Union[Callable, _custom_logger_compatible_callbacks_literal, "CustomLogger"] # CustomLogger is lazy-loaded + Union[ + Callable, _custom_logger_compatible_callbacks_literal, "CustomLogger" + ] # CustomLogger is lazy-loaded ] = [] callback_settings: Dict[str, Dict[str, Any]] = {} initialized_langfuse_clients: int = 0 @@ -162,42 +165,50 @@ prometheus_initialize_budget_metrics: Optional[bool] = False require_auth_for_metrics_endpoint: Optional[bool] = False argilla_batch_size: Optional[int] = None datadog_use_v1: Optional[bool] = False # if you want to use v1 datadog logged payload. -gcs_pub_sub_use_v1: Optional[bool] = ( - False # if you want to use v1 gcs pubsub logged payload -) -generic_api_use_v1: Optional[bool] = ( - False # if you want to use v1 generic api logged payload -) +gcs_pub_sub_use_v1: Optional[ + bool +] = False # if you want to use v1 gcs pubsub logged payload +generic_api_use_v1: Optional[ + bool +] = False # if you want to use v1 generic api logged payload argilla_transformation_object: Optional[Dict[str, Any]] = None -_async_input_callback: List[Union[str, Callable, "CustomLogger"]] = ( # CustomLogger is lazy-loaded +_async_input_callback: List[ + Union[str, Callable, "CustomLogger"] +] = ( # CustomLogger is lazy-loaded [] ) # internal variable - async custom callbacks are routed here. -_async_success_callback: List[Union[str, Callable, "CustomLogger"]] = ( # CustomLogger is lazy-loaded +_async_success_callback: List[ + Union[str, Callable, "CustomLogger"] +] = ( # CustomLogger is lazy-loaded [] ) # internal variable - async custom callbacks are routed here. -_async_failure_callback: List[Union[str, Callable, "CustomLogger"]] = ( # CustomLogger is lazy-loaded +_async_failure_callback: List[ + Union[str, Callable, "CustomLogger"] +] = ( # CustomLogger is lazy-loaded [] ) # internal variable - async custom callbacks are routed here. pre_call_rules: List[Callable] = [] post_call_rules: List[Callable] = [] turn_off_message_logging: Optional[bool] = False -standard_logging_payload_excluded_fields: Optional[List[str]] = None # Fields to exclude from StandardLoggingPayload before callbacks receive it +standard_logging_payload_excluded_fields: Optional[ + List[str] +] = None # Fields to exclude from StandardLoggingPayload before callbacks receive it log_raw_request_response: bool = False redact_messages_in_exceptions: Optional[bool] = False redact_user_api_key_info: Optional[bool] = False filter_invalid_headers: Optional[bool] = False -add_user_information_to_llm_headers: Optional[bool] = ( - None # adds user_id, team_id, token hash (params from StandardLoggingMetadata) to request headers -) +add_user_information_to_llm_headers: Optional[ + bool +] = None # adds user_id, team_id, token hash (params from StandardLoggingMetadata) to request headers store_audit_logs = False # Enterprise feature, allow users to see audit logs ### end of callbacks ############# -email: Optional[str] = ( - None # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648 -) -token: Optional[str] = ( - None # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648 -) +email: Optional[ + str +] = None # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648 +token: Optional[ + str +] = None # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648 telemetry = True max_tokens: int = DEFAULT_MAX_TOKENS # OpenAI Defaults drop_params = bool(os.getenv("LITELLM_DROP_PARAMS", False)) @@ -259,9 +270,9 @@ use_client: bool = False ssl_verify: Union[str, bool] = True ssl_security_level: Optional[str] = None ssl_certificate: Optional[str] = None -ssl_ecdh_curve: Optional[str] = ( - None # Set to 'X25519' to disable PQC and improve performance -) +ssl_ecdh_curve: Optional[ + str +] = None # Set to 'X25519' to disable PQC and improve performance disable_streaming_logging: bool = False disable_token_counter: bool = False disable_add_transform_inline_image_block: bool = False @@ -314,24 +325,20 @@ enable_loadbalancing_on_batch_endpoints: Optional[bool] = None enable_caching_on_provider_specific_optional_params: bool = ( False # feature-flag for caching on optional params - e.g. 'top_k' ) -caching: bool = ( - False # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648 -) -caching_with_models: bool = ( - False # # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648 -) -cache: Optional["Cache"] = ( - None # cache object <- use this - https://docs.litellm.ai/docs/caching -) +caching: bool = False # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648 +caching_with_models: bool = False # # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648 +cache: Optional[ + "Cache" +] = None # cache object <- use this - https://docs.litellm.ai/docs/caching default_in_memory_ttl: Optional[float] = None default_redis_ttl: Optional[float] = None default_redis_batch_cache_expiry: Optional[float] = None model_alias_map: Dict[str, str] = {} model_group_settings: Optional["ModelGroupSettings"] = None max_budget: float = 0.0 # set the max budget across all providers -budget_duration: Optional[str] = ( - None # proxy only - resets budget after fixed duration. You can set duration as seconds ("30s"), minutes ("30m"), hours ("30h"), days ("30d"). -) +budget_duration: Optional[ + str +] = None # proxy only - resets budget after fixed duration. You can set duration as seconds ("30s"), minutes ("30m"), hours ("30h"), days ("30d"). default_soft_budget: float = ( DEFAULT_SOFT_BUDGET # by default all litellm proxy keys have a soft budget of 50.0 ) @@ -340,9 +347,7 @@ forward_traceparent_to_llm_provider: bool = False _current_cost = 0.0 # private variable, used if max budget is set error_logs: Dict = {} -add_function_to_prompt: bool = ( - False # if function calling not supported by api, append function call details to system prompt -) +add_function_to_prompt: bool = False # if function calling not supported by api, append function call details to system prompt client_session: Optional[httpx.Client] = None aclient_session: Optional[httpx.AsyncClient] = None model_fallbacks: Optional[List] = None # Deprecated for 'litellm.fallbacks' @@ -389,9 +394,7 @@ prometheus_emit_stream_label: bool = False disable_add_prefix_to_prompt: bool = ( False # used by anthropic, to disable adding prefix to prompt ) -disable_copilot_system_to_assistant: bool = ( - 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: bool = False # If false (default), converts all 'system' role messages to 'assistant' for GitHub Copilot compatibility. Set to true to disable this behavior. public_mcp_servers: Optional[List[str]] = None public_model_groups: Optional[List[str]] = None public_agent_groups: Optional[List[str]] = None @@ -410,17 +413,13 @@ if TYPE_CHECKING: ######## Networking Settings ######## -use_aiohttp_transport: bool = ( - True # Older variable, aiohttp is now the default. use disable_aiohttp_transport instead. -) +use_aiohttp_transport: bool = True # Older variable, aiohttp is now the default. use disable_aiohttp_transport instead. aiohttp_trust_env: bool = False # set to true to use HTTP_ Proxy settings disable_aiohttp_transport: bool = False # Set this to true to use httpx instead disable_aiohttp_trust_env: bool = ( False # When False, aiohttp will respect HTTP(S)_PROXY env vars ) -force_ipv4: bool = ( - False # when True, litellm will force ipv4 for all LLM requests. Some users have seen httpx ConnectionError when using ipv6. -) +force_ipv4: bool = False # when True, litellm will force ipv4 for all LLM requests. Some users have seen httpx ConnectionError when using ipv6. network_mock: bool = False # When True, use mock transport — no real network calls ####### STOP SEQUENCE LIMIT ####### @@ -435,13 +434,13 @@ context_window_fallbacks: Optional[List] = None content_policy_fallbacks: Optional[List] = None allowed_fails: int = 3 allow_dynamic_callback_disabling: bool = True -num_retries_per_request: Optional[int] = ( - None # for the request overall (incl. fallbacks + model retries) -) +num_retries_per_request: Optional[ + int +] = None # for the request overall (incl. fallbacks + model retries) ####### SECRET MANAGERS ##################### -secret_manager_client: Optional[Any] = ( - None # list of instantiated key management clients - e.g. azure kv, infisical, etc. -) +secret_manager_client: Optional[ + Any +] = None # list of instantiated key management clients - e.g. azure kv, infisical, etc. _google_kms_resource_name: Optional[str] = None _key_management_system: Optional["KeyManagementSystem"] = None # Note: KeyManagementSettings must be eagerly imported because _key_management_settings @@ -454,12 +453,12 @@ output_parse_pii: bool = False from litellm.litellm_core_utils.get_model_cost_map import get_model_cost_map model_cost = get_model_cost_map(url=model_cost_map_url) -cost_discount_config: Dict[str, float] = ( - {} -) # Provider-specific cost discounts {"vertex_ai": 0.05} = 5% discount -cost_margin_config: Dict[str, Union[float, Dict[str, float]]] = ( - {} -) # Provider-specific or global cost margins. Examples: +cost_discount_config: Dict[ + str, float +] = {} # Provider-specific cost discounts {"vertex_ai": 0.05} = 5% discount +cost_margin_config: Dict[ + str, Union[float, Dict[str, float]] +] = {} # Provider-specific or global cost margins. Examples: # Percentage: {"openai": 0.10} = 10% margin # Fixed: {"openai": {"fixed_amount": 0.001}} = $0.001 per request # Global: {"global": 0.05} = 5% global margin on all providers @@ -1077,7 +1076,7 @@ models_by_provider: dict = { "aws_polly": aws_polly_models, "gigachat": gigachat_models, "llamagate": llamagate_models, - "bedrock_mantle": bedrock_mantle_models + "bedrock_mantle": bedrock_mantle_models, } # mapping for those models which have larger equivalents @@ -1128,10 +1127,12 @@ openai_video_generation_models = ["sora-2"] # Import KeyManagementSettings here (before utils import) because _key_management_settings # is accessed during import time in secret_managers/main.py (via dd_tracing -> datadog -> _service_logger -> utils) from litellm.types.secret_managers.main import KeyManagementSettings + _key_management_settings: KeyManagementSettings = KeyManagementSettings() # client must be imported immediately as it's used as a decorator at function definition time from .utils import client + # Note: Most other utils imports are lazy-loaded via __getattr__ to avoid loading utils.py # (which imports tiktoken) at import time @@ -1160,6 +1161,7 @@ from .llms.topaz.common_utils import TopazModelInfo # OpenAIOSeriesConfig is lazy loaded - openaiOSeriesConfig will be created on first access # OpenAIGPTConfig, OpenAIGPT5Config, etc. are lazy loaded - instances will be created on first access from .llms.xai.common_utils import XAIModelInfo + # PublicAI now uses JSON-based configuration (see litellm/llms/openai_like/providers.json) # All remaining configs are now lazy loaded - see _lazy_imports_registry.py @@ -1241,6 +1243,7 @@ from .batch_completion.main import * # type: ignore from .rerank_api.main import * from .llms.anthropic.experimental_pass_through.messages.handler import * from .responses.main import * + # Interactions API is available as litellm.interactions module # Usage: litellm.interactions.create(), litellm.interactions.get(), etc. from . import interactions @@ -1258,7 +1261,11 @@ from .containers.main import * from .ocr.main import * from .rag.main import * from .search.main import * -from .realtime_api.main import _arealtime +from .realtime_api.main import ( + _arealtime, + acreate_realtime_client_secret, + arealtime_calls, +) from .responses.main import _aresponses_websocket from .fine_tuning.main import * from .files.main import * @@ -1300,12 +1307,12 @@ from . import rag from .types.llms.custom_llm import CustomLLMItem custom_provider_map: List[CustomLLMItem] = [] -_custom_providers: List[str] = ( - [] -) # internal helper util, used to track names of custom providers -disable_hf_tokenizer_download: Optional[bool] = ( - None # disable huggingface tokenizer download. Defaults to openai clk100 -) +_custom_providers: List[ + str +] = [] # internal helper util, used to track names of custom providers +disable_hf_tokenizer_download: Optional[ + bool +] = None # disable huggingface tokenizer download. Defaults to openai clk100 global_disable_no_log_param: bool = False ### CLI UTILITIES ### @@ -1344,131 +1351,327 @@ if TYPE_CHECKING: from litellm.caching.caching import Cache # Type stubs for lazy-loaded configs to help mypy - from .llms.bedrock.chat.converse_transformation import AmazonConverseConfig as AmazonConverseConfig - from .llms.openai_like.chat.handler import OpenAILikeChatConfig as OpenAILikeChatConfig - from .llms.galadriel.chat.transformation import GaladrielChatConfig as GaladrielChatConfig + from .llms.bedrock.chat.converse_transformation import ( + AmazonConverseConfig as AmazonConverseConfig, + ) + from .llms.openai_like.chat.handler import ( + OpenAILikeChatConfig as OpenAILikeChatConfig, + ) + from .llms.galadriel.chat.transformation import ( + GaladrielChatConfig as GaladrielChatConfig, + ) from .llms.github.chat.transformation import GithubChatConfig as GithubChatConfig - from .llms.azure_ai.anthropic.transformation import AzureAnthropicConfig as AzureAnthropicConfig + from .llms.azure_ai.anthropic.transformation import ( + AzureAnthropicConfig as AzureAnthropicConfig, + ) from .llms.bytez.chat.transformation import BytezChatConfig as BytezChatConfig - from .llms.compactifai.chat.transformation import CompactifAIChatConfig as CompactifAIChatConfig + from .llms.compactifai.chat.transformation import ( + CompactifAIChatConfig as CompactifAIChatConfig, + ) from .llms.empower.chat.transformation import EmpowerChatConfig as EmpowerChatConfig from .llms.minimax.chat.transformation import MinimaxChatConfig as MinimaxChatConfig - from .llms.aiohttp_openai.chat.transformation import AiohttpOpenAIChatConfig as AiohttpOpenAIChatConfig - from .llms.huggingface.chat.transformation import HuggingFaceChatConfig as HuggingFaceChatConfig - from .llms.huggingface.embedding.transformation import HuggingFaceEmbeddingConfig as HuggingFaceEmbeddingConfig + from .llms.aiohttp_openai.chat.transformation import ( + AiohttpOpenAIChatConfig as AiohttpOpenAIChatConfig, + ) + from .llms.huggingface.chat.transformation import ( + HuggingFaceChatConfig as HuggingFaceChatConfig, + ) + from .llms.huggingface.embedding.transformation import ( + HuggingFaceEmbeddingConfig as HuggingFaceEmbeddingConfig, + ) from .llms.oobabooga.chat.transformation import OobaboogaConfig as OobaboogaConfig from .llms.maritalk import MaritalkConfig as MaritalkConfig - from .llms.openrouter.chat.transformation import OpenrouterConfig as OpenrouterConfig + from .llms.openrouter.chat.transformation import ( + OpenrouterConfig as OpenrouterConfig, + ) from .llms.datarobot.chat.transformation import DataRobotConfig as DataRobotConfig from .llms.anthropic.chat.transformation import AnthropicConfig as AnthropicConfig - from .llms.anthropic.completion.transformation import AnthropicTextConfig as AnthropicTextConfig + from .llms.anthropic.completion.transformation import ( + AnthropicTextConfig as AnthropicTextConfig, + ) from .llms.groq.stt.transformation import GroqSTTConfig as GroqSTTConfig from .llms.triton.completion.transformation import TritonConfig as TritonConfig - from .llms.triton.completion.transformation import TritonGenerateConfig as TritonGenerateConfig - from .llms.triton.completion.transformation import TritonInferConfig as TritonInferConfig - from .llms.triton.embedding.transformation import TritonEmbeddingConfig as TritonEmbeddingConfig - from .llms.huggingface.rerank.transformation import HuggingFaceRerankConfig as HuggingFaceRerankConfig - from .llms.databricks.chat.transformation import DatabricksConfig as DatabricksConfig - from .llms.databricks.embed.transformation import DatabricksEmbeddingConfig as DatabricksEmbeddingConfig + from .llms.triton.completion.transformation import ( + TritonGenerateConfig as TritonGenerateConfig, + ) + from .llms.triton.completion.transformation import ( + TritonInferConfig as TritonInferConfig, + ) + from .llms.triton.embedding.transformation import ( + TritonEmbeddingConfig as TritonEmbeddingConfig, + ) + from .llms.huggingface.rerank.transformation import ( + HuggingFaceRerankConfig as HuggingFaceRerankConfig, + ) + from .llms.databricks.chat.transformation import ( + DatabricksConfig as DatabricksConfig, + ) + from .llms.databricks.embed.transformation import ( + DatabricksEmbeddingConfig as DatabricksEmbeddingConfig, + ) from .llms.predibase.chat.transformation import PredibaseConfig as PredibaseConfig from .llms.replicate.chat.transformation import ReplicateConfig as ReplicateConfig from .llms.snowflake.chat.transformation import SnowflakeConfig as SnowflakeConfig - from .llms.cohere.rerank.transformation import CohereRerankConfig as CohereRerankConfig - from .llms.cohere.rerank_v2.transformation import CohereRerankV2Config as CohereRerankV2Config - from .llms.azure_ai.rerank.transformation import AzureAIRerankConfig as AzureAIRerankConfig - from .llms.infinity.rerank.transformation import InfinityRerankConfig as InfinityRerankConfig - from .llms.jina_ai.rerank.transformation import JinaAIRerankConfig as JinaAIRerankConfig - from .llms.deepinfra.rerank.transformation import DeepinfraRerankConfig as DeepinfraRerankConfig - from .llms.hosted_vllm.rerank.transformation import HostedVLLMRerankConfig as HostedVLLMRerankConfig - from .llms.nvidia_nim.rerank.transformation import NvidiaNimRerankConfig as NvidiaNimRerankConfig - from .llms.nvidia_nim.rerank.ranking_transformation import NvidiaNimRankingConfig as NvidiaNimRankingConfig - from .llms.vertex_ai.rerank.transformation import VertexAIRerankConfig as VertexAIRerankConfig - from .llms.fireworks_ai.rerank.transformation import FireworksAIRerankConfig as FireworksAIRerankConfig - from .llms.voyage.rerank.transformation import VoyageRerankConfig as VoyageRerankConfig - from .llms.watsonx.rerank.transformation import IBMWatsonXRerankConfig as IBMWatsonXRerankConfig + from .llms.cohere.rerank.transformation import ( + CohereRerankConfig as CohereRerankConfig, + ) + from .llms.cohere.rerank_v2.transformation import ( + CohereRerankV2Config as CohereRerankV2Config, + ) + from .llms.azure_ai.rerank.transformation import ( + AzureAIRerankConfig as AzureAIRerankConfig, + ) + from .llms.infinity.rerank.transformation import ( + InfinityRerankConfig as InfinityRerankConfig, + ) + from .llms.jina_ai.rerank.transformation import ( + JinaAIRerankConfig as JinaAIRerankConfig, + ) + from .llms.deepinfra.rerank.transformation import ( + DeepinfraRerankConfig as DeepinfraRerankConfig, + ) + from .llms.hosted_vllm.rerank.transformation import ( + HostedVLLMRerankConfig as HostedVLLMRerankConfig, + ) + from .llms.nvidia_nim.rerank.transformation import ( + NvidiaNimRerankConfig as NvidiaNimRerankConfig, + ) + from .llms.nvidia_nim.rerank.ranking_transformation import ( + NvidiaNimRankingConfig as NvidiaNimRankingConfig, + ) + from .llms.vertex_ai.rerank.transformation import ( + VertexAIRerankConfig as VertexAIRerankConfig, + ) + from .llms.fireworks_ai.rerank.transformation import ( + FireworksAIRerankConfig as FireworksAIRerankConfig, + ) + from .llms.voyage.rerank.transformation import ( + VoyageRerankConfig as VoyageRerankConfig, + ) + from .llms.watsonx.rerank.transformation import ( + IBMWatsonXRerankConfig as IBMWatsonXRerankConfig, + ) from .llms.clarifai.chat.transformation import ClarifaiConfig as ClarifaiConfig from .llms.ai21.chat.transformation import AI21ChatConfig as AI21ChatConfig from .llms.meta_llama.chat.transformation import LlamaAPIConfig as LlamaAPIConfig - from .llms.together_ai.completion.transformation import TogetherAITextCompletionConfig as TogetherAITextCompletionConfig - from .llms.cloudflare.chat.transformation import CloudflareChatConfig as CloudflareChatConfig + from .llms.together_ai.completion.transformation import ( + TogetherAITextCompletionConfig as TogetherAITextCompletionConfig, + ) + from .llms.cloudflare.chat.transformation import ( + CloudflareChatConfig as CloudflareChatConfig, + ) from .llms.novita.chat.transformation import NovitaConfig as NovitaConfig from .llms.petals.completion.transformation import PetalsConfig as PetalsConfig from .llms.ollama.chat.transformation import OllamaChatConfig as OllamaChatConfig from .llms.ollama.completion.transformation import OllamaConfig as OllamaConfig - from .llms.sagemaker.completion.transformation import SagemakerConfig as SagemakerConfig - from .llms.sagemaker.chat.transformation import SagemakerChatConfig as SagemakerChatConfig + from .llms.sagemaker.completion.transformation import ( + SagemakerConfig as SagemakerConfig, + ) + from .llms.sagemaker.chat.transformation import ( + SagemakerChatConfig as SagemakerChatConfig, + ) from .llms.cohere.chat.transformation import CohereChatConfig as CohereChatConfig - from .llms.anthropic.experimental_pass_through.messages.transformation import AnthropicMessagesConfig as AnthropicMessagesConfig - from .llms.bedrock.messages.invoke_transformations.anthropic_claude3_transformation import AmazonAnthropicClaudeMessagesConfig as AmazonAnthropicClaudeMessagesConfig + from .llms.anthropic.experimental_pass_through.messages.transformation import ( + AnthropicMessagesConfig as AnthropicMessagesConfig, + ) + from .llms.bedrock.messages.invoke_transformations.anthropic_claude3_transformation import ( + AmazonAnthropicClaudeMessagesConfig as AmazonAnthropicClaudeMessagesConfig, + ) from .llms.together_ai.chat import TogetherAIConfig as TogetherAIConfig from .llms.nlp_cloud.chat.handler import NLPCloudConfig as NLPCloudConfig - from .llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import VertexGeminiConfig as VertexGeminiConfig - from .llms.gemini.chat.transformation import GoogleAIStudioGeminiConfig as GoogleAIStudioGeminiConfig - from .llms.vertex_ai.vertex_ai_partner_models.anthropic.transformation import VertexAIAnthropicConfig as VertexAIAnthropicConfig - from .llms.vertex_ai.vertex_ai_partner_models.llama3.transformation import VertexAILlama3Config as VertexAILlama3Config - from .llms.vertex_ai.vertex_ai_partner_models.ai21.transformation import VertexAIAi21Config as VertexAIAi21Config - from .llms.bedrock.chat.invoke_handler import AmazonCohereChatConfig as AmazonCohereChatConfig - from .llms.bedrock.common_utils import AmazonBedrockGlobalConfig as AmazonBedrockGlobalConfig - from .llms.bedrock.chat.invoke_transformations.amazon_ai21_transformation import AmazonAI21Config as AmazonAI21Config - from .llms.bedrock.chat.invoke_transformations.amazon_nova_transformation import AmazonInvokeNovaConfig as AmazonInvokeNovaConfig - from .llms.bedrock.chat.invoke_transformations.amazon_qwen2_transformation import AmazonQwen2Config as AmazonQwen2Config - from .llms.bedrock.chat.invoke_transformations.amazon_qwen3_transformation import AmazonQwen3Config as AmazonQwen3Config - from .llms.bedrock.chat.invoke_transformations.anthropic_claude2_transformation import AmazonAnthropicConfig as AmazonAnthropicConfig - from .llms.bedrock.chat.invoke_transformations.anthropic_claude3_transformation import AmazonAnthropicClaudeConfig as AmazonAnthropicClaudeConfig - from .llms.bedrock.chat.invoke_transformations.amazon_cohere_transformation import AmazonCohereConfig as AmazonCohereConfig - from .llms.bedrock.chat.invoke_transformations.amazon_llama_transformation import AmazonLlamaConfig as AmazonLlamaConfig - from .llms.bedrock.chat.invoke_transformations.amazon_deepseek_transformation import AmazonDeepSeekR1Config as AmazonDeepSeekR1Config - from .llms.bedrock.chat.invoke_transformations.amazon_mistral_transformation import AmazonMistralConfig as AmazonMistralConfig - from .llms.bedrock.chat.invoke_transformations.amazon_moonshot_transformation import AmazonMoonshotConfig as AmazonMoonshotConfig - from .llms.bedrock.chat.invoke_transformations.amazon_titan_transformation import AmazonTitanConfig as AmazonTitanConfig - from .llms.bedrock.chat.invoke_transformations.amazon_twelvelabs_pegasus_transformation import AmazonTwelveLabsPegasusConfig as AmazonTwelveLabsPegasusConfig - from .llms.bedrock.chat.invoke_transformations.base_invoke_transformation import AmazonInvokeConfig as AmazonInvokeConfig - from .llms.bedrock.chat.invoke_transformations.amazon_openai_transformation import AmazonBedrockOpenAIConfig as AmazonBedrockOpenAIConfig - from .llms.bedrock.image_generation.amazon_stability1_transformation import AmazonStabilityConfig as AmazonStabilityConfig - from .llms.bedrock.image_generation.amazon_stability3_transformation import AmazonStability3Config as AmazonStability3Config - from .llms.bedrock.image_generation.amazon_nova_canvas_transformation import AmazonNovaCanvasConfig as AmazonNovaCanvasConfig - from .llms.bedrock.embed.amazon_titan_g1_transformation import AmazonTitanG1Config as AmazonTitanG1Config - from .llms.bedrock.embed.amazon_titan_multimodal_transformation import AmazonTitanMultimodalEmbeddingG1Config as AmazonTitanMultimodalEmbeddingG1Config - from .llms.cohere.chat.v2_transformation import CohereV2ChatConfig as CohereV2ChatConfig - from .llms.bedrock.embed.cohere_transformation import BedrockCohereEmbeddingConfig as BedrockCohereEmbeddingConfig - from .llms.bedrock.embed.twelvelabs_marengo_transformation import TwelveLabsMarengoEmbeddingConfig as TwelveLabsMarengoEmbeddingConfig - from .llms.bedrock.embed.amazon_nova_transformation import AmazonNovaEmbeddingConfig as AmazonNovaEmbeddingConfig - from .llms.openai.openai import OpenAIConfig as OpenAIConfig, MistralEmbeddingConfig as MistralEmbeddingConfig - from .llms.openai.image_variations.transformation import OpenAIImageVariationConfig as OpenAIImageVariationConfig - from .llms.deepgram.audio_transcription.transformation import DeepgramAudioTranscriptionConfig as DeepgramAudioTranscriptionConfig - from .llms.topaz.image_variations.transformation import TopazImageVariationConfig as TopazImageVariationConfig - from litellm.llms.openai.completion.transformation import OpenAITextCompletionConfig as OpenAITextCompletionConfig + from .llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import ( + VertexGeminiConfig as VertexGeminiConfig, + ) + from .llms.gemini.chat.transformation import ( + GoogleAIStudioGeminiConfig as GoogleAIStudioGeminiConfig, + ) + from .llms.vertex_ai.vertex_ai_partner_models.anthropic.transformation import ( + VertexAIAnthropicConfig as VertexAIAnthropicConfig, + ) + from .llms.vertex_ai.vertex_ai_partner_models.llama3.transformation import ( + VertexAILlama3Config as VertexAILlama3Config, + ) + from .llms.vertex_ai.vertex_ai_partner_models.ai21.transformation import ( + VertexAIAi21Config as VertexAIAi21Config, + ) + from .llms.bedrock.chat.invoke_handler import ( + AmazonCohereChatConfig as AmazonCohereChatConfig, + ) + from .llms.bedrock.common_utils import ( + AmazonBedrockGlobalConfig as AmazonBedrockGlobalConfig, + ) + from .llms.bedrock.chat.invoke_transformations.amazon_ai21_transformation import ( + AmazonAI21Config as AmazonAI21Config, + ) + from .llms.bedrock.chat.invoke_transformations.amazon_nova_transformation import ( + AmazonInvokeNovaConfig as AmazonInvokeNovaConfig, + ) + from .llms.bedrock.chat.invoke_transformations.amazon_qwen2_transformation import ( + AmazonQwen2Config as AmazonQwen2Config, + ) + from .llms.bedrock.chat.invoke_transformations.amazon_qwen3_transformation import ( + AmazonQwen3Config as AmazonQwen3Config, + ) + from .llms.bedrock.chat.invoke_transformations.anthropic_claude2_transformation import ( + AmazonAnthropicConfig as AmazonAnthropicConfig, + ) + from .llms.bedrock.chat.invoke_transformations.anthropic_claude3_transformation import ( + AmazonAnthropicClaudeConfig as AmazonAnthropicClaudeConfig, + ) + from .llms.bedrock.chat.invoke_transformations.amazon_cohere_transformation import ( + AmazonCohereConfig as AmazonCohereConfig, + ) + from .llms.bedrock.chat.invoke_transformations.amazon_llama_transformation import ( + AmazonLlamaConfig as AmazonLlamaConfig, + ) + from .llms.bedrock.chat.invoke_transformations.amazon_deepseek_transformation import ( + AmazonDeepSeekR1Config as AmazonDeepSeekR1Config, + ) + from .llms.bedrock.chat.invoke_transformations.amazon_mistral_transformation import ( + AmazonMistralConfig as AmazonMistralConfig, + ) + from .llms.bedrock.chat.invoke_transformations.amazon_moonshot_transformation import ( + AmazonMoonshotConfig as AmazonMoonshotConfig, + ) + from .llms.bedrock.chat.invoke_transformations.amazon_titan_transformation import ( + AmazonTitanConfig as AmazonTitanConfig, + ) + from .llms.bedrock.chat.invoke_transformations.amazon_twelvelabs_pegasus_transformation import ( + AmazonTwelveLabsPegasusConfig as AmazonTwelveLabsPegasusConfig, + ) + from .llms.bedrock.chat.invoke_transformations.base_invoke_transformation import ( + AmazonInvokeConfig as AmazonInvokeConfig, + ) + from .llms.bedrock.chat.invoke_transformations.amazon_openai_transformation import ( + AmazonBedrockOpenAIConfig as AmazonBedrockOpenAIConfig, + ) + from .llms.bedrock.image_generation.amazon_stability1_transformation import ( + AmazonStabilityConfig as AmazonStabilityConfig, + ) + from .llms.bedrock.image_generation.amazon_stability3_transformation import ( + AmazonStability3Config as AmazonStability3Config, + ) + from .llms.bedrock.image_generation.amazon_nova_canvas_transformation import ( + AmazonNovaCanvasConfig as AmazonNovaCanvasConfig, + ) + from .llms.bedrock.embed.amazon_titan_g1_transformation import ( + AmazonTitanG1Config as AmazonTitanG1Config, + ) + from .llms.bedrock.embed.amazon_titan_multimodal_transformation import ( + AmazonTitanMultimodalEmbeddingG1Config as AmazonTitanMultimodalEmbeddingG1Config, + ) + from .llms.cohere.chat.v2_transformation import ( + CohereV2ChatConfig as CohereV2ChatConfig, + ) + from .llms.bedrock.embed.cohere_transformation import ( + BedrockCohereEmbeddingConfig as BedrockCohereEmbeddingConfig, + ) + from .llms.bedrock.embed.twelvelabs_marengo_transformation import ( + TwelveLabsMarengoEmbeddingConfig as TwelveLabsMarengoEmbeddingConfig, + ) + from .llms.bedrock.embed.amazon_nova_transformation import ( + AmazonNovaEmbeddingConfig as AmazonNovaEmbeddingConfig, + ) + from .llms.openai.openai import ( + OpenAIConfig as OpenAIConfig, + MistralEmbeddingConfig as MistralEmbeddingConfig, + ) + from .llms.openai.image_variations.transformation import ( + OpenAIImageVariationConfig as OpenAIImageVariationConfig, + ) + from .llms.deepgram.audio_transcription.transformation import ( + DeepgramAudioTranscriptionConfig as DeepgramAudioTranscriptionConfig, + ) + 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.bedrock_mantle.chat.transformation import BedrockMantleChatConfig as BedrockMantleChatConfig + from .llms.bedrock_mantle.chat.transformation import ( + BedrockMantleChatConfig as BedrockMantleChatConfig, + ) 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 - from .llms.perplexity.embedding.transformation import PerplexityEmbeddingConfig as PerplexityEmbeddingConfig - from .llms.azure_ai.chat.transformation import AzureAIStudioConfig as AzureAIStudioConfig + 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, + ) + from .llms.perplexity.embedding.transformation import ( + PerplexityEmbeddingConfig as PerplexityEmbeddingConfig, + ) + from .llms.azure_ai.chat.transformation import ( + AzureAIStudioConfig as AzureAIStudioConfig, + ) from .llms.mistral.chat.transformation import MistralConfig as MistralConfig - from .llms.openai.responses.transformation import OpenAIResponsesAPIConfig as OpenAIResponsesAPIConfig - from .llms.azure.responses.transformation import AzureOpenAIResponsesAPIConfig as AzureOpenAIResponsesAPIConfig - from .llms.azure.responses.o_series_transformation import AzureOpenAIOSeriesResponsesAPIConfig as AzureOpenAIOSeriesResponsesAPIConfig - from .llms.xai.responses.transformation import XAIResponsesAPIConfig as XAIResponsesAPIConfig - from .llms.litellm_proxy.responses.transformation import LiteLLMProxyResponsesAPIConfig as LiteLLMProxyResponsesAPIConfig - from .llms.volcengine.responses.transformation import VolcEngineResponsesAPIConfig as VolcEngineResponsesAPIConfig - from .llms.manus.responses.transformation import ManusResponsesAPIConfig as ManusResponsesAPIConfig - from .llms.perplexity.responses.transformation import PerplexityResponsesConfig as PerplexityResponsesConfig - from .llms.databricks.responses.transformation import DatabricksResponsesAPIConfig as DatabricksResponsesAPIConfig - from .llms.openrouter.responses.transformation import OpenRouterResponsesAPIConfig as OpenRouterResponsesAPIConfig - from .llms.gemini.interactions.transformation import GoogleAIStudioInteractionsConfig as GoogleAIStudioInteractionsConfig - from .llms.openai.chat.o_series_transformation import OpenAIOSeriesConfig as OpenAIOSeriesConfig, OpenAIOSeriesConfig as OpenAIO1Config - from .llms.anthropic.skills.transformation import AnthropicSkillsConfig as AnthropicSkillsConfig - from .llms.base_llm.skills.transformation import BaseSkillsAPIConfig as BaseSkillsAPIConfig - from .llms.gradient_ai.chat.transformation import GradientAIConfig as GradientAIConfig + from .llms.openai.responses.transformation import ( + OpenAIResponsesAPIConfig as OpenAIResponsesAPIConfig, + ) + from .llms.azure.responses.transformation import ( + AzureOpenAIResponsesAPIConfig as AzureOpenAIResponsesAPIConfig, + ) + from .llms.azure.responses.o_series_transformation import ( + AzureOpenAIOSeriesResponsesAPIConfig as AzureOpenAIOSeriesResponsesAPIConfig, + ) + from .llms.xai.responses.transformation import ( + XAIResponsesAPIConfig as XAIResponsesAPIConfig, + ) + from .llms.litellm_proxy.responses.transformation import ( + LiteLLMProxyResponsesAPIConfig as LiteLLMProxyResponsesAPIConfig, + ) + from .llms.volcengine.responses.transformation import ( + VolcEngineResponsesAPIConfig as VolcEngineResponsesAPIConfig, + ) + from .llms.manus.responses.transformation import ( + ManusResponsesAPIConfig as ManusResponsesAPIConfig, + ) + from .llms.perplexity.responses.transformation import ( + PerplexityResponsesConfig as PerplexityResponsesConfig, + ) + from .llms.databricks.responses.transformation import ( + DatabricksResponsesAPIConfig as DatabricksResponsesAPIConfig, + ) + from .llms.openrouter.responses.transformation import ( + OpenRouterResponsesAPIConfig as OpenRouterResponsesAPIConfig, + ) + from .llms.gemini.interactions.transformation import ( + GoogleAIStudioInteractionsConfig as GoogleAIStudioInteractionsConfig, + ) + from .llms.openai.chat.o_series_transformation import ( + OpenAIOSeriesConfig as OpenAIOSeriesConfig, + OpenAIOSeriesConfig as OpenAIO1Config, + ) + from .llms.anthropic.skills.transformation import ( + AnthropicSkillsConfig as AnthropicSkillsConfig, + ) + from .llms.base_llm.skills.transformation import ( + BaseSkillsAPIConfig as BaseSkillsAPIConfig, + ) + from .llms.gradient_ai.chat.transformation import ( + GradientAIConfig as GradientAIConfig, + ) from .llms.openai.chat.gpt_transformation import OpenAIGPTConfig as OpenAIGPTConfig - from .llms.openai.chat.gpt_5_transformation import OpenAIGPT5Config as OpenAIGPT5Config - from .llms.openai.transcriptions.whisper_transformation import OpenAIWhisperAudioTranscriptionConfig as OpenAIWhisperAudioTranscriptionConfig - from .llms.openai.transcriptions.gpt_transformation import OpenAIGPTAudioTranscriptionConfig as OpenAIGPTAudioTranscriptionConfig - from .llms.openai.chat.gpt_audio_transformation import OpenAIGPTAudioConfig as OpenAIGPTAudioConfig + from .llms.openai.chat.gpt_5_transformation import ( + OpenAIGPT5Config as OpenAIGPT5Config, + ) + from .llms.openai.transcriptions.whisper_transformation import ( + OpenAIWhisperAudioTranscriptionConfig as OpenAIWhisperAudioTranscriptionConfig, + ) + from .llms.openai.transcriptions.gpt_transformation import ( + OpenAIGPTAudioTranscriptionConfig as OpenAIGPTAudioTranscriptionConfig, + ) + from .llms.openai.chat.gpt_audio_transformation import ( + OpenAIGPTAudioConfig as OpenAIGPTAudioConfig, + ) from .llms.nvidia_nim.chat.transformation import NvidiaNimConfig as NvidiaNimConfig - from .llms.nvidia_nim.embed import NvidiaNimEmbeddingConfig as NvidiaNimEmbeddingConfig + from .llms.nvidia_nim.embed import ( + NvidiaNimEmbeddingConfig as NvidiaNimEmbeddingConfig, + ) # Type stubs for lazy-loaded config instances openaiOSeriesConfig: OpenAIOSeriesConfig @@ -1480,21 +1683,47 @@ if TYPE_CHECKING: # Import config classes that need type stubs (for mypy) - import with _ prefix to avoid circular reference from .llms.vllm.completion.transformation import VLLMConfig as _VLLMConfig - from .llms.deepseek.chat.transformation import DeepSeekChatConfig as _DeepSeekChatConfig - from .llms.sap.chat.transformation import GenAIHubOrchestrationConfig as _GenAIHubOrchestrationConfig - from .llms.sap.embed.transformation import GenAIHubEmbeddingConfig as _GenAIHubEmbeddingConfig - from .llms.azure.chat.o_series_transformation import AzureOpenAIO1Config as _AzureOpenAIO1Config - from .llms.perplexity.chat.transformation import PerplexityChatConfig as _PerplexityChatConfig + from .llms.deepseek.chat.transformation import ( + DeepSeekChatConfig as _DeepSeekChatConfig, + ) + from .llms.sap.chat.transformation import ( + GenAIHubOrchestrationConfig as _GenAIHubOrchestrationConfig, + ) + from .llms.sap.embed.transformation import ( + GenAIHubEmbeddingConfig as _GenAIHubEmbeddingConfig, + ) + from .llms.azure.chat.o_series_transformation import ( + AzureOpenAIO1Config as _AzureOpenAIO1Config, + ) + from .llms.perplexity.chat.transformation import ( + PerplexityChatConfig as _PerplexityChatConfig, + ) from .llms.nscale.chat.transformation import NscaleConfig as _NscaleConfig - from .llms.watsonx.chat.transformation import IBMWatsonXChatConfig as _IBMWatsonXChatConfig - from .llms.watsonx.completion.transformation import IBMWatsonXAIConfig as _IBMWatsonXAIConfig - from .llms.litellm_proxy.chat.transformation import LiteLLMProxyChatConfig as _LiteLLMProxyChatConfig + from .llms.watsonx.chat.transformation import ( + IBMWatsonXChatConfig as _IBMWatsonXChatConfig, + ) + from .llms.watsonx.completion.transformation import ( + IBMWatsonXAIConfig as _IBMWatsonXAIConfig, + ) + from .llms.litellm_proxy.chat.transformation import ( + LiteLLMProxyChatConfig as _LiteLLMProxyChatConfig, + ) from .llms.deepinfra.chat.transformation import DeepInfraConfig as _DeepInfraConfig - from .llms.llamafile.chat.transformation import LlamafileChatConfig as _LlamafileChatConfig - from .llms.lm_studio.chat.transformation import LMStudioChatConfig as _LMStudioChatConfig - from .llms.lm_studio.embed.transformation import LmStudioEmbeddingConfig as _LmStudioEmbeddingConfig - from .llms.watsonx.embed.transformation import IBMWatsonXEmbeddingConfig as _IBMWatsonXEmbeddingConfig - from .llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import VertexGeminiConfig as _VertexGeminiConfig + from .llms.llamafile.chat.transformation import ( + LlamafileChatConfig as _LlamafileChatConfig, + ) + from .llms.lm_studio.chat.transformation import ( + LMStudioChatConfig as _LMStudioChatConfig, + ) + from .llms.lm_studio.embed.transformation import ( + LmStudioEmbeddingConfig as _LmStudioEmbeddingConfig, + ) + from .llms.watsonx.embed.transformation import ( + IBMWatsonXEmbeddingConfig as _IBMWatsonXEmbeddingConfig, + ) + from .llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import ( + VertexGeminiConfig as _VertexGeminiConfig, + ) # Type stubs for lazy-loaded config classes (to help mypy understand types) VLLMConfig: Type[_VLLMConfig] @@ -1514,56 +1743,125 @@ if TYPE_CHECKING: IBMWatsonXEmbeddingConfig: Type[_IBMWatsonXEmbeddingConfig] VertexAIConfig: Type[_VertexGeminiConfig] # Alias for VertexGeminiConfig - from .llms.featherless_ai.chat.transformation import FeatherlessAIConfig as FeatherlessAIConfig + from .llms.featherless_ai.chat.transformation import ( + FeatherlessAIConfig as FeatherlessAIConfig, + ) from .llms.cerebras.chat import CerebrasConfig as CerebrasConfig from .llms.baseten.chat import BasetenConfig as BasetenConfig from .llms.sambanova.chat import SambanovaConfig as SambanovaConfig - from .llms.sambanova.embedding.transformation import SambaNovaEmbeddingConfig as SambaNovaEmbeddingConfig - from .llms.fireworks_ai.chat.transformation import FireworksAIConfig as FireworksAIConfig - from .llms.fireworks_ai.completion.transformation import FireworksAITextCompletionConfig as FireworksAITextCompletionConfig - from .llms.fireworks_ai.audio_transcription.transformation import FireworksAIAudioTranscriptionConfig as FireworksAIAudioTranscriptionConfig - from .llms.fireworks_ai.embed.fireworks_ai_transformation import FireworksAIEmbeddingConfig as FireworksAIEmbeddingConfig - from .llms.friendliai.chat.transformation import FriendliaiChatConfig as FriendliaiChatConfig - from .llms.jina_ai.embedding.transformation import JinaAIEmbeddingConfig as JinaAIEmbeddingConfig + from .llms.sambanova.embedding.transformation import ( + SambaNovaEmbeddingConfig as SambaNovaEmbeddingConfig, + ) + from .llms.fireworks_ai.chat.transformation import ( + FireworksAIConfig as FireworksAIConfig, + ) + from .llms.fireworks_ai.completion.transformation import ( + FireworksAITextCompletionConfig as FireworksAITextCompletionConfig, + ) + from .llms.fireworks_ai.audio_transcription.transformation import ( + FireworksAIAudioTranscriptionConfig as FireworksAIAudioTranscriptionConfig, + ) + from .llms.fireworks_ai.embed.fireworks_ai_transformation import ( + FireworksAIEmbeddingConfig as FireworksAIEmbeddingConfig, + ) + from .llms.friendliai.chat.transformation import ( + FriendliaiChatConfig as FriendliaiChatConfig, + ) + from .llms.jina_ai.embedding.transformation import ( + JinaAIEmbeddingConfig as JinaAIEmbeddingConfig, + ) from .llms.xai.chat.transformation import XAIChatConfig as XAIChatConfig from .llms.zai.chat.transformation import ZAIChatConfig as ZAIChatConfig from .llms.aiml.chat.transformation import AIMLChatConfig as AIMLChatConfig - from .llms.volcengine.chat.transformation import VolcEngineChatConfig as VolcEngineChatConfig, VolcEngineChatConfig as VolcEngineConfig - from .llms.codestral.completion.transformation import CodestralTextCompletionConfig as CodestralTextCompletionConfig - from .llms.azure.azure import AzureOpenAIAssistantsAPIConfig as AzureOpenAIAssistantsAPIConfig + from .llms.volcengine.chat.transformation import ( + VolcEngineChatConfig as VolcEngineChatConfig, + VolcEngineChatConfig as VolcEngineConfig, + ) + from .llms.codestral.completion.transformation import ( + CodestralTextCompletionConfig as CodestralTextCompletionConfig, + ) + from .llms.azure.azure import ( + AzureOpenAIAssistantsAPIConfig as AzureOpenAIAssistantsAPIConfig, + ) from .llms.heroku.chat.transformation import HerokuChatConfig as HerokuChatConfig from .llms.cometapi.chat.transformation import CometAPIConfig as CometAPIConfig - from .llms.azure.chat.gpt_transformation import AzureOpenAIConfig as AzureOpenAIConfig - from .llms.azure.chat.gpt_5_transformation import AzureOpenAIGPT5Config as AzureOpenAIGPT5Config - from .llms.azure.completion.transformation import AzureOpenAITextConfig as AzureOpenAITextConfig - from .llms.hosted_vllm.chat.transformation import HostedVLLMChatConfig as HostedVLLMChatConfig - from .llms.hosted_vllm.embedding.transformation import HostedVLLMEmbeddingConfig as HostedVLLMEmbeddingConfig - from .llms.hosted_vllm.responses.transformation import HostedVLLMResponsesAPIConfig as HostedVLLMResponsesAPIConfig - from .llms.github_copilot.chat.transformation import GithubCopilotConfig as GithubCopilotConfig - from .llms.github_copilot.responses.transformation import GithubCopilotResponsesAPIConfig as GithubCopilotResponsesAPIConfig - from .llms.github_copilot.embedding.transformation import GithubCopilotEmbeddingConfig as GithubCopilotEmbeddingConfig + from .llms.azure.chat.gpt_transformation import ( + AzureOpenAIConfig as AzureOpenAIConfig, + ) + from .llms.azure.chat.gpt_5_transformation import ( + AzureOpenAIGPT5Config as AzureOpenAIGPT5Config, + ) + from .llms.azure.completion.transformation import ( + AzureOpenAITextConfig as AzureOpenAITextConfig, + ) + from .llms.hosted_vllm.chat.transformation import ( + HostedVLLMChatConfig as HostedVLLMChatConfig, + ) + from .llms.hosted_vllm.embedding.transformation import ( + HostedVLLMEmbeddingConfig as HostedVLLMEmbeddingConfig, + ) + from .llms.hosted_vllm.responses.transformation import ( + HostedVLLMResponsesAPIConfig as HostedVLLMResponsesAPIConfig, + ) + from .llms.github_copilot.chat.transformation import ( + GithubCopilotConfig as GithubCopilotConfig, + ) + from .llms.github_copilot.responses.transformation import ( + GithubCopilotResponsesAPIConfig as GithubCopilotResponsesAPIConfig, + ) + from .llms.github_copilot.embedding.transformation import ( + GithubCopilotEmbeddingConfig as GithubCopilotEmbeddingConfig, + ) from .llms.chatgpt.chat.transformation import ChatGPTConfig as ChatGPTConfig - from .llms.chatgpt.responses.transformation import ChatGPTResponsesAPIConfig as ChatGPTResponsesAPIConfig + from .llms.chatgpt.responses.transformation import ( + ChatGPTResponsesAPIConfig as ChatGPTResponsesAPIConfig, + ) from .llms.gigachat.chat.transformation import GigaChatConfig as GigaChatConfig - from .llms.gigachat.embedding.transformation import GigaChatEmbeddingConfig as GigaChatEmbeddingConfig + from .llms.gigachat.embedding.transformation import ( + GigaChatEmbeddingConfig as GigaChatEmbeddingConfig, + ) from .llms.nebius.chat.transformation import NebiusConfig as NebiusConfig from .llms.wandb.chat.transformation import WandbConfig as WandbConfig - from .llms.dashscope.chat.transformation import DashScopeChatConfig as DashScopeChatConfig - from .llms.moonshot.chat.transformation import MoonshotChatConfig as MoonshotChatConfig - from .llms.docker_model_runner.chat.transformation import DockerModelRunnerChatConfig as DockerModelRunnerChatConfig + from .llms.dashscope.chat.transformation import ( + DashScopeChatConfig as DashScopeChatConfig, + ) + from .llms.moonshot.chat.transformation import ( + MoonshotChatConfig as MoonshotChatConfig, + ) + from .llms.docker_model_runner.chat.transformation import ( + DockerModelRunnerChatConfig as DockerModelRunnerChatConfig, + ) from .llms.v0.chat.transformation import V0ChatConfig as V0ChatConfig from .llms.oci.chat.transformation import OCIChatConfig as OCIChatConfig from .llms.morph.chat.transformation import MorphChatConfig as MorphChatConfig from .llms.ragflow.chat.transformation import RAGFlowConfig as RAGFlowConfig - from .llms.lambda_ai.chat.transformation import LambdaAIChatConfig as LambdaAIChatConfig - from .llms.hyperbolic.chat.transformation import HyperbolicChatConfig as HyperbolicChatConfig - from .llms.vercel_ai_gateway.chat.transformation import VercelAIGatewayConfig as VercelAIGatewayConfig - from .llms.ovhcloud.chat.transformation import OVHCloudChatConfig as OVHCloudChatConfig - from .llms.ovhcloud.embedding.transformation import OVHCloudEmbeddingConfig as OVHCloudEmbeddingConfig - from .llms.cometapi.embed.transformation import CometAPIEmbeddingConfig as CometAPIEmbeddingConfig - from .llms.lemonade.chat.transformation import LemonadeChatConfig as LemonadeChatConfig - from .llms.snowflake.embedding.transformation import SnowflakeEmbeddingConfig as SnowflakeEmbeddingConfig - from .llms.amazon_nova.chat.transformation import AmazonNovaChatConfig as AmazonNovaChatConfig + from .llms.lambda_ai.chat.transformation import ( + LambdaAIChatConfig as LambdaAIChatConfig, + ) + from .llms.hyperbolic.chat.transformation import ( + HyperbolicChatConfig as HyperbolicChatConfig, + ) + from .llms.vercel_ai_gateway.chat.transformation import ( + VercelAIGatewayConfig as VercelAIGatewayConfig, + ) + from .llms.ovhcloud.chat.transformation import ( + OVHCloudChatConfig as OVHCloudChatConfig, + ) + from .llms.ovhcloud.embedding.transformation import ( + OVHCloudEmbeddingConfig as OVHCloudEmbeddingConfig, + ) + from .llms.cometapi.embed.transformation import ( + CometAPIEmbeddingConfig as CometAPIEmbeddingConfig, + ) + from .llms.lemonade.chat.transformation import ( + LemonadeChatConfig as LemonadeChatConfig, + ) + from .llms.snowflake.embedding.transformation import ( + SnowflakeEmbeddingConfig as SnowflakeEmbeddingConfig, + ) + from .llms.amazon_nova.chat.transformation import ( + AmazonNovaChatConfig as AmazonNovaChatConfig, + ) from litellm.caching.llm_caching_handler import LLMClientCache from litellm.types.llms.bedrock import COHERE_EMBEDDING_INPUT_TYPES from litellm.types.utils import ( @@ -1599,7 +1897,7 @@ if TYPE_CHECKING: supports_reasoning: Callable[..., bool] acreate: Callable[..., Any] get_max_tokens: Callable[..., int] - get_model_info: Callable[..., _ModelInfoType] + get_model_info: Callable[..., _ModelInfoType] # type: ignore[no-redef] register_prompt_template: Callable[..., None] validate_environment: Callable[..., dict] check_valid_key: Callable[..., bool] @@ -1624,6 +1922,7 @@ if TYPE_CHECKING: # Bedrock tool name mappings instance (lazy-loaded) from litellm.caching.caching import InMemoryCache + bedrock_tool_name_mappings: InMemoryCache # Azure exception class (lazy-loaded) @@ -1642,11 +1941,15 @@ if TYPE_CHECKING: from litellm.types.integrations.datadog_llm_obs import DatadogLLMObsInitParams # Logging callback manager class and instance (lazy-loaded) - from litellm.litellm_core_utils.logging_callback_manager import LoggingCallbackManager + from litellm.litellm_core_utils.logging_callback_manager import ( + LoggingCallbackManager, + ) + logging_callback_manager: LoggingCallbackManager # provider_list is lazy-loaded from litellm.types.utils import LlmProviders + provider_list: List[Union[LlmProviders, str]] # Note: AmazonConverseConfig and OpenAILikeChatConfig are imported above in TYPE_CHECKING block @@ -1671,7 +1974,10 @@ def __getattr__(name: str) -> Any: global _async_client_cleanup_registered # Register async client cleanup on first access (only once) if not _async_client_cleanup_registered: - from litellm.llms.custom_httpx.async_client_cleanup import register_async_client_cleanup + from litellm.llms.custom_httpx.async_client_cleanup import ( + register_async_client_cleanup, + ) + register_async_client_cleanup() _async_client_cleanup_registered = True @@ -1688,36 +1994,45 @@ def __getattr__(name: str) -> Any: # Lazy load encoding from main.py to avoid heavy tiktoken import if name == "encoding": from ._lazy_imports import _get_litellm_globals + _globals = _get_litellm_globals() # Check if already cached if "encoding" not in _globals: from .main import encoding as _encoding + _globals["encoding"] = _encoding return _globals["encoding"] # Lazy load bedrock_tool_name_mappings instance if name == "bedrock_tool_name_mappings": from ._lazy_imports import _get_litellm_globals + _globals = _get_litellm_globals() # Check if already cached if "bedrock_tool_name_mappings" not in _globals: - from .llms.bedrock.chat.invoke_handler import bedrock_tool_name_mappings as _bedrock_tool_name_mappings + from .llms.bedrock.chat.invoke_handler import ( + bedrock_tool_name_mappings as _bedrock_tool_name_mappings, + ) + _globals["bedrock_tool_name_mappings"] = _bedrock_tool_name_mappings return _globals["bedrock_tool_name_mappings"] # Lazy load AzureOpenAIError exception class if name == "AzureOpenAIError": from ._lazy_imports import _get_litellm_globals + _globals = _get_litellm_globals() # Check if already cached if "AzureOpenAIError" not in _globals: from .llms.azure.common_utils import AzureOpenAIError as _AzureOpenAIError + _globals["AzureOpenAIError"] = _AzureOpenAIError return _globals["AzureOpenAIError"] # Lazy load openaiOSeriesConfig instance if name == "openaiOSeriesConfig": from ._lazy_imports import _get_litellm_globals + _globals = _get_litellm_globals() if "openaiOSeriesConfig" not in _globals: # Import the config class and instantiate it @@ -1735,6 +2050,7 @@ def __getattr__(name: str) -> Any: } if name in _config_instances: from ._lazy_imports import _get_litellm_globals + _globals = _get_litellm_globals() if name not in _globals: # Import the config class and instantiate it @@ -1749,17 +2065,20 @@ def __getattr__(name: str) -> Any: # Lazy load provider_list if name == "provider_list": from ._lazy_imports import _get_litellm_globals + _globals = _get_litellm_globals() # Check if already cached if "provider_list" not in _globals: # LlmProviders is eagerly imported above, so we can import it directly from litellm.types.utils import LlmProviders + _globals["provider_list"] = list(LlmProviders) return _globals["provider_list"] # Lazy load priority_reservation_settings instance if name == "priority_reservation_settings": from ._lazy_imports import _get_litellm_globals + _globals = _get_litellm_globals() # Check if already cached if "priority_reservation_settings" not in _globals: @@ -1771,6 +2090,7 @@ def __getattr__(name: str) -> Any: # Lazy load logging_callback_manager instance if name == "logging_callback_manager": from ._lazy_imports import _get_litellm_globals + _globals = _get_litellm_globals() # Check if already cached if "logging_callback_manager" not in _globals: @@ -1782,19 +2102,41 @@ def __getattr__(name: str) -> Any: # Lazy load _service_logger module if name == "_service_logger": from ._lazy_imports import _get_litellm_globals + _globals = _get_litellm_globals() # Check if already cached if "_service_logger" not in _globals: # Import the module lazily import litellm._service_logger + _globals["_service_logger"] = litellm._service_logger return _globals["_service_logger"] # Lazy load evals module functions - if name in ["acreate_eval", "alist_evals", "aget_eval", "aupdate_eval", "adelete_eval", "acancel_eval", - "create_eval", "list_evals", "get_eval", "update_eval", "delete_eval", "cancel_eval", - "acreate_run", "alist_runs", "aget_run", "acancel_run", "adelete_run", - "create_run", "list_runs", "get_run", "cancel_run", "delete_run"]: + if name in [ + "acreate_eval", + "alist_evals", + "aget_eval", + "aupdate_eval", + "adelete_eval", + "acancel_eval", + "create_eval", + "list_evals", + "get_eval", + "update_eval", + "delete_eval", + "cancel_eval", + "acreate_run", + "alist_runs", + "aget_run", + "acancel_run", + "adelete_run", + "create_run", + "list_runs", + "get_run", + "cancel_run", + "delete_run", + ]: from litellm.evals.main import ( acreate_eval, alist_evals, @@ -1819,6 +2161,7 @@ def __getattr__(name: str) -> Any: cancel_run, delete_run, ) + return locals()[name] raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/litellm/_lazy_imports.py b/litellm/_lazy_imports.py index 3bfeba2e394..3604506d406 100644 --- a/litellm/_lazy_imports.py +++ b/litellm/_lazy_imports.py @@ -55,7 +55,7 @@ from ._lazy_imports_registry import ( def _get_litellm_globals() -> dict: """ Get the globals dictionary of the litellm module. - + This is where we cache imported attributes so we don't import them twice. When you do `litellm.some_function`, it gets stored in this dictionary. """ @@ -65,12 +65,13 @@ def _get_litellm_globals() -> dict: def _get_utils_globals() -> dict: """ Get the globals dictionary of the utils module. - + This is where we cache imported attributes so we don't import them twice. When you do `litellm.utils.some_function`, it gets stored in this dictionary. """ return sys.modules["litellm.utils"].__dict__ + # These are special lazy loaders for things that are used internally # They're separate from the main lazy import system because they have specific use cases @@ -81,10 +82,10 @@ _default_encoding: Optional[Any] = None def _get_default_encoding() -> Any: """ Lazily load and cache the default OpenAI encoding. - + This avoids importing `litellm.litellm_core_utils.default_encoding` (and thus tiktoken) at `litellm` import time. The encoding is cached after the first import. - + This is used internally by utils.py functions that need the encoding but shouldn't trigger its import during module load. """ @@ -103,10 +104,10 @@ _get_modified_max_tokens_func: Optional[Any] = None def _get_modified_max_tokens() -> Any: """ Lazily load and cache the get_modified_max_tokens function. - + This avoids importing `litellm.litellm_core_utils.token_counter` at `litellm` import time. The function is cached after the first import. - + This is used internally by utils.py functions that need the token counter but shouldn't trigger its import during module load. """ @@ -127,10 +128,10 @@ _token_counter_new_func: Optional[Any] = None def _get_token_counter_new() -> Any: """ Lazily load and cache the token_counter function (aliased as token_counter_new). - + This avoids importing `litellm.litellm_core_utils.token_counter` at `litellm` import time. The function is cached after the first import. - + This is used internally by utils.py functions that need the token counter but shouldn't trigger its import during module load. """ @@ -157,10 +158,10 @@ _LAZY_IMPORT_REGISTRY: Optional[dict[str, Callable[[str], Any]]] = None def _get_lazy_import_registry() -> dict[str, Callable[[str], Any]]: """ Build the registry that maps attribute names to their handler functions. - + This is called once, the first time someone accesses a lazy-loaded attribute. After that, we just look up the handler function in this dictionary. - + Returns: Dictionary like {"ModelResponse": _lazy_import_utils, ...} """ @@ -199,17 +200,19 @@ def _get_lazy_import_registry() -> dict[str, Callable[[str], Any]]: _LAZY_IMPORT_REGISTRY[name] = _lazy_import_llm_provider_logic for name in UTILS_MODULE_NAMES: _LAZY_IMPORT_REGISTRY[name] = _lazy_import_utils_module - + return _LAZY_IMPORT_REGISTRY -def _generic_lazy_import(name: str, import_map: dict[str, tuple[str, str]], category: str) -> Any: +def _generic_lazy_import( + name: str, import_map: dict[str, tuple[str, str]], category: str +) -> Any: """ Generic function that handles lazy importing for most attributes. - + This is the workhorse function - it does the actual importing and caching. Most handler functions just call this with their specific import map. - + Steps: 1. Check if the name exists in the import map (if not, raise error) 2. Check if we've already imported it (if yes, return cached value) @@ -218,7 +221,7 @@ def _generic_lazy_import(name: str, import_map: dict[str, tuple[str, str]], cate 5. Get the attribute from the module 6. Cache it in _globals so we don't import again 7. Return it - + Args: name: The attribute name someone is trying to access (e.g., "ModelResponse") import_map: Dictionary telling us where to find each attribute @@ -228,19 +231,19 @@ def _generic_lazy_import(name: str, import_map: dict[str, tuple[str, str]], cate # Step 1: Make sure this attribute exists in our map if name not in import_map: raise AttributeError(f"{category} lazy import: unknown attribute {name!r}") - + # Step 2: Get the cache (where we store imported things) _globals = _get_litellm_globals() - + # Step 3: If we've already imported it, just return the cached version if name in _globals: return _globals[name] - + # Step 4: Look up where to find this attribute # The map tells us: (module_path, attribute_name) # Example: (".utils", "ModelResponse") means "look in .utils module, get ModelResponse" module_path, attr_name = import_map[name] - + # Step 5: Import the module # Python automatically caches modules in sys.modules, so calling this twice is fast # If module_path starts with ".", it's a relative import (needs package="litellm") @@ -249,14 +252,14 @@ def _generic_lazy_import(name: str, import_map: dict[str, tuple[str, str]], cate module = importlib.import_module(module_path, package="litellm") else: module = importlib.import_module(module_path) - + # Step 6: Get the actual attribute from the module # Example: getattr(utils_module, "ModelResponse") returns the ModelResponse class value = getattr(module, attr_name) - + # Step 7: Cache it so we don't have to import again next time _globals[name] = value - + # Step 8: Return it return value @@ -268,6 +271,7 @@ def _generic_lazy_import(name: str, import_map: dict[str, tuple[str, str]], cate # Most of them just call _generic_lazy_import with their specific import map. # The registry (above) maps attribute names to these handler functions. + def _lazy_import_utils(name: str) -> Any: """Handler for utils module attributes (ModelResponse, token_counter, etc.)""" return _generic_lazy_import(name, _UTILS_IMPORT_MAP, "Utils") @@ -297,6 +301,7 @@ def _lazy_import_caching(name: str) -> Any: """Handler for caching classes (Cache, DualCache, RedisCache, etc.)""" return _generic_lazy_import(name, _CACHING_IMPORT_MAP, "Caching") + def _lazy_import_dotprompt(name: str) -> Any: """Handler for dotprompt integration globals""" return _generic_lazy_import(name, _DOTPROMPT_IMPORT_MAP, "Dotprompt") @@ -311,6 +316,7 @@ def _lazy_import_llm_configs(name: str) -> Any: """Handler for LLM config classes (AnthropicConfig, OpenAILikeChatConfig, etc.)""" return _generic_lazy_import(name, _LLM_CONFIGS_IMPORT_MAP, "LLM config") + def _lazy_import_litellm_logging(name: str) -> Any: """Handler for litellm_logging module (Logging, modify_integration)""" return _generic_lazy_import(name, _LITELLM_LOGGING_IMPORT_MAP, "Litellm logging") @@ -318,87 +324,91 @@ def _lazy_import_litellm_logging(name: str) -> Any: def _lazy_import_llm_provider_logic(name: str) -> Any: """Handler for LLM provider logic functions (get_llm_provider, etc.)""" - return _generic_lazy_import(name, _LLM_PROVIDER_LOGIC_IMPORT_MAP, "LLM provider logic") + return _generic_lazy_import( + name, _LLM_PROVIDER_LOGIC_IMPORT_MAP, "LLM provider logic" + ) def _lazy_import_utils_module(name: str) -> Any: """ Handler for utils module lazy imports. - + This uses a custom implementation because utils module needs to use _get_utils_globals() instead of _get_litellm_globals() for caching. """ # Check if this attribute exists in our map if name not in _UTILS_MODULE_IMPORT_MAP: raise AttributeError(f"Utils module lazy import: unknown attribute {name!r}") - + # Get the cache (where we store imported things) - use utils globals _globals = _get_utils_globals() - + # If we've already imported it, just return the cached version if name in _globals: return _globals[name] - + # Look up where to find this attribute module_path, attr_name = _UTILS_MODULE_IMPORT_MAP[name] - + # Import the module if module_path.startswith("."): module = importlib.import_module(module_path, package="litellm") else: module = importlib.import_module(module_path) - + # Get the actual attribute from the module value = getattr(module, attr_name) - + # Cache it so we don't have to import again next time _globals[name] = value - + # Return it return value + # ============================================================================ # SPECIAL HANDLERS # ============================================================================ # These handlers have custom logic that doesn't fit the generic pattern + def _lazy_import_llm_client_cache(name: str) -> Any: """ Handler for LLM client cache - has special logic for singleton instance. - + This one is different because: - "LLMClientCache" is the class itself - "in_memory_llm_clients_cache" is a singleton instance of that class So we need custom logic to handle both cases. """ _globals = _get_litellm_globals() - + # If already cached, return it if name in _globals: return _globals[name] - + # Import the class module = importlib.import_module("litellm.caching.llm_caching_handler") LLMClientCache = getattr(module, "LLMClientCache") - + # If they want the class itself, return it if name == "LLMClientCache": _globals["LLMClientCache"] = LLMClientCache return LLMClientCache - + # If they want the singleton instance, create it (only once) if name == "in_memory_llm_clients_cache": instance = LLMClientCache() _globals["in_memory_llm_clients_cache"] = instance return instance - + raise AttributeError(f"LLM client cache lazy import: unknown attribute {name!r}") def _lazy_import_http_handlers(name: str) -> Any: """ Handler for HTTP clients - has special logic for creating client instances. - + This one is different because: - These aren't just imports, they're actual client instances that need to be created - They need configuration (timeout, etc.) from the module globals @@ -413,14 +423,14 @@ def _lazy_import_http_handlers(name: str) -> Any: # Get timeout from module config (if set) timeout = _globals.get("request_timeout") params = {"timeout": timeout, "client_alias": "module level aclient"} - + # Create the client instance provider_id = cast(Any, "litellm_module_level_client") async_client = get_async_httpx_client( llm_provider=provider_id, params=params, ) - + # Cache it so we don't create it again _globals["module_level_aclient"] = async_client return async_client @@ -431,7 +441,7 @@ def _lazy_import_http_handlers(name: str) -> Any: timeout = _globals.get("request_timeout") sync_client = HTTPHandler(timeout=timeout) - + # Cache it _globals["module_level_client"] = sync_client return sync_client diff --git a/litellm/_lazy_imports_registry.py b/litellm/_lazy_imports_registry.py index 9e0453102d0..f7f56d2b889 100644 --- a/litellm/_lazy_imports_registry.py +++ b/litellm/_lazy_imports_registry.py @@ -677,7 +677,10 @@ _LLM_CONFIGS_IMPORT_MAP = { "FireworksAIRerankConfig", ), "VoyageRerankConfig": (".llms.voyage.rerank.transformation", "VoyageRerankConfig"), - "IBMWatsonXRerankConfig": (".llms.watsonx.rerank.transformation", "IBMWatsonXRerankConfig"), + "IBMWatsonXRerankConfig": ( + ".llms.watsonx.rerank.transformation", + "IBMWatsonXRerankConfig", + ), "ClarifaiConfig": (".llms.clarifai.chat.transformation", "ClarifaiConfig"), "AI21ChatConfig": (".llms.ai21.chat.transformation", "AI21ChatConfig"), "LlamaAPIConfig": (".llms.meta_llama.chat.transformation", "LlamaAPIConfig"), @@ -859,7 +862,10 @@ _LLM_CONFIGS_IMPORT_MAP = { "OpenAITextCompletionConfig", ), "GroqChatConfig": (".llms.groq.chat.transformation", "GroqChatConfig"), - "BedrockMantleChatConfig": (".llms.bedrock_mantle.chat.transformation", "BedrockMantleChatConfig"), + "BedrockMantleChatConfig": ( + ".llms.bedrock_mantle.chat.transformation", + "BedrockMantleChatConfig", + ), "A2AConfig": (".llms.a2a.chat.transformation", "A2AConfig"), "GenAIHubOrchestrationConfig": ( ".llms.sap.chat.transformation", diff --git a/litellm/_redis.py b/litellm/_redis.py index c61582abd1a..b754c1f4330 100644 --- a/litellm/_redis.py +++ b/litellm/_redis.py @@ -34,7 +34,12 @@ def _get_redis_kwargs(): "retry", } - include_args = ["url", "redis_connect_func", "gcp_service_account", "gcp_ssl_ca_certs"] + include_args = [ + "url", + "redis_connect_func", + "gcp_service_account", + "gcp_ssl_ca_certs", + ] available_args = [x for x in arg_spec.args if x not in exclude_args] + include_args @@ -75,7 +80,9 @@ def _get_redis_cluster_kwargs(client=None): available_args.append("ssl_cert_reqs") available_args.append("ssl_check_hostname") available_args.append("ssl_ca_certs") - available_args.append("redis_connect_func") # Needed for sync clusters and IAM detection + available_args.append( + "redis_connect_func" + ) # Needed for sync clusters and IAM detection available_args.append("gcp_service_account") available_args.append("gcp_ssl_ca_certs") available_args.append("max_connections") @@ -103,10 +110,10 @@ def _redis_kwargs_from_environment(): def _generate_gcp_iam_access_token(service_account: str) -> str: """ Generate GCP IAM access token for Redis authentication. - + Args: service_account: GCP service account in format 'projects/-/serviceAccounts/name@project.iam.gserviceaccount.com' - + Returns: Access token string for GCP IAM authentication """ @@ -117,11 +124,11 @@ def _generate_gcp_iam_access_token(service_account: str) -> str: "google-cloud-iam is required for GCP IAM Redis authentication. " "Install it with: pip install google-cloud-iam" ) - + client = iam_credentials_v1.IAMCredentialsClient() request = iam_credentials_v1.GenerateAccessTokenRequest( name=service_account, - scope=['https://www.googleapis.com/auth/cloud-platform'], + scope=["https://www.googleapis.com/auth/cloud-platform"], ) response = client.generate_access_token(request=request) return str(response.access_token) @@ -133,14 +140,15 @@ def create_gcp_iam_redis_connect_func( ) -> Callable: """ Creates a custom Redis connection function for GCP IAM authentication. - + Args: service_account: GCP service account in format 'projects/-/serviceAccounts/name@project.iam.gserviceaccount.com' ssl_ca_certs: Path to SSL CA certificate file for secure connections - + Returns: A connection function that can be used with Redis clients """ + def iam_connect(self): """Initialize the connection and authenticate using GCP IAM""" from redis.exceptions import ( @@ -148,25 +156,25 @@ def create_gcp_iam_redis_connect_func( AuthenticationWrongNumberOfArgsError, ) from redis.utils import str_if_bytes - + self._parser.on_connect(self) - + auth_args = (_generate_gcp_iam_access_token(service_account),) self.send_command("AUTH", *auth_args, check_health=False) - + try: auth_response = self.read_response() except AuthenticationWrongNumberOfArgsError: # Fallback to password auth if IAM fails - if hasattr(self, 'password') and self.password: + if hasattr(self, "password") and self.password: self.send_command("AUTH", self.password, check_health=False) auth_response = self.read_response() else: raise - + if str_if_bytes(auth_response) != "OK": raise AuthenticationError("GCP IAM authentication failed") - + return iam_connect @@ -178,22 +186,20 @@ def get_redis_url_from_environment(): raise ValueError( "Either 'REDIS_URL' or both 'REDIS_HOST' and 'REDIS_PORT' must be specified for Redis." ) - + if "REDIS_SSL" in os.environ and os.environ["REDIS_SSL"].lower() == "true": redis_protocol = "rediss" else: redis_protocol = "redis" - + # Build authentication part of URL auth_part = "" if "REDIS_USERNAME" in os.environ and "REDIS_PASSWORD" in os.environ: auth_part = f"{os.environ['REDIS_USERNAME']}:{os.environ['REDIS_PASSWORD']}@" elif "REDIS_PASSWORD" in os.environ: auth_part = f"{os.environ['REDIS_PASSWORD']}@" - - return ( - f"{redis_protocol}://{auth_part}{os.environ['REDIS_HOST']}:{os.environ['REDIS_PORT']}" - ) + + return f"{redis_protocol}://{auth_part}{os.environ['REDIS_HOST']}:{os.environ['REDIS_PORT']}" def _get_redis_client_logic(**env_overrides): @@ -241,22 +247,27 @@ def _get_redis_client_logic(**env_overrides): redis_kwargs["service_name"] = _service_name # Handle GCP IAM authentication - _gcp_service_account = redis_kwargs.get("gcp_service_account") or get_secret_str("REDIS_GCP_SERVICE_ACCOUNT") - _gcp_ssl_ca_certs = redis_kwargs.get("gcp_ssl_ca_certs") or get_secret_str("REDIS_GCP_SSL_CA_CERTS") - + _gcp_service_account = redis_kwargs.get("gcp_service_account") or get_secret_str( + "REDIS_GCP_SERVICE_ACCOUNT" + ) + _gcp_ssl_ca_certs = redis_kwargs.get("gcp_ssl_ca_certs") or get_secret_str( + "REDIS_GCP_SSL_CA_CERTS" + ) + if _gcp_service_account is not None: - verbose_logger.debug("Setting up GCP IAM authentication for Redis with service account.") + verbose_logger.debug( + "Setting up GCP IAM authentication for Redis with service account." + ) redis_kwargs["redis_connect_func"] = create_gcp_iam_redis_connect_func( - service_account=_gcp_service_account, - ssl_ca_certs=_gcp_ssl_ca_certs + service_account=_gcp_service_account, ssl_ca_certs=_gcp_ssl_ca_certs ) # Store GCP service account in redis_connect_func for async cluster access redis_kwargs["redis_connect_func"]._gcp_service_account = _gcp_service_account - + # Remove GCP-specific kwargs that shouldn't be passed to Redis client redis_kwargs.pop("gcp_service_account", None) redis_kwargs.pop("gcp_ssl_ca_certs", None) - + # Only enable SSL if explicitly requested AND SSL CA certs are provided if _gcp_ssl_ca_certs and redis_kwargs.get("ssl", False): redis_kwargs["ssl_ca_certs"] = _gcp_ssl_ca_certs @@ -377,7 +388,8 @@ def get_redis_client(**env_overrides): def get_redis_async_client( - connection_pool: Optional[async_redis.BlockingConnectionPool] = None, **env_overrides, + connection_pool: Optional[async_redis.BlockingConnectionPool] = None, + **env_overrides, ) -> Union[async_redis.Redis, async_redis.RedisCluster]: redis_kwargs = _get_redis_client_logic(**env_overrides) if "url" in redis_kwargs and redis_kwargs["url"] is not None: @@ -411,39 +423,50 @@ def get_redis_async_client( # Get GCP service account - first try from redis_connect_func, then from environment gcp_service_account = None - if redis_connect_func and hasattr(redis_connect_func, '_gcp_service_account'): + if redis_connect_func and hasattr(redis_connect_func, "_gcp_service_account"): gcp_service_account = redis_connect_func._gcp_service_account else: - gcp_service_account = redis_kwargs.get("gcp_service_account") or get_secret_str("REDIS_GCP_SERVICE_ACCOUNT") - - verbose_logger.debug(f"DEBUG: Redis cluster kwargs: redis_connect_func={redis_connect_func is not None}, gcp_service_account_provided={gcp_service_account is not None}") - + gcp_service_account = redis_kwargs.get( + "gcp_service_account" + ) or get_secret_str("REDIS_GCP_SERVICE_ACCOUNT") + + verbose_logger.debug( + f"DEBUG: Redis cluster kwargs: redis_connect_func={redis_connect_func is not None}, gcp_service_account_provided={gcp_service_account is not None}" + ) + # If GCP IAM is configured (indicated by redis_connect_func), generate access token and use as password if redis_connect_func and gcp_service_account: - verbose_logger.debug("DEBUG: Generating IAM token for service account (value not logged for security reasons)") + verbose_logger.debug( + "DEBUG: Generating IAM token for service account (value not logged for security reasons)" + ) try: # Generate IAM access token using the helper function access_token = _generate_gcp_iam_access_token(gcp_service_account) cluster_kwargs["password"] = access_token - verbose_logger.debug("DEBUG: Successfully generated GCP IAM access token for async Redis cluster") + verbose_logger.debug( + "DEBUG: Successfully generated GCP IAM access token for async Redis cluster" + ) except Exception as e: verbose_logger.error(f"Failed to generate GCP IAM access token: {e}") from redis.exceptions import AuthenticationError + raise AuthenticationError("Failed to generate GCP IAM access token") else: - verbose_logger.debug(f"DEBUG: Not using GCP IAM auth - redis_connect_func={redis_connect_func is not None}, gcp_service_account_provided={gcp_service_account is not None}") - + verbose_logger.debug( + f"DEBUG: Not using GCP IAM auth - redis_connect_func={redis_connect_func is not None}, gcp_service_account_provided={gcp_service_account is not None}" + ) + new_startup_nodes: List[ClusterNode] = [] for item in redis_kwargs["startup_nodes"]: new_startup_nodes.append(ClusterNode(**item)) cluster_kwargs.pop("startup_nodes", None) - + # Create async RedisCluster with IAM token as password if available cluster_client = async_redis.RedisCluster( startup_nodes=new_startup_nodes, **cluster_kwargs # type: ignore ) - + return cluster_client # Check for Redis Sentinel @@ -463,7 +486,10 @@ def get_redis_connection_pool(**env_overrides): redis_kwargs = _get_redis_client_logic(**env_overrides) verbose_logger.debug("get_redis_connection_pool: redis_kwargs", redis_kwargs) if "url" in redis_kwargs and redis_kwargs["url"] is not None: - pool_kwargs = {"timeout": REDIS_CONNECTION_POOL_TIMEOUT, "url": redis_kwargs["url"]} + pool_kwargs = { + "timeout": REDIS_CONNECTION_POOL_TIMEOUT, + "url": redis_kwargs["url"], + } if "max_connections" in redis_kwargs: try: pool_kwargs["max_connections"] = int(redis_kwargs["max_connections"]) @@ -483,6 +509,7 @@ def get_redis_connection_pool(**env_overrides): timeout=REDIS_CONNECTION_POOL_TIMEOUT, **redis_kwargs ) + def _pretty_print_redis_config(redis_kwargs: dict) -> None: """Pretty print the Redis configuration using rich with sensitive data masking""" try: @@ -492,6 +519,7 @@ def _pretty_print_redis_config(redis_kwargs: dict) -> None: from rich.panel import Panel from rich.table import Table from rich.text import Text + if not verbose_logger.isEnabledFor(logging.DEBUG): return @@ -499,7 +527,7 @@ def _pretty_print_redis_config(redis_kwargs: dict) -> None: # Initialize the sensitive data masker masker = SensitiveDataMasker() - + # Mask sensitive data in redis_kwargs masked_redis_kwargs = masker.mask_dict(redis_kwargs) @@ -531,7 +559,7 @@ def _pretty_print_redis_config(redis_kwargs: dict) -> None: value_str = str(value) else: value_str = str(value) - + config_table.add_row(key, value_str) # Determine connection type @@ -568,4 +596,3 @@ def _pretty_print_redis_config(redis_kwargs: dict) -> None: verbose_logger.info(f"Redis configuration: {masked_redis_kwargs}") except Exception as e: verbose_logger.error(f"Error pretty printing Redis configuration: {e}") - diff --git a/litellm/_service_logger.py b/litellm/_service_logger.py index 8f9a3c5083f..1a3be203fec 100644 --- a/litellm/_service_logger.py +++ b/litellm/_service_logger.py @@ -317,7 +317,7 @@ class ServiceLogging(CustomLogger): await self.async_service_success_hook( service=ServiceTypes.LITELLM, duration=_duration, - call_type=kwargs.get("call_type", "unknown") + call_type=kwargs.get("call_type", "unknown"), ) except Exception as e: raise e diff --git a/litellm/a2a_protocol/client.py b/litellm/a2a_protocol/client.py index 31f7c3b6a90..05e21284af1 100644 --- a/litellm/a2a_protocol/client.py +++ b/litellm/a2a_protocol/client.py @@ -103,5 +103,7 @@ class A2AClient: from litellm.a2a_protocol.main import asend_message_streaming a2a_client = await self._get_client() - async for chunk in asend_message_streaming(a2a_client=a2a_client, request=request): + async for chunk in asend_message_streaming( + a2a_client=a2a_client, request=request + ): yield chunk diff --git a/litellm/a2a_protocol/cost_calculator.py b/litellm/a2a_protocol/cost_calculator.py index f3e84c5b84d..f64174f8be5 100644 --- a/litellm/a2a_protocol/cost_calculator.py +++ b/litellm/a2a_protocol/cost_calculator.py @@ -97,7 +97,11 @@ class A2ACostCalculator: completion_tokens = getattr(usage, "completion_tokens", 0) or 0 # Calculate costs - input_cost = prompt_tokens * (float(input_cost_per_token) if input_cost_per_token else 0.0) - output_cost = completion_tokens * (float(output_cost_per_token) if output_cost_per_token else 0.0) + input_cost = prompt_tokens * ( + float(input_cost_per_token) if input_cost_per_token else 0.0 + ) + output_cost = completion_tokens * ( + float(output_cost_per_token) if output_cost_per_token else 0.0 + ) return input_cost + output_cost diff --git a/litellm/a2a_protocol/litellm_completion_bridge/handler.py b/litellm/a2a_protocol/litellm_completion_bridge/handler.py index 1916b04454a..c3d2e415237 100644 --- a/litellm/a2a_protocol/litellm_completion_bridge/handler.py +++ b/litellm/a2a_protocol/litellm_completion_bridge/handler.py @@ -50,30 +50,28 @@ class A2ACompletionBridgeHandler: a2a_provider_config = A2AProviderConfigManager.get_provider_config( custom_llm_provider=custom_llm_provider ) - + # If provider config exists, use it if a2a_provider_config is not None: if api_base is None: raise ValueError(f"api_base is required for {custom_llm_provider}") - - verbose_logger.info( - f"A2A: Using provider config for {custom_llm_provider}" - ) - + + verbose_logger.info(f"A2A: Using provider config for {custom_llm_provider}") + response_data = await a2a_provider_config.handle_non_streaming( request_id=request_id, params=params, api_base=api_base, ) - + return response_data - + # Extract message from params message = params.get("message", {}) # Transform A2A message to OpenAI format - openai_messages = A2ACompletionBridgeTransformation.a2a_message_to_openai_messages( - message + openai_messages = ( + A2ACompletionBridgeTransformation.a2a_message_to_openai_messages(message) ) # Get completion params @@ -100,7 +98,8 @@ class A2ACompletionBridgeHandler: } # Add litellm_params (contains api_key, client_id, client_secret, tenant_id, etc.) litellm_params_to_add = { - k: v for k, v in litellm_params.items() + k: v + for k, v in litellm_params.items() if k not in ("model", "custom_llm_provider") } completion_params.update(litellm_params_to_add) @@ -109,9 +108,11 @@ class A2ACompletionBridgeHandler: response = await litellm.acompletion(**completion_params) # Transform response to A2A format - a2a_response = A2ACompletionBridgeTransformation.openai_response_to_a2a_response( - response=response, - request_id=request_id, + a2a_response = ( + A2ACompletionBridgeTransformation.openai_response_to_a2a_response( + response=response, + request_id=request_id, + ) ) verbose_logger.info(f"A2A completion bridge completed: request_id={request_id}") @@ -148,25 +149,25 @@ class A2ACompletionBridgeHandler: a2a_provider_config = A2AProviderConfigManager.get_provider_config( custom_llm_provider=custom_llm_provider ) - + # If provider config exists, use it if a2a_provider_config is not None: if api_base is None: raise ValueError(f"api_base is required for {custom_llm_provider}") - + verbose_logger.info( f"A2A: Using provider config for {custom_llm_provider} (streaming)" ) - + async for chunk in a2a_provider_config.handle_streaming( request_id=request_id, params=params, api_base=api_base, ): yield chunk - + return - + # Extract message from params message = params.get("message", {}) @@ -177,8 +178,8 @@ class A2ACompletionBridgeHandler: ) # Transform A2A message to OpenAI format - openai_messages = A2ACompletionBridgeTransformation.a2a_message_to_openai_messages( - message + openai_messages = ( + A2ACompletionBridgeTransformation.a2a_message_to_openai_messages(message) ) # Get completion params @@ -205,7 +206,8 @@ class A2ACompletionBridgeHandler: } # Add litellm_params (contains api_key, client_id, client_secret, tenant_id, etc.) litellm_params_to_add = { - k: v for k, v in litellm_params.items() + k: v + for k, v in litellm_params.items() if k not in ("model", "custom_llm_provider") } completion_params.update(litellm_params_to_add) @@ -244,9 +246,11 @@ class A2ACompletionBridgeHandler: # Emit artifact update with accumulated content if accumulated_text: - artifact_event = A2ACompletionBridgeTransformation.create_artifact_update_event( - ctx=ctx, - text=accumulated_text, + artifact_event = ( + A2ACompletionBridgeTransformation.create_artifact_update_event( + ctx=ctx, + text=accumulated_text, + ) ) yield artifact_event diff --git a/litellm/a2a_protocol/litellm_completion_bridge/transformation.py b/litellm/a2a_protocol/litellm_completion_bridge/transformation.py index bbe7daa9fc4..8a03569f689 100644 --- a/litellm/a2a_protocol/litellm_completion_bridge/transformation.py +++ b/litellm/a2a_protocol/litellm_completion_bridge/transformation.py @@ -124,9 +124,7 @@ class A2ACompletionBridgeTransformation: }, } - verbose_logger.debug( - f"OpenAI -> A2A transform: content_length={len(content)}" - ) + verbose_logger.debug(f"OpenAI -> A2A transform: content_length={len(content)}") return a2a_response diff --git a/litellm/a2a_protocol/main.py b/litellm/a2a_protocol/main.py index 8cf477ee5e1..c86549da77a 100644 --- a/litellm/a2a_protocol/main.py +++ b/litellm/a2a_protocol/main.py @@ -120,9 +120,9 @@ def _get_a2a_model_info(a2a_client: Any, kwargs: Dict[str, Any]) -> str: litellm_logging_obj.model = model litellm_logging_obj.custom_llm_provider = custom_llm_provider litellm_logging_obj.model_call_details["model"] = model - litellm_logging_obj.model_call_details["custom_llm_provider"] = ( - custom_llm_provider - ) + litellm_logging_obj.model_call_details[ + "custom_llm_provider" + ] = custom_llm_provider return agent_name @@ -664,9 +664,7 @@ async def create_a2a_client( if extra_headers: # Encode headers into a cache-key-only param so each unique header # set produces a distinct cache key. - _client_params["disable_aiohttp_transport"] = str( - sorted(extra_headers.items()) - ) + _client_params["disable_aiohttp_transport"] = str(sorted(extra_headers.items())) _async_handler = get_async_httpx_client( llm_provider=httpxSpecialProvider.A2AProvider, params=_client_params, diff --git a/litellm/a2a_protocol/providers/__init__.py b/litellm/a2a_protocol/providers/__init__.py index 873a5a83749..a21fa5f8f5e 100644 --- a/litellm/a2a_protocol/providers/__init__.py +++ b/litellm/a2a_protocol/providers/__init__.py @@ -8,4 +8,3 @@ from litellm.a2a_protocol.providers.base import BaseA2AProviderConfig from litellm.a2a_protocol.providers.config_manager import A2AProviderConfigManager __all__ = ["BaseA2AProviderConfig", "A2AProviderConfigManager"] - diff --git a/litellm/a2a_protocol/providers/base.py b/litellm/a2a_protocol/providers/base.py index 9931076a948..a2354b3495e 100644 --- a/litellm/a2a_protocol/providers/base.py +++ b/litellm/a2a_protocol/providers/base.py @@ -9,7 +9,7 @@ from typing import Any, AsyncIterator, Dict class BaseA2AProviderConfig(ABC): """ Base configuration class for A2A protocol providers. - + Each provider should implement this interface to define how to handle A2A requests for their specific agent type. """ @@ -60,4 +60,3 @@ class BaseA2AProviderConfig(ABC): # The yield is here to make this a generator function if False: # pragma: no cover yield {} - diff --git a/litellm/a2a_protocol/providers/config_manager.py b/litellm/a2a_protocol/providers/config_manager.py index e0703ec466b..a8b9566c171 100644 --- a/litellm/a2a_protocol/providers/config_manager.py +++ b/litellm/a2a_protocol/providers/config_manager.py @@ -12,7 +12,7 @@ from litellm.a2a_protocol.providers.base import BaseA2AProviderConfig class A2AProviderConfigManager: """ Manager for A2A provider configurations. - + Similar to ProviderConfigManager in litellm.utils but specifically for A2A providers. """ @@ -31,7 +31,7 @@ class A2AProviderConfigManager: """ if custom_llm_provider is None: return None - + if custom_llm_provider == "pydantic_ai_agents": from litellm.a2a_protocol.providers.pydantic_ai_agents.config import ( PydanticAIProviderConfig, @@ -45,4 +45,3 @@ class A2AProviderConfigManager: # return AnotherProviderConfig() return None - diff --git a/litellm/a2a_protocol/providers/litellm_completion/__init__.py b/litellm/a2a_protocol/providers/litellm_completion/__init__.py index 3f2b88bfaa3..fc2fc17f54f 100644 --- a/litellm/a2a_protocol/providers/litellm_completion/__init__.py +++ b/litellm/a2a_protocol/providers/litellm_completion/__init__.py @@ -3,4 +3,3 @@ LiteLLM Completion bridge provider for A2A protocol. Routes A2A requests through litellm.acompletion based on custom_llm_provider. """ - diff --git a/litellm/a2a_protocol/providers/litellm_completion/handler.py b/litellm/a2a_protocol/providers/litellm_completion/handler.py index 57388a5d0ed..730f8f6b36f 100644 --- a/litellm/a2a_protocol/providers/litellm_completion/handler.py +++ b/litellm/a2a_protocol/providers/litellm_completion/handler.py @@ -52,26 +52,26 @@ class A2ACompletionBridgeHandler: if custom_llm_provider == "pydantic_ai_agents": if api_base is None: raise ValueError("api_base is required for Pydantic AI agents") - + verbose_logger.info( f"Pydantic AI: Routing to Pydantic AI agent at {api_base}" ) - + # Send request directly to Pydantic AI agent response_data = await PydanticAITransformation.send_non_streaming_request( api_base=api_base, request_id=request_id, params=params, ) - + return response_data - + # Extract message from params message = params.get("message", {}) # Transform A2A message to OpenAI format - openai_messages = A2ACompletionBridgeTransformation.a2a_message_to_openai_messages( - message + openai_messages = ( + A2ACompletionBridgeTransformation.a2a_message_to_openai_messages(message) ) # Get completion params @@ -98,7 +98,8 @@ class A2ACompletionBridgeHandler: } # Add litellm_params (contains api_key, client_id, client_secret, tenant_id, etc.) litellm_params_to_add = { - k: v for k, v in litellm_params.items() + k: v + for k, v in litellm_params.items() if k not in ("model", "custom_llm_provider") } completion_params.update(litellm_params_to_add) @@ -107,9 +108,11 @@ class A2ACompletionBridgeHandler: response = await litellm.acompletion(**completion_params) # Transform response to A2A format - a2a_response = A2ACompletionBridgeTransformation.openai_response_to_a2a_response( - response=response, - request_id=request_id, + a2a_response = ( + A2ACompletionBridgeTransformation.openai_response_to_a2a_response( + response=response, + request_id=request_id, + ) ) verbose_logger.info(f"A2A completion bridge completed: request_id={request_id}") @@ -146,27 +149,27 @@ class A2ACompletionBridgeHandler: if custom_llm_provider == "pydantic_ai_agents": if api_base is None: raise ValueError("api_base is required for Pydantic AI agents") - + verbose_logger.info( f"Pydantic AI: Faking streaming for Pydantic AI agent at {api_base}" ) - + # Get non-streaming response first response_data = await PydanticAITransformation.send_non_streaming_request( api_base=api_base, request_id=request_id, params=params, ) - + # Convert to fake streaming async for chunk in PydanticAITransformation.fake_streaming_from_response( response_data=response_data, request_id=request_id, ): yield chunk - + return - + # Extract message from params message = params.get("message", {}) @@ -177,8 +180,8 @@ class A2ACompletionBridgeHandler: ) # Transform A2A message to OpenAI format - openai_messages = A2ACompletionBridgeTransformation.a2a_message_to_openai_messages( - message + openai_messages = ( + A2ACompletionBridgeTransformation.a2a_message_to_openai_messages(message) ) # Get completion params @@ -205,7 +208,8 @@ class A2ACompletionBridgeHandler: } # Add litellm_params (contains api_key, client_id, client_secret, tenant_id, etc.) litellm_params_to_add = { - k: v for k, v in litellm_params.items() + k: v + for k, v in litellm_params.items() if k not in ("model", "custom_llm_provider") } completion_params.update(litellm_params_to_add) @@ -244,9 +248,11 @@ class A2ACompletionBridgeHandler: # Emit artifact update with accumulated content if accumulated_text: - artifact_event = A2ACompletionBridgeTransformation.create_artifact_update_event( - ctx=ctx, - text=accumulated_text, + artifact_event = ( + A2ACompletionBridgeTransformation.create_artifact_update_event( + ctx=ctx, + text=accumulated_text, + ) ) yield artifact_event diff --git a/litellm/a2a_protocol/providers/litellm_completion/transformation.py b/litellm/a2a_protocol/providers/litellm_completion/transformation.py index bbe7daa9fc4..8a03569f689 100644 --- a/litellm/a2a_protocol/providers/litellm_completion/transformation.py +++ b/litellm/a2a_protocol/providers/litellm_completion/transformation.py @@ -124,9 +124,7 @@ class A2ACompletionBridgeTransformation: }, } - verbose_logger.debug( - f"OpenAI -> A2A transform: content_length={len(content)}" - ) + verbose_logger.debug(f"OpenAI -> A2A transform: content_length={len(content)}") return a2a_response diff --git a/litellm/a2a_protocol/providers/pydantic_ai_agents/__init__.py b/litellm/a2a_protocol/providers/pydantic_ai_agents/__init__.py index 2187400b2d1..8e9cd6fc87e 100644 --- a/litellm/a2a_protocol/providers/pydantic_ai_agents/__init__.py +++ b/litellm/a2a_protocol/providers/pydantic_ai_agents/__init__.py @@ -14,4 +14,3 @@ from litellm.a2a_protocol.providers.pydantic_ai_agents.transformation import ( ) __all__ = ["PydanticAIHandler", "PydanticAITransformation", "PydanticAIProviderConfig"] - diff --git a/litellm/a2a_protocol/providers/pydantic_ai_agents/config.py b/litellm/a2a_protocol/providers/pydantic_ai_agents/config.py index acf09554e5e..d4c5f6a2985 100644 --- a/litellm/a2a_protocol/providers/pydantic_ai_agents/config.py +++ b/litellm/a2a_protocol/providers/pydantic_ai_agents/config.py @@ -11,7 +11,7 @@ from litellm.a2a_protocol.providers.pydantic_ai_agents.handler import PydanticAI class PydanticAIProviderConfig(BaseA2AProviderConfig): """ Provider configuration for Pydantic AI agents. - + Pydantic AI agents follow A2A protocol but don't support streaming natively. This config provides fake streaming by converting non-streaming responses into streaming chunks. """ @@ -48,4 +48,3 @@ class PydanticAIProviderConfig(BaseA2AProviderConfig): delay_ms=kwargs.get("delay_ms", 10), ): yield chunk - diff --git a/litellm/a2a_protocol/providers/pydantic_ai_agents/handler.py b/litellm/a2a_protocol/providers/pydantic_ai_agents/handler.py index 6680a9fe487..7d4167752f8 100644 --- a/litellm/a2a_protocol/providers/pydantic_ai_agents/handler.py +++ b/litellm/a2a_protocol/providers/pydantic_ai_agents/handler.py @@ -16,7 +16,7 @@ from litellm.a2a_protocol.providers.pydantic_ai_agents.transformation import ( class PydanticAIHandler: """ Handler for Pydantic AI agent requests. - + Provides: - Direct non-streaming requests to Pydantic AI agents - Fake streaming by converting non-streaming responses into streaming chunks @@ -41,9 +41,7 @@ class PydanticAIHandler: Returns: A2A SendMessageResponse dict """ - verbose_logger.info( - f"Pydantic AI: Routing to Pydantic AI agent at {api_base}" - ) + verbose_logger.info(f"Pydantic AI: Routing to Pydantic AI agent at {api_base}") # Send request directly to Pydantic AI agent response_data = await PydanticAITransformation.send_non_streaming_request( @@ -102,5 +100,3 @@ class PydanticAIHandler: delay_ms=delay_ms, ): yield chunk - - diff --git a/litellm/a2a_protocol/providers/pydantic_ai_agents/transformation.py b/litellm/a2a_protocol/providers/pydantic_ai_agents/transformation.py index 9352eab6c8e..e73b17ac3c0 100644 --- a/litellm/a2a_protocol/providers/pydantic_ai_agents/transformation.py +++ b/litellm/a2a_protocol/providers/pydantic_ai_agents/transformation.py @@ -10,13 +10,16 @@ from typing import Any, AsyncIterator, Dict, cast from uuid import uuid4 from litellm._logging import verbose_logger -from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, get_async_httpx_client +from litellm.llms.custom_httpx.http_handler import ( + AsyncHTTPHandler, + get_async_httpx_client, +) class PydanticAITransformation: """ Transformation layer for Pydantic AI agents. - + Handles: - Direct A2A requests to Pydantic AI endpoints - Polling for task completion (since Pydantic AI doesn't support streaming) @@ -27,13 +30,13 @@ class PydanticAITransformation: def _remove_none_values(obj: Any) -> Any: """ Recursively remove None values from a dict/list structure. - + FastA2A/Pydantic AI servers don't accept None values for optional fields - they expect those fields to be omitted entirely. - + Args: obj: Dict, list, or other value to clean - + Returns: Cleaned object with None values removed """ @@ -56,10 +59,10 @@ class PydanticAITransformation: def _params_to_dict(params: Any) -> Dict[str, Any]: """ Convert params to a dict, handling Pydantic models. - + Args: params: Dict or Pydantic model - + Returns: Dict representation of params """ @@ -86,7 +89,7 @@ class PydanticAITransformation: ) -> Dict[str, Any]: """ Poll for task completion using tasks/get method. - + Args: client: HTTPX async client endpoint: API endpoint URL @@ -94,7 +97,7 @@ class PydanticAITransformation: request_id: JSON-RPC request ID max_attempts: Maximum polling attempts poll_interval: Seconds between poll attempts - + Returns: Completed task response """ @@ -105,7 +108,7 @@ class PydanticAITransformation: "method": "tasks/get", "params": {"id": task_id}, } - + response = await client.post( endpoint, json=poll_request, @@ -113,23 +116,25 @@ class PydanticAITransformation: ) response.raise_for_status() poll_data = response.json() - + result = poll_data.get("result", {}) status = result.get("status", {}) state = status.get("state", "") - + verbose_logger.debug( f"Pydantic AI: Poll attempt {attempt + 1}/{max_attempts}, state={state}" ) - + if state == "completed": return poll_data elif state in ("failed", "canceled"): raise Exception(f"Task {task_id} ended with state: {state}") - + await asyncio.sleep(poll_interval) - - raise TimeoutError(f"Task {task_id} did not complete within {max_attempts * poll_interval} seconds") + + raise TimeoutError( + f"Task {task_id} did not complete within {max_attempts * poll_interval} seconds" + ) @staticmethod async def _send_and_poll_raw( @@ -140,7 +145,7 @@ class PydanticAITransformation: ) -> Dict[str, Any]: """ Send a request to Pydantic AI agent and return the raw task response. - + This is an internal method used by both non-streaming and streaming handlers. Returns the raw Pydantic AI task format with history/artifacts. @@ -155,10 +160,10 @@ class PydanticAITransformation: """ # Convert params to dict if it's a Pydantic model params_dict = PydanticAITransformation._params_to_dict(params) - + # Remove None values - FastA2A doesn't accept null for optional fields params_dict = PydanticAITransformation._remove_none_values(params_dict) - + # Ensure the message has 'kind': 'message' as required by FastA2A/Pydantic AI if "message" in params_dict: params_dict["message"]["kind"] = "message" @@ -174,9 +179,7 @@ class PydanticAITransformation: # FastA2A uses root endpoint (/) not /messages endpoint = api_base.rstrip("/") - verbose_logger.info( - f"Pydantic AI: Sending non-streaming request to {endpoint}" - ) + verbose_logger.info(f"Pydantic AI: Sending non-streaming request to {endpoint}") # Send request to Pydantic AI agent using shared async HTTP client client = get_async_httpx_client( @@ -190,12 +193,12 @@ class PydanticAITransformation: ) response.raise_for_status() response_data = response.json() - + # Check if task is already completed result = response_data.get("result", {}) status = result.get("status", {}) state = status.get("state", "") - + if state != "completed": # Need to poll for completion task_id = result.get("id") @@ -210,7 +213,9 @@ class PydanticAITransformation: request_id=request_id, ) - verbose_logger.info(f"Pydantic AI: Received completed response for request_id={request_id}") + verbose_logger.info( + f"Pydantic AI: Received completed response for request_id={request_id}" + ) return response_data @@ -256,7 +261,7 @@ class PydanticAITransformation: ) -> Dict[str, Any]: """ Send a request to Pydantic AI agent and return the raw task response. - + Used by streaming handler to get raw response for fake streaming. Args: @@ -282,7 +287,7 @@ class PydanticAITransformation: ) -> Dict[str, Any]: """ Transform Pydantic AI task response to standard A2A non-streaming format. - + Pydantic AI returns a task with history/artifacts, but the standard A2A non-streaming format expects: { @@ -296,11 +301,11 @@ class PydanticAITransformation: } } } - + Args: response_data: Pydantic AI task response request_id: Original request ID - + Returns: Standard A2A non-streaming response format """ @@ -308,14 +313,14 @@ class PydanticAITransformation: full_text, message_id, parts = PydanticAITransformation._extract_response_text( response_data ) - + # Build standard A2A message a2a_message = { "role": "agent", "parts": parts if parts else [{"kind": "text", "text": full_text}], "messageId": message_id, } - + # Return standard A2A non-streaming format return { "jsonrpc": "2.0", @@ -329,19 +334,19 @@ class PydanticAITransformation: def _extract_response_text(response_data: Dict[str, Any]) -> tuple[str, str, list]: """ Extract response text from completed task response. - + Pydantic AI returns completed tasks with: - history: list of messages (user and agent) - artifacts: list of result artifacts - + Args: response_data: Completed task response - + Returns: Tuple of (full_text, message_id, parts) """ result = response_data.get("result", {}) - + # Try to extract from artifacts first (preferred for results) artifacts = result.get("artifacts", []) if artifacts: @@ -352,7 +357,7 @@ class PydanticAITransformation: text = part.get("text", "") if text: return text, str(uuid4()), parts - + # Fall back to history - get the last agent message history = result.get("history", []) for msg in reversed(history): @@ -365,7 +370,7 @@ class PydanticAITransformation: full_text += part.get("text", "") if full_text: return full_text, message_id, parts - + # Fall back to message field (original format) message = result.get("message", {}) if message: @@ -376,7 +381,7 @@ class PydanticAITransformation: if part.get("kind") == "text": full_text += part.get("text", "") return full_text, message_id, parts - + return "", str(uuid4()), [] @staticmethod @@ -408,7 +413,7 @@ class PydanticAITransformation: full_text, message_id, parts = PydanticAITransformation._extract_response_text( response_data ) - + # Extract input message from raw response for history result = response_data.get("result", {}) history = result.get("history", []) @@ -436,7 +441,9 @@ class PydanticAITransformation: "contextId": context_id, "kind": "message", "messageId": input_message_id, - "parts": input_message.get("parts", [{"kind": "text", "text": ""}]), + "parts": input_message.get( + "parts", [{"kind": "text", "text": ""}] + ), "role": "user", "taskId": task_id, } @@ -475,7 +482,7 @@ class PydanticAITransformation: if full_text: # Split text into chunks for i in range(0, len(full_text), chunk_size): - chunk_text = full_text[i:i + chunk_size] + chunk_text = full_text[i : i + chunk_size] is_last_chunk = (i + chunk_size) >= len(full_text) artifact_event = { @@ -521,5 +528,3 @@ class PydanticAITransformation: verbose_logger.info( f"Pydantic AI: Fake streaming completed for request_id={request_id}" ) - - diff --git a/litellm/a2a_protocol/streaming_iterator.py b/litellm/a2a_protocol/streaming_iterator.py index 921dc0e52e0..98d45cf2ac1 100644 --- a/litellm/a2a_protocol/streaming_iterator.py +++ b/litellm/a2a_protocol/streaming_iterator.py @@ -71,7 +71,11 @@ class A2AStreamingIterator: def _collect_text_from_chunk(self, chunk: Any) -> None: """Extract text from a streaming chunk and add to collected parts.""" try: - chunk_dict = chunk.model_dump(mode="json", exclude_none=True) if hasattr(chunk, "model_dump") else {} + chunk_dict = ( + chunk.model_dump(mode="json", exclude_none=True) + if hasattr(chunk, "model_dump") + else {} + ) text = A2ARequestUtils.extract_text_from_response(chunk_dict) if text: self.collected_text_parts.append(text) @@ -81,7 +85,11 @@ class A2AStreamingIterator: def _is_completed_chunk(self, chunk: Any) -> bool: """Check if chunk indicates stream completion.""" try: - chunk_dict = chunk.model_dump(mode="json", exclude_none=True) if hasattr(chunk, "model_dump") else {} + chunk_dict = ( + chunk.model_dump(mode="json", exclude_none=True) + if hasattr(chunk, "model_dump") + else {} + ) result = chunk_dict.get("result", {}) if isinstance(result, dict): status = result.get("status", {}) @@ -102,7 +110,9 @@ class A2AStreamingIterator: prompt_tokens = A2ARequestUtils.count_tokens(input_text) # Use the last (most complete) text from chunks - output_text = self.collected_text_parts[-1] if self.collected_text_parts else "" + output_text = ( + self.collected_text_parts[-1] if self.collected_text_parts else "" + ) completion_tokens = A2ARequestUtils.count_tokens(output_text) total_tokens = prompt_tokens + completion_tokens @@ -158,7 +168,9 @@ class A2AStreamingIterator: result: Dict[str, Any] = { "id": getattr(self.request, "id", "unknown"), "jsonrpc": "2.0", - "usage": usage.model_dump() if hasattr(usage, "model_dump") else dict(usage), + "usage": usage.model_dump() + if hasattr(usage, "model_dump") + else dict(usage), } # Add final chunk result if available @@ -170,4 +182,3 @@ class A2AStreamingIterator: pass return result - diff --git a/litellm/anthropic_beta_headers_manager.py b/litellm/anthropic_beta_headers_manager.py index 24df6296b91..efa57ca0586 100644 --- a/litellm/anthropic_beta_headers_manager.py +++ b/litellm/anthropic_beta_headers_manager.py @@ -38,7 +38,7 @@ _BETA_HEADERS_CONFIG: Optional[Dict] = None class GetAnthropicBetaHeadersConfig: """ Handles fetching, validating, and loading the Anthropic beta headers configuration. - + Similar to GetModelCostMap, this class manages the lifecycle of the beta headers configuration with support for remote fetching and local fallback. """ @@ -62,7 +62,7 @@ class GetAnthropicBetaHeadersConfig: "bedrock": {}, "bedrock_converse": {}, "vertex_ai": {}, - "provider_aliases": {} + "provider_aliases": {}, } @staticmethod @@ -84,9 +84,15 @@ class GetAnthropicBetaHeadersConfig: return False # Check for at least one provider key - provider_keys = ["anthropic", "azure_ai", "bedrock", "bedrock_converse", "vertex_ai"] + provider_keys = [ + "anthropic", + "azure_ai", + "bedrock", + "bedrock_converse", + "vertex_ai", + ] has_provider = any(key in fetched_config for key in provider_keys) - + if not has_provider: verbose_logger.warning( "LiteLLM: Fetched beta headers config missing provider keys. " @@ -100,7 +106,7 @@ class GetAnthropicBetaHeadersConfig: def validate_beta_headers_config(cls, fetched_config: dict) -> bool: """ Validate the integrity of a fetched beta headers config. - + Returns True if all checks pass, False otherwise. """ return cls._check_is_valid_dict(fetched_config) @@ -109,7 +115,7 @@ class GetAnthropicBetaHeadersConfig: def fetch_remote_beta_headers_config(url: str, timeout: int = 5) -> dict: """ Fetch the beta headers config from a remote URL. - + Returns the parsed JSON dict. Raises on network/parse errors (caller is expected to handle). """ @@ -121,14 +127,14 @@ class GetAnthropicBetaHeadersConfig: def get_beta_headers_config(url: str) -> dict: """ Public entry point — returns the beta headers config dict. - + 1. If ``LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS`` is set, uses the local backup only. 2. Otherwise fetches from ``url``, validates integrity, and falls back to the local backup on any failure. - + Args: url: URL to fetch the remote beta headers configuration from - + Returns: Dict containing the beta headers configuration """ @@ -149,7 +155,9 @@ def get_beta_headers_config(url: str) -> dict: return GetAnthropicBetaHeadersConfig.load_local_beta_headers_config() # Validate the fetched config - if not GetAnthropicBetaHeadersConfig.validate_beta_headers_config(fetched_config=content): + if not GetAnthropicBetaHeadersConfig.validate_beta_headers_config( + fetched_config=content + ): verbose_logger.warning( "LiteLLM: Fetched beta headers config failed integrity check. " "Using local backup instead. url=%s", @@ -164,23 +172,23 @@ def _load_beta_headers_config() -> Dict: """ Load the beta headers configuration. Uses caching to avoid repeated fetches/file reads. - + This function is called by all public API functions and manages the global cache. - + Returns: Dict containing the beta headers configuration """ global _BETA_HEADERS_CONFIG - + if _BETA_HEADERS_CONFIG is not None: return _BETA_HEADERS_CONFIG - + # Get the URL from environment or use default from litellm import anthropic_beta_headers_url - + _BETA_HEADERS_CONFIG = get_beta_headers_config(url=anthropic_beta_headers_url) verbose_logger.debug("Loaded and cached beta headers config") - + return _BETA_HEADERS_CONFIG @@ -188,7 +196,7 @@ def reload_beta_headers_config() -> Dict: """ Force reload the beta headers configuration from source (remote or local). Clears the cache and fetches fresh configuration. - + Returns: Dict containing the newly loaded beta headers configuration """ @@ -201,10 +209,10 @@ def reload_beta_headers_config() -> Dict: 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 """ @@ -219,53 +227,53 @@ def filter_and_transform_beta_headers( ) -> List[str]: """ Filter and transform beta headers based on provider's mapping configuration. - + This function: 1. Only allows headers that are present in the provider's mapping keys 2. Filters out headers with null values (unsupported) 3. Maps headers to provider-specific names (e.g., advanced-tool-use -> tool-search-tool) - + Args: beta_headers: List of Anthropic beta header values provider: Provider name (e.g., "anthropic", "bedrock", "vertex_ai") - + Returns: List of filtered and transformed beta headers for the provider """ if not beta_headers: return [] - + config = _load_beta_headers_config() provider = get_provider_name(provider) - + # Get the header mapping for this provider provider_mapping = config.get(provider, {}) - + filtered_headers: Set[str] = set() - + for header in beta_headers: header = header.strip() - + # Check if header is in the mapping if header not in provider_mapping: verbose_logger.debug( f"Dropping unknown beta header '{header}' for provider '{provider}' (not in mapping)" ) continue - + # Get the mapped header value mapped_header = provider_mapping[header] - + # Skip if header is unsupported (null value) if mapped_header is None: verbose_logger.debug( f"Dropping unsupported beta header '{header}' for provider '{provider}'" ) continue - + # Add the mapped header filtered_headers.add(mapped_header) - + return sorted(list(filtered_headers)) @@ -275,18 +283,18 @@ def is_beta_header_supported( ) -> 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 in the mapping with a non-null value, False otherwise """ config = _load_beta_headers_config() provider = get_provider_name(provider) provider_mapping = config.get(provider, {}) - + # Header is supported if it's in the mapping and has a non-null value return beta_header in provider_mapping and provider_mapping[beta_header] is not None @@ -297,26 +305,26 @@ def get_provider_beta_header( ) -> Optional[str]: """ Get the provider-specific beta header name for a given Anthropic beta header. - + This function handles header transformations/mappings (e.g., advanced-tool-use -> tool-search-tool). - + Args: anthropic_beta_header: The Anthropic beta header value provider: Provider name - + Returns: The provider-specific header name if supported, or None if unsupported/unknown """ config = _load_beta_headers_config() provider = get_provider_name(provider) - + # Get the header mapping for this provider provider_mapping = config.get(provider, {}) - + # Check if header is in the mapping if anthropic_beta_header not in provider_mapping: return None - + # Return the mapped value (could be None if unsupported) return provider_mapping[anthropic_beta_header] @@ -328,50 +336,50 @@ def update_headers_with_filtered_beta( """ 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 (have null values in mapping). - + Args: provider: Provider name - + Returns: List of unsupported Anthropic beta header names """ config = _load_beta_headers_config() provider = get_provider_name(provider) provider_mapping = config.get(provider, {}) - + # Return headers with null values return [header for header, value in provider_mapping.items() if value is None] diff --git a/litellm/anthropic_interface/exceptions/exception_mapping_utils.py b/litellm/anthropic_interface/exceptions/exception_mapping_utils.py index b8a5079a4eb..28020e763f4 100644 --- a/litellm/anthropic_interface/exceptions/exception_mapping_utils.py +++ b/litellm/anthropic_interface/exceptions/exception_mapping_utils.py @@ -149,7 +149,9 @@ class AnthropicExceptionMapping: parsed = None # If parsed and already in Anthropic format - passthrough - if parsed is not None and AnthropicExceptionMapping._is_anthropic_error_dict(parsed): + if parsed is not None and AnthropicExceptionMapping._is_anthropic_error_dict( + parsed + ): # Optionally add request_id if provided and not present if request_id and "request_id" not in parsed: parsed["request_id"] = request_id @@ -157,7 +159,9 @@ class AnthropicExceptionMapping: # Extract message - use parsed dict if available, otherwise raw string if parsed is not None: - message = AnthropicExceptionMapping._extract_message_from_dict(parsed, raw_message) + message = AnthropicExceptionMapping._extract_message_from_dict( + parsed, raw_message + ) else: message = raw_message diff --git a/litellm/batches/batch_utils.py b/litellm/batches/batch_utils.py index c752e84b967..4b965d4e635 100644 --- a/litellm/batches/batch_utils.py +++ b/litellm/batches/batch_utils.py @@ -10,7 +10,9 @@ from litellm.utils import token_counter async def calculate_batch_cost_and_usage( file_content_dictionary: List[dict], - custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic"], + custom_llm_provider: Literal[ + "openai", "azure", "vertex_ai", "hosted_vllm", "anthropic" + ], model_name: Optional[str] = None, model_info: Optional[ModelInfo] = None, ) -> Tuple[float, Usage, List[str]]: @@ -34,19 +36,23 @@ async def calculate_batch_cost_and_usage( custom_llm_provider=custom_llm_provider, model_name=model_name, ) - batch_models = _get_batch_models_from_file_content(file_content_dictionary, model_name) + batch_models = _get_batch_models_from_file_content( + file_content_dictionary, model_name + ) return batch_cost, batch_usage, batch_models async def _handle_completed_batch( batch: Batch, - custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic"], + custom_llm_provider: Literal[ + "openai", "azure", "vertex_ai", "hosted_vllm", "anthropic" + ], model_name: Optional[str] = None, litellm_params: Optional[dict] = None, ) -> Tuple[float, Usage, List[str]]: """Helper function to process a completed batch and handle logging - + Args: batch: The batch object custom_llm_provider: The LLM provider @@ -70,7 +76,9 @@ async def _handle_completed_batch( model_name=model_name, ) - batch_models = _get_batch_models_from_file_content(file_content_dictionary, model_name) + batch_models = _get_batch_models_from_file_content( + file_content_dictionary, model_name + ) return batch_cost, batch_usage, batch_models @@ -96,7 +104,9 @@ def _get_batch_models_from_file_content( def _batch_cost_calculator( file_content_dictionary: List[dict], - custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic"] = "openai", + custom_llm_provider: Literal[ + "openai", "azure", "vertex_ai", "hosted_vllm", "anthropic" + ] = "openai", model_name: Optional[str] = None, model_info: Optional[ModelInfo] = None, ) -> float: @@ -105,10 +115,12 @@ def _batch_cost_calculator( """ # Handle Vertex AI with specialized method if custom_llm_provider == "vertex_ai" and model_name: - batch_cost, _ = calculate_vertex_ai_batch_cost_and_usage(file_content_dictionary, model_name) + batch_cost, _ = calculate_vertex_ai_batch_cost_and_usage( + file_content_dictionary, model_name + ) verbose_logger.debug("vertex_ai_total_cost=%s", batch_cost) return batch_cost - + # For other providers, use the existing logic total_cost = _get_batch_job_cost_from_file_content( file_content_dictionary=file_content_dictionary, @@ -173,7 +185,10 @@ def calculate_vertex_ai_batch_cost_and_usage( verbose_logger.info( "vertex_ai batch cost: cost=%s, prompt=%d, completion=%d, total=%d", - total_cost, prompt_tokens, completion_tokens, total_tokens, + total_cost, + prompt_tokens, + completion_tokens, + total_tokens, ) return total_cost, Usage( @@ -185,12 +200,14 @@ def calculate_vertex_ai_batch_cost_and_usage( async def _get_batch_output_file_content_as_dictionary( batch: Batch, - custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic"] = "openai", + custom_llm_provider: Literal[ + "openai", "azure", "vertex_ai", "hosted_vllm", "anthropic" + ] = "openai", litellm_params: Optional[dict] = None, ) -> List[dict]: """ Get the batch output file content as a list of dictionaries - + Args: batch: The batch object custom_llm_provider: The LLM provider @@ -198,8 +215,9 @@ async def _get_batch_output_file_content_as_dictionary( Required for Azure and other providers that need authentication """ from litellm.files.main import afile_content - from litellm.proxy.openai_files_endpoints.common_utils import \ - _is_base64_encoded_unified_file_id + from litellm.proxy.openai_files_endpoints.common_utils import ( + _is_base64_encoded_unified_file_id, + ) if custom_llm_provider == "vertex_ai": raise ValueError("Vertex AI does not support file content retrieval") @@ -211,21 +229,27 @@ async def _get_batch_output_file_content_as_dictionary( is_base64_unified_file_id = _is_base64_encoded_unified_file_id(file_id) if is_base64_unified_file_id: try: - file_id = is_base64_unified_file_id.split("llm_output_file_id,")[1].split(";")[0] - verbose_logger.debug(f"Extracted LLM output file ID from unified file ID: {file_id}") + file_id = is_base64_unified_file_id.split("llm_output_file_id,")[1].split( + ";" + )[0] + verbose_logger.debug( + f"Extracted LLM output file ID from unified file ID: {file_id}" + ) except (IndexError, AttributeError) as e: - verbose_logger.error(f"Failed to extract LLM output file ID from unified file ID: {batch.output_file_id}, error: {e}") + verbose_logger.error( + f"Failed to extract LLM output file ID from unified file ID: {batch.output_file_id}, error: {e}" + ) # Build kwargs for afile_content with credentials from litellm_params file_content_kwargs = { "file_id": file_id, "custom_llm_provider": custom_llm_provider, } - + # Extract and add credentials for file access credentials = _extract_file_access_credentials(litellm_params) file_content_kwargs.update(credentials) - + _file_content = await afile_content(**file_content_kwargs) # type: ignore[reportArgumentType] return _get_file_content_as_dictionary(_file_content.content) @@ -233,30 +257,37 @@ async def _get_batch_output_file_content_as_dictionary( def _extract_file_access_credentials(litellm_params: Optional[dict]) -> dict: """ Extract credentials from litellm_params for file access operations. - + This method extracts relevant authentication and configuration parameters needed for accessing files across different providers (Azure, Vertex AI, etc.). - + Args: litellm_params: Dictionary containing litellm parameters with credentials - + Returns: Dictionary containing only the credentials needed for file access """ credentials = {} - + if litellm_params: # List of credential keys that should be passed to file operations credential_keys = [ - "api_key", "api_base", "api_version", "organization", - "azure_ad_token", "azure_ad_token_provider", - "vertex_project", "vertex_location", "vertex_credentials", - "timeout", "max_retries" + "api_key", + "api_base", + "api_version", + "organization", + "azure_ad_token", + "azure_ad_token_provider", + "vertex_project", + "vertex_location", + "vertex_credentials", + "timeout", + "max_retries", ] for key in credential_keys: if key in litellm_params: credentials[key] = litellm_params[key] - + return credentials @@ -279,7 +310,9 @@ def _get_file_content_as_dictionary(file_content: bytes) -> List[dict]: def _get_batch_job_cost_from_file_content( file_content_dictionary: List[dict], - custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic"] = "openai", + custom_llm_provider: Literal[ + "openai", "azure", "vertex_ai", "hosted_vllm", "anthropic" + ] = "openai", model_info: Optional[ModelInfo] = None, ) -> float: """ @@ -321,7 +354,9 @@ def _get_batch_job_cost_from_file_content( def _get_batch_job_total_usage_from_file_content( file_content_dictionary: List[dict], - custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic"] = "openai", + custom_llm_provider: Literal[ + "openai", "azure", "vertex_ai", "hosted_vllm", "anthropic" + ] = "openai", model_name: Optional[str] = None, ) -> Usage: """ @@ -329,9 +364,11 @@ def _get_batch_job_total_usage_from_file_content( """ # Handle Vertex AI with specialized method if custom_llm_provider == "vertex_ai" and model_name: - _, batch_usage = calculate_vertex_ai_batch_cost_and_usage(file_content_dictionary, model_name) + _, batch_usage = calculate_vertex_ai_batch_cost_and_usage( + file_content_dictionary, model_name + ) return batch_usage - + # For other providers, use the existing logic total_tokens: int = 0 prompt_tokens: int = 0 @@ -349,6 +386,7 @@ def _get_batch_job_total_usage_from_file_content( completion_tokens=completion_tokens, ) + def _get_batch_job_input_file_usage( file_content_dictionary: List[dict], custom_llm_provider: Literal["openai", "azure", "vertex_ai"] = "openai", @@ -358,25 +396,26 @@ def _get_batch_job_input_file_usage( Count the number of tokens in the input file Used for batch rate limiting to count the number of tokens in the input file - """ + """ prompt_tokens: int = 0 completion_tokens: int = 0 - + for _item in file_content_dictionary: body = _item.get("body", {}) model = body.get("model", model_name or "") messages = body.get("messages", []) - + if messages: item_tokens = token_counter(model=model, messages=messages) prompt_tokens += item_tokens - + return Usage( total_tokens=prompt_tokens + completion_tokens, prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, ) + def _get_batch_job_usage_from_response_body(response_body: dict) -> Usage: """ Get the tokens of a batch job from the response body @@ -400,4 +439,4 @@ def _batch_response_was_successful(batch_job_output_file: dict) -> bool: Check if the batch job response status == 200 """ _response: dict = batch_job_output_file.get("response", None) or {} - return _response.get("status_code", None) == 200 \ No newline at end of file + return _response.get("status_code", None) == 200 diff --git a/litellm/batches/main.py b/litellm/batches/main.py index 723b59c6b46..1a03b172d38 100644 --- a/litellm/batches/main.py +++ b/litellm/batches/main.py @@ -109,7 +109,9 @@ async def acreate_batch( completion_window: Literal["24h"], endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"], input_file_id: str, - custom_llm_provider: Literal["openai", "azure", "vertex_ai", "bedrock", "hosted_vllm"] = "openai", + custom_llm_provider: Literal[ + "openai", "azure", "vertex_ai", "bedrock", "hosted_vllm" + ] = "openai", metadata: Optional[Dict[str, str]] = None, extra_headers: Optional[Dict[str, str]] = None, extra_body: Optional[Dict[str, str]] = None, @@ -159,7 +161,9 @@ def create_batch( # noqa: PLR0915 completion_window: Literal["24h"], endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"], input_file_id: str, - custom_llm_provider: Literal["openai", "azure", "vertex_ai", "bedrock", "hosted_vllm"] = "openai", + custom_llm_provider: Literal[ + "openai", "azure", "vertex_ai", "bedrock", "hosted_vllm" + ] = "openai", metadata: Optional[Dict[str, str]] = None, extra_headers: Optional[Dict[str, str]] = None, extra_body: Optional[Dict[str, str]] = None, @@ -220,7 +224,9 @@ def create_batch( # noqa: PLR0915 extra_body=extra_body, ) if output_expires_after is not None: - _create_batch_request["output_expires_after"] = cast(FileExpiresAfter, output_expires_after) + _create_batch_request["output_expires_after"] = cast( + FileExpiresAfter, output_expires_after + ) if model is not None: provider_config = ProviderConfigManager.get_provider_batches_config( model=model, @@ -364,7 +370,9 @@ def create_batch( # noqa: PLR0915 @client async def aretrieve_batch( batch_id: str, - custom_llm_provider: Literal["openai", "azure", "vertex_ai", "bedrock", "hosted_vllm", "anthropic"] = "openai", + custom_llm_provider: Literal[ + "openai", "azure", "vertex_ai", "bedrock", "hosted_vllm", "anthropic" + ] = "openai", metadata: Optional[Dict[str, str]] = None, extra_headers: Optional[Dict[str, str]] = None, extra_body: Optional[Dict[str, str]] = None, @@ -410,7 +418,9 @@ def _handle_retrieve_batch_providers_without_provider_config( litellm_params: dict, _retrieve_batch_request: RetrieveBatchRequest, _is_async: bool, - custom_llm_provider: Literal["openai", "azure", "vertex_ai", "bedrock", "hosted_vllm", "anthropic"] = "openai", + custom_llm_provider: Literal[ + "openai", "azure", "vertex_ai", "bedrock", "hosted_vllm", "anthropic" + ] = "openai", logging_obj: Optional[Any] = None, ): api_base: Optional[str] = None @@ -549,7 +559,9 @@ def _handle_retrieve_batch_providers_without_provider_config( @client def retrieve_batch( batch_id: str, - custom_llm_provider: Literal["openai", "azure", "vertex_ai", "bedrock", "hosted_vllm", "anthropic"] = "openai", + custom_llm_provider: Literal[ + "openai", "azure", "vertex_ai", "bedrock", "hosted_vllm", "anthropic" + ] = "openai", metadata: Optional[Dict[str, str]] = None, extra_headers: Optional[Dict[str, str]] = None, extra_body: Optional[Dict[str, str]] = None, @@ -929,7 +941,6 @@ def cancel_batch( LiteLLM Equivalent of POST https://api.openai.com/v1/batches/{batch_id}/cancel """ try: - try: if model is not None: _, custom_llm_provider, _, _ = get_llm_provider( @@ -1097,25 +1108,40 @@ def _handle_async_invoke_status( "inprogress": "in_progress", "in_progress": "in_progress", } - normalized_status: BatchJobStatus = status_mapping.get(aws_status_lower, "failed") # Default to "failed" if unknown status + normalized_status: BatchJobStatus = status_mapping.get( + aws_status_lower, "failed" + ) # Default to "failed" if unknown status # Get output S3 URI safely output_s3_uri = "" try: - output_s3_uri = status_response["outputDataConfig"]["s3OutputDataConfig"]["s3Uri"] + output_s3_uri = status_response["outputDataConfig"]["s3OutputDataConfig"][ + "s3Uri" + ] except (KeyError, TypeError): pass - + # Use BedrockBatchesConfig's timestamp parsing method (expects raw AWS status string) import time from litellm.llms.bedrock.batches.transformation import BedrockBatchesConfig - created_at, in_progress_at, completed_at, failed_at, _, _ = BedrockBatchesConfig()._parse_timestamps_and_status(status_response, aws_status_raw) + + ( + created_at, + in_progress_at, + completed_at, + failed_at, + _, + _, + ) = BedrockBatchesConfig()._parse_timestamps_and_status( + status_response, aws_status_raw + ) result = LiteLLMBatch( id=status_response["invocationArn"], object="batch", status=normalized_status, - created_at=created_at or int(time.time()), # Provide default timestamp if None + created_at=created_at + or int(time.time()), # Provide default timestamp if None in_progress_at=in_progress_at, completed_at=completed_at, failed_at=failed_at, diff --git a/litellm/caching/azure_blob_cache.py b/litellm/caching/azure_blob_cache.py index 45e551bdae9..a2246640c30 100644 --- a/litellm/caching/azure_blob_cache.py +++ b/litellm/caching/azure_blob_cache.py @@ -22,7 +22,9 @@ class AzureBlobCache(BaseCache): from azure.storage.blob import BlobServiceClient from azure.core.exceptions import ResourceExistsError from azure.identity import DefaultAzureCredential - from azure.identity.aio import DefaultAzureCredential as AsyncDefaultAzureCredential + from azure.identity.aio import ( + DefaultAzureCredential as AsyncDefaultAzureCredential, + ) from azure.storage.blob.aio import BlobServiceClient as AsyncBlobServiceClient self.container_client = BlobServiceClient( @@ -50,14 +52,16 @@ class AzureBlobCache(BaseCache): print_verbose(f"LiteLLM SET Cache - Azure Blob. Key={key}. Value={value}") serialized_value = json.dumps(value) try: - await self.async_container_client.upload_blob(key, serialized_value, overwrite=True) + await self.async_container_client.upload_blob( + key, serialized_value, overwrite=True + ) except Exception as e: # NON blocking - notify users Azure Blob is throwing an exception print_verbose(f"LiteLLM set_cache() - Got exception from Azure Blob: {e}") def get_cache(self, key, **kwargs): from azure.core.exceptions import ResourceNotFoundError - + try: print_verbose(f"Get Azure Blob Cache: key: {key}") as_bytes = self.container_client.download_blob(key).readall() @@ -74,7 +78,7 @@ class AzureBlobCache(BaseCache): async def async_get_cache(self, key, **kwargs): from azure.core.exceptions import ResourceNotFoundError - + try: print_verbose(f"Get Azure Blob Cache: key: {key}") blob = await self.async_container_client.download_blob(key) diff --git a/litellm/caching/base_cache.py b/litellm/caching/base_cache.py index 8660e64efde..81f1d61bd0d 100644 --- a/litellm/caching/base_cache.py +++ b/litellm/caching/base_cache.py @@ -53,12 +53,12 @@ class BaseCache(ABC): async def disconnect(self): raise NotImplementedError - + async def test_connection(self) -> dict: """ Test the cache connection. - + Returns: dict: {"status": "success" | "failed", "message": str, "error": Optional[str]} """ - raise NotImplementedError \ No newline at end of file + raise NotImplementedError diff --git a/litellm/caching/caching_handler.py b/litellm/caching/caching_handler.py index 4e97197a9de..7cdbd3fc03d 100644 --- a/litellm/caching/caching_handler.py +++ b/litellm/caching/caching_handler.py @@ -78,9 +78,7 @@ class CachingHandlerResponse(BaseModel): cached_result: Optional[Any] = None final_embedding_cached_response: Optional[EmbeddingResponse] = None - embedding_all_elements_cache_hit: bool = ( - False # this is set to True when all elements in the list have a cache hit in the embedding cache, if true return the final_embedding_cached_response no need to make an API call - ) + embedding_all_elements_cache_hit: bool = False # this is set to True when all elements in the list have a cache hit in the embedding cache, if true return the final_embedding_cached_response no need to make an API call in_memory_cache_obj = InMemoryCache() @@ -159,7 +157,7 @@ class LLMCachingHandler: ######################################################### parent_otel_span = _get_parent_otel_span_from_kwargs(kwargs) kwargs["parent_otel_span"] = parent_otel_span - + if litellm.cache is not None and self._is_call_type_supported_by_cache( original_function=original_function ): @@ -181,7 +179,9 @@ class LLMCachingHandler: api_base=kwargs.get("api_base", None), api_key=kwargs.get("api_key", None), ) - cache_duration_ms = (cache_check_end_time - cache_check_start_time) * 1000 + cache_duration_ms = ( + cache_check_end_time - cache_check_start_time + ) * 1000 self._update_litellm_logging_obj_environment( logging_obj=logging_obj, model=model, @@ -194,7 +194,6 @@ class LLMCachingHandler: call_type = original_function.__name__ - cached_result = self._convert_cached_result_to_model_response( cached_result=cached_result, call_type=call_type, @@ -244,7 +243,7 @@ class LLMCachingHandler: final_embedding_cached_response=final_embedding_cached_response, embedding_all_elements_cache_hit=embedding_all_elements_cache_hit, ) - + verbose_logger.debug(f"CACHE RESULT: {cached_result}") return CachingHandlerResponse( cached_result=cached_result, @@ -265,9 +264,8 @@ class LLMCachingHandler: ) -> CachingHandlerResponse: from litellm.utils import CustomStreamWrapper - cached_result: Optional[Any] = None - + # Check if caching should be performed BEFORE doing expensive kwargs copy if litellm.cache is not None and self._is_call_type_supported_by_cache( original_function=original_function @@ -325,7 +323,7 @@ class LLMCachingHandler: result=cached_result, start_time=start_time, end_time=end_time, - cache_hit=cache_hit + cache_hit=cache_hit, ) cache_key = litellm.cache.get_cache_key(**kwargs) if ( @@ -554,12 +552,18 @@ class LLMCachingHandler: GLOBAL_LOGGING_WORKER.ensure_initialized_and_enqueue( async_coroutine=logging_obj.async_success_handler( - result=cached_result, start_time=start_time, end_time=end_time, cache_hit=cache_hit + result=cached_result, + start_time=start_time, + end_time=end_time, + cache_hit=cache_hit, ) ) logging_obj.handle_sync_success_callbacks_for_async_calls( - result=cached_result, start_time=start_time, end_time=end_time, cache_hit=cache_hit + result=cached_result, + start_time=start_time, + end_time=end_time, + cache_hit=cache_hit, ) async def _retrieve_from_cache( @@ -728,10 +732,9 @@ class LLMCachingHandler: response_type="audio_transcription", hidden_params=hidden_params, ) - elif ( - call_type == "aresponses" - or call_type == "responses" - ) and isinstance(cached_result, dict): + elif (call_type == "aresponses" or call_type == "responses") and isinstance( + cached_result, dict + ): # Convert cached dict back to ResponsesAPIResponse object cached_result = ResponsesAPIResponse(**cached_result) @@ -741,7 +744,7 @@ class LLMCachingHandler: and isinstance(cached_result._hidden_params, dict) ): cached_result._hidden_params["cache_hit"] = True - + ######################################################### # Add final timing metrics to the cached result ######################################################### @@ -1011,9 +1014,9 @@ class LLMCachingHandler: } if litellm.cache is not None: - litellm_params["preset_cache_key"] = ( - litellm.cache._get_preset_cache_key_from_kwargs(**kwargs) - ) + litellm_params[ + "preset_cache_key" + ] = litellm.cache._get_preset_cache_key_from_kwargs(**kwargs) else: litellm_params["preset_cache_key"] = None diff --git a/litellm/caching/dual_cache.py b/litellm/caching/dual_cache.py index 6df570c72b9..4020b8cc22e 100644 --- a/litellm/caching/dual_cache.py +++ b/litellm/caching/dual_cache.py @@ -319,18 +319,20 @@ class DualCache(BaseCache): previous_access_times ) raise - + # Short-circuit if redis_result is None or contains only None values - if redis_result is None or all(v is None for v in redis_result.values()): + if redis_result is None or all( + v is None for v in redis_result.values() + ): return result # Pre-compute key-to-index mapping for O(1) lookup key_to_index = {key: i for i, key in enumerate(keys)} - + # Update both result and in-memory cache in a single loop for key, value in redis_result.items(): result[key_to_index[key]] = value - + if value is not None and self.in_memory_cache is not None: await self.in_memory_cache.async_set_cache( key, value, **kwargs @@ -346,6 +348,8 @@ class DualCache(BaseCache): ) try: if self.in_memory_cache is not None: + if "ttl" not in kwargs and self.default_in_memory_ttl is not None: + kwargs["ttl"] = self.default_in_memory_ttl await self.in_memory_cache.async_set_cache(key, value, **kwargs) if self.redis_cache is not None and local_only is False: @@ -367,6 +371,8 @@ class DualCache(BaseCache): ) try: if self.in_memory_cache is not None: + if "ttl" not in kwargs and self.default_in_memory_ttl is not None: + kwargs["ttl"] = self.default_in_memory_ttl await self.in_memory_cache.async_set_cache_pipeline( cache_list=cache_list, **kwargs ) diff --git a/litellm/caching/gcs_cache.py b/litellm/caching/gcs_cache.py index 88857ba0e70..a5bd092f154 100644 --- a/litellm/caching/gcs_cache.py +++ b/litellm/caching/gcs_cache.py @@ -16,13 +16,23 @@ from .base_cache import BaseCache class GCSCache(BaseCache): - def __init__(self, bucket_name: Optional[str] = None, path_service_account: Optional[str] = None, gcs_path: Optional[str] = None) -> None: + def __init__( + self, + bucket_name: Optional[str] = None, + path_service_account: Optional[str] = None, + gcs_path: Optional[str] = None, + ) -> None: super().__init__() self.bucket_name = bucket_name or GCSBucketBase(bucket_name=None).BUCKET_NAME - self.path_service_account = path_service_account or GCSBucketBase(bucket_name=None).path_service_account_json + self.path_service_account = ( + path_service_account + or GCSBucketBase(bucket_name=None).path_service_account_json + ) self.key_prefix = gcs_path.rstrip("/") + "/" if gcs_path else "" # create httpx clients - self.async_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) + self.async_client = get_async_httpx_client( + llm_provider=httpxSpecialProvider.LoggingCallback + ) self.sync_client = _get_httpx_client() def _construct_headers(self) -> dict: @@ -52,7 +62,9 @@ class GCSCache(BaseCache): data = json.dumps(value) await self.async_client.post(url=url, data=data, headers=headers) except Exception as e: - print_verbose(f"GCS Caching: async_set_cache() - Got exception from GCS: {e}") + print_verbose( + f"GCS Caching: async_set_cache() - Got exception from GCS: {e}" + ) def get_cache(self, key, **kwargs): try: @@ -69,7 +81,9 @@ class GCSCache(BaseCache): return cached_response return None except Exception as e: - verbose_logger.error(f"GCS Caching: get_cache() - Got exception from GCS: {e}") + verbose_logger.error( + f"GCS Caching: get_cache() - Got exception from GCS: {e}" + ) async def async_get_cache(self, key, **kwargs): try: @@ -82,7 +96,9 @@ class GCSCache(BaseCache): return json.loads(response.text) return None except Exception as e: - verbose_logger.error(f"GCS Caching: async_get_cache() - Got exception from GCS: {e}") + verbose_logger.error( + f"GCS Caching: async_get_cache() - Got exception from GCS: {e}" + ) def flush_cache(self): pass diff --git a/litellm/caching/qdrant_semantic_cache.py b/litellm/caching/qdrant_semantic_cache.py index 181effa01d4..5e3713e5a15 100644 --- a/litellm/caching/qdrant_semantic_cache.py +++ b/litellm/caching/qdrant_semantic_cache.py @@ -54,7 +54,9 @@ class QdrantSemanticCache(BaseCache): raise Exception("similarity_threshold must be provided, passed None") self.similarity_threshold = similarity_threshold self.embedding_model = embedding_model - self.vector_size = vector_size if vector_size is not None else QDRANT_VECTOR_SIZE + self.vector_size = ( + vector_size if vector_size is not None else QDRANT_VECTOR_SIZE + ) headers = {} # check if defined as os.environ/ variable diff --git a/litellm/caching/redis_cache.py b/litellm/caching/redis_cache.py index fa9b94bc2ac..82794c116f2 100644 --- a/litellm/caching/redis_cache.py +++ b/litellm/caching/redis_cache.py @@ -268,19 +268,19 @@ class RedisCache(BaseCache): def _parse_redis_major_version(self) -> int: """ Parse Redis version to extract the major version number. - + Handles multiple version formats: - Strings: "7.0.0", "6", "7.0.0-rc1", " 7.0.0 " - Floats: 7.0 (e.g., from AWS ElastiCache Valkey) - Integers: 7 - Malformed: "latest", "", "Unknown" (defaults to DEFAULT_REDIS_MAJOR_VERSION) - + Returns: int: The major version number (defaults to DEFAULT_REDIS_MAJOR_VERSION if unparseable) """ if self.redis_version == "Unknown": return DEFAULT_REDIS_MAJOR_VERSION - + try: version_str = str(self.redis_version).strip() # Handle cases where there's no dot (e.g., "7" or 7) @@ -1113,14 +1113,14 @@ class RedisCache(BaseCache): self.redis_client.close() except Exception as e: verbose_logger.debug("Error closing sync Redis client: %s", e) - + async def test_connection(self) -> dict: """ Test the Redis connection by creating a new client and pinging it. - + This creates a fresh connection without using cached clients or connection pools to ensure the credentials are actually valid. - + Returns: dict: {"status": "success" | "failed", "message": str, "error": Optional[str]} """ @@ -1129,29 +1129,26 @@ class RedisCache(BaseCache): # Create a fresh Redis client with current settings redis_client = redis_async.Redis(**self.redis_kwargs) - + # Test the connection ping_result = await redis_client.ping() # type: ignore[misc] # Close the connection await redis_client.aclose() # type: ignore[attr-defined] - + if ping_result: return { "status": "success", - "message": "Redis connection test successful" + "message": "Redis connection test successful", } else: - return { - "status": "failed", - "message": "Redis ping returned False" - } + return {"status": "failed", "message": "Redis ping returned False"} except Exception as e: verbose_logger.error(f"Redis connection test failed: {str(e)}") return { "status": "failed", "message": f"Redis connection failed: {str(e)}", - "error": str(e) + "error": str(e), } async def async_delete_cache(self, key: str): diff --git a/litellm/caching/redis_cluster_cache.py b/litellm/caching/redis_cluster_cache.py index 664578c8700..b0f5754f58e 100644 --- a/litellm/caching/redis_cluster_cache.py +++ b/litellm/caching/redis_cluster_cache.py @@ -57,11 +57,11 @@ class RedisClusterCache(RedisCache): """ async_redis_cluster_client = self.init_async_client() return await async_redis_cluster_client.mget_nonatomic(keys=keys) # type: ignore - + async def test_connection(self) -> dict: """ Test the Redis Cluster connection. - + Returns: dict: {"status": "success" | "failed", "message": str, "error": Optional[str]} """ @@ -72,37 +72,38 @@ class RedisClusterCache(RedisCache): # Create ClusterNode objects from startup_nodes cluster_kwargs = self.redis_kwargs.copy() startup_nodes = cluster_kwargs.pop("startup_nodes", []) - + new_startup_nodes: List[ClusterNode] = [] for item in startup_nodes: new_startup_nodes.append(ClusterNode(**item)) - + # Create a fresh Redis Cluster client with current settings redis_client = redis_async.RedisCluster( startup_nodes=new_startup_nodes, **cluster_kwargs # type: ignore ) - + # Test the connection ping_result = await redis_client.ping() # type: ignore[attr-defined, misc] # Close the connection await redis_client.aclose() # type: ignore[attr-defined] - + if ping_result: return { "status": "success", - "message": "Redis Cluster connection test successful" + "message": "Redis Cluster connection test successful", } else: return { "status": "failed", - "message": "Redis Cluster ping returned False" + "message": "Redis Cluster ping returned False", } except Exception as e: from litellm._logging import verbose_logger + verbose_logger.error(f"Redis Cluster connection test failed: {str(e)}") return { "status": "failed", "message": f"Redis Cluster connection failed: {str(e)}", - "error": str(e) - } \ No newline at end of file + "error": str(e), + } diff --git a/litellm/caching/s3_cache.py b/litellm/caching/s3_cache.py index 180964605f6..e26fbe8981c 100644 --- a/litellm/caching/s3_cache.py +++ b/litellm/caching/s3_cache.py @@ -110,7 +110,9 @@ class S3Cache(BaseCache): func = partial(self.set_cache, key, value, **kwargs) await loop.run_in_executor(None, func) except Exception as e: - verbose_logger.error(f"S3 Caching: async_set_cache() - Got exception from S3: {e}") + verbose_logger.error( + f"S3 Caching: async_set_cache() - Got exception from S3: {e}" + ) def get_cache(self, key, **kwargs): import botocore @@ -126,7 +128,7 @@ class S3Cache(BaseCache): if cached_response is not None: if "Expires" in cached_response: - expires_time = cached_response['Expires'] + expires_time = cached_response["Expires"] current_time = datetime.now(expires_time.tzinfo) if current_time > expires_time: diff --git a/litellm/completion_extras/litellm_responses_transformation/handler.py b/litellm/completion_extras/litellm_responses_transformation/handler.py index e9ac1d2ad7b..2164a2c0f01 100644 --- a/litellm/completion_extras/litellm_responses_transformation/handler.py +++ b/litellm/completion_extras/litellm_responses_transformation/handler.py @@ -61,9 +61,7 @@ class ResponsesToCompletionBridgeHandler: existing.setdefault(key, value) return response - def _collect_response_from_stream( - self, stream_iter: Any - ) -> "ResponsesAPIResponse": + def _collect_response_from_stream(self, stream_iter: Any) -> "ResponsesAPIResponse": for _ in stream_iter: pass @@ -144,7 +142,9 @@ class ResponsesToCompletionBridgeHandler: custom_llm_provider=custom_llm_provider, ) - def completion(self, *args, **kwargs) -> Union[ + def completion( + self, *args, **kwargs + ) -> Union[ Coroutine[Any, Any, Union["ModelResponse", "CustomStreamWrapper"]], "ModelResponse", "CustomStreamWrapper", diff --git a/litellm/completion_extras/litellm_responses_transformation/transformation.py b/litellm/completion_extras/litellm_responses_transformation/transformation.py index babb575ee32..4b31bcfc285 100644 --- a/litellm/completion_extras/litellm_responses_transformation/transformation.py +++ b/litellm/completion_extras/litellm_responses_transformation/transformation.py @@ -63,7 +63,9 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): def __init__(self): pass - def _handle_raw_dict_response_item(self, item: Dict[str, Any], index: int) -> Tuple[Optional[Any], int]: + def _handle_raw_dict_response_item( + self, item: Dict[str, Any], index: int + ) -> Tuple[Optional[Any], int]: """ Handle raw dict response items from Responses API (e.g., GPT-5 Codex format). @@ -106,9 +108,13 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): if item_type == "function_call": # Extract provider_specific_fields if present and pass through as-is provider_specific_fields = item.get("provider_specific_fields") - if provider_specific_fields and not isinstance(provider_specific_fields, dict): + if provider_specific_fields and not isinstance( + provider_specific_fields, dict + ): provider_specific_fields = ( - dict(provider_specific_fields) if hasattr(provider_specific_fields, "__dict__") else {} + dict(provider_specific_fields) + if hasattr(provider_specific_fields, "__dict__") + else {} ) tool_call_dict = { @@ -124,7 +130,9 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): if provider_specific_fields: tool_call_dict["provider_specific_fields"] = provider_specific_fields # Also add to function's provider_specific_fields for consistency - tool_call_dict["function"]["provider_specific_fields"] = provider_specific_fields + tool_call_dict["function"][ + "provider_specific_fields" + ] = provider_specific_fields msg = Message( content=None, @@ -232,10 +240,10 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): if key in ("max_tokens", "max_completion_tokens"): responses_api_request["max_output_tokens"] = value elif key == "tools" and value is not None: - responses_api_request["tools"] = ( - self._convert_tools_to_responses_format( - cast(List[Dict[str, Any]], value) - ) + responses_api_request[ + "tools" + ] = self._convert_tools_to_responses_format( + cast(List[Dict[str, Any]], value) ) elif key == "response_format": text_format = self._transform_response_format_to_text_format(value) @@ -250,9 +258,7 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): elif key == "web_search_options": self._add_web_search_tool(responses_api_request, value) - def _build_sanitized_litellm_params( - self, litellm_params: dict - ) -> Dict[str, Any]: + def _build_sanitized_litellm_params(self, litellm_params: dict) -> Dict[str, Any]: """Build sanitized litellm_params with merged metadata.""" responses_optional_param_keys = set( ResponsesAPIOptionalRequestParams.__annotations__.keys() @@ -337,7 +343,9 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): previous_response_id = optional_params.get("previous_response_id") if previous_response_id: # Use the existing session handler for responses API - verbose_logger.debug(f"Chat provider: Warning ignoring previous response ID: {previous_response_id}") + verbose_logger.debug( + f"Chat provider: Warning ignoring previous response ID: {previous_response_id}" + ) # Convert back to responses API format for the actual request @@ -347,9 +355,7 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): setattr(litellm_logging_obj, "call_type", CallTypes.responses.value) - sanitized_litellm_params = self._build_sanitized_litellm_params( - litellm_params - ) + sanitized_litellm_params = self._build_sanitized_litellm_params(litellm_params) request_data = { "model": api_model, @@ -359,7 +365,9 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): "client": client, } - verbose_logger.debug(f"Chat provider: Final request model={api_model}, input_items={len(input_items)}") + verbose_logger.debug( + f"Chat provider: Final request model={api_model}, input_items={len(input_items)}" + ) self._merge_responses_api_request_into_request_data( request_data, responses_api_request, instructions @@ -390,6 +398,12 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): ResponseOutputMessage, ResponseReasoningItem, ) + try: + from openai.types.responses.response_output_item import ( + ResponseApplyPatchToolCall, + ) + except ImportError: + ResponseApplyPatchToolCall = None # type: ignore[assignment,misc] from litellm.types.utils import Choices, Message @@ -439,11 +453,21 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): LiteLLMCompletionResponsesConfig, ) - tool_call_dict = ( - LiteLLMCompletionResponsesConfig.convert_response_function_tool_call_to_chat_completion_tool_call( - tool_call_item=item, - index=tool_call_index, - ) + tool_call_dict = LiteLLMCompletionResponsesConfig.convert_response_function_tool_call_to_chat_completion_tool_call( + tool_call_item=item, + index=tool_call_index, + ) + accumulated_tool_calls.append(tool_call_dict) + tool_call_index += 1 + + elif ResponseApplyPatchToolCall is not None and isinstance(item, ResponseApplyPatchToolCall): + from litellm.responses.litellm_completion_transformation.transformation import ( + LiteLLMCompletionResponsesConfig, + ) + + tool_call_dict = LiteLLMCompletionResponsesConfig.convert_apply_patch_tool_call_to_chat_completion_tool_call( + tool_call_item=item, + index=tool_call_index, ) accumulated_tool_calls.append(tool_call_dict) tool_call_index += 1 @@ -463,7 +487,9 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): tool_calls=accumulated_tool_calls, reasoning_content=reasoning_content, ) - choices.append(Choices(message=msg, finish_reason="tool_calls", index=index)) + choices.append( + Choices(message=msg, finish_reason="tool_calls", index=index) + ) reasoning_content = None return choices @@ -499,10 +525,17 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): ) if len(choices) == 0: - if raw_response.incomplete_details is not None and raw_response.incomplete_details.reason is not None: - raise ValueError(f"{model} unable to complete request: {raw_response.incomplete_details.reason}") + if ( + raw_response.incomplete_details is not None + and raw_response.incomplete_details.reason is not None + ): + raise ValueError( + f"{model} unable to complete request: {raw_response.incomplete_details.reason}" + ) else: - raise ValueError(f"Unknown items in responses API response: {raw_response.output}") + raise ValueError( + f"Unknown items in responses API response: {raw_response.output}" + ) setattr(model_response, "choices", choices) @@ -511,21 +544,28 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): setattr( model_response, "usage", - ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(raw_response.usage), + ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage( + raw_response.usage + ), ) # Preserve hidden params from the ResponsesAPIResponse, especially the headers # which contain important provider information like x-request-id raw_response_hidden_params = getattr(raw_response, "_hidden_params", {}) if raw_response_hidden_params: - if not hasattr(model_response, "_hidden_params") or model_response._hidden_params is None: + if ( + not hasattr(model_response, "_hidden_params") + or model_response._hidden_params is None + ): model_response._hidden_params = {} # Merge the raw_response hidden params with model_response hidden params # Preserve existing keys in model_response but add/override with raw_response params for key, value in raw_response_hidden_params.items(): if key == "additional_headers" and key in model_response._hidden_params: # Merge additional_headers to preserve both sets - existing_additional_headers = model_response._hidden_params.get("additional_headers", {}) + existing_additional_headers = model_response._hidden_params.get( + "additional_headers", {} + ) merged_headers = {**value, **existing_additional_headers} model_response._hidden_params[key] = merged_headers else: @@ -535,13 +575,19 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): def get_model_response_iterator( self, - streaming_response: Union[Iterator[str], AsyncIterator[str], "ModelResponse", "BaseModel"], + streaming_response: Union[ + Iterator[str], AsyncIterator[str], "ModelResponse", "BaseModel" + ], sync_stream: bool, json_mode: Optional[bool] = False, ) -> BaseModelResponseIterator: - return OpenAiResponsesToChatCompletionStreamIterator(streaming_response, sync_stream, json_mode) + return OpenAiResponsesToChatCompletionStreamIterator( + streaming_response, sync_stream, json_mode + ) - def _convert_content_str_to_input_text(self, content: str, role: str) -> Dict[str, Any]: + def _convert_content_str_to_input_text( + self, content: str, role: str + ) -> Dict[str, Any]: if role == "user" or role == "system" or role == "tool": return {"type": "input_text", "text": content} else: @@ -568,7 +614,9 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): if actual_image_url is None: raise ValueError(f"Invalid image URL: {content_image_url}") - image_param = ResponseInputImageParam(image_url=actual_image_url, detail="auto", type="input_image") + image_param = ResponseInputImageParam( + image_url=actual_image_url, detail="auto", type="input_image" + ) if detail: image_param["detail"] = detail @@ -581,7 +629,13 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): Union[ str, List[Any], - Iterable[Union["OpenAIMessageContentListBlock", "ChatCompletionThinkingBlock", "ChatCompletionRedactedThinkingBlock"]], + Iterable[ + Union[ + "OpenAIMessageContentListBlock", + "ChatCompletionThinkingBlock", + "ChatCompletionRedactedThinkingBlock", + ] + ], ] ], role: str, @@ -589,7 +643,9 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): """Convert chat completion content to responses API format""" from litellm.types.llms.openai import ChatCompletionImageObject - verbose_logger.debug(f"Chat provider: Converting content to responses format - input type: {type(content)}") + verbose_logger.debug( + f"Chat provider: Converting content to responses format - input type: {type(content)}" + ) if content is None: return [self._convert_content_str_to_input_text("", role)] @@ -600,7 +656,9 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): elif isinstance(content, list): result = [] for i, item in enumerate(content): - verbose_logger.debug(f"Chat provider: Processing content item {i}: {type(item)} = {item}") + verbose_logger.debug( + f"Chat provider: Processing content item {i}: {type(item)} = {item}" + ) if isinstance(item, str): converted = self._convert_content_str_to_input_text(item, role) result.append(converted) @@ -609,7 +667,9 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): # Handle multimodal content original_type = item.get("type") if original_type == "text": - converted = self._convert_content_str_to_input_text(item.get("text", ""), role) + converted = self._convert_content_str_to_input_text( + item.get("text", ""), role + ) result.append(converted) verbose_logger.debug(f"Chat provider: text -> {converted}") elif original_type == "image_url": @@ -621,14 +681,18 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): ), ) result.append(converted) - verbose_logger.debug(f"Chat provider: image_url -> {converted}") + verbose_logger.debug( + f"Chat provider: image_url -> {converted}" + ) else: # Try to map other types to responses API format item_type = original_type or "input_text" if item_type == "image": converted = {"type": "input_image", **item} result.append(converted) - verbose_logger.debug(f"Chat provider: image -> {converted}") + verbose_logger.debug( + f"Chat provider: image -> {converted}" + ) elif item_type in [ "input_text", "input_image", @@ -640,12 +704,18 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): ]: # Already in responses API format result.append(item) - verbose_logger.debug(f"Chat provider: passthrough -> {item}") + verbose_logger.debug( + f"Chat provider: passthrough -> {item}" + ) else: # Default to input_text for unknown types - converted = self._convert_content_str_to_input_text(str(item.get("text", item)), role) + converted = self._convert_content_str_to_input_text( + str(item.get("text", item)), role + ) result.append(converted) - verbose_logger.debug(f"Chat provider: unknown({original_type}) -> {converted}") + verbose_logger.debug( + f"Chat provider: unknown({original_type}) -> {converted}" + ) verbose_logger.debug(f"Chat provider: Final converted content: {result}") return result else: @@ -653,13 +723,17 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): verbose_logger.debug(f"Chat provider: Other content type -> {result}") return result - def _convert_tools_to_responses_format(self, tools: List[Dict[str, Any]]) -> List["ALL_RESPONSES_API_TOOL_PARAMS"]: + def _convert_tools_to_responses_format( + self, tools: List[Dict[str, Any]] + ) -> List["ALL_RESPONSES_API_TOOL_PARAMS"]: """Convert chat completion tools to responses API tools format""" responses_tools: List["ALL_RESPONSES_API_TOOL_PARAMS"] = [] for tool in tools: # convert function tool from chat completion to responses API format if tool.get("type") == "function": - function_tool = cast(ChatCompletionToolParamFunctionChunk, tool.get("function")) + function_tool = cast( + ChatCompletionToolParamFunctionChunk, tool.get("function") + ) responses_tools.append( FunctionToolParam( name=function_tool["name"], @@ -685,7 +759,9 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): if not extra_body: return optional_params - supported_responses_api_params = set(ResponsesAPIOptionalRequestParams.__annotations__.keys()) + supported_responses_api_params = set( + ResponsesAPIOptionalRequestParams.__annotations__.keys() + ) # Also include params we handle specially supported_responses_api_params.update( { @@ -703,7 +779,9 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): return optional_params - def _map_reasoning_effort(self, reasoning_effort: Union[str, Dict[str, Any]]) -> Optional[Reasoning]: + def _map_reasoning_effort( + self, reasoning_effort: Union[str, Dict[str, Any]] + ) -> Optional[Reasoning]: # If dict is passed, convert it directly to Reasoning object if isinstance(reasoning_effort, dict): return Reasoning(**reasoning_effort) # type: ignore[typeddict-item] @@ -711,25 +789,38 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): # Check if auto-summary is enabled via flag or environment variable # Priority: litellm.reasoning_auto_summary flag > LITELLM_REASONING_AUTO_SUMMARY env var auto_summary_enabled = ( - litellm.reasoning_auto_summary or os.getenv("LITELLM_REASONING_AUTO_SUMMARY", "false").lower() == "true" + litellm.reasoning_auto_summary + or os.getenv("LITELLM_REASONING_AUTO_SUMMARY", "false").lower() == "true" ) # If string is passed, map with optional summary based on flag/env var if reasoning_effort == "none": return Reasoning(effort="none", summary="detailed") if auto_summary_enabled else Reasoning(effort="none") # type: ignore elif reasoning_effort == "high": - return Reasoning(effort="high", summary="detailed") if auto_summary_enabled else Reasoning(effort="high") + return ( + Reasoning(effort="high", summary="detailed") + if auto_summary_enabled + else Reasoning(effort="high") + ) elif reasoning_effort == "xhigh": return Reasoning(effort="xhigh", summary="detailed") if auto_summary_enabled else Reasoning(effort="xhigh") # type: ignore[typeddict-item] elif reasoning_effort == "medium": return ( - Reasoning(effort="medium", summary="detailed") if auto_summary_enabled else Reasoning(effort="medium") + Reasoning(effort="medium", summary="detailed") + if auto_summary_enabled + else Reasoning(effort="medium") ) elif reasoning_effort == "low": - return Reasoning(effort="low", summary="detailed") if auto_summary_enabled else Reasoning(effort="low") + return ( + Reasoning(effort="low", summary="detailed") + if auto_summary_enabled + else Reasoning(effort="low") + ) elif reasoning_effort == "minimal": return ( - Reasoning(effort="minimal", summary="detailed") if auto_summary_enabled else Reasoning(effort="minimal") + Reasoning(effort="minimal", summary="detailed") + if auto_summary_enabled + else Reasoning(effort="minimal") ) return None @@ -745,7 +836,10 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): responses_api_request: The responses API request dict to modify web_search_options: Web search configuration (dict or other value) """ - if "tools" not in responses_api_request or responses_api_request["tools"] is None: + if ( + "tools" not in responses_api_request + or responses_api_request["tools"] is None + ): responses_api_request["tools"] = [] # Get the tools list with proper type narrowing @@ -835,13 +929,17 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): annotation_dict = annotation else: # Skip unsupported annotation types - verbose_logger.debug(f"Skipping unsupported annotation type: {type(annotation)}") + verbose_logger.debug( + f"Skipping unsupported annotation type: {type(annotation)}" + ) continue result.append(annotation_dict) # type: ignore except Exception as e: # Skip malformed annotations - verbose_logger.debug(f"Skipping malformed annotation: {annotation}, error: {e}") + verbose_logger.debug( + f"Skipping malformed annotation: {annotation}, error: {e}" + ) continue return result if result else None @@ -862,7 +960,9 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge): class OpenAiResponsesToChatCompletionStreamIterator(BaseModelResponseIterator): - def __init__(self, streaming_response, sync_stream: bool, json_mode: Optional[bool] = False): + def __init__( + self, streaming_response, sync_stream: bool, json_mode: Optional[bool] = False + ): super().__init__(streaming_response, sync_stream, json_mode) def _handle_string_chunk( @@ -875,7 +975,9 @@ class OpenAiResponsesToChatCompletionStreamIterator(BaseModelResponseIterator): if not str_line or str_line.startswith("event:"): # ignore. - return GenericStreamingChunk(text="", tool_use=None, is_finished=False, finish_reason="", usage=None) + return GenericStreamingChunk( + text="", tool_use=None, is_finished=False, finish_reason="", usage=None + ) index = str_line.find("data:") if index != -1: str_line = str_line[index + 5 :] @@ -938,9 +1040,13 @@ class OpenAiResponsesToChatCompletionStreamIterator(BaseModelResponseIterator): if output_item.get("type") == "function_call": # Extract provider_specific_fields if present provider_specific_fields = output_item.get("provider_specific_fields") - if provider_specific_fields and not isinstance(provider_specific_fields, dict): + if provider_specific_fields and not isinstance( + provider_specific_fields, dict + ): provider_specific_fields = ( - dict(provider_specific_fields) if hasattr(provider_specific_fields, "__dict__") else {} + dict(provider_specific_fields) + if hasattr(provider_specific_fields, "__dict__") + else {} ) function_chunk = ChatCompletionToolCallFunctionChunk( @@ -949,7 +1055,9 @@ class OpenAiResponsesToChatCompletionStreamIterator(BaseModelResponseIterator): ) if provider_specific_fields: - function_chunk["provider_specific_fields"] = provider_specific_fields + function_chunk[ + "provider_specific_fields" + ] = provider_specific_fields tool_call_index = parsed_chunk.get("output_index", 0) tool_call_chunk = ChatCompletionToolCallChunk( @@ -986,7 +1094,9 @@ class OpenAiResponsesToChatCompletionStreamIterator(BaseModelResponseIterator): id=None, index=tool_call_index, type="function", - function=ChatCompletionToolCallFunctionChunk(name=None, arguments=content_part), + function=ChatCompletionToolCallFunctionChunk( + name=None, arguments=content_part + ), ) ] ), @@ -995,16 +1105,22 @@ class OpenAiResponsesToChatCompletionStreamIterator(BaseModelResponseIterator): ] ) else: - raise ValueError(f"Chat provider: Invalid function argument delta {parsed_chunk}") + raise ValueError( + f"Chat provider: Invalid function argument delta {parsed_chunk}" + ) elif event_type == "response.output_item.done": # New output item added output_item = parsed_chunk.get("item", {}) if output_item.get("type") == "function_call": # Extract provider_specific_fields if present provider_specific_fields = output_item.get("provider_specific_fields") - if provider_specific_fields and not isinstance(provider_specific_fields, dict): + if provider_specific_fields and not isinstance( + provider_specific_fields, dict + ): provider_specific_fields = ( - dict(provider_specific_fields) if hasattr(provider_specific_fields, "__dict__") else {} + dict(provider_specific_fields) + if hasattr(provider_specific_fields, "__dict__") + else {} ) function_chunk = ChatCompletionToolCallFunctionChunk( @@ -1014,7 +1130,9 @@ class OpenAiResponsesToChatCompletionStreamIterator(BaseModelResponseIterator): # Add provider_specific_fields to function if present if provider_specific_fields: - function_chunk["provider_specific_fields"] = provider_specific_fields + function_chunk[ + "provider_specific_fields" + ] = provider_specific_fields tool_call_index = parsed_chunk.get("output_index", 0) tool_call_chunk = ChatCompletionToolCallChunk( @@ -1090,11 +1208,22 @@ class OpenAiResponsesToChatCompletionStreamIterator(BaseModelResponseIterator): output_items = response_data.get("output", []) if response_data else [] has_function_calls = any( - item.get("type") == "function_call" for item in output_items if isinstance(item, dict) + item.get("type") == "function_call" + for item in output_items + if isinstance(item, dict) ) finish_reason = "tool_calls" if has_function_calls else "stop" + usage = None + if response_data.get("usage"): + from litellm.responses.utils import ResponseAPILoggingUtils + + usage = ( + ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage( + response_data.get("usage") + ) + ) return ModelResponseStream( choices=[ StreamingChoices( @@ -1102,12 +1231,15 @@ class OpenAiResponsesToChatCompletionStreamIterator(BaseModelResponseIterator): delta=Delta(content=""), finish_reason=finish_reason, ) - ] + ], + usage=usage, ) else: pass # For any unhandled event types, create a minimal valid chunk or skip - verbose_logger.debug(f"Chat provider: Unhandled event type '{event_type}', creating empty chunk") + verbose_logger.debug( + f"Chat provider: Unhandled event type '{event_type}', creating empty chunk" + ) # Return a minimal valid chunk for unknown events return ModelResponseStream( @@ -1130,5 +1262,9 @@ class OpenAiResponsesToChatCompletionStreamIterator(BaseModelResponseIterator): Returns: ModelResponseStream: OpenAI-formatted streaming chunk """ - verbose_logger.debug(f"Chat provider: transform_streaming_response called with chunk: {chunk}") - return OpenAiResponsesToChatCompletionStreamIterator.translate_responses_chunk_to_openai_stream(chunk) + verbose_logger.debug( + f"Chat provider: transform_streaming_response called with chunk: {chunk}" + ) + return OpenAiResponsesToChatCompletionStreamIterator.translate_responses_chunk_to_openai_stream( + chunk + ) diff --git a/litellm/constants.py b/litellm/constants.py index 2486c223ec1..dbc79b69a67 100644 --- a/litellm/constants.py +++ b/litellm/constants.py @@ -60,9 +60,7 @@ LITELLM_MAX_STREAMING_DURATION_SECONDS = ( # Maximum number of base64 characters to keep in logging payloads. # Data URIs exceeding this are replaced with a size placeholder. # Set to 0 to disable truncation. -MAX_BASE64_LENGTH_FOR_LOGGING = int( - os.getenv("MAX_BASE64_LENGTH_FOR_LOGGING", 64) -) +MAX_BASE64_LENGTH_FOR_LOGGING = int(os.getenv("MAX_BASE64_LENGTH_FOR_LOGGING", 64)) # When true, adds detailed per-phase timing breakdown headers to responses. # Headers: x-litellm-timing-{pre-processing,llm-api,post-processing,message-copy}-ms @@ -1353,6 +1351,15 @@ PROXY_BUDGET_RESCHEDULER_MIN_TIME = int( os.getenv("PROXY_BUDGET_RESCHEDULER_MIN_TIME", 597) ) PROXY_BATCH_POLLING_INTERVAL = int(os.getenv("PROXY_BATCH_POLLING_INTERVAL", 3600)) +MAX_OBJECTS_PER_POLL_CYCLE = max(1, int(os.getenv("MAX_OBJECTS_PER_POLL_CYCLE", 50))) +MANAGED_OBJECT_STALENESS_CUTOFF_DAYS = max( + 1, int(os.getenv("MANAGED_OBJECT_STALENESS_CUTOFF_DAYS", 7)) +) +# Set PROXY_BATCH_POLLING_ENABLED=false to disable the CheckBatchCost and +# CheckResponsesCost background polling jobs entirely (e.g. to avoid DB load on +# installations with large numbers of stale managed objects). +_batch_polling_env = os.getenv("PROXY_BATCH_POLLING_ENABLED", "true").lower() +PROXY_BATCH_POLLING_ENABLED = _batch_polling_env == "true" PROXY_BUDGET_RESCHEDULER_MAX_TIME = int( os.getenv("PROXY_BUDGET_RESCHEDULER_MAX_TIME", 605) ) @@ -1421,9 +1428,7 @@ SPECIAL_LITELLM_AUTH_TOKEN = ["ui-token"] DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL = int( os.getenv("DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL", 60) ) -DEFAULT_ACCESS_GROUP_CACHE_TTL = int( - os.getenv("DEFAULT_ACCESS_GROUP_CACHE_TTL", 600) -) +DEFAULT_ACCESS_GROUP_CACHE_TTL = int(os.getenv("DEFAULT_ACCESS_GROUP_CACHE_TTL", 600)) # Sentry Scrubbing Configuration SENTRY_DENYLIST = [ diff --git a/litellm/containers/__init__.py b/litellm/containers/__init__.py index e279cb429e5..48ab5de4181 100644 --- a/litellm/containers/__init__.py +++ b/litellm/containers/__init__.py @@ -42,4 +42,3 @@ __all__ = [ "retrieve_container_file", "retrieve_container_file_content", ] - diff --git a/litellm/containers/endpoint_factory.py b/litellm/containers/endpoint_factory.py index 0b73a19b922..22fd4226dec 100644 --- a/litellm/containers/endpoint_factory.py +++ b/litellm/containers/endpoint_factory.py @@ -43,13 +43,13 @@ def _load_endpoints_config() -> Dict: def create_sync_endpoint_function(endpoint_config: Dict) -> Callable: """ Create a sync SDK function from endpoint config. - + Uses the generic container handler instead of individual handler methods. """ endpoint_name = endpoint_config["name"] response_type = RESPONSE_TYPES.get(endpoint_config["response_type"]) path_params = endpoint_config.get("path_params", []) - + @client def endpoint_func( timeout: int = 600, @@ -76,14 +76,16 @@ def create_sync_endpoint_function(endpoint_config: Dict) -> Callable: # Get provider config litellm_params = GenericLiteLLMParams(**kwargs) - container_provider_config: Optional[BaseContainerConfig] = ( - ProviderConfigManager.get_provider_container_config( - provider=litellm.LlmProviders(custom_llm_provider), - ) + container_provider_config: Optional[ + BaseContainerConfig + ] = ProviderConfigManager.get_provider_container_config( + provider=litellm.LlmProviders(custom_llm_provider), ) if container_provider_config is None: - raise ValueError(f"Container provider config not found for: {custom_llm_provider}") + raise ValueError( + f"Container provider config not found for: {custom_llm_provider}" + ) # Build optional params for logging optional_params = {k: kwargs.get(k) for k in path_params if k in kwargs} @@ -126,7 +128,7 @@ def create_async_endpoint_function( endpoint_config: Dict, ) -> Callable: """Create an async SDK function that wraps the sync function.""" - + @client async def async_endpoint_func( timeout: int = 600, @@ -176,21 +178,21 @@ def create_async_endpoint_function( def generate_container_endpoints() -> Dict[str, Callable]: """ Generate all container endpoint functions from the JSON config. - + Returns a dict mapping function names to their implementations. """ config = _load_endpoints_config() endpoints = {} - + for endpoint_config in config["endpoints"]: # Create sync function sync_func = create_sync_endpoint_function(endpoint_config) endpoints[endpoint_config["name"]] = sync_func - + # Create async function async_func = create_async_endpoint_function(sync_func, endpoint_config) endpoints[endpoint_config["async_name"]] = async_func - + return endpoints @@ -222,5 +224,9 @@ retrieve_container_file = _generated_endpoints.get("retrieve_container_file") aretrieve_container_file = _generated_endpoints.get("aretrieve_container_file") delete_container_file = _generated_endpoints.get("delete_container_file") adelete_container_file = _generated_endpoints.get("adelete_container_file") -retrieve_container_file_content = _generated_endpoints.get("retrieve_container_file_content") -aretrieve_container_file_content = _generated_endpoints.get("aretrieve_container_file_content") +retrieve_container_file_content = _generated_endpoints.get( + "retrieve_container_file_content" +) +aretrieve_container_file_content = _generated_endpoints.get( + "aretrieve_container_file_content" +) diff --git a/litellm/containers/main.py b/litellm/containers/main.py index 105e999ffe8..88318ee039e 100644 --- a/litellm/containers/main.py +++ b/litellm/containers/main.py @@ -39,6 +39,7 @@ __all__ = [ "upload_container_file", ] + ##### Container Create ####################### @client async def acreate_container( @@ -164,10 +165,7 @@ def create_container( extra_query: Optional[Dict[str, Any]] = None, extra_body: Optional[Dict[str, Any]] = None, **kwargs, -) -> Union[ - ContainerObject, - Coroutine[Any, Any, ContainerObject], -]: +) -> Union[ContainerObject, Coroutine[Any, Any, ContainerObject],]: """Create a container using the OpenAI Container API. Currently supports OpenAI @@ -175,7 +173,7 @@ def create_container( Example: ```python import litellm - + response = litellm.create_container( name="My Container", custom_llm_provider="openai", @@ -207,19 +205,23 @@ def create_container( **kwargs, ) # get provider config - container_provider_config: Optional[BaseContainerConfig] = ( - ProviderConfigManager.get_provider_container_config( - provider=litellm.LlmProviders(custom_llm_provider), - ) + container_provider_config: Optional[ + BaseContainerConfig + ] = ProviderConfigManager.get_provider_container_config( + provider=litellm.LlmProviders(custom_llm_provider), ) if container_provider_config is None: - raise ValueError(f"container operations are not supported for {custom_llm_provider}") + raise ValueError( + f"container operations are not supported for {custom_llm_provider}" + ) local_vars.update(kwargs) # Get ContainerCreateOptionalRequestParams with only valid parameters container_create_optional_params: ContainerCreateOptionalRequestParams = ( - ContainerRequestUtils.get_requested_container_create_optional_param(local_vars) + ContainerRequestUtils.get_requested_container_create_optional_param( + local_vars + ) ) # Get optional parameters for the container API @@ -388,10 +390,7 @@ def list_containers( extra_query: Optional[Dict[str, Any]] = None, extra_body: Optional[Dict[str, Any]] = None, **kwargs, -) -> Union[ - ContainerListResponse, - Coroutine[Any, Any, ContainerListResponse], -]: +) -> Union[ContainerListResponse, Coroutine[Any, Any, ContainerListResponse],]: """List containers using the OpenAI Container API. Currently supports OpenAI @@ -420,18 +419,22 @@ def list_containers( **kwargs, ) # get provider config - container_provider_config: Optional[BaseContainerConfig] = ( - ProviderConfigManager.get_provider_container_config( - provider=litellm.LlmProviders(custom_llm_provider), - ) + container_provider_config: Optional[ + BaseContainerConfig + ] = ProviderConfigManager.get_provider_container_config( + provider=litellm.LlmProviders(custom_llm_provider), ) if container_provider_config is None: - raise ValueError(f"Container provider config not found for provider: {custom_llm_provider}") + raise ValueError( + f"Container provider config not found for provider: {custom_llm_provider}" + ) # Get container list request parameters container_list_optional_params: ContainerListOptionalRequestParams = ( - ContainerRequestUtils.get_requested_container_list_optional_param(local_vars) + ContainerRequestUtils.get_requested_container_list_optional_param( + local_vars + ) ) # Pre Call logging @@ -582,10 +585,7 @@ def retrieve_container( extra_query: Optional[Dict[str, Any]] = None, extra_body: Optional[Dict[str, Any]] = None, **kwargs, -) -> Union[ - ContainerObject, - Coroutine[Any, Any, ContainerObject], -]: +) -> Union[ContainerObject, Coroutine[Any, Any, ContainerObject],]: """Retrieve a container using the OpenAI Container API. Currently supports OpenAI @@ -614,14 +614,16 @@ def retrieve_container( **kwargs, ) # get provider config - container_provider_config: Optional[BaseContainerConfig] = ( - ProviderConfigManager.get_provider_container_config( - provider=litellm.LlmProviders(custom_llm_provider), - ) + container_provider_config: Optional[ + BaseContainerConfig + ] = ProviderConfigManager.get_provider_container_config( + provider=litellm.LlmProviders(custom_llm_provider), ) if container_provider_config is None: - raise ValueError(f"Container provider config not found for provider: {custom_llm_provider}") + raise ValueError( + f"Container provider config not found for provider: {custom_llm_provider}" + ) # Pre Call logging litellm_logging_obj.update_environment_variables( @@ -768,10 +770,7 @@ def delete_container( extra_query: Optional[Dict[str, Any]] = None, extra_body: Optional[Dict[str, Any]] = None, **kwargs, -) -> Union[ - DeleteContainerResult, - Coroutine[Any, Any, DeleteContainerResult], -]: +) -> Union[DeleteContainerResult, Coroutine[Any, Any, DeleteContainerResult],]: """Delete a container using the OpenAI Container API. Currently supports OpenAI @@ -800,14 +799,16 @@ def delete_container( **kwargs, ) # get provider config - container_provider_config: Optional[BaseContainerConfig] = ( - ProviderConfigManager.get_provider_container_config( - provider=litellm.LlmProviders(custom_llm_provider), - ) + container_provider_config: Optional[ + BaseContainerConfig + ] = ProviderConfigManager.get_provider_container_config( + provider=litellm.LlmProviders(custom_llm_provider), ) if container_provider_config is None: - raise ValueError(f"Container provider config not found for provider: {custom_llm_provider}") + raise ValueError( + f"Container provider config not found for provider: {custom_llm_provider}" + ) # Pre Call logging litellm_logging_obj.update_environment_variables( @@ -968,10 +969,7 @@ def list_container_files( extra_query: Optional[Dict[str, Any]] = None, extra_body: Optional[Dict[str, Any]] = None, **kwargs, -) -> Union[ - ContainerFileListResponse, - Coroutine[Any, Any, ContainerFileListResponse], -]: +) -> Union[ContainerFileListResponse, Coroutine[Any, Any, ContainerFileListResponse],]: """List files in a container using the OpenAI Container API. Currently supports OpenAI @@ -1000,19 +998,26 @@ def list_container_files( **kwargs, ) # get provider config - container_provider_config: Optional[BaseContainerConfig] = ( - ProviderConfigManager.get_provider_container_config( - provider=litellm.LlmProviders(custom_llm_provider), - ) + container_provider_config: Optional[ + BaseContainerConfig + ] = ProviderConfigManager.get_provider_container_config( + provider=litellm.LlmProviders(custom_llm_provider), ) if container_provider_config is None: - raise ValueError(f"Container provider config not found for provider: {custom_llm_provider}") + raise ValueError( + f"Container provider config not found for provider: {custom_llm_provider}" + ) # Pre Call logging litellm_logging_obj.update_environment_variables( model="", - optional_params={"container_id": container_id, "after": after, "limit": limit, "order": order}, + optional_params={ + "container_id": container_id, + "after": after, + "limit": limit, + "order": order, + }, litellm_params={ "litellm_call_id": litellm_call_id, }, @@ -1180,10 +1185,7 @@ def upload_container_file( extra_query: Optional[Dict[str, Any]] = None, extra_body: Optional[Dict[str, Any]] = None, **kwargs, -) -> Union[ - ContainerFileObject, - Coroutine[Any, Any, ContainerFileObject], -]: +) -> Union[ContainerFileObject, Coroutine[Any, Any, ContainerFileObject],]: """Upload a file to a container using the OpenAI Container API. This endpoint allows uploading files directly to a container session, @@ -1241,14 +1243,16 @@ def upload_container_file( **kwargs, ) # get provider config - container_provider_config: Optional[BaseContainerConfig] = ( - ProviderConfigManager.get_provider_container_config( - provider=litellm.LlmProviders(custom_llm_provider), - ) + container_provider_config: Optional[ + BaseContainerConfig + ] = ProviderConfigManager.get_provider_container_config( + provider=litellm.LlmProviders(custom_llm_provider), ) if container_provider_config is None: - raise ValueError(f"Container provider config not found for provider: {custom_llm_provider}") + raise ValueError( + f"Container provider config not found for provider: {custom_llm_provider}" + ) # Pre Call logging litellm_logging_obj.update_environment_variables( diff --git a/litellm/containers/utils.py b/litellm/containers/utils.py index f30f1e154be..048f587fda7 100644 --- a/litellm/containers/utils.py +++ b/litellm/containers/utils.py @@ -1,7 +1,10 @@ from typing import Dict from litellm.llms.base_llm.containers.transformation import BaseContainerConfig -from litellm.types.containers.main import ContainerCreateOptionalRequestParams, ContainerListOptionalRequestParams +from litellm.types.containers.main import ( + ContainerCreateOptionalRequestParams, + ContainerListOptionalRequestParams, +) class ContainerRequestUtils: diff --git a/litellm/cost_calculator.py b/litellm/cost_calculator.py index 75d45af86e6..c1daa109c7b 100644 --- a/litellm/cost_calculator.py +++ b/litellm/cost_calculator.py @@ -120,37 +120,49 @@ else: LitellmLoggingObject = Any # Pre-resolved CallTypes enum values for fast membership checks -_A2A_CALL_TYPES = frozenset({ - CallTypes.asend_message.value, - CallTypes.send_message.value, -}) +_A2A_CALL_TYPES = frozenset( + { + CallTypes.asend_message.value, + CallTypes.send_message.value, + } +) -_VIDEO_CALL_TYPES = frozenset({ - CallTypes.create_video.value, - CallTypes.acreate_video.value, - CallTypes.video_remix.value, - CallTypes.avideo_remix.value, -}) +_VIDEO_CALL_TYPES = frozenset( + { + CallTypes.create_video.value, + CallTypes.acreate_video.value, + CallTypes.video_remix.value, + CallTypes.avideo_remix.value, + } +) -_SPEECH_CALL_TYPES = frozenset({ - CallTypes.speech.value, - CallTypes.aspeech.value, -}) +_SPEECH_CALL_TYPES = frozenset( + { + CallTypes.speech.value, + CallTypes.aspeech.value, + } +) -_TRANSCRIPTION_CALL_TYPES = frozenset({ - CallTypes.atranscription.value, - CallTypes.transcription.value, -}) +_TRANSCRIPTION_CALL_TYPES = frozenset( + { + CallTypes.atranscription.value, + CallTypes.transcription.value, + } +) -_RERANK_CALL_TYPES = frozenset({ - CallTypes.rerank.value, - CallTypes.arerank.value, -}) +_RERANK_CALL_TYPES = frozenset( + { + CallTypes.rerank.value, + CallTypes.arerank.value, + } +) -_SEARCH_CALL_TYPES = frozenset({ - CallTypes.search.value, - CallTypes.asearch.value, -}) +_SEARCH_CALL_TYPES = frozenset( + { + CallTypes.search.value, + CallTypes.asearch.value, + } +) _AREALTIME_CALL_TYPE = CallTypes.arealtime.value _MCP_CALL_TYPE = CallTypes.call_mcp_tool.value @@ -522,7 +534,10 @@ def cost_per_token( # noqa: PLR0915 return dashscope_cost_per_token(model=model, usage=usage_block) elif custom_llm_provider == "azure_ai": return azure_ai_cost_per_token( - model=model, usage=usage_block, response_time_ms=response_time_ms, request_model=request_model + model=model, + usage=usage_block, + response_time_ms=response_time_ms, + request_model=request_model, ) else: model_info = _cached_get_model_info_helper( @@ -1114,9 +1129,9 @@ def completion_cost( # noqa: PLR0915 or isinstance(completion_response, dict) ): # tts returns a custom class if isinstance(completion_response, dict): - usage_obj: Optional[Union[dict, Usage]] = ( - completion_response.get("usage", {}) - ) + usage_obj: Optional[ + Union[dict, Usage] + ] = completion_response.get("usage", {}) else: usage_obj = getattr(completion_response, "usage", {}) if isinstance(usage_obj, BaseModel) and not _is_known_usage_objects( @@ -1501,7 +1516,6 @@ def completion_cost( # noqa: PLR0915 else: additional_costs = None - _final_cost = ( prompt_tokens_cost_usd_dollar + completion_tokens_cost_usd_dollar ) @@ -1519,7 +1533,11 @@ def completion_cost( # noqa: PLR0915 # Apply discount from module-level config if configured original_cost = _final_cost if litellm.cost_discount_config: - _final_cost, discount_percent, discount_amount = _apply_cost_discount( + ( + _final_cost, + discount_percent, + discount_amount, + ) = _apply_cost_discount( base_cost=_final_cost, custom_llm_provider=custom_llm_provider, ) @@ -1976,9 +1994,7 @@ def default_video_cost_calculator( cost_info = litellm.model_cost[prefixed_model] if cost_info is None: - raise Exception( - f"Model not found in cost map for model={model}" - ) + raise Exception(f"Model not found in cost map for model={model}") # Check for video-specific cost per second first video_cost_per_second = cost_info.get("output_cost_per_video_per_second") @@ -2250,4 +2266,3 @@ def handle_realtime_stream_cost_calculation( total_cost = input_cost_per_token + output_cost_per_token return total_cost - diff --git a/litellm/evals/main.py b/litellm/evals/main.py index a39c2839150..e57c75bd9b6 100644 --- a/litellm/evals/main.py +++ b/litellm/evals/main.py @@ -152,16 +152,14 @@ def create_eval( custom_llm_provider = "openai" # Get provider config - evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ( - ProviderConfigManager.get_provider_evals_api_config( # type: ignore - provider=litellm.LlmProviders(custom_llm_provider), - ) + evals_api_provider_config: Optional[ + BaseEvalsAPIConfig + ] = ProviderConfigManager.get_provider_evals_api_config( # type: ignore + provider=litellm.LlmProviders(custom_llm_provider), ) if evals_api_provider_config is None: - raise ValueError( - f"CREATE eval is not supported for {custom_llm_provider}" - ) + raise ValueError(f"CREATE eval is not supported for {custom_llm_provider}") # Build create request create_request: CreateEvalRequest = { @@ -344,10 +342,10 @@ def list_evals( custom_llm_provider = "openai" # Get provider config - evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ( - ProviderConfigManager.get_provider_evals_api_config( # type: ignore - provider=litellm.LlmProviders(custom_llm_provider), - ) + evals_api_provider_config: Optional[ + BaseEvalsAPIConfig + ] = ProviderConfigManager.get_provider_evals_api_config( # type: ignore + provider=litellm.LlmProviders(custom_llm_provider), ) if evals_api_provider_config is None: @@ -513,10 +511,10 @@ def get_eval( custom_llm_provider = "openai" # Get provider config - evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ( - ProviderConfigManager.get_provider_evals_api_config( # type: ignore - provider=litellm.LlmProviders(custom_llm_provider), - ) + evals_api_provider_config: Optional[ + BaseEvalsAPIConfig + ] = ProviderConfigManager.get_provider_evals_api_config( # type: ignore + provider=litellm.LlmProviders(custom_llm_provider), ) if evals_api_provider_config is None: @@ -681,16 +679,14 @@ def update_eval( custom_llm_provider = "openai" # Get provider config - evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ( - ProviderConfigManager.get_provider_evals_api_config( # type: ignore - provider=litellm.LlmProviders(custom_llm_provider), - ) + evals_api_provider_config: Optional[ + BaseEvalsAPIConfig + ] = ProviderConfigManager.get_provider_evals_api_config( # type: ignore + provider=litellm.LlmProviders(custom_llm_provider), ) if evals_api_provider_config is None: - raise ValueError( - f"UPDATE eval is not supported for {custom_llm_provider}" - ) + raise ValueError(f"UPDATE eval is not supported for {custom_llm_provider}") # Build update request update_request: UpdateEvalRequest = {} @@ -701,20 +697,41 @@ def update_eval( if metadata is not None: # List of internal LiteLLM metadata keys that should NOT be sent to OpenAI internal_keys = { - "headers", "requester_metadata", "user_api_key_hash", "user_api_key_alias", - "user_api_key_spend", "user_api_key_max_budget", "user_api_key_team_id", - "user_api_key_user_id", "user_api_key_org_id", "user_api_key_team_alias", - "user_api_key_end_user_id", "user_api_key_user_email", "user_api_key_request_route", - "user_api_key_budget_reset_at", "user_api_key_auth_metadata", "user_api_key", - "user_api_end_user_max_budget", "user_api_key_auth", "litellm_api_version", - "global_max_parallel_requests", "user_api_key_team_max_budget", - "user_api_key_team_spend", "user_api_key_model_max_budget", - "user_api_key_user_spend", "user_api_key_user_max_budget", - "user_api_key_metadata", "endpoint", "litellm_parent_otel_span", - "requester_ip_address", "user_agent", + "headers", + "requester_metadata", + "user_api_key_hash", + "user_api_key_alias", + "user_api_key_spend", + "user_api_key_max_budget", + "user_api_key_team_id", + "user_api_key_user_id", + "user_api_key_org_id", + "user_api_key_team_alias", + "user_api_key_end_user_id", + "user_api_key_user_email", + "user_api_key_request_route", + "user_api_key_budget_reset_at", + "user_api_key_auth_metadata", + "user_api_key", + "user_api_end_user_max_budget", + "user_api_key_auth", + "litellm_api_version", + "global_max_parallel_requests", + "user_api_key_team_max_budget", + "user_api_key_team_spend", + "user_api_key_model_max_budget", + "user_api_key_user_spend", + "user_api_key_user_max_budget", + "user_api_key_metadata", + "endpoint", + "litellm_parent_otel_span", + "requester_ip_address", + "user_agent", } # Only include user-provided metadata keys - filtered_metadata = {k: v for k, v in metadata.items() if k not in internal_keys} + filtered_metadata = { + k: v for k, v in metadata.items() if k not in internal_keys + } if filtered_metadata: # Only add if there's user metadata update_request["metadata"] = filtered_metadata @@ -730,7 +747,11 @@ def update_eval( # Transform request api_base = litellm_params.api_base or DEFAULT_OPENAI_API_BASE - url, headers, request_body = evals_api_provider_config.transform_update_eval_request( + ( + url, + headers, + request_body, + ) = evals_api_provider_config.transform_update_eval_request( eval_id=eval_id, update_request=update_request, api_base=api_base, @@ -868,10 +889,10 @@ def delete_eval( custom_llm_provider = "openai" # Get provider config - evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ( - ProviderConfigManager.get_provider_evals_api_config( # type: ignore - provider=litellm.LlmProviders(custom_llm_provider), - ) + evals_api_provider_config: Optional[ + BaseEvalsAPIConfig + ] = ProviderConfigManager.get_provider_evals_api_config( # type: ignore + provider=litellm.LlmProviders(custom_llm_provider), ) if evals_api_provider_config is None: @@ -1021,10 +1042,10 @@ def cancel_eval( custom_llm_provider = "openai" # Get provider config - evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ( - ProviderConfigManager.get_provider_evals_api_config( # type: ignore - provider=litellm.LlmProviders(custom_llm_provider), - ) + evals_api_provider_config: Optional[ + BaseEvalsAPIConfig + ] = ProviderConfigManager.get_provider_evals_api_config( # type: ignore + provider=litellm.LlmProviders(custom_llm_provider), ) if evals_api_provider_config is None: @@ -1038,7 +1059,11 @@ def cancel_eval( # Transform request api_base = litellm_params.api_base or DEFAULT_OPENAI_API_BASE - url, headers, request_body = evals_api_provider_config.transform_cancel_eval_request( + ( + url, + headers, + request_body, + ) = evals_api_provider_config.transform_cancel_eval_request( eval_id=eval_id, api_base=api_base, litellm_params=litellm_params, @@ -1199,16 +1224,14 @@ def create_run( custom_llm_provider = "openai" # Get provider config - evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ( - ProviderConfigManager.get_provider_evals_api_config( # type: ignore - provider=litellm.LlmProviders(custom_llm_provider), - ) + evals_api_provider_config: Optional[ + BaseEvalsAPIConfig + ] = ProviderConfigManager.get_provider_evals_api_config( # type: ignore + provider=litellm.LlmProviders(custom_llm_provider), ) if evals_api_provider_config is None: - raise ValueError( - f"CREATE run is not supported for {custom_llm_provider}" - ) + raise ValueError(f"CREATE run is not supported for {custom_llm_provider}") # Build create request create_request: CreateRunRequest = { @@ -1388,10 +1411,10 @@ def list_runs( custom_llm_provider = "openai" # Get provider config - evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ( - ProviderConfigManager.get_provider_evals_api_config( # type: ignore - provider=litellm.LlmProviders(custom_llm_provider), - ) + evals_api_provider_config: Optional[ + BaseEvalsAPIConfig + ] = ProviderConfigManager.get_provider_evals_api_config( # type: ignore + provider=litellm.LlmProviders(custom_llm_provider), ) if evals_api_provider_config is None: @@ -1561,10 +1584,10 @@ def get_run( custom_llm_provider = "openai" # Get provider config - evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ( - ProviderConfigManager.get_provider_evals_api_config( # type: ignore - provider=litellm.LlmProviders(custom_llm_provider), - ) + evals_api_provider_config: Optional[ + BaseEvalsAPIConfig + ] = ProviderConfigManager.get_provider_evals_api_config( # type: ignore + provider=litellm.LlmProviders(custom_llm_provider), ) if evals_api_provider_config is None: @@ -1720,10 +1743,10 @@ def cancel_run( custom_llm_provider = "openai" # Get provider config - evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ( - ProviderConfigManager.get_provider_evals_api_config( # type: ignore - provider=litellm.LlmProviders(custom_llm_provider), - ) + evals_api_provider_config: Optional[ + BaseEvalsAPIConfig + ] = ProviderConfigManager.get_provider_evals_api_config( # type: ignore + provider=litellm.LlmProviders(custom_llm_provider), ) if evals_api_provider_config is None: @@ -1737,7 +1760,11 @@ def cancel_run( # Transform request api_base = litellm_params.api_base or DEFAULT_OPENAI_API_BASE - url, headers, request_body = evals_api_provider_config.transform_cancel_run_request( + ( + url, + headers, + request_body, + ) = evals_api_provider_config.transform_cancel_run_request( eval_id=eval_id, run_id=run_id, api_base=api_base, @@ -1884,10 +1911,10 @@ def delete_run( custom_llm_provider = "openai" # Get provider config - evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ( - ProviderConfigManager.get_provider_evals_api_config( # type: ignore - provider=litellm.LlmProviders(custom_llm_provider), - ) + evals_api_provider_config: Optional[ + BaseEvalsAPIConfig + ] = ProviderConfigManager.get_provider_evals_api_config( # type: ignore + provider=litellm.LlmProviders(custom_llm_provider), ) if evals_api_provider_config is None: @@ -1901,7 +1928,11 @@ def delete_run( # Transform request api_base = litellm_params.api_base or DEFAULT_OPENAI_API_BASE - url, headers, request_body = evals_api_provider_config.transform_delete_run_request( + ( + url, + headers, + request_body, + ) = evals_api_provider_config.transform_delete_run_request( eval_id=eval_id, run_id=run_id, api_base=api_base, diff --git a/litellm/exceptions.py b/litellm/exceptions.py index b36d4ef877c..abdba09dd8d 100644 --- a/litellm/exceptions.py +++ b/litellm/exceptions.py @@ -25,9 +25,7 @@ def _get_minimal_error_response() -> httpx.Response: if _MINIMAL_ERROR_RESPONSE is None: _MINIMAL_ERROR_RESPONSE = httpx.Response( status_code=400, - request=httpx.Request( - method="GET", url="https://litellm.ai" - ), + request=httpx.Request(method="GET", url="https://litellm.ai"), ) return _MINIMAL_ERROR_RESPONSE @@ -996,7 +994,7 @@ class MidStreamFallbackError(ServiceUnavailableError): # type: ignore max_retries=self.max_retries, num_retries=self.num_retries, ) - + # Restore the propagated status and original response/request objects self.status_code = int(original_status) if original_status is not None else 503 self.response = _saved_response diff --git a/litellm/experimental_mcp_client/client.py b/litellm/experimental_mcp_client/client.py index 30a1ac20d0c..a638a28aba3 100644 --- a/litellm/experimental_mcp_client/client.py +++ b/litellm/experimental_mcp_client/client.py @@ -4,7 +4,18 @@ LiteLLM Proxy uses this MCP Client to connnect to other MCP servers. import asyncio import base64 -from typing import Any, Awaitable, Callable, Dict, Generator, List, Optional, Tuple, TypeVar, Union +from typing import ( + Any, + Awaitable, + Callable, + Dict, + Generator, + List, + Optional, + Tuple, + TypeVar, + Union, +) import httpx from mcp import ClientSession, ReadResourceResult, Resource, StdioServerParameters @@ -14,7 +25,10 @@ from mcp.client.stdio import stdio_client streamable_http_client: Optional[Any] = None try: import mcp.client.streamable_http as streamable_http_module # type: ignore - streamable_http_client = getattr(streamable_http_module, "streamable_http_client", None) + + streamable_http_client = getattr( + streamable_http_module, "streamable_http_client", None + ) except ImportError: pass from mcp.types import CallToolRequestParams as MCPCallToolRequestParams @@ -188,12 +202,15 @@ class MCPClient: if self.transport_type == MCPTransport.sse: headers = self._get_auth_headers() httpx_client_factory = self._create_httpx_client_factory() - return sse_client( - url=self.server_url, - timeout=self.timeout, - headers=headers, - httpx_client_factory=httpx_client_factory, - ), None + return ( + sse_client( + url=self.server_url, + timeout=self.timeout, + headers=headers, + httpx_client_factory=httpx_client_factory, + ), + None, + ) # HTTP transport (default) if streamable_http_client is None: @@ -201,12 +218,10 @@ class MCPClient: "streamable_http_client is not available. " "Please install mcp with HTTP support." ) - + headers = self._get_auth_headers() httpx_client_factory = self._create_httpx_client_factory() - verbose_logger.debug( - "litellm headers for streamable_http_client: %s", headers - ) + verbose_logger.debug("litellm headers for streamable_http_client: %s", headers) http_client = httpx_client_factory( headers=headers, timeout=httpx.Timeout(self.timeout), @@ -392,7 +407,7 @@ class MCPClient: async def call_tool( self, call_tool_request_params: MCPCallToolRequestParams, - host_progress_callback: Optional[Callable] = None + host_progress_callback: Optional[Callable] = None, ) -> MCPCallToolResult: """ Call an MCP Tool. @@ -401,13 +416,15 @@ class MCPClient: f"MCP client calling tool '{call_tool_request_params.name}' with arguments: {call_tool_request_params.arguments}" ) - async def on_progress(progress: float, total: float | None, message: str | None): + async def on_progress( + progress: float, total: float | None, message: str | None + ): percentage = (progress / total * 100) if total else 0 verbose_logger.info( f"MCP Tool '{call_tool_request_params.name}' progress: " f"{progress}/{total} ({percentage:.0f}%) - {message or ''}" ) - + # Forward to Host if callback provided if host_progress_callback: try: @@ -421,8 +438,8 @@ class MCPClient: name=call_tool_request_params.name, arguments=call_tool_request_params.arguments, progress_callback=on_progress, - ) + try: tool_result = await self.run_with_session(_call_tool_operation) verbose_logger.info( diff --git a/litellm/experimental_mcp_client/tools.py b/litellm/experimental_mcp_client/tools.py index b716e3171e7..bd42f7e7111 100644 --- a/litellm/experimental_mcp_client/tools.py +++ b/litellm/experimental_mcp_client/tools.py @@ -18,7 +18,7 @@ from litellm.types.utils import ChatCompletionMessageToolCall def transform_mcp_tool_to_openai_tool(mcp_tool: MCPTool) -> ChatCompletionToolParam: """Convert an MCP tool to an OpenAI tool.""" normalized_parameters = _normalize_mcp_input_schema(mcp_tool.inputSchema) - + return ChatCompletionToolParam( type="function", function=FunctionDefinition( @@ -33,41 +33,39 @@ def transform_mcp_tool_to_openai_tool(mcp_tool: MCPTool) -> ChatCompletionToolPa def _normalize_mcp_input_schema(input_schema: dict) -> dict: """ Normalize MCP input schema to ensure it's valid for OpenAI function calling. - + OpenAI requires that function parameters have: - type: 'object' - properties: dict (can be empty) - additionalProperties: false (recommended) """ if not input_schema: - return { - "type": "object", - "properties": {}, - "additionalProperties": False - } - + return {"type": "object", "properties": {}, "additionalProperties": False} + # Make a copy to avoid modifying the original normalized_schema = dict(input_schema) - + # Ensure type is 'object' if "type" not in normalized_schema: normalized_schema["type"] = "object" - + # Ensure properties exists (can be empty) if "properties" not in normalized_schema: normalized_schema["properties"] = {} - + # Add additionalProperties if not present (recommended by OpenAI) if "additionalProperties" not in normalized_schema: normalized_schema["additionalProperties"] = False - + return normalized_schema -def transform_mcp_tool_to_openai_responses_api_tool(mcp_tool: MCPTool) -> FunctionToolParam: +def transform_mcp_tool_to_openai_responses_api_tool( + mcp_tool: MCPTool, +) -> FunctionToolParam: """Convert an MCP tool to an OpenAI Responses API tool.""" normalized_parameters = _normalize_mcp_input_schema(mcp_tool.inputSchema) - + return FunctionToolParam( name=mcp_tool.name, parameters=normalized_parameters, @@ -76,6 +74,7 @@ def transform_mcp_tool_to_openai_responses_api_tool(mcp_tool: MCPTool) -> Functi description=mcp_tool.description or "", ) + async def load_mcp_tools( session: ClientSession, format: Literal["mcp", "openai"] = "mcp" ) -> Union[List[MCPTool], List[ChatCompletionToolParam]]: diff --git a/litellm/files/main.py b/litellm/files/main.py index 2a10789e741..f7c89e0ba3b 100644 --- a/litellm/files/main.py +++ b/litellm/files/main.py @@ -14,11 +14,30 @@ from typing import Any, Coroutine, Dict, Literal, Optional, Union, cast import httpx +# Type aliases for provider parameters +FileCreateProvider = Literal[ + "openai", + "azure", + "gemini", + "vertex_ai", + "bedrock", + "hosted_vllm", + "manus", + "anthropic", +] +FileRetrieveProvider = Literal[ + "openai", "azure", "gemini", "vertex_ai", "hosted_vllm", "manus", "anthropic" +] +FileDeleteProvider = Literal["openai", "azure", "gemini", "manus", "anthropic"] +FileListProvider = Literal["openai", "azure", "manus", "anthropic"] +FileContentProvider = Literal[ + "openai", "azure", "vertex_ai", "bedrock", "hosted_vllm", "anthropic", "manus" +] + import litellm from litellm import get_secret_str from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj -from litellm.llms.anthropic.files.handler import AnthropicFilesHandler from litellm.llms.azure.common_utils import get_azure_credentials from litellm.llms.azure.files.handler import AzureOpenAIFilesAPI from litellm.llms.bedrock.files.handler import BedrockFilesHandler @@ -54,16 +73,15 @@ openai_files_instance = OpenAIFilesAPI() azure_files_instance = AzureOpenAIFilesAPI() vertex_ai_files_instance = VertexAIFilesHandler() bedrock_files_instance = BedrockFilesHandler() -anthropic_files_instance = AnthropicFilesHandler() ################################################# @client async def acreate_file( file: FileTypes, - purpose: Literal["assistants", "batch", "fine-tune"], + purpose: Literal["assistants", "batch", "fine-tune", "messages"], expires_after: Optional[FileExpiresAfter] = None, - custom_llm_provider: Literal["openai", "azure", "gemini", "vertex_ai", "bedrock", "hosted_vllm", "manus"] = "openai", + custom_llm_provider: FileCreateProvider = "openai", extra_headers: Optional[Dict[str, str]] = None, extra_body: Optional[Dict[str, str]] = None, **kwargs, @@ -106,9 +124,9 @@ async def acreate_file( @client def create_file( file: FileTypes, - purpose: Literal["assistants", "batch", "fine-tune"], + purpose: Literal["assistants", "batch", "fine-tune", "messages"], expires_after: Optional[FileExpiresAfter] = None, - custom_llm_provider: Optional[Literal["openai", "azure", "gemini", "vertex_ai", "bedrock", "hosted_vllm", "manus"]] = None, + custom_llm_provider: Optional[FileCreateProvider] = None, extra_headers: Optional[Dict[str, str]] = None, extra_body: Optional[Dict[str, str]] = None, **kwargs, @@ -218,7 +236,7 @@ def create_file( ) else: raise litellm.exceptions.BadRequestError( - message="LiteLLM doesn't support {} for 'create_file'. Only ['openai', 'azure', 'vertex_ai', 'manus'] are supported.".format( + message="LiteLLM doesn't support {} for 'create_file'. Only ['openai', 'azure', 'vertex_ai', 'manus', 'anthropic'] are supported.".format( custom_llm_provider ), model="n/a", @@ -237,7 +255,7 @@ def create_file( @client async def afile_retrieve( file_id: str, - custom_llm_provider: Literal["openai", "azure", "gemini", "vertex_ai", "hosted_vllm", "manus"] = "openai", + custom_llm_provider: FileRetrieveProvider = "openai", extra_headers: Optional[Dict[str, str]] = None, extra_body: Optional[Dict[str, str]] = None, **kwargs, @@ -278,7 +296,7 @@ async def afile_retrieve( @client def file_retrieve( file_id: str, - custom_llm_provider: Literal["openai", "azure", "gemini", "vertex_ai", "hosted_vllm", "manus"] = "openai", + custom_llm_provider: FileRetrieveProvider = "openai", extra_headers: Optional[Dict[str, str]] = None, extra_body: Optional[Dict[str, str]] = None, **kwargs, @@ -348,22 +366,25 @@ def file_retrieve( litellm_params_dict = get_litellm_params(**kwargs) litellm_params_dict["api_key"] = optional_params.api_key litellm_params_dict["api_base"] = optional_params.api_base - + logging_obj = kwargs.get("litellm_logging_obj") if logging_obj is None: from litellm.litellm_core_utils.litellm_logging import ( Logging as LiteLLMLoggingObj, ) + logging_obj = LiteLLMLoggingObj( model="", messages=[], stream=False, call_type="afile_retrieve" if _is_async else "file_retrieve", start_time=time.time(), - litellm_call_id=kwargs.get("litellm_call_id", str(uuid_module.uuid4())), + litellm_call_id=kwargs.get( + "litellm_call_id", str(uuid_module.uuid4()) + ), function_id=str(kwargs.get("id") or ""), ) - + client = kwargs.get("client") response = base_llm_http_handler.retrieve_file( file_id=file_id, @@ -382,7 +403,7 @@ def file_retrieve( ) else: raise litellm.exceptions.BadRequestError( - message="LiteLLM doesn't support {} for 'file_retrieve'. Only 'openai', 'azure', and 'manus' are supported.".format( + message="LiteLLM doesn't support {} for 'file_retrieve'. Only 'openai', 'azure', 'manus', and 'anthropic' are supported.".format( custom_llm_provider ), model="n/a", @@ -403,7 +424,7 @@ def file_retrieve( @client async def afile_delete( file_id: str, - custom_llm_provider: Literal["openai", "azure", "gemini", "manus"] = "openai", + custom_llm_provider: FileDeleteProvider = "openai", extra_headers: Optional[Dict[str, str]] = None, extra_body: Optional[Dict[str, str]] = None, **kwargs, @@ -447,7 +468,7 @@ async def afile_delete( def file_delete( file_id: str, model: Optional[str] = None, - custom_llm_provider: Union[Literal["openai", "azure", "gemini", "manus"], str] = "openai", + custom_llm_provider: Union[FileDeleteProvider, str] = "openai", extra_headers: Optional[Dict[str, str]] = None, extra_body: Optional[Dict[str, str]] = None, **kwargs, @@ -525,22 +546,25 @@ def file_delete( if provider_config is not None: litellm_params_dict["api_key"] = optional_params.api_key litellm_params_dict["api_base"] = optional_params.api_base - + logging_obj = kwargs.get("litellm_logging_obj") if logging_obj is None: from litellm.litellm_core_utils.litellm_logging import ( Logging as LiteLLMLoggingObj, ) + logging_obj = LiteLLMLoggingObj( model="", messages=[], stream=False, call_type="afile_delete" if _is_async else "file_delete", start_time=time.time(), - litellm_call_id=kwargs.get("litellm_call_id", str(uuid_module.uuid4())), + litellm_call_id=kwargs.get( + "litellm_call_id", str(uuid_module.uuid4()) + ), function_id=str(kwargs.get("id") or ""), ) - + response = base_llm_http_handler.delete_file( file_id=file_id, provider_config=provider_config, @@ -558,7 +582,7 @@ def file_delete( ) else: raise litellm.exceptions.BadRequestError( - message="LiteLLM doesn't support {} for 'file_delete'. Only 'openai', 'azure', 'gemini', and 'manus' are supported.".format( + message="LiteLLM doesn't support {} for 'file_delete'. Only 'openai', 'azure', 'gemini', 'manus', and 'anthropic' are supported.".format( custom_llm_provider ), model="n/a", @@ -577,7 +601,7 @@ def file_delete( # List files @client async def afile_list( - custom_llm_provider: Literal["openai", "azure", "manus"] = "openai", + custom_llm_provider: FileListProvider = "openai", purpose: Optional[str] = None, extra_headers: Optional[Dict[str, str]] = None, extra_body: Optional[Dict[str, str]] = None, @@ -618,7 +642,7 @@ async def afile_list( @client def file_list( - custom_llm_provider: Literal["openai", "azure", "manus"] = "openai", + custom_llm_provider: FileListProvider = "openai", purpose: Optional[str] = None, extra_headers: Optional[Dict[str, str]] = None, extra_body: Optional[Dict[str, str]] = None, @@ -648,7 +672,7 @@ def file_list( timeout = 600.0 _is_async = kwargs.pop("is_async", False) is True - + # Check if provider has a custom files config (e.g., Manus, Bedrock, Vertex AI) provider_config = ProviderConfigManager.get_provider_files_config( model="", @@ -658,22 +682,25 @@ def file_list( litellm_params_dict = get_litellm_params(**kwargs) litellm_params_dict["api_key"] = optional_params.api_key litellm_params_dict["api_base"] = optional_params.api_base - + logging_obj = kwargs.get("litellm_logging_obj") if logging_obj is None: from litellm.litellm_core_utils.litellm_logging import ( Logging as LiteLLMLoggingObj, ) + logging_obj = LiteLLMLoggingObj( model="", messages=[], stream=False, call_type="afile_list" if _is_async else "file_list", start_time=time.time(), - litellm_call_id=kwargs.get("litellm_call_id", str(uuid_module.uuid4())), + litellm_call_id=kwargs.get( + "litellm_call_id", str(uuid_module.uuid4()) + ), function_id=str(kwargs.get("id", "")), ) - + client = kwargs.get("client") response = base_llm_http_handler.list_files( purpose=purpose, @@ -723,7 +750,7 @@ def file_list( ) else: raise litellm.exceptions.BadRequestError( - message="LiteLLM doesn't support {} for 'file_list'. Only 'openai', 'azure', and 'manus' are supported.".format( + message="LiteLLM doesn't support {} for 'file_list'. Only 'openai', 'azure', 'manus', and 'anthropic' are supported.".format( custom_llm_provider ), model="n/a", @@ -742,7 +769,7 @@ def file_list( @client async def afile_content( file_id: str, - custom_llm_provider: Literal["openai", "azure", "vertex_ai", "bedrock", "hosted_vllm", "anthropic", "manus"] = "openai", + custom_llm_provider: FileContentProvider = "openai", extra_headers: Optional[Dict[str, str]] = None, extra_body: Optional[Dict[str, str]] = None, **kwargs, @@ -786,9 +813,7 @@ async def afile_content( def file_content( file_id: str, model: Optional[str] = None, - custom_llm_provider: Optional[ - Union[Literal["openai", "azure", "vertex_ai", "bedrock", "hosted_vllm", "anthropic", "manus"], str] - ] = None, + custom_llm_provider: Optional[Union[FileContentProvider, str]] = None, extra_headers: Optional[Dict[str, str]] = None, extra_body: Optional[Dict[str, str]] = None, **kwargs, @@ -834,15 +859,43 @@ def file_content( _is_async = kwargs.pop("afile_content", False) is True - # Check if this is an Anthropic batch results request - if custom_llm_provider == "anthropic": - response = anthropic_files_instance.file_content( - _is_async=_is_async, + # Check if provider has a custom files config (e.g., Anthropic, Manus) + provider_config = ProviderConfigManager.get_provider_files_config( + model="", + provider=LlmProviders(custom_llm_provider), + ) + if provider_config is not None: + litellm_params_dict["api_key"] = optional_params.api_key + litellm_params_dict["api_base"] = optional_params.api_base + + logging_obj = kwargs.get("litellm_logging_obj") + if logging_obj is None: + logging_obj = LiteLLMLoggingObj( + model="", + messages=[], + stream=False, + call_type="afile_content" if _is_async else "file_content", + start_time=time.time(), + litellm_call_id=kwargs.get( + "litellm_call_id", str(uuid_module.uuid4()) + ), + function_id=str(kwargs.get("id") or ""), + ) + + response = base_llm_http_handler.retrieve_file_content( file_content_request=_file_content_request, - api_base=optional_params.api_base, - api_key=optional_params.api_key, + provider_config=provider_config, + litellm_params=litellm_params_dict, + headers=extra_headers or {}, + logging_obj=logging_obj, + _is_async=_is_async, + client=( + client + if client is not None + and isinstance(client, (HTTPHandler, AsyncHTTPHandler)) + else None + ), timeout=timeout, - max_retries=optional_params.max_retries, ) return response @@ -915,7 +968,7 @@ def file_content( ) else: raise litellm.exceptions.BadRequestError( - message="LiteLLM doesn't support {} for 'file_content'. Supported providers are 'openai', 'azure', 'vertex_ai', 'bedrock', 'manus'.".format( + message="LiteLLM doesn't support {} for 'file_content'. Supported providers are 'openai', 'azure', 'vertex_ai', 'bedrock', 'manus', 'anthropic'.".format( custom_llm_provider ), model="n/a", diff --git a/litellm/files/utils.py b/litellm/files/utils.py index a56a29467d9..a2b9a42c154 100644 --- a/litellm/files/utils.py +++ b/litellm/files/utils.py @@ -8,17 +8,22 @@ class FilesAPIUtils: """ Utils for files API interface on litellm """ + @staticmethod - def is_batch_jsonl_file(create_file_data: CreateFileRequest, extracted_file_data: ExtractedFileData) -> bool: + def is_batch_jsonl_file( + create_file_data: CreateFileRequest, extracted_file_data: ExtractedFileData + ) -> bool: """ Check if the file is a batch jsonl file """ return ( create_file_data.get("purpose") == "batch" - and FilesAPIUtils.valid_content_type(extracted_file_data.get("content_type")) + and FilesAPIUtils.valid_content_type( + extracted_file_data.get("content_type") + ) and extracted_file_data.get("content") is not None ) - + @staticmethod def valid_content_type(content_type: Optional[str]) -> bool: """ diff --git a/litellm/fine_tuning/main.py b/litellm/fine_tuning/main.py index 93fa56ff971..08373cda782 100644 --- a/litellm/fine_tuning/main.py +++ b/litellm/fine_tuning/main.py @@ -41,34 +41,34 @@ def _prepare_azure_extra_body( ) -> Dict[str, Any]: """ Prepare extra_body for Azure fine-tuning API by combining Azure-specific parameters. - + Azure fine-tuning API accepts additional parameters beyond the standard OpenAI spec: - trainingType: Type of training (e.g., 1 for supervised fine-tuning) - prompt_loss_weight: Weight for prompt loss in training - + These parameters must be passed in the extra_body field when calling the Azure OpenAI SDK. - + Args: extra_body: Optional existing extra_body dict kwargs: Request kwargs that may contain Azure-specific parameters azure_specific_hyperparams: Dict of Azure-specific hyperparameters already extracted - + Returns: Dict containing all Azure-specific parameters to be passed in extra_body """ if extra_body is None: extra_body = {} - + # Azure-specific root-level parameters azure_specific_params = ["trainingType"] for param in azure_specific_params: if param in kwargs: extra_body[param] = kwargs[param] - + # Add Azure-specific hyperparameters if azure_specific_hyperparams: extra_body.update(azure_specific_hyperparams) - + return extra_body @@ -126,7 +126,9 @@ async def acreate_fine_tuning_job( raise e -def _build_fine_tuning_job_data(model, training_file, hyperparameters, suffix, validation_file, integrations, seed): +def _build_fine_tuning_job_data( + model, training_file, hyperparameters, suffix, validation_file, integrations, seed +): return FineTuningJobCreate( model=model, training_file=training_file, @@ -177,7 +179,7 @@ def create_fine_tuning_job( # handle hyperparameters hyperparameters = hyperparameters or {} # original hyperparameters - + # For Azure, extract Azure-specific hyperparameters before creating OpenAI-spec hyperparameters azure_specific_hyperparams = {} if custom_llm_provider == "azure": @@ -185,7 +187,7 @@ def create_fine_tuning_job( for key in azure_hyperparameter_keys: if key in hyperparameters: azure_specific_hyperparams[key] = hyperparameters.pop(key) - + _oai_hyperparameters: Hyperparameters = Hyperparameters( **hyperparameters ) # Typed Hyperparameters for OpenAI Spec @@ -219,7 +221,13 @@ def create_fine_tuning_job( ) create_fine_tuning_job_data_dict = _build_fine_tuning_job_data( - model, training_file, _oai_hyperparameters, suffix, validation_file, integrations, seed, + model, + training_file, + _oai_hyperparameters, + suffix, + validation_file, + integrations, + seed, ).model_dump(exclude_none=True) response = openai_fine_tuning_apis_instance.create_fine_tuning_job( @@ -258,12 +266,20 @@ def create_fine_tuning_job( extra_body.pop("azure_ad_token", None) else: get_secret_str("AZURE_AD_TOKEN") # type: ignore - + # Prepare Azure-specific parameters for extra_body - extra_body = _prepare_azure_extra_body(extra_body, kwargs, azure_specific_hyperparams) - + extra_body = _prepare_azure_extra_body( + extra_body, kwargs, azure_specific_hyperparams + ) + create_fine_tuning_job_data_dict = _build_fine_tuning_job_data( - model, training_file, _oai_hyperparameters, suffix, validation_file, integrations, seed, + model, + training_file, + _oai_hyperparameters, + suffix, + validation_file, + integrations, + seed, ).model_dump(exclude_none=True) # Add extra_body if it has Azure-specific parameters @@ -298,7 +314,13 @@ def create_fine_tuning_job( response = vertex_fine_tuning_apis_instance.create_fine_tuning_job( _is_async=_is_async, create_fine_tuning_job_data=_build_fine_tuning_job_data( - model, training_file, _oai_hyperparameters, suffix, validation_file, integrations, seed, + model, + training_file, + _oai_hyperparameters, + suffix, + validation_file, + integrations, + seed, ), vertex_credentials=vertex_credentials, vertex_project=vertex_ai_project, diff --git a/litellm/google_genai/__init__.py b/litellm/google_genai/__init__.py index faeb1f227d1..ca7b547c440 100644 --- a/litellm/google_genai/__init__.py +++ b/litellm/google_genai/__init__.py @@ -13,7 +13,7 @@ from .main import ( __all__ = [ "generate_content", - "agenerate_content", + "agenerate_content", "generate_content_stream", "agenerate_content_stream", -] \ No newline at end of file +] diff --git a/litellm/google_genai/adapters/__init__.py b/litellm/google_genai/adapters/__init__.py index 96ff777ebe8..bfa9e712678 100644 --- a/litellm/google_genai/adapters/__init__.py +++ b/litellm/google_genai/adapters/__init__.py @@ -13,7 +13,7 @@ from .handler import GenerateContentToCompletionHandler from .transformation import GoogleGenAIAdapter, GoogleGenAIStreamWrapper __all__ = [ - "GoogleGenAIAdapter", + "GoogleGenAIAdapter", "GoogleGenAIStreamWrapper", - "GenerateContentToCompletionHandler" -] \ No newline at end of file + "GenerateContentToCompletionHandler", +] diff --git a/litellm/google_genai/main.py b/litellm/google_genai/main.py index 9ec56c37170..a937a35da25 100644 --- a/litellm/google_genai/main.py +++ b/litellm/google_genai/main.py @@ -168,7 +168,9 @@ class GenerateContentHelper: ) ) # Extract systemInstruction from kwargs to pass to transform - system_instruction = kwargs.get("systemInstruction") or kwargs.get("system_instruction") + system_instruction = kwargs.get("systemInstruction") or kwargs.get( + "system_instruction" + ) request_body = ( generate_content_provider_config.transform_generate_content_request( model=model, @@ -318,7 +320,9 @@ def generate_content( ) # Extract systemInstruction from kwargs to pass to handler - system_instruction = kwargs.get("systemInstruction") or kwargs.get("system_instruction") + system_instruction = kwargs.get("systemInstruction") or kwargs.get( + "system_instruction" + ) # Check if we should use the adapter (when provider config is None) if setup_result.generate_content_provider_config is None: @@ -407,7 +411,9 @@ async def agenerate_content_stream( ) # Extract systemInstruction from kwargs to pass to handler - system_instruction = kwargs.get("systemInstruction") or kwargs.get("system_instruction") + system_instruction = kwargs.get("systemInstruction") or kwargs.get( + "system_instruction" + ) # Check if we should use the adapter (when provider config is None) if setup_result.generate_content_provider_config is None: diff --git a/litellm/google_genai/streaming_iterator.py b/litellm/google_genai/streaming_iterator.py index d0fa5a0be6c..8cb2ee09370 100644 --- a/litellm/google_genai/streaming_iterator.py +++ b/litellm/google_genai/streaming_iterator.py @@ -17,6 +17,7 @@ else: GLOBAL_PASS_THROUGH_SUCCESS_HANDLER_OBJ = PassThroughEndpointLogging() + class BaseGoogleGenAIGenerateContentStreamingIterator: """ Base class for Google GenAI Generate Content streaming iterators that provides common logic @@ -42,6 +43,7 @@ class BaseGoogleGenAIGenerateContentStreamingIterator: from litellm.proxy.pass_through_endpoints.streaming_handler import ( PassThroughStreamingHandler, ) + end_time = datetime.now() asyncio.create_task( PassThroughStreamingHandler._route_streaming_logging_to_handler( @@ -58,7 +60,9 @@ class BaseGoogleGenAIGenerateContentStreamingIterator: ) -class GoogleGenAIGenerateContentStreamingIterator(BaseGoogleGenAIGenerateContentStreamingIterator): +class GoogleGenAIGenerateContentStreamingIterator( + BaseGoogleGenAIGenerateContentStreamingIterator +): """ Streaming iterator specifically for Google GenAI generate content API. """ @@ -105,10 +109,14 @@ class GoogleGenAIGenerateContentStreamingIterator(BaseGoogleGenAIGenerateContent async def __anext__(self): # This should not be used for sync responses # If you need async iteration, use AsyncGoogleGenAIGenerateContentStreamingIterator - raise NotImplementedError("Use AsyncGoogleGenAIGenerateContentStreamingIterator for async iteration") + raise NotImplementedError( + "Use AsyncGoogleGenAIGenerateContentStreamingIterator for async iteration" + ) -class AsyncGoogleGenAIGenerateContentStreamingIterator(BaseGoogleGenAIGenerateContentStreamingIterator): +class AsyncGoogleGenAIGenerateContentStreamingIterator( + BaseGoogleGenAIGenerateContentStreamingIterator +): """ Async streaming iterator specifically for Google GenAI generate content API. """ @@ -148,4 +156,4 @@ class AsyncGoogleGenAIGenerateContentStreamingIterator(BaseGoogleGenAIGenerateCo return chunk except StopAsyncIteration: await self._handle_async_streaming_logging() - raise StopAsyncIteration \ No newline at end of file + raise StopAsyncIteration diff --git a/litellm/images/main.py b/litellm/images/main.py index 553aa26da98..a3ae97b57dd 100644 --- a/litellm/images/main.py +++ b/litellm/images/main.py @@ -86,7 +86,6 @@ def _get_ImageEditRequestUtils() -> "ImageEditRequestUtils": return _ImageEditRequestUtils_cache - ##### Image Generation ####################### @client async def aimage_generation(*args, **kwargs) -> ImageResponse: @@ -212,10 +211,7 @@ def image_generation( # noqa: PLR0915 api_version: Optional[str] = None, custom_llm_provider=None, **kwargs, -) -> Union[ - ImageResponse, - Coroutine[Any, Any, ImageResponse], -]: +) -> Union[ImageResponse, Coroutine[Any, Any, ImageResponse],]: """ Maps the https://api.openai.com/v1/images/generations endpoint. @@ -346,7 +342,7 @@ def image_generation( # noqa: PLR0915 azure_ad_token = optional_params.pop( "azure_ad_token", None ) or get_secret_str("AZURE_AD_TOKEN") - + # Create azure_ad_token_provider from tenant_id, client_id, client_secret if not already provided if azure_ad_token_provider is None: from litellm.llms.azure.common_utils import ( @@ -357,8 +353,11 @@ def image_generation( # noqa: PLR0915 tenant_id = litellm_params_dict.get("tenant_id") client_id = litellm_params_dict.get("client_id") client_secret = litellm_params_dict.get("client_secret") - azure_scope = litellm_params_dict.get("azure_scope") or "https://cognitiveservices.azure.com/.default" - + azure_scope = ( + litellm_params_dict.get("azure_scope") + or "https://cognitiveservices.azure.com/.default" + ) + # Create token provider if credentials are available if tenant_id and client_id and client_secret: azure_ad_token_provider = get_azure_ad_token_from_entra_id( @@ -375,7 +374,7 @@ def image_generation( # noqa: PLR0915 # Azure AD authentication will use Authorization header instead if api_key is not None: default_headers["api-key"] = api_key - + for k, v in default_headers.items(): if k not in headers: headers[k] = v @@ -462,7 +461,7 @@ def image_generation( # noqa: PLR0915 # Azure AD authentication will use Authorization header instead if api_key is not None: default_headers["api-key"] = api_key - + for k, v in default_headers.items(): if k not in headers: headers[k] = v @@ -738,7 +737,7 @@ def image_variation( @client def image_edit( # noqa: PLR0915 image: Optional[Union[FileTypes, List[FileTypes]]] = None, - prompt: Optional[str]= None, + prompt: Optional[str] = None, model: Optional[str] = None, mask: Optional[str] = None, n: Optional[int] = None, @@ -762,23 +761,23 @@ def image_edit( # noqa: PLR0915 local_vars = locals() try: openai_params = [ - "user", - "request_timeout", - "api_base", - "api_version", - "api_key", - "deployment_id", - "organization", - "base_url", - "default_headers", - "timeout", - "max_retries", - "n", - "quality", - "size", - "style", - "async_call", - ] + "user", + "request_timeout", + "api_base", + "api_version", + "api_key", + "deployment_id", + "organization", + "base_url", + "default_headers", + "timeout", + "max_retries", + "n", + "quality", + "size", + "style", + "async_call", + ] litellm_params_list = all_litellm_params default_params = openai_params + litellm_params_list non_default_params = { @@ -791,7 +790,9 @@ def image_edit( # noqa: PLR0915 _is_async = kwargs.pop("async_call", False) is True # add images / or return a single image - images = image if isinstance(image, list) else ([image] if image is not None else []) + images = ( + image if isinstance(image, list) else ([image] if image is not None else []) + ) headers_from_kwargs = kwargs.get("headers") merged_extra_headers: Dict[str, Any] = {} @@ -864,11 +865,11 @@ def image_edit( # noqa: PLR0915 ) # get provider config - image_edit_provider_config: Optional[BaseImageEditConfig] = ( - ProviderConfigManager.get_provider_image_edit_config( - model=model, - provider=litellm.LlmProviders(custom_llm_provider), - ) + image_edit_provider_config: Optional[ + BaseImageEditConfig + ] = ProviderConfigManager.get_provider_image_edit_config( + model=model, + provider=litellm.LlmProviders(custom_llm_provider), ) if image_edit_provider_config is None: @@ -877,7 +878,9 @@ def image_edit( # noqa: PLR0915 local_vars.update(kwargs) # Get ImageEditOptionalRequestParams with only valid parameters image_edit_optional_params: ImageEditOptionalRequestParams = ( - _get_ImageEditRequestUtils().get_requested_image_edit_optional_param(local_vars) + _get_ImageEditRequestUtils().get_requested_image_edit_optional_param( + local_vars + ) ) # Get optional parameters for the responses API image_edit_request_params: Dict = ( @@ -926,20 +929,20 @@ def image_edit( # noqa: PLR0915 elif custom_llm_provider == "stability": image_edit_request_params.update(non_default_params) return base_llm_http_handler.image_edit_handler( - model=model, - image=images, - prompt=prompt, - image_edit_provider_config=image_edit_provider_config, - image_edit_optional_request_params=image_edit_request_params, - custom_llm_provider=custom_llm_provider, - litellm_params=litellm_params, - logging_obj=litellm_logging_obj, - extra_headers=extra_headers, - extra_body=extra_body, - timeout=timeout or DEFAULT_REQUEST_TIMEOUT, - _is_async=_is_async, - client=kwargs.get("client"), - ) + model=model, + image=images, + prompt=prompt, + image_edit_provider_config=image_edit_provider_config, + image_edit_optional_request_params=image_edit_request_params, + custom_llm_provider=custom_llm_provider, + litellm_params=litellm_params, + logging_obj=litellm_logging_obj, + extra_headers=extra_headers, + extra_body=extra_body, + timeout=timeout or DEFAULT_REQUEST_TIMEOUT, + _is_async=_is_async, + client=kwargs.get("client"), + ) elif custom_llm_provider == "black_forest_labs": # Route to BFL-specific handler (polling required) if model is None: diff --git a/litellm/images/utils.py b/litellm/images/utils.py index fa271b61b6a..8d3e96f1433 100644 --- a/litellm/images/utils.py +++ b/litellm/images/utils.py @@ -40,9 +40,7 @@ class ImageEditRequestUtils: filtered_optional_params.pop(param, None) unsupported_params = [ - param - for param in filtered_optional_params - if param not in supported_params + param for param in filtered_optional_params if param not in supported_params ] if unsupported_params: diff --git a/litellm/integrations/SlackAlerting/hanging_request_check.py b/litellm/integrations/SlackAlerting/hanging_request_check.py index d2f70c9caf1..b9c485dce82 100644 --- a/litellm/integrations/SlackAlerting/hanging_request_check.py +++ b/litellm/integrations/SlackAlerting/hanging_request_check.py @@ -102,10 +102,10 @@ class AlertingHangingRequestCheck: ) for request_id in hanging_requests: - hanging_request_data: Optional[HangingRequestData] = ( - await self.hanging_request_cache.async_get_cache( - key=request_id, - ) + hanging_request_data: Optional[ + HangingRequestData + ] = await self.hanging_request_cache.async_get_cache( + key=request_id, ) if hanging_request_data is None: diff --git a/litellm/integrations/SlackAlerting/slack_alerting.py b/litellm/integrations/SlackAlerting/slack_alerting.py index 35634d50671..013cef74805 100644 --- a/litellm/integrations/SlackAlerting/slack_alerting.py +++ b/litellm/integrations/SlackAlerting/slack_alerting.py @@ -96,7 +96,9 @@ class SlackAlerting(CustomBatchLogger): self.alert_type_config: Dict[str, AlertTypeConfig] = {} if alert_type_config: for key, val in alert_type_config.items(): - self.alert_type_config[key] = AlertTypeConfig(**val) if isinstance(val, dict) else val + self.alert_type_config[key] = ( + AlertTypeConfig(**val) if isinstance(val, dict) else val + ) self.digest_buckets: Dict[str, DigestEntry] = {} self.digest_lock = asyncio.Lock() super().__init__(**kwargs, flush_lock=self.flush_lock) @@ -126,7 +128,9 @@ class SlackAlerting(CustomBatchLogger): self.periodic_started = True if alert_type_config is not None: for key, val in alert_type_config.items(): - self.alert_type_config[key] = AlertTypeConfig(**val) if isinstance(val, dict) else val + self.alert_type_config[key] = ( + AlertTypeConfig(**val) if isinstance(val, dict) else val + ) if alert_to_webhook_url is not None: # update the dict @@ -1367,7 +1371,7 @@ Model Info: return False - async def send_alert( # noqa: PLR0915 + async def send_alert( # noqa: PLR0915 self, message: str, level: Literal["Low", "Medium", "High"], @@ -1439,7 +1443,9 @@ Model Info: self.alert_to_webhook_url is not None and alert_type in self.alert_to_webhook_url ): - _digest_webhook: Optional[Union[str, List[str]]] = self.alert_to_webhook_url[alert_type] + _digest_webhook: Optional[ + Union[str, List[str]] + ] = self.alert_to_webhook_url[alert_type] elif self.default_webhook_url is not None: _digest_webhook = self.default_webhook_url else: @@ -1588,11 +1594,21 @@ Model Info: if isinstance(webhook_url, list): for url in webhook_url: self.log_queue.append( - {"url": url, "headers": headers, "payload": payload, "alert_type": alert_type_name} + { + "url": url, + "headers": headers, + "payload": payload, + "alert_type": alert_type_name, + } ) else: self.log_queue.append( - {"url": webhook_url, "headers": headers, "payload": payload, "alert_type": alert_type_name} + { + "url": webhook_url, + "headers": headers, + "payload": payload, + "alert_type": alert_type_name, + } ) flushed_keys.append(key) diff --git a/litellm/integrations/_types/open_inference.py b/litellm/integrations/_types/open_inference.py index 0fde1ff7525..3404df7495f 100644 --- a/litellm/integrations/_types/open_inference.py +++ b/litellm/integrations/_types/open_inference.py @@ -73,11 +73,15 @@ class SpanAttributes: """ Number of tokens in the prompt. """ - LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_WRITE = "llm.token_count.prompt_details.cache_write" + LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_WRITE = ( + "llm.token_count.prompt_details.cache_write" + ) """ Number of tokens in the prompt that were written to cache. """ - LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_READ = "llm.token_count.prompt_details.cache_read" + LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_READ = ( + "llm.token_count.prompt_details.cache_read" + ) """ Number of tokens in the prompt that were read from cache. """ @@ -89,11 +93,15 @@ class SpanAttributes: """ Number of tokens in the completion. """ - LLM_TOKEN_COUNT_COMPLETION_DETAILS_REASONING = "llm.token_count.completion_details.reasoning" + LLM_TOKEN_COUNT_COMPLETION_DETAILS_REASONING = ( + "llm.token_count.completion_details.reasoning" + ) """ Number of tokens used for reasoning steps in the completion. """ - LLM_TOKEN_COUNT_COMPLETION_DETAILS_AUDIO = "llm.token_count.completion_details.audio" + LLM_TOKEN_COUNT_COMPLETION_DETAILS_AUDIO = ( + "llm.token_count.completion_details.audio" + ) """ The number of audio input tokens generated by the model """ @@ -396,7 +404,7 @@ class OpenInferenceLLMProviderValues(Enum): class ErrorAttributes: """ Attributes for error information in spans. - + These attributes follow OpenTelemetry semantic conventions for exceptions and are used to record error information from StandardLoggingPayloadErrorInformation. """ diff --git a/litellm/integrations/agentops/__init__.py b/litellm/integrations/agentops/__init__.py index 6ad02ce0ba1..003a12a6112 100644 --- a/litellm/integrations/agentops/__init__.py +++ b/litellm/integrations/agentops/__init__.py @@ -1,3 +1,3 @@ from .agentops import AgentOps -__all__ = ["AgentOps"] \ No newline at end of file +__all__ = ["AgentOps"] diff --git a/litellm/integrations/agentops/agentops.py b/litellm/integrations/agentops/agentops.py index 11e76841e99..38b91c06587 100644 --- a/litellm/integrations/agentops/agentops.py +++ b/litellm/integrations/agentops/agentops.py @@ -7,6 +7,7 @@ from typing import Optional, Dict, Any from litellm.integrations.opentelemetry import OpenTelemetry, OpenTelemetryConfig from litellm.llms.custom_httpx.http_handler import _get_httpx_client + @dataclass class AgentOpsConfig: endpoint: str = "https://otlp.agentops.cloud/v1/traces" @@ -22,9 +23,10 @@ class AgentOpsConfig: api_key=os.getenv("AGENTOPS_API_KEY"), service_name=os.getenv("AGENTOPS_SERVICE_NAME", "agentops"), deployment_environment=os.getenv("AGENTOPS_ENVIRONMENT", "production"), - auth_endpoint="https://api.agentops.ai/v3/auth/token" + auth_endpoint="https://api.agentops.ai/v3/auth/token", ) + class AgentOps(OpenTelemetry): """ AgentOps integration - built on top of OpenTelemetry @@ -32,7 +34,7 @@ class AgentOps(OpenTelemetry): Example usage: ```python import litellm - + litellm.success_callback = ["agentops"] response = litellm.completion( @@ -41,6 +43,7 @@ class AgentOps(OpenTelemetry): ) ``` """ + def __init__( self, config: Optional[AgentOpsConfig] = None, @@ -60,18 +63,13 @@ class AgentOps(OpenTelemetry): pass headers = f"Authorization=Bearer {jwt_token}" if jwt_token else None - + otel_config = OpenTelemetryConfig( - exporter="otlp_http", - endpoint=config.endpoint, - headers=headers + exporter="otlp_http", endpoint=config.endpoint, headers=headers ) # Initialize OpenTelemetry with our config - super().__init__( - config=otel_config, - callback_name="agentops" - ) + super().__init__(config=otel_config, callback_name="agentops") # Set AgentOps-specific resource attributes resource_attrs = { @@ -79,20 +77,20 @@ class AgentOps(OpenTelemetry): "deployment.environment": config.deployment_environment or "production", "telemetry.sdk.name": "agentops", } - + if project_id: resource_attrs["project.id"] = project_id - + self.resource_attributes = resource_attrs def _fetch_auth_token(self, api_key: str, auth_endpoint: str) -> Dict[str, Any]: """ Fetch JWT authentication token from AgentOps API - + Args: api_key: AgentOps API key auth_endpoint: Authentication endpoint - + Returns: Dict containing JWT token and project ID """ @@ -100,19 +98,19 @@ class AgentOps(OpenTelemetry): "Content-Type": "application/json", "Connection": "keep-alive", } - + client = _get_httpx_client() try: response = client.post( url=auth_endpoint, headers=headers, json={"api_key": api_key}, - timeout=10 + timeout=10, ) - + if response.status_code != 200: raise Exception(f"Failed to fetch auth token: {response.text}") - + return response.json() finally: - client.close() \ No newline at end of file + client.close() diff --git a/litellm/integrations/anthropic_cache_control_hook.py b/litellm/integrations/anthropic_cache_control_hook.py index 67b95c7694b..8e4d40c460e 100644 --- a/litellm/integrations/anthropic_cache_control_hook.py +++ b/litellm/integrations/anthropic_cache_control_hook.py @@ -99,10 +99,10 @@ class AnthropicCacheControlHook(CustomPromptManagement): targetted_index += len(messages) if 0 <= targetted_index < len(messages): - messages[targetted_index] = ( - AnthropicCacheControlHook._safe_insert_cache_control_in_message( - messages[targetted_index], control - ) + messages[ + targetted_index + ] = AnthropicCacheControlHook._safe_insert_cache_control_in_message( + messages[targetted_index], control ) else: verbose_logger.warning( diff --git a/litellm/integrations/arize/_utils.py b/litellm/integrations/arize/_utils.py index b75e296be47..8dfaa8b1425 100644 --- a/litellm/integrations/arize/_utils.py +++ b/litellm/integrations/arize/_utils.py @@ -14,12 +14,12 @@ from litellm.types.utils import StandardLoggingPayload if TYPE_CHECKING: from opentelemetry.trace import Span from litellm.integrations._types.open_inference import ( - MessageAttributes, - ImageAttributes, - SpanAttributes, - AudioAttributes, - EmbeddingAttributes, - OpenInferenceSpanKindValues + MessageAttributes, + ImageAttributes, + SpanAttributes, + AudioAttributes, + EmbeddingAttributes, + OpenInferenceSpanKindValues, ) @@ -158,7 +158,9 @@ def _set_audio_outputs(span: "Span", response_obj, audio_attrs, span_attrs): audio_transcript = audio_item.get("transcript") if audio_transcript: - safe_set_attribute(span, f"{audio_attrs.AUDIO_TRANSCRIPT}.{i}", audio_transcript) + safe_set_attribute( + span, f"{audio_attrs.AUDIO_TRANSCRIPT}.{i}", audio_transcript + ) def _set_embedding_outputs(span: "Span", response_obj, embedding_attrs, span_attrs): @@ -212,7 +214,9 @@ def _set_structured_outputs(span: "Span", response_obj, msg_attrs, span_attrs): message_content = getattr(first_content, "text", "") message_role = getattr(item, "role", "assistant") safe_set_attribute(span, span_attrs.OUTPUT_VALUE, message_content) - safe_set_attribute(span, f"{prefix}.{msg_attrs.MESSAGE_CONTENT}", message_content) + safe_set_attribute( + span, f"{prefix}.{msg_attrs.MESSAGE_CONTENT}", message_content + ) safe_set_attribute(span, f"{prefix}.{msg_attrs.MESSAGE_ROLE}", message_role) @@ -221,16 +225,24 @@ def _set_usage_outputs(span: "Span", response_obj, span_attrs): if not usage: return - safe_set_attribute(span, span_attrs.LLM_TOKEN_COUNT_TOTAL, usage.get("total_tokens")) + safe_set_attribute( + span, span_attrs.LLM_TOKEN_COUNT_TOTAL, usage.get("total_tokens") + ) completion_tokens = usage.get("completion_tokens") or usage.get("output_tokens") if completion_tokens: - safe_set_attribute(span, span_attrs.LLM_TOKEN_COUNT_COMPLETION, completion_tokens) + safe_set_attribute( + span, span_attrs.LLM_TOKEN_COUNT_COMPLETION, completion_tokens + ) prompt_tokens = usage.get("prompt_tokens") or usage.get("input_tokens") if prompt_tokens: safe_set_attribute(span, span_attrs.LLM_TOKEN_COUNT_PROMPT, prompt_tokens) reasoning_tokens = usage.get("output_tokens_details", {}).get("reasoning_tokens") if reasoning_tokens: - safe_set_attribute(span, span_attrs.LLM_TOKEN_COUNT_COMPLETION_DETAILS_REASONING, reasoning_tokens) + safe_set_attribute( + span, + span_attrs.LLM_TOKEN_COUNT_COMPLETION_DETAILS_REASONING, + reasoning_tokens, + ) def _infer_open_inference_span_kind(call_type: Optional[str]) -> str: @@ -281,11 +293,15 @@ def _infer_open_inference_span_kind(call_type: Optional[str]) -> str: ): return OpenInferenceSpanKindValues.LLM.value - if any(keyword in lowered for keyword in ("file", "batch", "container", "fine_tuning_job")): + if any( + keyword in lowered + for keyword in ("file", "batch", "container", "fine_tuning_job") + ): return OpenInferenceSpanKindValues.CHAIN.value return OpenInferenceSpanKindValues.UNKNOWN.value + def _set_tool_attributes( span: "Span", optional_tools: Optional[list], metadata_tools: Optional[list] ): @@ -294,18 +310,30 @@ def _set_tool_attributes( for idx, tool in enumerate(optional_tools): if not isinstance(tool, dict): continue - function = tool.get("function") if isinstance(tool.get("function"), dict) else None + function = ( + tool.get("function") if isinstance(tool.get("function"), dict) else None + ) if not function: continue tool_name = function.get("name") if tool_name: - safe_set_attribute(span, f"{SpanAttributes.LLM_TOOLS}.{idx}.name", tool_name) + safe_set_attribute( + span, f"{SpanAttributes.LLM_TOOLS}.{idx}.name", tool_name + ) tool_description = function.get("description") if tool_description: - safe_set_attribute(span, f"{SpanAttributes.LLM_TOOLS}.{idx}.description", tool_description) + safe_set_attribute( + span, + f"{SpanAttributes.LLM_TOOLS}.{idx}.description", + tool_description, + ) params = function.get("parameters") if params is not None: - safe_set_attribute(span, f"{SpanAttributes.LLM_TOOLS}.{idx}.parameters", json.dumps(params)) + safe_set_attribute( + span, + f"{SpanAttributes.LLM_TOOLS}.{idx}.parameters", + json.dumps(params), + ) if metadata_tools and isinstance(metadata_tools, list): for idx, tool in enumerate(metadata_tools): @@ -343,7 +371,11 @@ def set_attributes( if standard_logging_payload is None: raise ValueError("standard_logging_object not found in kwargs") - metadata = standard_logging_payload.get("metadata") if standard_logging_payload else None + metadata = ( + standard_logging_payload.get("metadata") + if standard_logging_payload + else None + ) _set_metadata_attributes(span, metadata, SpanAttributes) metadata_tools = _extract_metadata_tools(metadata) @@ -362,13 +394,19 @@ def set_attributes( span_kind = _infer_open_inference_span_kind(call_type=call_type) _set_tool_attributes(span, optional_tools, metadata_tools) - if (optional_tools or metadata_tools) and span_kind != OpenInferenceSpanKindValues.TOOL.value: + if ( + optional_tools or metadata_tools + ) and span_kind != OpenInferenceSpanKindValues.TOOL.value: span_kind = OpenInferenceSpanKindValues.TOOL.value safe_set_attribute(span, SpanAttributes.OPENINFERENCE_SPAN_KIND, span_kind) attributes.set_messages(span, kwargs) - model_params = standard_logging_payload.get("model_parameters") if standard_logging_payload else None + model_params = ( + standard_logging_payload.get("model_parameters") + if standard_logging_payload + else None + ) _set_model_params(span, model_params, SpanAttributes) _set_response_attributes(span=span, response_obj=response_obj) @@ -418,17 +456,29 @@ def _set_request_attributes( if kwargs.get("model"): safe_set_attribute(span, span_attrs.LLM_MODEL_NAME, kwargs.get("model")) - safe_set_attribute(span, "llm.request.type", standard_logging_payload.get("call_type")) - safe_set_attribute(span, span_attrs.LLM_PROVIDER, litellm_params.get("custom_llm_provider", "Unknown")) + safe_set_attribute( + span, "llm.request.type", standard_logging_payload.get("call_type") + ) + safe_set_attribute( + span, + span_attrs.LLM_PROVIDER, + litellm_params.get("custom_llm_provider", "Unknown"), + ) if optional_params.get("max_tokens"): - safe_set_attribute(span, "llm.request.max_tokens", optional_params.get("max_tokens")) + safe_set_attribute( + span, "llm.request.max_tokens", optional_params.get("max_tokens") + ) if optional_params.get("temperature"): - safe_set_attribute(span, "llm.request.temperature", optional_params.get("temperature")) + safe_set_attribute( + span, "llm.request.temperature", optional_params.get("temperature") + ) if optional_params.get("top_p"): safe_set_attribute(span, "llm.request.top_p", optional_params.get("top_p")) - safe_set_attribute(span, "llm.is_streaming", str(optional_params.get("stream", False))) + safe_set_attribute( + span, "llm.is_streaming", str(optional_params.get("stream", False)) + ) if optional_params.get("user"): safe_set_attribute(span, "llm.user", optional_params.get("user")) @@ -443,7 +493,9 @@ def _set_model_params(span: "Span", model_params: Optional[dict], span_attrs) -> if not model_params: return - safe_set_attribute(span, span_attrs.LLM_INVOCATION_PARAMETERS, safe_dumps(model_params)) + safe_set_attribute( + span, span_attrs.LLM_INVOCATION_PARAMETERS, safe_dumps(model_params) + ) if model_params.get("user"): user_id = model_params.get("user") if user_id is not None: diff --git a/litellm/integrations/arize/arize_phoenix.py b/litellm/integrations/arize/arize_phoenix.py index 6720a930440..00bc24d4188 100644 --- a/litellm/integrations/arize/arize_phoenix.py +++ b/litellm/integrations/arize/arize_phoenix.py @@ -12,7 +12,9 @@ if TYPE_CHECKING: from opentelemetry.trace import SpanKind from litellm.integrations.opentelemetry import OpenTelemetry as _OpenTelemetry - from litellm.integrations.opentelemetry import OpenTelemetryConfig as _OpenTelemetryConfig + from litellm.integrations.opentelemetry import ( + OpenTelemetryConfig as _OpenTelemetryConfig, + ) from litellm.types.integrations.arize import Protocol as _Protocol Protocol = _Protocol @@ -91,7 +93,9 @@ class ArizePhoenixLogger(OpenTelemetry): # type: ignore @staticmethod def set_arize_phoenix_attributes(span: Span, kwargs, response_obj): - from litellm.integrations.opentelemetry_utils.base_otel_llm_obs_attributes import safe_set_attribute + from litellm.integrations.opentelemetry_utils.base_otel_llm_obs_attributes import ( + safe_set_attribute, + ) _utils.set_attributes(span, kwargs, response_obj, ArizeOTELAttributes) @@ -103,7 +107,9 @@ class ArizePhoenixLogger(OpenTelemetry): # type: ignore # Fall back to static config from env var config = ArizePhoenixLogger.get_arize_phoenix_config() if config.project_name: - safe_set_attribute(span, "openinference.project.name", config.project_name) + safe_set_attribute( + span, "openinference.project.name", config.project_name + ) return @@ -172,7 +178,9 @@ class ArizePhoenixLogger(OpenTelemetry): # type: ignore start_time_val = kwargs.get("start_time", kwargs.get("api_call_start_time")) parent_span = self.tracer.start_span( name="litellm_proxy_request", - start_time=self._to_ns(start_time_val) if start_time_val is not None else None, + start_time=self._to_ns(start_time_val) + if start_time_val is not None + else None, context=traceparent_ctx, kind=self.span_kind.SERVER, ) @@ -212,9 +220,7 @@ class ArizePhoenixLogger(OpenTelemetry): # type: ignore # Raw-request sub-span (if enabled) — must be created before # ending the parent span so the hierarchy is valid. - self._maybe_log_raw_request( - kwargs, response_obj, start_time, end_time, span - ) + self._maybe_log_raw_request(kwargs, response_obj, start_time, end_time, span) span.end(end_time=self._to_ns(end_time)) # Guardrail span @@ -290,7 +296,9 @@ class ArizePhoenixLogger(OpenTelemetry): # type: ignore if collector_endpoint: # Parse the endpoint to determine protocol - if collector_endpoint.startswith("grpc://") or (":4317" in collector_endpoint and "/v1/traces" not in collector_endpoint): + if collector_endpoint.startswith("grpc://") or ( + ":4317" in collector_endpoint and "/v1/traces" not in collector_endpoint + ): endpoint = collector_endpoint protocol = "otlp_grpc" else: @@ -334,11 +342,10 @@ class ArizePhoenixLogger(OpenTelemetry): # type: ignore endpoint=endpoint, project_name=project_name, ) - + ## cannot suppress additional proxy server spans, removed previous methods. async def async_health_check(self): - config = self.get_arize_phoenix_config() if not config.otlp_auth_headers: @@ -350,4 +357,4 @@ class ArizePhoenixLogger(OpenTelemetry): # type: ignore return { "status": "healthy", "message": "Arize-Phoenix credentials are configured properly", - } \ No newline at end of file + } diff --git a/litellm/integrations/azure_sentinel/__init__.py b/litellm/integrations/azure_sentinel/__init__.py index 46f2fed0a97..036711a80dd 100644 --- a/litellm/integrations/azure_sentinel/__init__.py +++ b/litellm/integrations/azure_sentinel/__init__.py @@ -1,4 +1,3 @@ from litellm.integrations.azure_sentinel.azure_sentinel import AzureSentinelLogger __all__ = ["AzureSentinelLogger"] - diff --git a/litellm/integrations/azure_sentinel/azure_sentinel.py b/litellm/integrations/azure_sentinel/azure_sentinel.py index 875432de876..dd508e6c6c2 100644 --- a/litellm/integrations/azure_sentinel/azure_sentinel.py +++ b/litellm/integrations/azure_sentinel/azure_sentinel.py @@ -62,18 +62,22 @@ class AzureSentinelLogger(CustomBatchLogger): llm_provider=httpxSpecialProvider.LoggingCallback ) - self.dcr_immutable_id = ( - dcr_immutable_id or os.getenv("AZURE_SENTINEL_DCR_IMMUTABLE_ID") + self.dcr_immutable_id = dcr_immutable_id or os.getenv( + "AZURE_SENTINEL_DCR_IMMUTABLE_ID" ) self.stream_name = stream_name or os.getenv( "AZURE_SENTINEL_STREAM_NAME", "Custom-LiteLLM" ) self.endpoint = endpoint or os.getenv("AZURE_SENTINEL_ENDPOINT") - self.tenant_id = tenant_id or os.getenv("AZURE_SENTINEL_TENANT_ID") or os.getenv( - "AZURE_TENANT_ID" + self.tenant_id = ( + tenant_id + or os.getenv("AZURE_SENTINEL_TENANT_ID") + or os.getenv("AZURE_TENANT_ID") ) - self.client_id = client_id or os.getenv("AZURE_SENTINEL_CLIENT_ID") or os.getenv( - "AZURE_CLIENT_ID" + self.client_id = ( + client_id + or os.getenv("AZURE_SENTINEL_CLIENT_ID") + or os.getenv("AZURE_CLIENT_ID") ) self.client_secret = ( client_secret @@ -103,9 +107,7 @@ class AzureSentinelLogger(CustomBatchLogger): ) # Build API endpoint: {Endpoint}/dataCollectionRules/{DCR Immutable ID}/streams/{Stream Name}?api-version=2023-01-01 - self.api_endpoint = ( - f"{self.endpoint.rstrip('/')}/dataCollectionRules/{self.dcr_immutable_id}/streams/{self.stream_name}?api-version=2023-01-01" - ) + self.api_endpoint = f"{self.endpoint.rstrip('/')}/dataCollectionRules/{self.dcr_immutable_id}/streams/{self.stream_name}?api-version=2023-01-01" # OAuth2 scope for Azure Monitor self.oauth_scope = "https://monitor.azure.com/.default" @@ -139,7 +141,9 @@ class AzureSentinelLogger(CustomBatchLogger): assert self.client_id is not None, "client_id is required" assert self.client_secret is not None, "client_secret is required" - token_url = f"https://login.microsoftonline.com/{self.tenant_id}/oauth2/v2.0/token" + token_url = ( + f"https://login.microsoftonline.com/{self.tenant_id}/oauth2/v2.0/token" + ) token_data = { "client_id": self.client_id, @@ -173,9 +177,7 @@ class AzureSentinelLogger(CustomBatchLogger): return self.oauth_token - async def async_log_success_event( - self, kwargs, response_obj, start_time, end_time - ): + async def async_log_success_event(self, kwargs, response_obj, start_time, end_time): """ Async Log success events to Azure Sentinel @@ -209,9 +211,7 @@ class AzureSentinelLogger(CustomBatchLogger): ) pass - async def async_log_failure_event( - self, kwargs, response_obj, start_time, end_time - ): + async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time): """ Async Log failure events to Azure Sentinel diff --git a/litellm/integrations/azure_storage/azure_storage.py b/litellm/integrations/azure_storage/azure_storage.py index 85f91199c1c..6fc7b9c1048 100644 --- a/litellm/integrations/azure_storage/azure_storage.py +++ b/litellm/integrations/azure_storage/azure_storage.py @@ -54,12 +54,12 @@ class AzureBlobStorageLogger(CustomBatchLogger): self._service_client_timeout: Optional[float] = None # Internal variables used for Token based authentication - self.azure_auth_token: Optional[str] = ( - None # the Azure AD token to use for Azure Storage API requests - ) - self.token_expiry: Optional[datetime] = ( - None # the expiry time of the currentAzure AD token - ) + self.azure_auth_token: Optional[ + str + ] = None # the Azure AD token to use for Azure Storage API requests + self.token_expiry: Optional[ + datetime + ] = None # the expiry time of the currentAzure AD token asyncio.create_task(self.periodic_flush()) self.flush_lock = asyncio.Lock() diff --git a/litellm/integrations/braintrust_logging.py b/litellm/integrations/braintrust_logging.py index 42e9680a7fc..cb1b2bc5531 100644 --- a/litellm/integrations/braintrust_logging.py +++ b/litellm/integrations/braintrust_logging.py @@ -41,7 +41,9 @@ class BraintrustLogger(CustomLogger): self.is_mock_mode = should_use_braintrust_mock() if self.is_mock_mode: create_mock_braintrust_client() - verbose_logger.info("[BRAINTRUST MOCK] Braintrust logger initialized in mock mode") + verbose_logger.info( + "[BRAINTRUST MOCK] Braintrust logger initialized in mock mode" + ) self.validate_environment(api_key=api_key) self.api_base = api_base or os.getenv("BRAINTRUST_API_BASE") or API_BASE self.default_project_id = None @@ -50,9 +52,9 @@ class BraintrustLogger(CustomLogger): "Authorization": "Bearer " + self.api_key, "Content-Type": "application/json", } - self._project_id_cache: Dict[str, str] = ( - {} - ) # Cache mapping project names to IDs + self._project_id_cache: Dict[ + str, str + ] = {} # Cache mapping project names to IDs self.global_braintrust_http_handler = get_async_httpx_client( llm_provider=httpxSpecialProvider.LoggingCallback ) @@ -214,7 +216,7 @@ class BraintrustLogger(CustomLogger): # Allow metadata override for span name span_name = dynamic_metadata.get("span_name", "Chat Completion") - + # Span parents is a special case span_parents = dynamic_metadata.get("span_parents") @@ -236,7 +238,7 @@ class BraintrustLogger(CustomLogger): "span_attributes": {"name": span_name, "type": "llm"}, } - # Braintrust cannot specify 'tags' for non-root spans + # Braintrust cannot specify 'tags' for non-root spans if dynamic_metadata.get("root_span_id") is None: request_data["tags"] = tags @@ -386,7 +388,7 @@ class BraintrustLogger(CustomLogger): "span_attributes": {"name": span_name, "type": "llm"}, } - # Braintrust cannot specify 'tags' for non-root spans + # Braintrust cannot specify 'tags' for non-root spans if dynamic_metadata.get("root_span_id") is None: request_data["tags"] = tags diff --git a/litellm/integrations/braintrust_mock_client.py b/litellm/integrations/braintrust_mock_client.py index 030aa62cd0f..59e0988a10a 100644 --- a/litellm/integrations/braintrust_mock_client.py +++ b/litellm/integrations/braintrust_mock_client.py @@ -13,7 +13,11 @@ import time from urllib.parse import urlparse from litellm._logging import verbose_logger -from litellm.integrations.mock_client_factory import MockClientConfig, MockResponse, create_mock_client_factory +from litellm.integrations.mock_client_factory import ( + MockClientConfig, + MockResponse, + create_mock_client_factory, +) # Use factory for should_use_mock and MockResponse # Braintrust uses both HTTPHandler (sync) and AsyncHTTPHandler (async) @@ -37,7 +41,10 @@ _config = MockClientConfig( # Get should_use_mock and create_mock_client from factory # We need to call the factory's create_mock_client to patch AsyncHTTPHandler.post -create_mock_braintrust_factory_client, should_use_braintrust_mock = create_mock_client_factory(_config) +( + create_mock_braintrust_factory_client, + should_use_braintrust_mock, +) = create_mock_client_factory(_config) # Store original HTTPHandler.post method (Braintrust-specific for sync calls with custom logic) _original_http_handler_post = None @@ -66,7 +73,19 @@ def _is_braintrust_url(url: str) -> bool: ) -def _mock_http_handler_post(self, url, data=None, json=None, params=None, headers=None, timeout=None, stream=False, files=None, content=None, logging_obj=None): +def _mock_http_handler_post( + self, + url, + data=None, + json=None, + params=None, + headers=None, + timeout=None, + stream=False, + files=None, + content=None, + logging_obj=None, +): """Monkey-patched HTTPHandler.post that intercepts Braintrust calls with endpoint-specific responses.""" # Only mock Braintrust API calls if isinstance(url, str) and _is_braintrust_url(url): @@ -86,46 +105,62 @@ def _mock_http_handler_post(self, url, data=None, json=None, params=None, header status_code=_config.default_status_code, json_data=mock_data, url=url, - elapsed_seconds=_MOCK_LATENCY_SECONDS + elapsed_seconds=_MOCK_LATENCY_SECONDS, ) if _original_http_handler_post is not None: - return _original_http_handler_post(self, url=url, data=data, json=json, params=params, headers=headers, timeout=timeout, stream=stream, files=files, content=content, logging_obj=logging_obj) + return _original_http_handler_post( + self, + url=url, + data=data, + json=json, + params=params, + headers=headers, + timeout=timeout, + stream=stream, + files=files, + content=content, + logging_obj=logging_obj, + ) raise RuntimeError("Original HTTPHandler.post not available") def create_mock_braintrust_client(): """ Monkey-patch HTTPHandler.post to intercept Braintrust sync calls. - + Braintrust uses HTTPHandler for sync calls and AsyncHTTPHandler for async calls. HTTPHandler.post uses self.client.send(), not self.client.post(), so we need custom patching for sync (similar to Helicone). AsyncHTTPHandler.post is patched by the factory. - + We use custom patching instead of factory's patch_http_handler because we need endpoint-specific responses (different for /project vs /project_logs). - + This function is idempotent - it only initializes mocks once, even if called multiple times. """ global _original_http_handler_post, _mocks_initialized - + if _mocks_initialized: return - + verbose_logger.debug("[BRAINTRUST MOCK] Initializing Braintrust mock client...") - + from litellm.llms.custom_httpx.http_handler import HTTPHandler - + if _original_http_handler_post is None: _original_http_handler_post = HTTPHandler.post HTTPHandler.post = _mock_http_handler_post # type: ignore verbose_logger.debug("[BRAINTRUST MOCK] Patched HTTPHandler.post") - + # CRITICAL: Call the factory's initialization function to patch AsyncHTTPHandler.post # This is required for async calls to be mocked create_mock_braintrust_factory_client() - - verbose_logger.debug(f"[BRAINTRUST MOCK] Mock latency set to {_MOCK_LATENCY_SECONDS*1000:.0f}ms") - verbose_logger.debug("[BRAINTRUST MOCK] Braintrust mock client initialization complete") - + + verbose_logger.debug( + f"[BRAINTRUST MOCK] Mock latency set to {_MOCK_LATENCY_SECONDS*1000:.0f}ms" + ) + verbose_logger.debug( + "[BRAINTRUST MOCK] Braintrust mock client initialization complete" + ) + _mocks_initialized = True diff --git a/litellm/integrations/cloudzero/cz_resource_names.py b/litellm/integrations/cloudzero/cz_resource_names.py index f1098d20381..20862c1c7ec 100644 --- a/litellm/integrations/cloudzero/cz_resource_names.py +++ b/litellm/integrations/cloudzero/cz_resource_names.py @@ -30,7 +30,9 @@ class CZEntityType(str, Enum): class CZRNGenerator: """Generate CloudZero Resource Names (CZRNs) for LiteLLM resources.""" - CZRN_REGEX = re.compile(r'^czrn:([a-z0-9-]+):([a-zA-Z0-9-]+):([a-z0-9-]+):([a-z0-9-]+):([a-z0-9-]+):(.+)$') + CZRN_REGEX = re.compile( + r"^czrn:([a-z0-9-]+):([a-zA-Z0-9-]+):([a-z0-9-]+):([a-z0-9-]+):([a-z0-9-]+):(.+)$" + ) def __init__(self): """Initialize CZRN generator.""" @@ -38,9 +40,9 @@ class CZRNGenerator: def create_from_litellm_data(self, row: dict[str, Any]) -> str: """Create a CZRN from LiteLLM daily spend data. - + CZRN format: czrn:::::: - + For LiteLLM resources, we map: - service-type: 'litellm' (the service managing the LLM calls) - provider: The custom_llm_provider (e.g., 'openai', 'anthropic', 'azure') @@ -49,18 +51,18 @@ class CZRNGenerator: - resource-type: 'llm-usage' (represents LLM usage/inference) - cloud-local-id: model """ - service_type = 'litellm' - provider = self._normalize_provider(row.get('custom_llm_provider', 'unknown')) - region = 'cross-region' + service_type = "litellm" + provider = self._normalize_provider(row.get("custom_llm_provider", "unknown")) + region = "cross-region" # Use the actual entity_id (team_id or user_id) as the owner account - team_id = row.get('team_id', 'unknown') + team_id = row.get("team_id", "unknown") owner_account_id = self._normalize_component(team_id) - resource_type = 'llm-usage' + resource_type = "llm-usage" # Create a unique identifier with just the model (entity info already in owner_account_id) - model = row.get('model', 'unknown') + model = row.get("model", "unknown") cloud_local_id = model @@ -70,7 +72,7 @@ class CZRNGenerator: region=region, owner_account_id=owner_account_id, resource_type=resource_type, - cloud_local_id=cloud_local_id + cloud_local_id=cloud_local_id, ) def create_from_components( @@ -80,7 +82,7 @@ class CZRNGenerator: region: str, owner_account_id: str, resource_type: str, - cloud_local_id: str + cloud_local_id: str, ) -> str: """Create a CZRN from individual components.""" # Normalize components to ensure they meet CZRN requirements @@ -104,7 +106,7 @@ class CZRNGenerator: def extract_components(self, czrn: str) -> tuple[str, str, str, str, str, str]: """Extract all components from a CZRN. - + Returns: (service_type, provider, region, owner_account_id, resource_type, cloud_local_id) """ match = self.CZRN_REGEX.match(czrn) @@ -117,42 +119,43 @@ class CZRNGenerator: """Normalize provider names to standard CZRN format.""" # Map common provider names to CZRN standards provider_map = { - litellm.LlmProviders.AZURE.value: 'azure', - litellm.LlmProviders.AZURE_AI.value: 'azure', - litellm.LlmProviders.ANTHROPIC.value: 'anthropic', - litellm.LlmProviders.BEDROCK.value: 'aws', - litellm.LlmProviders.VERTEX_AI.value: 'gcp', - litellm.LlmProviders.GEMINI.value: 'google', - litellm.LlmProviders.COHERE.value: 'cohere', - litellm.LlmProviders.HUGGINGFACE.value: 'huggingface', - litellm.LlmProviders.REPLICATE.value: 'replicate', - litellm.LlmProviders.TOGETHER_AI.value: 'together-ai', + litellm.LlmProviders.AZURE.value: "azure", + litellm.LlmProviders.AZURE_AI.value: "azure", + litellm.LlmProviders.ANTHROPIC.value: "anthropic", + litellm.LlmProviders.BEDROCK.value: "aws", + litellm.LlmProviders.VERTEX_AI.value: "gcp", + litellm.LlmProviders.GEMINI.value: "google", + litellm.LlmProviders.COHERE.value: "cohere", + litellm.LlmProviders.HUGGINGFACE.value: "huggingface", + litellm.LlmProviders.REPLICATE.value: "replicate", + litellm.LlmProviders.TOGETHER_AI.value: "together-ai", } - normalized = provider.lower().replace('_', '-') + normalized = provider.lower().replace("_", "-") # use litellm custom llm provider if not in provider_map if normalized not in provider_map: return normalized return provider_map.get(normalized, normalized) - def _normalize_component(self, component: str, allow_uppercase: bool = False) -> str: + def _normalize_component( + self, component: str, allow_uppercase: bool = False + ) -> str: """Normalize a CZRN component to meet format requirements.""" if not component: - return 'unknown' + return "unknown" # Convert to lowercase unless uppercase is allowed if not allow_uppercase: component = component.lower() # Replace invalid characters with hyphens - component = re.sub(r'[^a-zA-Z0-9-]', '-', component) + component = re.sub(r"[^a-zA-Z0-9-]", "-", component) # Remove consecutive hyphens - component = re.sub(r'-+', '-', component) + component = re.sub(r"-+", "-", component) # Remove leading/trailing hyphens - component = component.strip('-') - - return component or 'unknown' + component = component.strip("-") + return component or "unknown" diff --git a/litellm/integrations/cloudzero/cz_stream_api.py b/litellm/integrations/cloudzero/cz_stream_api.py index 83b6e318ba7..d673536e72d 100644 --- a/litellm/integrations/cloudzero/cz_stream_api.py +++ b/litellm/integrations/cloudzero/cz_stream_api.py @@ -30,7 +30,9 @@ from rich.console import Console class CloudZeroStreamer: """Stream CBF data to CloudZero AnyCost API with proper batching and timezone handling.""" - def __init__(self, api_key: str, connection_id: str, user_timezone: Optional[str] = None): + def __init__( + self, api_key: str, connection_id: str, user_timezone: Optional[str] = None + ): """Initialize CloudZero streamer with credentials.""" self.api_key = api_key self.connection_id = connection_id @@ -43,12 +45,16 @@ class CloudZeroStreamer: try: self.user_timezone = zoneinfo.ZoneInfo(user_timezone) except zoneinfo.ZoneInfoNotFoundError: - self.console.print(f"[yellow]Warning: Unknown timezone '{user_timezone}', using UTC[/yellow]") + self.console.print( + f"[yellow]Warning: Unknown timezone '{user_timezone}', using UTC[/yellow]" + ) self.user_timezone = timezone.utc else: self.user_timezone = timezone.utc - def send_batched(self, data: pl.DataFrame, operation: str = "replace_hourly") -> None: + def send_batched( + self, data: pl.DataFrame, operation: str = "replace_hourly" + ) -> None: """Send CBF data in daily batches to CloudZero AnyCost API.""" if data.is_empty(): self.console.print("[yellow]No data to send to CloudZero[/yellow]") @@ -61,7 +67,9 @@ class CloudZeroStreamer: self.console.print("[yellow]No valid daily batches to send[/yellow]") return - self.console.print(f"[blue]Sending {len(daily_batches)} daily batch(es) with operation '{operation}'[/blue]") + self.console.print( + f"[blue]Sending {len(daily_batches)} daily batch(es) with operation '{operation}'[/blue]" + ) for batch_date, batch_data in daily_batches.items(): self._send_daily_batch(batch_date, batch_data, operation) @@ -71,21 +79,23 @@ class CloudZeroStreamer: daily_batches: dict[str, list[dict[str, Any]]] = {} # Ensure we have the required columns - if 'time/usage_start' not in data.columns: - self.console.print("[red]Error: Missing 'time/usage_start' column for date grouping[/red]") + if "time/usage_start" not in data.columns: + self.console.print( + "[red]Error: Missing 'time/usage_start' column for date grouping[/red]" + ) return {} - + timestamp_str: Optional[str] = None for row in data.iter_rows(named=True): try: # Parse the timestamp and convert to UTC - timestamp_str = row.get('time/usage_start') + timestamp_str = row.get("time/usage_start") if not timestamp_str: continue # Parse timestamp and handle timezone conversion dt = self._parse_and_convert_timestamp(timestamp_str) - batch_date = dt.strftime('%Y-%m-%d') + batch_date = dt.strftime("%Y-%m-%d") if batch_date not in daily_batches: daily_batches[batch_date] = [] @@ -93,25 +103,54 @@ class CloudZeroStreamer: daily_batches[batch_date].append(row) except Exception as e: - self.console.print(f"[yellow]Warning: Could not process timestamp '{timestamp_str}': {e}[/yellow]") + self.console.print( + f"[yellow]Warning: Could not process timestamp '{timestamp_str}': {e}[/yellow]" + ) continue # Convert lists back to DataFrames - return {date_key: pl.DataFrame(records) for date_key, records in daily_batches.items() if records} + return { + date_key: pl.DataFrame(records) + for date_key, records in daily_batches.items() + if records + } def _parse_and_convert_timestamp(self, timestamp_str: str) -> datetime: """Parse timestamp string and convert to UTC.""" # Try to parse the timestamp string try: # Handle various ISO 8601 formats - if timestamp_str.endswith('Z'): - dt = datetime.fromisoformat(timestamp_str.replace('Z', '+00:00')) - elif '+' in timestamp_str or timestamp_str.endswith(('-00:00', '-01:00', '-02:00', '-03:00', - '-04:00', '-05:00', '-06:00', '-07:00', - '-08:00', '-09:00', '-10:00', '-11:00', - '-12:00', '+01:00', '+02:00', '+03:00', - '+04:00', '+05:00', '+06:00', '+07:00', - '+08:00', '+09:00', '+10:00', '+11:00', '+12:00')): + if timestamp_str.endswith("Z"): + dt = datetime.fromisoformat(timestamp_str.replace("Z", "+00:00")) + elif "+" in timestamp_str or timestamp_str.endswith( + ( + "-00:00", + "-01:00", + "-02:00", + "-03:00", + "-04:00", + "-05:00", + "-06:00", + "-07:00", + "-08:00", + "-09:00", + "-10:00", + "-11:00", + "-12:00", + "+01:00", + "+02:00", + "+03:00", + "+04:00", + "+05:00", + "+06:00", + "+07:00", + "+08:00", + "+09:00", + "+10:00", + "+11:00", + "+12:00", + ) + ): dt = datetime.fromisoformat(timestamp_str) else: # Assume user timezone if no timezone info @@ -125,14 +164,16 @@ class CloudZeroStreamer: except ValueError as e: raise ValueError(f"Could not parse timestamp '{timestamp_str}': {e}") - def _send_daily_batch(self, batch_date: str, batch_data: pl.DataFrame, operation: str) -> None: + def _send_daily_batch( + self, batch_date: str, batch_data: pl.DataFrame, operation: str + ) -> None: """Send a single daily batch to CloudZero API.""" if batch_data.is_empty(): return headers = { - 'Authorization': f'Bearer {self.api_key}', - 'Content-Type': 'application/json' + "Authorization": f"Bearer {self.api_key}", + "Content-Type": "application/json", } # Use the correct API endpoint format from documentation @@ -143,29 +184,39 @@ class CloudZeroStreamer: try: with httpx.Client(timeout=30.0) as client: - self.console.print(f"[blue]Sending batch for {batch_date} ({len(batch_data)} records)[/blue]") + self.console.print( + f"[blue]Sending batch for {batch_date} ({len(batch_data)} records)[/blue]" + ) response = client.post(url, headers=headers, json=payload) response.raise_for_status() - self.console.print(f"[green]✓ Successfully sent batch for {batch_date} ({len(batch_data)} records)[/green]") + self.console.print( + f"[green]✓ Successfully sent batch for {batch_date} ({len(batch_data)} records)[/green]" + ) except httpx.RequestError as e: - self.console.print(f"[red]✗ Network error sending batch for {batch_date}: {e}[/red]") + self.console.print( + f"[red]✗ Network error sending batch for {batch_date}: {e}[/red]" + ) raise except httpx.HTTPStatusError as e: - self.console.print(f"[red]✗ HTTP error sending batch for {batch_date}: {e.response.status_code} {e.response.text}[/red]") + self.console.print( + f"[red]✗ HTTP error sending batch for {batch_date}: {e.response.status_code} {e.response.text}[/red]" + ) raise - def _prepare_batch_payload(self, batch_date: str, batch_data: pl.DataFrame, operation: str) -> dict[str, Any]: + def _prepare_batch_payload( + self, batch_date: str, batch_data: pl.DataFrame, operation: str + ) -> dict[str, Any]: """Prepare batch payload according to CloudZero AnyCost API format.""" # Convert batch_date to month for the API (YYYY-MM format) try: - date_obj = datetime.strptime(batch_date, '%Y-%m-%d') - month_str = date_obj.strftime('%Y-%m') + date_obj = datetime.strptime(batch_date, "%Y-%m-%d") + month_str = date_obj.strftime("%Y-%m") except ValueError: # Fallback to current month - month_str = datetime.now().strftime('%Y-%m') + month_str = datetime.now().strftime("%Y-%m") # Convert DataFrame rows to API format data_records = [] @@ -174,15 +225,13 @@ class CloudZeroStreamer: if record: data_records.append(record) - payload = { - 'month': month_str, - 'operation': operation, - 'data': data_records - } + payload = {"month": month_str, "operation": operation, "data": data_records} return payload - def _convert_cbf_to_api_format(self, row: dict[str, Any]) -> Optional[dict[str, Any]]: + def _convert_cbf_to_api_format( + self, row: dict[str, Any] + ) -> Optional[dict[str, Any]]: """Convert CBF row to CloudZero API format - keeping CBF field names as CloudZero expects them.""" try: # CloudZero expects CBF format field names directly, not converted names @@ -196,20 +245,24 @@ class CloudZeroStreamer: # Format floats to avoid scientific notation if isinstance(value, float): # Use a reasonable precision that avoids scientific notation - api_record[key] = f"{value:.10f}".rstrip('0').rstrip('.') + api_record[key] = f"{value:.10f}".rstrip("0").rstrip(".") else: api_record[key] = str(value) else: api_record[key] = value # Ensure timestamp is in UTC format - if 'time/usage_start' in api_record: - api_record['time/usage_start'] = self._ensure_utc_timestamp(api_record['time/usage_start']) + if "time/usage_start" in api_record: + api_record["time/usage_start"] = self._ensure_utc_timestamp( + api_record["time/usage_start"] + ) return api_record except Exception as e: - self.console.print(f"[yellow]Warning: Could not convert record to API format: {e}[/yellow]") + self.console.print( + f"[yellow]Warning: Could not convert record to API format: {e}[/yellow]" + ) return None def _ensure_utc_timestamp(self, timestamp_str: str) -> str: @@ -219,9 +272,7 @@ class CloudZeroStreamer: try: dt = self._parse_and_convert_timestamp(timestamp_str) - return dt.isoformat().replace('+00:00', 'Z') + return dt.isoformat().replace("+00:00", "Z") except Exception: # Fallback to current time in UTC - return datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z') - - + return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") diff --git a/litellm/integrations/cloudzero/transform.py b/litellm/integrations/cloudzero/transform.py index b40a71da1c6..c1b0d5cf411 100644 --- a/litellm/integrations/cloudzero/transform.py +++ b/litellm/integrations/cloudzero/transform.py @@ -41,8 +41,8 @@ class CBFTransformer: # Filter out records with zero successful_requests first original_count = len(data) - if 'successful_requests' in data.columns: - filtered_data = data.filter(pl.col('successful_requests') > 0) + if "successful_requests" in data.columns: + filtered_data = data.filter(pl.col("successful_requests") > 0) zero_requests_dropped = original_count - len(filtered_data) else: filtered_data = data @@ -64,16 +64,23 @@ class CBFTransformer: # Print summary of dropped records if any from rich.console import Console + console = Console() if zero_requests_dropped > 0: - console.print(f"[yellow]⚠️ Dropped {zero_requests_dropped:,} of {original_count:,} records with zero successful_requests[/yellow]") + console.print( + f"[yellow]⚠️ Dropped {zero_requests_dropped:,} of {original_count:,} records with zero successful_requests[/yellow]" + ) if czrn_dropped_count > 0: - console.print(f"[yellow]⚠️ Dropped {czrn_dropped_count:,} of {filtered_count:,} filtered records due to invalid CZRNs[/yellow]") + console.print( + f"[yellow]⚠️ Dropped {czrn_dropped_count:,} of {filtered_count:,} filtered records due to invalid CZRNs[/yellow]" + ) if len(cbf_data) > 0: - console.print(f"[green]✓ Successfully transformed {len(cbf_data):,} records[/green]") + console.print( + f"[green]✓ Successfully transformed {len(cbf_data):,} records[/green]" + ) return pl.DataFrame(cbf_data) @@ -81,99 +88,116 @@ class CBFTransformer: """Create a single CBF record from LiteLLM daily spend row.""" # Parse date (daily spend tables use date strings like '2025-04-19') - usage_date = self._parse_date(row.get('date')) + usage_date = self._parse_date(row.get("date")) # Calculate total tokens - prompt_tokens = int(row.get('prompt_tokens', 0)) - completion_tokens = int(row.get('completion_tokens', 0)) + prompt_tokens = int(row.get("prompt_tokens", 0)) + completion_tokens = int(row.get("completion_tokens", 0)) total_tokens = prompt_tokens + completion_tokens # Create CloudZero Resource Name (CZRN) as resource_id resource_id = self.czrn_generator.create_from_litellm_data(row) # Build dimensions for CloudZero - model = str(row.get('model', '')) - api_key_hash = str(row.get('api_key', ''))[:8] # First 8 chars for identification - + model = str(row.get("model", "")) + api_key_hash = str(row.get("api_key", ""))[ + :8 + ] # First 8 chars for identification + # Handle team information with fallbacks - team_id = row.get('team_id') - team_alias = row.get('team_alias') - user_email = row.get('user_email') - + team_id = row.get("team_id") + team_alias = row.get("team_alias") + user_email = row.get("user_email") + # Use team_alias if available, otherwise team_id, otherwise fallback to 'unknown' - entity_id = str(team_alias) if team_alias else (str(team_id) if team_id else 'unknown') - + entity_id = ( + str(team_alias) if team_alias else (str(team_id) if team_id else "unknown") + ) + # Get alias fields if they exist - api_key_alias = row.get('api_key_alias') - organization_alias = row.get('organization_alias') - project_alias = row.get('project_alias') - user_alias = row.get('user_alias') + api_key_alias = row.get("api_key_alias") + organization_alias = row.get("organization_alias") + project_alias = row.get("project_alias") + user_alias = row.get("user_alias") dimensions = { - 'entity_type': CZEntityType.TEAM.value, - 'entity_id': entity_id, - 'team_alias': str(team_alias) if team_alias else 'unknown', - 'model': model, - 'model_group': str(row.get('model_group', '')), - 'provider': str(row.get('custom_llm_provider', '')), - 'api_key_prefix': api_key_hash, - 'api_key_alias': str(row.get('api_key_alias', '')), - 'user_email': str(user_email) if user_email else '', - 'api_requests': str(row.get('api_requests', 0)), - 'successful_requests': str(row.get('successful_requests', 0)), - 'failed_requests': str(row.get('failed_requests', 0)), - 'cache_creation_tokens': str(row.get('cache_creation_input_tokens', 0)), - 'cache_read_tokens': str(row.get('cache_read_input_tokens', 0)), - 'organization_alias': str(organization_alias) if organization_alias else '', - 'project_alias': str(project_alias) if project_alias else '', - 'user_alias': str(user_alias) if user_alias else '', + "entity_type": CZEntityType.TEAM.value, + "entity_id": entity_id, + "team_alias": str(team_alias) if team_alias else "unknown", + "model": model, + "model_group": str(row.get("model_group", "")), + "provider": str(row.get("custom_llm_provider", "")), + "api_key_prefix": api_key_hash, + "api_key_alias": str(row.get("api_key_alias", "")), + "user_email": str(user_email) if user_email else "", + "api_requests": str(row.get("api_requests", 0)), + "successful_requests": str(row.get("successful_requests", 0)), + "failed_requests": str(row.get("failed_requests", 0)), + "cache_creation_tokens": str(row.get("cache_creation_input_tokens", 0)), + "cache_read_tokens": str(row.get("cache_read_input_tokens", 0)), + "organization_alias": str(organization_alias) if organization_alias else "", + "project_alias": str(project_alias) if project_alias else "", + "user_alias": str(user_alias) if user_alias else "", } # Extract CZRN components to populate corresponding CBF columns czrn_components = self.czrn_generator.extract_components(resource_id) - service_type, provider, region, owner_account_id, resource_type, cloud_local_id = czrn_components + ( + service_type, + provider, + region, + owner_account_id, + resource_type, + cloud_local_id, + ) = czrn_components # Build resource/account as concat of api_key_alias and api_key_prefix - resource_account = f"{api_key_alias}|{api_key_hash}" if api_key_alias else api_key_hash + resource_account = ( + f"{api_key_alias}|{api_key_hash}" if api_key_alias else api_key_hash + ) # CloudZero CBF format with proper column names cbf_record = { # Required CBF fields - 'time/usage_start': usage_date.isoformat() if usage_date else None, # Required: ISO-formatted UTC datetime - 'cost/cost': float(row.get('spend', 0.0)), # Required: billed cost - 'resource/id': resource_id, # CZRN (CloudZero Resource Name) - + "time/usage_start": usage_date.isoformat() + if usage_date + else None, # Required: ISO-formatted UTC datetime + "cost/cost": float(row.get("spend", 0.0)), # Required: billed cost + "resource/id": resource_id, # CZRN (CloudZero Resource Name) # Usage metrics for token consumption - 'usage/amount': total_tokens, # Numeric value of tokens consumed - 'usage/units': 'tokens', # Description of token units - + "usage/amount": total_tokens, # Numeric value of tokens consumed + "usage/units": "tokens", # Description of token units # CBF fields - updated per LIT-1907 - 'resource/service': str(row.get('model_group', '')), # Send model_group - 'resource/account': resource_account, # Send api_key_alias|api_key_prefix - 'resource/region': region, # Maps to CZRN region (cross-region) - 'resource/usage_family': str(row.get('custom_llm_provider', '')), # Send provider - + "resource/service": str(row.get("model_group", "")), # Send model_group + "resource/account": resource_account, # Send api_key_alias|api_key_prefix + "resource/region": region, # Maps to CZRN region (cross-region) + "resource/usage_family": str( + row.get("custom_llm_provider", "") + ), # Send provider # Action field - 'action/operation': str(team_id) if team_id else '', # Send team_id - + "action/operation": str(team_id) if team_id else "", # Send team_id # Line item details - 'lineitem/type': 'Usage', # Standard usage line item + "lineitem/type": "Usage", # Standard usage line item } # Add CZRN components that don't have direct CBF column mappings as resource tags - cbf_record['resource/tag:provider'] = provider # CZRN provider component - cbf_record['resource/tag:model'] = cloud_local_id # CZRN cloud-local-id component (model) - + cbf_record["resource/tag:provider"] = provider # CZRN provider component + cbf_record[ + "resource/tag:model" + ] = cloud_local_id # CZRN cloud-local-id component (model) + # Add resource tags for all dimensions (using resource/tag: format) for key, value in dimensions.items(): - if value and value != 'N/A' and value != 'unknown': # Only add meaningful tags - cbf_record[f'resource/tag:{key}'] = str(value) + if ( + value and value != "N/A" and value != "unknown" + ): # Only add meaningful tags + cbf_record[f"resource/tag:{key}"] = str(value) # Add token breakdown as resource tags for analysis (excluding total_tokens per LIT-1907) if prompt_tokens > 0: - cbf_record['resource/tag:prompt_tokens'] = str(prompt_tokens) + cbf_record["resource/tag:prompt_tokens"] = str(prompt_tokens) if completion_tokens > 0: - cbf_record['resource/tag:completion_tokens'] = str(completion_tokens) + cbf_record["resource/tag:completion_tokens"] = str(completion_tokens) return CBFRecord(cbf_record) @@ -197,4 +221,3 @@ class CBFTransformer: return None return None - diff --git a/litellm/integrations/custom_logger.py b/litellm/integrations/custom_logger.py index c244363e389..06ba9675ca2 100644 --- a/litellm/integrations/custom_logger.py +++ b/litellm/integrations/custom_logger.py @@ -377,6 +377,7 @@ class CustomLogger: # https://docs.litellm.ai/docs/observability/custom_callbac user_api_key_dict: UserAPIKeyAuth, response: Any, request_headers: Optional[Dict[str, str]] = None, + litellm_call_info: Optional[Dict[str, Any]] = None, ) -> Optional[Dict[str, str]]: """ Called after an LLM API call (success or failure) to allow injecting custom HTTP response headers. @@ -386,6 +387,11 @@ class CustomLogger: # https://docs.litellm.ai/docs/observability/custom_callbac - user_api_key_dict: UserAPIKeyAuth - The user API key dictionary. - response: Any - The response object (None for failure cases). - request_headers: Optional[Dict[str, str]] - The original request headers. + - litellm_call_info: Optional[Dict[str, Any]] - Normalized routing metadata: + - custom_llm_provider: str - The LLM provider (e.g. "openai", "azure") + - model_info: dict - The model_info from router config + - api_base: str - The API base URL used + - model_id: str - The deployment model ID Returns: - Optional[Dict[str, str]]: A dictionary of headers to inject into the HTTP response. @@ -664,7 +670,7 @@ class CustomLogger: # https://docs.litellm.ai/docs/observability/custom_callbac return final_response """ pass - + async def async_should_run_chat_completion_agentic_loop( self, response: Any, @@ -863,9 +869,9 @@ class CustomLogger: # https://docs.litellm.ai/docs/observability/custom_callbac model_response_dict = model_response.model_dump() standard_logging_object_copy["response"] = model_response_dict - model_call_details_copy["standard_logging_object"] = ( - standard_logging_object_copy - ) + model_call_details_copy[ + "standard_logging_object" + ] = standard_logging_object_copy return model_call_details_copy async def get_proxy_server_request_from_cold_storage_with_object_key( diff --git a/litellm/integrations/custom_secret_manager.py b/litellm/integrations/custom_secret_manager.py index 2125aef2200..45ffa2e08cf 100644 --- a/litellm/integrations/custom_secret_manager.py +++ b/litellm/integrations/custom_secret_manager.py @@ -100,9 +100,7 @@ class CustomSecretManager(BaseSecretManager): """ super().__init__() self.secret_manager_name = secret_manager_name or "custom_secret_manager" - verbose_logger.info( - "Initialized custom secret manager" - ) + verbose_logger.info("Initialized custom secret manager") @abstractmethod async def async_read_secret( diff --git a/litellm/integrations/custom_sso_handler.py b/litellm/integrations/custom_sso_handler.py index bc80966f8ca..7f60decabc3 100644 --- a/litellm/integrations/custom_sso_handler.py +++ b/litellm/integrations/custom_sso_handler.py @@ -13,6 +13,7 @@ class CustomSSOLoginHandler(CustomLogger): Useful when you have an OAuth proxy in front of LiteLLM and you want to use the headers from the proxy to sign in the user """ + async def handle_custom_ui_sso_sign_in( self, request: Request, @@ -26,4 +27,4 @@ class CustomSSOLoginHandler(CustomLogger): display_name="Test", picture="https://test.com/test.png", provider="test", - ) \ No newline at end of file + ) diff --git a/litellm/integrations/datadog/datadog_llm_obs.py b/litellm/integrations/datadog/datadog_llm_obs.py index e5ce9997491..de6cc02fa3d 100644 --- a/litellm/integrations/datadog/datadog_llm_obs.py +++ b/litellm/integrations/datadog/datadog_llm_obs.py @@ -48,13 +48,15 @@ class DataDogLLMObsLogger(CustomBatchLogger): def __init__(self, **kwargs): try: verbose_logger.debug("DataDogLLMObs: Initializing logger") - + self.is_mock_mode = should_use_datadog_mock() - + if self.is_mock_mode: create_mock_datadog_client() - verbose_logger.debug("[DATADOG MOCK] DataDogLLMObs logger initialized in mock mode") - + verbose_logger.debug( + "[DATADOG MOCK] DataDogLLMObs logger initialized in mock mode" + ) + # Configure DataDog endpoint (Agent or Direct API) # Use LITELLM_DD_AGENT_HOST to avoid conflicts with ddtrace's DD_AGENT_HOST # Check for agent mode FIRST - agent mode doesn't require DD_API_KEY or DD_SITE @@ -189,9 +191,11 @@ class DataDogLLMObsLogger(CustomBatchLogger): verbose_logger.debug( f"DataDogLLMObs: Flushing {len(self.log_queue)} events" ) - + if self.is_mock_mode: - verbose_logger.debug("[DATADOG MOCK] Mock mode enabled - API calls will be intercepted") + verbose_logger.debug( + "[DATADOG MOCK] Mock mode enabled - API calls will be intercepted" + ) # Prepare the payload payload = { diff --git a/litellm/integrations/datadog/datadog_mock_client.py b/litellm/integrations/datadog/datadog_mock_client.py index a0a760deb0b..7f9beab72cc 100644 --- a/litellm/integrations/datadog/datadog_mock_client.py +++ b/litellm/integrations/datadog/datadog_mock_client.py @@ -8,7 +8,10 @@ Usage: Set DATADOG_MOCK=true in environment variables or config to enable mock mode. """ -from litellm.integrations.mock_client_factory import MockClientConfig, create_mock_client_factory +from litellm.integrations.mock_client_factory import ( + MockClientConfig, + create_mock_client_factory, +) # Create mock client using factory _config = MockClientConfig( @@ -25,4 +28,6 @@ _config = MockClientConfig( patch_sync_client=True, ) -create_mock_datadog_client, should_use_datadog_mock = create_mock_client_factory(_config) +create_mock_datadog_client, should_use_datadog_mock = create_mock_client_factory( + _config +) diff --git a/litellm/integrations/dotprompt/__init__.py b/litellm/integrations/dotprompt/__init__.py index 3847c8fa192..394929f4a25 100644 --- a/litellm/integrations/dotprompt/__init__.py +++ b/litellm/integrations/dotprompt/__init__.py @@ -25,6 +25,7 @@ def set_global_prompt_directory(directory: str) -> None: litellm.global_prompt_directory = directory # type: ignore + def _get_prompt_data_from_dotprompt_content(dotprompt_content: str) -> dict: """ Get the prompt data from the dotprompt content. @@ -36,12 +37,10 @@ def _get_prompt_data_from_dotprompt_content(dotprompt_content: str) -> dict: # Parse the dotprompt content to extract frontmatter and content temp_manager = PromptManager() metadata, content = temp_manager._parse_frontmatter(dotprompt_content) - + # Convert to prompt_data format - return { - "content": content.strip(), - "metadata": metadata - } + return {"content": content.strip(), "metadata": metadata} + def prompt_initializer( litellm_params: "PromptLiteLLMParams", prompt_spec: "PromptSpec" @@ -58,7 +57,7 @@ def prompt_initializer( ) prompt_file = getattr(litellm_params, "prompt_file", None) - + # Handle dotprompt_content from database dotprompt_content = getattr(litellm_params, "dotprompt_content", None) if dotprompt_content and not prompt_data and not prompt_file: @@ -74,7 +73,6 @@ def prompt_initializer( return dot_prompt_manager except Exception as e: - raise e diff --git a/litellm/integrations/dotprompt/dotprompt_manager.py b/litellm/integrations/dotprompt/dotprompt_manager.py index 9412ac3c842..37fdf7da693 100644 --- a/litellm/integrations/dotprompt/dotprompt_manager.py +++ b/litellm/integrations/dotprompt/dotprompt_manager.py @@ -128,7 +128,6 @@ class DotpromptManager(CustomPromptManagement): raise ValueError("prompt_id is required for dotprompt manager") try: - # Get the prompt template (versioned or base) template = self.prompt_manager.get_prompt( prompt_id=prompt_id, version=prompt_version @@ -205,7 +204,6 @@ class DotpromptManager(CustomPromptManagement): ignore_prompt_manager_model: Optional[bool] = False, ignore_prompt_manager_optional_params: Optional[bool] = False, ) -> Tuple[str, List[AllMessageValues], dict]: - from litellm.integrations.prompt_management_base import PromptManagementBase return PromptManagementBase.get_chat_completion_prompt( diff --git a/litellm/integrations/dotprompt/prompt_manager.py b/litellm/integrations/dotprompt/prompt_manager.py index fc5a325ffe1..997a40d545e 100644 --- a/litellm/integrations/dotprompt/prompt_manager.py +++ b/litellm/integrations/dotprompt/prompt_manager.py @@ -205,7 +205,7 @@ class PromptManager: """ # Get the template (versioned or base) template = self.get_prompt(prompt_id=prompt_id, version=version) - + if template is None: available_prompts = list(self.prompts.keys()) version_str = f" (version {version})" if version else "" @@ -266,11 +266,11 @@ class PromptManager: ) -> Optional[PromptTemplate]: """ Get a prompt template by ID and optional version. - + Args: prompt_id: The base prompt ID version: Optional version number. If provided, looks for {prompt_id}.v{version} - + Returns: The prompt template if found, None otherwise """ @@ -279,7 +279,7 @@ class PromptManager: versioned_id = f"{prompt_id}.v{version}" if versioned_id in self.prompts: return self.prompts[versioned_id] - + # Fall back to base prompt_id return self.prompts.get(prompt_id) diff --git a/litellm/integrations/email_templates/key_rotated_email.py b/litellm/integrations/email_templates/key_rotated_email.py index dab7172dc6a..9e6dd41378f 100644 --- a/litellm/integrations/email_templates/key_rotated_email.py +++ b/litellm/integrations/email_templates/key_rotated_email.py @@ -222,4 +222,3 @@ response = client.chat.completions.create(
""" - diff --git a/litellm/integrations/email_templates/templates.py b/litellm/integrations/email_templates/templates.py index 091351df2bb..8df816dfecd 100644 --- a/litellm/integrations/email_templates/templates.py +++ b/litellm/integrations/email_templates/templates.py @@ -131,4 +131,4 @@ MAX_BUDGET_ALERT_EMAIL_TEMPLATE = """ Best,
The LiteLLM team
-""" \ No newline at end of file +""" diff --git a/litellm/integrations/focus/focus_logger.py b/litellm/integrations/focus/focus_logger.py index ade1cf861b1..f493d47e29f 100644 --- a/litellm/integrations/focus/focus_logger.py +++ b/litellm/integrations/focus/focus_logger.py @@ -56,7 +56,9 @@ class FocusLogger(CustomLogger): self.interval_seconds = int(raw_interval) if raw_interval is not None else None env_prefix = os.getenv("FOCUS_PREFIX") self.prefix: str = ( - prefix if prefix is not None else (env_prefix if env_prefix else "focus_exports") + prefix + if prefix is not None + else (env_prefix if env_prefix else "focus_exports") ) self._destination_config = destination_config @@ -208,4 +210,5 @@ class FocusLogger(CustomLogger): frequency=self.frequency, ) + __all__ = ["FocusLogger"] diff --git a/litellm/integrations/gcs_bucket/gcs_bucket.py b/litellm/integrations/gcs_bucket/gcs_bucket.py index 0f1ba4a4093..65296bafcf3 100644 --- a/litellm/integrations/gcs_bucket/gcs_bucket.py +++ b/litellm/integrations/gcs_bucket/gcs_bucket.py @@ -34,7 +34,10 @@ class GCSBucketLogger(GCSBucketBase, AdditionalLoggingUtils): os.getenv("GCS_FLUSH_INTERVAL", GCS_DEFAULT_FLUSH_INTERVAL_SECONDS) ) self.use_batched_logging = ( - os.getenv("GCS_USE_BATCHED_LOGGING", str(GCS_DEFAULT_USE_BATCHED_LOGGING).lower()).lower() == "true" + os.getenv( + "GCS_USE_BATCHED_LOGGING", str(GCS_DEFAULT_USE_BATCHED_LOGGING).lower() + ).lower() + == "true" ) self.flush_lock = asyncio.Lock() super().__init__( @@ -112,9 +115,9 @@ class GCSBucketLogger(GCSBucketBase, AdditionalLoggingUtils): def _drain_queue_batch(self) -> List[GCSLogQueueItem]: """ Drain items from the queue (non-blocking), respecting batch_size limit. - + This prevents unbounded queue growth when processing is slower than log accumulation. - + Returns: List of items to process, up to batch_size items """ @@ -137,33 +140,45 @@ class GCSBucketLogger(GCSBucketBase, AdditionalLoggingUtils): """ Extract a synchronous grouping key from kwargs to group items by GCS config. This allows us to batch items with the same bucket/credentials together. - + Returns a string key that uniquely identifies the GCS config combination. This key may contain sensitive information (bucket names, paths) - use _sanitize_config_key() for logging purposes. """ - standard_callback_dynamic_params = kwargs.get("standard_callback_dynamic_params", None) or {} - - bucket_name = standard_callback_dynamic_params.get("gcs_bucket_name", None) or self.BUCKET_NAME or "default" - path_service_account = standard_callback_dynamic_params.get("gcs_path_service_account", None) or self.path_service_account_json or "default" - + standard_callback_dynamic_params = ( + kwargs.get("standard_callback_dynamic_params", None) or {} + ) + + bucket_name = ( + standard_callback_dynamic_params.get("gcs_bucket_name", None) + or self.BUCKET_NAME + or "default" + ) + path_service_account = ( + standard_callback_dynamic_params.get("gcs_path_service_account", None) + or self.path_service_account_json + or "default" + ) + return f"{bucket_name}|{path_service_account}" - + def _sanitize_config_key(self, config_key: str) -> str: """ Create a sanitized version of the config key for logging. Uses a hash to avoid exposing sensitive bucket names or service account paths. - + Returns a short hash prefix for safe logging. """ - hash_obj = hashlib.sha256(config_key.encode('utf-8')) + hash_obj = hashlib.sha256(config_key.encode("utf-8")) return f"config-{hash_obj.hexdigest()[:8]}" - - def _group_items_by_config(self, items: List[GCSLogQueueItem]) -> Dict[str, List[GCSLogQueueItem]]: + + def _group_items_by_config( + self, items: List[GCSLogQueueItem] + ) -> Dict[str, List[GCSLogQueueItem]]: """ Group items by their GCS config (bucket + credentials). This ensures items with different configs are processed separately. - + Returns a dict mapping config_key -> list of items with that config. """ grouped: Dict[str, List[GCSLogQueueItem]] = {} @@ -186,18 +201,20 @@ class GCSBucketLogger(GCSBucketBase, AdditionalLoggingUtils): lines.append(json_line) return "\n".join(lines) - async def _send_grouped_batch(self, items: List[GCSLogQueueItem], config_key: str) -> Tuple[int, int]: + async def _send_grouped_batch( + self, items: List[GCSLogQueueItem], config_key: str + ) -> Tuple[int, int]: """ Send a batch of items that share the same GCS config. - + Returns: (success_count, error_count) """ if not items: return (0, 0) - + first_kwargs = items[0]["kwargs"] - + try: gcs_logging_config: GCSLoggingConfig = await self.get_gcs_logging_config( first_kwargs @@ -208,23 +225,25 @@ class GCSBucketLogger(GCSBucketBase, AdditionalLoggingUtils): service_account_json=gcs_logging_config["path_service_account"], ) bucket_name = gcs_logging_config["bucket_name"] - - current_date = self._get_object_date_from_datetime(datetime.now(timezone.utc)) + + current_date = self._get_object_date_from_datetime( + datetime.now(timezone.utc) + ) batch_id = f"{int(time.time() * 1000)}-{uuid.uuid4().hex[:8]}" object_name = self._generate_batch_object_name(current_date, batch_id) combined_payload = self._combine_payloads_to_ndjson(items) - + await self._log_json_data_on_gcs( headers=headers, bucket_name=bucket_name, object_name=object_name, logging_payload=combined_payload, ) - + success_count = len(items) error_count = 0 return (success_count, error_count) - + except Exception as e: success_count = 0 error_count = len(items) @@ -255,13 +274,13 @@ class GCSBucketLogger(GCSBucketBase, AdditionalLoggingUtils): service_account_json=gcs_logging_config["path_service_account"], ) bucket_name = gcs_logging_config["bucket_name"] - + object_name = self._get_object_name( kwargs=item["kwargs"], logging_payload=item["payload"], response_obj=item["response_obj"], ) - + await self._log_json_data_on_gcs( headers=headers, bucket_name=bucket_name, @@ -289,7 +308,7 @@ class GCSBucketLogger(GCSBucketBase, AdditionalLoggingUtils): if self.use_batched_logging: grouped_items = self._group_items_by_config(items_to_process) - + for config_key, group_items in grouped_items.items(): await self._send_grouped_batch(group_items, config_key) else: diff --git a/litellm/integrations/gcs_bucket/gcs_bucket_base.py b/litellm/integrations/gcs_bucket/gcs_bucket_base.py index b1db9ec9588..923f613291f 100644 --- a/litellm/integrations/gcs_bucket/gcs_bucket_base.py +++ b/litellm/integrations/gcs_bucket/gcs_bucket_base.py @@ -7,7 +7,7 @@ from litellm.integrations.gcs_bucket.gcs_bucket_mock_client import ( create_mock_gcs_client, mock_vertex_auth_methods, ) - + from litellm._logging import verbose_logger from litellm.integrations.custom_batch_logger import CustomBatchLogger @@ -28,11 +28,11 @@ IAM_AUTH_KEY = "IAM_AUTH" class GCSBucketBase(CustomBatchLogger): def __init__(self, bucket_name: Optional[str] = None, **kwargs) -> None: self.is_mock_mode = should_use_gcs_mock() - + if self.is_mock_mode: mock_vertex_auth_methods() create_mock_gcs_client() - + self.async_httpx_client = get_async_httpx_client( llm_provider=httpxSpecialProvider.LoggingCallback ) @@ -85,10 +85,10 @@ class GCSBucketBase(CustomBatchLogger): from litellm import vertex_chat_completion # Get project_id from environment if available, otherwise None - # This helps support use of this library to auth to pull secrets + # This helps support use of this library to auth to pull secrets # from Secret Manager. project_id = os.getenv("GOOGLE_SECRET_MANAGER_PROJECT_ID") - + _auth_header, vertex_project = vertex_chat_completion._ensure_access_token( credentials=self.path_service_account_json, project_id=project_id, diff --git a/litellm/integrations/gcs_bucket/gcs_bucket_mock_client.py b/litellm/integrations/gcs_bucket/gcs_bucket_mock_client.py index 2d14f5eb962..1761fe010c9 100644 --- a/litellm/integrations/gcs_bucket/gcs_bucket_mock_client.py +++ b/litellm/integrations/gcs_bucket/gcs_bucket_mock_client.py @@ -11,7 +11,11 @@ Usage: import asyncio from litellm._logging import verbose_logger -from litellm.integrations.mock_client_factory import MockClientConfig, create_mock_client_factory, MockResponse +from litellm.integrations.mock_client_factory import ( + MockClientConfig, + create_mock_client_factory, + MockResponse, +) # Use factory for POST handler _config = MockClientConfig( @@ -34,10 +38,14 @@ _mocks_initialized = False # Default mock latency in seconds (simulates network round-trip) # Typical GCS API calls take 100-300ms for uploads, 50-150ms for GET/DELETE -_MOCK_LATENCY_SECONDS = float(__import__("os").getenv("GCS_MOCK_LATENCY_MS", "150")) / 1000.0 +_MOCK_LATENCY_SECONDS = ( + float(__import__("os").getenv("GCS_MOCK_LATENCY_MS", "150")) / 1000.0 +) -async def _mock_async_handler_get(self, url, params=None, headers=None, follow_redirects=None): +async def _mock_async_handler_get( + self, url, params=None, headers=None, follow_redirects=None +): """Monkey-patched AsyncHTTPHandler.get that intercepts GCS calls.""" # Only mock GCS API calls if isinstance(url, str) and "storage.googleapis.com" in url: @@ -86,14 +94,30 @@ async def _mock_async_handler_get(self, url, params=None, headers=None, follow_r status_code=200, json_data=mock_payload, url=url, - elapsed_seconds=_MOCK_LATENCY_SECONDS + elapsed_seconds=_MOCK_LATENCY_SECONDS, ) if _original_async_handler_get is not None: - return await _original_async_handler_get(self, url=url, params=params, headers=headers, follow_redirects=follow_redirects) + return await _original_async_handler_get( + self, + url=url, + params=params, + headers=headers, + follow_redirects=follow_redirects, + ) raise RuntimeError("Original AsyncHTTPHandler.get not available") -async def _mock_async_handler_delete(self, url, data=None, json=None, params=None, headers=None, timeout=None, stream=False, content=None): +async def _mock_async_handler_delete( + self, + url, + data=None, + json=None, + params=None, + headers=None, + timeout=None, + stream=False, + content=None, +): """Monkey-patched AsyncHTTPHandler.delete that intercepts GCS calls.""" # Only mock GCS API calls if isinstance(url, str) and "storage.googleapis.com" in url: @@ -104,49 +128,61 @@ async def _mock_async_handler_delete(self, url, data=None, json=None, params=Non status_code=204, json_data=None, # Empty body for DELETE url=url, - elapsed_seconds=_MOCK_LATENCY_SECONDS + elapsed_seconds=_MOCK_LATENCY_SECONDS, ) if _original_async_handler_delete is not None: - return await _original_async_handler_delete(self, url=url, data=data, json=json, params=params, headers=headers, timeout=timeout, stream=stream, content=content) + return await _original_async_handler_delete( + self, + url=url, + data=data, + json=json, + params=params, + headers=headers, + timeout=timeout, + stream=stream, + content=content, + ) raise RuntimeError("Original AsyncHTTPHandler.delete not available") def create_mock_gcs_client(): """ Monkey-patch AsyncHTTPHandler methods to intercept GCS calls. - + AsyncHTTPHandler is used by LiteLLM's get_async_httpx_client() which is what GCSBucketBase uses for making API calls. - + This function is idempotent - it only initializes mocks once, even if called multiple times. """ global _original_async_handler_get, _original_async_handler_delete, _mocks_initialized - + # Use factory for POST handler _create_mock_gcs_post() - + # If already initialized, skip GET/DELETE patching if _mocks_initialized: return - + verbose_logger.debug("[GCS MOCK] Initializing GCS GET/DELETE handlers...") - + # Patch GET and DELETE handlers (GCS-specific) from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler - + if _original_async_handler_get is None: _original_async_handler_get = AsyncHTTPHandler.get AsyncHTTPHandler.get = _mock_async_handler_get # type: ignore verbose_logger.debug("[GCS MOCK] Patched AsyncHTTPHandler.get") - + if _original_async_handler_delete is None: _original_async_handler_delete = AsyncHTTPHandler.delete AsyncHTTPHandler.delete = _mock_async_handler_delete # type: ignore verbose_logger.debug("[GCS MOCK] Patched AsyncHTTPHandler.delete") - - verbose_logger.debug(f"[GCS MOCK] Mock latency set to {_MOCK_LATENCY_SECONDS*1000:.0f}ms") + + verbose_logger.debug( + f"[GCS MOCK] Mock latency set to {_MOCK_LATENCY_SECONDS*1000:.0f}ms" + ) verbose_logger.debug("[GCS MOCK] GCS mock client initialization complete") - + _mocks_initialized = True @@ -154,38 +190,64 @@ def mock_vertex_auth_methods(): """ Monkey-patch Vertex AI auth methods to return fake tokens. This prevents auth failures when GCS_MOCK is enabled. - + This function is idempotent - it only patches once, even if called multiple times. """ from litellm.llms.vertex_ai.vertex_llm_base import VertexBase - + # Store original methods if not already stored - if not hasattr(VertexBase, '_original_ensure_access_token_async'): - setattr(VertexBase, '_original_ensure_access_token_async', VertexBase._ensure_access_token_async) - setattr(VertexBase, '_original_ensure_access_token', VertexBase._ensure_access_token) - setattr(VertexBase, '_original_get_token_and_url', VertexBase._get_token_and_url) - - async def _mock_ensure_access_token_async(self, credentials, project_id, custom_llm_provider): + if not hasattr(VertexBase, "_original_ensure_access_token_async"): + setattr( + VertexBase, + "_original_ensure_access_token_async", + VertexBase._ensure_access_token_async, + ) + setattr( + VertexBase, "_original_ensure_access_token", VertexBase._ensure_access_token + ) + setattr( + VertexBase, "_original_get_token_and_url", VertexBase._get_token_and_url + ) + + async def _mock_ensure_access_token_async( + self, credentials, project_id, custom_llm_provider + ): """Mock async auth method - returns fake token.""" - verbose_logger.debug("[GCS MOCK] Vertex AI auth: _ensure_access_token_async called") + verbose_logger.debug( + "[GCS MOCK] Vertex AI auth: _ensure_access_token_async called" + ) return ("mock-gcs-token", "mock-project-id") - - def _mock_ensure_access_token(self, credentials, project_id, custom_llm_provider): + + def _mock_ensure_access_token( + self, credentials, project_id, custom_llm_provider + ): """Mock sync auth method - returns fake token.""" - verbose_logger.debug("[GCS MOCK] Vertex AI auth: _ensure_access_token called") + verbose_logger.debug( + "[GCS MOCK] Vertex AI auth: _ensure_access_token called" + ) return ("mock-gcs-token", "mock-project-id") - - def _mock_get_token_and_url(self, model, auth_header, vertex_credentials, vertex_project, - vertex_location, gemini_api_key, stream, custom_llm_provider, api_base): + + def _mock_get_token_and_url( + self, + model, + auth_header, + vertex_credentials, + vertex_project, + vertex_location, + gemini_api_key, + stream, + custom_llm_provider, + api_base, + ): """Mock get_token_and_url - returns fake token.""" verbose_logger.debug("[GCS MOCK] Vertex AI auth: _get_token_and_url called") return ("mock-gcs-token", "https://storage.googleapis.com") - + # Patch the methods VertexBase._ensure_access_token_async = _mock_ensure_access_token_async # type: ignore VertexBase._ensure_access_token = _mock_ensure_access_token # type: ignore VertexBase._get_token_and_url = _mock_get_token_and_url # type: ignore - + verbose_logger.debug("[GCS MOCK] Patched Vertex AI auth methods") diff --git a/litellm/integrations/generic_api/generic_api_callback.py b/litellm/integrations/generic_api/generic_api_callback.py index 1c62ce9fcc3..9a8060520d6 100644 --- a/litellm/integrations/generic_api/generic_api_callback.py +++ b/litellm/integrations/generic_api/generic_api_callback.py @@ -164,7 +164,11 @@ class GenericAPILogger(CustomBatchLogger): self.callback_name: Optional[str] = callback_name # Validate and store log_format - if log_format is not None and log_format not in ["json_array", "ndjson", "single"]: + if log_format is not None and log_format not in [ + "json_array", + "ndjson", + "single", + ]: raise ValueError( f"Invalid log_format: {log_format}. Must be one of: 'json_array', 'ndjson', 'single'" ) diff --git a/litellm/integrations/generic_prompt_management/generic_prompt_manager.py b/litellm/integrations/generic_prompt_management/generic_prompt_manager.py index 9490d9fde1c..858bfd458b6 100644 --- a/litellm/integrations/generic_prompt_management/generic_prompt_manager.py +++ b/litellm/integrations/generic_prompt_management/generic_prompt_manager.py @@ -120,7 +120,6 @@ class GenericPromptManager(CustomPromptManagement): http_client = _get_httpx_client() try: - response = http_client.get( url, params=params, @@ -325,7 +324,6 @@ class GenericPromptManager(CustomPromptManagement): prompt_label: Optional[str] = None, prompt_version: Optional[int] = None, ) -> PromptManagementClient: - # Check cache first cached_prompt = self._common_caching_logic( prompt_id=prompt_id, diff --git a/litellm/integrations/gitlab/__init__.py b/litellm/integrations/gitlab/__init__.py index c73a23b6874..24e7ddea9e8 100644 --- a/litellm/integrations/gitlab/__init__.py +++ b/litellm/integrations/gitlab/__init__.py @@ -39,11 +39,8 @@ def prompt_initializer( gitlab_config = getattr(litellm_params, "gitlab_config", None) prompt_id = getattr(litellm_params, "prompt_id", None) - if not gitlab_config: - raise ValueError( - "gitlab_config is required for gitlab prompt integration" - ) + raise ValueError("gitlab_config is required for gitlab prompt integration") try: gitlab_prompt_manager = GitLabPromptManager( @@ -55,9 +52,10 @@ def prompt_initializer( except Exception as e: raise e + def _gitlab_prompt_initializer( - litellm_params: PromptLiteLLMParams, - prompt: PromptSpec, + litellm_params: PromptLiteLLMParams, + prompt: PromptSpec, ) -> CustomPromptManagement: """ Build a GitLab-backed prompt manager for this prompt. diff --git a/litellm/integrations/gitlab/gitlab_client.py b/litellm/integrations/gitlab/gitlab_client.py index ce03a35d48e..60f73256185 100644 --- a/litellm/integrations/gitlab/gitlab_client.py +++ b/litellm/integrations/gitlab/gitlab_client.py @@ -45,7 +45,7 @@ class GitLabClient: self.auth_method = config.get("auth_method", "token") # 'token' or 'oauth' self.branch = config.get("branch", None) if not self.branch: - self.branch = 'main' + self.branch = "main" self.tag = config.get("tag") self.base_url = config.get("base_url", "https://gitlab.com/api/v4") @@ -86,7 +86,13 @@ class GitLabClient: ref_q = quote(ref or self.ref, safe="") return f"{self.base_url}/projects/{self._project_enc}/repository/files/{file_enc}?ref={ref_q}" - def _tree_url(self, directory_path: str = "", recursive: bool = False, *, ref: Optional[str] = None) -> str: + def _tree_url( + self, + directory_path: str = "", + recursive: bool = False, + *, + ref: Optional[str] = None, + ) -> str: path_q = f"&path={quote(directory_path, safe='')}" if directory_path else "" rec_q = "&recursive=true" if recursive else "" ref_q = quote(ref or self.ref, safe="") @@ -102,7 +108,9 @@ class GitLabClient: raise ValueError("ref must be a non-empty string") self.ref = ref - def get_file_content(self, file_path: str, *, ref: Optional[str] = None) -> Optional[str]: + def get_file_content( + self, file_path: str, *, ref: Optional[str] = None + ) -> Optional[str]: """ Fetch the content of a file from the GitLab repository at the given ref (tag, branch, or commit SHA). If `ref` is None, uses self.ref. @@ -124,7 +132,11 @@ class GitLabClient: resp.raise_for_status() ctype = (resp.headers.get("content-type") or "").lower() - if ctype.startswith("text/") or "charset=" in ctype or ctype.startswith("application/json"): + if ( + ctype.startswith("text/") + or "charset=" in ctype + or ctype.startswith("application/json") + ): return resp.text try: return resp.content.decode("utf-8") @@ -140,10 +152,14 @@ class GitLabClient: f"Access denied to file '{file_path}'. Check your GitLab permissions for project '{self.project}'." ) if status == 401: - raise Exception("Authentication failed. Check your GitLab token and auth_method.") + raise Exception( + "Authentication failed. Check your GitLab token and auth_method." + ) raise Exception(f"Failed to fetch file '{file_path}': {e}") - def _get_file_content_via_json(self, file_path: str, *, ref: Optional[str] = None) -> Optional[str]: + def _get_file_content_via_json( + self, file_path: str, *, ref: Optional[str] = None + ) -> Optional[str]: """ Fallback for get_file_content(): use the JSON file API which returns base64 content. """ @@ -171,16 +187,20 @@ class GitLabClient: f"Access denied to file '{file_path}'. Check your GitLab permissions for project '{self.project}'." ) if status == 401: - raise Exception("Authentication failed. Check your GitLab token and auth_method.") - raise Exception(f"Failed to fetch file '{file_path}' via JSON endpoint: {e}") + raise Exception( + "Authentication failed. Check your GitLab token and auth_method." + ) + raise Exception( + f"Failed to fetch file '{file_path}' via JSON endpoint: {e}" + ) def list_files( - self, - directory_path: str = "", - file_extension: str = ".prompt", - recursive: bool = False, - *, - ref: Optional[str] = None, + self, + directory_path: str = "", + file_extension: str = ".prompt", + recursive: bool = False, + *, + ref: Optional[str] = None, ) -> List[str]: """ List files in a directory with a specific extension using the repository tree API. @@ -220,7 +240,9 @@ class GitLabClient: f"Access denied to directory '{directory_path}'. Check your GitLab permissions for project '{self.project}'." ) if status == 401: - raise Exception("Authentication failed. Check your GitLab token and auth_method.") + raise Exception( + "Authentication failed. Check your GitLab token and auth_method." + ) raise Exception(f"Failed to list files in '{directory_path}': {e}") def get_repository_info(self) -> Dict[str, Any]: @@ -252,7 +274,9 @@ class GitLabClient: except Exception as e: raise Exception(f"Failed to get branches: {e}") - def get_file_metadata(self, file_path: str, *, ref: Optional[str] = None) -> Optional[Dict[str, Any]]: + def get_file_metadata( + self, file_path: str, *, ref: Optional[str] = None + ) -> Optional[Dict[str, Any]]: """ Get minimal metadata about a file via RAW endpoint headers at a given ref. diff --git a/litellm/integrations/helicone.py b/litellm/integrations/helicone.py index 51e6699c5f4..376952033a0 100644 --- a/litellm/integrations/helicone.py +++ b/litellm/integrations/helicone.py @@ -31,8 +31,10 @@ class HeliconeLogger: self.is_mock_mode = should_use_helicone_mock() if self.is_mock_mode: create_mock_helicone_client() - verbose_logger.info("[HELICONE MOCK] Helicone logger initialized in mock mode") - + verbose_logger.info( + "[HELICONE MOCK] Helicone logger initialized in mock mode" + ) + self.provider_url = "https://api.openai.com/v1" self.key = os.getenv("HELICONE_API_KEY") self.api_base = os.getenv("HELICONE_API_BASE") or "https://api.hconeai.com" @@ -111,7 +113,7 @@ class HeliconeLogger: for header_key in proxy_headers: if header_key.startswith("helicone_"): metadata[header_key] = proxy_headers.get(header_key) - + # Remove OpenTelemetry span from metadata as it's not JSON serializable # The span is used internally for tracing but shouldn't be logged to external services if "litellm_parent_otel_span" in metadata: @@ -134,14 +136,17 @@ class HeliconeLogger: metadata = self.add_metadata_from_header(litellm_params, metadata) # Check if model is a vertex_ai model - is_vertex_ai = custom_llm_provider == "vertex_ai" or model.startswith("vertex_ai/") + is_vertex_ai = custom_llm_provider == "vertex_ai" or model.startswith( + "vertex_ai/" + ) model = ( model if any( accepted_model in model for accepted_model in self.helicone_model_list - ) or is_vertex_ai + ) + or is_vertex_ai else "gpt-3.5-turbo" ) provider_request = {"model": model, "messages": messages} @@ -208,7 +213,9 @@ class HeliconeLogger: response = litellm.module_level_client.post(url, headers=headers, json=data) if response.status_code == 200: if self.is_mock_mode: - print_verbose("[HELICONE MOCK] Helicone Logging - Successfully mocked!") + print_verbose( + "[HELICONE MOCK] Helicone Logging - Successfully mocked!" + ) else: print_verbose("Helicone Logging - Success!") else: diff --git a/litellm/integrations/helicone_mock_client.py b/litellm/integrations/helicone_mock_client.py index 0f4670a1d2c..c2d3dfdf5bc 100644 --- a/litellm/integrations/helicone_mock_client.py +++ b/litellm/integrations/helicone_mock_client.py @@ -8,7 +8,10 @@ Usage: Set HELICONE_MOCK=true in environment variables or config to enable mock mode. """ -from litellm.integrations.mock_client_factory import MockClientConfig, create_mock_client_factory +from litellm.integrations.mock_client_factory import ( + MockClientConfig, + create_mock_client_factory, +) # Create mock client using factory # Helicone uses HTTPHandler which internally uses httpx.Client.send(), not httpx.Client.post() @@ -29,4 +32,6 @@ _config = MockClientConfig( patch_http_handler=True, # Patch HTTPHandler.post directly ) -create_mock_helicone_client, should_use_helicone_mock = create_mock_client_factory(_config) +create_mock_helicone_client, should_use_helicone_mock = create_mock_client_factory( + _config +) diff --git a/litellm/integrations/humanloop.py b/litellm/integrations/humanloop.py index 369df5ee0bd..11414869a65 100644 --- a/litellm/integrations/humanloop.py +++ b/litellm/integrations/humanloop.py @@ -162,11 +162,7 @@ class HumanloopLogger(CustomLogger): prompt_version: Optional[int] = None, ignore_prompt_manager_model: Optional[bool] = False, ignore_prompt_manager_optional_params: Optional[bool] = False, - ) -> Tuple[ - str, - List[AllMessageValues], - dict, - ]: + ) -> Tuple[str, List[AllMessageValues], dict,]: humanloop_api_key = dynamic_callback_params.get( "humanloop_api_key" ) or get_secret_str("HUMANLOOP_API_KEY") diff --git a/litellm/integrations/langfuse/langfuse.py b/litellm/integrations/langfuse/langfuse.py index 7bf97665fd2..9d6ddd0f1e9 100644 --- a/litellm/integrations/langfuse/langfuse.py +++ b/litellm/integrations/langfuse/langfuse.py @@ -123,7 +123,7 @@ class LangFuseLogger: self.langfuse_flush_interval = LangFuseLogger._get_langfuse_flush_interval( flush_interval ) - + if should_use_langfuse_mock(): self.langfuse_client = create_mock_langfuse_client() self.is_mock_mode = True @@ -607,9 +607,7 @@ class LangFuseLogger: # Use standard_logging_object.trace_id if available (when trace_id from metadata is None) # This allows standard trace_id to be used when provided in standard_logging_object if trace_id is None and standard_logging_object is not None: - trace_id = cast( - Optional[str], standard_logging_object.get("trace_id") - ) + trace_id = cast(Optional[str], standard_logging_object.get("trace_id")) # Fallback to litellm_call_id if no trace_id found if trace_id is None: trace_id = litellm_call_id diff --git a/litellm/integrations/langfuse/langfuse_mock_client.py b/litellm/integrations/langfuse/langfuse_mock_client.py index 8ed6cff8d47..b7862274f62 100644 --- a/litellm/integrations/langfuse/langfuse_mock_client.py +++ b/litellm/integrations/langfuse/langfuse_mock_client.py @@ -9,7 +9,10 @@ Usage: """ import httpx -from litellm.integrations.mock_client_factory import MockClientConfig, create_mock_client_factory +from litellm.integrations.mock_client_factory import ( + MockClientConfig, + create_mock_client_factory, +) # Create mock client using factory _config = MockClientConfig( @@ -26,7 +29,11 @@ _config = MockClientConfig( patch_sync_client=True, ) -_create_mock_langfuse_client_internal, should_use_langfuse_mock = create_mock_client_factory(_config) +( + _create_mock_langfuse_client_internal, + should_use_langfuse_mock, +) = create_mock_client_factory(_config) + # Langfuse needs to return an httpx.Client instance def create_mock_langfuse_client(): diff --git a/litellm/integrations/langfuse/langfuse_prompt_management.py b/litellm/integrations/langfuse/langfuse_prompt_management.py index 3986fc6a6ef..f0e1e30b689 100644 --- a/litellm/integrations/langfuse/langfuse_prompt_management.py +++ b/litellm/integrations/langfuse/langfuse_prompt_management.py @@ -318,7 +318,7 @@ class LangfusePromptManagement(LangFuseLogger, PromptManagementBase, CustomLogge ) except Exception as e: from litellm._logging import verbose_logger - + verbose_logger.exception( f"Langfuse Layer Error - Exception occurred while logging success event: {str(e)}" ) @@ -351,7 +351,7 @@ class LangfusePromptManagement(LangFuseLogger, PromptManagementBase, CustomLogge ) except Exception as e: from litellm._logging import verbose_logger - + verbose_logger.exception( f"Langfuse Layer Error - Exception occurred while logging failure event: {str(e)}" ) diff --git a/litellm/integrations/langsmith.py b/litellm/integrations/langsmith.py index ebd005f8804..03845af521d 100644 --- a/litellm/integrations/langsmith.py +++ b/litellm/integrations/langsmith.py @@ -50,11 +50,13 @@ class LangsmithLogger(CustomBatchLogger): self.flush_lock = asyncio.Lock() super().__init__(**kwargs, flush_lock=self.flush_lock) self.is_mock_mode = should_use_langsmith_mock() - + if self.is_mock_mode: create_mock_langsmith_client() - verbose_logger.debug("[LANGSMITH MOCK] LangSmith logger initialized in mock mode") - + verbose_logger.debug( + "[LANGSMITH MOCK] LangSmith logger initialized in mock mode" + ) + self.default_credentials = self.get_credentials_from_env( langsmith_api_key=langsmith_api_key, langsmith_project=langsmith_project, @@ -399,7 +401,9 @@ class LangsmithLogger(CustomBatchLogger): "Sending batch of %s runs to Langsmith", len(elements_to_log) ) if self.is_mock_mode: - verbose_logger.debug("[LANGSMITH MOCK] Mock mode enabled - API calls will be intercepted") + verbose_logger.debug( + "[LANGSMITH MOCK] Mock mode enabled - API calls will be intercepted" + ) response = await self.async_httpx_client.post( url=url, json={"post": elements_to_log}, diff --git a/litellm/integrations/langsmith_mock_client.py b/litellm/integrations/langsmith_mock_client.py index ef602908231..0226bdecc27 100644 --- a/litellm/integrations/langsmith_mock_client.py +++ b/litellm/integrations/langsmith_mock_client.py @@ -8,7 +8,10 @@ Usage: Set LANGSMITH_MOCK=true in environment variables or config to enable mock mode. """ -from litellm.integrations.mock_client_factory import MockClientConfig, create_mock_client_factory +from litellm.integrations.mock_client_factory import ( + MockClientConfig, + create_mock_client_factory, +) # Create mock client using factory _config = MockClientConfig( @@ -26,4 +29,6 @@ _config = MockClientConfig( patch_sync_client=False, ) -create_mock_langsmith_client, should_use_langsmith_mock = create_mock_client_factory(_config) +create_mock_langsmith_client, should_use_langsmith_mock = create_mock_client_factory( + _config +) diff --git a/litellm/integrations/levo/levo.py b/litellm/integrations/levo/levo.py index 562f2fd9068..4b08ce50f74 100644 --- a/litellm/integrations/levo/levo.py +++ b/litellm/integrations/levo/levo.py @@ -6,7 +6,9 @@ from litellm.integrations.opentelemetry import OpenTelemetry if TYPE_CHECKING: from opentelemetry.trace import Span as _Span - from litellm.integrations.opentelemetry import OpenTelemetryConfig as _OpenTelemetryConfig + from litellm.integrations.opentelemetry import ( + OpenTelemetryConfig as _OpenTelemetryConfig, + ) from litellm.types.integrations.arize import Protocol as _Protocol Protocol = _Protocol @@ -114,4 +116,3 @@ class LevoLogger(OpenTelemetry): "status": "unhealthy", "error_message": str(e), } - diff --git a/litellm/integrations/mock_client_factory.py b/litellm/integrations/mock_client_factory.py index 2f04fae9f76..3f2f0ae5b6d 100644 --- a/litellm/integrations/mock_client_factory.py +++ b/litellm/integrations/mock_client_factory.py @@ -19,16 +19,21 @@ from litellm._logging import verbose_logger @dataclass class MockClientConfig: """Configuration for creating a mock client.""" + name: str # e.g., "GCS", "LANGFUSE", "LANGSMITH", "DATADOG" env_var: str # e.g., "GCS_MOCK", "LANGFUSE_MOCK" default_latency_ms: int = 100 # Default mock latency in milliseconds default_status_code: int = 200 # Default HTTP status code default_json_data: Optional[Dict] = None # Default JSON response data - url_matchers: Optional[List[str]] = None # List of strings to match in URLs (e.g., ["storage.googleapis.com"]) + url_matchers: Optional[ + List[str] + ] = None # List of strings to match in URLs (e.g., ["storage.googleapis.com"]) patch_async_handler: bool = True # Whether to patch AsyncHTTPHandler.post patch_sync_client: bool = False # Whether to patch httpx.Client.post - patch_http_handler: bool = False # Whether to patch HTTPHandler.post (for sync calls that use HTTPHandler) - + patch_http_handler: bool = ( + False # Whether to patch HTTPHandler.post (for sync calls that use HTTPHandler) + ) + def __post_init__(self): """Ensure url_matchers is a list.""" if self.url_matchers is None: @@ -37,8 +42,14 @@ class MockClientConfig: class MockResponse: """Generic mock httpx.Response that satisfies API requirements.""" - - def __init__(self, status_code: int = 200, json_data: Optional[Dict] = None, url: Optional[str] = None, elapsed_seconds: float = 0.0): + + def __init__( + self, + status_code: int = 200, + json_data: Optional[Dict] = None, + url: Optional[str] = None, + elapsed_seconds: float = 0.0, + ): self.status_code = status_code self._json_data = json_data or {"status": "success"} self.headers = httpx.Headers({}) @@ -49,25 +60,25 @@ class MockResponse: self.elapsed = timedelta(seconds=elapsed_seconds) self._text = json.dumps(self._json_data) if json_data else "" self._content = self._text.encode("utf-8") - + @property def text(self) -> str: """Return response text.""" return self._text - + @property def content(self) -> bytes: """Return response content.""" return self._content - + def json(self) -> Dict: """Return JSON response data.""" return self._json_data - + def read(self) -> bytes: """Read response content.""" return self._content - + def raise_for_status(self): """Raise exception for error status codes.""" if self.status_code >= 400: @@ -80,17 +91,17 @@ def _is_url_match(url, matchers: List[str]) -> bool: parsed_url = httpx.URL(url) if isinstance(url, str) else url url_str = str(parsed_url).lower() hostname = parsed_url.host or "" - + for matcher in matchers: if matcher.lower() in url_str or matcher.lower() in hostname.lower(): return True - + # Also check for localhost with matcher in path if hostname in ("localhost", "127.0.0.1"): for matcher in matchers: if matcher.lower() in url_str: return True - + return False except Exception: return False @@ -99,7 +110,7 @@ def _is_url_match(url, matchers: List[str]) -> bool: def create_mock_client_factory(config: MockClientConfig): # noqa: PLR0915 """ Factory function that creates mock client functions based on configuration. - + Returns: tuple: (create_mock_client_func, should_use_mock_func) """ @@ -108,19 +119,34 @@ def create_mock_client_factory(config: MockClientConfig): # noqa: PLR0915 _original_sync_client_post = None _original_http_handler_post = None _mocks_initialized = False - + # Calculate mock latency import os + latency_env = f"{config.name.upper()}_MOCK_LATENCY_MS" - _MOCK_LATENCY_SECONDS = float(os.getenv(latency_env, str(config.default_latency_ms))) / 1000.0 - + _MOCK_LATENCY_SECONDS = ( + float(os.getenv(latency_env, str(config.default_latency_ms))) / 1000.0 + ) + # Create URL matcher function def _is_mock_url(url) -> bool: # url_matchers is guaranteed to be a list after __post_init__ return _is_url_match(url, cast(List[str], config.url_matchers)) - + # Create async handler mock - async def _mock_async_handler_post(self, url, data=None, json=None, params=None, headers=None, timeout=None, stream=False, logging_obj=None, files=None, content=None): + async def _mock_async_handler_post( + self, + url, + data=None, + json=None, + params=None, + headers=None, + timeout=None, + stream=False, + logging_obj=None, + files=None, + content=None, + ): """Monkey-patched AsyncHTTPHandler.post that intercepts API calls.""" if isinstance(url, str) and _is_mock_url(url): verbose_logger.info(f"[{config.name} MOCK] POST to {url}") @@ -129,12 +155,24 @@ def create_mock_client_factory(config: MockClientConfig): # noqa: PLR0915 status_code=config.default_status_code, json_data=config.default_json_data, url=url, - elapsed_seconds=_MOCK_LATENCY_SECONDS + elapsed_seconds=_MOCK_LATENCY_SECONDS, ) if _original_async_handler_post is not None: - return await _original_async_handler_post(self, url=url, data=data, json=json, params=params, headers=headers, timeout=timeout, stream=stream, logging_obj=logging_obj, files=files, content=content) + return await _original_async_handler_post( + self, + url=url, + data=data, + json=json, + params=params, + headers=headers, + timeout=timeout, + stream=stream, + logging_obj=logging_obj, + files=files, + content=content, + ) raise RuntimeError("Original AsyncHTTPHandler.post not available") - + # Create sync client mock def _mock_sync_client_post(self, url, **kwargs): """Monkey-patched httpx.Client.post that intercepts API calls.""" @@ -144,73 +182,108 @@ def create_mock_client_factory(config: MockClientConfig): # noqa: PLR0915 status_code=config.default_status_code, json_data=config.default_json_data, url=url, - elapsed_seconds=_MOCK_LATENCY_SECONDS + elapsed_seconds=_MOCK_LATENCY_SECONDS, ) if _original_sync_client_post is not None: return _original_sync_client_post(self, url, **kwargs) - + # Create HTTPHandler mock (for sync calls that use HTTPHandler.post) - def _mock_http_handler_post(self, url, data=None, json=None, params=None, headers=None, timeout=None, stream=False, files=None, content=None, logging_obj=None): + def _mock_http_handler_post( + self, + url, + data=None, + json=None, + params=None, + headers=None, + timeout=None, + stream=False, + files=None, + content=None, + logging_obj=None, + ): """Monkey-patched HTTPHandler.post that intercepts API calls.""" if isinstance(url, str) and _is_mock_url(url): verbose_logger.info(f"[{config.name} MOCK] POST to {url}") import time + time.sleep(_MOCK_LATENCY_SECONDS) return MockResponse( status_code=config.default_status_code, json_data=config.default_json_data, url=url, - elapsed_seconds=_MOCK_LATENCY_SECONDS + elapsed_seconds=_MOCK_LATENCY_SECONDS, ) if _original_http_handler_post is not None: - return _original_http_handler_post(self, url=url, data=data, json=json, params=params, headers=headers, timeout=timeout, stream=stream, files=files, content=content, logging_obj=logging_obj) + return _original_http_handler_post( + self, + url=url, + data=data, + json=json, + params=params, + headers=headers, + timeout=timeout, + stream=stream, + files=files, + content=content, + logging_obj=logging_obj, + ) raise RuntimeError("Original HTTPHandler.post not available") - + # Create mock client initialization function def create_mock_client(): """Initialize the mock client by patching HTTP handlers.""" nonlocal _original_async_handler_post, _original_sync_client_post, _original_http_handler_post, _mocks_initialized - + if _mocks_initialized: return - - verbose_logger.debug(f"[{config.name} MOCK] Initializing {config.name} mock client...") - + + verbose_logger.debug( + f"[{config.name} MOCK] Initializing {config.name} mock client..." + ) + if config.patch_async_handler and _original_async_handler_post is None: from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler + _original_async_handler_post = AsyncHTTPHandler.post AsyncHTTPHandler.post = _mock_async_handler_post # type: ignore verbose_logger.debug(f"[{config.name} MOCK] Patched AsyncHTTPHandler.post") - + if config.patch_sync_client and _original_sync_client_post is None: _original_sync_client_post = httpx.Client.post httpx.Client.post = _mock_sync_client_post # type: ignore verbose_logger.debug(f"[{config.name} MOCK] Patched httpx.Client.post") - + if config.patch_http_handler and _original_http_handler_post is None: from litellm.llms.custom_httpx.http_handler import HTTPHandler + _original_http_handler_post = HTTPHandler.post HTTPHandler.post = _mock_http_handler_post # type: ignore verbose_logger.debug(f"[{config.name} MOCK] Patched HTTPHandler.post") - - verbose_logger.debug(f"[{config.name} MOCK] Mock latency set to {_MOCK_LATENCY_SECONDS*1000:.0f}ms") - verbose_logger.debug(f"[{config.name} MOCK] {config.name} mock client initialization complete") - + + verbose_logger.debug( + f"[{config.name} MOCK] Mock latency set to {_MOCK_LATENCY_SECONDS*1000:.0f}ms" + ) + verbose_logger.debug( + f"[{config.name} MOCK] {config.name} mock client initialization complete" + ) + _mocks_initialized = True - + # Create should_use_mock function def should_use_mock() -> bool: """Determine if mock mode should be enabled.""" import os from litellm.secret_managers.main import str_to_bool - + mock_mode = os.getenv(config.env_var, "false") result = str_to_bool(mock_mode) result = bool(result) if result is not None else False - + if result: - verbose_logger.info(f"{config.name} Mock Mode: ENABLED - API calls will be mocked") - + verbose_logger.info( + f"{config.name} Mock Mode: ENABLED - API calls will be mocked" + ) + return result - + return create_mock_client, should_use_mock diff --git a/litellm/integrations/openmeter.py b/litellm/integrations/openmeter.py index b8fb64ec287..5a8ab4bcc9f 100644 --- a/litellm/integrations/openmeter.py +++ b/litellm/integrations/openmeter.py @@ -66,19 +66,19 @@ class OpenMeterLogger(CustomLogger): } user_param = kwargs.get("user", None) # end-user passed in via 'user' param - + # If no user provided directly, try to get it from token user_id if user_param is None: # Check if user_id is available from the API key metadata litellm_params = kwargs.get("litellm_params", {}) metadata = litellm_params.get("metadata", {}) user_api_key_user_id = metadata.get("user_api_key_user_id", None) - + if user_api_key_user_id is not None: user_param = user_api_key_user_id else: raise Exception("OpenMeter: user is required") - + # Ensure subject is always a string for OpenMeter API subject = str(user_param) diff --git a/litellm/integrations/opentelemetry.py b/litellm/integrations/opentelemetry.py index a77a6f73b11..7689a6cc7e4 100644 --- a/litellm/integrations/opentelemetry.py +++ b/litellm/integrations/opentelemetry.py @@ -1611,9 +1611,8 @@ class OpenTelemetry(CustomLogger): # the litellm call ID so every call type can be correlated # across LiteLLM UI, Phoenix traces, and provider logs (Issue #8). response_id = ( - (response_obj.get("id") if response_obj else None) - or standard_logging_payload.get("id") - ) + response_obj.get("id") if response_obj else None + ) or standard_logging_payload.get("id") if response_id: self.safe_set_attribute( span=span, diff --git a/litellm/integrations/opik/opik_payload_builder/api.py b/litellm/integrations/opik/opik_payload_builder/api.py index 99dbea165e9..e3ffab80ae8 100644 --- a/litellm/integrations/opik/opik_payload_builder/api.py +++ b/litellm/integrations/opik/opik_payload_builder/api.py @@ -97,11 +97,11 @@ def build_opik_payload( # Always create a span usage = utils.create_usage_object(response_obj["usage"]) - + # Extract provider and cost provider = extractors.normalize_provider_name(kwargs.get("custom_llm_provider")) cost = kwargs.get("response_cost") - + span_payload = payload_builders.build_span_payload( project_name=current_project_name, trace_id=trace_id, diff --git a/litellm/integrations/opik/opik_payload_builder/extractors.py b/litellm/integrations/opik/opik_payload_builder/extractors.py index e4ff021778a..9779ccddacf 100644 --- a/litellm/integrations/opik/opik_payload_builder/extractors.py +++ b/litellm/integrations/opik/opik_payload_builder/extractors.py @@ -9,16 +9,16 @@ from litellm import _logging def normalize_provider_name(provider: Optional[str]) -> Optional[str]: """ Normalize LiteLLM provider names to standardized string names. - + Args: provider: LiteLLM internal provider name - + Returns: Normalized provider name or the original if no mapping exists """ if provider is None: return None - + # Provider mapping to names used in Opik provider_mapping = { "openai": "openai", @@ -30,7 +30,7 @@ def normalize_provider_name(provider: Optional[str]) -> Optional[str]: "bedrock_converse": "bedrock", "groq": "groq", } - + return provider_mapping.get(provider, provider) diff --git a/litellm/integrations/posthog.py b/litellm/integrations/posthog.py index c4b6e843d60..17bb56b8f17 100644 --- a/litellm/integrations/posthog.py +++ b/litellm/integrations/posthog.py @@ -45,12 +45,14 @@ class PostHogLogger(CustomBatchLogger): """ try: verbose_logger.debug("PostHog: in init posthog logger") - + self.is_mock_mode = should_use_posthog_mock() if self.is_mock_mode: create_mock_posthog_client() - verbose_logger.debug("[POSTHOG MOCK] PostHog logger initialized in mock mode") - + verbose_logger.debug( + "[POSTHOG MOCK] PostHog logger initialized in mock mode" + ) + if os.getenv("POSTHOG_API_KEY", None) is None: raise Exception("POSTHOG_API_KEY is not set, set 'POSTHOG_API_KEY=<>'") @@ -58,10 +60,10 @@ class PostHogLogger(CustomBatchLogger): llm_provider=httpxSpecialProvider.LoggingCallback ) self.sync_client = _get_httpx_client() - + self.POSTHOG_API_KEY = os.getenv("POSTHOG_API_KEY") posthog_api_url = os.getenv("POSTHOG_API_URL", "https://us.i.posthog.com") - self.posthog_host = posthog_api_url.rstrip('/') + self.posthog_host = posthog_api_url.rstrip("/") self.capture_url = f"{self.posthog_host}/batch/" self._async_initialized = False @@ -141,17 +143,17 @@ class PostHogLogger(CustomBatchLogger): verbose_logger.exception(f"PostHog Layer Error - {str(e)}") pass - async def _log_async_event(self, kwargs, response_obj=None, start_time=0.0, end_time=0.0): + async def _log_async_event( + self, kwargs, response_obj=None, start_time=0.0, end_time=0.0 + ): # Note: response_obj, start_time, end_time not used - all data comes from kwargs api_key, api_url = self._get_credentials_for_request(kwargs) event_payload = self.create_posthog_event_payload(kwargs) # Store event with its credentials for batch sending - self.log_queue.append({ - "event": event_payload, - "api_key": api_key, - "api_url": api_url - }) + self.log_queue.append( + {"event": event_payload, "api_key": api_key, "api_url": api_url} + ) verbose_logger.debug( f"PostHog, event added to queue. Will flush in {self.flush_interval} seconds..." ) @@ -159,7 +161,9 @@ class PostHogLogger(CustomBatchLogger): if len(self.log_queue) >= self.batch_size: await self.flush_queue() - def create_posthog_event_payload(self, kwargs: Dict[str, Any]) -> PostHogEventPayload: + def create_posthog_event_payload( + self, kwargs: Dict[str, Any] + ) -> PostHogEventPayload: """ Helper function to create a PostHog event payload for logging @@ -203,7 +207,9 @@ class PostHogLogger(CustomBatchLogger): # Core model information properties["$ai_model"] = self._safe_get(standard_logging_object, "model", "") - properties["$ai_provider"] = self._safe_get(standard_logging_object, "custom_llm_provider", "") + properties["$ai_provider"] = self._safe_get( + standard_logging_object, "custom_llm_provider", "" + ) # Input/Output data messages = self._safe_get(standard_logging_object, "messages") @@ -216,16 +222,22 @@ class PostHogLogger(CustomBatchLogger): properties["$ai_output_choices"] = response # Token information - properties["$ai_input_tokens"] = self._safe_get(standard_logging_object, "prompt_tokens", 0) + properties["$ai_input_tokens"] = self._safe_get( + standard_logging_object, "prompt_tokens", 0 + ) if event_name == "$ai_generation": - properties["$ai_output_tokens"] = self._safe_get(standard_logging_object, "completion_tokens", 0) + properties["$ai_output_tokens"] = self._safe_get( + standard_logging_object, "completion_tokens", 0 + ) # Cost and performance response_cost = self._safe_get(standard_logging_object, "response_cost") if response_cost is not None: properties["$ai_total_cost_usd"] = response_cost - properties["$ai_latency"] = self._safe_get(standard_logging_object, "response_time", 0.0) + properties["$ai_latency"] = self._safe_get( + standard_logging_object, "response_time", 0.0 + ) # Error handling if self._safe_get(standard_logging_object, "status") == "failure": @@ -245,7 +257,9 @@ class PostHogLogger(CustomBatchLogger): def _add_trace_properties(self, properties: Dict[str, Any], kwargs: Dict[str, Any]): standard_logging_object = self._safe_get(kwargs, "standard_logging_object", {}) - trace_id = self._safe_get(standard_logging_object, "trace_id", self._safe_uuid()) + trace_id = self._safe_get( + standard_logging_object, "trace_id", self._safe_uuid() + ) properties["$ai_trace_id"] = trace_id span_id = self._safe_get(standard_logging_object, "id", self._safe_uuid()) @@ -256,22 +270,48 @@ class PostHogLogger(CustomBatchLogger): if parent_id: properties["$ai_parent_id"] = parent_id - def _add_custom_metadata_properties(self, properties: Dict[str, Any], kwargs: Dict[str, Any]): + def _add_custom_metadata_properties( + self, properties: Dict[str, Any], kwargs: Dict[str, Any] + ): """Add custom metadata fields to PostHog properties""" metadata = self._extract_metadata(kwargs) if not isinstance(metadata, dict): return litellm_internal_fields = { - "endpoint", "caching_groups", "user_api_key_hash", "user_api_key_alias", - "user_api_key_team_id", "user_api_key_user_id", "user_api_key_org_id", - "user_api_key_team_alias", "user_api_key_end_user_id", "user_api_key_user_email", - "user_api_key", "user_api_end_user_max_budget", "litellm_api_version", - "global_max_parallel_requests", "user_api_key_team_max_budget", "user_api_key_team_spend", - "user_api_key_spend", "user_api_key_max_budget", "user_api_key_model_max_budget", - "user_api_key_metadata", "headers", "litellm_parent_otel_span", "requester_ip_address", - "model_group", "model_group_size", "deployment", "model_info", "api_base", - "caching_groups", "hidden_params", "parent_run_id", "parent_id", "user_id" + "endpoint", + "caching_groups", + "user_api_key_hash", + "user_api_key_alias", + "user_api_key_team_id", + "user_api_key_user_id", + "user_api_key_org_id", + "user_api_key_team_alias", + "user_api_key_end_user_id", + "user_api_key_user_email", + "user_api_key", + "user_api_end_user_max_budget", + "litellm_api_version", + "global_max_parallel_requests", + "user_api_key_team_max_budget", + "user_api_key_team_spend", + "user_api_key_spend", + "user_api_key_max_budget", + "user_api_key_model_max_budget", + "user_api_key_metadata", + "headers", + "litellm_parent_otel_span", + "requester_ip_address", + "model_group", + "model_group_size", + "deployment", + "model_info", + "api_base", + "caching_groups", + "hidden_params", + "parent_run_id", + "parent_id", + "user_id", } for key, value in metadata.items(): @@ -294,7 +334,9 @@ class PostHogLogger(CustomBatchLogger): return self._safe_uuid() - def _get_credentials_for_request(self, kwargs: Dict[str, Any]) -> Tuple[Optional[str], Optional[str]]: + def _get_credentials_for_request( + self, kwargs: Dict[str, Any] + ) -> Tuple[Optional[str], Optional[str]]: """ Get PostHog credentials for this request. @@ -307,13 +349,19 @@ class PostHogLogger(CustomBatchLogger): Returns: tuple[str, str]: (api_key, api_url) """ - standard_callback_dynamic_params: Optional[StandardCallbackDynamicParams] = ( - kwargs.get("standard_callback_dynamic_params", None) - ) + standard_callback_dynamic_params: Optional[ + StandardCallbackDynamicParams + ] = kwargs.get("standard_callback_dynamic_params", None) if standard_callback_dynamic_params is not None: - api_key = standard_callback_dynamic_params.get("posthog_api_key") or self.POSTHOG_API_KEY - api_url = standard_callback_dynamic_params.get("posthog_api_url") or self.posthog_host + api_key = ( + standard_callback_dynamic_params.get("posthog_api_key") + or self.POSTHOG_API_KEY + ) + api_url = ( + standard_callback_dynamic_params.get("posthog_api_url") + or self.posthog_host + ) else: api_key = self.POSTHOG_API_KEY api_url = self.posthog_host @@ -334,9 +382,11 @@ class PostHogLogger(CustomBatchLogger): verbose_logger.debug( f"PostHog: Sending batch of {len(self.log_queue)} events" ) - + if self.is_mock_mode: - verbose_logger.debug("[POSTHOG MOCK] Mock mode enabled - API calls will be intercepted") + verbose_logger.debug( + "[POSTHOG MOCK] Mock mode enabled - API calls will be intercepted" + ) # Group events by credentials for batch sending batches_by_credentials: Dict[tuple[str, str], list] = {} @@ -368,7 +418,9 @@ class PostHogLogger(CustomBatchLogger): ) if self.is_mock_mode: - verbose_logger.debug(f"[POSTHOG MOCK] Batch of {len(self.log_queue)} events successfully mocked") + verbose_logger.debug( + f"[POSTHOG MOCK] Batch of {len(self.log_queue)} events successfully mocked" + ) else: verbose_logger.debug( f"PostHog: Batch of {len(self.log_queue)} events successfully sent" @@ -384,7 +436,9 @@ class PostHogLogger(CustomBatchLogger): self._async_initialized = True verbose_logger.debug("PostHog: Async components initialized") except Exception as e: - verbose_logger.error(f"PostHog: Failed to initialize async components: {str(e)}") + verbose_logger.error( + f"PostHog: Failed to initialize async components: {str(e)}" + ) raise def _extract_metadata(self, kwargs: Dict[str, Any]) -> Dict[str, Any]: @@ -398,7 +452,7 @@ class PostHogLogger(CustomBatchLogger): return {"api_key": api_key, "batch": events} def _safe_get(self, obj: Any, key: str, default: Any = None) -> Any: - if obj is None or not hasattr(obj, 'get'): + if obj is None or not hasattr(obj, "get"): return default return obj.get(key, default) diff --git a/litellm/integrations/posthog_mock_client.py b/litellm/integrations/posthog_mock_client.py index b713587ed6f..de085b855ce 100644 --- a/litellm/integrations/posthog_mock_client.py +++ b/litellm/integrations/posthog_mock_client.py @@ -8,7 +8,10 @@ Usage: Set POSTHOG_MOCK=true in environment variables or config to enable mock mode. """ -from litellm.integrations.mock_client_factory import MockClientConfig, create_mock_client_factory +from litellm.integrations.mock_client_factory import ( + MockClientConfig, + create_mock_client_factory, +) # Create mock client using factory _config = MockClientConfig( @@ -27,4 +30,6 @@ _config = MockClientConfig( patch_sync_client=True, ) -create_mock_posthog_client, should_use_posthog_mock = create_mock_client_factory(_config) +create_mock_posthog_client, should_use_posthog_mock = create_mock_client_factory( + _config +) diff --git a/litellm/integrations/prometheus.py b/litellm/integrations/prometheus.py index 7a08432b9a1..357e0229fc6 100644 --- a/litellm/integrations/prometheus.py +++ b/litellm/integrations/prometheus.py @@ -1417,7 +1417,9 @@ class PrometheusLogger(CustomLogger): _sanitize_prometheus_label_value(user_api_team), _sanitize_prometheus_label_value(user_api_team_alias), _sanitize_prometheus_label_value(user_id), - _sanitize_prometheus_label_value(standard_logging_payload.get("model_id", "")), + _sanitize_prometheus_label_value( + standard_logging_payload.get("model_id", "") + ), ).inc() self.set_llm_deployment_failure_metrics(kwargs) except Exception as e: diff --git a/litellm/integrations/prompt_management_base.py b/litellm/integrations/prompt_management_base.py index b32f78c0dea..71da650dc48 100644 --- a/litellm/integrations/prompt_management_base.py +++ b/litellm/integrations/prompt_management_base.py @@ -75,7 +75,6 @@ class PromptManagementBase(ABC): prompt_version: Optional[int] = None, prompt_spec: Optional[PromptSpec] = None, ) -> PromptManagementClient: - compiled_prompt_client = self._compile_prompt_helper( prompt_id=prompt_id, prompt_spec=prompt_spec, @@ -179,7 +178,6 @@ class PromptManagementBase(ABC): ignore_prompt_manager_model: Optional[bool] = False, ignore_prompt_manager_optional_params: Optional[bool] = False, ) -> Tuple[str, List[AllMessageValues], dict]: - if prompt_id is None: raise ValueError("prompt_id is required for Prompt Management Base class") if not self.should_run_prompt_management( diff --git a/litellm/integrations/s3_v2.py b/litellm/integrations/s3_v2.py index eddc80dbc1f..c8db4be7cea 100644 --- a/litellm/integrations/s3_v2.py +++ b/litellm/integrations/s3_v2.py @@ -80,7 +80,7 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM): s3_use_team_prefix=s3_use_team_prefix, s3_strip_base64_files=s3_strip_base64_files, s3_use_key_prefix=s3_use_key_prefix, - s3_use_virtual_hosted_style=s3_use_virtual_hosted_style + s3_use_virtual_hosted_style=s3_use_virtual_hosted_style, ) verbose_logger.debug(f"s3 logger using endpoint url {s3_endpoint_url}") @@ -91,7 +91,7 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM): ) self.async_httpx_client = get_async_httpx_client( llm_provider=httpxSpecialProvider.LoggingCallback, - params={"ssl_verify": self.s3_verify} + params={"ssl_verify": self.s3_verify}, ) asyncio.create_task(self.periodic_flush()) @@ -158,10 +158,14 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM): litellm.s3_callback_params.get("s3_api_version") or s3_api_version ) self.s3_use_ssl = ( - litellm.s3_callback_params.get("s3_use_ssl", True) if litellm.s3_callback_params.get("s3_use_ssl") is not None else s3_use_ssl + litellm.s3_callback_params.get("s3_use_ssl", True) + if litellm.s3_callback_params.get("s3_use_ssl") is not None + else s3_use_ssl ) self.s3_verify = ( - litellm.s3_callback_params.get("s3_verify") if litellm.s3_callback_params.get("s3_verify") is not None else s3_verify + litellm.s3_callback_params.get("s3_verify") + if litellm.s3_callback_params.get("s3_verify") is not None + else s3_verify ) self.s3_endpoint_url = ( litellm.s3_callback_params.get("s3_endpoint_url") or s3_endpoint_url @@ -211,8 +215,8 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM): ) self.s3_use_key_prefix = ( - bool(litellm.s3_callback_params.get("s3_use_key_prefix", False)) - or s3_use_key_prefix + bool(litellm.s3_callback_params.get("s3_use_key_prefix", False)) + or s3_use_key_prefix ) self.s3_strip_base64_files = ( @@ -308,9 +312,7 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM): verbose_logger.debug( f"s3_v2 logger - uploading data to s3 - {batch_logging_element.s3_object_key}" ) - verbose_logger.debug( - f"s3_v2 logger - s3_verify setting: {self.s3_verify}" - ) + verbose_logger.debug(f"s3_v2 logger - s3_verify setting: {self.s3_verify}") # Prepare the URL url = f"https://{self.s3_bucket_name}.s3.{self.s3_region_name}.amazonaws.com/{batch_logging_element.s3_object_key}" @@ -318,8 +320,14 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM): if self.s3_endpoint_url and self.s3_bucket_name: if self.s3_use_virtual_hosted_style: # Virtual-hosted-style: bucket.endpoint/key - endpoint_host = self.s3_endpoint_url.replace("https://", "").replace("http://", "") - protocol = "https://" if self.s3_endpoint_url.startswith("https://") else "http://" + endpoint_host = self.s3_endpoint_url.replace( + "https://", "" + ).replace("http://", "") + protocol = ( + "https://" + if self.s3_endpoint_url.startswith("https://") + else "http://" + ) url = f"{protocol}{self.s3_bucket_name}.{endpoint_host}/{batch_logging_element.s3_object_key}" else: # Path-style: endpoint/bucket/key @@ -413,20 +421,25 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM): return None if self.s3_strip_base64_files: - standard_logging_payload = self._strip_base64_from_messages_sync(standard_logging_payload) + standard_logging_payload = self._strip_base64_from_messages_sync( + standard_logging_payload + ) # Base prefix (default empty) prefix_components = [] if self.s3_use_team_prefix: - team_alias = standard_logging_payload.get("metadata", {}).get("user_api_key_team_alias", None) + team_alias = standard_logging_payload.get("metadata", {}).get( + "user_api_key_team_alias", None + ) if team_alias: prefix_components.append(team_alias) if self.s3_use_key_prefix: - user_api_key_alias = standard_logging_payload.get("metadata", {}).get("user_api_key_alias", None) + user_api_key_alias = standard_logging_payload.get("metadata", {}).get( + "user_api_key_alias", None + ) if user_api_key_alias: prefix_components.append(user_api_key_alias) - # Construct full prefix path prefix_path = "/".join(prefix_components) if prefix_path: @@ -435,7 +448,9 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM): s3_file_name = ( litellm.utils.get_logging_id(start_time, standard_logging_payload) or "" ) - verbose_logger.debug(f"Creating s3 file with prefix_components={prefix_components},prefix_path={prefix_path} and {s3_file_name}") + verbose_logger.debug( + f"Creating s3 file with prefix_components={prefix_components},prefix_path={prefix_path} and {s3_file_name}" + ) s3_object_key = get_s3_object_key( s3_path=cast(Optional[str], self.s3_path) or "", prefix=prefix_path, @@ -479,8 +494,14 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM): if self.s3_endpoint_url and self.s3_bucket_name: if self.s3_use_virtual_hosted_style: # Virtual-hosted-style: bucket.endpoint/key - endpoint_host = self.s3_endpoint_url.replace("https://", "").replace("http://", "") - protocol = "https://" if self.s3_endpoint_url.startswith("https://") else "http://" + endpoint_host = self.s3_endpoint_url.replace( + "https://", "" + ).replace("http://", "") + protocol = ( + "https://" + if self.s3_endpoint_url.startswith("https://") + else "http://" + ) url = f"{protocol}{self.s3_bucket_name}.{endpoint_host}/{batch_logging_element.s3_object_key}" else: # Path-style: endpoint/bucket/key @@ -525,7 +546,9 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM): signed_headers = dict(aws_request.headers.items()) httpx_client = _get_httpx_client( - params={"ssl_verify": self.s3_verify} if self.s3_verify is not None else None + params={"ssl_verify": self.s3_verify} + if self.s3_verify is not None + else None ) # Make the request response = httpx_client.put(url, data=json_string, headers=signed_headers) @@ -580,8 +603,14 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM): if self.s3_endpoint_url and self.s3_bucket_name: if self.s3_use_virtual_hosted_style: # Virtual-hosted-style: bucket.endpoint/key - endpoint_host = self.s3_endpoint_url.replace("https://", "").replace("http://", "") - protocol = "https://" if self.s3_endpoint_url.startswith("https://") else "http://" + endpoint_host = self.s3_endpoint_url.replace( + "https://", "" + ).replace("http://", "") + protocol = ( + "https://" + if self.s3_endpoint_url.startswith("https://") + else "http://" + ) url = f"{protocol}{self.s3_bucket_name}.{endpoint_host}/{s3_object_key}" else: # Path-style: endpoint/bucket/key @@ -653,4 +682,4 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM): verbose_logger.exception( f"Error retrieving object {object_key} from cold storage: {str(e)}" ) - return None \ No newline at end of file + return None diff --git a/litellm/integrations/sqs.py b/litellm/integrations/sqs.py index 97a4c5723d8..6cbd2c7974f 100644 --- a/litellm/integrations/sqs.py +++ b/litellm/integrations/sqs.py @@ -42,31 +42,31 @@ class SQSLogger(CustomBatchLogger, BaseAWSLLM): """Batching logger that writes logs to an AWS SQS queue, optionally encrypting the payload.""" def __init__( - self, - # --- Standard SQS params --- - sqs_queue_url: Optional[str] = None, - sqs_region_name: Optional[str] = None, - sqs_api_version: Optional[str] = None, - sqs_use_ssl: bool = True, - sqs_verify: Optional[bool] = None, - sqs_endpoint_url: Optional[str] = None, - sqs_aws_access_key_id: Optional[str] = None, - sqs_aws_secret_access_key: Optional[str] = None, - sqs_aws_session_token: Optional[str] = None, - sqs_aws_session_name: Optional[str] = None, - sqs_aws_profile_name: Optional[str] = None, - sqs_aws_role_name: Optional[str] = None, - sqs_aws_web_identity_token: Optional[str] = None, - sqs_aws_sts_endpoint: Optional[str] = None, - sqs_flush_interval: Optional[int] = DEFAULT_SQS_FLUSH_INTERVAL_SECONDS, - sqs_batch_size: Optional[int] = DEFAULT_SQS_BATCH_SIZE, - sqs_config=None, - sqs_strip_base64_files: bool = False, - # --- 🔐 Application-level encryption params --- - sqs_aws_use_application_level_encryption: bool = False, - sqs_app_encryption_key_b64: Optional[str] = None, - sqs_app_encryption_aad: Optional[str] = None, - **kwargs, + self, + # --- Standard SQS params --- + sqs_queue_url: Optional[str] = None, + sqs_region_name: Optional[str] = None, + sqs_api_version: Optional[str] = None, + sqs_use_ssl: bool = True, + sqs_verify: Optional[bool] = None, + sqs_endpoint_url: Optional[str] = None, + sqs_aws_access_key_id: Optional[str] = None, + sqs_aws_secret_access_key: Optional[str] = None, + sqs_aws_session_token: Optional[str] = None, + sqs_aws_session_name: Optional[str] = None, + sqs_aws_profile_name: Optional[str] = None, + sqs_aws_role_name: Optional[str] = None, + sqs_aws_web_identity_token: Optional[str] = None, + sqs_aws_sts_endpoint: Optional[str] = None, + sqs_flush_interval: Optional[int] = DEFAULT_SQS_FLUSH_INTERVAL_SECONDS, + sqs_batch_size: Optional[int] = DEFAULT_SQS_BATCH_SIZE, + sqs_config=None, + sqs_strip_base64_files: bool = False, + # --- 🔐 Application-level encryption params --- + sqs_aws_use_application_level_encryption: bool = False, + sqs_app_encryption_key_b64: Optional[str] = None, + sqs_app_encryption_aad: Optional[str] = None, + **kwargs, ) -> None: try: verbose_logger.debug( @@ -122,26 +122,26 @@ class SQSLogger(CustomBatchLogger, BaseAWSLLM): raise e def _init_sqs_params( - self, - sqs_queue_url: Optional[str] = None, - sqs_region_name: Optional[str] = None, - sqs_api_version: Optional[str] = None, - sqs_use_ssl: bool = True, - sqs_verify: Optional[bool] = None, - sqs_endpoint_url: Optional[str] = None, - sqs_aws_access_key_id: Optional[str] = None, - sqs_aws_secret_access_key: Optional[str] = None, - sqs_aws_session_token: Optional[str] = None, - sqs_aws_session_name: Optional[str] = None, - sqs_aws_profile_name: Optional[str] = None, - sqs_aws_role_name: Optional[str] = None, - sqs_aws_web_identity_token: Optional[str] = None, - sqs_aws_sts_endpoint: Optional[str] = None, - sqs_strip_base64_files: bool = False, - sqs_aws_use_application_level_encryption: bool = False, - sqs_app_encryption_key_b64: Optional[str] = None, - sqs_app_encryption_aad: Optional[str] = None, - sqs_config=None, + self, + sqs_queue_url: Optional[str] = None, + sqs_region_name: Optional[str] = None, + sqs_api_version: Optional[str] = None, + sqs_use_ssl: bool = True, + sqs_verify: Optional[bool] = None, + sqs_endpoint_url: Optional[str] = None, + sqs_aws_access_key_id: Optional[str] = None, + sqs_aws_secret_access_key: Optional[str] = None, + sqs_aws_session_token: Optional[str] = None, + sqs_aws_session_name: Optional[str] = None, + sqs_aws_profile_name: Optional[str] = None, + sqs_aws_role_name: Optional[str] = None, + sqs_aws_web_identity_token: Optional[str] = None, + sqs_aws_sts_endpoint: Optional[str] = None, + sqs_strip_base64_files: bool = False, + sqs_aws_use_application_level_encryption: bool = False, + sqs_app_encryption_key_b64: Optional[str] = None, + sqs_app_encryption_aad: Optional[str] = None, + sqs_config=None, ) -> None: litellm.aws_sqs_callback_params = litellm.aws_sqs_callback_params or {} @@ -151,87 +151,98 @@ class SQSLogger(CustomBatchLogger, BaseAWSLLM): litellm.aws_sqs_callback_params[key] = litellm.get_secret(value) self.sqs_queue_url = ( - litellm.aws_sqs_callback_params.get("sqs_queue_url") or sqs_queue_url + litellm.aws_sqs_callback_params.get("sqs_queue_url") or sqs_queue_url ) self.sqs_region_name = ( - litellm.aws_sqs_callback_params.get("sqs_region_name") or sqs_region_name + litellm.aws_sqs_callback_params.get("sqs_region_name") or sqs_region_name ) self.sqs_api_version = ( - litellm.aws_sqs_callback_params.get("sqs_api_version") or sqs_api_version + litellm.aws_sqs_callback_params.get("sqs_api_version") or sqs_api_version ) self.sqs_use_ssl = ( - litellm.aws_sqs_callback_params.get("sqs_use_ssl", True) or sqs_use_ssl + litellm.aws_sqs_callback_params.get("sqs_use_ssl", True) or sqs_use_ssl + ) + self.sqs_verify = ( + litellm.aws_sqs_callback_params.get("sqs_verify") or sqs_verify ) - self.sqs_verify = litellm.aws_sqs_callback_params.get("sqs_verify") or sqs_verify self.sqs_endpoint_url = ( - litellm.aws_sqs_callback_params.get("sqs_endpoint_url") or sqs_endpoint_url + litellm.aws_sqs_callback_params.get("sqs_endpoint_url") or sqs_endpoint_url ) self.sqs_aws_access_key_id = ( - litellm.aws_sqs_callback_params.get("sqs_aws_access_key_id") - or sqs_aws_access_key_id + litellm.aws_sqs_callback_params.get("sqs_aws_access_key_id") + or sqs_aws_access_key_id ) self.sqs_aws_secret_access_key = ( - litellm.aws_sqs_callback_params.get("sqs_aws_secret_access_key") - or sqs_aws_secret_access_key + litellm.aws_sqs_callback_params.get("sqs_aws_secret_access_key") + or sqs_aws_secret_access_key ) self.sqs_aws_session_token = ( - litellm.aws_sqs_callback_params.get("sqs_aws_session_token") - or sqs_aws_session_token + litellm.aws_sqs_callback_params.get("sqs_aws_session_token") + or sqs_aws_session_token ) self.sqs_aws_session_name = ( - litellm.aws_sqs_callback_params.get("sqs_aws_session_name") or sqs_aws_session_name + litellm.aws_sqs_callback_params.get("sqs_aws_session_name") + or sqs_aws_session_name ) self.sqs_aws_profile_name = ( - litellm.aws_sqs_callback_params.get("sqs_aws_profile_name") or sqs_aws_profile_name + litellm.aws_sqs_callback_params.get("sqs_aws_profile_name") + or sqs_aws_profile_name ) self.sqs_aws_role_name = ( - litellm.aws_sqs_callback_params.get("sqs_aws_role_name") or sqs_aws_role_name + litellm.aws_sqs_callback_params.get("sqs_aws_role_name") + or sqs_aws_role_name ) self.sqs_aws_web_identity_token = ( - litellm.aws_sqs_callback_params.get("sqs_aws_web_identity_token") - or sqs_aws_web_identity_token + litellm.aws_sqs_callback_params.get("sqs_aws_web_identity_token") + or sqs_aws_web_identity_token ) self.sqs_aws_sts_endpoint = ( - litellm.aws_sqs_callback_params.get("sqs_aws_sts_endpoint") or sqs_aws_sts_endpoint + litellm.aws_sqs_callback_params.get("sqs_aws_sts_endpoint") + or sqs_aws_sts_endpoint ) self.sqs_strip_base64_files = ( - litellm.aws_sqs_callback_params.get("sqs_strip_base64_files", False) - or sqs_strip_base64_files + litellm.aws_sqs_callback_params.get("sqs_strip_base64_files", False) + or sqs_strip_base64_files ) self.sqs_aws_use_application_level_encryption = ( - litellm.aws_sqs_callback_params.get("sqs_aws_use_application_level_encryption", False) - or sqs_aws_use_application_level_encryption + litellm.aws_sqs_callback_params.get( + "sqs_aws_use_application_level_encryption", False + ) + or sqs_aws_use_application_level_encryption ) self.sqs_app_encryption_key_b64 = ( - litellm.aws_sqs_callback_params.get("sqs_app_encryption_key_b64") - or sqs_app_encryption_key_b64 + litellm.aws_sqs_callback_params.get("sqs_app_encryption_key_b64") + or sqs_app_encryption_key_b64 ) self.sqs_app_encryption_aad = ( - litellm.aws_sqs_callback_params.get("sqs_app_encryption_aad") - or sqs_app_encryption_aad + litellm.aws_sqs_callback_params.get("sqs_app_encryption_aad") + or sqs_app_encryption_aad ) self.app_crypto: Optional["AppCrypto"] = None if self.sqs_aws_use_application_level_encryption: from litellm.litellm_core_utils.app_crypto import AppCrypto + if not self.sqs_app_encryption_key_b64: - raise ValueError("sqs_app_encryption_key_b64 is required when encryption is enabled.") + raise ValueError( + "sqs_app_encryption_key_b64 is required when encryption is enabled." + ) key = base64.b64decode(self.sqs_app_encryption_key_b64) self.app_crypto = AppCrypto(key) - verbose_logger.debug( - "SQSLogger: Application-level encryption enabled." - ) - self.sqs_config = litellm.aws_sqs_callback_params.get("sqs_config") or sqs_config + verbose_logger.debug("SQSLogger: Application-level encryption enabled.") + self.sqs_config = ( + litellm.aws_sqs_callback_params.get("sqs_config") or sqs_config + ) async def async_log_success_event( - self, kwargs, response_obj, start_time, end_time + self, kwargs, response_obj, start_time, end_time ) -> None: try: verbose_logger.debug( @@ -239,7 +250,9 @@ class SQSLogger(CustomBatchLogger, BaseAWSLLM): ) standard_logging_payload = kwargs.get("standard_logging_object") if self.sqs_strip_base64_files: - standard_logging_payload = await self._strip_base64_from_messages(standard_logging_payload) + standard_logging_payload = await self._strip_base64_from_messages( + standard_logging_payload + ) if standard_logging_payload is None: raise ValueError("standard_logging_payload is None") @@ -258,7 +271,9 @@ class SQSLogger(CustomBatchLogger, BaseAWSLLM): if standard_logging_payload is None: raise ValueError("standard_logging_payload is None") if self.sqs_strip_base64_files: - standard_logging_payload = await self._strip_base64_from_messages(standard_logging_payload) + standard_logging_payload = await self._strip_base64_from_messages( + standard_logging_payload + ) self.log_queue.append(standard_logging_payload) verbose_logger.debug( @@ -274,9 +289,7 @@ class SQSLogger(CustomBatchLogger, BaseAWSLLM): pass async def async_send_batch(self) -> None: - verbose_logger.debug( - f"sqs logger - sending batch of {len(self.log_queue)}" - ) + verbose_logger.debug(f"sqs logger - sending batch of {len(self.log_queue)}") if not self.log_queue: return @@ -322,8 +335,8 @@ class SQSLogger(CustomBatchLogger, BaseAWSLLM): json_string = safe_dumps(payload) body = ( - f"Action={SQS_SEND_MESSAGE_ACTION}&Version={SQS_API_VERSION}&MessageBody=" - + quote(json_string, safe="") + f"Action={SQS_SEND_MESSAGE_ACTION}&Version={SQS_API_VERSION}&MessageBody=" + + quote(json_string, safe="") ) headers = { @@ -341,9 +354,7 @@ class SQSLogger(CustomBatchLogger, BaseAWSLLM): data=prepped.body, headers=prepped.headers, ) - SigV4Auth(credentials, "sqs", self.sqs_region_name).add_auth( - aws_request - ) + SigV4Auth(credentials, "sqs", self.sqs_region_name).add_auth(aws_request) signed_headers = dict(aws_request.headers.items()) @@ -364,10 +375,15 @@ class SQSLogger(CustomBatchLogger, BaseAWSLLM): from litellm.litellm_core_utils.litellm_logging import ( create_dummy_standard_logging_payload, ) + # Create a minimal standard logging payload - standard_logging_object: StandardLoggingPayload = create_dummy_standard_logging_payload() + standard_logging_object: StandardLoggingPayload = ( + create_dummy_standard_logging_payload() + ) # Attempt to send a single message await self.async_send_message(standard_logging_object) return IntegrationHealthCheckStatus(status="healthy", error_message=None) except Exception as e: - return IntegrationHealthCheckStatus(status="unhealthy", error_message=str(e)) + return IntegrationHealthCheckStatus( + status="unhealthy", error_message=str(e) + ) diff --git a/litellm/integrations/vector_store_integrations/vector_store_pre_call_hook.py b/litellm/integrations/vector_store_integrations/vector_store_pre_call_hook.py index c94b925ea21..50420fb7137 100644 --- a/litellm/integrations/vector_store_integrations/vector_store_pre_call_hook.py +++ b/litellm/integrations/vector_store_integrations/vector_store_pre_call_hook.py @@ -82,17 +82,18 @@ class VectorStorePreCallHook(CustomLogger): prisma_client = None try: from litellm.proxy.proxy_server import prisma_client as _prisma_client + prisma_client = _prisma_client except ImportError: pass # Use database fallback to ensure synchronization across instances - vector_stores_to_run: List[LiteLLM_ManagedVectorStore] = ( - await litellm.vector_store_registry.pop_vector_stores_to_run_with_db_fallback( - non_default_params=non_default_params, - tools=tools, - prisma_client=prisma_client - ) + vector_stores_to_run: List[ + LiteLLM_ManagedVectorStore + ] = await litellm.vector_store_registry.pop_vector_stores_to_run_with_db_fallback( + non_default_params=non_default_params, + tools=tools, + prisma_client=prisma_client, ) if not vector_stores_to_run: @@ -111,7 +112,6 @@ class VectorStorePreCallHook(CustomLogger): all_search_results: List[VectorStoreSearchResponse] = [] for vector_store_to_run in vector_stores_to_run: - # Get vector store id from the vector store config vector_store_id = vector_store_to_run.get("vector_store_id", "") custom_llm_provider = vector_store_to_run.get("custom_llm_provider") @@ -147,9 +147,9 @@ class VectorStorePreCallHook(CustomLogger): # Store search results as-is (already in OpenAI-compatible format) if litellm_logging_obj and all_search_results: - litellm_logging_obj.model_call_details["search_results"] = ( - all_search_results - ) + litellm_logging_obj.model_call_details[ + "search_results" + ] = all_search_results return model, modified_messages, non_default_params @@ -208,9 +208,9 @@ class VectorStorePreCallHook(CustomLogger): Returns: Modified list of messages with context appended """ - search_response_data: Optional[List[VectorStoreSearchResult]] = ( - search_response.get("data") - ) + search_response_data: Optional[ + List[VectorStoreSearchResult] + ] = search_response.get("data") if not search_response_data: return messages @@ -268,9 +268,9 @@ class VectorStorePreCallHook(CustomLogger): ) # Get search results from model_call_details (already in OpenAI format) - search_results: Optional[List[VectorStoreSearchResponse]] = ( - litellm_logging_obj.model_call_details.get("search_results") - ) + search_results: Optional[ + List[VectorStoreSearchResponse] + ] = litellm_logging_obj.model_call_details.get("search_results") verbose_logger.debug(f"Search results found: {search_results is not None}") @@ -328,9 +328,9 @@ class VectorStorePreCallHook(CustomLogger): ) # Get search results from model_call_details (already in OpenAI format) - search_results: Optional[List[VectorStoreSearchResponse]] = ( - request_data.get("search_results") - ) + search_results: Optional[ + List[VectorStoreSearchResponse] + ] = request_data.get("search_results") verbose_logger.debug( f"Search results found for streaming chunk: {search_results is not None}" diff --git a/litellm/integrations/weave/weave_otel.py b/litellm/integrations/weave/weave_otel.py index 167deaf2cdc..796a33a34d5 100644 --- a/litellm/integrations/weave/weave_otel.py +++ b/litellm/integrations/weave/weave_otel.py @@ -9,7 +9,9 @@ from opentelemetry.trace import Status, StatusCode from typing_extensions import override from litellm._logging import verbose_logger -from litellm.integrations._types.open_inference import SpanAttributes as OpenInferenceSpanAttributes +from litellm.integrations._types.open_inference import ( + SpanAttributes as OpenInferenceSpanAttributes, +) from litellm.integrations.arize import _utils from litellm.integrations.opentelemetry import OpenTelemetry, OpenTelemetryConfig from litellm.integrations.opentelemetry_utils.base_otel_llm_obs_attributes import ( @@ -54,10 +56,14 @@ class WeaveLLMObsOTELAttributes(BaseLLMObsOTELAttributes): prompt["functions"] = functions if tools is not None: prompt["tools"] = tools - safe_set_attribute(span, OpenInferenceSpanAttributes.INPUT_VALUE, json.dumps(prompt)) + safe_set_attribute( + span, OpenInferenceSpanAttributes.INPUT_VALUE, json.dumps(prompt) + ) -def _set_weave_specific_attributes(span: Span, kwargs: dict[str, Any], response_obj: Any): +def _set_weave_specific_attributes( + span: Span, kwargs: dict[str, Any], response_obj: Any +): """ Sets Weave-specific metadata attributes onto the OTEL span. @@ -100,7 +106,9 @@ def _set_weave_specific_attributes(span: Span, kwargs: dict[str, Any], response_ output_dict = response_obj if output_dict: - safe_set_attribute(span, OpenInferenceSpanAttributes.OUTPUT_VALUE, safe_dumps(output_dict)) + safe_set_attribute( + span, OpenInferenceSpanAttributes.OUTPUT_VALUE, safe_dumps(output_dict) + ) def _get_weave_authorization_header(api_key: str) -> str: @@ -134,7 +142,9 @@ def get_weave_otel_config() -> WeaveOtelConfig: host = os.getenv("WANDB_HOST") if not api_key: - raise ValueError("WANDB_API_KEY must be set for Weave OpenTelemetry integration.") + raise ValueError( + "WANDB_API_KEY must be set for Weave OpenTelemetry integration." + ) if not project_id: raise ValueError( @@ -223,7 +233,9 @@ class WeaveOtelLogger(OpenTelemetry): super().__init__(config=config, callback_name=callback_name, **kwargs) - def _maybe_log_raw_request(self, kwargs, response_obj, start_time, end_time, parent_span): + def _maybe_log_raw_request( + self, kwargs, response_obj, start_time, end_time, parent_span + ): """ Override to skip creating the raw_gen_ai_request child span. @@ -281,7 +293,9 @@ class WeaveOtelLogger(OpenTelemetry): primary_span_parent = None # 1. Primary span - span = self._start_primary_span(kwargs, response_obj, start_time, end_time, ctx, primary_span_parent) + span = self._start_primary_span( + kwargs, response_obj, start_time, end_time, ctx, primary_span_parent + ) # 2. Raw-request sub-span (skipped for Weave via _maybe_log_raw_request override) self._maybe_log_raw_request(kwargs, response_obj, start_time, end_time, span) @@ -315,7 +329,9 @@ class WeaveOtelLogger(OpenTelemetry): dynamic_headers = {} dynamic_wandb_api_key = standard_callback_dynamic_params.get("wandb_api_key") - dynamic_weave_project_id = standard_callback_dynamic_params.get("weave_project_id") + dynamic_weave_project_id = standard_callback_dynamic_params.get( + "weave_project_id" + ) if dynamic_wandb_api_key: auth_header = _get_weave_authorization_header( diff --git a/litellm/integrations/websearch_interception/handler.py b/litellm/integrations/websearch_interception/handler.py index c31140d44d8..2541a0bd7aa 100644 --- a/litellm/integrations/websearch_interception/handler.py +++ b/litellm/integrations/websearch_interception/handler.py @@ -62,8 +62,7 @@ class WebSearchInterceptionLogger(CustomLogger): self.enabled_providers = [LlmProviders.BEDROCK.value] else: self.enabled_providers = [ - p.value if isinstance(p, LlmProviders) else p - for p in enabled_providers + p.value if isinstance(p, LlmProviders) else p for p in enabled_providers ] self.search_tool_name = search_tool_name self._request_has_websearch = False # Track if current request has web search @@ -80,10 +79,14 @@ class WebSearchInterceptionLogger(CustomLogger): """ # Check if this is for an enabled provider # Try top-level kwargs first, then nested litellm_params, then derive from model name - custom_llm_provider = kwargs.get("custom_llm_provider", "") or kwargs.get("litellm_params", {}).get("custom_llm_provider", "") + custom_llm_provider = kwargs.get("custom_llm_provider", "") or kwargs.get( + "litellm_params", {} + ).get("custom_llm_provider", "") if not custom_llm_provider: try: - _, custom_llm_provider, _, _ = litellm.get_llm_provider(model=kwargs.get("model", "")) + _, custom_llm_provider, _, _ = litellm.get_llm_provider( + model=kwargs.get("model", "") + ) except Exception: custom_llm_provider = "" if custom_llm_provider not in self.enabled_providers: @@ -197,7 +200,10 @@ class WebSearchInterceptionLogger(CustomLogger): f" - enabled_providers={self.enabled_providers or 'ALL'}" ) - if self.enabled_providers is not None and custom_llm_provider not in self.enabled_providers: + if ( + self.enabled_providers is not None + and custom_llm_provider not in self.enabled_providers + ): verbose_logger.debug( f"WebSearchInterception: Skipping - provider {custom_llm_provider} not in {self.enabled_providers}" ) @@ -258,18 +264,23 @@ class WebSearchInterceptionLogger(CustomLogger): ) -> Tuple[bool, Dict]: """ Check if WebSearch tool interception is needed for Anthropic Messages API. - + This is the legacy method for Anthropic-style responses. For chat completions, use async_should_run_chat_completion_agentic_loop instead. """ - verbose_logger.debug(f"WebSearchInterception: Hook called! provider={custom_llm_provider}, stream={stream}") + verbose_logger.debug( + f"WebSearchInterception: Hook called! provider={custom_llm_provider}, stream={stream}" + ) verbose_logger.debug(f"WebSearchInterception: Response type: {type(response)}") # Check if provider should be intercepted # Note: custom_llm_provider is already normalized by get_llm_provider() # (e.g., "bedrock/invoke/..." -> "bedrock") - if self.enabled_providers is not None and custom_llm_provider not in self.enabled_providers: + if ( + self.enabled_providers is not None + and custom_llm_provider not in self.enabled_providers + ): verbose_logger.debug( f"WebSearchInterception: Skipping provider {custom_llm_provider} (not in enabled list: {self.enabled_providers})" ) @@ -278,9 +289,7 @@ class WebSearchInterceptionLogger(CustomLogger): # Check if tools include any web search tool (LiteLLM standard or native) has_websearch_tool = any(is_web_search_tool(t) for t in (tools or [])) if not has_websearch_tool: - verbose_logger.debug( - "WebSearchInterception: No web search tool in request" - ) + verbose_logger.debug("WebSearchInterception: No web search tool in request") return False, {} # Detect WebSearch tool_use in response (Anthropic format) @@ -324,16 +333,12 @@ class WebSearchInterceptionLogger(CustomLogger): # pattern in _detect_from_non_streaming_response thinking_block_dict: Dict = {"type": block_type} if block_type == "thinking": - thinking_block_dict["thinking"] = getattr( - block, "thinking", "" - ) + thinking_block_dict["thinking"] = getattr(block, "thinking", "") thinking_block_dict["signature"] = getattr( block, "signature", "" ) else: # redacted_thinking - thinking_block_dict["data"] = getattr( - block, "data", "" - ) + thinking_block_dict["data"] = getattr(block, "data", "") thinking_blocks.append(thinking_block_dict) if thinking_blocks: @@ -363,22 +368,29 @@ class WebSearchInterceptionLogger(CustomLogger): ) -> Tuple[bool, Dict]: """ Check if WebSearch tool interception is needed for Chat Completions API. - + Similar to async_should_run_agentic_loop but for OpenAI-style chat completions. """ - verbose_logger.debug(f"WebSearchInterception: Chat completion hook called! provider={custom_llm_provider}, stream={stream}") + verbose_logger.debug( + f"WebSearchInterception: Chat completion hook called! provider={custom_llm_provider}, stream={stream}" + ) verbose_logger.debug(f"WebSearchInterception: Response type: {type(response)}") # Check if provider should be intercepted - if self.enabled_providers is not None and custom_llm_provider not in self.enabled_providers: + if ( + self.enabled_providers is not None + and custom_llm_provider not in self.enabled_providers + ): verbose_logger.debug( f"WebSearchInterception: Skipping provider {custom_llm_provider} (not in enabled list: {self.enabled_providers})" ) return False, {} # Check if tools include any web search tool (strict check for chat completions) - has_websearch_tool = any(is_web_search_tool_chat_completion(t) for t in (tools or [])) + has_websearch_tool = any( + is_web_search_tool_chat_completion(t) for t in (tools or []) + ) if not has_websearch_tool: verbose_logger.debug( "WebSearchInterception: No litellm_web_search tool in request" @@ -425,7 +437,7 @@ class WebSearchInterceptionLogger(CustomLogger): ) -> Any: """ Execute agentic loop with WebSearch execution for Anthropic Messages API. - + This is the legacy method for Anthropic-style responses. """ @@ -460,7 +472,7 @@ class WebSearchInterceptionLogger(CustomLogger): ) -> Any: """ Execute agentic loop with WebSearch execution for Chat Completions API. - + Similar to async_run_agentic_loop but for OpenAI-style chat completions. """ @@ -510,7 +522,9 @@ class WebSearchInterceptionLogger(CustomLogger): verbose_logger.debug( "WebSearchInterception: max_tokens=%s <= thinking.budget_tokens=%s, " "adjusting to %s to satisfy Anthropic API constraint", - max_tokens, budget_tokens, adjusted, + max_tokens, + budget_tokens, + adjusted, ) max_tokens = adjusted return max_tokens @@ -526,10 +540,11 @@ class WebSearchInterceptionLogger(CustomLogger): call's spend from being recorded — the root cause of the SpendLog / AWS billing mismatch. """ - _internal_keys = {'litellm_logging_obj'} + _internal_keys = {"litellm_logging_obj"} return { - k: v for k, v in kwargs.items() - if not k.startswith('_websearch_interception') and k not in _internal_keys + k: v + for k, v in kwargs.items() + if not k.startswith("_websearch_interception") and k not in _internal_keys } async def _execute_agentic_loop( @@ -574,9 +589,7 @@ class WebSearchInterceptionLogger(CustomLogger): verbose_logger.error( f"WebSearchInterception: Search {i} failed with error: {str(result)}" ) - final_search_results.append( - f"Search failed: {str(result)}" - ) + final_search_results.append(f"Search failed: {str(result)}") elif isinstance(result, str): # Explicitly cast to str for type checker final_search_results.append(cast(str, result)) @@ -609,9 +622,8 @@ class WebSearchInterceptionLogger(CustomLogger): ) # Correlation context for structured logging - _call_id = ( - getattr(logging_obj, "litellm_call_id", None) - or kwargs.get("litellm_call_id", "unknown") + _call_id = getattr(logging_obj, "litellm_call_id", None) or kwargs.get( + "litellm_call_id", "unknown" ) full_model_name = model # safe default before try block @@ -628,8 +640,9 @@ class WebSearchInterceptionLogger(CustomLogger): # Create a copy of optional params without max_tokens (since we pass it explicitly) optional_params_without_max_tokens = { - k: v for k, v in anthropic_messages_optional_request_params.items() - if k != 'max_tokens' + k: v + for k, v in anthropic_messages_optional_request_params.items() + if k != "max_tokens" } kwargs_for_followup = self._prepare_followup_kwargs(kwargs) @@ -637,12 +650,14 @@ class WebSearchInterceptionLogger(CustomLogger): # Get model from logging_obj.model_call_details["agentic_loop_params"] # This preserves the full model name with provider prefix (e.g., "bedrock/invoke/...") if logging_obj is not None: - agentic_params = logging_obj.model_call_details.get("agentic_loop_params", {}) + agentic_params = logging_obj.model_call_details.get( + "agentic_loop_params", {} + ) full_model_name = agentic_params.get("model", model) verbose_logger.debug( f"WebSearchInterception: Using model name: {full_model_name}" ) - + final_response = await anthropic_messages.acreate( max_tokens=max_tokens, messages=follow_up_messages, @@ -661,8 +676,11 @@ class WebSearchInterceptionLogger(CustomLogger): verbose_logger.exception( "WebSearchInterception: Follow-up request failed " "[call_id=%s model=%s messages=%d searches=%d]: %s", - _call_id, full_model_name, len(follow_up_messages), - len(final_search_results), str(e), + _call_id, + full_model_name, + len(follow_up_messages), + len(final_search_results), + str(e), ) raise @@ -685,12 +703,15 @@ class WebSearchInterceptionLogger(CustomLogger): if self.search_tool_name: # Find specific search tool by name matching_tools = [ - tool for tool in llm_router.search_tools + tool + for tool in llm_router.search_tools if tool.get("search_tool_name") == self.search_tool_name ] if matching_tools: search_tool = matching_tools[0] - search_provider = search_tool.get("litellm_params", {}).get("search_provider") + search_provider = search_tool.get("litellm_params", {}).get( + "search_provider" + ) verbose_logger.debug( f"WebSearchInterception: Found search tool '{self.search_tool_name}' " f"with provider '{search_provider}'" @@ -704,7 +725,9 @@ class WebSearchInterceptionLogger(CustomLogger): # If no specific tool or not found, use first available if not search_provider and llm_router.search_tools: first_tool = llm_router.search_tools[0] - search_provider = first_tool.get("litellm_params", {}).get("search_provider") + search_provider = first_tool.get("litellm_params", {}).get( + "search_provider" + ) verbose_logger.debug( f"WebSearchInterception: Using first available search tool with provider '{search_provider}'" ) @@ -720,9 +743,7 @@ class WebSearchInterceptionLogger(CustomLogger): verbose_logger.debug( f"WebSearchInterception: Executing search for '{query}' using provider '{search_provider}'" ) - result = await litellm.asearch( - query=query, search_provider=search_provider - ) + result = await litellm.asearch(query=query, search_provider=search_provider) # Format using transformation function search_result_text = WebSearchTransformation.format_search_response(result) @@ -737,7 +758,7 @@ class WebSearchInterceptionLogger(CustomLogger): ) raise - async def _execute_chat_completion_agentic_loop( # noqa: PLR0915 + async def _execute_chat_completion_agentic_loop( # noqa: PLR0915 self, model: str, messages: List[Dict], @@ -763,7 +784,7 @@ class WebSearchInterceptionLogger(CustomLogger): args = func.get("arguments", {}) if isinstance(args, dict): query = args.get("query") - + if query: verbose_logger.debug( f"WebSearchInterception: Queuing search for query='{query}'" @@ -789,9 +810,7 @@ class WebSearchInterceptionLogger(CustomLogger): verbose_logger.error( f"WebSearchInterception: Search {i} failed with error: {str(result)}" ) - final_search_results.append( - f"Search failed: {str(result)}" - ) + final_search_results.append(f"Search failed: {str(result)}") elif isinstance(result, str): final_search_results.append(cast(str, result)) else: @@ -801,7 +820,10 @@ class WebSearchInterceptionLogger(CustomLogger): final_search_results.append(str(result)) # Build assistant and tool messages using transformation - assistant_message, tool_messages_or_user = WebSearchTransformation.transform_response( + ( + assistant_message, + tool_messages_or_user, + ) = WebSearchTransformation.transform_response( tool_calls=tool_calls, search_results=final_search_results, response_format=response_format, @@ -810,10 +832,15 @@ class WebSearchInterceptionLogger(CustomLogger): # Make follow-up request with search results # For OpenAI format, tool_messages_or_user is a list of tool messages if response_format == "openai": - follow_up_messages = messages + [assistant_message] + cast(List[Dict], tool_messages_or_user) + follow_up_messages = ( + messages + [assistant_message] + cast(List[Dict], tool_messages_or_user) + ) else: # For Anthropic format (shouldn't happen in this method, but handle it) - follow_up_messages = messages + [assistant_message, cast(Dict, tool_messages_or_user)] + follow_up_messages = messages + [ + assistant_message, + cast(Dict, tool_messages_or_user), + ] verbose_logger.debug( "WebSearchInterception: Making follow-up chat completion request with search results" @@ -826,17 +853,19 @@ class WebSearchInterceptionLogger(CustomLogger): try: # Remove internal parameters that shouldn't be passed to follow-up request internal_params = { - '_websearch_interception', - 'acompletion', - 'litellm_logging_obj', - 'custom_llm_provider', - 'model_alias_map', - 'stream_response', - 'custom_prompt_dict', + "_websearch_interception", + "acompletion", + "litellm_logging_obj", + "custom_llm_provider", + "model_alias_map", + "stream_response", + "custom_prompt_dict", } kwargs_for_followup = { - k: v for k, v in kwargs.items() - if not k.startswith('_websearch_interception') and k not in internal_params + k: v + for k, v in kwargs.items() + if not k.startswith("_websearch_interception") + and k not in internal_params } # Get full model name from kwargs @@ -848,21 +877,29 @@ class WebSearchInterceptionLogger(CustomLogger): # Check if model already has a provider prefix if "/" not in model: full_model_name = f"{custom_llm_provider}/{model}" - + verbose_logger.debug( f"WebSearchInterception: Using model name: {full_model_name}" ) # Prepare tools for follow-up request (same as original) tools_param = optional_params.get("tools") - + # Remove tools and extra_body from optional_params to avoid issues # extra_body often contains internal LiteLLM params that shouldn't be forwarded optional_params_clean = { - k: v for k, v in optional_params.items() - if k not in {"tools", "extra_body", "model_alias_map","stream_response", "custom_prompt_dict" } + k: v + for k, v in optional_params.items() + if k + not in { + "tools", + "extra_body", + "model_alias_map", + "stream_response", + "custom_prompt_dict", + } } - + final_response = await litellm.acompletion( model=full_model_name, messages=follow_up_messages, @@ -870,7 +907,7 @@ class WebSearchInterceptionLogger(CustomLogger): **optional_params_clean, **kwargs_for_followup, ) - + verbose_logger.debug( f"WebSearchInterception: Follow-up request completed, response type: {type(final_response)}" ) diff --git a/litellm/integrations/websearch_interception/tools.py b/litellm/integrations/websearch_interception/tools.py index 7ef2b35004d..e373b64cdda 100644 --- a/litellm/integrations/websearch_interception/tools.py +++ b/litellm/integrations/websearch_interception/tools.py @@ -41,11 +41,11 @@ def get_litellm_web_search_tool() -> Dict[str, Any]: "properties": { "query": { "type": "string", - "description": "The search query to execute" + "description": "The search query to execute", } }, - "required": ["query"] - } + "required": ["query"], + }, } @@ -73,19 +73,19 @@ def get_litellm_web_search_tool_openai() -> Dict[str, Any]: "properties": { "query": { "type": "string", - "description": "The search query to execute" + "description": "The search query to execute", } }, - "required": ["query"] - } - } + "required": ["query"], + }, + }, } def is_web_search_tool_chat_completion(tool: Dict[str, Any]) -> bool: """ Check if a tool is a web search tool for Chat Completions API (strict check). - + This is a stricter version that ONLY checks for the exact LiteLLM web search tool name. Use this for Chat Completions API to avoid false positives with user-defined tools. @@ -111,7 +111,7 @@ def is_web_search_tool_chat_completion(tool: Dict[str, Any]) -> bool: """ tool_name = tool.get("name", "") tool_type = tool.get("type", "") - + # Check for OpenAI format: {"type": "function", "function": {"name": "litellm_web_search"}} if tool_type == "function" and "function" in tool: function_def = tool.get("function", {}) @@ -155,7 +155,7 @@ def is_web_search_tool(tool: Dict[str, Any]) -> bool: """ tool_name = tool.get("name", "") tool_type = tool.get("type", "") - + # Check for OpenAI format: {"type": "function", "function": {"name": "..."}} if tool_type == "function" and "function" in tool: function_def = tool.get("function", {}) diff --git a/litellm/integrations/websearch_interception/transformation.py b/litellm/integrations/websearch_interception/transformation.py index e016899e0c3..f777a7d7418 100644 --- a/litellm/integrations/websearch_interception/transformation.py +++ b/litellm/integrations/websearch_interception/transformation.py @@ -81,9 +81,7 @@ class WebSearchTransformation: content = response.content or [] if not content: - verbose_logger.debug( - "WebSearchInterception: Response has empty content" - ) + verbose_logger.debug("WebSearchInterception: Response has empty content") return False, [] # Find all WebSearch tool_use blocks @@ -104,7 +102,9 @@ class WebSearchTransformation: # Check for LiteLLM standard or legacy web search tools # Handles: litellm_web_search, WebSearch, web_search if block_type == "tool_use" and block_name in ( - LITELLM_WEB_SEARCH_TOOL_NAME, "WebSearch", "web_search" + LITELLM_WEB_SEARCH_TOOL_NAME, + "WebSearch", + "web_search", ): # Convert to dict for easier handling tool_call = { @@ -125,7 +125,7 @@ class WebSearchTransformation: response: Any, ) -> Tuple[bool, List[Dict]]: """Parse OpenAI-style response for WebSearch tool_calls""" - + # Handle both dict and ModelResponse objects if isinstance(response, dict): choices = response.get("choices", []) @@ -138,9 +138,7 @@ class WebSearchTransformation: choices = response.choices or [] if not choices: - verbose_logger.debug( - "WebSearchInterception: Response has empty choices" - ) + verbose_logger.debug("WebSearchInterception: Response has empty choices") return False, [] # Get first choice's message @@ -149,11 +147,9 @@ class WebSearchTransformation: message = first_choice.get("message", {}) else: message = getattr(first_choice, "message", None) - + if not message: - verbose_logger.debug( - "WebSearchInterception: First choice has no message" - ) + verbose_logger.debug("WebSearchInterception: First choice has no message") return False, [] # Get tool_calls from message @@ -163,9 +159,7 @@ class WebSearchTransformation: openai_tool_calls = getattr(message, "tool_calls", None) or [] if not openai_tool_calls: - verbose_logger.debug( - "WebSearchInterception: Message has no tool_calls" - ) + verbose_logger.debug("WebSearchInterception: Message has no tool_calls") return False, [] # Find all WebSearch tool calls @@ -176,18 +170,30 @@ class WebSearchTransformation: tool_id = tool_call.get("id") tool_type = tool_call.get("type") function = tool_call.get("function", {}) - function_name = function.get("name") if isinstance(function, dict) else getattr(function, "name", None) - function_arguments = function.get("arguments") if isinstance(function, dict) else getattr(function, "arguments", None) + function_name = ( + function.get("name") + if isinstance(function, dict) + else getattr(function, "name", None) + ) + function_arguments = ( + function.get("arguments") + if isinstance(function, dict) + else getattr(function, "arguments", None) + ) else: tool_id = getattr(tool_call, "id", None) tool_type = getattr(tool_call, "type", None) function = getattr(tool_call, "function", None) function_name = getattr(function, "name", None) if function else None - function_arguments = getattr(function, "arguments", None) if function else None + function_arguments = ( + getattr(function, "arguments", None) if function else None + ) # Check for LiteLLM standard or legacy web search tools if tool_type == "function" and function_name in ( - LITELLM_WEB_SEARCH_TOOL_NAME, "WebSearch", "web_search" + LITELLM_WEB_SEARCH_TOOL_NAME, + "WebSearch", + "web_search", ): # Parse arguments (might be JSON string) if isinstance(function_arguments, str): @@ -320,7 +326,9 @@ class WebSearchTransformation: "type": "function", "function": { "name": tc["name"], - "arguments": json.dumps(tc["input"]) if isinstance(tc["input"], dict) else str(tc["input"]), + "arguments": json.dumps(tc["input"]) + if isinstance(tc["input"], dict) + else str(tc["input"]), }, } for tc in tool_calls diff --git a/litellm/integrations/weights_biases.py b/litellm/integrations/weights_biases.py index 0d011e26aef..028b6e69a81 100644 --- a/litellm/integrations/weights_biases.py +++ b/litellm/integrations/weights_biases.py @@ -44,7 +44,9 @@ try: request, response, time_elapsed ) else: - logger.debug(f"Unknown OpenAI response object: {response['object']}") + logger.debug( + f"Unknown OpenAI response object: {response['object']}" + ) except Exception as e: logger.warning(f"Failed to resolve request/response: {e}") return None diff --git a/litellm/interactions/http_handler.py b/litellm/interactions/http_handler.py index 4b4ed9be4db..7fead07043f 100644 --- a/litellm/interactions/http_handler.py +++ b/litellm/interactions/http_handler.py @@ -86,11 +86,17 @@ class InteractionsHTTPHandler: ) -> Union[ InteractionsAPIResponse, Iterator[InteractionsAPIStreamingResponse], - Coroutine[Any, Any, Union[InteractionsAPIResponse, AsyncIterator[InteractionsAPIStreamingResponse]]], + Coroutine[ + Any, + Any, + Union[ + InteractionsAPIResponse, AsyncIterator[InteractionsAPIStreamingResponse] + ], + ], ]: """ Create a new interaction (synchronous or async based on _is_async flag). - + Per Google's OpenAPI spec, the endpoint is POST /{api_version}/interactions """ if _is_async: @@ -199,7 +205,9 @@ class InteractionsHTTPHandler: timeout: Optional[Union[float, httpx.Timeout]] = None, client: Optional[AsyncHTTPHandler] = None, stream: Optional[bool] = None, - ) -> Union[InteractionsAPIResponse, AsyncIterator[InteractionsAPIStreamingResponse]]: + ) -> Union[ + InteractionsAPIResponse, AsyncIterator[InteractionsAPIStreamingResponse] + ]: """ Create a new interaction (async version). """ @@ -287,7 +295,7 @@ class InteractionsHTTPHandler: interactions_api_config: BaseInteractionsAPIConfig, ) -> SyncInteractionsAPIStreamingIterator: """Create a synchronous streaming iterator. - + Google AI's streaming format uses SSE (Server-Sent Events). Returns a proper streaming iterator that yields chunks as they arrive. """ @@ -306,7 +314,7 @@ class InteractionsHTTPHandler: interactions_api_config: BaseInteractionsAPIConfig, ) -> InteractionsAPIStreamingIterator: """Create an asynchronous streaming iterator. - + Google AI's streaming format uses SSE (Server-Sent Events). Returns a proper streaming iterator that yields chunks as they arrive. """ @@ -687,4 +695,3 @@ class InteractionsHTTPHandler: # Initialize the HTTP handler singleton interactions_http_handler = InteractionsHTTPHandler() - diff --git a/litellm/interactions/litellm_responses_transformation/__init__.py b/litellm/interactions/litellm_responses_transformation/__init__.py index 2450a9f3d20..6f6b32503d2 100644 --- a/litellm/interactions/litellm_responses_transformation/__init__.py +++ b/litellm/interactions/litellm_responses_transformation/__init__.py @@ -13,4 +13,3 @@ __all__ = [ "LiteLLMResponsesInteractionsHandler", "LiteLLMResponsesInteractionsConfig", # Transformation config class (not BaseInteractionsAPIConfig) ] - diff --git a/litellm/interactions/litellm_responses_transformation/handler.py b/litellm/interactions/litellm_responses_transformation/handler.py index c2df8f96eff..b121ee37de6 100644 --- a/litellm/interactions/litellm_responses_transformation/handler.py +++ b/litellm/interactions/litellm_responses_transformation/handler.py @@ -56,7 +56,7 @@ class LiteLLMResponsesInteractionsHandler: ]: """ Handle Interactions API request by calling litellm.responses(). - + Args: model: The model to use input: The input content @@ -65,22 +65,20 @@ class LiteLLMResponsesInteractionsHandler: _is_async: Whether this is an async call stream: Whether to stream the response **kwargs: Additional parameters - + Returns: InteractionsAPIResponse or streaming iterator """ # Transform interactions request to responses request - responses_request = ( - LiteLLMResponsesInteractionsConfig.transform_interactions_request_to_responses_request( - model=model, - input=input, - optional_params=optional_params, - custom_llm_provider=custom_llm_provider, - stream=stream, - **kwargs, - ) + responses_request = LiteLLMResponsesInteractionsConfig.transform_interactions_request_to_responses_request( + model=model, + input=input, + optional_params=optional_params, + custom_llm_provider=custom_llm_provider, + stream=stream, + **kwargs, ) - + if _is_async: return self.async_interactions_api_handler( responses_request=responses_request, @@ -89,14 +87,14 @@ class LiteLLMResponsesInteractionsHandler: optional_params=optional_params, **kwargs, ) - + # Call litellm.responses() # Note: litellm.responses() returns Union[ResponsesAPIResponse, BaseResponsesAPIStreamingIterator] # but the type checker may see it as a coroutine in some contexts responses_response = litellm.responses( **responses_request, ) - + # Handle streaming response if isinstance(responses_response, BaseResponsesAPIStreamingIterator): return LiteLLMResponsesInteractionsStreamingIterator( @@ -107,11 +105,11 @@ class LiteLLMResponsesInteractionsHandler: custom_llm_provider=custom_llm_provider, litellm_metadata=kwargs.get("litellm_metadata", {}), ) - + # At this point, responses_response must be ResponsesAPIResponse (not streaming) # Cast to satisfy type checker since we've already checked it's not a streaming iterator responses_api_response = cast(ResponsesAPIResponse, responses_response) - + # Transform responses response to interactions response return LiteLLMResponsesInteractionsConfig.transform_responses_response_to_interactions_response( responses_response=responses_api_response, @@ -125,14 +123,16 @@ class LiteLLMResponsesInteractionsHandler: input: Optional[InteractionInput], optional_params: InteractionsAPIOptionalRequestParams, **kwargs, - ) -> Union[InteractionsAPIResponse, AsyncIterator[InteractionsAPIStreamingResponse]]: + ) -> Union[ + InteractionsAPIResponse, AsyncIterator[InteractionsAPIStreamingResponse] + ]: """Async handler for interactions API requests.""" # Call litellm.aresponses() # Note: litellm.aresponses() returns Union[ResponsesAPIResponse, BaseResponsesAPIStreamingIterator] responses_response = await litellm.aresponses( **responses_request, ) - + # Handle streaming response if isinstance(responses_response, BaseResponsesAPIStreamingIterator): return LiteLLMResponsesInteractionsStreamingIterator( @@ -143,14 +143,13 @@ class LiteLLMResponsesInteractionsHandler: custom_llm_provider=responses_request.get("custom_llm_provider"), litellm_metadata=kwargs.get("litellm_metadata", {}), ) - + # At this point, responses_response must be ResponsesAPIResponse (not streaming) # Cast to satisfy type checker since we've already checked it's not a streaming iterator responses_api_response = cast(ResponsesAPIResponse, responses_response) - + # Transform responses response to interactions response return LiteLLMResponsesInteractionsConfig.transform_responses_response_to_interactions_response( responses_response=responses_api_response, model=model, ) - diff --git a/litellm/interactions/litellm_responses_transformation/streaming_iterator.py b/litellm/interactions/litellm_responses_transformation/streaming_iterator.py index 511b69e83b2..72a3afbc3c5 100644 --- a/litellm/interactions/litellm_responses_transformation/streaming_iterator.py +++ b/litellm/interactions/litellm_responses_transformation/streaming_iterator.py @@ -26,7 +26,7 @@ from litellm.types.llms.openai import ( class LiteLLMResponsesInteractionsStreamingIterator: """ Iterator that wraps Responses API streaming and transforms chunks to Interactions API format. - + This class handles both sync and async iteration, transforming Responses API streaming events (output.text.delta, response.completed, etc.) to Interactions API streaming events (content.delta, interaction.complete, etc.). @@ -58,11 +58,11 @@ class LiteLLMResponsesInteractionsStreamingIterator: ) -> Optional[InteractionsAPIStreamingResponse]: """ Transform a Responses API streaming chunk to an Interactions API streaming chunk. - + Responses API events: - output.text.delta -> content.delta - response.completed -> interaction.complete - + Interactions API events: - interaction.start - content.start @@ -72,23 +72,26 @@ class LiteLLMResponsesInteractionsStreamingIterator: """ if not responses_chunk: return None - + # Handle OutputTextDeltaEvent -> content.delta if isinstance(responses_chunk, OutputTextDeltaEvent): - delta_text = responses_chunk.delta if isinstance(responses_chunk.delta, str) else "" + delta_text = ( + responses_chunk.delta if isinstance(responses_chunk.delta, str) else "" + ) self.collected_text += delta_text - + # Send interaction.start if not sent if not self.sent_interaction_start: self.sent_interaction_start = True return InteractionsAPIStreamingResponse( event_type="interaction.start", - id=getattr(responses_chunk, "item_id", None) or f"interaction_{id(self)}", + id=getattr(responses_chunk, "item_id", None) + or f"interaction_{id(self)}", object="interaction", status="in_progress", model=self.model, ) - + # Send content.start if not sent if not self.sent_content_start: self.sent_content_start = True @@ -98,7 +101,7 @@ class LiteLLMResponsesInteractionsStreamingIterator: object="content", delta={"type": "text", "text": ""}, ) - + # Send content.delta return InteractionsAPIStreamingResponse( event_type="content.delta", @@ -106,12 +109,16 @@ class LiteLLMResponsesInteractionsStreamingIterator: object="content", delta={"text": delta_text}, ) - + # Handle ResponseCreatedEvent or ResponseInProgressEvent -> interaction.start if isinstance(responses_chunk, (ResponseCreatedEvent, ResponseInProgressEvent)): if not self.sent_interaction_start: self.sent_interaction_start = True - response_id = getattr(responses_chunk.response, "id", None) if hasattr(responses_chunk, "response") else None + response_id = ( + getattr(responses_chunk.response, "id", None) + if hasattr(responses_chunk, "response") + else None + ) return InteractionsAPIStreamingResponse( event_type="interaction.start", id=response_id or f"interaction_{id(self)}", @@ -119,17 +126,17 @@ class LiteLLMResponsesInteractionsStreamingIterator: status="in_progress", model=self.model, ) - + # Handle ResponseCompletedEvent -> interaction.complete if isinstance(responses_chunk, ResponseCompletedEvent): self.finished = True response = responses_chunk.response - + # Send content.stop first if content was started if self.sent_content_start: # Note: We'll send this in the iterator, not here pass - + # Send interaction.complete return InteractionsAPIStreamingResponse( event_type="interaction.complete", @@ -144,7 +151,7 @@ class LiteLLMResponsesInteractionsStreamingIterator: } ], ) - + # For other event types, return None (skip) return None @@ -156,26 +163,36 @@ class LiteLLMResponsesInteractionsStreamingIterator: """Get next chunk in sync mode.""" if self.finished: raise StopIteration - + # Check if we have a pending interaction.complete to send if hasattr(self, "_pending_interaction_complete"): - pending: InteractionsAPIStreamingResponse = getattr(self, "_pending_interaction_complete") + pending: InteractionsAPIStreamingResponse = getattr( + self, "_pending_interaction_complete" + ) delattr(self, "_pending_interaction_complete") return pending - + # Use a loop instead of recursion to avoid stack overflow - sync_iterator = cast(SyncResponsesAPIStreamingIterator, self.responses_stream_iterator) + sync_iterator = cast( + SyncResponsesAPIStreamingIterator, self.responses_stream_iterator + ) while True: try: # Get next chunk from responses API stream chunk = next(sync_iterator) - + # Transform chunk (chunk is already a ResponsesAPIStreamingResponse) - transformed = self._transform_responses_chunk_to_interactions_chunk(chunk) - + transformed = self._transform_responses_chunk_to_interactions_chunk( + chunk + ) + if transformed: # If we finished and content was started, send content.stop before interaction.complete - if self.finished and self.sent_content_start and transformed.event_type == "interaction.complete": + if ( + self.finished + and self.sent_content_start + and transformed.event_type == "interaction.complete" + ): # Send content.stop first content_stop = InteractionsAPIStreamingResponse( event_type="content.stop", @@ -187,12 +204,12 @@ class LiteLLMResponsesInteractionsStreamingIterator: self._pending_interaction_complete = transformed return content_stop return transformed - + # If no transformation, continue to next chunk (loop continues) - + except StopIteration: self.finished = True - + # Send final events if needed if self.sent_content_start: return InteractionsAPIStreamingResponse( @@ -200,7 +217,7 @@ class LiteLLMResponsesInteractionsStreamingIterator: object="content", delta={"type": "text", "text": self.collected_text}, ) - + raise StopIteration def __aiter__(self) -> AsyncIterator[InteractionsAPIStreamingResponse]: @@ -211,26 +228,36 @@ class LiteLLMResponsesInteractionsStreamingIterator: """Get next chunk in async mode.""" if self.finished: raise StopAsyncIteration - + # Check if we have a pending interaction.complete to send if hasattr(self, "_pending_interaction_complete"): - pending: InteractionsAPIStreamingResponse = getattr(self, "_pending_interaction_complete") + pending: InteractionsAPIStreamingResponse = getattr( + self, "_pending_interaction_complete" + ) delattr(self, "_pending_interaction_complete") return pending - + # Use a loop instead of recursion to avoid stack overflow - async_iterator = cast(ResponsesAPIStreamingIterator, self.responses_stream_iterator) + async_iterator = cast( + ResponsesAPIStreamingIterator, self.responses_stream_iterator + ) while True: try: # Get next chunk from responses API stream chunk = await async_iterator.__anext__() - + # Transform chunk (chunk is already a ResponsesAPIStreamingResponse) - transformed = self._transform_responses_chunk_to_interactions_chunk(chunk) - + transformed = self._transform_responses_chunk_to_interactions_chunk( + chunk + ) + if transformed: # If we finished and content was started, send content.stop before interaction.complete - if self.finished and self.sent_content_start and transformed.event_type == "interaction.complete": + if ( + self.finished + and self.sent_content_start + and transformed.event_type == "interaction.complete" + ): # Send content.stop first content_stop = InteractionsAPIStreamingResponse( event_type="content.stop", @@ -242,12 +269,12 @@ class LiteLLMResponsesInteractionsStreamingIterator: self._pending_interaction_complete = transformed return content_stop return transformed - + # If no transformation, continue to next chunk (loop continues) - + except StopAsyncIteration: self.finished = True - + # Send final events if needed if self.sent_content_start: return InteractionsAPIStreamingResponse( @@ -255,6 +282,5 @@ class LiteLLMResponsesInteractionsStreamingIterator: object="content", delta={"type": "text", "text": self.collected_text}, ) - - raise StopAsyncIteration + raise StopAsyncIteration diff --git a/litellm/interactions/litellm_responses_transformation/transformation.py b/litellm/interactions/litellm_responses_transformation/transformation.py index 24b2c5dbde7..b07e61c76dd 100644 --- a/litellm/interactions/litellm_responses_transformation/transformation.py +++ b/litellm/interactions/litellm_responses_transformation/transformation.py @@ -32,7 +32,7 @@ class LiteLLMResponsesInteractionsConfig: ) -> Dict[str, Any]: """ Transform an Interactions API request to a Responses API request. - + Key transformations: - system_instruction -> instructions - input (string | Turn[]) -> input (ResponseInputParam) @@ -42,23 +42,23 @@ class LiteLLMResponsesInteractionsConfig: responses_request: Dict[str, Any] = { "model": model, } - + # Transform input if input is not None: - responses_request["input"] = ( - LiteLLMResponsesInteractionsConfig._transform_interactions_input_to_responses_input( - input - ) + responses_request[ + "input" + ] = LiteLLMResponsesInteractionsConfig._transform_interactions_input_to_responses_input( + input ) - + # Transform system_instruction -> instructions if optional_params.get("system_instruction"): responses_request["instructions"] = optional_params["system_instruction"] - + # Transform tools (similar format, pass through for now) if optional_params.get("tools"): responses_request["tools"] = optional_params["tools"] - + # Transform generation_config to temperature, top_p, etc. generation_config = optional_params.get("generation_config") if generation_config: @@ -71,17 +71,19 @@ class LiteLLMResponsesInteractionsConfig: # Responses API doesn't have top_k, skip it pass if "max_output_tokens" in generation_config: - responses_request["max_output_tokens"] = generation_config["max_output_tokens"] - + responses_request["max_output_tokens"] = generation_config[ + "max_output_tokens" + ] + # Pass through other optional params that match passthrough_params = ["stream", "store", "metadata", "user"] for param in passthrough_params: if param in optional_params and optional_params[param] is not None: responses_request[param] = optional_params[param] - + # Add any extra kwargs responses_request.update(kwargs) - + return responses_request @staticmethod @@ -90,12 +92,12 @@ class LiteLLMResponsesInteractionsConfig: ) -> ResponseInputParam: """ Transform Interactions API input to Responses API input format. - + Interactions API input can be: - string: "Hello" - Turn[]: [{"role": "user", "content": [...]}] - Content object - + Responses API input is: - string: "Hello" - Message[]: [{"role": "user", "content": [...]}] @@ -103,7 +105,7 @@ class LiteLLMResponsesInteractionsConfig: if isinstance(input, str): # ResponseInputParam accepts str return cast(ResponseInputParam, input) - + if isinstance(input, list): # Turn[] format - convert to Responses API Message[] format messages = [] @@ -111,21 +113,25 @@ class LiteLLMResponsesInteractionsConfig: if isinstance(turn, dict): role = turn.get("role", "user") content = turn.get("content", []) - + # Transform content array transformed_content = ( - LiteLLMResponsesInteractionsConfig._transform_content_array(content) + LiteLLMResponsesInteractionsConfig._transform_content_array( + content + ) + ) + + messages.append( + { + "role": role, + "content": transformed_content, + } ) - - messages.append({ - "role": role, - "content": transformed_content, - }) elif isinstance(turn, Turn): # Pydantic model role = turn.role if hasattr(turn, "role") else "user" content = turn.content if hasattr(turn, "content") else [] - + # Ensure content is a list for _transform_content_array # Cast to List[Any] to handle various content types if isinstance(content, list): @@ -134,27 +140,38 @@ class LiteLLMResponsesInteractionsConfig: content_list = [content] else: content_list = [] - + transformed_content = ( - LiteLLMResponsesInteractionsConfig._transform_content_array(content_list) + LiteLLMResponsesInteractionsConfig._transform_content_array( + content_list + ) ) - - messages.append({ - "role": role, - "content": transformed_content, - }) - + + messages.append( + { + "role": role, + "content": transformed_content, + } + ) + return cast(ResponseInputParam, messages) - + # Single content object - wrap in message if isinstance(input, dict): - return cast(ResponseInputParam, [{ - "role": "user", - "content": LiteLLMResponsesInteractionsConfig._transform_content_array( - input.get("content", []) if isinstance(input.get("content"), list) else [input] - ), - }]) - + return cast( + ResponseInputParam, + [ + { + "role": "user", + "content": LiteLLMResponsesInteractionsConfig._transform_content_array( + input.get("content", []) + if isinstance(input.get("content"), list) + else [input] + ), + } + ], + ) + # Fallback: convert to string return cast(ResponseInputParam, str(input)) @@ -164,7 +181,7 @@ class LiteLLMResponsesInteractionsConfig: if not isinstance(content, list): # Single content item - wrap in array content = [content] - + transformed: List[Dict[str, Any]] = [] for item in content: if isinstance(item, dict): @@ -192,7 +209,7 @@ class LiteLLMResponsesInteractionsConfig: else: # Fallback: wrap in text format transformed.append({"type": "text", "text": str(item)}) - + return transformed @staticmethod @@ -202,7 +219,7 @@ class LiteLLMResponsesInteractionsConfig: ) -> InteractionsAPIResponse: """ Transform a Responses API response to an Interactions API response. - + Key transformations: - Extract text from output[].content[].text - Convert created_at (int) to created (ISO string) @@ -221,23 +238,29 @@ class LiteLLMResponsesInteractionsConfig: # Check if content_item has text attribute text = getattr(content_item, "text", None) if text is not None: - outputs.append({ - "type": "text", - "text": text, - }) - elif isinstance(content_item, dict) and content_item.get("type") == "text": + outputs.append( + { + "type": "text", + "text": text, + } + ) + elif ( + isinstance(content_item, dict) + and content_item.get("type") == "text" + ): outputs.append(content_item) - + # Convert created_at to ISO string created_at = getattr(responses_response, "created_at", None) if isinstance(created_at, int): from datetime import datetime + created = datetime.fromtimestamp(created_at).isoformat() elif created_at is not None and hasattr(created_at, "isoformat"): created = created_at.isoformat() else: created = None - + # Map status status = getattr(responses_response, "status", "completed") if status == "completed": @@ -246,7 +269,7 @@ class LiteLLMResponsesInteractionsConfig: interactions_status = "in_progress" else: interactions_status = status - + # Build interactions response interactions_response_dict: Dict[str, Any] = { "id": getattr(responses_response, "id", ""), @@ -256,7 +279,7 @@ class LiteLLMResponsesInteractionsConfig: "model": model or getattr(responses_response, "model", ""), "created": created, } - + # Add usage if available # Map Responses API usage (input_tokens, output_tokens) to Interactions API spec format # (total_input_tokens, total_output_tokens) @@ -266,12 +289,11 @@ class LiteLLMResponsesInteractionsConfig: "total_input_tokens": getattr(usage, "input_tokens", 0), "total_output_tokens": getattr(usage, "output_tokens", 0), } - + # Add role interactions_response_dict["role"] = "model" - + # Add updated (same as created for now) interactions_response_dict["updated"] = created - - return InteractionsAPIResponse(**interactions_response_dict) + return InteractionsAPIResponse(**interactions_response_dict) diff --git a/litellm/interactions/main.py b/litellm/interactions/main.py index fb811b25b2f..2b1786ac3ae 100644 --- a/litellm/interactions/main.py +++ b/litellm/interactions/main.py @@ -105,9 +105,9 @@ async def acreate( ) -> Union[InteractionsAPIResponse, AsyncIterator[InteractionsAPIStreamingResponse]]: """ Async: Create a new interaction using Google's Interactions API. - + Per OpenAPI spec, provide either `model` or `agent`. - + Args: model: The model to use (e.g., "gemini-2.5-flash") agent: The agent to use (e.g., "deep-research-pro-preview-12-2025") @@ -126,7 +126,7 @@ async def acreate( extra_body: Additional body parameters timeout: Request timeout custom_llm_provider: Override the LLM provider - + Returns: InteractionsAPIResponse or async iterator for streaming """ @@ -134,14 +134,14 @@ async def acreate( try: loop = asyncio.get_event_loop() kwargs["acreate_interaction"] = True - + if custom_llm_provider is None and model: _, custom_llm_provider, _, _ = litellm.get_llm_provider( model=model, api_base=kwargs.get("api_base", None) ) elif custom_llm_provider is None: custom_llm_provider = "gemini" - + func = partial( create, model=model, @@ -163,16 +163,16 @@ async def acreate( custom_llm_provider=custom_llm_provider, **kwargs, ) - + ctx = contextvars.copy_context() func_with_context = partial(ctx.run, func) init_response = await loop.run_in_executor(None, func_with_context) - + if asyncio.iscoroutine(init_response): response = await init_response else: response = init_response - + return response # type: ignore except Exception as e: raise litellm.exception_type( @@ -219,13 +219,17 @@ def create( ) -> Union[ InteractionsAPIResponse, Iterator[InteractionsAPIStreamingResponse], - Coroutine[Any, Any, Union[InteractionsAPIResponse, AsyncIterator[InteractionsAPIStreamingResponse]]], + Coroutine[ + Any, + Any, + Union[InteractionsAPIResponse, AsyncIterator[InteractionsAPIStreamingResponse]], + ], ]: """ Sync: Create a new interaction using Google's Interactions API. - + Per OpenAPI spec, provide either `model` or `agent`. - + Args: model: The model to use (e.g., "gemini-2.5-flash") agent: The agent to use (e.g., "deep-research-pro-preview-12-2025") @@ -244,47 +248,53 @@ def create( extra_body: Additional body parameters timeout: Request timeout custom_llm_provider: Override the LLM provider - + Returns: InteractionsAPIResponse or iterator for streaming """ local_vars = locals() - + try: litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None) _is_async = kwargs.pop("acreate_interaction", False) is True - + litellm_params = GenericLiteLLMParams(**kwargs) - + if model: model, custom_llm_provider, _, _ = litellm.get_llm_provider( - model=model, - custom_llm_provider=custom_llm_provider, - api_base=litellm_params.api_base, - api_key=litellm_params.api_key, - ) + model=model, + custom_llm_provider=custom_llm_provider, + api_base=litellm_params.api_base, + api_key=litellm_params.api_key, + ) else: custom_llm_provider = custom_llm_provider or "gemini" - + interactions_api_config = get_provider_interactions_api_config( provider=custom_llm_provider, model=model, ) - + # Get optional params using utility (similar to responses API pattern) local_vars.update(kwargs) - optional_params = InteractionsAPIRequestUtils.get_requested_interactions_api_optional_params( - local_vars + optional_params = ( + InteractionsAPIRequestUtils.get_requested_interactions_api_optional_params( + local_vars + ) ) - + # Check if this is a bridge provider (litellm_responses) - similar to responses API # Either provider is explicitly "litellm_responses" or no config found (bridge to responses) - if custom_llm_provider == "litellm_responses" or interactions_api_config is None: + if ( + custom_llm_provider == "litellm_responses" + or interactions_api_config is None + ): # Bridge to litellm.responses() for non-native providers from litellm.interactions.litellm_responses_transformation.handler import ( LiteLLMResponsesInteractionsHandler, ) + handler = LiteLLMResponsesInteractionsHandler() return handler.interactions_api_handler( model=model or "", @@ -295,14 +305,14 @@ def create( stream=stream, **kwargs, ) - + litellm_logging_obj.update_environment_variables( model=model, optional_params=dict(optional_params), litellm_params={"litellm_call_id": litellm_call_id}, custom_llm_provider=custom_llm_provider, ) - + response = interactions_http_handler.create_interaction( model=model, agent=agent, @@ -318,7 +328,7 @@ def create( _is_async=_is_async, stream=stream, ) - + return response except Exception as e: raise litellm.exception_type( @@ -348,7 +358,7 @@ async def aget( try: loop = asyncio.get_event_loop() kwargs["aget_interaction"] = True - + func = partial( get, interaction_id=interaction_id, @@ -357,16 +367,16 @@ async def aget( custom_llm_provider=custom_llm_provider or "gemini", **kwargs, ) - + ctx = contextvars.copy_context() func_with_context = partial(ctx.run, func) init_response = await loop.run_in_executor(None, func_with_context) - + if asyncio.iscoroutine(init_response): response = await init_response else: response = init_response - + return response # type: ignore except Exception as e: raise litellm.exception_type( @@ -389,28 +399,30 @@ def get( """Sync: Get an interaction by its ID.""" local_vars = locals() custom_llm_provider = custom_llm_provider or "gemini" - + try: litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None) _is_async = kwargs.pop("aget_interaction", False) is True - + litellm_params = GenericLiteLLMParams(**kwargs) - + interactions_api_config = get_provider_interactions_api_config( provider=custom_llm_provider, ) - + if interactions_api_config is None: - raise ValueError(f"Interactions API not supported for: {custom_llm_provider}") - + raise ValueError( + f"Interactions API not supported for: {custom_llm_provider}" + ) + litellm_logging_obj.update_environment_variables( model=None, optional_params={"interaction_id": interaction_id}, litellm_params={"litellm_call_id": litellm_call_id}, custom_llm_provider=custom_llm_provider, ) - + return interactions_http_handler.get_interaction( interaction_id=interaction_id, interactions_api_config=interactions_api_config, @@ -449,7 +461,7 @@ async def adelete( try: loop = asyncio.get_event_loop() kwargs["adelete_interaction"] = True - + func = partial( delete, interaction_id=interaction_id, @@ -458,16 +470,16 @@ async def adelete( custom_llm_provider=custom_llm_provider or "gemini", **kwargs, ) - + ctx = contextvars.copy_context() func_with_context = partial(ctx.run, func) init_response = await loop.run_in_executor(None, func_with_context) - + if asyncio.iscoroutine(init_response): response = await init_response else: response = init_response - + return response # type: ignore except Exception as e: raise litellm.exception_type( @@ -490,28 +502,30 @@ def delete( """Sync: Delete an interaction by its ID.""" local_vars = locals() custom_llm_provider = custom_llm_provider or "gemini" - + try: litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None) _is_async = kwargs.pop("adelete_interaction", False) is True - + litellm_params = GenericLiteLLMParams(**kwargs) - + interactions_api_config = get_provider_interactions_api_config( provider=custom_llm_provider, ) - + if interactions_api_config is None: - raise ValueError(f"Interactions API not supported for: {custom_llm_provider}") - + raise ValueError( + f"Interactions API not supported for: {custom_llm_provider}" + ) + litellm_logging_obj.update_environment_variables( model=None, optional_params={"interaction_id": interaction_id}, litellm_params={"litellm_call_id": litellm_call_id}, custom_llm_provider=custom_llm_provider, ) - + return interactions_http_handler.delete_interaction( interaction_id=interaction_id, interactions_api_config=interactions_api_config, @@ -550,7 +564,7 @@ async def acancel( try: loop = asyncio.get_event_loop() kwargs["acancel_interaction"] = True - + func = partial( cancel, interaction_id=interaction_id, @@ -559,16 +573,16 @@ async def acancel( custom_llm_provider=custom_llm_provider or "gemini", **kwargs, ) - + ctx = contextvars.copy_context() func_with_context = partial(ctx.run, func) init_response = await loop.run_in_executor(None, func_with_context) - + if asyncio.iscoroutine(init_response): response = await init_response else: response = init_response - + return response # type: ignore except Exception as e: raise litellm.exception_type( @@ -591,28 +605,30 @@ def cancel( """Sync: Cancel an interaction by its ID.""" local_vars = locals() custom_llm_provider = custom_llm_provider or "gemini" - + try: litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None) _is_async = kwargs.pop("acancel_interaction", False) is True - + litellm_params = GenericLiteLLMParams(**kwargs) - + interactions_api_config = get_provider_interactions_api_config( provider=custom_llm_provider, ) - + if interactions_api_config is None: - raise ValueError(f"Interactions API not supported for: {custom_llm_provider}") - + raise ValueError( + f"Interactions API not supported for: {custom_llm_provider}" + ) + litellm_logging_obj.update_environment_variables( model=None, optional_params={"interaction_id": interaction_id}, litellm_params={"litellm_call_id": litellm_call_id}, custom_llm_provider=custom_llm_provider, ) - + return interactions_http_handler.cancel_interaction( interaction_id=interaction_id, interactions_api_config=interactions_api_config, diff --git a/litellm/interactions/streaming_iterator.py b/litellm/interactions/streaming_iterator.py index f65d08d3ca9..a5a7f9e06e5 100644 --- a/litellm/interactions/streaming_iterator.py +++ b/litellm/interactions/streaming_iterator.py @@ -61,7 +61,9 @@ class BaseInteractionsAPIStreamingIterator: "litellm_params", {} ), ) - _model_info: Dict = litellm_metadata.get("model_info", {}) if litellm_metadata else {} + _model_info: Dict = ( + litellm_metadata.get("model_info", {}) if litellm_metadata else {} + ) self._hidden_params = { "model_id": _model_info.get("id", None), "api_base": _api_base, @@ -91,10 +93,12 @@ class BaseInteractionsAPIStreamingIterator: # Format as InteractionsAPIStreamingResponse if isinstance(parsed_chunk, dict): - streaming_response = self.interactions_api_config.transform_streaming_response( - model=self.model, - parsed_chunk=parsed_chunk, - logging_obj=self.logging_obj, + streaming_response = ( + self.interactions_api_config.transform_streaming_response( + model=self.model, + parsed_chunk=parsed_chunk, + logging_obj=self.logging_obj, + ) ) # Store the completed response (check for status=completed) @@ -110,7 +114,9 @@ class BaseInteractionsAPIStreamingIterator: return None except json.JSONDecodeError: # If we can't parse the chunk, continue - verbose_logger.debug(f"Failed to parse streaming chunk: {stripped_chunk[:200]}...") + verbose_logger.debug( + f"Failed to parse streaming chunk: {stripped_chunk[:200]}..." + ) return None def _handle_logging_completed_response(self): @@ -171,6 +177,7 @@ class InteractionsAPIStreamingIterator(BaseInteractionsAPIStreamingIterator): def _handle_logging_completed_response(self): """Handle logging for completed responses in async context.""" import copy + logging_response = copy.deepcopy(self.completed_response) asyncio.create_task( @@ -244,6 +251,7 @@ class SyncInteractionsAPIStreamingIterator(BaseInteractionsAPIStreamingIterator) def _handle_logging_completed_response(self): """Handle logging for completed responses in sync context.""" import copy + logging_response = copy.deepcopy(self.completed_response) run_async_function( @@ -261,4 +269,3 @@ class SyncInteractionsAPIStreamingIterator(BaseInteractionsAPIStreamingIterator) start_time=self.start_time, end_time=datetime.now(), ) - diff --git a/litellm/interactions/utils.py b/litellm/interactions/utils.py index 4fc40916e52..3a18ddf52fe 100644 --- a/litellm/interactions/utils.py +++ b/litellm/interactions/utils.py @@ -29,22 +29,23 @@ def get_provider_interactions_api_config( ) -> Optional[BaseInteractionsAPIConfig]: """ Get the interactions API config for the given provider. - + Args: provider: The LLM provider name model: Optional model name - + Returns: The provider-specific interactions API config, or None if not supported """ from litellm.types.utils import LlmProviders - + if provider == LlmProviders.GEMINI.value or provider == "gemini": from litellm.llms.gemini.interactions.transformation import ( GoogleAIStudioInteractionsConfig, ) + return GoogleAIStudioInteractionsConfig() - + return None @@ -76,7 +77,9 @@ class InteractionsAPIRequestUtils: special_params=special_params, custom_llm_provider=custom_llm_provider, additional_drop_params=additional_drop_params, - default_param_values={k: None for k in INTERACTIONS_API_OPTIONAL_PARAMS}, + default_param_values={ + k: None for k in INTERACTIONS_API_OPTIONAL_PARAMS + }, additional_endpoint_specific_params=["input", "model", "agent"], ) ) diff --git a/litellm/litellm_core_utils/app_crypto.py b/litellm/litellm_core_utils/app_crypto.py index 5ce6d8d77f9..e47962d6a36 100644 --- a/litellm/litellm_core_utils/app_crypto.py +++ b/litellm/litellm_core_utils/app_crypto.py @@ -30,4 +30,4 @@ class AppCrypto: ct = base64.b64decode(enc["ciphertext"]) tag = base64.b64decode(enc["tag"]) data = aes.decrypt(nonce, ct + tag, aad) - return json.loads(data.decode()) \ No newline at end of file + return json.loads(data.decode()) diff --git a/litellm/litellm_core_utils/audio_utils/utils.py b/litellm/litellm_core_utils/audio_utils/utils.py index a7d12841e58..2141df18738 100644 --- a/litellm/litellm_core_utils/audio_utils/utils.py +++ b/litellm/litellm_core_utils/audio_utils/utils.py @@ -135,7 +135,7 @@ def get_audio_file_content_hash(file_obj: FileTypes) -> str: """ file_content: Optional[bytes] = None fallback_filename: Optional[str] = None - + if isinstance(file_obj, tuple): if len(file_obj) < 2: fallback_filename = str(file_obj[0]) if len(file_obj) > 0 else None @@ -145,7 +145,7 @@ def get_audio_file_content_hash(file_obj: FileTypes) -> str: else: file_content_obj = file_obj fallback_filename = get_audio_file_name(file_obj) - + try: if isinstance(file_content_obj, (bytes, bytearray)): file_content = bytes(file_content_obj) @@ -160,7 +160,11 @@ def get_audio_file_content_hash(file_obj: FileTypes) -> str: file_content = None elif hasattr(file_content_obj, "read"): try: - current_position = file_content_obj.tell() if hasattr(file_content_obj, "tell") else None + current_position = ( + file_content_obj.tell() + if hasattr(file_content_obj, "tell") + else None + ) if hasattr(file_content_obj, "seek"): file_content_obj.seek(0) file_content = file_content_obj.read() # type: ignore @@ -172,20 +176,20 @@ def get_audio_file_content_hash(file_obj: FileTypes) -> str: file_content = None except Exception: file_content = None - + if file_content is not None and isinstance(file_content, bytes): try: hash_object = hashlib.sha256(file_content) return hash_object.hexdigest() except Exception: pass - + if fallback_filename: - hash_object = hashlib.sha256(fallback_filename.encode('utf-8')) + hash_object = hashlib.sha256(fallback_filename.encode("utf-8")) return hash_object.hexdigest() - + file_obj_str = str(file_obj) - hash_object = hashlib.sha256(file_obj_str.encode('utf-8')) + hash_object = hashlib.sha256(file_obj_str.encode("utf-8")) return hash_object.hexdigest() diff --git a/litellm/litellm_core_utils/cached_imports.py b/litellm/litellm_core_utils/cached_imports.py index c3ab292e9c5..1a3943cc517 100644 --- a/litellm/litellm_core_utils/cached_imports.py +++ b/litellm/litellm_core_utils/cached_imports.py @@ -24,6 +24,7 @@ def get_litellm_logging_class() -> Type["Logging"]: if _LiteLLMLogging is not None: return _LiteLLMLogging from litellm.litellm_core_utils.litellm_logging import Logging + _LiteLLMLogging = Logging return _LiteLLMLogging @@ -34,6 +35,7 @@ def get_coroutine_checker() -> "CoroutineChecker": if _coroutine_checker is not None: return _coroutine_checker from litellm.litellm_core_utils.coroutine_checker import coroutine_checker + _coroutine_checker = coroutine_checker return _coroutine_checker @@ -44,6 +46,7 @@ def get_set_callbacks() -> Callable: if _set_callbacks is not None: return _set_callbacks from litellm.litellm_core_utils.litellm_logging import set_callbacks + _set_callbacks = set_callbacks return _set_callbacks diff --git a/litellm/litellm_core_utils/cli_token_utils.py b/litellm/litellm_core_utils/cli_token_utils.py index 2aedb1c19d2..e2e304931a4 100644 --- a/litellm/litellm_core_utils/cli_token_utils.py +++ b/litellm/litellm_core_utils/cli_token_utils.py @@ -23,9 +23,9 @@ def load_cli_token() -> Optional[dict]: token_file = get_cli_token_file_path() if not os.path.exists(token_file): return None - + try: - with open(token_file, 'r') as f: + with open(token_file, "r") as f: return json.load(f) except (json.JSONDecodeError, IOError): return None @@ -34,13 +34,13 @@ def load_cli_token() -> Optional[dict]: def get_litellm_gateway_api_key() -> Optional[str]: """ Get the stored CLI API key for use with LiteLLM SDK. - + This function reads the token file created by `litellm-proxy login` and returns the API key for use in Python scripts. - + Returns: str: The API key if found, None otherwise - + Example: >>> import litellm >>> api_key = litellm.get_litellm_gateway_api_key() @@ -53,6 +53,6 @@ def get_litellm_gateway_api_key() -> Optional[str]: >>> ) """ token_data = load_cli_token() - if token_data and 'key' in token_data: - return token_data['key'] + if token_data and "key" in token_data: + return token_data["key"] return None diff --git a/litellm/litellm_core_utils/coroutine_checker.py b/litellm/litellm_core_utils/coroutine_checker.py index 368aee62ed0..bf065e5a153 100644 --- a/litellm/litellm_core_utils/coroutine_checker.py +++ b/litellm/litellm_core_utils/coroutine_checker.py @@ -10,14 +10,14 @@ from litellm.constants import ( class CoroutineChecker: """Utility class for checking coroutine status of functions and callables. - + Simple bounded cache using WeakKeyDictionary to avoid memory leaks. """ - + def __init__(self): self._cache = WeakKeyDictionary() self._max_size = COROUTINE_CHECKER_MAX_SIZE_IN_MEMORY - + def is_async_callable(self, callback: Any) -> bool: """Fast, cached check for whether a callback is an async function. Falls back gracefully if the object cannot be weak-referenced or cached. @@ -52,12 +52,13 @@ class CoroutineChecker: # Simple size enforcement: clear cache if it gets too large if len(self._cache) >= self._max_size: self._cache.clear() - + self._cache[callback] = result except Exception: pass return result + # Global instance for backward compatibility and convenience coroutine_checker = CoroutineChecker() diff --git a/litellm/litellm_core_utils/dot_notation_indexing.py b/litellm/litellm_core_utils/dot_notation_indexing.py index 1e835004e94..65810e83c66 100644 --- a/litellm/litellm_core_utils/dot_notation_indexing.py +++ b/litellm/litellm_core_utils/dot_notation_indexing.py @@ -107,7 +107,7 @@ def _parse_path_segments(path: str) -> list: # Match field names OR bracket expressions # Pattern: field_name (anything except . or [) | [anything_in_brackets] - pattern = r'[^\.\[]+|\[[^\]]*\]' + pattern = r"[^\.\[]+|\[[^\]]*\]" segments = re.findall(pattern, path) return segments @@ -158,7 +158,9 @@ def _delete_nested_value_custom( # Only recurse if element is a dict or list (nested structure) element = data[index] if isinstance(element, (dict, list)): - _delete_nested_value_custom(element, segments, segment_index + 1) + _delete_nested_value_custom( + element, segments, segment_index + 1 + ) except (ValueError, IndexError): # Invalid index, skip pass @@ -172,15 +174,23 @@ def _delete_nested_value_custom( else: # Navigate deeper if segment in data: - next_segment = segments[segment_index + 1] if segment_index + 1 < len(segments) else None + next_segment = ( + segments[segment_index + 1] + if segment_index + 1 < len(segments) + else None + ) # If next segment is array notation, current field should be list if next_segment and (next_segment.startswith("[")): if isinstance(data[segment], list): - _delete_nested_value_custom(data[segment], segments, segment_index + 1) + _delete_nested_value_custom( + data[segment], segments, segment_index + 1 + ) # Otherwise navigate into dict elif isinstance(data[segment], dict): - _delete_nested_value_custom(data[segment], segments, segment_index + 1) + _delete_nested_value_custom( + data[segment], segments, segment_index + 1 + ) def delete_nested_value( diff --git a/litellm/litellm_core_utils/duration_parser.py b/litellm/litellm_core_utils/duration_parser.py index 70c28c4e067..6d2b4226ff4 100644 --- a/litellm/litellm_core_utils/duration_parser.py +++ b/litellm/litellm_core_utils/duration_parser.py @@ -64,12 +64,10 @@ def duration_in_seconds(duration: str) -> int: now = time.time() current_time = datetime.fromtimestamp(now) - if current_time.month == 12: - target_year = current_time.year + 1 - target_month = 1 - else: - target_year = current_time.year - target_month = current_time.month + value + # Calculate target month and year, handling overflow past December + total_months = current_time.month - 1 + value # 0-indexed months + target_year = current_time.year + total_months // 12 + target_month = total_months % 12 + 1 # back to 1-indexed # Determine the day to set for next month target_day = current_time.day diff --git a/litellm/litellm_core_utils/exception_mapping_utils.py b/litellm/litellm_core_utils/exception_mapping_utils.py index 951485130b3..bc54786420a 100644 --- a/litellm/litellm_core_utils/exception_mapping_utils.py +++ b/litellm/litellm_core_utils/exception_mapping_utils.py @@ -73,7 +73,10 @@ class ExceptionCheckers: # Exclude param validation errors (e.g. OpenAI "user" param max 64 chars) if "string_above_max_length" in _error_str_lowercase: return False - if "invalid 'user'" in _error_str_lowercase and "string too long" in _error_str_lowercase: + if ( + "invalid 'user'" in _error_str_lowercase + and "string too long" in _error_str_lowercase + ): return False known_exception_substrings = [ "exceed context limit", @@ -97,7 +100,7 @@ class ExceptionCheckers: return True return False - + @staticmethod def is_azure_content_policy_violation_error(error_str: str) -> bool: """ @@ -443,7 +446,10 @@ def exception_type( # type: ignore # noqa: PLR0915 response=getattr(original_exception, "response", None), litellm_debug_info=extra_information, ) - elif "invalid_encrypted_content" in error_str or "could not be verified" in error_str: + elif ( + "invalid_encrypted_content" in error_str + or "could not be verified" in error_str + ): exception_mapping_worked = True helpful_message = ( f"{exception_provider} - {message}\n\n" @@ -2093,13 +2099,18 @@ def exception_type( # type: ignore # noqa: PLR0915 # content policy violation even when the top-level # code is generic (e.g. "invalid_request_error"). if azure_error_code != "content_policy_violation": - _inner = ( - body_dict["error"].get("inner_error") # type: ignore[index] - or body_dict["error"].get("innererror") # type: ignore[index] - ) - if isinstance(_inner, dict) and _inner.get( - "code" - ) == "ResponsibleAIPolicyViolation": + _inner = body_dict["error"].get( + "inner_error" + ) or body_dict[ # type: ignore[index] + "error" + ].get( + "innererror" + ) # type: ignore[index] + if ( + isinstance(_inner, dict) + and _inner.get("code") + == "ResponsibleAIPolicyViolation" + ): azure_error_code = "content_policy_violation" else: azure_error_code = body_dict.get("code") @@ -2135,19 +2146,25 @@ def exception_type( # type: ignore # noqa: PLR0915 ) elif ( azure_error_code == "content_policy_violation" - or ExceptionCheckers.is_azure_content_policy_violation_error(error_str) + or ExceptionCheckers.is_azure_content_policy_violation_error( + error_str + ) ): exception_mapping_worked = True from litellm.llms.azure.exception_mapping import ( AzureOpenAIExceptionMapping, ) + raise AzureOpenAIExceptionMapping.create_content_policy_violation_error( message=message, model=model, extra_information=extra_information, original_exception=original_exception, ) - elif azure_error_code == "invalid_encrypted_content" or "could not be verified" in error_str: + elif ( + azure_error_code == "invalid_encrypted_content" + or "could not be verified" in error_str + ): exception_mapping_worked = True helpful_message = ( f"AzureException - {message}\n\n" diff --git a/litellm/litellm_core_utils/fallback_utils.py b/litellm/litellm_core_utils/fallback_utils.py index aa5bdd92713..52eb35663bd 100644 --- a/litellm/litellm_core_utils/fallback_utils.py +++ b/litellm/litellm_core_utils/fallback_utils.py @@ -3,7 +3,10 @@ from typing import Optional import litellm from litellm._logging import verbose_logger -from litellm.litellm_core_utils.core_helpers import safe_deep_copy, filter_internal_params +from litellm.litellm_core_utils.core_helpers import ( + safe_deep_copy, + filter_internal_params, +) from .asyncify import run_async_function diff --git a/litellm/litellm_core_utils/get_blog_posts.py b/litellm/litellm_core_utils/get_blog_posts.py index 4f054c78ffe..f54deb59290 100644 --- a/litellm/litellm_core_utils/get_blog_posts.py +++ b/litellm/litellm_core_utils/get_blog_posts.py @@ -51,9 +51,7 @@ class GetBlogPosts: def load_local_blog_posts() -> List[Dict[str, str]]: """Load the bundled local backup blog posts.""" content = json.loads( - files("litellm") - .joinpath("blog_posts.json") - .read_text(encoding="utf-8") + files("litellm").joinpath("blog_posts.json").read_text(encoding="utf-8") ) return content.get("posts", []) diff --git a/litellm/litellm_core_utils/get_litellm_params.py b/litellm/litellm_core_utils/get_litellm_params.py index c91e4b6de1d..ad9538ac171 100644 --- a/litellm/litellm_core_utils/get_litellm_params.py +++ b/litellm/litellm_core_utils/get_litellm_params.py @@ -2,36 +2,38 @@ from typing import Optional # Pre-define optional kwargs keys as frozenset for O(1) lookups # These are extracted from kwargs only if present, avoiding unnecessary .get() calls -_OPTIONAL_KWARGS_KEYS = frozenset({ - "azure_ad_token", - "tenant_id", - "client_id", - "client_secret", - "azure_username", - "azure_password", - "azure_scope", - "timeout", - "bucket_name", - "vertex_credentials", - "vertex_project", - "vertex_location", - "vertex_ai_project", - "vertex_ai_location", - "vertex_ai_credentials", - "aws_region_name", - "aws_access_key_id", - "aws_secret_access_key", - "aws_session_token", - "aws_session_name", - "aws_profile_name", - "aws_role_name", - "aws_web_identity_token", - "aws_sts_endpoint", - "aws_external_id", - "aws_bedrock_runtime_endpoint", - "tpm", - "rpm", -}) +_OPTIONAL_KWARGS_KEYS = frozenset( + { + "azure_ad_token", + "tenant_id", + "client_id", + "client_secret", + "azure_username", + "azure_password", + "azure_scope", + "timeout", + "bucket_name", + "vertex_credentials", + "vertex_project", + "vertex_location", + "vertex_ai_project", + "vertex_ai_location", + "vertex_ai_credentials", + "aws_region_name", + "aws_access_key_id", + "aws_secret_access_key", + "aws_session_token", + "aws_session_name", + "aws_profile_name", + "aws_role_name", + "aws_web_identity_token", + "aws_sts_endpoint", + "aws_external_id", + "aws_bedrock_runtime_endpoint", + "tpm", + "rpm", + } +) def _get_base_model_from_litellm_call_metadata( diff --git a/litellm/litellm_core_utils/get_llm_provider_logic.py b/litellm/litellm_core_utils/get_llm_provider_logic.py index d1ee17fdd2e..36218417377 100644 --- a/litellm/litellm_core_utils/get_llm_provider_logic.py +++ b/litellm/litellm_core_utils/get_llm_provider_logic.py @@ -279,10 +279,16 @@ def get_llm_provider( # noqa: PLR0915 elif endpoint == "api.moonshot.ai/v1": custom_llm_provider = "moonshot" dynamic_api_key = get_secret_str("MOONSHOT_API_KEY") - elif endpoint == "api.minimax.io/anthropic" or endpoint == "api.minimaxi.com/anthropic": + elif ( + endpoint == "api.minimax.io/anthropic" + or endpoint == "api.minimaxi.com/anthropic" + ): custom_llm_provider = "minimax" dynamic_api_key = get_secret_str("MINIMAX_API_KEY") - elif endpoint == "api.minimax.io/v1" or endpoint == "api.minimaxi.com/v1": + elif ( + endpoint == "api.minimax.io/v1" + or endpoint == "api.minimaxi.com/v1" + ): custom_llm_provider = "minimax" dynamic_api_key = get_secret_str("MINIMAX_API_KEY") elif endpoint == "platform.publicai.co/v1": @@ -586,7 +592,11 @@ def _get_openai_compatible_provider_info( # noqa: PLR0915 if api_base is None: api_base = litellm.BasetenConfig.get_api_base_for_model(model) else: - api_base = api_base or get_secret_str("BASETEN_API_BASE") or "https://inference.baseten.co/v1" + api_base = ( + api_base + or get_secret_str("BASETEN_API_BASE") + or "https://inference.baseten.co/v1" + ) dynamic_api_key = api_key or get_secret_str("BASETEN_API_KEY") elif custom_llm_provider == "sambanova": api_base = ( @@ -611,9 +621,7 @@ def _get_openai_compatible_provider_info( # noqa: PLR0915 dynamic_api_key = api_key or get_secret_str("NEBIUS_API_KEY") elif custom_llm_provider == "ollama": api_base = ( - api_base - or get_secret("OLLAMA_API_BASE") - or "http://localhost:11434" + api_base or get_secret("OLLAMA_API_BASE") or "http://localhost:11434" ) # type: ignore dynamic_api_key = api_key or get_secret_str("OLLAMA_API_KEY") elif (custom_llm_provider == "ai21_chat") or ( @@ -927,17 +935,13 @@ def _get_openai_compatible_provider_info( # noqa: PLR0915 elif custom_llm_provider == "langgraph": # LangGraph is a custom provider, just need to set api_base api_base = ( - api_base - or get_secret_str("LANGGRAPH_API_BASE") - or "http://localhost:2024" + api_base or get_secret_str("LANGGRAPH_API_BASE") or "http://localhost:2024" ) dynamic_api_key = api_key or get_secret_str("LANGGRAPH_API_KEY") elif custom_llm_provider == "manus": # Manus is OpenAI compatible for responses API api_base = ( - api_base - or get_secret_str("MANUS_API_BASE") - or "https://api.manus.im" + api_base or get_secret_str("MANUS_API_BASE") or "https://api.manus.im" ) dynamic_api_key = api_key or get_secret_str("MANUS_API_KEY") diff --git a/litellm/litellm_core_utils/get_model_cost_map.py b/litellm/litellm_core_utils/get_model_cost_map.py index 5673064a238..7679358bbc6 100644 --- a/litellm/litellm_core_utils/get_model_cost_map.py +++ b/litellm/litellm_core_utils/get_model_cost_map.py @@ -92,7 +92,10 @@ class GetModelCostMap: ) return False - if backup_model_count > 0 and fetched_count < backup_model_count * max_shrink_ratio: + if ( + backup_model_count > 0 + and fetched_count < backup_model_count * max_shrink_ratio + ): verbose_logger.warning( "LiteLLM: Fetched model cost map shrank significantly " "(fetched=%d, backup=%d, threshold=%.0f%%). " @@ -286,7 +289,9 @@ def get_model_cost_map(url: str) -> dict: url, ) _cost_map_source_info.source = "local" - _cost_map_source_info.fallback_reason = "Remote data failed integrity validation" + _cost_map_source_info.fallback_reason = ( + "Remote data failed integrity validation" + ) return _expand_model_aliases(GetModelCostMap.load_local_model_cost_map()) _cost_map_source_info.source = "remote" diff --git a/litellm/litellm_core_utils/get_supported_openai_params.py b/litellm/litellm_core_utils/get_supported_openai_params.py index 07065aff322..b72d7abeae0 100644 --- a/litellm/litellm_core_utils/get_supported_openai_params.py +++ b/litellm/litellm_core_utils/get_supported_openai_params.py @@ -89,7 +89,9 @@ def get_supported_openai_params( # noqa: PLR0915 elif custom_llm_provider == "groq": return litellm.GroqChatConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "bedrock_mantle": - return litellm.BedrockMantleChatConfig().get_supported_openai_params(model=model) + return litellm.BedrockMantleChatConfig().get_supported_openai_params( + model=model + ) elif custom_llm_provider == "hosted_vllm": return litellm.HostedVLLMChatConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "vllm": @@ -120,9 +122,13 @@ def get_supported_openai_params( # noqa: PLR0915 return litellm.OpenAIConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "sap": if request_type == "chat_completion": - return litellm.GenAIHubOrchestrationConfig().get_supported_openai_params(model=model) + return litellm.GenAIHubOrchestrationConfig().get_supported_openai_params( + model=model + ) elif request_type == "embeddings": - return litellm.GenAIHubEmbeddingConfig().get_supported_openai_params(model=model) + return litellm.GenAIHubEmbeddingConfig().get_supported_openai_params( + model=model + ) elif custom_llm_provider == "azure": if litellm.AzureOpenAIO1Config().is_o_series_model(model=model): return litellm.AzureOpenAIO1Config().get_supported_openai_params( diff --git a/litellm/litellm_core_utils/json_validation_rule.py b/litellm/litellm_core_utils/json_validation_rule.py index 315a90fe300..bbfd3e6de96 100644 --- a/litellm/litellm_core_utils/json_validation_rule.py +++ b/litellm/litellm_core_utils/json_validation_rule.py @@ -4,93 +4,105 @@ from typing import Any, Dict, List, Union from litellm.constants import DEFAULT_MAX_RECURSE_DEPTH -def normalize_json_schema_types(schema: Union[Dict[str, Any], List[Any], Any], depth: int = 0, max_depth: int = DEFAULT_MAX_RECURSE_DEPTH) -> Union[Dict[str, Any], List[Any], Any]: +def normalize_json_schema_types( + schema: Union[Dict[str, Any], List[Any], Any], + depth: int = 0, + max_depth: int = DEFAULT_MAX_RECURSE_DEPTH, +) -> Union[Dict[str, Any], List[Any], Any]: """ Normalize JSON schema types from uppercase to lowercase format. - + Some providers (like certain Google services) use uppercase types like 'BOOLEAN', 'STRING', 'ARRAY', 'OBJECT' but standard JSON Schema requires lowercase: 'boolean', 'string', 'array', 'object' - + This function recursively normalizes all type fields in a schema to lowercase. - + Args: schema: The schema to normalize (dict, list, or other) depth: Current recursion depth max_depth: Maximum recursion depth to prevent infinite loops - + Returns: The normalized schema with lowercase types """ # Prevent infinite recursion if depth >= max_depth: return schema - + if not isinstance(schema, (dict, list)): return schema - + # Type mapping from uppercase to lowercase type_mapping = { - 'BOOLEAN': 'boolean', - 'STRING': 'string', - 'ARRAY': 'array', - 'OBJECT': 'object', - 'NUMBER': 'number', - 'INTEGER': 'integer', - 'NULL': 'null' + "BOOLEAN": "boolean", + "STRING": "string", + "ARRAY": "array", + "OBJECT": "object", + "NUMBER": "number", + "INTEGER": "integer", + "NULL": "null", } - + if isinstance(schema, list): - return [normalize_json_schema_types(item, depth + 1, max_depth) for item in schema] - + return [ + normalize_json_schema_types(item, depth + 1, max_depth) for item in schema + ] + if isinstance(schema, dict): normalized_schema: Dict[str, Any] = {} - + for key, value in schema.items(): - if key == 'type' and isinstance(value, str) and value in type_mapping: + if key == "type" and isinstance(value, str) and value in type_mapping: normalized_schema[key] = type_mapping[value] - elif key == 'properties' and isinstance(value, dict): + elif key == "properties" and isinstance(value, dict): # Recursively normalize properties normalized_schema[key] = { - prop_key: normalize_json_schema_types(prop_value, depth + 1, max_depth) + prop_key: normalize_json_schema_types( + prop_value, depth + 1, max_depth + ) for prop_key, prop_value in value.items() } - elif key == 'items' and isinstance(value, (dict, list)): + elif key == "items" and isinstance(value, (dict, list)): # Recursively normalize array items - normalized_schema[key] = normalize_json_schema_types(value, depth + 1, max_depth) + normalized_schema[key] = normalize_json_schema_types( + value, depth + 1, max_depth + ) elif isinstance(value, (dict, list)): # Recursively normalize any nested dict or list - normalized_schema[key] = normalize_json_schema_types(value, depth + 1, max_depth) + normalized_schema[key] = normalize_json_schema_types( + value, depth + 1, max_depth + ) else: normalized_schema[key] = value - + return normalized_schema - + return schema def normalize_tool_schema(tool: Dict[str, Any]) -> Dict[str, Any]: """ Normalize a tool's parameter schema to use standard JSON Schema lowercase types. - + Args: tool: The tool definition containing function parameters - + Returns: The tool with normalized schema types """ if not isinstance(tool, dict): return tool - + normalized_tool = tool.copy() - + # Normalize function parameters if present - if 'function' in tool and isinstance(tool['function'], dict): - normalized_tool['function'] = tool['function'].copy() - if 'parameters' in tool['function']: - normalized_tool['function']['parameters'] = normalize_json_schema_types( - tool['function']['parameters'] + if "function" in tool and isinstance(tool["function"], dict): + normalized_tool["function"] = tool["function"].copy() + if "parameters" in tool["function"]: + normalized_tool["function"]["parameters"] = normalize_json_schema_types( + tool["function"]["parameters"] ) - + return normalized_tool diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py index 6f587abcdf1..e22d057bb69 100644 --- a/litellm/litellm_core_utils/litellm_logging.py +++ b/litellm/litellm_core_utils/litellm_logging.py @@ -352,9 +352,9 @@ class Logging(LiteLLMLoggingBaseClass): ) self.function_id = function_id self.streaming_chunks: List[Any] = [] # for generating complete stream response - self.sync_streaming_chunks: List[Any] = ( - [] - ) # for generating complete stream response + self.sync_streaming_chunks: List[ + Any + ] = [] # for generating complete stream response self.log_raw_request_response = log_raw_request_response # Initialize dynamic callbacks @@ -746,9 +746,9 @@ class Logging(LiteLLMLoggingBaseClass): prompt_spec=prompt_spec, dynamic_callback_params=dynamic_callback_params, ): - self.model_call_details["prompt_integration"] = ( - logger.__class__.__name__ - ) + self.model_call_details[ + "prompt_integration" + ] = logger.__class__.__name__ return logger except Exception: # If check fails, continue to next logger @@ -816,9 +816,9 @@ class Logging(LiteLLMLoggingBaseClass): if anthropic_cache_control_logger := AnthropicCacheControlHook.get_custom_logger_for_anthropic_cache_control_hook( non_default_params ): - self.model_call_details["prompt_integration"] = ( - anthropic_cache_control_logger.__class__.__name__ - ) + self.model_call_details[ + "prompt_integration" + ] = anthropic_cache_control_logger.__class__.__name__ return anthropic_cache_control_logger ######################################################### @@ -830,9 +830,9 @@ class Logging(LiteLLMLoggingBaseClass): internal_usage_cache=None, llm_router=None, ) - self.model_call_details["prompt_integration"] = ( - vector_store_custom_logger.__class__.__name__ - ) + self.model_call_details[ + "prompt_integration" + ] = vector_store_custom_logger.__class__.__name__ # Add to global callbacks so post-call hooks are invoked if ( vector_store_custom_logger @@ -892,9 +892,9 @@ class Logging(LiteLLMLoggingBaseClass): model ): # if model name was changes pre-call, overwrite the initial model call name with the new one self.model_call_details["model"] = model - self.model_call_details["litellm_params"]["api_base"] = ( - self._get_masked_api_base(additional_args.get("api_base", "")) - ) + self.model_call_details["litellm_params"][ + "api_base" + ] = self._get_masked_api_base(additional_args.get("api_base", "")) def pre_call(self, input, api_key, model=None, additional_args={}): # noqa: PLR0915 # Log the exact input to the LLM API @@ -923,10 +923,10 @@ class Logging(LiteLLMLoggingBaseClass): try: # [Non-blocking Extra Debug Information in metadata] if turn_off_message_logging is True: - _metadata["raw_request"] = ( - "redacted by litellm. \ + _metadata[ + "raw_request" + ] = "redacted by litellm. \ 'litellm.turn_off_message_logging=True'" - ) else: curl_command = self._get_request_curl_command( api_base=additional_args.get("api_base", ""), @@ -937,34 +937,34 @@ class Logging(LiteLLMLoggingBaseClass): _metadata["raw_request"] = str(curl_command) # split up, so it's easier to parse in the UI - self.model_call_details["raw_request_typed_dict"] = ( - RawRequestTypedDict( - raw_request_api_base=str( - additional_args.get("api_base") or "" - ), - raw_request_body=self._get_raw_request_body( - additional_args.get("complete_input_dict", {}) - ), - # NOTE: setting ignore_sensitive_headers to True will cause - # the Authorization header to be leaked when calls to the health - # endpoint are made and fail. - raw_request_headers=self._get_masked_headers( - additional_args.get("headers", {}) or {}, - ), - error=None, - ) + self.model_call_details[ + "raw_request_typed_dict" + ] = RawRequestTypedDict( + raw_request_api_base=str( + additional_args.get("api_base") or "" + ), + raw_request_body=self._get_raw_request_body( + additional_args.get("complete_input_dict", {}) + ), + # NOTE: setting ignore_sensitive_headers to True will cause + # the Authorization header to be leaked when calls to the health + # endpoint are made and fail. + raw_request_headers=self._get_masked_headers( + additional_args.get("headers", {}) or {}, + ), + error=None, ) except Exception as e: - self.model_call_details["raw_request_typed_dict"] = ( - RawRequestTypedDict( - error=str(e), - ) + self.model_call_details[ + "raw_request_typed_dict" + ] = RawRequestTypedDict( + error=str(e), ) - _metadata["raw_request"] = ( - "Unable to Log \ + _metadata[ + "raw_request" + ] = "Unable to Log \ raw request: {}".format( - str(e) - ) + str(e) ) if getattr(self, "logger_fn", None) and callable(self.logger_fn): try: @@ -1265,13 +1265,13 @@ class Logging(LiteLLMLoggingBaseClass): for callback in callbacks: try: if isinstance(callback, CustomLogger): - response: Optional[MCPPostCallResponseObject] = ( - await callback.async_post_mcp_tool_call_hook( - kwargs=kwargs, - response_obj=post_mcp_tool_call_response_obj, - start_time=start_time, - end_time=end_time, - ) + response: Optional[ + MCPPostCallResponseObject + ] = await callback.async_post_mcp_tool_call_hook( + kwargs=kwargs, + response_obj=post_mcp_tool_call_response_obj, + start_time=start_time, + end_time=end_time, ) ###################################################################### # if any of the callbacks modify the response, use the modified response @@ -1466,9 +1466,9 @@ class Logging(LiteLLMLoggingBaseClass): verbose_logger.debug( f"response_cost_failure_debug_information: {debug_info}" ) - self.model_call_details["response_cost_failure_debug_information"] = ( - debug_info - ) + self.model_call_details[ + "response_cost_failure_debug_information" + ] = debug_info return None try: @@ -1494,9 +1494,9 @@ class Logging(LiteLLMLoggingBaseClass): verbose_logger.debug( f"response_cost_failure_debug_information: {debug_info}" ) - self.model_call_details["response_cost_failure_debug_information"] = ( - debug_info - ) + self.model_call_details[ + "response_cost_failure_debug_information" + ] = debug_info return None @@ -1652,9 +1652,9 @@ class Logging(LiteLLMLoggingBaseClass): result=logging_result ) - self.model_call_details["standard_logging_object"] = ( - self._build_standard_logging_payload(logging_result, start_time, end_time) - ) + self.model_call_details[ + "standard_logging_object" + ] = self._build_standard_logging_payload(logging_result, start_time, end_time) if ( standard_logging_payload := self.model_call_details.get( @@ -1732,9 +1732,9 @@ class Logging(LiteLLMLoggingBaseClass): end_time = datetime.datetime.now() if self.completion_start_time is None: self.completion_start_time = end_time - self.model_call_details["completion_start_time"] = ( - self.completion_start_time - ) + self.model_call_details[ + "completion_start_time" + ] = self.completion_start_time self.model_call_details["log_event_type"] = "successful_api_call" self.model_call_details["end_time"] = end_time @@ -1771,10 +1771,10 @@ class Logging(LiteLLMLoggingBaseClass): end_time=end_time, ) elif isinstance(result, dict) or isinstance(result, list): - self.model_call_details["standard_logging_object"] = ( - self._build_standard_logging_payload( - result, start_time, end_time - ) + self.model_call_details[ + "standard_logging_object" + ] = self._build_standard_logging_payload( + result, start_time, end_time ) if ( standard_logging_payload := self.model_call_details.get( @@ -1783,9 +1783,9 @@ class Logging(LiteLLMLoggingBaseClass): ) is not None: emit_standard_logging_payload(standard_logging_payload) elif standard_logging_object is not None: - self.model_call_details["standard_logging_object"] = ( - standard_logging_object - ) + self.model_call_details[ + "standard_logging_object" + ] = standard_logging_object else: self.model_call_details["response_cost"] = None @@ -1943,17 +1943,17 @@ class Logging(LiteLLMLoggingBaseClass): verbose_logger.debug( "Logging Details LiteLLM-Success Call streaming complete" ) - self.model_call_details["complete_streaming_response"] = ( - complete_streaming_response - ) - self.model_call_details["response_cost"] = ( - self._response_cost_calculator(result=complete_streaming_response) - ) + self.model_call_details[ + "complete_streaming_response" + ] = complete_streaming_response + self.model_call_details[ + "response_cost" + ] = self._response_cost_calculator(result=complete_streaming_response) ## STANDARDIZED LOGGING PAYLOAD - self.model_call_details["standard_logging_object"] = ( - self._build_standard_logging_payload( - complete_streaming_response, start_time, end_time - ) + self.model_call_details[ + "standard_logging_object" + ] = self._build_standard_logging_payload( + complete_streaming_response, start_time, end_time ) if ( standard_logging_payload := self.model_call_details.get( @@ -2287,10 +2287,10 @@ class Logging(LiteLLMLoggingBaseClass): ) else: if self.stream and complete_streaming_response: - self.model_call_details["complete_response"] = ( - self.model_call_details.get( - "complete_streaming_response", {} - ) + self.model_call_details[ + "complete_response" + ] = self.model_call_details.get( + "complete_streaming_response", {} ) result = self.model_call_details["complete_response"] openMeterLogger.log_success_event( @@ -2314,10 +2314,10 @@ class Logging(LiteLLMLoggingBaseClass): ) else: if self.stream and complete_streaming_response: - self.model_call_details["complete_response"] = ( - self.model_call_details.get( - "complete_streaming_response", {} - ) + self.model_call_details[ + "complete_response" + ] = self.model_call_details.get( + "complete_streaming_response", {} ) result = self.model_call_details["complete_response"] @@ -2456,9 +2456,9 @@ class Logging(LiteLLMLoggingBaseClass): if complete_streaming_response is not None: print_verbose("Async success callbacks: Got a complete streaming response") - self.model_call_details["async_complete_streaming_response"] = ( - complete_streaming_response - ) + self.model_call_details[ + "async_complete_streaming_response" + ] = complete_streaming_response try: if self.model_call_details.get("cache_hit", False) is True: @@ -2469,10 +2469,10 @@ class Logging(LiteLLMLoggingBaseClass): model_call_details=self.model_call_details ) # base_model defaults to None if not set on model_info - self.model_call_details["response_cost"] = ( - self._response_cost_calculator( - result=complete_streaming_response - ) + self.model_call_details[ + "response_cost" + ] = self._response_cost_calculator( + result=complete_streaming_response ) verbose_logger.debug( @@ -2485,10 +2485,10 @@ class Logging(LiteLLMLoggingBaseClass): self.model_call_details["response_cost"] = None ## STANDARDIZED LOGGING PAYLOAD - self.model_call_details["standard_logging_object"] = ( - self._build_standard_logging_payload( - complete_streaming_response, start_time, end_time - ) + self.model_call_details[ + "standard_logging_object" + ] = self._build_standard_logging_payload( + complete_streaming_response, start_time, end_time ) # print standard logging payload @@ -2515,9 +2515,9 @@ class Logging(LiteLLMLoggingBaseClass): # _success_handler_helper_fn if self.model_call_details.get("standard_logging_object") is None: ## STANDARDIZED LOGGING PAYLOAD - self.model_call_details["standard_logging_object"] = ( - self._build_standard_logging_payload(result, start_time, end_time) - ) + self.model_call_details[ + "standard_logging_object" + ] = self._build_standard_logging_payload(result, start_time, end_time) # print standard logging payload if ( @@ -2760,18 +2760,18 @@ class Logging(LiteLLMLoggingBaseClass): ## STANDARDIZED LOGGING PAYLOAD - self.model_call_details["standard_logging_object"] = ( - get_standard_logging_object_payload( - kwargs=self.model_call_details, - init_response_obj={}, - start_time=start_time, - end_time=end_time, - logging_obj=self, - status="failure", - error_str=str(exception), - original_exception=exception, - standard_built_in_tools_params=self.standard_built_in_tools_params, - ) + self.model_call_details[ + "standard_logging_object" + ] = get_standard_logging_object_payload( + kwargs=self.model_call_details, + init_response_obj={}, + start_time=start_time, + end_time=end_time, + logging_obj=self, + status="failure", + error_str=str(exception), + original_exception=exception, + standard_built_in_tools_params=self.standard_built_in_tools_params, ) return start_time, end_time @@ -3735,9 +3735,9 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915 service_name=arize_config.project_name, ) - os.environ["OTEL_EXPORTER_OTLP_TRACES_HEADERS"] = ( - f"space_id={arize_config.space_key or arize_config.space_id},api_key={arize_config.api_key}" - ) + os.environ[ + "OTEL_EXPORTER_OTLP_TRACES_HEADERS" + ] = f"space_id={arize_config.space_key or arize_config.space_id},api_key={arize_config.api_key}" for callback in _in_memory_loggers: if ( isinstance(callback, ArizeLogger) @@ -3763,13 +3763,13 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915 existing_attrs = os.environ.get("OTEL_RESOURCE_ATTRIBUTES", "") # Add openinference.project.name attribute if existing_attrs: - os.environ["OTEL_RESOURCE_ATTRIBUTES"] = ( - f"{existing_attrs},openinference.project.name={arize_phoenix_config.project_name}" - ) + os.environ[ + "OTEL_RESOURCE_ATTRIBUTES" + ] = f"{existing_attrs},openinference.project.name={arize_phoenix_config.project_name}" else: - os.environ["OTEL_RESOURCE_ATTRIBUTES"] = ( - f"openinference.project.name={arize_phoenix_config.project_name}" - ) + os.environ[ + "OTEL_RESOURCE_ATTRIBUTES" + ] = f"openinference.project.name={arize_phoenix_config.project_name}" # Set Phoenix project name from environment variable phoenix_project_name = os.environ.get("PHOENIX_PROJECT_NAME", None) @@ -3777,19 +3777,19 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915 existing_attrs = os.environ.get("OTEL_RESOURCE_ATTRIBUTES", "") # Add openinference.project.name attribute if existing_attrs: - os.environ["OTEL_RESOURCE_ATTRIBUTES"] = ( - f"{existing_attrs},openinference.project.name={phoenix_project_name}" - ) + os.environ[ + "OTEL_RESOURCE_ATTRIBUTES" + ] = f"{existing_attrs},openinference.project.name={phoenix_project_name}" else: - os.environ["OTEL_RESOURCE_ATTRIBUTES"] = ( - f"openinference.project.name={phoenix_project_name}" - ) + os.environ[ + "OTEL_RESOURCE_ATTRIBUTES" + ] = f"openinference.project.name={phoenix_project_name}" # auth can be disabled on local deployments of arize phoenix if arize_phoenix_config.otlp_auth_headers is not None: - os.environ["OTEL_EXPORTER_OTLP_TRACES_HEADERS"] = ( - arize_phoenix_config.otlp_auth_headers - ) + os.environ[ + "OTEL_EXPORTER_OTLP_TRACES_HEADERS" + ] = arize_phoenix_config.otlp_auth_headers for callback in _in_memory_loggers: if ( @@ -3965,9 +3965,9 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915 exporter="otlp_http", endpoint="https://langtrace.ai/api/trace", ) - os.environ["OTEL_EXPORTER_OTLP_TRACES_HEADERS"] = ( - f"api_key={os.getenv('LANGTRACE_API_KEY')}" - ) + os.environ[ + "OTEL_EXPORTER_OTLP_TRACES_HEADERS" + ] = f"api_key={os.getenv('LANGTRACE_API_KEY')}" for callback in _in_memory_loggers: if ( isinstance(callback, OpenTelemetry) @@ -4881,10 +4881,10 @@ class StandardLoggingPayloadSetup: for key in StandardLoggingHiddenParams.__annotations__.keys(): if key in hidden_params: if key == "additional_headers": - clean_hidden_params["additional_headers"] = ( - StandardLoggingPayloadSetup.get_additional_headers( - hidden_params[key] - ) + clean_hidden_params[ + "additional_headers" + ] = StandardLoggingPayloadSetup.get_additional_headers( + hidden_params[key] ) else: clean_hidden_params[key] = hidden_params[key] # type: ignore @@ -5036,7 +5036,6 @@ class StandardLoggingPayloadSetup: dynamic_litellm_session_id = litellm_params.get("litellm_session_id") dynamic_litellm_trace_id = litellm_params.get("litellm_trace_id") - # Note: we recommend using `litellm_session_id` for session tracking # `litellm_trace_id` is an internal litellm param if dynamic_litellm_session_id: @@ -5346,6 +5345,23 @@ def get_standard_logging_object_payload( model_name = reconstruct_model_name( kwargs.get("model", "") or "", custom_llm_provider, metadata ) + response_model_name: Optional[str] = None + if isinstance(final_response_obj, dict): + response_model_name = final_response_obj.get("model") + + # For Azure Model Router, preserve the actual model in the top-level standard + # logging payload only when the user has opted in. + requested_model = kwargs.get("model") + if ( + isinstance(requested_model, str) + and ( + "model_router" in requested_model.lower() + or "model-router" in requested_model.lower() + ) + and isinstance(response_model_name, str) + and response_model_name + ): + model_name = response_model_name payload: StandardLoggingPayload = StandardLoggingPayload( id=str(id), @@ -5507,9 +5523,9 @@ def scrub_sensitive_keys_in_metadata(litellm_params: Optional[dict]): ): for k, v in metadata["user_api_key_metadata"].items(): if k == "logging": # prevent logging user logging keys - cleaned_user_api_key_metadata[k] = ( - "scrubbed_by_litellm_for_sensitive_keys" - ) + cleaned_user_api_key_metadata[ + k + ] = "scrubbed_by_litellm_for_sensitive_keys" else: cleaned_user_api_key_metadata[k] = v diff --git a/litellm/litellm_core_utils/llm_cost_calc/tool_call_cost_tracking.py b/litellm/litellm_core_utils/llm_cost_calc/tool_call_cost_tracking.py index 4a4a2508d2e..4454fca3b00 100644 --- a/litellm/litellm_core_utils/llm_cost_calc/tool_call_cost_tracking.py +++ b/litellm/litellm_core_utils/llm_cost_calc/tool_call_cost_tracking.py @@ -233,9 +233,10 @@ class StandardBuiltInToolCostTracking: return 0.0 model_info_dict = dict(model_info) if model_info is not None else None - input_tokens, output_tokens = ( - StandardBuiltInToolCostTracking._extract_token_counts(computer_use_usage) - ) + ( + input_tokens, + output_tokens, + ) = StandardBuiltInToolCostTracking._extract_token_counts(computer_use_usage) return StandardBuiltInToolCostTracking.get_cost_for_computer_use( input_tokens=input_tokens, @@ -314,8 +315,10 @@ class StandardBuiltInToolCostTracking: if isinstance(response_object, ModelResponse): # chat completions only include url_citation annotations when a web search call is made - has_url_citations = StandardBuiltInToolCostTracking.response_includes_annotation_type( - response_object=response_object, annotation_type="url_citation" + has_url_citations = ( + StandardBuiltInToolCostTracking.response_includes_annotation_type( + response_object=response_object, annotation_type="url_citation" + ) ) if has_url_citations: return True @@ -325,7 +328,9 @@ class StandardBuiltInToolCostTracking: if ( hasattr(usage, "prompt_tokens_details") and usage.prompt_tokens_details is not None - and isinstance(usage.prompt_tokens_details, PromptTokensDetailsWrapper) + and isinstance( + usage.prompt_tokens_details, PromptTokensDetailsWrapper + ) and hasattr(usage.prompt_tokens_details, "web_search_requests") and usage.prompt_tokens_details.web_search_requests is not None ): @@ -468,7 +473,9 @@ class StandardBuiltInToolCostTracking: """ if model_info is None: return 0.0 - search_context_raw: Any = model_info.get("search_context_cost_per_query", {}) or {} + search_context_raw: Any = ( + model_info.get("search_context_cost_per_query", {}) or {} + ) search_context_pricing: SearchContextCostPerQuery = ( SearchContextCostPerQuery(**search_context_raw) if search_context_raw @@ -603,21 +610,26 @@ class StandardBuiltInToolCostTracking: Get code interpreter cost per session from model cost map. """ import litellm - + try: container_model = f"{provider}/container" model_info = litellm.get_model_info( - model=container_model, - custom_llm_provider=provider + model=container_model, custom_llm_provider=provider ) - model_key = model_info.get("key") if isinstance(model_info, dict) else getattr(model_info, "key", None) - + model_key = ( + model_info.get("key") + if isinstance(model_info, dict) + else getattr(model_info, "key", None) + ) + if model_key and model_key in litellm.model_cost: - return litellm.model_cost[model_key].get("code_interpreter_cost_per_session") - + return litellm.model_cost[model_key].get( + "code_interpreter_cost_per_session" + ) + except Exception: pass - + return None @staticmethod @@ -646,7 +658,6 @@ class StandardBuiltInToolCostTracking: ) if cost_per_session is not None: return sessions * cost_per_session - return 0.0 diff --git a/litellm/litellm_core_utils/llm_cost_calc/utils.py b/litellm/litellm_core_utils/llm_cost_calc/utils.py index bf0b2709365..191231f3e66 100644 --- a/litellm/litellm_core_utils/llm_cost_calc/utils.py +++ b/litellm/litellm_core_utils/llm_cost_calc/utils.py @@ -19,13 +19,15 @@ from litellm.types.utils import ( from litellm.utils import get_model_info # Pre-resolved CallTypes enum values for fast membership checks -_IMAGE_RESPONSE_CALL_TYPES = frozenset({ - CallTypes.image_generation.value, - CallTypes.aimage_generation.value, - PassthroughCallTypes.passthrough_image_generation.value, - CallTypes.image_edit.value, - CallTypes.aimage_edit.value, -}) +_IMAGE_RESPONSE_CALL_TYPES = frozenset( + { + CallTypes.image_generation.value, + CallTypes.aimage_generation.value, + PassthroughCallTypes.passthrough_image_generation.value, + CallTypes.image_edit.value, + CallTypes.aimage_edit.value, + } +) def _is_above_128k(tokens: float) -> bool: @@ -245,7 +247,10 @@ def _get_token_base_cost( else key ) prompt_base_cost = cast( - float, _get_cost_per_unit(model_info, tiered_input_key, prompt_base_cost) + float, + _get_cost_per_unit( + model_info, tiered_input_key, prompt_base_cost + ), ) tiered_output_key = ( _get_service_tier_cost_key( @@ -268,9 +273,7 @@ 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_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" ) @@ -576,7 +579,10 @@ def _calculate_input_cost( ) ### CACHE WRITING COST - Now uses tiered pricing - if prompt_tokens_details["cache_creation_tokens"] or prompt_tokens_details["cache_creation_token_details"] is not None: + if ( + prompt_tokens_details["cache_creation_tokens"] + or prompt_tokens_details["cache_creation_token_details"] is not None + ): prompt_cost += calculate_cache_writing_cost( cache_creation_tokens=prompt_tokens_details["cache_creation_tokens"], cache_creation_token_details=prompt_tokens_details[ @@ -589,7 +595,9 @@ def _calculate_input_cost( ### CHARACTER COST if prompt_tokens_details["character_count"]: prompt_cost += calculate_cost_component( - model_info, "input_cost_per_character", prompt_tokens_details["character_count"] + model_info, + "input_cost_per_character", + prompt_tokens_details["character_count"], ) ### IMAGE COUNT COST @@ -661,10 +669,14 @@ def generic_cost_per_token( # noqa: PLR0915 image_tokens = prompt_tokens_details["image_tokens"] # Check for double-counting: sum of details > prompt_tokens means overlap - total_details = text_tokens + cache_hit + audio_tokens + cache_creation + image_tokens + total_details = ( + text_tokens + cache_hit + audio_tokens + cache_creation + image_tokens + ) has_double_counting = cache_hit > 0 and total_details > usage.prompt_tokens - if (text_tokens == 0 and prompt_tokens_details["image_count"] == 0) or has_double_counting: + if ( + text_tokens == 0 and prompt_tokens_details["image_count"] == 0 + ) or has_double_counting: text_tokens = ( usage.prompt_tokens - cache_hit diff --git a/litellm/litellm_core_utils/llm_request_utils.py b/litellm/litellm_core_utils/llm_request_utils.py index 89f5728979f..a2292d6e00f 100644 --- a/litellm/litellm_core_utils/llm_request_utils.py +++ b/litellm/litellm_core_utils/llm_request_utils.py @@ -67,6 +67,7 @@ def pick_cheapest_chat_models_from_llm_provider(custom_llm_provider: str, n=1): # Return the top n cheapest models return [model for model, _ in model_costs[:n]] + def get_proxy_server_request_headers(litellm_params: Optional[dict]) -> dict: """ Get the `proxy_server_request` headers from the litellm_params.\ @@ -80,4 +81,4 @@ def get_proxy_server_request_headers(litellm_params: Optional[dict]) -> dict: litellm_params.get("proxy_server_request", {}).get("headers", {}) or {} ) - return proxy_request_headers \ No newline at end of file + return proxy_request_headers diff --git a/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py b/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py index 4bc9f0c835a..20cc5746667 100644 --- a/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py +++ b/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py @@ -471,7 +471,7 @@ def convert_to_model_response_object( # noqa: PLR0915 if hidden_params is None: hidden_params = {} - + # Preserve existing additional_headers if they contain important provider headers # For responses API, additional_headers may already be set with LLM provider headers existing_additional_headers = hidden_params.get("additional_headers", {}) @@ -482,7 +482,7 @@ def convert_to_model_response_object( # noqa: PLR0915 # Merge new headers with existing ones if existing_additional_headers: additional_headers.update(existing_additional_headers) - + hidden_params["additional_headers"] = additional_headers ### CHECK IF ERROR IN RESPONSE ### - openrouter returns these in the dictionary @@ -596,9 +596,9 @@ def convert_to_model_response_object( # noqa: PLR0915 provider_specific_fields["thinking_blocks"] = thinking_blocks if reasoning_content: - provider_specific_fields["reasoning_content"] = ( - reasoning_content - ) + provider_specific_fields[ + "reasoning_content" + ] = reasoning_content message = Message( content=content, @@ -654,7 +654,9 @@ def convert_to_model_response_object( # noqa: PLR0915 if "id" in response_object: # Preserve the auto-generated id from ModelResponse.__init__ # when the provider returns a falsy id (None, "") - model_response_object.id = response_object["id"] or model_response_object.id + model_response_object.id = ( + response_object["id"] or model_response_object.id + ) if "system_fingerprint" in response_object: model_response_object.system_fingerprint = response_object[ @@ -785,7 +787,9 @@ def convert_to_model_response_object( # noqa: PLR0915 # tracking without exposing it in the response body. Must be set # after hidden_params assignment to avoid being overwritten. if "_audio_transcription_duration" in response_object: - model_response_object._hidden_params["audio_transcription_duration"] = response_object["_audio_transcription_duration"] + model_response_object._hidden_params[ + "audio_transcription_duration" + ] = response_object["_audio_transcription_duration"] if _response_headers is not None: model_response_object._response_headers = _response_headers diff --git a/litellm/litellm_core_utils/logging_callback_manager.py b/litellm/litellm_core_utils/logging_callback_manager.py index 38da11e777a..c5c150274cc 100644 --- a/litellm/litellm_core_utils/logging_callback_manager.py +++ b/litellm/litellm_core_utils/logging_callback_manager.py @@ -150,11 +150,11 @@ class LoggingCallbackManager: 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 diff --git a/litellm/litellm_core_utils/logging_worker.py b/litellm/litellm_core_utils/logging_worker.py index d5eca9eeb55..7f00c47c1ff 100644 --- a/litellm/litellm_core_utils/logging_worker.py +++ b/litellm/litellm_core_utils/logging_worker.py @@ -417,26 +417,30 @@ class LoggingWorker: """ # Check if logger has valid handlers before attempting to log # During shutdown, handlers may be closed, causing ValueError when writing - if not hasattr(verbose_logger, 'handlers') or not verbose_logger.handlers: + if not hasattr(verbose_logger, "handlers") or not verbose_logger.handlers: return - + # Check if any handler has a valid stream has_valid_handler = False for handler in verbose_logger.handlers: try: - if hasattr(handler, 'stream') and handler.stream and not handler.stream.closed: + if ( + hasattr(handler, "stream") + and handler.stream + and not handler.stream.closed + ): has_valid_handler = True break - elif not hasattr(handler, 'stream'): + elif not hasattr(handler, "stream"): # Non-stream handlers (like NullHandler) are always valid has_valid_handler = True break except (AttributeError, ValueError): continue - + if not has_valid_handler: return - + try: if level == "debug": verbose_logger.debug(message) diff --git a/litellm/litellm_core_utils/model_param_helper.py b/litellm/litellm_core_utils/model_param_helper.py index 4d45c47c224..66b174feac4 100644 --- a/litellm/litellm_core_utils/model_param_helper.py +++ b/litellm/litellm_core_utils/model_param_helper.py @@ -93,9 +93,9 @@ class ModelParamHelper: streaming_params: Set[str] = set( getattr(CompletionCreateParamsStreaming, "__annotations__", {}).keys() ) - litellm_provider_specific_params: Set[str] = ( - ModelParamHelper.get_litellm_provider_specific_params_for_chat_params() - ) + litellm_provider_specific_params: Set[ + str + ] = ModelParamHelper.get_litellm_provider_specific_params_for_chat_params() all_chat_completion_kwargs: Set[str] = non_streaming_params.union( streaming_params ).union(litellm_provider_specific_params) diff --git a/litellm/litellm_core_utils/model_response_utils.py b/litellm/litellm_core_utils/model_response_utils.py index 00462221fe3..6c290fa30c0 100644 --- a/litellm/litellm_core_utils/model_response_utils.py +++ b/litellm/litellm_core_utils/model_response_utils.py @@ -114,23 +114,19 @@ def _is_choice_non_empty(choice: Any) -> bool: """ # Check finish_reason if hasattr(choice, "finish_reason") and choice.finish_reason is not None: - return True # Check logprobs if hasattr(choice, "logprobs") and choice.logprobs is not None: - return True # Check enhancements (if present) if hasattr(choice, "enhancements") and choice.enhancements is not None: - return True # Deep check delta object if hasattr(choice, "delta") and choice.delta is not None: if _is_delta_non_empty(choice.delta): - return True # Check model_extra for dynamically added fields on the choice @@ -138,19 +134,15 @@ def _is_choice_non_empty(choice: Any) -> bool: for extra_field_name, extra_field_value in choice.model_extra.items(): # Skip certain structural fields that are just default/None placeholders if extra_field_name == "index" and extra_field_value == 0: - continue if ( extra_field_name in {"finish_reason", "logprobs"} and extra_field_value is None ): - continue if extra_field_name == "delta": - continue if _has_meaningful_content(extra_field_value): - return True # Check for any other non-standard fields on the choice @@ -169,12 +161,10 @@ def _is_choice_non_empty(choice: Any) -> bool: "enhancements", } ): - continue attr_value = getattr(choice, attr_name, None) if _has_meaningful_content(attr_value): - return True return False @@ -195,7 +185,6 @@ def _is_delta_non_empty(delta: Delta) -> bool: for extra_field_name, extra_field_value in delta.model_extra.items(): # Even structural fields are meaningful if they have actual content if _has_meaningful_content(extra_field_value): - return True # Check all regular attributes of the delta object @@ -210,7 +199,6 @@ def _is_delta_non_empty(delta: Delta) -> bool: attr_value = getattr(delta, attr_name, None) if _has_meaningful_content(attr_value): - return True return False diff --git a/litellm/litellm_core_utils/prompt_templates/common_utils.py b/litellm/litellm_core_utils/prompt_templates/common_utils.py index d59b8d88714..a5d6bc936bb 100644 --- a/litellm/litellm_core_utils/prompt_templates/common_utils.py +++ b/litellm/litellm_core_utils/prompt_templates/common_utils.py @@ -644,6 +644,10 @@ def extract_file_data(file_data: FileTypes) -> ExtractedFileData: content = f.read() elif isinstance(file_content, io.IOBase): # If it's a file-like object + # Try to get filename from file handle if not already set + if not filename and hasattr(file_content, "name"): + filename = Path(file_content.name).name + content = file_content.read() if isinstance(content, str): diff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.py index 610e3a368ed..ea1f81f9b36 100644 --- a/litellm/litellm_core_utils/prompt_templates/factory.py +++ b/litellm/litellm_core_utils/prompt_templates/factory.py @@ -1037,8 +1037,7 @@ def convert_to_anthropic_tool_invoke_xml(tool_calls: list) -> str: ) if isinstance(parsed_args, dict): parameters = "".join( - f"<{param}>{val}\n" - for param, val in parsed_args.items() + f"<{param}>{val}\n" for param, val in parsed_args.items() ) else: parameters = f"{parsed_args}\n" @@ -1394,10 +1393,10 @@ def convert_to_gemini_tool_call_invoke( if tool_calls is not None: for idx, tool in enumerate(tool_calls): if "function" in tool: - gemini_function_call: Optional[VertexFunctionCall] = ( - _gemini_tool_call_invoke_helper( - function_call_params=tool["function"] - ) + gemini_function_call: Optional[ + VertexFunctionCall + ] = _gemini_tool_call_invoke_helper( + function_call_params=tool["function"] ) if gemini_function_call is not None: part_dict: VertexPartType = { @@ -1705,7 +1704,9 @@ def convert_to_anthropic_tool_result( anthropic_content_element=_anthropic_image_param, original_content_element=content, ) - anthropic_content_list.append(cast(AnthropicMessagesImageParam, _anthropic_image_param)) + anthropic_content_list.append( + cast(AnthropicMessagesImageParam, _anthropic_image_param) + ) anthropic_content = anthropic_content_list anthropic_tool_result: Optional[AnthropicMessagesToolResultParam] = None @@ -2036,7 +2037,7 @@ def _sanitize_empty_text_content( """ Case C: Sanitize empty text content - Replace empty or whitespace-only text content with a placeholder message. - + Returns: The message with sanitized content if needed, otherwise the original message """ @@ -2045,14 +2046,16 @@ def _sanitize_empty_text_content( if isinstance(content, str): if not content or not content.strip(): message = cast(AllMessageValues, dict(message)) # Make a copy - message["content"] = "[System: Empty message content sanitised to satisfy protocol]" + message[ + "content" + ] = "[System: Empty message content sanitised to satisfy protocol]" verbose_logger.debug( f"_sanitize_empty_text_content: Replaced empty text content in {message.get('role')} message" ) return message -def _add_missing_tool_results( # noqa: PLR0915 +def _add_missing_tool_results( # noqa: PLR0915 current_message: AllMessageValues, messages: List[AllMessageValues], current_index: int, @@ -2084,40 +2087,40 @@ def _add_missing_tool_results( # noqa: PLR0915 tool_call_id = getattr(tool_call, "id", None) if tool_call_id: expected_tool_call_ids.add(tool_call_id) - + # Collect actual tool result messages that follow this assistant message found_tool_call_ids = set() actual_tool_results: List[AllMessageValues] = [] j = current_index + 1 - + while j < len(messages): next_msg = messages[j] next_role = next_msg.get("role") - + if next_role == "assistant": break - + if next_role in ["tool", "function"]: tool_call_id = next_msg.get("tool_call_id") if tool_call_id and tool_call_id in expected_tool_call_ids: found_tool_call_ids.add(tool_call_id) actual_tool_results.append(next_msg) - + j += 1 - + # Find missing tool results missing_tool_call_ids = expected_tool_call_ids - found_tool_call_ids - + if missing_tool_call_ids: verbose_logger.debug( f"_add_missing_tool_results: Found {len(missing_tool_call_ids)} orphaned tool calls. Adding dummy tool results." ) - + result_messages.append(current_message) - + # Add existing tool results FIRST result_messages.extend(actual_tool_results) - + # Then add dummy tool results for missing ones for tool_call_id in missing_tool_call_ids: tool_name = "unknown_tool" @@ -2127,7 +2130,7 @@ def _add_missing_tool_results( # noqa: PLR0915 tc_id = tool_call.get("id") else: tc_id = getattr(tool_call, "id", None) - + if tc_id == tool_call_id: if isinstance(tool_call, dict): function = tool_call.get("function", {}) @@ -2140,17 +2143,17 @@ def _add_missing_tool_results( # noqa: PLR0915 if function: tool_name = getattr(function, "name", "unknown_tool") break - + dummy_tool_result: ChatCompletionToolMessage = { "role": "tool", "tool_call_id": tool_call_id, "content": f"[System: Tool execution skipped/interrupted by user. No result provided for tool '{tool_name}'.]", } result_messages.append(dummy_tool_result) - + # Return the messages and the number of original messages to skip return (result_messages, len(actual_tool_results)) - + return ([current_message], 0) @@ -2162,21 +2165,21 @@ def _is_orphaned_tool_result( Case B: Orphaned tool_result (unexpected result) - Check if a tool message references a tool_call_id that doesn't exist in the previous assistant message. - + Returns: True if this is an orphaned tool result that should be removed, False otherwise """ if current_message.get("role") not in ["tool", "function"]: return False - + tool_call_id = current_message.get("tool_call_id") - + if not tool_call_id: return False - + # Look back to find the most recent assistant message with tool_calls found_matching_tool_call = False - + for j in range(len(sanitized_messages) - 1, -1, -1): prev_msg = sanitized_messages[j] if prev_msg.get("role") == "assistant": @@ -2188,19 +2191,19 @@ def _is_orphaned_tool_result( tc_id = tool_call.get("id") else: tc_id = getattr(tool_call, "id", None) - + if tc_id == tool_call_id: found_matching_tool_call = True break - + break - + if not found_matching_tool_call: verbose_logger.debug( "_is_orphaned_tool_result: Found orphaned tool result with redacted tool_call_id" ) return True - + return False @@ -2209,58 +2212,60 @@ def sanitize_messages_for_tool_calling( ) -> List[AllMessageValues]: """ Sanitize messages for tool calling to handle common issues when modify_params=True: - + Case A: Missing tool_result for tool_use (orphaned tool calls) - If an assistant message has tool_calls but no corresponding tool result follows, add a dummy tool result message indicating the user did not provide the result. - + Case B: Orphaned tool_result (unexpected result) - If a tool message references a tool_call_id that doesn't exist in the previous assistant message, remove that tool message. - + Case C: Empty text content - Replace empty or whitespace-only text content with a placeholder message. - + Case D: Duplicate tool_result for same tool_use (duplicate results) - If multiple tool messages reference the same tool_call_id, keep only the last occurrence. Anthropic requires exactly one tool_result per tool_use and rejects with: "each tool_use must have a single result". - + This function operates on OpenAI format messages before they are converted to provider-specific formats. """ if not litellm.modify_params: return messages - + sanitized_messages: List[AllMessageValues] = [] i = 0 - + while i < len(messages): current_message = messages[i] - + # Case C: Sanitize empty text content current_message = _sanitize_empty_text_content(current_message) - + # Case A: Check if assistant message has tool_calls without following tool results if current_message.get("role") == "assistant": - result_messages, messages_consumed = _add_missing_tool_results(current_message, messages, i) - + result_messages, messages_consumed = _add_missing_tool_results( + current_message, messages, i + ) + # If dummy tool results were added, extend sanitized_messages and skip consumed messages if len(result_messages) > 1: sanitized_messages.extend(result_messages) # Skip the assistant message and any actual tool results that were included i += 1 + messages_consumed continue - + # Case B: Check for orphaned tool results if _is_orphaned_tool_result(current_message, sanitized_messages): i += 1 continue # Skip this orphaned tool result - + # Add the message to sanitized list sanitized_messages.append(current_message) i += 1 - + # Case D: Deduplicate tool results with the same tool_call_id. # Anthropic requires exactly one tool_result per tool_use. Session history # (e.g. from conversation resume) can contain duplicate tool_result messages @@ -2278,7 +2283,7 @@ def sanitize_messages_for_tool_calling( for idx, msg in enumerate(sanitized_messages): role = msg.get("role") tcid = msg.get("tool_call_id") if role in ["tool", "function"] else None - if tcid: + if tcid and isinstance(tcid, str): if tcid in seen_in_block: # Mark the earlier occurrence for removal (keep latest) duplicates_to_remove.add(seen_in_block[tcid]) @@ -2328,7 +2333,7 @@ def anthropic_messages_pt( # noqa: PLR0915 """ # Sanitize messages for tool calling issues when modify_params=True messages = sanitize_messages_for_tool_calling(messages) - + # add role=tool support to allow function call result/error submission user_message_types = {"user", "tool", "function"} # reformat messages to ensure user/assistant are alternating, if there's either 2 consecutive 'user' messages or 2 consecutive 'assistant' message, merge them. @@ -2383,9 +2388,9 @@ def anthropic_messages_pt( # noqa: PLR0915 # Convert ChatCompletionImageUrlObject to dict if needed image_url_value = m["image_url"] if isinstance(image_url_value, str): - image_url_input: Union[str, dict[str, Any]] = ( - image_url_value - ) + image_url_input: Union[ + str, dict[str, Any] + ] = image_url_value else: # ChatCompletionImageUrlObject or dict case - convert to dict image_url_input = { @@ -2412,9 +2417,9 @@ def anthropic_messages_pt( # noqa: PLR0915 ) if "cache_control" in _content_element: - _anthropic_content_element["cache_control"] = ( - _content_element["cache_control"] - ) + _anthropic_content_element[ + "cache_control" + ] = _content_element["cache_control"] user_content.append(_anthropic_content_element) elif m.get("type", "") == "text": m = cast(ChatCompletionTextObject, m) @@ -2452,9 +2457,9 @@ def anthropic_messages_pt( # noqa: PLR0915 ) if "cache_control" in _content_element: - _anthropic_content_text_element["cache_control"] = ( - _content_element["cache_control"] - ) + _anthropic_content_text_element[ + "cache_control" + ] = _content_element["cache_control"] user_content.append(_anthropic_content_text_element) @@ -2487,7 +2492,9 @@ def anthropic_messages_pt( # noqa: PLR0915 "provider_specific_fields" ) if isinstance(_provider_specific_fields_raw, dict): - _compaction_blocks = _provider_specific_fields_raw.get("compaction_blocks") + _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 @@ -2507,7 +2514,11 @@ def anthropic_messages_pt( # noqa: PLR0915 if isinstance(_tc, dict) else getattr(_tc, "id", None) ) - if _tc_id and isinstance(_tc_id, str) and _tc_id.startswith("srvtoolu_"): + if ( + _tc_id + and isinstance(_tc_id, str) + and _tc_id.startswith("srvtoolu_") + ): _has_server_tool_calls = True break @@ -2570,22 +2581,20 @@ def anthropic_messages_pt( # noqa: PLR0915 # Build the text block if content is a non-empty string text_element = None - if ( - isinstance(assistant_content_block.get("content"), str) - and assistant_content_block["content"] - ): + _acb_content = assistant_content_block.get("content") + if isinstance(_acb_content, str) and _acb_content: _anthropic_text_content_element = AnthropicMessagesTextParam( type="text", - text=assistant_content_block["content"], + text=_acb_content, ) _content_element = add_cache_control_to_content( anthropic_content_element=_anthropic_text_content_element, original_content_element=dict(assistant_content_block), ) if "cache_control" in _content_element: - _anthropic_text_content_element["cache_control"] = ( - _content_element["cache_control"] - ) + _anthropic_text_content_element[ + "cache_control" + ] = _content_element["cache_control"] text_element = _anthropic_text_content_element # Interleave: each thinking block precedes its server tool group. @@ -2671,20 +2680,25 @@ def anthropic_messages_pt( # noqa: PLR0915 _content_is_list = "content" in assistant_content_block and isinstance( assistant_content_block["content"], list ) + _content_list = assistant_content_block.get("content") if _content_is_list else None _list_has_thinking = False - if _content_is_list: - for _item in assistant_content_block["content"]: - if isinstance(_item, dict) and _item.get("type") in ("thinking", "redacted_thinking"): + if _content_is_list and _content_list is not None: + for _item in _content_list: + if isinstance(_item, dict) and _item.get("type") in ( + "thinking", + "redacted_thinking", + ): _list_has_thinking = True break if ( - thinking_blocks is not None - and not _list_has_thinking + thinking_blocks is not None and not _list_has_thinking ): # IMPORTANT: ADD THIS FIRST, ELSE ANTHROPIC WILL RAISE AN ERROR assistant_content.extend(thinking_blocks) - if _content_is_list: - for m in assistant_content_block["content"]: + if _content_is_list and _content_list is not None: + for m in _content_list: + if not isinstance(m, dict): + continue # handle thinking blocks thinking_block = cast(str, m.get("thinking", "")) text_block = cast(str, m.get("text", "")) @@ -2738,9 +2752,9 @@ def anthropic_messages_pt( # noqa: PLR0915 ) if "cache_control" in _content_element: - _anthropic_text_content_element["cache_control"] = _content_element[ + _anthropic_text_content_element[ "cache_control" - ] + ] = _content_element["cache_control"] assistant_content.append(_anthropic_text_content_element) @@ -3795,16 +3809,12 @@ def _convert_to_bedrock_tool_call_invoke( # '{"cmd":"a"}{"cmd":"b"}{"cmd":"c"}' # Split them and emit one toolUse block per object. # Fixes: https://github.com/BerriAI/litellm/issues/20543 - parsed_objects = split_concatenated_json_objects( - arguments - ) + parsed_objects = split_concatenated_json_objects(arguments) if parsed_objects: # First object keeps the original tool id. for obj_idx, obj in enumerate(parsed_objects): block_id = ( - tool_id - if obj_idx == 0 - else f"{tool_id}_{obj_idx}" + tool_id if obj_idx == 0 else f"{tool_id}_{obj_idx}" ) bedrock_tool = BedrockToolUseBlock( input=obj, name=name, toolUseId=block_id @@ -3817,9 +3827,7 @@ def _convert_to_bedrock_tool_call_invoke( if tool.get("cache_control", None) is not None: _parts_list.append( BedrockContentBlock( - cachePoint=CachePointBlock( - type="default" - ) + cachePoint=CachePointBlock(type="default") ) ) continue @@ -4572,7 +4580,9 @@ class BedrockConverseMessagesProcessor: msg_i += 1 - assistant_content = _deduplicate_bedrock_content_blocks(assistant_content, "toolUse") + assistant_content = _deduplicate_bedrock_content_blocks( + assistant_content, "toolUse" + ) if assistant_content: contents.append( @@ -4888,7 +4898,9 @@ def _bedrock_converse_messages_pt( # noqa: PLR0915 # 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_part = BedrockContentBlock( + text=element["text"] + ) assistants_parts.append(assistants_part) elif element["type"] == "image_url": if isinstance(element["image_url"], dict): @@ -4914,7 +4926,9 @@ def _bedrock_converse_messages_pt( # noqa: PLR0915 elif _assistant_content is not None and isinstance(_assistant_content, str): # Skip completely empty strings to avoid blank content blocks if _assistant_content.strip(): - assistant_content.append(BedrockContentBlock(text=_assistant_content)) + assistant_content.append( + BedrockContentBlock(text=_assistant_content) + ) # Add cache point block for assistant string content _cache_point_block = ( litellm.AmazonConverseConfig()._get_cache_point_block( @@ -4931,7 +4945,9 @@ def _bedrock_converse_messages_pt( # noqa: PLR0915 msg_i += 1 - assistant_content = _deduplicate_bedrock_content_blocks(assistant_content, "toolUse") + assistant_content = _deduplicate_bedrock_content_blocks( + assistant_content, "toolUse" + ) if assistant_content: contents.append( @@ -4995,18 +5011,18 @@ def add_cache_point_tool_block(tool: dict) -> Optional[BedrockToolBlock]: def _is_bedrock_tool_block(tool: dict) -> bool: """ Check if a tool is already a BedrockToolBlock. - + BedrockToolBlock has one of: systemTool, toolSpec, or cachePoint. This is used to detect tools that are already in Bedrock format (e.g., systemTool for Nova grounding) vs OpenAI-style function tools that need transformation. - + Args: tool: The tool dict to check - + Returns: True if the tool is already a BedrockToolBlock, False otherwise - + Examples: >>> _is_bedrock_tool_block({"systemTool": {"name": "nova_grounding"}}) True diff --git a/litellm/litellm_core_utils/prompt_templates/huggingface_template_handler.py b/litellm/litellm_core_utils/prompt_templates/huggingface_template_handler.py index 9305d5bbfc1..fc8a0d28583 100644 --- a/litellm/litellm_core_utils/prompt_templates/huggingface_template_handler.py +++ b/litellm/litellm_core_utils/prompt_templates/huggingface_template_handler.py @@ -12,7 +12,7 @@ from litellm.types.llms.custom_http import httpxSpecialProvider def strftime_now(fmt: str) -> str: """ Custom function for templates that need current date/time formatting (e.g., gpt-oss) - + Args: fmt: Format string for datetime.now().strftime() @@ -25,10 +25,10 @@ def strftime_now(fmt: str) -> str: def _get_tokenizer_config(hf_model_name: str) -> Dict[str, Any]: """ Fetch tokenizer_config.json from HuggingFace (sync) - + Args: hf_model_name: HuggingFace model name (e.g., 'openai/gpt-oss-120b') - + Returns: Dict with 'status' and optionally 'tokenizer' keys """ @@ -48,10 +48,10 @@ def _get_tokenizer_config(hf_model_name: str) -> Dict[str, Any]: async def _aget_tokenizer_config(hf_model_name: str) -> Dict[str, Any]: """ Fetch tokenizer_config.json from HuggingFace (async) - + Args: hf_model_name: HuggingFace model name (e.g., 'openai/gpt-oss-120b') - + Returns: Dict with 'status' and optionally 'tokenizer' keys """ @@ -73,35 +73,38 @@ async def _aget_tokenizer_config(hf_model_name: str) -> Dict[str, Any]: def _get_chat_template_file(hf_model_name: str) -> Dict[str, Any]: """ Fetch chat template from separate .jinja file (sync) - + Args: hf_model_name: HuggingFace model name (e.g., 'openai/gpt-oss-120b') - + Returns: Dict with 'status' and optionally 'chat_template' keys """ template_filenames = ["chat_template.jinja", "chat_template.jinja2"] client = _get_httpx_client() - + for filename in template_filenames: try: url = f"https://huggingface.co/{hf_model_name}/raw/main/{filename}" response = client.get(url=url) if response.status_code == 200: - return {"status": "success", "chat_template": response.content.decode("utf-8")} + return { + "status": "success", + "chat_template": response.content.decode("utf-8"), + } except Exception: continue - + return {"status": "failure"} async def _aget_chat_template_file(hf_model_name: str) -> Dict[str, Any]: """ Fetch chat template from separate .jinja file (async) - + Args: hf_model_name: HuggingFace model name (e.g., 'openai/gpt-oss-120b') - + Returns: Dict with 'status' and optionally 'chat_template' keys """ @@ -109,26 +112,29 @@ async def _aget_chat_template_file(hf_model_name: str) -> Dict[str, Any]: client = get_async_httpx_client( llm_provider=httpxSpecialProvider.PromptFactory, ) - + for filename in template_filenames: try: url = f"https://huggingface.co/{hf_model_name}/raw/main/{filename}" response = await client.get(url=url) if response.status_code == 200: - return {"status": "success", "chat_template": response.content.decode("utf-8")} + return { + "status": "success", + "chat_template": response.content.decode("utf-8"), + } except Exception: continue - + return {"status": "failure"} def _extract_token_value(token_value: Union[None, str, Dict[str, Any]]) -> str: """ Extract token string from various formats (string, dict, etc.) - + Args: token_value: Token value in various formats (None, str, or dict with 'content' key) - + Returns: Extracted token string """ @@ -136,4 +142,4 @@ def _extract_token_value(token_value: Union[None, str, Dict[str, Any]]) -> str: return token_value or "" if isinstance(token_value, dict): return token_value.get("content", "") - return "" \ No newline at end of file + return "" diff --git a/litellm/litellm_core_utils/prompt_templates/image_handling.py b/litellm/litellm_core_utils/prompt_templates/image_handling.py index 7137a4e4222..eaf78b7bcf5 100644 --- a/litellm/litellm_core_utils/prompt_templates/image_handling.py +++ b/litellm/litellm_core_utils/prompt_templates/image_handling.py @@ -35,7 +35,7 @@ def _process_image_response(response: Response, url: str) -> str: max_bytes = int(MAX_IMAGE_URL_DOWNLOAD_SIZE_MB * 1024 * 1024) image_bytes = bytearray() bytes_downloaded = 0 - + for chunk in response.iter_bytes(chunk_size=8192): bytes_downloaded += len(chunk) if bytes_downloaded > max_bytes: @@ -44,7 +44,7 @@ def _process_image_response(response: Response, url: str) -> str: f"Error: Image size ({size_mb:.2f}MB) exceeds maximum allowed size ({MAX_IMAGE_URL_DOWNLOAD_SIZE_MB}MB). url={url}" ) image_bytes.extend(chunk) - + base64_image = base64.b64encode(image_bytes).decode("utf-8") image_type = response.headers.get("Content-Type") diff --git a/litellm/litellm_core_utils/realtime_streaming.py b/litellm/litellm_core_utils/realtime_streaming.py index 14a25e61d63..37233680714 100644 --- a/litellm/litellm_core_utils/realtime_streaming.py +++ b/litellm/litellm_core_utils/realtime_streaming.py @@ -111,9 +111,7 @@ class RealTimeStreaming: if self._should_store_message(message_obj): self.messages.append(message_obj) - def _collect_user_input_from_client_event( - self, message: Union[str, dict] - ) -> None: + def _collect_user_input_from_client_event(self, message: Union[str, dict]) -> None: """Extract user text content from client WebSocket events for spend logging.""" try: if isinstance(message, str): @@ -158,15 +156,10 @@ class RealTimeStreaming: """Extract user voice transcription from backend events for spend logging.""" try: event_type = event_obj.get("type", "") - if ( - event_type - == "conversation.item.input_audio_transcription.completed" - ): + if event_type == "conversation.item.input_audio_transcription.completed": transcript = cast(str, event_obj.get("transcript", "")) if transcript: - self.input_messages.append( - {"role": "user", "content": transcript} - ) + self.input_messages.append({"role": "user", "content": transcript}) except (AttributeError, TypeError): pass @@ -204,9 +197,7 @@ class RealTimeStreaming: """Log messages in list""" if self.logging_obj: if self.input_messages: - self.logging_obj.model_call_details["messages"] = ( - self.input_messages - ) + self.logging_obj.model_call_details["messages"] = self.input_messages if self.session_tools or self.tool_calls: self.logging_obj.model_call_details[ "realtime_tools" @@ -313,10 +304,13 @@ class RealTimeStreaming: except Exception as e: # Re-raise unexpected errors (no status_code/detail = programming bug, not a block). # HTTPException and guardrail-raised exceptions have a status_code or detail attr. - is_guardrail_block = hasattr(e, "status_code") or isinstance(e, ValueError) + is_guardrail_block = hasattr(e, "status_code") or isinstance( + e, ValueError + ) if not is_guardrail_block: verbose_logger.exception( - "[realtime guardrail] unexpected error in apply_guardrail: %s", e + "[realtime guardrail] unexpected error in apply_guardrail: %s", + e, ) raise # Extract the human-readable error from the detail dict (HTTPException) @@ -327,23 +321,30 @@ class RealTimeStreaming: elif detail is not None: safe_msg = str(detail) else: - safe_msg = str(e) or "I'm sorry, that request was blocked by the content filter." + safe_msg = ( + str(e) + or "I'm sorry, that request was blocked by the content filter." + ) # Use realtime_violation_message if configured; fall back to guardrail error text. - error_msg = getattr(callback, "realtime_violation_message", None) or safe_msg + error_msg = ( + getattr(callback, "realtime_violation_message", None) or safe_msg + ) # Cancel any in-progress LLM response (e.g. VAD auto-response). await self._send_to_backend(json.dumps({"type": "response.cancel"})) # Send the policy violation hint (shows as small gray status text in UI). await self.websocket.send_text( - json.dumps({ - "type": "error", - "error": { - "type": "guardrail_violation", - "message": error_msg, - "code": "content_policy_violation", - }, - }) + json.dumps( + { + "type": "error", + "error": { + "type": "guardrail_violation", + "message": error_msg, + "code": "content_policy_violation", + }, + } + ) ) # Ask the LLM to voice the exact guardrail message so the # user hears it as audio in voice sessions (not just text). @@ -351,23 +352,29 @@ class RealTimeStreaming: f"Say exactly the following message to the user, word for word, " f"do not add anything else: {error_msg}" ) - await self._send_to_backend(json.dumps({ - "type": "conversation.item.create", - "item": { - "type": "message", - "role": "user", - "content": [{"type": "input_text", "text": guardrail_prompt}], - }, - })) await self._send_to_backend( - json.dumps({"type": "response.create"}) + json.dumps( + { + "type": "conversation.item.create", + "item": { + "type": "message", + "role": "user", + "content": [ + {"type": "input_text", "text": guardrail_prompt} + ], + }, + } + ) ) + await self._send_to_backend(json.dumps({"type": "response.create"})) self._violation_count += 1 end_session_after: Optional[int] = getattr( callback, "end_session_after_n_fails", None ) - should_end = getattr(callback, "on_violation", None) == "end_session" or ( + should_end = getattr( + callback, "on_violation", None + ) == "end_session" or ( end_session_after is not None and self._violation_count >= end_session_after ) @@ -410,7 +417,9 @@ class RealTimeStreaming: self.current_conversation_id = returned_object["current_conversation_id"] self.current_item_chunks = returned_object["current_item_chunks"] self.current_delta_type = returned_object["current_delta_type"] - self.session_configuration_request = returned_object["session_configuration_request"] + self.session_configuration_request = returned_object[ + "session_configuration_request" + ] events = ( transformed_response if isinstance(transformed_response, list) @@ -446,12 +455,11 @@ class RealTimeStreaming: self.store_message(event_str) await self.websocket.send_text(event_str) blocked = await self.run_realtime_guardrails( - cast(str, transcript), item_id=cast(Optional[str], event.get("item_id")) + cast(str, transcript), + item_id=cast(Optional[str], event.get("item_id")), ) if not blocked: - await self._send_to_backend( - json.dumps({"type": "response.create"}) - ) + await self._send_to_backend(json.dumps({"type": "response.create"})) continue ## LOGGING self.store_message(event_str) @@ -502,9 +510,7 @@ class RealTimeStreaming: ) if not blocked: # Clean — trigger LLM response - await self._send_to_backend( - json.dumps({"type": "response.create"}) - ) + await self._send_to_backend(json.dumps({"type": "response.create"})) return True except (json.JSONDecodeError, AttributeError): pass @@ -579,7 +585,10 @@ class RealTimeStreaming: self._pending_guardrail_message = combined_text continue # don't forward the original blocked message - if msg_type == "response.create" and self._pending_guardrail_message: + if ( + msg_type == "response.create" + and self._pending_guardrail_message + ): # The guardrail already sent the synthetic AI bubble — drop this # response.create so OpenAI doesn't generate an additional response. self._pending_guardrail_message = None diff --git a/litellm/litellm_core_utils/redact_messages.py b/litellm/litellm_core_utils/redact_messages.py index ad68f3851a8..dbeb4111077 100644 --- a/litellm/litellm_core_utils/redact_messages.py +++ b/litellm/litellm_core_utils/redact_messages.py @@ -64,15 +64,64 @@ def _redact_responses_api_output(output_items): for content_part in output_item.content: if hasattr(content_part, "text"): content_part.text = "redacted-by-litellm" - + # Redact reasoning items in output array if hasattr(output_item, "type") and output_item.type == "reasoning": - if hasattr(output_item, "summary") and isinstance(output_item.summary, list): + if hasattr(output_item, "summary") and isinstance( + output_item.summary, list + ): for summary_item in output_item.summary: if hasattr(summary_item, "text"): summary_item.text = "redacted-by-litellm" +def _redact_standard_logging_object(model_call_details: dict): + """Redact messages and response inside standard_logging_object if present.""" + standard_logging_object = model_call_details.get("standard_logging_object") + if standard_logging_object is None: + return + + redacted_str = "redacted-by-litellm" + + if standard_logging_object.get("messages") is not None: + standard_logging_object["messages"] = [ + {"role": "user", "content": redacted_str} + ] + + response = standard_logging_object.get("response") + if response is not None: + if isinstance(response, dict) and "output" in response: + # ResponsesAPIResponse format - redact content in output items + if isinstance(response.get("output"), list): + for output_item in response["output"]: + if isinstance(output_item, dict) and "content" in output_item: + if isinstance(output_item["content"], list): + for content_item in output_item["content"]: + if ( + isinstance(content_item, dict) + and "text" in content_item + ): + content_item["text"] = redacted_str + elif isinstance(response, dict) and "choices" in response: + # ModelResponse dict format - redact content in choices + if isinstance(response.get("choices"), list): + for choice in response["choices"]: + if isinstance(choice, dict): + if "message" in choice and isinstance(choice["message"], dict): + choice["message"]["content"] = redacted_str + if "audio" in choice["message"]: + choice["message"]["audio"] = None + elif "delta" in choice and isinstance(choice["delta"], dict): + choice["delta"]["content"] = redacted_str + if "audio" in choice["delta"]: + choice["delta"]["audio"] = None + elif isinstance(response, str): + standard_logging_object["response"] = redacted_str + else: + # For other formats (empty dict, None, etc.), use simple text format + standard_logging_object["response"] = {"text": redacted_str} + + def perform_redaction(model_call_details: dict, result): """ Performs the actual redaction on the logging object and result. @@ -96,24 +145,56 @@ def perform_redaction(model_call_details: dict, result): elif hasattr(_streaming_response, "output"): _redact_responses_api_output(_streaming_response.output) # Redact reasoning field in ResponsesAPIResponse - if hasattr(_streaming_response, "reasoning") and _streaming_response.reasoning is not None: + if ( + hasattr(_streaming_response, "reasoning") + and _streaming_response.reasoning is not None + ): _streaming_response.reasoning = None # Redact result if result is not None: # Check if result is a coroutine, async generator, or other async object - these cannot be deepcopied - if (asyncio.iscoroutine(result) or - inspect.iscoroutinefunction(result) or - hasattr(result, '__aiter__') or # async generator - hasattr(result, '__anext__')): # async iterator + if ( + asyncio.iscoroutine(result) + or inspect.iscoroutinefunction(result) + or hasattr(result, "__aiter__") + or hasattr(result, "__anext__") # async generator + ): # async iterator # For async objects, return a simple redacted response without deepcopy return {"text": "redacted-by-litellm"} - + _result = copy.deepcopy(result) if isinstance(_result, litellm.ModelResponse): if hasattr(_result, "choices") and _result.choices is not None: for choice in _result.choices: _redact_choice_content(choice) + elif isinstance(_result, dict) and "choices" in _result: + # Handle dict representation of ModelResponse (e.g., from model_dump()) + if _result.get("choices") is not None: + for choice in _result["choices"]: + if isinstance(choice, dict): + if "message" in choice and isinstance(choice["message"], dict): + choice["message"]["content"] = "redacted-by-litellm" + if "reasoning_content" in choice["message"]: + choice["message"][ + "reasoning_content" + ] = "redacted-by-litellm" + if "thinking_blocks" in choice["message"]: + choice["message"]["thinking_blocks"] = None + if "audio" in choice["message"]: + choice["message"]["audio"] = None + elif "delta" in choice and isinstance(choice["delta"], dict): + choice["delta"]["content"] = "redacted-by-litellm" + if "reasoning_content" in choice["delta"]: + choice["delta"][ + "reasoning_content" + ] = "redacted-by-litellm" + if "thinking_blocks" in choice["delta"]: + choice["delta"]["thinking_blocks"] = None + if "audio" in choice["delta"]: + choice["delta"]["audio"] = None + else: + _redact_choice_content(choice) elif isinstance(_result, litellm.ResponsesAPIResponse): if hasattr(_result, "output"): _redact_responses_api_output(_result.output) @@ -131,14 +212,14 @@ 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", {}) - + metadata_field = get_metadata_variable_name_from_kwargs(litellm_params) metadata = litellm_params.get(metadata_field, {}) if not isinstance(metadata, dict): @@ -169,15 +250,17 @@ def should_redact_message_logging(model_call_details: dict) -> bool: break # Priority 1: Check dynamic parameter first (if explicitly set) - dynamic_turn_off = _get_turn_off_message_logging_from_dynamic_params(model_call_details) + 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 @@ -202,9 +285,9 @@ def _get_turn_off_message_logging_from_dynamic_params( handles boolean and string values of `turn_off_message_logging` """ - standard_callback_dynamic_params: Optional[StandardCallbackDynamicParams] = ( - model_call_details.get("standard_callback_dynamic_params", None) - ) + standard_callback_dynamic_params: Optional[ + StandardCallbackDynamicParams + ] = model_call_details.get("standard_callback_dynamic_params", None) if standard_callback_dynamic_params: _turn_off_message_logging = standard_callback_dynamic_params.get( "turn_off_message_logging" diff --git a/litellm/litellm_core_utils/safe_json_loads.py b/litellm/litellm_core_utils/safe_json_loads.py index a7ab0d3e3b5..bb4b72cfd97 100644 --- a/litellm/litellm_core_utils/safe_json_loads.py +++ b/litellm/litellm_core_utils/safe_json_loads.py @@ -4,6 +4,7 @@ Helper for safe JSON loading in LiteLLM. from typing import Any import json + def safe_json_loads(data: str, default: Any = None) -> Any: """ Safely parse a JSON string. If parsing fails, return the default value (None by default). @@ -11,4 +12,4 @@ def safe_json_loads(data: str, default: Any = None) -> Any: try: return json.loads(data) except Exception: - return default \ No newline at end of file + return default diff --git a/litellm/litellm_core_utils/sensitive_data_masker.py b/litellm/litellm_core_utils/sensitive_data_masker.py index 3ec34e6d9ef..663c3fac801 100644 --- a/litellm/litellm_core_utils/sensitive_data_masker.py +++ b/litellm/litellm_core_utils/sensitive_data_masker.py @@ -98,7 +98,9 @@ class SensitiveDataMasker: masked_items.append(self._mask_value(item)) else: masked_items.append( - item if isinstance(item, (int, float, bool, str, list)) else str(item) + item + if isinstance(item, (int, float, bool, str, list)) + else str(item) ) return masked_items diff --git a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py index ba35a2c7cad..1935372e5df 100644 --- a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py +++ b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py @@ -54,13 +54,16 @@ class ChunkProcessor: first_hidden_params = candidate if first_hidden_params.get("created_at"): + def _created_at(chunk: Any) -> Union[int, float]: if isinstance(chunk, dict): params = chunk.get("_hidden_params", {}) else: params = getattr(chunk, "_hidden_params", {}) if isinstance(params, dict): - return cast(Union[int, float], params.get("created_at", float("inf"))) + return cast( + Union[int, float], params.get("created_at", float("inf")) + ) return float("inf") return sorted(chunks, key=_created_at) @@ -88,7 +91,9 @@ class ChunkProcessor: return "" @staticmethod - def _get_model_from_chunks(chunks: List[Dict[str, Any]], first_chunk_model: str) -> str: + def _get_model_from_chunks( + chunks: List[Dict[str, Any]], first_chunk_model: str + ) -> str: """ Get the actual model from chunks, preferring a model that differs from the first chunk. @@ -151,13 +156,13 @@ class ChunkProcessor: ) return response - def get_combined_tool_content( # noqa: PLR0915 + def get_combined_tool_content( # noqa: PLR0915 self, tool_call_chunks: List[Dict[str, Any]] ) -> List[ChatCompletionMessageToolCall]: tool_calls_list: List[ChatCompletionMessageToolCall] = [] - tool_call_map: Dict[int, Dict[str, Any]] = ( - {} - ) # Map to store tool calls by index + tool_call_map: Dict[ + int, Dict[str, Any] + ] = {} # Map to store tool calls by index for chunk in tool_call_chunks: choices = chunk["choices"] @@ -169,14 +174,20 @@ class ChunkProcessor: # Handle both dict and object formats if not tool_call: continue - + # Check if tool_call has function (either as attribute or dict key) has_function = False if isinstance(tool_call, dict): - has_function = "function" in tool_call and tool_call["function"] is not None + has_function = ( + "function" in tool_call + and tool_call["function"] is not None + ) else: - has_function = hasattr(tool_call, "function") and tool_call.function is not None - + has_function = ( + hasattr(tool_call, "function") + and tool_call.function is not None + ) + if not has_function: continue @@ -185,7 +196,7 @@ class ChunkProcessor: index = tool_call.get("index", 0) else: index = getattr(tool_call, "index", 0) - + if index not in tool_call_map: tool_call_map[index] = { "id": None, @@ -201,19 +212,23 @@ class ChunkProcessor: tool_call_map[index]["id"] = tool_call["id"] if tool_call.get("type"): tool_call_map[index]["type"] = tool_call["type"] - + function = tool_call.get("function", {}) if isinstance(function, dict): if function.get("name"): tool_call_map[index]["name"] = function["name"] if function.get("arguments"): - tool_call_map[index]["arguments"].append(function["arguments"]) + tool_call_map[index]["arguments"].append( + function["arguments"] + ) else: # function is an object if hasattr(function, "name") and function.name: tool_call_map[index]["name"] = function.name if hasattr(function, "arguments") and function.arguments: - tool_call_map[index]["arguments"].append(function.arguments) + tool_call_map[index]["arguments"].append( + function.arguments + ) else: # tool_call is an object if hasattr(tool_call, "id") and tool_call.id: @@ -233,19 +248,32 @@ class ChunkProcessor: tool_call_map[index]["arguments"].append( tool_call.function.arguments ) - + # Preserve provider_specific_fields from streaming chunks provider_fields = None if isinstance(tool_call, dict): provider_fields = tool_call.get("provider_specific_fields") - if not provider_fields and isinstance(tool_call.get("function"), dict): - provider_fields = tool_call["function"].get("provider_specific_fields") + if not provider_fields and isinstance( + tool_call.get("function"), dict + ): + provider_fields = tool_call["function"].get( + "provider_specific_fields" + ) else: - if hasattr(tool_call, "provider_specific_fields") and tool_call.provider_specific_fields: + if ( + hasattr(tool_call, "provider_specific_fields") + and tool_call.provider_specific_fields + ): provider_fields = tool_call.provider_specific_fields - elif hasattr(tool_call, "function") and hasattr(tool_call.function, "provider_specific_fields") and tool_call.function.provider_specific_fields: - provider_fields = tool_call.function.provider_specific_fields - + elif ( + hasattr(tool_call, "function") + and hasattr(tool_call.function, "provider_specific_fields") + and tool_call.function.provider_specific_fields + ): + provider_fields = ( + tool_call.function.provider_specific_fields + ) + if provider_fields: # Merge provider_specific_fields if multiple chunks have them if tool_call_map[index]["provider_specific_fields"] is None: @@ -260,30 +288,31 @@ class ChunkProcessor: tool_call_data = tool_call_map[index] if tool_call_data["id"] and tool_call_data["name"]: combined_arguments = "".join(tool_call_data["arguments"]) or "{}" - + # Build function - provider_specific_fields should be on tool_call level, not function level function = Function( arguments=combined_arguments, name=tool_call_data["name"], ) - + # Prepare params for ChatCompletionMessageToolCall tool_call_params = { "id": tool_call_data["id"], "function": function, "type": tool_call_data["type"] or "function", } - + # Add provider_specific_fields if present (for thought signatures in Gemini 3) if tool_call_data.get("provider_specific_fields"): - tool_call_params["provider_specific_fields"] = tool_call_data["provider_specific_fields"] - + tool_call_params["provider_specific_fields"] = tool_call_data[ + "provider_specific_fields" + ] + tool_call = ChatCompletionMessageToolCall(**tool_call_params) tool_calls_list.append(tool_call) return tool_calls_list - def get_combined_function_call_content( self, function_call_chunks: List[Dict[str, Any]] ) -> FunctionCall: @@ -506,7 +535,7 @@ class ChunkProcessor: ## anthropic prompt caching information ## cache_creation_input_tokens: Optional[int] = None cache_read_input_tokens: Optional[int] = None - + server_tool_use: Optional[ServerToolUse] = None web_search_requests: Optional[int] = None completion_tokens_details: Optional[CompletionTokensDetails] = None @@ -551,7 +580,10 @@ class ChunkProcessor: completion_tokens_details = usage_chunk_dict[ "completion_tokens_details" ] - if hasattr(usage_chunk, 'server_tool_use') and usage_chunk.server_tool_use is not None: + if ( + hasattr(usage_chunk, "server_tool_use") + and usage_chunk.server_tool_use is not None + ): server_tool_use = usage_chunk.server_tool_use if ( usage_chunk_dict["prompt_tokens_details"] is not None @@ -611,12 +643,12 @@ class ChunkProcessor: web_search_requests: Optional[int] = calculated_usage_per_chunk[ "web_search_requests" ] - completion_tokens_details: Optional[CompletionTokensDetails] = ( - calculated_usage_per_chunk["completion_tokens_details"] - ) - prompt_tokens_details: Optional[PromptTokensDetailsWrapper] = ( - calculated_usage_per_chunk["prompt_tokens_details"] - ) + completion_tokens_details: Optional[ + CompletionTokensDetails + ] = calculated_usage_per_chunk["completion_tokens_details"] + prompt_tokens_details: Optional[ + PromptTokensDetailsWrapper + ] = calculated_usage_per_chunk["prompt_tokens_details"] try: returned_usage.prompt_tokens = prompt_tokens or token_counter( @@ -650,8 +682,10 @@ class ChunkProcessor: ) # for anthropic if completion_tokens_details is not None: if isinstance(completion_tokens_details, CompletionTokensDetails): - returned_usage.completion_tokens_details = CompletionTokensDetailsWrapper( - **completion_tokens_details.model_dump() + returned_usage.completion_tokens_details = ( + CompletionTokensDetailsWrapper( + **completion_tokens_details.model_dump() + ) ) else: returned_usage.completion_tokens_details = completion_tokens_details diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.py index 317f1037686..db2369d03d6 100644 --- a/litellm/litellm_core_utils/streaming_handler.py +++ b/litellm/litellm_core_utils/streaming_handler.py @@ -485,7 +485,6 @@ class CustomStreamWrapper: def handle_openai_chat_completion_chunk(self, chunk): try: - str_line = chunk text = "" is_finished = False @@ -535,7 +534,6 @@ class CustomStreamWrapper: def handle_azure_text_completion_chunk(self, chunk): try: - text = "" is_finished = False finish_reason = None @@ -556,7 +554,6 @@ class CustomStreamWrapper: def handle_openai_text_completion_chunk(self, chunk): try: - text = "" is_finished = False finish_reason = None @@ -1100,8 +1097,7 @@ class CustomStreamWrapper: ): if self.received_finish_reason is not None: _chunk_has_content = isinstance(chunk, dict) and ( - bool(chunk.get("text", "")) - or chunk.get("tool_use") is not None + bool(chunk.get("text", "")) or chunk.get("tool_use") is not None ) if not _chunk_has_content and ( not isinstance(chunk, dict) @@ -1356,7 +1352,10 @@ class CustomStreamWrapper: if response_obj["is_finished"]: self.received_finish_reason = response_obj["finish_reason"] else: # openai / azure chat model - if self.custom_llm_provider in [LlmProviders.AZURE.value, LlmProviders.AZURE_AI.value]: + if self.custom_llm_provider in [ + LlmProviders.AZURE.value, + LlmProviders.AZURE_AI.value, + ]: if isinstance(chunk, BaseModel) and hasattr(chunk, "model"): # for azure, we need to pass the model from the original chunk self.model = getattr(chunk, "model", self.model) @@ -1612,10 +1611,12 @@ class CustomStreamWrapper: ) return chunk - def _add_mcp_list_tools_to_first_chunk(self, chunk: ModelResponseStream) -> ModelResponseStream: + def _add_mcp_list_tools_to_first_chunk( + self, chunk: ModelResponseStream + ) -> ModelResponseStream: """ Add mcp_list_tools from _hidden_params to the first chunk's delta.provider_specific_fields. - + This method checks if MCP metadata with mcp_list_tools is stored in _hidden_params and adds it to the first chunk's delta.provider_specific_fields. """ @@ -1623,43 +1624,53 @@ class CustomStreamWrapper: # Check if MCP metadata should be added to first chunk if not hasattr(self, "_hidden_params") or not self._hidden_params: return chunk - + mcp_metadata = self._hidden_params.get("mcp_metadata") if not mcp_metadata or not isinstance(mcp_metadata, dict): return chunk - + # Only add mcp_list_tools to first chunk (not tool_calls or tool_results) mcp_list_tools = mcp_metadata.get("mcp_list_tools") if not mcp_list_tools: return chunk - + # Add mcp_list_tools to delta.provider_specific_fields if hasattr(chunk, "choices") and chunk.choices: for choice in chunk.choices: - if isinstance(choice, StreamingChoices) and hasattr(choice, "delta") and choice.delta: + if ( + isinstance(choice, StreamingChoices) + and hasattr(choice, "delta") + and choice.delta + ): # Get existing provider_specific_fields or create new dict provider_fields = ( - getattr(choice.delta, "provider_specific_fields", None) or {} + getattr(choice.delta, "provider_specific_fields", None) + or {} ) - + # Add only mcp_list_tools to first chunk provider_fields["mcp_list_tools"] = mcp_list_tools - + # Set the provider_specific_fields - setattr(choice.delta, "provider_specific_fields", provider_fields) - + setattr( + choice.delta, "provider_specific_fields", provider_fields + ) + except Exception as e: from litellm._logging import verbose_logger + verbose_logger.exception( f"Error adding MCP list tools to first chunk: {str(e)}" ) - + return chunk - def _add_mcp_metadata_to_final_chunk(self, chunk: ModelResponseStream) -> ModelResponseStream: + def _add_mcp_metadata_to_final_chunk( + self, chunk: ModelResponseStream + ) -> ModelResponseStream: """ Add MCP metadata from _hidden_params to the final chunk's delta.provider_specific_fields. - + This method checks if MCP metadata is stored in _hidden_params and adds it to the chunk's delta.provider_specific_fields, similar to how RAG adds search results. """ @@ -1667,33 +1678,41 @@ class CustomStreamWrapper: # Check if MCP metadata should be added to final chunk if not hasattr(self, "_hidden_params") or not self._hidden_params: return chunk - + mcp_metadata = self._hidden_params.get("mcp_metadata") if not mcp_metadata: return chunk - + # Add MCP metadata to delta.provider_specific_fields if hasattr(chunk, "choices") and chunk.choices: for choice in chunk.choices: - if isinstance(choice, StreamingChoices) and hasattr(choice, "delta") and choice.delta: + if ( + isinstance(choice, StreamingChoices) + and hasattr(choice, "delta") + and choice.delta + ): # Get existing provider_specific_fields or create new dict provider_fields = ( - getattr(choice.delta, "provider_specific_fields", None) or {} + getattr(choice.delta, "provider_specific_fields", None) + or {} ) - + # Add MCP metadata if isinstance(mcp_metadata, dict): provider_fields.update(mcp_metadata) - + # Set the provider_specific_fields - setattr(choice.delta, "provider_specific_fields", provider_fields) - + setattr( + choice.delta, "provider_specific_fields", provider_fields + ) + except Exception as e: from litellm._logging import verbose_logger + verbose_logger.exception( f"Error adding MCP metadata to final chunk: {str(e)}" ) - + return chunk def cache_streaming_response(self, processed_chunk, cache_hit: bool): @@ -1813,12 +1832,12 @@ class CustomStreamWrapper: ) # HANDLE STREAM OPTIONS self.chunks.append(response) - + # Add mcp_list_tools to first chunk if present if not self.sent_first_chunk: response = self._add_mcp_list_tools_to_first_chunk(response) self.sent_first_chunk = True - + if hasattr( response, "usage" ): # remove usage from chunk, only send on final chunk @@ -1898,9 +1917,7 @@ class CustomStreamWrapper: and complete_streaming_response is not None and self._last_returned_hidden_params is not None ): - final_usage = getattr( - complete_streaming_response, "usage", None - ) + final_usage = getattr(complete_streaming_response, "usage", None) if final_usage is not None: self._last_returned_hidden_params["usage"] = final_usage @@ -1991,7 +2008,9 @@ class CustomStreamWrapper: ) # Add mcp_list_tools to first chunk if present if not self.sent_first_chunk: - processed_chunk = self._add_mcp_list_tools_to_first_chunk(processed_chunk) + processed_chunk = self._add_mcp_list_tools_to_first_chunk( + processed_chunk + ) self.sent_first_chunk = True _has_usage = ( @@ -2026,7 +2045,9 @@ class CustomStreamWrapper: if self.sent_last_chunk is True and self.stream_options is None: usage = calculate_total_usage(chunks=self.chunks) processed_chunk._hidden_params["usage"] = usage - self._last_returned_hidden_params = processed_chunk._hidden_params + self._last_returned_hidden_params = ( + processed_chunk._hidden_params + ) # Call post-call streaming deployment hook for final chunk if self.sent_last_chunk is True: @@ -2098,9 +2119,7 @@ class CustomStreamWrapper: and complete_streaming_response is not None and self._last_returned_hidden_params is not None ): - final_usage = getattr( - complete_streaming_response, "usage", None - ) + final_usage = getattr(complete_streaming_response, "usage", None) if final_usage is not None: self._last_returned_hidden_params["usage"] = final_usage @@ -2214,9 +2233,17 @@ class CustomStreamWrapper: # Raise non-retriable client errors directly (skip fallback). # Exception: 429 (rate-limit) IS retriable/transient — allow it # through so the Router can switch to a different model group. - if mapped_status_code is not None and 400 <= mapped_status_code < 500 and mapped_status_code != 429: + if ( + mapped_status_code is not None + and 400 <= mapped_status_code < 500 + and mapped_status_code != 429 + ): raise mapped_exception - if original_status_code is not None and 400 <= original_status_code < 500 and original_status_code != 429: + if ( + original_status_code is not None + and 400 <= original_status_code < 500 + and original_status_code != 429 + ): raise mapped_exception raise MidStreamFallbackError( diff --git a/litellm/litellm_core_utils/token_counter.py b/litellm/litellm_core_utils/token_counter.py index da357e51c22..09c62f2eb55 100644 --- a/litellm/litellm_core_utils/token_counter.py +++ b/litellm/litellm_core_utils/token_counter.py @@ -727,7 +727,9 @@ def _count_content_list( num_tokens += count_function(thinking_text) else: content_type = ( - c.get("type", type(c).__name__) if isinstance(c, dict) else type(c).__name__ + c.get("type", type(c).__name__) + if isinstance(c, dict) + else type(c).__name__ ) raise ValueError( f"Invalid content item type: {content_type}. " diff --git a/litellm/llms/a2a/chat/streaming_iterator.py b/litellm/llms/a2a/chat/streaming_iterator.py index 4b689414ddd..72902f65f7c 100644 --- a/litellm/llms/a2a/chat/streaming_iterator.py +++ b/litellm/llms/a2a/chat/streaming_iterator.py @@ -12,10 +12,10 @@ 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, @@ -29,11 +29,13 @@ class A2AModelResponseIterator(BaseModelResponseIterator): json_mode=json_mode, ) self.model = model - - def chunk_parser(self, chunk: dict) -> Union[GenericStreamingChunk, ModelResponseStream]: + + def chunk_parser( + self, chunk: dict + ) -> Union[GenericStreamingChunk, ModelResponseStream]: """ Parse A2A streaming chunk to OpenAI format. - + A2A chunk format: { "jsonrpc": "2.0", @@ -44,7 +46,7 @@ class A2AModelResponseIterator(BaseModelResponseIterator): } } } - + Or for tasks: { "jsonrpc": "2.0", @@ -58,10 +60,10 @@ class A2AModelResponseIterator(BaseModelResponseIterator): 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, @@ -81,11 +83,11 @@ class A2AModelResponseIterator(BaseModelResponseIterator): 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", {}) @@ -95,9 +97,9 @@ class A2AModelResponseIterator(BaseModelResponseIterator): 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 index 163cd5ab22e..d0887028632 100644 --- a/litellm/llms/a2a/chat/transformation.py +++ b/litellm/llms/a2a/chat/transformation.py @@ -22,10 +22,10 @@ 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, @@ -36,58 +36,63 @@ class A2AConfig(BaseConfig): ) -> 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): + 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: + 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 [ @@ -96,7 +101,7 @@ class A2AConfig(BaseConfig): "max_tokens", "top_p", ] - + def map_openai_params( self, non_default_params: dict, @@ -106,7 +111,7 @@ class A2AConfig(BaseConfig): ) -> 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. """ @@ -114,9 +119,9 @@ class A2AConfig(BaseConfig): 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, @@ -129,7 +134,7 @@ class A2AConfig(BaseConfig): ) -> dict: """ Validate environment and set headers for A2A requests. - + Args: headers: Request headers dict model: Model name @@ -138,20 +143,20 @@ class A2AConfig(BaseConfig): 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], @@ -163,11 +168,11 @@ class A2AConfig(BaseConfig): ) -> 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) @@ -175,17 +180,17 @@ class A2AConfig(BaseConfig): 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, @@ -196,51 +201,49 @@ class A2AConfig(BaseConfig): ) -> 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 - } + "params": {"message": a2a_message}, } - + return request_data - + def transform_response( self, model: str, @@ -257,7 +260,7 @@ class A2AConfig(BaseConfig): ) -> ModelResponse: """ Transform A2A JSON-RPC 2.0 response to OpenAI format. - + Args: model: Model name raw_response: HTTP response from A2A agent @@ -270,7 +273,7 @@ class A2AConfig(BaseConfig): encoding: Encoding object api_key: API key json_mode: JSON mode flag - + Returns: Populated ModelResponse object """ @@ -282,7 +285,7 @@ class A2AConfig(BaseConfig): 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"] @@ -291,10 +294,10 @@ class A2AConfig(BaseConfig): 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( @@ -306,15 +309,15 @@ class A2AConfig(BaseConfig): ), ) ] - + # 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], @@ -323,12 +326,12 @@ class A2AConfig(BaseConfig): ) -> 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 """ @@ -337,26 +340,26 @@ class A2AConfig(BaseConfig): 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: diff --git a/litellm/llms/a2a/common_utils.py b/litellm/llms/a2a/common_utils.py index 116e1205409..aa817ce0fe6 100644 --- a/litellm/llms/a2a/common_utils.py +++ b/litellm/llms/a2a/common_utils.py @@ -31,13 +31,13 @@ class A2AError(BaseLLMException): 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 """ @@ -45,7 +45,7 @@ def convert_messages_to_prompt(messages: List[AllMessageValues]) -> str: 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") @@ -53,10 +53,10 @@ def convert_messages_to_prompt(messages: List[AllMessageValues]) -> str: 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) @@ -65,21 +65,21 @@ def extract_text_from_a2a_message( ) -> 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", "")) @@ -88,7 +88,7 @@ def extract_text_from_a2a_message( nested_text = extract_text_from_a2a_message(part, depth + 1, max_depth) if nested_text: text_parts.append(nested_text) - + return " ".join(text_parts) @@ -97,41 +97,39 @@ def extract_text_from_a2a_response( ) -> 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 - ) - + 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): @@ -140,7 +138,7 @@ def extract_text_from_a2a_response( 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: @@ -148,5 +146,5 @@ def extract_text_from_a2a_response( return extract_text_from_a2a_message( first_artifact, depth=0, max_depth=max_depth ) - + return "" diff --git a/litellm/llms/aiml/chat/transformation.py b/litellm/llms/aiml/chat/transformation.py index 0f3e333343d..72e30a08173 100644 --- a/litellm/llms/aiml/chat/transformation.py +++ b/litellm/llms/aiml/chat/transformation.py @@ -20,4 +20,5 @@ class AIMLChatConfig(OpenAIGPTConfig): ) # type: ignore dynamic_api_key = api_key or get_secret_str("AIML_API_KEY") return api_base, dynamic_api_key - pass \ No newline at end of file + + pass diff --git a/litellm/llms/aiml/image_generation/cost_calculator.py b/litellm/llms/aiml/image_generation/cost_calculator.py index 1fecfb6a9a5..4442f57c555 100644 --- a/litellm/llms/aiml/image_generation/cost_calculator.py +++ b/litellm/llms/aiml/image_generation/cost_calculator.py @@ -22,4 +22,6 @@ def cost_calculator( num_images = len(image_response.data) return output_cost_per_image * num_images else: - raise ValueError(f"image_response must be of type ImageResponse got type={type(image_response)}") + raise ValueError( + f"image_response must be of type ImageResponse got type={type(image_response)}" + ) diff --git a/litellm/llms/aiml/image_generation/transformation.py b/litellm/llms/aiml/image_generation/transformation.py index d8f3e23fe7e..39b1cc742d4 100644 --- a/litellm/llms/aiml/image_generation/transformation.py +++ b/litellm/llms/aiml/image_generation/transformation.py @@ -24,19 +24,15 @@ else: class AimlImageGenerationConfig(BaseImageGenerationConfig): DEFAULT_BASE_URL: str = "https://api.aimlapi.com" IMAGE_GENERATION_ENDPOINT: str = "v1/images/generations" - + def get_supported_openai_params( self, model: str ) -> List[OpenAIImageGenerationOptionalParams]: """ https://api.aimlapi.com/v1/images/generations """ - return [ - "n", - "response_format", - "size" - ] - + return ["n", "response_format", "size"] + def map_openai_params( self, non_default_params: dict, @@ -45,7 +41,7 @@ class AimlImageGenerationConfig(BaseImageGenerationConfig): drop_params: bool, ) -> dict: supported_params = self.get_supported_openai_params(model) - + for k in non_default_params.keys(): if k not in optional_params.keys(): if k in supported_params: @@ -53,7 +49,7 @@ class AimlImageGenerationConfig(BaseImageGenerationConfig): if k == "n": optional_params["num_images"] = non_default_params[k] elif k == "response_format": - optional_params["output_format"] = non_default_params[k] + optional_params["output_format"] = non_default_params[k] elif k == "size": # Map OpenAI size format to AI/ML image_size size_value = non_default_params[k] @@ -61,7 +57,10 @@ class AimlImageGenerationConfig(BaseImageGenerationConfig): # Handle standard OpenAI sizes like "1024x1024" if "x" in size_value: width, height = map(int, size_value.split("x")) - optional_params["image_size"] = {"width": width, "height": height} + optional_params["image_size"] = { + "width": width, + "height": height, + } else: # Pass through predefined sizes optional_params["image_size"] = size_value @@ -91,9 +90,7 @@ class AimlImageGenerationConfig(BaseImageGenerationConfig): Get the complete url for the request """ complete_url: str = ( - api_base - or get_secret_str("AIML_API_BASE") - or self.DEFAULT_BASE_URL + api_base or get_secret_str("AIML_API_BASE") or self.DEFAULT_BASE_URL ) complete_url = complete_url.rstrip("/") @@ -114,15 +111,15 @@ class AimlImageGenerationConfig(BaseImageGenerationConfig): api_base: Optional[str] = None, ) -> dict: final_api_key: Optional[str] = ( - api_key or - get_secret_str("AIML_API_KEY") or - get_secret_str("AIMLAPI_KEY") # Alternative name + api_key + or get_secret_str("AIML_API_KEY") + or get_secret_str("AIMLAPI_KEY") # Alternative name ) if not final_api_key: raise ValueError("AIML_API_KEY or AIMLAPI_KEY is not set") - + headers["Authorization"] = f"Bearer {final_api_key}" - headers["Content-Type"] = "application/json" + headers["Content-Type"] = "application/json" return headers def transform_image_generation_request( @@ -138,10 +135,12 @@ class AimlImageGenerationConfig(BaseImageGenerationConfig): https://api.aimlapi.com/v1/images/generations """ - aiml_image_generation_request_body: AimlImageGenerationRequestParams = AimlImageGenerationRequestParams( - prompt=prompt, - model=model, - **optional_params, + aiml_image_generation_request_body: AimlImageGenerationRequestParams = ( + AimlImageGenerationRequestParams( + prompt=prompt, + model=model, + **optional_params, + ) ) return dict(aiml_image_generation_request_body) @@ -171,53 +170,65 @@ class AimlImageGenerationConfig(BaseImageGenerationConfig): status_code=raw_response.status_code, headers=raw_response.headers, ) - + if not model_response.data: model_response.data = [] - + # AI/ML API can return images in multiple formats: # 1. Top-level data array with url (OpenAI-like format) # 2. output.choices array with image_base64 # 3. images array with url (and optional width, height, content_type) - + if "data" in response_data and isinstance(response_data["data"], list): # Handle OpenAI-like format: {"data": [{"url": "...", "width": 1024, "height": 768, "content_type": "image/jpeg"}]} for image in response_data["data"]: if "url" in image: - model_response.data.append(ImageObject( - b64_json=None, - url=image["url"], - revised_prompt=image.get("revised_prompt"), - )) + model_response.data.append( + ImageObject( + b64_json=None, + url=image["url"], + revised_prompt=image.get("revised_prompt"), + ) + ) elif "b64_json" in image or "image_base64" in image: - model_response.data.append(ImageObject( - b64_json=image.get("b64_json") or image.get("image_base64"), - url=None, - revised_prompt=image.get("revised_prompt"), - )) + model_response.data.append( + ImageObject( + b64_json=image.get("b64_json") or image.get("image_base64"), + url=None, + revised_prompt=image.get("revised_prompt"), + ) + ) elif "output" in response_data and "choices" in response_data["output"]: for choice in response_data["output"]["choices"]: if "image_base64" in choice: - model_response.data.append(ImageObject( - b64_json=choice["image_base64"], - url=None, - )) + model_response.data.append( + ImageObject( + b64_json=choice["image_base64"], + url=None, + ) + ) elif "url" in choice: - model_response.data.append(ImageObject( - b64_json=None, - url=choice["url"], - )) + model_response.data.append( + ImageObject( + b64_json=None, + url=choice["url"], + ) + ) elif "images" in response_data: # Handle alternative format: {"images": [{"url": "...", "width": 1024, "height": 768, "content_type": "image/jpeg"}]} for image in response_data["images"]: if "url" in image: - model_response.data.append(ImageObject( - b64_json=None, - url=image["url"], - )) + model_response.data.append( + ImageObject( + b64_json=None, + url=image["url"], + ) + ) elif "image_base64" in image: - model_response.data.append(ImageObject( - b64_json=image["image_base64"], - url=None, - )) + model_response.data.append( + ImageObject( + b64_json=image["image_base64"], + url=None, + ) + ) return model_response diff --git a/litellm/llms/amazon_nova/chat/transformation.py b/litellm/llms/amazon_nova/chat/transformation.py index 6d321e298b8..0fd08e62872 100644 --- a/litellm/llms/amazon_nova/chat/transformation.py +++ b/litellm/llms/amazon_nova/chat/transformation.py @@ -56,7 +56,7 @@ class AmazonNovaChatConfig(OpenAILikeChatConfig): or get_secret_str("AMAZON_NOVA_API_BASE") or "https://api.nova.amazon.com/v1" ) # type: ignore - + # Get API key from multiple sources key = ( api_key @@ -65,7 +65,7 @@ class AmazonNovaChatConfig(OpenAILikeChatConfig): or litellm.api_key ) return api_base, key - + def get_supported_openai_params(self, model: str) -> List: return [ "top_p", @@ -78,7 +78,7 @@ class AmazonNovaChatConfig(OpenAILikeChatConfig): "stream_options", "tools", "tool_choice", - "reasoning_effort" + "reasoning_effort", ] def transform_response( @@ -112,4 +112,4 @@ class AmazonNovaChatConfig(OpenAILikeChatConfig): # Storing amazon_nova in the model response for easier cost calculation later setattr(model_response, "model", "amazon-nova/" + model) - return model_response \ No newline at end of file + return model_response diff --git a/litellm/llms/amazon_nova/cost_calculation.py b/litellm/llms/amazon_nova/cost_calculation.py index 9d9cedde875..857369b76ed 100644 --- a/litellm/llms/amazon_nova/cost_calculation.py +++ b/litellm/llms/amazon_nova/cost_calculation.py @@ -18,4 +18,4 @@ def cost_per_token(model: str, usage: "Usage") -> Tuple[float, float]: """ return generic_cost_per_token( model=model, usage=usage, custom_llm_provider="amazon_nova" - ) \ No newline at end of file + ) diff --git a/litellm/llms/anthropic/batches/__init__.py b/litellm/llms/anthropic/batches/__init__.py index 66d1a8f77f4..dd9ae5273b8 100644 --- a/litellm/llms/anthropic/batches/__init__.py +++ b/litellm/llms/anthropic/batches/__init__.py @@ -2,4 +2,3 @@ from .handler import AnthropicBatchesHandler from .transformation import AnthropicBatchesConfig __all__ = ["AnthropicBatchesHandler", "AnthropicBatchesConfig"] - diff --git a/litellm/llms/anthropic/batches/handler.py b/litellm/llms/anthropic/batches/handler.py index fd303e60afc..52bf29a5519 100644 --- a/litellm/llms/anthropic/batches/handler.py +++ b/litellm/llms/anthropic/batches/handler.py @@ -24,7 +24,7 @@ from .transformation import AnthropicBatchesConfig class AnthropicBatchesHandler: """ Handler for Anthropic Message Batches API. - + Supports: - retrieve_batch() - Retrieve batch status and information """ @@ -44,7 +44,7 @@ class AnthropicBatchesHandler: ) -> LiteLLMBatch: """ Async: Retrieve a batch from Anthropic. - + Args: batch_id: The batch ID to retrieve api_base: Anthropic API base URL @@ -52,20 +52,23 @@ class AnthropicBatchesHandler: timeout: Request timeout max_retries: Max retry attempts (unused for now) logging_obj: Optional logging object - + Returns: LiteLLMBatch: Batch information in OpenAI format """ # Resolve API credentials api_base = api_base or self.anthropic_model_info.get_api_base(api_base) api_key = api_key or self.anthropic_model_info.get_api_key() - + if not api_key: raise ValueError("Missing Anthropic API Key") - + # Create a minimal logging object if not provided if logging_obj is None: - from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObjClass + from litellm.litellm_core_utils.litellm_logging import ( + Logging as LiteLLMLoggingObjClass, + ) + logging_obj = LiteLLMLoggingObjClass( model="anthropic/unknown", messages=[], @@ -75,7 +78,7 @@ class AnthropicBatchesHandler: litellm_call_id=f"batch_retrieve_{batch_id}", function_id="batch_retrieve", ) - + # Get the complete URL for batch retrieval retrieve_url = self.provider_config.get_retrieve_batch_url( api_base=api_base, @@ -83,7 +86,7 @@ class AnthropicBatchesHandler: optional_params={}, litellm_params={}, ) - + # Validate environment and get headers headers = self.provider_config.validate_environment( headers={}, @@ -106,12 +109,9 @@ class AnthropicBatchesHandler: ) # Make the request async_client = get_async_httpx_client(llm_provider=LlmProviders.ANTHROPIC) - response = await async_client.get( - url=retrieve_url, - headers=headers - ) + response = await async_client.get(url=retrieve_url, headers=headers) response.raise_for_status() - + # Transform response to LiteLLM format return self.provider_config.transform_retrieve_batch_response( model=None, @@ -132,7 +132,7 @@ class AnthropicBatchesHandler: ) -> Union[LiteLLMBatch, Coroutine[Any, Any, LiteLLMBatch]]: """ Retrieve a batch from Anthropic. - + Args: _is_async: Whether to run asynchronously batch_id: The batch ID to retrieve @@ -141,7 +141,7 @@ class AnthropicBatchesHandler: timeout: Request timeout max_retries: Max retry attempts (unused for now) logging_obj: Optional logging object - + Returns: LiteLLMBatch or Coroutine: Batch information in OpenAI format """ @@ -165,4 +165,3 @@ class AnthropicBatchesHandler: logging_obj=logging_obj, ) ) - diff --git a/litellm/llms/anthropic/batches/transformation.py b/litellm/llms/anthropic/batches/transformation.py index 750dd002ff9..699f133f0f6 100644 --- a/litellm/llms/anthropic/batches/transformation.py +++ b/litellm/llms/anthropic/batches/transformation.py @@ -84,7 +84,7 @@ class AnthropicBatchesConfig(BaseBatchesConfig): ) -> Union[bytes, str, Dict[str, Any]]: """ Transform the batch creation request to Anthropic format. - + Not currently implemented - placeholder to satisfy abstract base class. """ raise NotImplementedError("Batch creation not yet implemented for Anthropic") @@ -98,7 +98,7 @@ class AnthropicBatchesConfig(BaseBatchesConfig): ) -> LiteLLMBatch: """ Transform Anthropic MessageBatch creation response to LiteLLM format. - + Not currently implemented - placeholder to satisfy abstract base class. """ raise NotImplementedError("Batch creation not yet implemented for Anthropic") @@ -112,13 +112,13 @@ class AnthropicBatchesConfig(BaseBatchesConfig): ) -> str: """ Get the complete URL for batch retrieval request. - + Args: api_base: Base API URL (optional, will use default if not provided) batch_id: Batch ID to retrieve optional_params: Optional parameters litellm_params: LiteLLM parameters - + Returns: Complete URL for Anthropic batch retrieval: {api_base}/v1/messages/batches/{batch_id} """ @@ -133,7 +133,7 @@ class AnthropicBatchesConfig(BaseBatchesConfig): ) -> Union[bytes, str, Dict[str, Any]]: """ Transform batch retrieval request for Anthropic. - + For Anthropic, the URL is constructed by get_retrieve_batch_url(), so this method returns an empty dict (no additional request params needed). """ @@ -156,9 +156,21 @@ class AnthropicBatchesConfig(BaseBatchesConfig): # Map Anthropic MessageBatch to OpenAI Batch format batch_id = response_data.get("id", "") processing_status = response_data.get("processing_status", "in_progress") - + # Map Anthropic processing_status to OpenAI status - status_mapping: Dict[str, Literal["validating", "failed", "in_progress", "finalizing", "completed", "expired", "cancelling", "cancelled"]] = { + status_mapping: Dict[ + str, + Literal[ + "validating", + "failed", + "in_progress", + "finalizing", + "completed", + "expired", + "cancelling", + "cancelled", + ], + ] = { "in_progress": "in_progress", "canceling": "cancelling", "ended": "completed", @@ -171,7 +183,8 @@ class AnthropicBatchesConfig(BaseBatchesConfig): return None try: from datetime import datetime - dt = datetime.fromisoformat(ts_str.replace('Z', '+00:00')) + + dt = datetime.fromisoformat(ts_str.replace("Z", "+00:00")) return int(dt.timestamp()) except Exception: return None @@ -185,14 +198,17 @@ class AnthropicBatchesConfig(BaseBatchesConfig): # Extract request counts request_counts_data = response_data.get("request_counts", {}) from openai.types.batch import BatchRequestCounts + request_counts = BatchRequestCounts( - total=sum([ - request_counts_data.get("processing", 0), - request_counts_data.get("succeeded", 0), - request_counts_data.get("errored", 0), - request_counts_data.get("canceled", 0), - request_counts_data.get("expired", 0), - ]), + total=sum( + [ + request_counts_data.get("processing", 0), + request_counts_data.get("succeeded", 0), + request_counts_data.get("errored", 0), + request_counts_data.get("canceled", 0), + request_counts_data.get("expired", 0), + ] + ), completed=request_counts_data.get("succeeded", 0), failed=request_counts_data.get("errored", 0), ) @@ -214,8 +230,12 @@ class AnthropicBatchesConfig(BaseBatchesConfig): completed_at=ended_at if processing_status == "ended" else None, failed_at=None, expired_at=archived_at if archived_at else None, - cancelling_at=cancel_initiated_at if processing_status == "canceling" else None, - cancelled_at=ended_at if processing_status == "canceling" and ended_at else None, + cancelling_at=cancel_initiated_at + if processing_status == "canceling" + else None, + cancelled_at=ended_at + if processing_status == "canceling" and ended_at + else None, request_counts=request_counts, metadata={}, ) @@ -232,7 +252,9 @@ class AnthropicBatchesConfig(BaseBatchesConfig): else: headers_obj = headers if isinstance(headers, Headers) else None - return AnthropicError(status_code=status_code, message=error_message, headers=headers_obj) + return AnthropicError( + status_code=status_code, message=error_message, headers=headers_obj + ) def transform_response( self, diff --git a/litellm/llms/anthropic/chat/guardrail_translation/handler.py b/litellm/llms/anthropic/chat/guardrail_translation/handler.py index a6df346e8a8..0bc0777e37a 100644 --- a/litellm/llms/anthropic/chat/guardrail_translation/handler.py +++ b/litellm/llms/anthropic/chat/guardrail_translation/handler.py @@ -75,11 +75,12 @@ class AnthropicMessagesHandler(BaseTranslation): if messages is None: return data - chat_completion_compatible_request, _tool_name_mapping = ( - LiteLLMAnthropicMessagesAdapter().translate_anthropic_to_openai( - # Use a shallow copy to avoid mutating request data (pop on litellm_metadata). - anthropic_message_request=cast(AnthropicMessagesRequest, data.copy()) - ) + ( + chat_completion_compatible_request, + _tool_name_mapping, + ) = LiteLLMAnthropicMessagesAdapter().translate_anthropic_to_openai( + # Use a shallow copy to avoid mutating request data (pop on litellm_metadata). + anthropic_message_request=cast(AnthropicMessagesRequest, data.copy()) ) structured_messages = chat_completion_compatible_request.get("messages", []) @@ -205,7 +206,7 @@ class AnthropicMessagesHandler(BaseTranslation): openai_tools = self.adapter.translate_anthropic_tools_to_openai( tools=cast(List[AllAnthropicToolsValues], tools) ) - tools_to_check.extend(openai_tools) # type: ignore + tools_to_check.extend(openai_tools) # type: ignore async def _apply_guardrail_responses_to_input( self, @@ -375,10 +376,12 @@ class AnthropicMessagesHandler(BaseTranslation): has_ended = self._check_streaming_has_ended(responses_so_far) if has_ended: # build the model response from the responses_so_far - built_response = AnthropicPassthroughLoggingHandler._build_complete_streaming_response( - all_chunks=responses_so_far, - litellm_logging_obj=cast("LiteLLMLoggingObj", litellm_logging_obj), - model="", + 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 @@ -407,7 +410,9 @@ class AnthropicMessagesHandler(BaseTranslation): logging_obj=litellm_logging_obj, ) else: - verbose_proxy_logger.debug("Skipping output guardrail - model response has no choices") + 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) diff --git a/litellm/llms/anthropic/chat/handler.py b/litellm/llms/anthropic/chat/handler.py index f51adf96102..72cc7ecd9cc 100644 --- a/litellm/llms/anthropic/chat/handler.py +++ b/litellm/llms/anthropic/chat/handler.py @@ -165,7 +165,10 @@ def make_sync_call( ) completion_stream = ModelResponseIterator( - streaming_response=response.iter_lines(), sync_stream=True, json_mode=json_mode, speed=speed + streaming_response=response.iter_lines(), + sync_stream=True, + json_mode=json_mode, + speed=speed, ) # LOGGING @@ -497,7 +500,11 @@ class AnthropicChatCompletion(BaseLLM): class ModelResponseIterator: def __init__( - self, streaming_response, sync_stream: bool, json_mode: Optional[bool] = False, speed: Optional[str] = None + self, + streaming_response, + sync_stream: bool, + json_mode: Optional[bool] = False, + speed: Optional[str] = None, ): self.streaming_response = streaming_response self.response_iterator = self.streaming_response @@ -525,7 +532,7 @@ class ModelResponseIterator: # 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]] = [] @@ -554,10 +561,14 @@ class ModelResponseIterator: def _handle_usage(self, anthropic_usage_chunk: Union[dict, UsageDelta]) -> Usage: return AnthropicConfig().calculate_usage( - usage_object=cast(dict, anthropic_usage_chunk), reasoning_content=None, speed=self.speed + usage_object=cast(dict, anthropic_usage_chunk), + reasoning_content=None, + speed=self.speed, ) - def _content_block_delta_helper(self, chunk: dict) -> Tuple[ + def _content_block_delta_helper( + self, chunk: dict + ) -> Tuple[ str, Optional[ChatCompletionToolCallChunk], List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]], @@ -608,11 +619,14 @@ class ModelResponseIterator: ) ] provider_specific_fields["thinking_blocks"] = thinking_blocks - elif "content" in content_block["delta"] and content_block["delta"].get("type") == "compaction_delta": + 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"] + "content": content_block["delta"]["content"], } return text, tool_use, thinking_blocks, provider_specific_fields @@ -710,10 +724,15 @@ class ModelResponseIterator: content_block_start = self.get_content_block_start(chunk=chunk) self.content_blocks = [] # reset content blocks when new block starts # Track current content block type for filtering deltas - self.current_content_block_type = content_block_start["content_block"]["type"] + self.current_content_block_type = content_block_start["content_block"][ + "type" + ] if content_block_start["content_block"]["type"] == "text": text = content_block_start["content_block"]["text"] - elif content_block_start["content_block"]["type"] == "tool_use" or content_block_start["content_block"]["type"] == "server_tool_use": + elif ( + content_block_start["content_block"]["type"] == "tool_use" + or content_block_start["content_block"]["type"] == "server_tool_use" + ): self.tool_index += 1 # Use empty string for arguments in content_block_start - actual arguments # come in subsequent content_block_delta chunks and get accumulated. @@ -746,21 +765,23 @@ class ModelResponseIterator: 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 - ) + 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", "") + "content": content_block_start["content_block"].get( + "content", "" + ), } - elif content_block_start["content_block"]["type"].endswith("_tool_result"): + 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"] - + # Special handling for web_search_tool_result for backwards compatibility if content_type == "web_search_tool_result": # Capture web_search_tool_result for multi-turn reconstruction @@ -769,9 +790,9 @@ class ModelResponseIterator: self.web_search_results.append( content_block_start["content_block"] ) - provider_specific_fields["web_search_results"] = ( - self.web_search_results - ) + provider_specific_fields[ + "web_search_results" + ] = self.web_search_results elif content_type == "web_fetch_tool_result": # Capture web_fetch_tool_result for multi-turn reconstruction # The full content comes in content_block_start, not in deltas @@ -779,9 +800,9 @@ class ModelResponseIterator: self.web_search_results.append( content_block_start["content_block"] ) - provider_specific_fields["web_search_results"] = ( - self.web_search_results - ) + provider_specific_fields[ + "web_search_results" + ] = self.web_search_results elif content_type != "tool_search_tool_result": # Handle other tool results (code execution, etc.) # Skip tool_search_tool_result as it's internal metadata @@ -932,7 +953,9 @@ class ModelResponseIterator: return text, tool_use - def _handle_message_delta(self, chunk: dict) -> Tuple[str, Optional[Usage], Optional[Dict[str, Any]]]: + def _handle_message_delta( + self, chunk: dict + ) -> Tuple[str, Optional[Usage], Optional[Dict[str, Any]]]: """ Handle message_delta event for finish_reason, usage, and container. @@ -1052,7 +1075,9 @@ class ModelResponseIterator: except StopIteration: raise StopIteration except ValueError as e: - raise RuntimeError(f"Error parsing chunk: {e},\nReceived chunk: {chunk}") + raise RuntimeError( + f"Error parsing chunk: {e},\nReceived chunk: {chunk}" + ) # Async iterator def __aiter__(self): @@ -1101,7 +1126,9 @@ class ModelResponseIterator: except StopAsyncIteration: raise StopAsyncIteration except ValueError as e: - raise RuntimeError(f"Error parsing chunk: {e},\nReceived chunk: {chunk}") + raise RuntimeError( + f"Error parsing chunk: {e},\nReceived chunk: {chunk}" + ) def convert_str_chunk_to_generic_chunk(self, chunk: str) -> ModelResponseStream: """ diff --git a/litellm/llms/anthropic/chat/transformation.py b/litellm/llms/anthropic/chat/transformation.py index fd1859f7d17..1b912bfc2a0 100644 --- a/litellm/llms/anthropic/chat/transformation.py +++ b/litellm/llms/anthropic/chat/transformation.py @@ -173,8 +173,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig): """Check if the model is specifically Claude Opus 4.6.""" model_lower = model.lower() return any( - v in model_lower - for v in ("opus-4-6", "opus_4_6", "opus-4.6", "opus_4.6") + v in model_lower for v in ("opus-4-6", "opus_4_6", "opus-4.6", "opus_4.6") ) def get_supported_openai_params(self, model: str): @@ -957,11 +956,11 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig): if mcp_servers: optional_params["mcp_servers"] = mcp_servers elif param == "tool_choice" or param == "parallel_tool_calls": - _tool_choice: Optional[AnthropicMessagesToolChoice] = ( - self._map_tool_choice( - tool_choice=non_default_params.get("tool_choice"), - parallel_tool_use=non_default_params.get("parallel_tool_calls"), - ) + _tool_choice: Optional[ + AnthropicMessagesToolChoice + ] = self._map_tool_choice( + tool_choice=non_default_params.get("tool_choice"), + parallel_tool_use=non_default_params.get("parallel_tool_calls"), ) if _tool_choice is not None: @@ -1059,9 +1058,9 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig): self.map_openai_context_management_to_anthropic(value) ) if anthropic_context_management is not None: - optional_params["context_management"] = ( - anthropic_context_management - ) + optional_params[ + "context_management" + ] = anthropic_context_management elif param == "speed" and isinstance(value, str): # Pass through Anthropic-specific speed parameter for fast mode optional_params["speed"] = value @@ -1135,9 +1134,9 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig): text=system_message_block["content"], ) if "cache_control" in system_message_block: - anthropic_system_message_content["cache_control"] = ( - system_message_block["cache_control"] - ) + anthropic_system_message_content[ + "cache_control" + ] = system_message_block["cache_control"] anthropic_system_message_list.append( anthropic_system_message_content ) @@ -1161,9 +1160,9 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig): ) ) if "cache_control" in _content: - anthropic_system_message_content["cache_control"] = ( - _content["cache_control"] - ) + anthropic_system_message_content[ + "cache_control" + ] = _content["cache_control"] anthropic_system_message_list.append( anthropic_system_message_content @@ -1460,7 +1459,9 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig): ) return _message - def extract_response_content(self, completion_response: dict) -> Tuple[ + def extract_response_content( + self, completion_response: dict + ) -> Tuple[ str, Optional[List[Any]], Optional[ diff --git a/litellm/llms/anthropic/common_utils.py b/litellm/llms/anthropic/common_utils.py index 8f196966dcc..ac352467878 100644 --- a/litellm/llms/anthropic/common_utils.py +++ b/litellm/llms/anthropic/common_utils.py @@ -31,6 +31,7 @@ def is_anthropic_oauth_key(value: Optional[str]) -> bool: value = value[7:] return value.startswith(ANTHROPIC_OAUTH_TOKEN_PREFIX) + def _merge_beta_headers(existing: Optional[str], new_beta: str) -> str: """Merge a new beta value into an existing comma-separated anthropic-beta header.""" if not existing: @@ -244,8 +245,14 @@ class AnthropicModelInfo(BaseLLMModelInfo): return any( v in model_lower for v in ( - "opus-4-6", "opus_4_6", "opus-4.6", "opus_4.6", - "sonnet-4-6", "sonnet_4_6", "sonnet-4.6", "sonnet_4.6", + "opus-4-6", + "opus_4_6", + "opus-4.6", + "opus_4.6", + "sonnet-4-6", + "sonnet_4_6", + "sonnet-4.6", + "sonnet_4.6", ) ) diff --git a/litellm/llms/anthropic/completion/transformation.py b/litellm/llms/anthropic/completion/transformation.py index a8798cd5d0e..576ddb57fb1 100644 --- a/litellm/llms/anthropic/completion/transformation.py +++ b/litellm/llms/anthropic/completion/transformation.py @@ -55,9 +55,9 @@ class AnthropicTextConfig(BaseConfig): to pass metadata to anthropic, it's {"user_id": "any-relevant-information"} """ - max_tokens_to_sample: Optional[int] = ( - litellm.max_tokens - ) # anthropic requires a default + max_tokens_to_sample: Optional[ + int + ] = litellm.max_tokens # anthropic requires a default stop_sequences: Optional[list] = None temperature: Optional[int] = None top_p: Optional[int] = None diff --git a/litellm/llms/anthropic/cost_calculation.py b/litellm/llms/anthropic/cost_calculation.py index cf9b18c4643..3882d8f978c 100644 --- a/litellm/llms/anthropic/cost_calculation.py +++ b/litellm/llms/anthropic/cost_calculation.py @@ -29,9 +29,13 @@ def _compute_cache_only_cost(model_info: "ModelInfo", usage: "Usage") -> float: return 0.0 prompt_tokens_details = _parse_prompt_tokens_details(usage) - _, _, cache_creation_cost, cache_creation_cost_above_1hr, cache_read_cost = ( - _get_token_base_cost(model_info=model_info, usage=usage) - ) + ( + _, + _, + cache_creation_cost, + cache_creation_cost_above_1hr, + cache_read_cost, + ) = _get_token_base_cost(model_info=model_info, usage=usage) cache_cost = float(prompt_tokens_details["cache_hit_tokens"]) * cache_read_cost @@ -68,7 +72,9 @@ def cost_per_token(model: str, usage: "Usage") -> Tuple[float, float]: # Apply provider_specific_entry multipliers for geo/speed routing try: - model_info = litellm.get_model_info(model=model, custom_llm_provider="anthropic") + model_info = litellm.get_model_info( + model=model, custom_llm_provider="anthropic" + ) provider_specific_entry: dict = model_info.get("provider_specific_entry") or {} multiplier = 1.0 @@ -77,9 +83,7 @@ def cost_per_token(model: str, usage: "Usage") -> Tuple[float, float]: and usage.inference_geo and usage.inference_geo.lower() not in ["global", "not_available"] ): - multiplier *= provider_specific_entry.get( - usage.inference_geo.lower(), 1.0 - ) + multiplier *= provider_specific_entry.get(usage.inference_geo.lower(), 1.0) if hasattr(usage, "speed") and usage.speed == "fast": multiplier *= provider_specific_entry.get("fast", 1.0) diff --git a/litellm/llms/anthropic/count_tokens/handler.py b/litellm/llms/anthropic/count_tokens/handler.py index 07481917afe..4d0af0b36c8 100644 --- a/litellm/llms/anthropic/count_tokens/handler.py +++ b/litellm/llms/anthropic/count_tokens/handler.py @@ -82,7 +82,9 @@ class AnthropicCountTokensHandler(AnthropicCountTokensConfig): ) # Use provided timeout or fall back to litellm.request_timeout - request_timeout = timeout if timeout is not None else litellm.request_timeout + request_timeout = ( + timeout if timeout is not None else litellm.request_timeout + ) response = await async_client.post( endpoint_url, diff --git a/litellm/llms/anthropic/count_tokens/transformation.py b/litellm/llms/anthropic/count_tokens/transformation.py index 2d3f5b1942b..ad5bbbda25f 100644 --- a/litellm/llms/anthropic/count_tokens/transformation.py +++ b/litellm/llms/anthropic/count_tokens/transformation.py @@ -73,14 +73,10 @@ class AnthropicCountTokensConfig: "anthropic-version": "2023-06-01", "anthropic-beta": ANTHROPIC_TOKEN_COUNTING_BETA_VERSION, } - headers, _ = optionally_handle_anthropic_oauth( - headers=headers, api_key=api_key - ) + headers, _ = optionally_handle_anthropic_oauth(headers=headers, api_key=api_key) return headers - def validate_request( - self, model: str, messages: List[Dict[str, Any]] - ) -> None: + def validate_request(self, model: str, messages: List[Dict[str, Any]]) -> None: """ Validate the incoming count tokens request. diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py b/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py index 73e74c228ba..8b1b21a0f9b 100644 --- a/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py +++ b/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py @@ -65,7 +65,9 @@ class LiteLLMMessagesToCompletionTransformationHandler: model = completion_kwargs.get("model") try: - model_info = get_model_info(model=cast(str, model), custom_llm_provider=custom_llm_provider) + model_info = get_model_info( + model=cast(str, model), custom_llm_provider=custom_llm_provider + ) if model_info and model_info.get("supports_reasoning") is False: # Model doesn't support reasoning/responses API, don't route return @@ -75,7 +77,7 @@ class LiteLLMMessagesToCompletionTransformationHandler: if isinstance(model, str) and model and not model.startswith("responses/"): # Prefix model with "responses/" to route to OpenAI Responses API completion_kwargs["model"] = f"responses/{model}" - + reasoning_effort = completion_kwargs.get("reasoning_effort") if isinstance(reasoning_effort, str) and reasoning_effort: completion_kwargs["reasoning_effort"] = { @@ -148,7 +150,10 @@ class LiteLLMMessagesToCompletionTransformationHandler: if output_format: request_data["output_format"] = output_format - openai_request, tool_name_mapping = ANTHROPIC_ADAPTER.translate_completion_input_params_with_tool_mapping( + ( + openai_request, + tool_name_mapping, + ) = ANTHROPIC_ADAPTER.translate_completion_input_params_with_tool_mapping( request_data ) @@ -210,24 +215,25 @@ class LiteLLMMessagesToCompletionTransformationHandler: **kwargs, ) -> Union[AnthropicMessagesResponse, AsyncIterator]: """Handle non-Anthropic models asynchronously using the adapter""" - completion_kwargs, tool_name_mapping = ( - LiteLLMMessagesToCompletionTransformationHandler._prepare_completion_kwargs( - max_tokens=max_tokens, - messages=messages, - model=model, - metadata=metadata, - stop_sequences=stop_sequences, - stream=stream, - system=system, - temperature=temperature, - thinking=thinking, - tool_choice=tool_choice, - tools=tools, - top_k=top_k, - top_p=top_p, - output_format=output_format, - extra_kwargs=kwargs, - ) + ( + completion_kwargs, + tool_name_mapping, + ) = LiteLLMMessagesToCompletionTransformationHandler._prepare_completion_kwargs( + max_tokens=max_tokens, + messages=messages, + model=model, + metadata=metadata, + stop_sequences=stop_sequences, + stream=stream, + system=system, + temperature=temperature, + thinking=thinking, + tool_choice=tool_choice, + tools=tools, + top_k=top_k, + top_p=top_p, + output_format=output_format, + extra_kwargs=kwargs, ) completion_response = await litellm.acompletion(**completion_kwargs) @@ -244,11 +250,9 @@ class LiteLLMMessagesToCompletionTransformationHandler: return transformed_stream raise ValueError("Failed to transform streaming response") else: - anthropic_response = ( - ANTHROPIC_ADAPTER.translate_completion_output_params( - cast(ModelResponse, completion_response), - tool_name_mapping=tool_name_mapping, - ) + anthropic_response = ANTHROPIC_ADAPTER.translate_completion_output_params( + cast(ModelResponse, completion_response), + tool_name_mapping=tool_name_mapping, ) if anthropic_response is not None: return anthropic_response @@ -297,24 +301,25 @@ class LiteLLMMessagesToCompletionTransformationHandler: **kwargs, ) - completion_kwargs, tool_name_mapping = ( - LiteLLMMessagesToCompletionTransformationHandler._prepare_completion_kwargs( - max_tokens=max_tokens, - messages=messages, - model=model, - metadata=metadata, - stop_sequences=stop_sequences, - stream=stream, - system=system, - temperature=temperature, - thinking=thinking, - tool_choice=tool_choice, - tools=tools, - top_k=top_k, - top_p=top_p, - output_format=output_format, - extra_kwargs=kwargs, - ) + ( + completion_kwargs, + tool_name_mapping, + ) = LiteLLMMessagesToCompletionTransformationHandler._prepare_completion_kwargs( + max_tokens=max_tokens, + messages=messages, + model=model, + metadata=metadata, + stop_sequences=stop_sequences, + stream=stream, + system=system, + temperature=temperature, + thinking=thinking, + tool_choice=tool_choice, + tools=tools, + top_k=top_k, + top_p=top_p, + output_format=output_format, + extra_kwargs=kwargs, ) completion_response = litellm.completion(**completion_kwargs) @@ -331,11 +336,9 @@ class LiteLLMMessagesToCompletionTransformationHandler: return transformed_stream raise ValueError("Failed to transform streaming response") else: - anthropic_response = ( - ANTHROPIC_ADAPTER.translate_completion_output_params( - cast(ModelResponse, completion_response), - tool_name_mapping=tool_name_mapping, - ) + anthropic_response = ANTHROPIC_ADAPTER.translate_completion_output_params( + cast(ModelResponse, completion_response), + tool_name_mapping=tool_name_mapping, ) if anthropic_response is not None: return anthropic_response 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 7f17526e75c..6bddad09f21 100644 --- a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py +++ b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py @@ -261,19 +261,37 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper): # Add usage to the held chunk uncached_input_tokens = chunk.usage.prompt_tokens or 0 - if hasattr(chunk.usage, "prompt_tokens_details") and chunk.usage.prompt_tokens_details: - cached_tokens = getattr(chunk.usage.prompt_tokens_details, "cached_tokens", 0) or 0 + if ( + hasattr(chunk.usage, "prompt_tokens_details") + and chunk.usage.prompt_tokens_details + ): + cached_tokens = ( + getattr( + chunk.usage.prompt_tokens_details, "cached_tokens", 0 + ) + or 0 + ) uncached_input_tokens -= cached_tokens - + usage_dict: UsageDelta = { "input_tokens": uncached_input_tokens, "output_tokens": chunk.usage.completion_tokens or 0, } # Add cache tokens if available (for prompt caching support) - if hasattr(chunk.usage, "_cache_creation_input_tokens") and chunk.usage._cache_creation_input_tokens > 0: - usage_dict["cache_creation_input_tokens"] = chunk.usage._cache_creation_input_tokens - if hasattr(chunk.usage, "_cache_read_input_tokens") and chunk.usage._cache_read_input_tokens > 0: - usage_dict["cache_read_input_tokens"] = chunk.usage._cache_read_input_tokens + if ( + hasattr(chunk.usage, "_cache_creation_input_tokens") + and chunk.usage._cache_creation_input_tokens > 0 + ): + usage_dict[ + "cache_creation_input_tokens" + ] = chunk.usage._cache_creation_input_tokens + if ( + hasattr(chunk.usage, "_cache_read_input_tokens") + and chunk.usage._cache_read_input_tokens > 0 + ): + usage_dict[ + "cache_read_input_tokens" + ] = chunk.usage._cache_read_input_tokens merged_chunk["usage"] = usage_dict # Queue the merged chunk and reset @@ -439,12 +457,14 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper): 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) + original_name = self.tool_name_mapping.get( + truncated_name, truncated_name + ) tool_block["name"] = original_name if block_type != self.current_content_block_type: @@ -458,7 +478,7 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper): 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 diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py index a7362a94312..43a6fa8045d 100644 --- a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py +++ b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py @@ -61,6 +61,7 @@ def create_tool_name_mapping( 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 ( @@ -172,10 +173,11 @@ class AnthropicAdapter: model=model, messages=messages, **kwargs ) - translated_body, tool_name_mapping = ( - LiteLLMAnthropicMessagesAdapter().translate_anthropic_to_openai( - anthropic_message_request=request_body - ) + ( + translated_body, + tool_name_mapping, + ) = LiteLLMAnthropicMessagesAdapter().translate_anthropic_to_openai( + anthropic_message_request=request_body ) return translated_body, tool_name_mapping @@ -283,7 +285,11 @@ class LiteLLMAnthropicMessagesAdapter: model: Model name to check if cache_control should be preserved """ # TypedDict objects are dicts at runtime, so .get() works - cache_control = source.get("cache_control") if isinstance(source, dict) else getattr(source, "cache_control", None) + cache_control = ( + source.get("cache_control") + if isinstance(source, dict) + else getattr(source, "cache_control", None) + ) if cache_control and model and self.is_anthropic_claude_model(model): # TypedDict objects support dict operations at runtime # Use type ignore consistent with codebase pattern (see anthropic/chat/transformation.py:432) @@ -297,7 +303,15 @@ class LiteLLMAnthropicMessagesAdapter: """ Which anthropic params, we need to translate to the openai format. """ - return ["messages", "metadata", "system", "tool_choice", "tools", "thinking", "output_format"] + return [ + "messages", + "metadata", + "system", + "tool_choice", + "tools", + "thinking", + "output_format", + ] def _is_web_search_tool(self, tool: Dict[str, Any]) -> bool: """ @@ -350,13 +364,17 @@ class LiteLLMAnthropicMessagesAdapter: text_obj = ChatCompletionTextObject( type="text", text=content.get("text", "") ) - self._add_cache_control_if_applicable(content, text_obj, model) + self._add_cache_control_if_applicable( + content, text_obj, model + ) new_user_content_list.append(text_obj) # type: ignore elif content.get("type") == "image": # Convert Anthropic image format to OpenAI format source = content.get("source", {}) openai_image_url = ( - self._translate_anthropic_image_to_openai(cast(dict, source)) + self._translate_anthropic_image_to_openai( + cast(dict, source) + ) ) if openai_image_url: @@ -366,13 +384,17 @@ class LiteLLMAnthropicMessagesAdapter: image_obj = ChatCompletionImageObject( type="image_url", image_url=image_url_obj ) - self._add_cache_control_if_applicable(content, image_obj, model) + self._add_cache_control_if_applicable( + content, image_obj, model + ) new_user_content_list.append(image_obj) # type: ignore elif content.get("type") == "document": # Convert Anthropic document format (PDF, etc.) to OpenAI format source = content.get("source", {}) openai_image_url = ( - self._translate_anthropic_image_to_openai(cast(dict, source)) + self._translate_anthropic_image_to_openai( + cast(dict, source) + ) ) if openai_image_url: @@ -382,7 +404,9 @@ class LiteLLMAnthropicMessagesAdapter: doc_obj = ChatCompletionImageObject( type="image_url", image_url=image_url_obj ) - self._add_cache_control_if_applicable(content, doc_obj, model) + self._add_cache_control_if_applicable( + content, doc_obj, model + ) new_user_content_list.append(doc_obj) # type: ignore elif content.get("type") == "tool_result": if "content" not in content: @@ -391,7 +415,9 @@ class LiteLLMAnthropicMessagesAdapter: tool_call_id=content.get("tool_use_id", ""), content="", ) - self._add_cache_control_if_applicable(content, tool_result, model) + self._add_cache_control_if_applicable( + content, tool_result, model + ) tool_message_list.append(tool_result) # type: ignore[arg-type] elif isinstance(content.get("content"), str): tool_result = ChatCompletionToolMessage( @@ -399,7 +425,9 @@ class LiteLLMAnthropicMessagesAdapter: tool_call_id=content.get("tool_use_id", ""), content=str(content.get("content", "")), ) - self._add_cache_control_if_applicable(content, tool_result, model) + self._add_cache_control_if_applicable( + content, tool_result, model + ) tool_message_list.append(tool_result) # type: ignore[arg-type] elif isinstance(content.get("content"), list): # Combine all content items into a single tool message @@ -416,7 +444,9 @@ class LiteLLMAnthropicMessagesAdapter: tool_call_id=content.get("tool_use_id", ""), content=c, ) - self._add_cache_control_if_applicable(content, tool_result, model) + self._add_cache_control_if_applicable( + content, tool_result, model + ) tool_message_list.append(tool_result) # type: ignore[arg-type] elif isinstance(c, dict): if c.get("type") == "text": @@ -427,7 +457,9 @@ class LiteLLMAnthropicMessagesAdapter: ), content=c.get("text", ""), ) - self._add_cache_control_if_applicable(content, tool_result, model) + self._add_cache_control_if_applicable( + content, tool_result, model + ) tool_message_list.append(tool_result) # type: ignore[arg-type] elif c.get("type") == "image": source = c.get("source", {}) @@ -444,7 +476,9 @@ class LiteLLMAnthropicMessagesAdapter: ), content=openai_image_url, ) - self._add_cache_control_if_applicable(content, tool_result, model) + self._add_cache_control_if_applicable( + content, tool_result, model + ) tool_message_list.append(tool_result) # type: ignore[arg-type] else: # For multiple content items, combine into a single tool message @@ -494,7 +528,9 @@ class LiteLLMAnthropicMessagesAdapter: tool_call_id=content.get("tool_use_id", ""), content=combined_content_parts, # type: ignore ) - self._add_cache_control_if_applicable(content, tool_result, model) + self._add_cache_control_if_applicable( + content, tool_result, model + ) tool_message_list.append(tool_result) # type: ignore[arg-type] if len(tool_message_list) > 0: @@ -508,7 +544,9 @@ class LiteLLMAnthropicMessagesAdapter: ## ASSISTANT MESSAGE ## assistant_message_str: Optional[str] = None - assistant_content_list: List[Dict[str, Any]] = [] # For content blocks with cache_control + assistant_content_list: List[ + Dict[str, Any] + ] = [] # For content blocks with cache_control has_cache_control_in_text = False tool_calls: List[ChatCompletionAssistantToolCall] = [] thinking_blocks: List[ @@ -527,7 +565,9 @@ class LiteLLMAnthropicMessagesAdapter: "type": "text", "text": content.get("text", ""), } - self._add_cache_control_if_applicable(content, text_block, model) + self._add_cache_control_if_applicable( + content, text_block, model + ) if "cache_control" in text_block: has_cache_control_in_text = True assistant_content_list.append(text_block) @@ -549,19 +589,21 @@ class LiteLLMAnthropicMessagesAdapter: function_chunk.get("provider_specific_fields") or {} ) - provider_specific_fields["thought_signature"] = ( - signature - ) - function_chunk["provider_specific_fields"] = ( - provider_specific_fields - ) + provider_specific_fields[ + "thought_signature" + ] = signature + function_chunk[ + "provider_specific_fields" + ] = provider_specific_fields tool_call = ChatCompletionAssistantToolCall( id=content.get("id", ""), type="function", function=function_chunk, ) - self._add_cache_control_if_applicable(content, tool_call, model) + self._add_cache_control_if_applicable( + content, tool_call, model + ) tool_calls.append(tool_call) elif content.get("type") == "thinking": thinking_block = ChatCompletionThinkingBlock( @@ -660,10 +702,7 @@ class LiteLLMAnthropicMessagesAdapter: - vertex_ai/*claude* models """ model_lower = model.lower() - return ( - "anthropic" in model_lower - or "claude" in model_lower - ) + return "anthropic" in model_lower or "claude" in model_lower @staticmethod def translate_thinking_for_model( @@ -751,7 +790,9 @@ class LiteLLMAnthropicMessagesAdapter: for k, v in tool.items(): if k not in mapped_tool_params: # pass additional computer kwargs function_chunk.setdefault("parameters", {}).update({k: v}) - tool_param = ChatCompletionToolParam(type="function", function=function_chunk) + tool_param = ChatCompletionToolParam( + type="function", function=function_chunk + ) self._add_cache_control_if_applicable(tool, tool_param, model) new_tools.append(tool_param) # type: ignore[arg-type] @@ -883,10 +924,10 @@ class LiteLLMAnthropicMessagesAdapter: if "tool_choice" in anthropic_message_request: tool_choice = anthropic_message_request["tool_choice"] if tool_choice: - new_kwargs["tool_choice"] = ( - self.translate_anthropic_tool_choice_to_openai( - tool_choice=cast(AnthropicMessagesToolChoice, tool_choice) - ) + new_kwargs[ + "tool_choice" + ] = self.translate_anthropic_tool_choice_to_openai( + tool_choice=cast(AnthropicMessagesToolChoice, tool_choice) ) ## CONVERT TOOLS if "tools" in anthropic_message_request: @@ -907,7 +948,10 @@ class LiteLLMAnthropicMessagesAdapter: # Only translate regular tools (non-web-search) if regular_tools: - new_kwargs["tools"], tool_name_mapping = self.translate_anthropic_tools_to_openai( + ( + new_kwargs["tools"], + tool_name_mapping, + ) = self.translate_anthropic_tools_to_openai( tools=cast(List[AllAnthropicToolsValues], regular_tools), model=new_kwargs.get("model"), ) @@ -920,8 +964,10 @@ class LiteLLMAnthropicMessagesAdapter: if self.is_anthropic_claude_model(model): new_kwargs["thinking"] = thinking # type: ignore else: - reasoning_effort = self.translate_anthropic_thinking_to_reasoning_effort( - cast(Dict[str, Any], thinking) + reasoning_effort = ( + self.translate_anthropic_thinking_to_reasoning_effort( + cast(Dict[str, Any], thinking) + ) ) if reasoning_effort: new_kwargs["reasoning_effort"] = reasoning_effort @@ -1108,15 +1154,22 @@ class LiteLLMAnthropicMessagesAdapter: uncached_input_tokens = usage.prompt_tokens or 0 cached_tokens = 0 if hasattr(usage, "prompt_tokens_details") and usage.prompt_tokens_details: - cached_tokens = getattr(usage.prompt_tokens_details, "cached_tokens", 0) or 0 + cached_tokens = ( + getattr(usage.prompt_tokens_details, "cached_tokens", 0) or 0 + ) uncached_input_tokens -= cached_tokens anthropic_usage = AnthropicUsage( input_tokens=uncached_input_tokens, output_tokens=usage.completion_tokens or 0, ) - if hasattr(usage, "_cache_creation_input_tokens") and usage._cache_creation_input_tokens > 0: - anthropic_usage["cache_creation_input_tokens"] = usage._cache_creation_input_tokens + if ( + hasattr(usage, "_cache_creation_input_tokens") + and usage._cache_creation_input_tokens > 0 + ): + anthropic_usage[ + "cache_creation_input_tokens" + ] = usage._cache_creation_input_tokens if cached_tokens > 0: anthropic_usage["cache_read_input_tokens"] = cached_tokens @@ -1191,7 +1244,6 @@ class LiteLLMAnthropicMessagesAdapter: ContentThinkingSignatureBlockDelta, ], ]: - text: str = "" reasoning_content: str = "" reasoning_signature: str = "" @@ -1272,16 +1324,31 @@ class LiteLLMAnthropicMessagesAdapter: if litellm_usage_chunk is not None: uncached_input_tokens = litellm_usage_chunk.prompt_tokens or 0 cached_tokens = 0 - if hasattr(litellm_usage_chunk, "prompt_tokens_details") and litellm_usage_chunk.prompt_tokens_details: - cached_tokens = getattr(litellm_usage_chunk.prompt_tokens_details, "cached_tokens", 0) or 0 + if ( + hasattr(litellm_usage_chunk, "prompt_tokens_details") + and litellm_usage_chunk.prompt_tokens_details + ): + cached_tokens = ( + getattr( + litellm_usage_chunk.prompt_tokens_details, + "cached_tokens", + 0, + ) + or 0 + ) uncached_input_tokens -= cached_tokens usage_delta = UsageDelta( input_tokens=uncached_input_tokens, output_tokens=litellm_usage_chunk.completion_tokens or 0, ) - if hasattr(litellm_usage_chunk, "_cache_creation_input_tokens") and litellm_usage_chunk._cache_creation_input_tokens > 0: - usage_delta["cache_creation_input_tokens"] = litellm_usage_chunk._cache_creation_input_tokens + if ( + hasattr(litellm_usage_chunk, "_cache_creation_input_tokens") + and litellm_usage_chunk._cache_creation_input_tokens > 0 + ): + usage_delta[ + "cache_creation_input_tokens" + ] = litellm_usage_chunk._cache_creation_input_tokens if cached_tokens > 0: usage_delta["cache_read_input_tokens"] = cached_tokens else: diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/fake_stream_iterator.py b/litellm/llms/anthropic/experimental_pass_through/messages/fake_stream_iterator.py index 542ae20b602..80afea78504 100644 --- a/litellm/llms/anthropic/experimental_pass_through/messages/fake_stream_iterator.py +++ b/litellm/llms/anthropic/experimental_pass_through/messages/fake_stream_iterator.py @@ -19,11 +19,11 @@ from litellm.types.llms.anthropic_messages.anthropic_response import ( class FakeAnthropicMessagesStreamIterator: """ Fake streaming iterator for Anthropic Messages responses. - + Used when we need to convert a non-streaming response to a streaming format, such as when WebSearch interception converts stream=True to stream=False but the LLM doesn't make a tool call. - + This creates a proper Anthropic-style streaming response with multiple events: - message_start - content_block_start (for each content block) @@ -32,19 +32,19 @@ class FakeAnthropicMessagesStreamIterator: - message_delta (for usage) - message_stop """ - + def __init__(self, response: AnthropicMessagesResponse): self.response = response self.chunks = self._create_streaming_chunks() self.current_index = 0 - + def _create_streaming_chunks(self) -> List[bytes]: """Convert the non-streaming response to streaming chunks""" chunks = [] - + # Cast response to dict for easier access response_dict = cast(Dict[str, Any], self.response) - + # 1. message_start event usage = response_dict.get("usage", {}) message_start = { @@ -59,12 +59,14 @@ class FakeAnthropicMessagesStreamIterator: "stop_sequence": None, "usage": { "input_tokens": usage.get("input_tokens", 0) if usage else 0, - "output_tokens": 0 - } - } + "output_tokens": 0, + }, + }, } - chunks.append(f"event: message_start\ndata: {json.dumps(message_start)}\n\n".encode()) - + chunks.append( + f"event: message_start\ndata: {json.dumps(message_start)}\n\n".encode() + ) + # 2-4. For each content block, send start/delta/stop events content_blocks = response_dict.get("content", []) if content_blocks: @@ -72,38 +74,35 @@ class FakeAnthropicMessagesStreamIterator: # Cast block to dict for easier access block_dict = cast(Dict[str, Any], block) block_type = block_dict.get("type") - + if block_type == "text": # content_block_start content_block_start = { "type": "content_block_start", "index": index, - "content_block": { - "type": "text", - "text": "" - } + "content_block": {"type": "text", "text": ""}, } - chunks.append(f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode()) - + chunks.append( + f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode() + ) + # content_block_delta (send full text as one delta for simplicity) text = block_dict.get("text", "") content_block_delta = { "type": "content_block_delta", "index": index, - "delta": { - "type": "text_delta", - "text": text - } + "delta": {"type": "text_delta", "text": text}, } - chunks.append(f"event: content_block_delta\ndata: {json.dumps(content_block_delta)}\n\n".encode()) - + chunks.append( + f"event: content_block_delta\ndata: {json.dumps(content_block_delta)}\n\n".encode() + ) + # content_block_stop - content_block_stop = { - "type": "content_block_stop", - "index": index - } - chunks.append(f"event: content_block_stop\ndata: {json.dumps(content_block_stop)}\n\n".encode()) - + content_block_stop = {"type": "content_block_stop", "index": index} + chunks.append( + f"event: content_block_stop\ndata: {json.dumps(content_block_stop)}\n\n".encode() + ) + elif block_type == "thinking": # content_block_start for thinking content_block_start = { @@ -112,11 +111,13 @@ class FakeAnthropicMessagesStreamIterator: "content_block": { "type": "thinking", "thinking": "", - "signature": "" - } + "signature": "", + }, } - chunks.append(f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode()) - + chunks.append( + f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode() + ) + # content_block_delta for thinking text thinking_text = block_dict.get("thinking", "") if thinking_text: @@ -125,11 +126,13 @@ class FakeAnthropicMessagesStreamIterator: "index": index, "delta": { "type": "thinking_delta", - "thinking": thinking_text - } + "thinking": thinking_text, + }, } - chunks.append(f"event: content_block_delta\ndata: {json.dumps(content_block_delta)}\n\n".encode()) - + chunks.append( + f"event: content_block_delta\ndata: {json.dumps(content_block_delta)}\n\n".encode() + ) + # content_block_delta for signature (if present) signature = block_dict.get("signature", "") if signature: @@ -138,36 +141,36 @@ class FakeAnthropicMessagesStreamIterator: "index": index, "delta": { "type": "signature_delta", - "signature": signature - } + "signature": signature, + }, } - chunks.append(f"event: content_block_delta\ndata: {json.dumps(signature_delta)}\n\n".encode()) - + chunks.append( + f"event: content_block_delta\ndata: {json.dumps(signature_delta)}\n\n".encode() + ) + # content_block_stop - content_block_stop = { - "type": "content_block_stop", - "index": index - } - chunks.append(f"event: content_block_stop\ndata: {json.dumps(content_block_stop)}\n\n".encode()) - + content_block_stop = {"type": "content_block_stop", "index": index} + chunks.append( + f"event: content_block_stop\ndata: {json.dumps(content_block_stop)}\n\n".encode() + ) + elif block_type == "redacted_thinking": # content_block_start for redacted_thinking content_block_start = { "type": "content_block_start", "index": index, - "content_block": { - "type": "redacted_thinking" - } + "content_block": {"type": "redacted_thinking"}, } - chunks.append(f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode()) - + chunks.append( + f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode() + ) + # content_block_stop (no delta for redacted thinking) - content_block_stop = { - "type": "content_block_stop", - "index": index - } - chunks.append(f"event: content_block_stop\ndata: {json.dumps(content_block_stop)}\n\n".encode()) - + content_block_stop = {"type": "content_block_stop", "index": index} + chunks.append( + f"event: content_block_stop\ndata: {json.dumps(content_block_stop)}\n\n".encode() + ) + elif block_type == "tool_use": # content_block_start content_block_start = { @@ -177,11 +180,13 @@ class FakeAnthropicMessagesStreamIterator: "type": "tool_use", "id": block_dict.get("id"), "name": block_dict.get("name"), - "input": {} - } + "input": {}, + }, } - chunks.append(f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode()) - + chunks.append( + f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode() + ) + # content_block_delta (send input as JSON delta) input_data = block_dict.get("input", {}) content_block_delta = { @@ -189,58 +194,58 @@ class FakeAnthropicMessagesStreamIterator: "index": index, "delta": { "type": "input_json_delta", - "partial_json": json.dumps(input_data) - } + "partial_json": json.dumps(input_data), + }, } - chunks.append(f"event: content_block_delta\ndata: {json.dumps(content_block_delta)}\n\n".encode()) - + chunks.append( + f"event: content_block_delta\ndata: {json.dumps(content_block_delta)}\n\n".encode() + ) + # content_block_stop - content_block_stop = { - "type": "content_block_stop", - "index": index - } - chunks.append(f"event: content_block_stop\ndata: {json.dumps(content_block_stop)}\n\n".encode()) - + content_block_stop = {"type": "content_block_stop", "index": index} + chunks.append( + f"event: content_block_stop\ndata: {json.dumps(content_block_stop)}\n\n".encode() + ) + # 5. message_delta event (with final usage and stop_reason) message_delta = { "type": "message_delta", "delta": { "stop_reason": response_dict.get("stop_reason"), - "stop_sequence": response_dict.get("stop_sequence") + "stop_sequence": response_dict.get("stop_sequence"), }, - "usage": { - "output_tokens": usage.get("output_tokens", 0) if usage else 0 - } + "usage": {"output_tokens": usage.get("output_tokens", 0) if usage else 0}, } - chunks.append(f"event: message_delta\ndata: {json.dumps(message_delta)}\n\n".encode()) - + chunks.append( + f"event: message_delta\ndata: {json.dumps(message_delta)}\n\n".encode() + ) + # 6. message_stop event - message_stop = { - "type": "message_stop", - "usage": usage if usage else {} - } - chunks.append(f"event: message_stop\ndata: {json.dumps(message_stop)}\n\n".encode()) - + message_stop = {"type": "message_stop", "usage": usage if usage else {}} + chunks.append( + f"event: message_stop\ndata: {json.dumps(message_stop)}\n\n".encode() + ) + return chunks - + def __aiter__(self): return self - + async def __anext__(self): if self.current_index >= len(self.chunks): raise StopAsyncIteration - + chunk = self.chunks[self.current_index] self.current_index += 1 return chunk - + def __iter__(self): return self - + def __next__(self): if self.current_index >= len(self.chunks): raise StopIteration - + chunk = self.chunks[self.current_index] self.current_index += 1 return chunk diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/handler.py b/litellm/llms/anthropic/experimental_pass_through/messages/handler.py index 5b215c1fe54..1b5f03ec722 100644 --- a/litellm/llms/anthropic/experimental_pass_through/messages/handler.py +++ b/litellm/llms/anthropic/experimental_pass_through/messages/handler.py @@ -43,6 +43,7 @@ def _should_route_to_responses_api(custom_llm_provider: Optional[str]) -> bool: return False return custom_llm_provider in _RESPONSES_API_PROVIDERS + ####### ENVIRONMENT VARIABLES ################### # Initialize any necessary instances or variables here base_llm_http_handler = BaseLLMHTTPHandler() @@ -229,7 +230,7 @@ def anthropic_messages_handler( ]: """ Makes Anthropic `/v1/messages` API calls In the Anthropic API Spec - + Args: container: Container config with skills for code execution """ @@ -263,7 +264,7 @@ def anthropic_messages_handler( api_base=litellm_params.api_base, api_key=litellm_params.api_key, ) - + # Store agentic loop params in logging object for agentic hooks # This provides original request context needed for follow-up calls if litellm_logging_obj is not None: @@ -271,14 +272,15 @@ def anthropic_messages_handler( "model": original_model, "custom_llm_provider": custom_llm_provider, } - + # Check if stream was converted for WebSearch interception # This is set in the async wrapper above when stream=True is converted to stream=False if kwargs.get("_websearch_interception_converted_stream", False): - litellm_logging_obj.model_call_details["websearch_interception_converted_stream"] = True + litellm_logging_obj.model_call_details[ + "websearch_interception_converted_stream" + ] = True if litellm_params.mock_response and isinstance(litellm_params.mock_response, str): - return mock_response( model=model, messages=messages, @@ -324,8 +326,10 @@ def anthropic_messages_handler( return LiteLLMMessagesToResponsesAPIHandler.anthropic_messages_handler( **_shared_kwargs ) - return LiteLLMMessagesToCompletionTransformationHandler.anthropic_messages_handler( - **_shared_kwargs + return ( + LiteLLMMessagesToCompletionTransformationHandler.anthropic_messages_handler( + **_shared_kwargs + ) ) if custom_llm_provider is None: diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.py b/litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.py index df106c0e696..6cab38932ae 100644 --- a/litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.py +++ b/litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.py @@ -12,6 +12,7 @@ from litellm.types.utils import GenericStreamingChunk, ModelResponseStream GLOBAL_PASS_THROUGH_SUCCESS_HANDLER_OBJ = PassThroughEndpointLogging() + class BaseAnthropicMessagesStreamingIterator: """ Base class for Anthropic Messages streaming iterators that provides common logic @@ -27,7 +28,6 @@ class BaseAnthropicMessagesStreamingIterator: self.request_body = request_body self.start_time = datetime.now() - async def _handle_streaming_logging(self, collected_chunks: List[bytes]): """Handle the logging after all chunks have been collected.""" from litellm.proxy.pass_through_endpoints.streaming_handler import ( @@ -47,7 +47,7 @@ class BaseAnthropicMessagesStreamingIterator: end_time=end_time, ) ) - + def get_async_streaming_response_iterator( self, httpx_response, @@ -73,7 +73,7 @@ class BaseAnthropicMessagesStreamingIterator: def _convert_chunk_to_sse_format(self, chunk: Union[dict, Any]) -> bytes: """ Convert a chunk to Server-Sent Events format. - + This method should be overridden by subclasses if they need custom chunk formatting logic. """ @@ -94,15 +94,15 @@ class BaseAnthropicMessagesStreamingIterator: """ Generic async SSE wrapper that converts streaming chunks to SSE format and handles logging. - + This method provides the common logic for both Anthropic and Bedrock implementations. """ collected_chunks = [] - + async for chunk in completion_stream: encoded_chunk = self._convert_chunk_to_sse_format(chunk) collected_chunks.append(encoded_chunk) yield encoded_chunk - + # Handle logging after all chunks are processed - await self._handle_streaming_logging(collected_chunks) \ No newline at end of file + await self._handle_streaming_logging(collected_chunks) diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py b/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py index e8d7a0383fb..4d0a2cd829b 100644 --- a/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py +++ b/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py @@ -165,15 +165,21 @@ class AnthropicMessagesConfig(BaseAnthropicMessagesConfig): anthropic_messages_optional_request_params.pop("system", None) # Transform context_management from OpenAI format to Anthropic format if needed - context_management_param = anthropic_messages_optional_request_params.get("context_management") + context_management_param = anthropic_messages_optional_request_params.get( + "context_management" + ) if context_management_param is not None: from litellm.llms.anthropic.chat.transformation import AnthropicConfig - - transformed_context_management = AnthropicConfig.map_openai_context_management_to_anthropic( - context_management_param + + transformed_context_management = ( + AnthropicConfig.map_openai_context_management_to_anthropic( + context_management_param + ) ) if transformed_context_management is not None: - anthropic_messages_optional_request_params["context_management"] = transformed_context_management + anthropic_messages_optional_request_params[ + "context_management" + ] = transformed_context_management ####### get required params for all anthropic messages requests ###### verbose_logger.debug(f"TRANSFORMATION DEBUG - Messages: {messages}") diff --git a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/handler.py b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/handler.py index ebc7d136f6e..198ebe1ff8c 100644 --- a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/handler.py +++ b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/handler.py @@ -43,7 +43,11 @@ def _build_responses_kwargs( Build the kwargs dict to pass directly to litellm.responses() / litellm.aresponses(). """ # Build a typed AnthropicMessagesRequest for the adapter - request_data: Dict[str, Any] = {"model": model, "messages": messages, "max_tokens": max_tokens} + request_data: Dict[str, Any] = { + "model": model, + "messages": messages, + "max_tokens": max_tokens, + } if context_management: request_data["context_management"] = context_management if output_config: @@ -142,7 +146,9 @@ class LiteLLMMessagesToResponsesAPIHandler: result = await litellm.aresponses(**responses_kwargs) if stream: - wrapper = AnthropicResponsesStreamWrapper(responses_stream=result, model=model) + wrapper = AnthropicResponsesStreamWrapper( + responses_stream=result, model=model + ) return wrapper.async_anthropic_sse_wrapper() if not isinstance(result, ResponsesAPIResponse): @@ -176,24 +182,26 @@ class LiteLLMMessagesToResponsesAPIHandler: Coroutine[Any, Any, Union[AnthropicMessagesResponse, AsyncIterator[Any]]], ]: if _is_async: - return LiteLLMMessagesToResponsesAPIHandler.async_anthropic_messages_handler( - max_tokens=max_tokens, - messages=messages, - model=model, - context_management=context_management, - metadata=metadata, - output_config=output_config, - stop_sequences=stop_sequences, - stream=stream, - system=system, - temperature=temperature, - thinking=thinking, - tool_choice=tool_choice, - tools=tools, - top_k=top_k, - top_p=top_p, - output_format=output_format, - **kwargs, + return ( + LiteLLMMessagesToResponsesAPIHandler.async_anthropic_messages_handler( + max_tokens=max_tokens, + messages=messages, + model=model, + context_management=context_management, + metadata=metadata, + output_config=output_config, + stop_sequences=stop_sequences, + stream=stream, + system=system, + temperature=temperature, + thinking=thinking, + tool_choice=tool_choice, + tools=tools, + top_k=top_k, + top_p=top_p, + output_format=output_format, + **kwargs, + ) ) # Sync path @@ -220,7 +228,9 @@ class LiteLLMMessagesToResponsesAPIHandler: result = litellm.responses(**responses_kwargs) if stream: - wrapper = AnthropicResponsesStreamWrapper(responses_stream=result, model=model) + wrapper = AnthropicResponsesStreamWrapper( + responses_stream=result, model=model + ) return wrapper.async_anthropic_sse_wrapper() if not isinstance(result, ResponsesAPIResponse): diff --git a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/streaming_iterator.py b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/streaming_iterator.py index 926719c4abf..aa0738a0719 100644 --- a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/streaming_iterator.py +++ b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/streaming_iterator.py @@ -35,7 +35,9 @@ class AnthropicResponsesStreamWrapper: # Map item_id -> content_block_index so we can stop the right block later self._item_id_to_block_index: Dict[str, int] = {} # Track open function_call items by item_id so we can emit tool_use start - self._pending_tool_ids: Dict[str, str] = {} # item_id -> call_id / name accumulator + self._pending_tool_ids: Dict[ + str, str + ] = {} # item_id -> call_id / name accumulator self._sent_message_start = False self._sent_message_stop = False self._chunk_queue: deque = deque() @@ -81,99 +83,168 @@ class AnthropicResponsesStreamWrapper: # ---- content_block_start for a new output message item ---- if event_type == "response.output_item.added": - item = getattr(event, "item", None) or (event.get("item") if isinstance(event, dict) else None) + item = getattr(event, "item", None) or ( + event.get("item") if isinstance(event, dict) else None + ) if item is None: return - item_type = getattr(item, "type", None) or (item.get("type") if isinstance(item, dict) else None) - item_id = getattr(item, "id", None) or (item.get("id") if isinstance(item, dict) else None) + item_type = getattr(item, "type", None) or ( + item.get("type") if isinstance(item, dict) else None + ) + item_id = getattr(item, "id", None) or ( + item.get("id") if isinstance(item, dict) else None + ) if item_type == "message": block_idx = self._next_block_index() if item_id: self._item_id_to_block_index[item_id] = block_idx - self._chunk_queue.append({ - "type": "content_block_start", - "index": block_idx, - "content_block": {"type": "text", "text": ""}, - }) + self._chunk_queue.append( + { + "type": "content_block_start", + "index": block_idx, + "content_block": {"type": "text", "text": ""}, + } + ) elif item_type == "function_call": - call_id = getattr(item, "call_id", None) or (item.get("call_id") if isinstance(item, dict) else None) or "" - name = getattr(item, "name", None) or (item.get("name") if isinstance(item, dict) else None) or "" + call_id = ( + getattr(item, "call_id", None) + or (item.get("call_id") if isinstance(item, dict) else None) + or "" + ) + name = ( + getattr(item, "name", None) + or (item.get("name") if isinstance(item, dict) else None) + or "" + ) block_idx = self._next_block_index() if item_id: self._item_id_to_block_index[item_id] = block_idx self._pending_tool_ids[item_id] = call_id - self._chunk_queue.append({ - "type": "content_block_start", - "index": block_idx, - "content_block": { - "type": "tool_use", - "id": call_id, - "name": name, - "input": {}, - }, - }) + self._chunk_queue.append( + { + "type": "content_block_start", + "index": block_idx, + "content_block": { + "type": "tool_use", + "id": call_id, + "name": name, + "input": {}, + }, + } + ) elif item_type == "reasoning": block_idx = self._next_block_index() if item_id: self._item_id_to_block_index[item_id] = block_idx - self._chunk_queue.append({ - "type": "content_block_start", - "index": block_idx, - "content_block": {"type": "thinking", "thinking": ""}, - }) + self._chunk_queue.append( + { + "type": "content_block_start", + "index": block_idx, + "content_block": {"type": "thinking", "thinking": ""}, + } + ) return # ---- text delta ---- if event_type == "response.output_text.delta": - item_id = getattr(event, "item_id", None) or (event.get("item_id") if isinstance(event, dict) else None) - delta = getattr(event, "delta", "") or (event.get("delta", "") if isinstance(event, dict) else "") - block_idx = self._item_id_to_block_index.get(item_id, self._current_block_index) if item_id else self._current_block_index - self._chunk_queue.append({ - "type": "content_block_delta", - "index": block_idx, - "delta": {"type": "text_delta", "text": delta}, - }) + item_id = getattr(event, "item_id", None) or ( + event.get("item_id") if isinstance(event, dict) else None + ) + delta = getattr(event, "delta", "") or ( + event.get("delta", "") if isinstance(event, dict) else "" + ) + block_idx = ( + self._item_id_to_block_index.get(item_id, self._current_block_index) + if item_id + else self._current_block_index + ) + self._chunk_queue.append( + { + "type": "content_block_delta", + "index": block_idx, + "delta": {"type": "text_delta", "text": delta}, + } + ) return # ---- reasoning summary text delta ---- if event_type == "response.reasoning_summary_text.delta": - item_id = getattr(event, "item_id", None) or (event.get("item_id") if isinstance(event, dict) else None) - delta = getattr(event, "delta", "") or (event.get("delta", "") if isinstance(event, dict) else "") - block_idx = self._item_id_to_block_index.get(item_id, self._current_block_index) if item_id else self._current_block_index - self._chunk_queue.append({ - "type": "content_block_delta", - "index": block_idx, - "delta": {"type": "thinking_delta", "thinking": delta}, - }) + item_id = getattr(event, "item_id", None) or ( + event.get("item_id") if isinstance(event, dict) else None + ) + delta = getattr(event, "delta", "") or ( + event.get("delta", "") if isinstance(event, dict) else "" + ) + block_idx = ( + self._item_id_to_block_index.get(item_id, self._current_block_index) + if item_id + else self._current_block_index + ) + self._chunk_queue.append( + { + "type": "content_block_delta", + "index": block_idx, + "delta": {"type": "thinking_delta", "thinking": delta}, + } + ) return # ---- function call arguments delta ---- if event_type == "response.function_call_arguments.delta": - item_id = getattr(event, "item_id", None) or (event.get("item_id") if isinstance(event, dict) else None) - delta = getattr(event, "delta", "") or (event.get("delta", "") if isinstance(event, dict) else "") - block_idx = self._item_id_to_block_index.get(item_id, self._current_block_index) if item_id else self._current_block_index - self._chunk_queue.append({ - "type": "content_block_delta", - "index": block_idx, - "delta": {"type": "input_json_delta", "partial_json": delta}, - }) + item_id = getattr(event, "item_id", None) or ( + event.get("item_id") if isinstance(event, dict) else None + ) + delta = getattr(event, "delta", "") or ( + event.get("delta", "") if isinstance(event, dict) else "" + ) + block_idx = ( + self._item_id_to_block_index.get(item_id, self._current_block_index) + if item_id + else self._current_block_index + ) + self._chunk_queue.append( + { + "type": "content_block_delta", + "index": block_idx, + "delta": {"type": "input_json_delta", "partial_json": delta}, + } + ) return # ---- output item done -> content_block_stop ---- if event_type == "response.output_item.done": - item = getattr(event, "item", None) or (event.get("item") if isinstance(event, dict) else None) - item_id = getattr(item, "id", None) or (item.get("id") if isinstance(item, dict) else None) if item else None - block_idx = self._item_id_to_block_index.get(item_id, self._current_block_index) if item_id else self._current_block_index - self._chunk_queue.append({ - "type": "content_block_stop", - "index": block_idx, - }) + item = getattr(event, "item", None) or ( + event.get("item") if isinstance(event, dict) else None + ) + item_id = ( + getattr(item, "id", None) + or (item.get("id") if isinstance(item, dict) else None) + if item + else None + ) + block_idx = ( + self._item_id_to_block_index.get(item_id, self._current_block_index) + if item_id + else self._current_block_index + ) + self._chunk_queue.append( + { + "type": "content_block_stop", + "index": block_idx, + } + ) return # ---- response completed -> message_delta + message_stop ---- - if event_type in ("response.completed", "response.failed", "response.incomplete"): - response_obj = getattr(event, "response", None) or (event.get("response") if isinstance(event, dict) else None) + if event_type in ( + "response.completed", + "response.failed", + "response.incomplete", + ): + response_obj = getattr(event, "response", None) or ( + event.get("response") if isinstance(event, dict) else None + ) stop_reason = "end_turn" input_tokens = 0 output_tokens = 0 @@ -191,14 +262,20 @@ class AnthropicResponsesStreamWrapper: cache_creation_tokens = getattr(usage, "input_tokens_details", None) # type: ignore[assignment] cache_read_tokens = getattr(usage, "output_tokens_details", None) # type: ignore[assignment] # Prefer direct cache fields if present - cache_creation_tokens = int(getattr(usage, "cache_creation_input_tokens", 0) or 0) - cache_read_tokens = int(getattr(usage, "cache_read_input_tokens", 0) or 0) + cache_creation_tokens = int( + getattr(usage, "cache_creation_input_tokens", 0) or 0 + ) + cache_read_tokens = int( + getattr(usage, "cache_read_input_tokens", 0) or 0 + ) # Check if tool_use was in the output to override stop_reason if response_obj is not None: output = getattr(response_obj, "output", []) or [] for out_item in output: - out_type = getattr(out_item, "type", None) or (out_item.get("type") if isinstance(out_item, dict) else None) + out_type = getattr(out_item, "type", None) or ( + out_item.get("type") if isinstance(out_item, dict) else None + ) if out_type == "function_call": stop_reason = "tool_use" break @@ -212,11 +289,13 @@ class AnthropicResponsesStreamWrapper: if cache_read_tokens: usage_delta["cache_read_input_tokens"] = cache_read_tokens - self._chunk_queue.append({ - "type": "message_delta", - "delta": {"stop_reason": stop_reason, "stop_sequence": None}, - "usage": usage_delta, - }) + self._chunk_queue.append( + { + "type": "message_delta", + "delta": {"stop_reason": stop_reason, "stop_sequence": None}, + "usage": usage_delta, + } + ) self._chunk_queue.append({"type": "message_stop"}) self._sent_message_stop = True return diff --git a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/transformation.py b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/transformation.py index 935babe4380..ddd514146df 100644 --- a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/transformation.py +++ b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/transformation.py @@ -75,11 +75,13 @@ class LiteLLMAnthropicToResponsesAPIAdapter: if role == "user": if isinstance(content, str): - input_items.append({ - "type": "message", - "role": "user", - "content": [{"type": "input_text", "text": content}], - }) + input_items.append( + { + "type": "message", + "role": "user", + "content": [{"type": "input_text", "text": content}], + } + ) elif isinstance(content, list): user_parts: List[Dict[str, Any]] = [] for block in content: @@ -87,11 +89,17 @@ class LiteLLMAnthropicToResponsesAPIAdapter: continue btype = block.get("type") if btype == "text": - user_parts.append({"type": "input_text", "text": block.get("text", "")}) + user_parts.append( + {"type": "input_text", "text": block.get("text", "")} + ) elif btype == "image": - url = self._translate_anthropic_image_source_to_url(block.get("source", {})) + url = self._translate_anthropic_image_source_to_url( + block.get("source", {}) + ) if url: - user_parts.append({"type": "input_image", "image_url": url}) + user_parts.append( + {"type": "input_image", "image_url": url} + ) elif btype == "tool_result": tool_use_id = block.get("tool_use_id", "") inner = block.get("content") @@ -109,25 +117,31 @@ class LiteLLMAnthropicToResponsesAPIAdapter: else: output_text = str(inner) # tool_result is a top-level item, not inside the message - input_items.append({ - "type": "function_call_output", - "call_id": tool_use_id, - "output": output_text, - }) + input_items.append( + { + "type": "function_call_output", + "call_id": tool_use_id, + "output": output_text, + } + ) if user_parts: - input_items.append({ - "type": "message", - "role": "user", - "content": user_parts, - }) + input_items.append( + { + "type": "message", + "role": "user", + "content": user_parts, + } + ) elif role == "assistant": if isinstance(content, str): - input_items.append({ - "type": "message", - "role": "assistant", - "content": [{"type": "output_text", "text": content}], - }) + input_items.append( + { + "type": "message", + "role": "assistant", + "content": [{"type": "output_text", "text": content}], + } + ) elif isinstance(content, list): asst_parts: List[Dict[str, Any]] = [] for block in content: @@ -135,25 +149,33 @@ class LiteLLMAnthropicToResponsesAPIAdapter: continue btype = block.get("type") if btype == "text": - asst_parts.append({"type": "output_text", "text": block.get("text", "")}) + asst_parts.append( + {"type": "output_text", "text": block.get("text", "")} + ) elif btype == "tool_use": # tool_use becomes a top-level function_call item - input_items.append({ - "type": "function_call", - "call_id": block.get("id", ""), - "name": block.get("name", ""), - "arguments": json.dumps(block.get("input", {})), - }) + input_items.append( + { + "type": "function_call", + "call_id": block.get("id", ""), + "name": block.get("name", ""), + "arguments": json.dumps(block.get("input", {})), + } + ) elif btype == "thinking": thinking_text = block.get("thinking", "") if thinking_text: - asst_parts.append({"type": "output_text", "text": thinking_text}) + asst_parts.append( + {"type": "output_text", "text": thinking_text} + ) if asst_parts: - input_items.append({ - "type": "message", - "role": "assistant", - "content": asst_parts, - }) + input_items.append( + { + "type": "message", + "role": "assistant", + "content": asst_parts, + } + ) return input_items @@ -168,7 +190,9 @@ class LiteLLMAnthropicToResponsesAPIAdapter: tool_type = tool_dict.get("type", "") tool_name = tool_dict.get("name", "") # web_search tool - if (isinstance(tool_type, str) and tool_type.startswith("web_search")) or tool_name == "web_search": + if ( + isinstance(tool_type, str) and tool_type.startswith("web_search") + ) or tool_name == "web_search": result.append({"type": "web_search_preview"}) continue func_tool: Dict[str, Any] = {"type": "function", "name": tool_name} @@ -223,7 +247,9 @@ class LiteLLMAnthropicToResponsesAPIAdapter: return result if result else None @staticmethod - def translate_thinking_to_reasoning(thinking: Dict[str, Any]) -> Optional[Dict[str, Any]]: + def translate_thinking_to_reasoning( + thinking: Dict[str, Any] + ) -> Optional[Dict[str, Any]]: """ Convert Anthropic thinking param to Responses API reasoning param. @@ -253,7 +279,12 @@ class LiteLLMAnthropicToResponsesAPIAdapter: """ model: str = anthropic_request["model"] messages_list = cast( - List[Union[AnthropicMessagesUserMessageParam, AnthopicMessagesAssistantMessageParam]], + List[ + Union[ + AnthropicMessagesUserMessageParam, + AnthopicMessagesAssistantMessageParam, + ] + ], anthropic_request["messages"], ) @@ -296,7 +327,9 @@ class LiteLLMAnthropicToResponsesAPIAdapter: # tool_choice tool_choice = anthropic_request.get("tool_choice") if tool_choice: - responses_kwargs["tool_choice"] = self.translate_tool_choice_to_responses_api( + responses_kwargs[ + "tool_choice" + ] = self.translate_tool_choice_to_responses_api( cast(AnthropicMessagesToolChoice, tool_choice) ) @@ -314,7 +347,10 @@ class LiteLLMAnthropicToResponsesAPIAdapter: output_config = anthropic_request.get("output_config") if not isinstance(output_format, dict) and isinstance(output_config, dict): output_format = output_config.get("format") # type: ignore[assignment] - if isinstance(output_format, dict) and output_format.get("type") == "json_schema": + if ( + isinstance(output_format, dict) + and output_format.get("type") == "json_schema" + ): schema = output_format.get("schema") if schema: responses_kwargs["text"] = { @@ -329,7 +365,9 @@ class LiteLLMAnthropicToResponsesAPIAdapter: # context_management: Anthropic dict -> OpenAI array context_management = anthropic_request.get("context_management") if isinstance(context_management, dict): - openai_cm = self.translate_context_management_to_responses_api(context_management) + openai_cm = self.translate_context_management_to_responses_api( + context_management + ) if openai_cm is not None: responses_kwargs["context_management"] = openai_cm diff --git a/litellm/llms/anthropic/files/__init__.py b/litellm/llms/anthropic/files/__init__.py index b8b538ffb62..78c9dc89f70 100644 --- a/litellm/llms/anthropic/files/__init__.py +++ b/litellm/llms/anthropic/files/__init__.py @@ -1,4 +1,4 @@ from .handler import AnthropicFilesHandler +from .transformation import AnthropicFilesConfig -__all__ = ["AnthropicFilesHandler"] - +__all__ = ["AnthropicFilesHandler", "AnthropicFilesConfig"] diff --git a/litellm/llms/anthropic/files/handler.py b/litellm/llms/anthropic/files/handler.py index d46fc401310..77cc8c27316 100644 --- a/litellm/llms/anthropic/files/handler.py +++ b/litellm/llms/anthropic/files/handler.py @@ -40,7 +40,7 @@ ANTHROPIC_ERROR_STATUS_CODE_MAP = { class AnthropicFilesHandler: """ Handles Anthropic Files API operations. - + Currently supports: - file_content() for retrieving Anthropic Message Batch results """ @@ -58,17 +58,17 @@ class AnthropicFilesHandler: ) -> HttpxBinaryResponseContent: """ Async: Retrieve file content from Anthropic. - + For batch results, the file_id should be the batch_id. This will call Anthropic's /v1/messages/batches/{batch_id}/results endpoint. - + Args: file_content_request: Contains file_id (batch_id for batch results) api_base: Anthropic API base URL api_key: Anthropic API key timeout: Request timeout max_retries: Max retry attempts (unused for now) - + Returns: HttpxBinaryResponseContent: Binary content wrapped in compatible response format """ @@ -102,10 +102,7 @@ class AnthropicFilesHandler: # Make the request to Anthropic async_client = get_async_httpx_client(llm_provider=LlmProviders.ANTHROPIC) - anthropic_response = await async_client.get( - url=results_url, - headers=headers - ) + anthropic_response = await async_client.get(url=results_url, headers=headers) anthropic_response.raise_for_status() # Transform Anthropic batch results to OpenAI format @@ -124,7 +121,6 @@ class AnthropicFilesHandler: # Return the transformed response content return HttpxBinaryResponseContent(response=transformed_response) - def file_content( self, _is_async: bool, @@ -138,10 +134,10 @@ class AnthropicFilesHandler: ]: """ Retrieve file content from Anthropic. - + For batch results, the file_id should be the batch_id. This will call Anthropic's /v1/messages/batches/{batch_id}/results endpoint. - + Args: _is_async: Whether to run asynchronously file_content_request: Contains file_id (batch_id for batch results) @@ -149,7 +145,7 @@ class AnthropicFilesHandler: api_key: Anthropic API key timeout: Request timeout max_retries: Max retry attempts (unused for now) - + Returns: HttpxBinaryResponseContent or Coroutine: Binary content wrapped in compatible response format """ @@ -176,7 +172,7 @@ class AnthropicFilesHandler: ) -> bytes: """ Transform Anthropic batch results JSONL to OpenAI batch results JSONL format. - + Anthropic format: { "custom_id": "...", @@ -185,7 +181,7 @@ class AnthropicFilesHandler: "message": { ... } // Anthropic message format } } - + OpenAI format: { "custom_id": "...", @@ -199,28 +195,30 @@ class AnthropicFilesHandler: try: anthropic_config = AnthropicConfig() transformed_lines = [] - + # Parse JSONL content content_str = anthropic_content.decode("utf-8") for line in content_str.strip().split("\n"): if not line.strip(): continue - + anthropic_result = json.loads(line) custom_id = anthropic_result.get("custom_id", "") result = anthropic_result.get("result", {}) result_type = result.get("type", "") - + # Transform based on result type if result_type == "succeeded": # Transform Anthropic message to OpenAI format anthropic_message = result.get("message", {}) if anthropic_message: - openai_response_body = self._transform_anthropic_message_to_openai_format( - anthropic_message=anthropic_message, - anthropic_config=anthropic_config, + openai_response_body = ( + self._transform_anthropic_message_to_openai_format( + anthropic_message=anthropic_message, + anthropic_config=anthropic_config, + ) ) - + # Create OpenAI batch result format openai_result: OpenAIBatchResult = { "custom_id": custom_id, @@ -237,9 +235,9 @@ class AnthropicFilesHandler: error_obj = error.get("error", {}) error_message = error_obj.get("message", "Unknown error") error_type = error_obj.get("type", "api_error") - + status_code = ANTHROPIC_ERROR_STATUS_CODE_MAP.get(error_type, 500) - + error_body_errored: OpenAIErrorBody = { "error": { "message": error_message, @@ -272,7 +270,7 @@ class AnthropicFilesHandler: }, } transformed_lines.append(json.dumps(openai_result_canceled)) - + # Join lines and encode back to bytes transformed_content = "\n".join(transformed_lines) if transformed_lines: @@ -297,7 +295,7 @@ class AnthropicFilesHandler: status_code=200, content=json.dumps(anthropic_message).encode("utf-8"), ) - + # Create a ModelResponse object model_response = ModelResponse() # Initialize with required fields - will be populated by transform_parsed_response @@ -308,7 +306,7 @@ class AnthropicFilesHandler: message=litellm.Message(content="", role="assistant"), ) ] # type: ignore - + # Create a logging object for transformation logging_obj = Logging( model=anthropic_message.get("model", "claude-3-5-sonnet-20241022"), @@ -322,7 +320,7 @@ class AnthropicFilesHandler: kwargs={"optional_params": {}}, ) logging_obj.optional_params = {} - + # Transform using AnthropicConfig transformed_response = anthropic_config.transform_parsed_response( completion_response=anthropic_message, @@ -331,14 +329,16 @@ class AnthropicFilesHandler: json_mode=False, prefix_prompt=None, ) - + # Convert ModelResponse to OpenAI format dict - it's already in OpenAI format - openai_body: OpenAIChatCompletionResponse = transformed_response.model_dump(exclude_none=True) - + openai_body: OpenAIChatCompletionResponse = transformed_response.model_dump( + exclude_none=True + ) + # Ensure id comes from anthropic_message if not set if not openai_body.get("id"): openai_body["id"] = anthropic_message.get("id", "") - + return openai_body except Exception as e: verbose_logger.error( @@ -364,4 +364,3 @@ class AnthropicFilesHandler: }, } return error_response - diff --git a/litellm/llms/anthropic/files/transformation.py b/litellm/llms/anthropic/files/transformation.py new file mode 100644 index 00000000000..0691742bb08 --- /dev/null +++ b/litellm/llms/anthropic/files/transformation.py @@ -0,0 +1,307 @@ +""" +Anthropic Files API transformation config. + +Implements BaseFilesConfig for Anthropic's Files API (beta). +Reference: https://docs.anthropic.com/en/docs/build-with-claude/files + +Anthropic Files API endpoints: +- POST /v1/files - Upload a file +- GET /v1/files - List files +- GET /v1/files/{file_id} - Retrieve file metadata +- DELETE /v1/files/{file_id} - Delete a file +- GET /v1/files/{file_id}/content - Download file content +""" + +import calendar +import time +from typing import Any, Dict, List, Optional, Union, cast + +import httpx +from openai.types.file_deleted import FileDeleted + +from litellm.litellm_core_utils.prompt_templates.common_utils import extract_file_data +from litellm.llms.base_llm.chat.transformation import BaseLLMException +from litellm.llms.base_llm.files.transformation import ( + BaseFilesConfig, + LiteLLMLoggingObj, +) +from litellm.types.llms.openai import ( + CreateFileRequest, + FileContentRequest, + HttpxBinaryResponseContent, + OpenAICreateFileRequestOptionalParams, + OpenAIFileObject, +) +from litellm.types.utils import LlmProviders + +from ..common_utils import AnthropicError, AnthropicModelInfo + +ANTHROPIC_FILES_API_BASE = "https://api.anthropic.com" +ANTHROPIC_FILES_BETA_HEADER = "files-api-2025-04-14" + + +class AnthropicFilesConfig(BaseFilesConfig): + """ + Transformation config for Anthropic Files API. + + Anthropic uses: + - x-api-key header for authentication + - anthropic-beta: files-api-2025-04-14 header + - multipart/form-data for file uploads + - purpose="messages" (Anthropic-specific, not for batches/fine-tuning) + """ + + def __init__(self): + pass + + @property + def custom_llm_provider(self) -> LlmProviders: + return LlmProviders.ANTHROPIC + + 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: + api_base = AnthropicModelInfo.get_api_base(api_base) or ANTHROPIC_FILES_API_BASE + return f"{api_base.rstrip('/')}/v1/files" + + def get_error_class( + self, + error_message: str, + status_code: int, + headers: Union[dict, httpx.Headers], + ) -> BaseLLMException: + return AnthropicError( + status_code=status_code, + message=error_message, + headers=cast(httpx.Headers, headers) if isinstance(headers, dict) else headers, + ) + + def validate_environment( + self, + headers: dict, + model: str, + messages: list, + optional_params: dict, + litellm_params: dict, + api_key: Optional[str] = None, + api_base: Optional[str] = None, + ) -> dict: + api_key = AnthropicModelInfo.get_api_key(api_key) + if not api_key: + raise ValueError( + "Anthropic API key is required. Set ANTHROPIC_API_KEY environment variable or pass api_key parameter." + ) + headers.update( + { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "anthropic-beta": ANTHROPIC_FILES_BETA_HEADER, + } + ) + return headers + + def get_supported_openai_params( + self, model: str + ) -> List[OpenAICreateFileRequestOptionalParams]: + return ["purpose"] + + def map_openai_params( + self, + non_default_params: dict, + optional_params: dict, + model: str, + drop_params: bool, + ) -> dict: + return optional_params + + def transform_create_file_request( + self, + model: str, + create_file_data: CreateFileRequest, + optional_params: dict, + litellm_params: dict, + ) -> dict: + """ + Transform to multipart form data for Anthropic file upload. + + Anthropic expects: POST /v1/files with multipart form-data + - file: the file content + - purpose: "messages" (defaults to "messages" if not provided) + """ + file_data = create_file_data.get("file") + if file_data is None: + raise ValueError("File data is required") + + extracted = extract_file_data(file_data) + filename = extracted["filename"] or f"file_{int(time.time())}" + content = extracted["content"] + content_type = extracted.get("content_type", "application/octet-stream") + + purpose = create_file_data.get("purpose", "messages") + + return { + "file": (filename, content, content_type), + "purpose": (None, purpose), + } + + def transform_create_file_response( + self, + model: Optional[str], + raw_response: httpx.Response, + logging_obj: LiteLLMLoggingObj, + litellm_params: dict, + ) -> OpenAIFileObject: + """ + Transform Anthropic file response to OpenAI format. + + Anthropic response: + { + "id": "file-xxx", + "type": "file", + "filename": "document.pdf", + "mime_type": "application/pdf", + "size_bytes": 12345, + "created_at": "2025-01-01T00:00:00Z" + } + """ + response_json = raw_response.json() + return self._parse_anthropic_file(response_json) + + def transform_retrieve_file_request( + self, + file_id: str, + optional_params: dict, + litellm_params: dict, + ) -> tuple[str, dict]: + api_base = ( + AnthropicModelInfo.get_api_base(litellm_params.get("api_base")) + or ANTHROPIC_FILES_API_BASE + ) + return f"{api_base.rstrip('/')}/v1/files/{file_id}", {} + + def transform_retrieve_file_response( + self, + raw_response: httpx.Response, + logging_obj: LiteLLMLoggingObj, + litellm_params: dict, + ) -> OpenAIFileObject: + response_json = raw_response.json() + return self._parse_anthropic_file(response_json) + + def transform_delete_file_request( + self, + file_id: str, + optional_params: dict, + litellm_params: dict, + ) -> tuple[str, dict]: + api_base = ( + AnthropicModelInfo.get_api_base(litellm_params.get("api_base")) + or ANTHROPIC_FILES_API_BASE + ) + return f"{api_base.rstrip('/')}/v1/files/{file_id}", {} + + def transform_delete_file_response( + self, + raw_response: httpx.Response, + logging_obj: LiteLLMLoggingObj, + litellm_params: dict, + ) -> FileDeleted: + response_json = raw_response.json() + file_id = response_json.get("id", "") + return FileDeleted( + id=file_id, + deleted=True, + object="file", + ) + + def transform_list_files_request( + self, + purpose: Optional[str], + optional_params: dict, + litellm_params: dict, + ) -> tuple[str, dict]: + api_base = ( + AnthropicModelInfo.get_api_base(litellm_params.get("api_base")) + or ANTHROPIC_FILES_API_BASE + ) + url = f"{api_base.rstrip('/')}/v1/files" + params: Dict[str, Any] = {} + if purpose: + params["purpose"] = purpose + return url, params + + def transform_list_files_response( + self, + raw_response: httpx.Response, + logging_obj: LiteLLMLoggingObj, + litellm_params: dict, + ) -> List[OpenAIFileObject]: + """ + Anthropic list response: + { + "data": [...], + "has_more": false, + "first_id": "...", + "last_id": "..." + } + """ + response_json = raw_response.json() + files_data = response_json.get("data", []) + return [self._parse_anthropic_file(f) for f in files_data] + + def transform_file_content_request( + self, + file_content_request: FileContentRequest, + optional_params: dict, + litellm_params: dict, + ) -> tuple[str, dict]: + file_id = file_content_request.get("file_id") + api_base = ( + AnthropicModelInfo.get_api_base(litellm_params.get("api_base")) + or ANTHROPIC_FILES_API_BASE + ) + return f"{api_base.rstrip('/')}/v1/files/{file_id}/content", {} + + def transform_file_content_response( + self, + raw_response: httpx.Response, + logging_obj: LiteLLMLoggingObj, + litellm_params: dict, + ) -> HttpxBinaryResponseContent: + return HttpxBinaryResponseContent(response=raw_response) + + @staticmethod + def _parse_anthropic_file(file_data: dict) -> OpenAIFileObject: + """Parse Anthropic file object into OpenAI format.""" + created_at_str = file_data.get("created_at", "") + if created_at_str: + try: + created_at = int( + calendar.timegm( + time.strptime( + created_at_str.replace("Z", "+00:00")[:19], + "%Y-%m-%dT%H:%M:%S", + ) + ) + ) + except (ValueError, TypeError): + created_at = int(time.time()) + else: + created_at = int(time.time()) + + return OpenAIFileObject( + id=file_data.get("id", ""), + bytes=file_data.get("size_bytes", file_data.get("bytes", 0)), + created_at=created_at, + filename=file_data.get("filename", ""), + object="file", + purpose=file_data.get("purpose", "messages"), + status="uploaded", + status_details=None, + ) diff --git a/litellm/llms/anthropic/skills/__init__.py b/litellm/llms/anthropic/skills/__init__.py index 60e78c24065..d7b3589db84 100644 --- a/litellm/llms/anthropic/skills/__init__.py +++ b/litellm/llms/anthropic/skills/__init__.py @@ -3,4 +3,3 @@ from .transformation import AnthropicSkillsConfig __all__ = ["AnthropicSkillsConfig"] - diff --git a/litellm/llms/anthropic/skills/transformation.py b/litellm/llms/anthropic/skills/transformation.py index ad0eff42970..af9863534ed 100644 --- a/litellm/llms/anthropic/skills/transformation.py +++ b/litellm/llms/anthropic/skills/transformation.py @@ -47,10 +47,10 @@ class AnthropicSkillsConfig(BaseSkillsAPIConfig): # Add required headers headers["x-api-key"] = api_key headers["anthropic-version"] = "2023-06-01" - + # Add beta header for skills API from litellm.constants import ANTHROPIC_SKILLS_API_BETA_VERSION - + if "anthropic-beta" not in headers: headers["anthropic-beta"] = ANTHROPIC_SKILLS_API_BETA_VERSION elif isinstance(headers["anthropic-beta"], list): @@ -58,8 +58,11 @@ class AnthropicSkillsConfig(BaseSkillsAPIConfig): headers["anthropic-beta"].append(ANTHROPIC_SKILLS_API_BETA_VERSION) elif isinstance(headers["anthropic-beta"], str): if ANTHROPIC_SKILLS_API_BETA_VERSION not in headers["anthropic-beta"]: - headers["anthropic-beta"] = [headers["anthropic-beta"], ANTHROPIC_SKILLS_API_BETA_VERSION] - + headers["anthropic-beta"] = [ + headers["anthropic-beta"], + ANTHROPIC_SKILLS_API_BETA_VERSION, + ] + headers["content-type"] = "application/json" return headers @@ -87,13 +90,11 @@ class AnthropicSkillsConfig(BaseSkillsAPIConfig): headers: dict, ) -> Dict: """Transform create skill request for Anthropic""" - verbose_logger.debug( - "Transforming create skill request: %s", create_request - ) - + verbose_logger.debug("Transforming create skill request: %s", create_request) + # Anthropic expects the request body directly request_body = {k: v for k, v in create_request.items() if v is not None} - + return request_body def transform_create_skill_response( @@ -103,10 +104,8 @@ class AnthropicSkillsConfig(BaseSkillsAPIConfig): ) -> Skill: """Transform Anthropic response to Skill object""" response_json = raw_response.json() - verbose_logger.debug( - "Transforming create skill response: %s", response_json - ) - + verbose_logger.debug("Transforming create skill response: %s", response_json) + return Skill(**response_json) def transform_list_skills_request( @@ -122,7 +121,7 @@ class AnthropicSkillsConfig(BaseSkillsAPIConfig): litellm_params.api_base if litellm_params else None ) url = self.get_complete_url(api_base=api_base, endpoint="skills") - + # Build query parameters query_params: Dict[str, Any] = {} if "limit" in list_params and list_params["limit"]: @@ -131,11 +130,12 @@ class AnthropicSkillsConfig(BaseSkillsAPIConfig): query_params["page"] = list_params["page"] if "source" in list_params and list_params["source"]: query_params["source"] = list_params["source"] - + verbose_logger.debug( - "List skills request made to Anthropic Skills endpoint with params: %s", query_params + "List skills request made to Anthropic Skills endpoint with params: %s", + query_params, ) - + return url, query_params def transform_list_skills_response( @@ -145,10 +145,8 @@ class AnthropicSkillsConfig(BaseSkillsAPIConfig): ) -> ListSkillsResponse: """Transform Anthropic response to ListSkillsResponse""" response_json = raw_response.json() - verbose_logger.debug( - "Transforming list skills response: %s", response_json - ) - + verbose_logger.debug("Transforming list skills response: %s", response_json) + return ListSkillsResponse(**response_json) def transform_get_skill_request( @@ -162,9 +160,9 @@ class AnthropicSkillsConfig(BaseSkillsAPIConfig): url = self.get_complete_url( api_base=api_base, endpoint="skills", skill_id=skill_id ) - + verbose_logger.debug("Get skill request - URL: %s", url) - + return url, headers def transform_get_skill_response( @@ -174,10 +172,8 @@ class AnthropicSkillsConfig(BaseSkillsAPIConfig): ) -> Skill: """Transform Anthropic response to Skill object""" response_json = raw_response.json() - verbose_logger.debug( - "Transforming get skill response: %s", response_json - ) - + verbose_logger.debug("Transforming get skill response: %s", response_json) + return Skill(**response_json) def transform_delete_skill_request( @@ -191,9 +187,9 @@ class AnthropicSkillsConfig(BaseSkillsAPIConfig): url = self.get_complete_url( api_base=api_base, endpoint="skills", skill_id=skill_id ) - + verbose_logger.debug("Delete skill request - URL: %s", url) - + return url, headers def transform_delete_skill_response( @@ -203,9 +199,6 @@ class AnthropicSkillsConfig(BaseSkillsAPIConfig): ) -> DeleteSkillResponse: """Transform Anthropic response to DeleteSkillResponse""" response_json = raw_response.json() - verbose_logger.debug( - "Transforming delete skill response: %s", response_json - ) - - return DeleteSkillResponse(**response_json) + verbose_logger.debug("Transforming delete skill response: %s", response_json) + return DeleteSkillResponse(**response_json) diff --git a/litellm/llms/aws_polly/text_to_speech/transformation.py b/litellm/llms/aws_polly/text_to_speech/transformation.py index dc6c40000f1..caf65770397 100644 --- a/litellm/llms/aws_polly/text_to_speech/transformation.py +++ b/litellm/llms/aws_polly/text_to_speech/transformation.py @@ -43,20 +43,20 @@ class AWSPollyTextToSpeechConfig(BaseTextToSpeechConfig, BaseAWSLLM): # Voice name mappings from OpenAI voices to Polly voices VOICE_MAPPINGS = { - "alloy": "Joanna", # US English female - "echo": "Matthew", # US English male - "fable": "Amy", # British English female - "onyx": "Brian", # British English male - "nova": "Ivy", # US English female (child) - "shimmer": "Kendra", # US English female + "alloy": "Joanna", # US English female + "echo": "Matthew", # US English male + "fable": "Amy", # British English female + "onyx": "Brian", # British English male + "nova": "Ivy", # US English female (child) + "shimmer": "Kendra", # US English female } # Response format mappings from OpenAI to Polly FORMAT_MAPPINGS = { "mp3": "mp3", "opus": "ogg_vorbis", - "aac": "mp3", # Polly doesn't support AAC, use MP3 - "flac": "mp3", # Polly doesn't support FLAC, use MP3 + "aac": "mp3", # Polly doesn't support AAC, use MP3 + "flac": "mp3", # Polly doesn't support FLAC, use MP3 "wav": "pcm", "pcm": "pcm", } @@ -92,9 +92,9 @@ class AWSPollyTextToSpeechConfig(BaseTextToSpeechConfig, BaseAWSLLM): base_llm_http_handler: The BaseLLMHTTPHandler instance from main.py """ # Get AWS region from kwargs or environment - aws_region_name = kwargs.get("aws_region_name") or self._get_aws_region_name_for_polly( - optional_params=optional_params - ) + aws_region_name = kwargs.get( + "aws_region_name" + ) or self._get_aws_region_name_for_polly(optional_params=optional_params) # Convert voice to string if it's a dict voice_str: Optional[str] = None @@ -263,7 +263,9 @@ class AWSPollyTextToSpeechConfig(BaseTextToSpeechConfig, BaseAWSLLM): from botocore.auth import SigV4Auth from botocore.awsrequest import AWSRequest except ImportError: - raise ImportError("Missing boto3 to call AWS Polly. Run 'pip install boto3'.") + raise ImportError( + "Missing boto3 to call AWS Polly. Run 'pip install boto3'." + ) # Get AWS region aws_region_name = litellm_params.get("aws_region_name", self.DEFAULT_REGION) @@ -388,4 +390,3 @@ class AWSPollyTextToSpeechConfig(BaseTextToSpeechConfig, BaseAWSLLM): from litellm.types.llms.openai import HttpxBinaryResponseContent return HttpxBinaryResponseContent(raw_response) - diff --git a/litellm/llms/azure/azure.py b/litellm/llms/azure/azure.py index 51b98c4af55..61cfd54b565 100644 --- a/litellm/llms/azure/azure.py +++ b/litellm/llms/azure/azure.py @@ -413,7 +413,9 @@ class AzureChatCompletion(BaseAzureLLM, BaseLLM): litellm_params=litellm_params, ) if not isinstance(azure_client, (AsyncAzureOpenAI, AsyncOpenAI)): - raise ValueError("Azure client is not an instance of AsyncAzureOpenAI or AsyncOpenAI") + raise ValueError( + "Azure client is not an instance of AsyncAzureOpenAI or AsyncOpenAI" + ) ## LOGGING logging_obj.pre_call( input=data["messages"], @@ -595,7 +597,9 @@ class AzureChatCompletion(BaseAzureLLM, BaseLLM): litellm_params=litellm_params, ) if not isinstance(azure_client, (AsyncAzureOpenAI, AsyncOpenAI)): - raise ValueError("Azure client is not an instance of AsyncAzureOpenAI or AsyncOpenAI") + raise ValueError( + "Azure client is not an instance of AsyncAzureOpenAI or AsyncOpenAI" + ) ## LOGGING logging_obj.pre_call( @@ -674,13 +678,15 @@ class AzureChatCompletion(BaseAzureLLM, BaseLLM): litellm_params=litellm_params, ) if not isinstance(openai_aclient, (AsyncAzureOpenAI, AsyncOpenAI)): - raise ValueError("Azure client is not an instance of AsyncAzureOpenAI or AsyncOpenAI") + raise ValueError( + "Azure client is not an instance of AsyncAzureOpenAI or AsyncOpenAI" + ) raw_response = await openai_aclient.embeddings.with_raw_response.create( **data, timeout=timeout ) headers = dict(raw_response.headers) - + # Convert json.JSONDecodeError to AzureOpenAIError for two critical reasons: # # 1. ROUTER BEHAVIOR: The router relies on exception.status_code to determine cooldown logic: @@ -698,7 +704,7 @@ class AzureChatCompletion(BaseAzureLLM, BaseLLM): except json.JSONDecodeError as json_error: raise AzureOpenAIError( status_code=raw_response.status_code or 500, - message=f"Failed to parse raw Azure embedding response: {str(json_error)}" + message=f"Failed to parse raw Azure embedding response: {str(json_error)}", ) from json_error if isinstance(response, str): raise AzureOpenAIError( @@ -1107,7 +1113,6 @@ class AzureChatCompletion(BaseAzureLLM, BaseLLM): timeout=None, model: Optional[str] = None, ) -> ImageResponse: - response: Optional[dict] = None try: # response = await azure_client.images.generate(**data, timeout=timeout) @@ -1119,7 +1124,8 @@ class AzureChatCompletion(BaseAzureLLM, BaseLLM): api_version: str = azure_client_params.get("api_version", "") # Use the deployment name (model) for URL construction, not the base_model from data img_gen_api_base = self.create_azure_base_url( - azure_client_params=azure_client_params, model=model or data.get("model", "") + azure_client_params=azure_client_params, + model=model or data.get("model", ""), ) ## LOGGING @@ -1212,13 +1218,17 @@ class AzureChatCompletion(BaseAzureLLM, BaseLLM): and litellm_params is not None and litellm_params.get("base_model", None) is not None ): - model_response._hidden_params["model"] = litellm_params.get("base_model", None) + model_response._hidden_params["model"] = litellm_params.get( + "base_model", None + ) # Azure image generation API doesn't support extra_body parameter extra_body = optional_params.pop("extra_body", {}) flattened_params = {**optional_params, **extra_body} - - base_model = litellm_params.get("base_model", None) if litellm_params else None + + base_model = ( + litellm_params.get("base_model", None) if litellm_params else None + ) data = {"model": base_model or model, "prompt": prompt, **flattened_params} max_retries = data.pop("max_retries", 2) if not isinstance(max_retries, int): diff --git a/litellm/llms/azure/batches/handler.py b/litellm/llms/azure/batches/handler.py index 0e474a468e5..6da3670b34a 100644 --- a/litellm/llms/azure/batches/handler.py +++ b/litellm/llms/azure/batches/handler.py @@ -47,7 +47,9 @@ class AzureBatchesAPI(BaseAzureLLM): api_version: Optional[str], timeout: Union[float, httpx.Timeout], max_retries: Optional[int], - client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = None, + client: Optional[ + Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] + ] = None, litellm_params: Optional[dict] = None, ) -> Union[LiteLLMBatch, Coroutine[Any, Any, LiteLLMBatch]]: azure_client: Optional[ @@ -93,7 +95,9 @@ class AzureBatchesAPI(BaseAzureLLM): api_version: Optional[str], timeout: Union[float, httpx.Timeout], max_retries: Optional[int], - client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = None, + client: Optional[ + Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] + ] = None, litellm_params: Optional[dict] = None, ): azure_client: Optional[ @@ -141,7 +145,9 @@ class AzureBatchesAPI(BaseAzureLLM): api_version: Optional[str], timeout: Union[float, httpx.Timeout], max_retries: Optional[int], - client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = None, + client: Optional[ + Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] + ] = None, litellm_params: Optional[dict] = None, ): azure_client: Optional[ @@ -158,7 +164,7 @@ class AzureBatchesAPI(BaseAzureLLM): raise ValueError( "OpenAI client is not initialized. Make sure api_key is passed or OPENAI_API_KEY is set in the environment." ) - + if _is_async is True: if not isinstance(azure_client, (AsyncAzureOpenAI, AsyncOpenAI)): raise ValueError( @@ -167,7 +173,7 @@ class AzureBatchesAPI(BaseAzureLLM): return self.acancel_batch( # type: ignore cancel_batch_data=cancel_batch_data, client=azure_client ) - + # At this point, azure_client is guaranteed to be a sync client if not isinstance(azure_client, (AzureOpenAI, OpenAI)): raise ValueError( @@ -195,7 +201,9 @@ class AzureBatchesAPI(BaseAzureLLM): max_retries: Optional[int], after: Optional[str] = None, limit: Optional[int] = None, - client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = None, + client: Optional[ + Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] + ] = None, litellm_params: Optional[dict] = None, ): azure_client: Optional[ diff --git a/litellm/llms/azure/chat/gpt_5_transformation.py b/litellm/llms/azure/chat/gpt_5_transformation.py index 78d6372d023..6310df9cecc 100644 --- a/litellm/llms/azure/chat/gpt_5_transformation.py +++ b/litellm/llms/azure/chat/gpt_5_transformation.py @@ -4,7 +4,10 @@ from typing import List import litellm from litellm.exceptions import UnsupportedParamsError -from litellm.llms.openai.chat.gpt_5_transformation import OpenAIGPT5Config +from litellm.llms.openai.chat.gpt_5_transformation import ( + OpenAIGPT5Config, + _get_effort_level, +) from litellm.types.llms.openai import AllMessageValues from .gpt_transformation import AzureOpenAIConfig @@ -38,7 +41,9 @@ class AzureOpenAIGPT5Config(AzureOpenAIConfig, OpenAIGPT5Config): used for manual routing. """ # gpt-5-chat* is a chat model and shouldn't go through GPT-5 reasoning restrictions. - return ("gpt-5" in model and "gpt-5-chat" not in model) or "gpt5_series" in model + return ( + "gpt-5" in model and "gpt-5-chat" not in model + ) or "gpt5_series" in model def get_supported_openai_params(self, model: str) -> List[str]: """Get supported parameters for Azure OpenAI GPT-5 models. @@ -61,7 +66,9 @@ class AzureOpenAIGPT5Config(AzureOpenAIConfig, OpenAIGPT5Config): # Only gpt-5.2+ has been verified to support logprobs on Azure. # The base OpenAI class includes logprobs for gpt-5.1+, but Azure # hasn't verified support for gpt-5.1, so remove them unless gpt-5.2/5.4+. - if self._supports_reasoning_effort_level(model, "none") and not self.is_model_gpt_5_2_model(model): + if self._supports_reasoning_effort_level( + model, "none" + ) and not self.is_model_gpt_5_2_model(model): params = [p for p in params if p not in ["logprobs", "top_logprobs"]] elif self.is_model_gpt_5_2_model(model): azure_supported_params = ["logprobs", "top_logprobs"] @@ -77,24 +84,27 @@ class AzureOpenAIGPT5Config(AzureOpenAIConfig, OpenAIGPT5Config): drop_params: bool, api_version: str = "", ) -> dict: - reasoning_effort_value = ( - non_default_params.get("reasoning_effort") - or optional_params.get("reasoning_effort") - ) + reasoning_effort_value = non_default_params.get( + "reasoning_effort" + ) or optional_params.get("reasoning_effort") + effective_effort = _get_effort_level(reasoning_effort_value) # gpt-5.1/5.2/5.4 support reasoning_effort='none', but other gpt-5 models don't # See: https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/reasoning supports_none = self._supports_reasoning_effort_level(model, "none") - if reasoning_effort_value == "none" and not supports_none: + if effective_effort == "none" and not supports_none: if litellm.drop_params is True or ( drop_params is not None and drop_params is True ): non_default_params = non_default_params.copy() optional_params = optional_params.copy() - if non_default_params.get("reasoning_effort") == "none": + if ( + _get_effort_level(non_default_params.get("reasoning_effort")) + == "none" + ): non_default_params.pop("reasoning_effort") - if optional_params.get("reasoning_effort") == "none": + if _get_effort_level(optional_params.get("reasoning_effort")) == "none": optional_params.pop("reasoning_effort") else: raise UnsupportedParamsError( @@ -117,9 +127,19 @@ class AzureOpenAIGPT5Config(AzureOpenAIConfig, OpenAIGPT5Config): ) # Only drop reasoning_effort='none' for models that don't support it - if result.get("reasoning_effort") == "none" and not supports_none: + result_effort = _get_effort_level(result.get("reasoning_effort")) + if result_effort == "none" and not supports_none: result.pop("reasoning_effort") + # Azure Chat Completions: gpt-5.4+ does not support tools + reasoning together. + # Drop reasoning_effort when both are present (OpenAI routes to Responses API; Azure does not). + if self.is_model_gpt_5_4_plus_model(model): + has_tools = bool( + non_default_params.get("tools") or optional_params.get("tools") + ) + if has_tools and result_effort not in (None, "none"): + result.pop("reasoning_effort", None) + return result def transform_request( diff --git a/litellm/llms/azure/chat/o_series_transformation.py b/litellm/llms/azure/chat/o_series_transformation.py index 778ec5f6dea..cae7513245c 100644 --- a/litellm/llms/azure/chat/o_series_transformation.py +++ b/litellm/llms/azure/chat/o_series_transformation.py @@ -44,7 +44,7 @@ class AzureOpenAIO1Config(OpenAIOSeriesConfig): return [ param for param in all_openai_params if param not in non_supported_params ] - + def _get_o_series_only_params(self, model: str) -> list: """ Helper function to get the o-series only params for the model @@ -52,7 +52,6 @@ class AzureOpenAIO1Config(OpenAIOSeriesConfig): - reasoning_effort """ o_series_only_param = [] - ######################################################### # Case 1: If the model is recognized and in litellm model cost map @@ -63,12 +62,12 @@ class AzureOpenAIO1Config(OpenAIOSeriesConfig): o_series_only_param.append("reasoning_effort") ######################################################### # Case 2: If the model is not recognized, then we assume it supports reasoning - # This is critical because several users tend to use custom deployment names + # This is critical because several users tend to use custom deployment names # for azure o-series models. ######################################################### else: o_series_only_param.append("reasoning_effort") - + return o_series_only_param def should_fake_stream( diff --git a/litellm/llms/azure/common_utils.py b/litellm/llms/azure/common_utils.py index 7ed4306e299..fcdb3eca23a 100644 --- a/litellm/llms/azure/common_utils.py +++ b/litellm/llms/azure/common_utils.py @@ -301,7 +301,9 @@ def get_azure_ad_token( ) tenant_id = litellm_params.get("tenant_id") or os.getenv("AZURE_TENANT_ID") client_id = litellm_params.get("client_id") or os.getenv("AZURE_CLIENT_ID") - client_secret = litellm_params.get("client_secret") or os.getenv("AZURE_CLIENT_SECRET") + client_secret = litellm_params.get("client_secret") or os.getenv( + "AZURE_CLIENT_SECRET" + ) azure_username = litellm_params.get("azure_username") or os.getenv("AZURE_USERNAME") azure_password = litellm_params.get("azure_password") or os.getenv("AZURE_PASSWORD") scope = litellm_params.get("azure_scope") or os.getenv( @@ -439,12 +441,16 @@ class BaseAzureLLM(BaseOpenAILLM): api_key: Optional[str], api_base: Optional[str], api_version: Optional[str] = None, - client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = None, + client: Optional[ + Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] + ] = None, litellm_params: Optional[dict] = None, _is_async: bool = False, model: Optional[str] = None, ) -> Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]]: - openai_client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = None + openai_client: Optional[ + Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] + ] = None client_initialization_params: dict = locals() client_initialization_params["is_async"] = _is_async if client is None: @@ -453,7 +459,9 @@ class BaseAzureLLM(BaseOpenAILLM): client_type="azure", ) if cached_client: - if isinstance(cached_client, (AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI)): + if isinstance( + cached_client, (AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI) + ): return cached_client azure_client_params = self.initialize_azure_sdk_client( @@ -481,7 +489,9 @@ class BaseAzureLLM(BaseOpenAILLM): if "http_client" in azure_client_params: v1_params["http_client"] = azure_client_params["http_client"] - verbose_logger.debug(f"Using Azure v1 API with base_url: {v1_params['base_url']}") + verbose_logger.debug( + f"Using Azure v1 API with base_url: {v1_params['base_url']}" + ) if _is_async is True: openai_client = AsyncOpenAI(**v1_params) # type: ignore @@ -495,9 +505,11 @@ class BaseAzureLLM(BaseOpenAILLM): openai_client = AzureOpenAI(**azure_client_params) # type: ignore else: openai_client = client - if api_version is not None and isinstance( - openai_client, (AzureOpenAI, AsyncAzureOpenAI) - ) and isinstance(openai_client._custom_query, dict): + if ( + api_version is not None + and isinstance(openai_client, (AzureOpenAI, AsyncAzureOpenAI)) + and isinstance(openai_client._custom_query, dict) + ): # set api_version to version passed by user openai_client._custom_query.setdefault("api-version", api_version) @@ -524,11 +536,21 @@ class BaseAzureLLM(BaseOpenAILLM): # litellm_params sometimes contains the key, but the value is None # We should respect environment variables in this case - tenant_id = self._resolve_env_var(litellm_params, "tenant_id", "AZURE_TENANT_ID") - client_id = self._resolve_env_var(litellm_params, "client_id", "AZURE_CLIENT_ID") - client_secret = self._resolve_env_var(litellm_params, "client_secret", "AZURE_CLIENT_SECRET") - azure_username = self._resolve_env_var(litellm_params, "azure_username", "AZURE_USERNAME") - azure_password = self._resolve_env_var(litellm_params, "azure_password", "AZURE_PASSWORD") + tenant_id = self._resolve_env_var( + litellm_params, "tenant_id", "AZURE_TENANT_ID" + ) + client_id = self._resolve_env_var( + litellm_params, "client_id", "AZURE_CLIENT_ID" + ) + client_secret = self._resolve_env_var( + litellm_params, "client_secret", "AZURE_CLIENT_SECRET" + ) + azure_username = self._resolve_env_var( + litellm_params, "azure_username", "AZURE_USERNAME" + ) + azure_password = self._resolve_env_var( + litellm_params, "azure_password", "AZURE_PASSWORD" + ) scope = self._resolve_env_var(litellm_params, "azure_scope", "AZURE_SCOPE") if scope is None: scope = "https://cognitiveservices.azure.com/.default" @@ -777,9 +799,11 @@ class BaseAzureLLM(BaseOpenAILLM): return False return api_version in {"preview", "latest", "v1"} - def _resolve_env_var(self, litellm_params: Dict[str, Any], param_key: str, env_var_key: str) -> Optional[str]: + def _resolve_env_var( + self, litellm_params: Dict[str, Any], param_key: str, env_var_key: str + ) -> Optional[str]: """Resolve the environment variable for a given parameter key. - + The logic here is different from `params.get(key, os.getenv(env_var))` because litellm_params may contain the key with a None value, in which case we want to fallback to the environment variable. @@ -802,15 +826,9 @@ def get_azure_credentials( api_version: Optional[str] = None, ) -> AzureCredentials: """Resolve Azure credentials from params, litellm globals, and env vars.""" - resolved_api_base = ( - api_base - or litellm.api_base - or get_secret_str("AZURE_API_BASE") - ) + resolved_api_base = api_base or litellm.api_base or get_secret_str("AZURE_API_BASE") resolved_api_version = ( - api_version - or litellm.api_version - or get_secret_str("AZURE_API_VERSION") + api_version or litellm.api_version or get_secret_str("AZURE_API_VERSION") ) resolved_api_key = ( api_key @@ -824,4 +842,3 @@ def get_azure_credentials( api_key=resolved_api_key, api_version=resolved_api_version, ) - diff --git a/litellm/llms/azure/exception_mapping.py b/litellm/llms/azure/exception_mapping.py index bcccad9352f..dec7e7e5c90 100644 --- a/litellm/llms/azure/exception_mapping.py +++ b/litellm/llms/azure/exception_mapping.py @@ -24,9 +24,7 @@ class AzureOpenAIExceptionMapping: # Prefer the provider message/type/code when present. provider_message = ( - azure_error.get("message") - if isinstance(azure_error, dict) - else None + azure_error.get("message") if isinstance(azure_error, dict) else None ) or message provider_type = ( azure_error.get("type") if isinstance(azure_error, dict) else None diff --git a/litellm/llms/azure/files/handler.py b/litellm/llms/azure/files/handler.py index e53ced6b0e2..72cbcba8a9a 100644 --- a/litellm/llms/azure/files/handler.py +++ b/litellm/llms/azure/files/handler.py @@ -25,10 +25,12 @@ class AzureOpenAIFilesAPI(BaseAzureLLM): super().__init__() @staticmethod - def _prepare_create_file_data(create_file_data: CreateFileRequest) -> dict[str, Any]: + def _prepare_create_file_data( + create_file_data: CreateFileRequest, + ) -> dict[str, Any]: """ Prepare create_file_data for OpenAI SDK. - + Removes expires_after if None to match SDK's Omit pattern. SDK expects file_create_params.ExpiresAfter | Omit, but FileExpiresAfter works at runtime. """ @@ -56,7 +58,9 @@ class AzureOpenAIFilesAPI(BaseAzureLLM): api_version: Optional[str], timeout: Union[float, httpx.Timeout], max_retries: Optional[int], - client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = None, + client: Optional[ + Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] + ] = None, litellm_params: Optional[dict] = None, ) -> Union[OpenAIFileObject, Coroutine[Any, Any, OpenAIFileObject]]: openai_client: Optional[ @@ -102,7 +106,9 @@ class AzureOpenAIFilesAPI(BaseAzureLLM): timeout: Union[float, httpx.Timeout], max_retries: Optional[int], api_version: Optional[str] = None, - client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = None, + client: Optional[ + Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] + ] = None, litellm_params: Optional[dict] = None, ) -> Union[ HttpxBinaryResponseContent, Coroutine[Any, Any, HttpxBinaryResponseContent] @@ -154,7 +160,9 @@ class AzureOpenAIFilesAPI(BaseAzureLLM): timeout: Union[float, httpx.Timeout], max_retries: Optional[int], api_version: Optional[str] = None, - client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = None, + client: Optional[ + Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] + ] = None, litellm_params: Optional[dict] = None, ): openai_client: Optional[ @@ -206,7 +214,9 @@ class AzureOpenAIFilesAPI(BaseAzureLLM): max_retries: Optional[int], organization: Optional[str] = None, api_version: Optional[str] = None, - client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = None, + client: Optional[ + Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] + ] = None, litellm_params: Optional[dict] = None, ): openai_client: Optional[ @@ -260,7 +270,9 @@ class AzureOpenAIFilesAPI(BaseAzureLLM): max_retries: Optional[int], purpose: Optional[str] = None, api_version: Optional[str] = None, - client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = None, + client: Optional[ + Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] + ] = None, litellm_params: Optional[dict] = None, ): openai_client: Optional[ diff --git a/litellm/llms/azure/realtime/handler.py b/litellm/llms/azure/realtime/handler.py index 0ad6fb57354..6d00ecd51c9 100644 --- a/litellm/llms/azure/realtime/handler.py +++ b/litellm/llms/azure/realtime/handler.py @@ -57,9 +57,12 @@ class AzureOpenAIRealtime(AzureChatCompletion): api_base = api_base.replace("https://", "wss://") # Determine path based on realtime_protocol (case-insensitive) - _is_ga = realtime_protocol is not None and realtime_protocol.upper() in ("GA", "V1") + _is_ga = realtime_protocol is not None and realtime_protocol.upper() in ( + "GA", + "V1", + ) if _is_ga: - path = "/openai/v1/realtime" + path = "/openai/v1/realtime" return f"{api_base}{path}?model={model}" else: # Default to beta path for backwards compatibility @@ -86,7 +89,9 @@ class AzureOpenAIRealtime(AzureChatCompletion): if api_base is None: raise ValueError("api_base is required for Azure OpenAI calls") - if api_version is None and (realtime_protocol is None or realtime_protocol.upper() not in ("GA", "V1")): + if api_version is None and ( + realtime_protocol is None or realtime_protocol.upper() not in ("GA", "V1") + ): raise ValueError("api_version is required for Azure OpenAI calls") url = self._construct_url( @@ -115,5 +120,7 @@ class AzureOpenAIRealtime(AzureChatCompletion): except websockets.exceptions.InvalidStatusCode as e: # type: ignore await websocket.close(code=e.status_code, reason=str(e)) except Exception: - verbose_proxy_logger.exception("Error in AzureOpenAIRealtime.async_realtime") + verbose_proxy_logger.exception( + "Error in AzureOpenAIRealtime.async_realtime" + ) pass diff --git a/litellm/llms/azure/realtime/http_transformation.py b/litellm/llms/azure/realtime/http_transformation.py new file mode 100644 index 00000000000..df1e2707af2 --- /dev/null +++ b/litellm/llms/azure/realtime/http_transformation.py @@ -0,0 +1,46 @@ +"""Azure OpenAI realtime HTTP transformation config (client_secrets + realtime_calls).""" + +from typing import Optional + +import litellm +from litellm.llms.base_llm.realtime.http_transformation import BaseRealtimeHTTPConfig +from litellm.secret_managers.main import get_secret_str + + +class AzureRealtimeHTTPConfig(BaseRealtimeHTTPConfig): + def get_api_base(self, api_base: Optional[str], **kwargs) -> str: + return api_base or litellm.api_base or get_secret_str("AZURE_API_BASE") or "" + + def get_api_key(self, api_key: Optional[str], **kwargs) -> str: + return api_key or litellm.api_key or get_secret_str("AZURE_API_KEY") or "" + + def get_complete_url( + self, api_base: Optional[str], model: str, api_version: Optional[str] = None + ) -> str: + base = self.get_api_base(api_base).rstrip("/") + version = api_version or get_secret_str("AZURE_API_VERSION") or "2024-12-17" + return f"{base}/openai/realtime/client_secrets?api-version={version}" + + def validate_environment( + self, + headers: dict, + model: str, + api_key: Optional[str] = None, + ) -> dict: + return { + **headers, + "api-key": api_key or "", + "Content-Type": "application/json", + } + + def get_realtime_calls_url( + self, api_base: Optional[str], model: str, api_version: Optional[str] = None + ) -> str: + base = self.get_api_base(api_base).rstrip("/") + version = api_version or get_secret_str("AZURE_API_VERSION") or "2024-12-17" + return f"{base}/openai/realtime/calls?api-version={version}" + + def get_realtime_calls_headers(self, ephemeral_key: str) -> dict: + return { + "api-key": ephemeral_key, + } diff --git a/litellm/llms/azure/responses/o_series_transformation.py b/litellm/llms/azure/responses/o_series_transformation.py index a0b2ef16300..3a554e9e194 100644 --- a/litellm/llms/azure/responses/o_series_transformation.py +++ b/litellm/llms/azure/responses/o_series_transformation.py @@ -27,7 +27,7 @@ else: class AzureOpenAIOSeriesResponsesAPIConfig(AzureOpenAIResponsesAPIConfig): """ Configuration for Azure OpenAI O-series models in Responses API. - + O-series models (o1, o3, etc.) do not support the temperature parameter in the responses API, so we need to drop it when drop_params is enabled. """ @@ -35,21 +35,22 @@ class AzureOpenAIOSeriesResponsesAPIConfig(AzureOpenAIResponsesAPIConfig): def get_supported_openai_params(self, model: str) -> list: """ Get supported parameters for Azure OpenAI O-series Responses API. - + O-series models don't support temperature parameter in responses API. """ # Get the base Azure supported params base_supported_params = super().get_supported_openai_params(model) - + # O-series models don't support temperature parameter in responses API o_series_unsupported_params = ["temperature"] - + # Filter out unsupported parameters for O-series models o_series_supported_params = [ - param for param in base_supported_params + param + for param in base_supported_params if param not in o_series_unsupported_params ] - + return o_series_supported_params def map_openai_params( @@ -60,34 +61,34 @@ class AzureOpenAIOSeriesResponsesAPIConfig(AzureOpenAIResponsesAPIConfig): ) -> Dict: """ Map OpenAI parameters for Azure OpenAI O-series Responses API. - + Drops temperature parameter if drop_params is True since O-series models don't support temperature in the responses API. """ mapped_params = dict(response_api_optional_params) - + # If drop_params is enabled, remove temperature parameter for O-series models if drop_params and "temperature" in mapped_params: verbose_logger.debug( f"Dropping unsupported parameter 'temperature' for Azure OpenAI O-series responses API model {model}" ) mapped_params.pop("temperature", None) - + return mapped_params def is_o_series_model(self, model: str) -> bool: """ Check if the model is an O-series model. - + Args: model: The model name to check - + Returns: True if it's an O-series model, False otherwise """ # Check if model name contains o_series or if it's a known O-series model if "o_series" in model.lower(): return True - + # Check if the model supports reasoning (which is O-series specific) - return supports_reasoning(model) \ No newline at end of file + return supports_reasoning(model) diff --git a/litellm/llms/azure/responses/transformation.py b/litellm/llms/azure/responses/transformation.py index 78631d38005..76a6d485bc4 100644 --- a/litellm/llms/azure/responses/transformation.py +++ b/litellm/llms/azure/responses/transformation.py @@ -21,7 +21,6 @@ else: class AzureOpenAIResponsesAPIConfig(OpenAIResponsesAPIConfig): - # Parameters not supported by Azure Responses API AZURE_UNSUPPORTED_PARAMS = ["context_management"] diff --git a/litellm/llms/azure/text_to_speech/__init__.py b/litellm/llms/azure/text_to_speech/__init__.py index ee923f122bd..24dfb4fb495 100644 --- a/litellm/llms/azure/text_to_speech/__init__.py +++ b/litellm/llms/azure/text_to_speech/__init__.py @@ -5,4 +5,3 @@ from .transformation import AzureAVATextToSpeechConfig __all__ = [ "AzureAVATextToSpeechConfig", ] - diff --git a/litellm/llms/azure/text_to_speech/transformation.py b/litellm/llms/azure/text_to_speech/transformation.py index df582c3c09b..a5dec243147 100644 --- a/litellm/llms/azure/text_to_speech/transformation.py +++ b/litellm/llms/azure/text_to_speech/transformation.py @@ -27,7 +27,7 @@ else: class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): """ Configuration for Azure AVA (Cognitive Services) Text-to-Speech - + Reference: https://learn.microsoft.com/en-us/azure/ai-services/speech-service/rest-text-to-speech """ @@ -78,9 +78,9 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): ]: """ Dispatch method to handle Azure AVA TTS requests - + This method encapsulates Azure-specific credential resolution and parameter handling - + Args: base_llm_http_handler: The BaseLLMHTTPHandler instance from main.py """ @@ -91,7 +91,7 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): or litellm.api_base or get_secret_str("AZURE_API_BASE") ) - + # Resolve api_key from multiple sources (Azure-specific) api_key = ( api_key @@ -101,7 +101,7 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): or get_secret_str("AZURE_OPENAI_API_KEY") or get_secret_str("AZURE_API_KEY") ) - + # Convert voice to string if it's a dict (for Azure AVA, voice must be a string) voice_str: Optional[str] = None if isinstance(voice, str): @@ -109,11 +109,13 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): elif isinstance(voice, dict): # Extract voice name from dict if needed voice_str = voice.get("name") if voice else None - - litellm_params_dict.update({ - "api_key": api_key, - "api_base": api_base, - }) + + litellm_params_dict.update( + { + "api_key": api_key, + "api_base": api_base, + } + ) # Call the text_to_speech_handler response = base_llm_http_handler.text_to_speech_handler( model=model, @@ -129,13 +131,13 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): client=None, _is_async=aspeech, ) - + return response def get_supported_openai_params(self, model: str) -> list: """ Azure AVA TTS supports these OpenAI parameters - + Note: Azure also supports additional SSML-specific parameters (style, styledegree, role) which can be passed but are not part of the OpenAI spec """ @@ -144,13 +146,13 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): def _convert_speed_to_azure_rate(self, speed: float) -> str: """ Convert OpenAI speed value to Azure SSML prosody rate percentage - + Args: speed: OpenAI speed value (0.25-4.0, default 1.0) - + Returns: Azure rate string with percentage (e.g., "+50%", "-50%", "+0%") - + Examples: speed=1.0 -> "+0%" (default) speed=2.0 -> "+100%" @@ -158,7 +160,7 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): """ rate_percentage = int((speed - 1.0) * 100) return f"{rate_percentage:+d}%" - + def _build_express_as_element( self, content: str, @@ -168,19 +170,19 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): ) -> str: """ Build mstts:express-as element with optional style, styledegree, and role attributes - + Args: content: The inner content to wrap style: Speaking style (e.g., "cheerful", "sad", "angry") styledegree: Style intensity (0.01 to 2) role: Voice role (e.g., "Girl", "Boy", "SeniorFemale", "SeniorMale") - + Returns: Content wrapped in mstts:express-as if any attributes provided, otherwise raw content """ if not (style or styledegree or role): return content - + express_as_attrs = [] if style: express_as_attrs.append(f"style='{style}'") @@ -188,10 +190,10 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): express_as_attrs.append(f"styledegree='{styledegree}'") if role: express_as_attrs.append(f"role='{role}'") - + express_as_attrs_str = " ".join(express_as_attrs) return f"{content}" - + def _get_voice_language( self, voice_name: Optional[str], @@ -199,14 +201,14 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): ) -> Optional[str]: """ Get the language for the voice element's xml:lang attribute - + Args: voice_name: The Azure voice name (e.g., "en-US-AriaNeural") explicit_lang: Explicitly provided language code (takes precedence) - + Returns: Language code if available (e.g., "es-ES"), or None - + Examples: - explicit_lang="es-ES" → "es-ES" (explicit takes precedence) - voice_name="en-US-AriaNeural", explicit_lang=None → None (use default from voice) @@ -215,7 +217,7 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): # If explicit language is provided, use it (for multilingual voices) if explicit_lang: return explicit_lang - + # For non-multilingual voices, we don't need to set xml:lang on the voice element # The voice name already encodes the language (e.g., en-US-AriaNeural) # Only return a language if explicitly set @@ -245,7 +247,7 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): else: # Assume it's already an Azure voice name mapped_voice = voice - + # Map response format if "response_format" in optional_params: format_name = optional_params["response_format"] @@ -257,23 +259,23 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): else: # Default to MP3 mapped_params["output_format"] = "audio-24khz-48kbitrate-mono-mp3" - + # Map speed (OpenAI: 0.25-4.0, Azure: prosody rate) if "speed" in optional_params: speed = optional_params["speed"] if speed is not None: mapped_params["rate"] = self._convert_speed_to_azure_rate(speed=speed) - + # Pass through Azure-specific SSML parameters if "style" in kwargs: mapped_params["style"] = kwargs["style"] - + if "styledegree" in kwargs: mapped_params["styledegree"] = kwargs["styledegree"] - + if "role" in kwargs: mapped_params["role"] = kwargs["role"] - + if "lang" in kwargs: mapped_params["lang"] = kwargs["lang"] return mapped_voice, mapped_params @@ -289,24 +291,24 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): Validate Azure environment and set up authentication headers """ validated_headers = headers.copy() - + # Azure AVA TTS requires either: # 1. Ocp-Apim-Subscription-Key header, or # 2. Authorization: Bearer header - + # We'll use the token-based auth via our token handler # The token will be added later in the handler - + if api_key: # If subscription key is provided, use it directly validated_headers["Ocp-Apim-Subscription-Key"] = api_key - + # Content-Type for SSML validated_headers["Content-Type"] = "application/ssml+xml" - + # User-Agent validated_headers["User-Agent"] = "litellm" - + return validated_headers def get_complete_url( @@ -317,7 +319,7 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): ) -> str: """ Get the complete URL for Azure AVA TTS request - + Azure TTS endpoint format: https://{region}.tts.speech.microsoft.com/cognitiveservices/v1 """ @@ -327,53 +329,50 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): f"Format: https://{{region}}.{self.COGNITIVE_SERVICES_DOMAIN} or " f"https://{{region}}.{self.TTS_SPEECH_DOMAIN}" ) - + # Remove trailing slash and parse URL api_base = api_base.rstrip("/") parsed_url = urlparse(api_base) hostname = parsed_url.hostname or "" - + # Check if it's a Cognitive Services endpoint (convert to TTS endpoint) if self._is_cognitive_services_endpoint(hostname=hostname): region = self._extract_region_from_hostname( - hostname=hostname, - domain=self.COGNITIVE_SERVICES_DOMAIN + hostname=hostname, domain=self.COGNITIVE_SERVICES_DOMAIN ) return self._build_tts_url(region=region) - + # Check if it's already a TTS endpoint if self._is_tts_endpoint(hostname=hostname): if not api_base.endswith(self.TTS_ENDPOINT_PATH): return f"{api_base}{self.TTS_ENDPOINT_PATH}" return api_base - + # Assume it's a custom endpoint, append the path return f"{api_base}{self.TTS_ENDPOINT_PATH}" def _is_cognitive_services_endpoint(self, hostname: str) -> bool: """Check if hostname is a Cognitive Services endpoint""" - return ( - hostname == self.COGNITIVE_SERVICES_DOMAIN - or hostname.endswith(f".{self.COGNITIVE_SERVICES_DOMAIN}") + return hostname == self.COGNITIVE_SERVICES_DOMAIN or hostname.endswith( + f".{self.COGNITIVE_SERVICES_DOMAIN}" ) def _is_tts_endpoint(self, hostname: str) -> bool: """Check if hostname is a TTS endpoint""" - return ( - hostname == self.TTS_SPEECH_DOMAIN - or hostname.endswith(f".{self.TTS_SPEECH_DOMAIN}") + return hostname == self.TTS_SPEECH_DOMAIN or hostname.endswith( + f".{self.TTS_SPEECH_DOMAIN}" ) def _extract_region_from_hostname(self, hostname: str, domain: str) -> str: """ Extract region from hostname - + Examples: eastus.api.cognitive.microsoft.com -> eastus api.cognitive.microsoft.com -> "" """ if hostname.endswith(f".{domain}"): - return hostname[:-len(f".{domain}")] + return hostname[: -len(f".{domain}")] return "" def _build_tts_url(self, region: str) -> str: @@ -382,7 +381,6 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): return f"https://{region}.{self.TTS_SPEECH_DOMAIN}{self.TTS_ENDPOINT_PATH}" return f"https://{self.TTS_SPEECH_DOMAIN}{self.TTS_ENDPOINT_PATH}" - def is_ssml_input(self, input: str) -> bool: """ Returns True if input is SSML, False otherwise @@ -402,30 +400,30 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): ) -> TextToSpeechRequestData: """ Transform OpenAI TTS request to Azure AVA TTS SSML format - + Note: optional_params should already be mapped via map_openai_params in main.py - + Supports Azure-specific SSML features: - style: Speaking style (e.g., "cheerful", "sad", "angry") - styledegree: Style intensity (0.01 to 2) - role: Voice role (e.g., "Girl", "Boy", "SeniorFemale", "SeniorMale") - lang: Language code for multilingual voices (e.g., "es-ES", "fr-FR") - + Auto-detects SSML: - If input contains , it's passed through as-is without transformation - + Returns: TextToSpeechRequestData: Contains SSML body and Azure-specific headers """ # Get voice (already mapped in main.py, or use default) azure_voice = voice or self.DEFAULT_VOICE - + # Get output format (already mapped in main.py) output_format = optional_params.get( "output_format", "audio-24khz-48kbitrate-mono-mp3" ) headers["X-Microsoft-OutputFormat"] = output_format - + # Auto-detect SSML: if input contains , pass it through as-is # Similar to Vertex AI behavior - check if input looks like SSML if self.is_ssml_input(input=input): @@ -433,14 +431,14 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): ssml_body=input, headers=headers, ) - + # Build SSML from plain text rate = optional_params.get("rate", "0%") style = optional_params.get("style") styledegree = optional_params.get("styledegree") role = optional_params.get("role") lang = optional_params.get("lang") - + # Escape XML special characters in input text escaped_input = ( input.replace("&", "&") @@ -449,19 +447,19 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): .replace('"', """) .replace("'", "'") ) - + # Determine if we need mstts namespace (for express-as element) use_mstts = style or role or styledegree - + # Build the xmlns attributes if use_mstts: xmlns = "xmlns='http://www.w3.org/2001/10/synthesis' xmlns:mstts='https://www.w3.org/2001/mstts'" else: xmlns = "xmlns='http://www.w3.org/2001/10/synthesis'" - + # Build the inner content with prosody prosody_content = f"{escaped_input}" - + # Wrap in mstts:express-as if style or role is specified voice_content = self._build_express_as_element( content=prosody_content, @@ -469,20 +467,20 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): styledegree=styledegree, role=role, ) - + # Build voice element with optional xml:lang attribute voice_lang = self._get_voice_language( voice_name=azure_voice, explicit_lang=lang, ) voice_lang_attr = f" xml:lang='{voice_lang}'" if voice_lang else "" - + ssml_body = f""" {voice_content} """ - + return { "ssml_body": ssml_body, "headers": headers, @@ -496,7 +494,7 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): ) -> "HttpxBinaryResponseContent": """ Transform Azure AVA TTS response to standard format - + Azure returns the audio data directly in the response body """ from litellm.types.llms.openai import HttpxBinaryResponseContent @@ -504,4 +502,3 @@ class AzureAVATextToSpeechConfig(BaseTextToSpeechConfig): # Azure returns audio data directly in the response body # Wrap it in HttpxBinaryResponseContent for consistent return type return HttpxBinaryResponseContent(raw_response) - diff --git a/litellm/llms/azure/vector_stores/transformation.py b/litellm/llms/azure/vector_stores/transformation.py index f1cd81b2bf2..a98e7ae8cb6 100644 --- a/litellm/llms/azure/vector_stores/transformation.py +++ b/litellm/llms/azure/vector_stores/transformation.py @@ -14,14 +14,12 @@ class AzureOpenAIVectorStoreConfig(OpenAIVectorStoreConfig): return BaseAzureLLM._get_base_azure_url( api_base=api_base, litellm_params=litellm_params, - route="/openai/vector_stores" + route="/openai/vector_stores", ) - def validate_environment( - self, headers: dict, litellm_params: Optional[GenericLiteLLMParams] + self, headers: dict, litellm_params: Optional[GenericLiteLLMParams] ) -> dict: return BaseAzureLLM._base_validate_azure_environment( - headers=headers, - litellm_params=litellm_params - ) \ No newline at end of file + headers=headers, litellm_params=litellm_params + ) diff --git a/litellm/llms/azure/videos/transformation.py b/litellm/llms/azure/videos/transformation.py index a6fbd8cef8b..1ee0e95fb0a 100644 --- a/litellm/llms/azure/videos/transformation.py +++ b/litellm/llms/azure/videos/transformation.py @@ -4,6 +4,7 @@ from litellm.types.videos.main import VideoCreateOptionalRequestParams from litellm.types.router import GenericLiteLLMParams from litellm.llms.azure.common_utils import BaseAzureLLM from litellm.llms.openai.videos.transformation import OpenAIVideoConfig + if TYPE_CHECKING: from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj @@ -64,16 +65,15 @@ class AzureVideoConfig(OpenAIVideoConfig): # If litellm_params is provided, use it; otherwise create a new one if litellm_params is None: litellm_params = GenericLiteLLMParams() - + if api_key and not litellm_params.api_key: litellm_params.api_key = api_key - + # Use the base Azure validation method which properly handles: # 1. Credentials from litellm_credential_name via litellm_params # 2. Sets the correct "api-key" header (not "Authorization: Bearer") return BaseAzureLLM._base_validate_azure_environment( - headers=headers, - litellm_params=litellm_params + headers=headers, litellm_params=litellm_params ) def get_complete_url( @@ -90,4 +90,4 @@ class AzureVideoConfig(OpenAIVideoConfig): litellm_params=litellm_params, route="/openai/v1/videos", default_api_version="", - ) \ No newline at end of file + ) diff --git a/litellm/llms/azure_ai/agents/handler.py b/litellm/llms/azure_ai/agents/handler.py index 379dc1e1c55..9eeec7f4e36 100644 --- a/litellm/llms/azure_ai/agents/handler.py +++ b/litellm/llms/azure_ai/agents/handler.py @@ -56,7 +56,7 @@ else: class AzureAIAgentsHandler: """ Handler for Azure AI Agent Service. - + Executes the complete agent flow which requires multiple API calls. """ @@ -72,16 +72,22 @@ class AzureAIAgentsHandler: def _build_thread_url(self, api_base: str, api_version: str) -> str: return f"{api_base}/threads?api-version={api_version}" - def _build_messages_url(self, api_base: str, thread_id: str, api_version: str) -> str: + def _build_messages_url( + self, api_base: str, thread_id: str, api_version: str + ) -> str: return f"{api_base}/threads/{thread_id}/messages?api-version={api_version}" def _build_runs_url(self, api_base: str, thread_id: str, api_version: str) -> str: return f"{api_base}/threads/{thread_id}/runs?api-version={api_version}" - def _build_run_status_url(self, api_base: str, thread_id: str, run_id: str, api_version: str) -> str: + def _build_run_status_url( + self, api_base: str, thread_id: str, run_id: str, api_version: str + ) -> str: return f"{api_base}/threads/{thread_id}/runs/{run_id}?api-version={api_version}" - def _build_list_messages_url(self, api_base: str, thread_id: str, api_version: str) -> str: + def _build_list_messages_url( + self, api_base: str, thread_id: str, api_version: str + ) -> str: return f"{api_base}/threads/{thread_id}/messages?api-version={api_version}" def _build_create_thread_and_run_url(self, api_base: str, api_version: str) -> str: @@ -112,12 +118,19 @@ class AzureAIAgentsHandler: from litellm.types.utils import Choices, Message, Usage model_response.choices = [ - Choices(finish_reason="stop", index=0, message=Message(content=content, role="assistant")) + Choices( + finish_reason="stop", + index=0, + message=Message(content=content, role="assistant"), + ) ] model_response.model = model # Store thread_id for conversation continuity - if not hasattr(model_response, "_hidden_params") or model_response._hidden_params is None: + if ( + not hasattr(model_response, "_hidden_params") + or model_response._hidden_params is None + ): model_response._hidden_params = {} model_response._hidden_params["thread_id"] = thread_id @@ -126,7 +139,9 @@ class AzureAIAgentsHandler: from litellm.utils import token_counter prompt_tokens = token_counter(model="gpt-3.5-turbo", messages=messages) - completion_tokens = token_counter(model="gpt-3.5-turbo", text=content, count_response_tokens=True) + completion_tokens = token_counter( + model="gpt-3.5-turbo", text=content, count_response_tokens=True + ) setattr( model_response, "usage", @@ -150,34 +165,43 @@ class AzureAIAgentsHandler: headers: Optional[dict], ) -> tuple: """Prepare common parameters for completion. - + Azure Foundry Agents API uses Bearer token authentication: - Authorization: Bearer (Azure AD token from 'az account get-access-token --resource https://ai.azure.com') - + See: https://learn.microsoft.com/en-us/azure/ai-foundry/agents/quickstart """ if headers is None: headers = {} headers["Content-Type"] = "application/json" - + # Azure Foundry Agents uses Bearer token authentication # The api_key here is expected to be an Azure AD token if api_key: headers["Authorization"] = f"Bearer {api_key}" - api_version = optional_params.get("api_version", self.config.DEFAULT_API_VERSION) + api_version = optional_params.get( + "api_version", self.config.DEFAULT_API_VERSION + ) agent_id = self.config._get_agent_id(model, optional_params) thread_id = optional_params.get("thread_id") api_base = api_base.rstrip("/") - verbose_logger.debug(f"Azure AI Agents completion - api_base: {api_base}, agent_id: {agent_id}") + verbose_logger.debug( + f"Azure AI Agents completion - api_base: {api_base}, agent_id: {agent_id}" + ) return headers, api_version, agent_id, thread_id, api_base - def _check_response(self, response: httpx.Response, expected_codes: List[int], error_msg: str): + def _check_response( + self, response: httpx.Response, expected_codes: List[int], error_msg: str + ): """Check response status and raise error if not expected.""" if response.status_code not in expected_codes: - raise AzureAIAgentsError(status_code=response.status_code, message=f"{error_msg}: {response.text}") + raise AzureAIAgentsError( + status_code=response.status_code, + message=f"{error_msg}: {response.text}", + ) # ------------------------------------------------------------------------- # Sync Completion @@ -200,16 +224,30 @@ class AzureAIAgentsHandler: from litellm.llms.custom_httpx.http_handler import _get_httpx_client if client is None: - client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) + client = _get_httpx_client( + params={"ssl_verify": litellm_params.get("ssl_verify", None)} + ) - headers, api_version, agent_id, thread_id, api_base = self._prepare_completion_params( + ( + headers, + api_version, + agent_id, + thread_id, + api_base, + ) = self._prepare_completion_params( model, api_base, api_key, optional_params, headers ) - def make_request(method: str, url: str, json_data: Optional[dict] = None) -> httpx.Response: + def make_request( + method: str, url: str, json_data: Optional[dict] = None + ) -> httpx.Response: if method == "GET": return client.get(url=url, headers=headers) - return client.post(url=url, headers=headers, data=json.dumps(json_data) if json_data else None) + return client.post( + url=url, + headers=headers, + data=json.dumps(json_data) if json_data else None, + ) # Execute the agent flow thread_id, content = self._execute_agent_flow_sync( @@ -222,7 +260,9 @@ class AzureAIAgentsHandler: optional_params=optional_params, ) - return self._build_model_response(model, content, model_response, thread_id, messages) + return self._build_model_response( + model, content, model_response, thread_id, messages + ) def _execute_agent_flow_sync( self, @@ -235,11 +275,15 @@ class AzureAIAgentsHandler: optional_params: dict, ) -> Tuple[str, str]: """Execute the agent flow synchronously. Returns (thread_id, content).""" - + # Step 1: Create thread if not provided if not thread_id: - verbose_logger.debug(f"Creating thread at: {self._build_thread_url(api_base, api_version)}") - response = make_request("POST", self._build_thread_url(api_base, api_version), {}) + verbose_logger.debug( + f"Creating thread at: {self._build_thread_url(api_base, api_version)}" + ) + response = make_request( + "POST", self._build_thread_url(api_base, api_version), {} + ) self._check_response(response, [200, 201], "Failed to create thread") thread_id = response.json()["id"] verbose_logger.debug(f"Created thread: {thread_id}") @@ -251,42 +295,58 @@ class AzureAIAgentsHandler: for msg in messages: if msg.get("role") in ["user", "system"]: url = self._build_messages_url(api_base, thread_id, api_version) - response = make_request("POST", url, {"role": "user", "content": msg.get("content", "")}) + response = make_request( + "POST", url, {"role": "user", "content": msg.get("content", "")} + ) self._check_response(response, [200, 201], "Failed to add message") # Step 3: Create run run_payload = {"assistant_id": agent_id} if "instructions" in optional_params: run_payload["instructions"] = optional_params["instructions"] - - response = make_request("POST", self._build_runs_url(api_base, thread_id, api_version), run_payload) + + response = make_request( + "POST", self._build_runs_url(api_base, thread_id, api_version), run_payload + ) self._check_response(response, [200, 201], "Failed to create run") run_id = response.json()["id"] verbose_logger.debug(f"Created run: {run_id}") # Step 4: Poll for completion - status_url = self._build_run_status_url(api_base, thread_id, run_id, api_version) + status_url = self._build_run_status_url( + api_base, thread_id, run_id, api_version + ) for _ in range(self.config.MAX_POLL_ATTEMPTS): response = make_request("GET", status_url) self._check_response(response, [200], "Failed to get run status") - + status = response.json().get("status") verbose_logger.debug(f"Run status: {status}") - + if status == "completed": break elif status in ["failed", "cancelled", "expired"]: - error_msg = response.json().get("last_error", {}).get("message", "Unknown error") - raise AzureAIAgentsError(status_code=500, message=f"Run {status}: {error_msg}") - + error_msg = ( + response.json() + .get("last_error", {}) + .get("message", "Unknown error") + ) + raise AzureAIAgentsError( + status_code=500, message=f"Run {status}: {error_msg}" + ) + time.sleep(self.config.POLL_INTERVAL_SECONDS) else: - raise AzureAIAgentsError(status_code=408, message="Run timed out waiting for completion") + raise AzureAIAgentsError( + status_code=408, message="Run timed out waiting for completion" + ) # Step 5: Get messages - response = make_request("GET", self._build_list_messages_url(api_base, thread_id, api_version)) + response = make_request( + "GET", self._build_list_messages_url(api_base, thread_id, api_version) + ) self._check_response(response, [200], "Failed to get messages") - + content = self._extract_content_from_messages(response.json()) return thread_id, content @@ -317,14 +377,26 @@ class AzureAIAgentsHandler: params={"ssl_verify": litellm_params.get("ssl_verify", None)}, ) - headers, api_version, agent_id, thread_id, api_base = self._prepare_completion_params( + ( + headers, + api_version, + agent_id, + thread_id, + api_base, + ) = self._prepare_completion_params( model, api_base, api_key, optional_params, headers ) - async def make_request(method: str, url: str, json_data: Optional[dict] = None) -> httpx.Response: + async def make_request( + method: str, url: str, json_data: Optional[dict] = None + ) -> httpx.Response: if method == "GET": return await client.get(url=url, headers=headers) - return await client.post(url=url, headers=headers, data=json.dumps(json_data) if json_data else None) + return await client.post( + url=url, + headers=headers, + data=json.dumps(json_data) if json_data else None, + ) # Execute the agent flow thread_id, content = await self._execute_agent_flow_async( @@ -337,7 +409,9 @@ class AzureAIAgentsHandler: optional_params=optional_params, ) - return self._build_model_response(model, content, model_response, thread_id, messages) + return self._build_model_response( + model, content, model_response, thread_id, messages + ) async def _execute_agent_flow_async( self, @@ -350,11 +424,15 @@ class AzureAIAgentsHandler: optional_params: dict, ) -> Tuple[str, str]: """Execute the agent flow asynchronously. Returns (thread_id, content).""" - + # Step 1: Create thread if not provided if not thread_id: - verbose_logger.debug(f"Creating thread at: {self._build_thread_url(api_base, api_version)}") - response = await make_request("POST", self._build_thread_url(api_base, api_version), {}) + verbose_logger.debug( + f"Creating thread at: {self._build_thread_url(api_base, api_version)}" + ) + response = await make_request( + "POST", self._build_thread_url(api_base, api_version), {} + ) self._check_response(response, [200, 201], "Failed to create thread") thread_id = response.json()["id"] verbose_logger.debug(f"Created thread: {thread_id}") @@ -366,42 +444,58 @@ class AzureAIAgentsHandler: for msg in messages: if msg.get("role") in ["user", "system"]: url = self._build_messages_url(api_base, thread_id, api_version) - response = await make_request("POST", url, {"role": "user", "content": msg.get("content", "")}) + response = await make_request( + "POST", url, {"role": "user", "content": msg.get("content", "")} + ) self._check_response(response, [200, 201], "Failed to add message") # Step 3: Create run run_payload = {"assistant_id": agent_id} if "instructions" in optional_params: run_payload["instructions"] = optional_params["instructions"] - - response = await make_request("POST", self._build_runs_url(api_base, thread_id, api_version), run_payload) + + response = await make_request( + "POST", self._build_runs_url(api_base, thread_id, api_version), run_payload + ) self._check_response(response, [200, 201], "Failed to create run") run_id = response.json()["id"] verbose_logger.debug(f"Created run: {run_id}") # Step 4: Poll for completion - status_url = self._build_run_status_url(api_base, thread_id, run_id, api_version) + status_url = self._build_run_status_url( + api_base, thread_id, run_id, api_version + ) for _ in range(self.config.MAX_POLL_ATTEMPTS): response = await make_request("GET", status_url) self._check_response(response, [200], "Failed to get run status") - + status = response.json().get("status") verbose_logger.debug(f"Run status: {status}") - + if status == "completed": break elif status in ["failed", "cancelled", "expired"]: - error_msg = response.json().get("last_error", {}).get("message", "Unknown error") - raise AzureAIAgentsError(status_code=500, message=f"Run {status}: {error_msg}") - + error_msg = ( + response.json() + .get("last_error", {}) + .get("message", "Unknown error") + ) + raise AzureAIAgentsError( + status_code=500, message=f"Run {status}: {error_msg}" + ) + await asyncio.sleep(self.config.POLL_INTERVAL_SECONDS) else: - raise AzureAIAgentsError(status_code=408, message="Run timed out waiting for completion") + raise AzureAIAgentsError( + status_code=408, message="Run timed out waiting for completion" + ) # Step 5: Get messages - response = await make_request("GET", self._build_list_messages_url(api_base, thread_id, api_version)) + response = await make_request( + "GET", self._build_list_messages_url(api_base, thread_id, api_version) + ) self._check_response(response, [200], "Failed to get messages") - + content = self._extract_content_from_messages(response.json()) return thread_id, content @@ -424,7 +518,13 @@ class AzureAIAgentsHandler: import litellm from litellm.llms.custom_httpx.http_handler import get_async_httpx_client - headers, api_version, agent_id, thread_id, api_base = self._prepare_completion_params( + ( + headers, + api_version, + agent_id, + thread_id, + api_base, + ) = self._prepare_completion_params( model, api_base, api_key, optional_params, headers ) @@ -432,20 +532,19 @@ class AzureAIAgentsHandler: thread_messages = [] for msg in messages: if msg.get("role") in ["user", "system"]: - thread_messages.append({ - "role": "user", - "content": msg.get("content", "") - }) + thread_messages.append( + {"role": "user", "content": msg.get("content", "")} + ) payload: Dict[str, Any] = { "assistant_id": agent_id, "stream": True, } - + # Add thread with messages if we don't have an existing thread if not thread_id: payload["thread"] = {"messages": thread_messages} - + if "instructions" in optional_params: payload["instructions"] = optional_params["instructions"] @@ -469,7 +568,7 @@ class AzureAIAgentsHandler: error_text = await response.aread() raise AzureAIAgentsError( status_code=response.status_code, - message=f"Streaming request failed: {error_text.decode()}" + message=f"Streaming request failed: {error_text.decode()}", ) async for chunk in self._process_sse_stream(response, model): @@ -482,23 +581,23 @@ class AzureAIAgentsHandler: ) -> AsyncIterator: """Process SSE stream and yield OpenAI-compatible streaming chunks.""" from litellm.types.utils import Delta, ModelResponseStream, StreamingChoices - + response_id = f"chatcmpl-{uuid.uuid4().hex[:8]}" created = int(time.time()) thread_id = None - + current_event = None - + async for line in response.aiter_lines(): line = line.strip() - + if line.startswith("event:"): current_event = line[6:].strip() continue - + if line.startswith("data:"): data_str = line[5:].strip() - + if data_str == "[DONE]": # Send final chunk with finish_reason final_chunk = ModelResponseStream( @@ -518,17 +617,17 @@ class AzureAIAgentsHandler: final_chunk._hidden_params = {"thread_id": thread_id} yield final_chunk return - + try: data = json.loads(data_str) except json.JSONDecodeError: continue - + # Extract thread_id from thread.created event if current_event == "thread.created" and "id" in data: thread_id = data["id"] verbose_logger.debug(f"Stream created thread: {thread_id}") - + # Process message deltas - this is where the actual content comes if current_event == "thread.message.delta": delta_content = data.get("delta", {}).get("content", []) @@ -545,7 +644,9 @@ class AzureAIAgentsHandler: StreamingChoices( finish_reason=None, index=0, - delta=Delta(content=text_value, role="assistant"), + delta=Delta( + content=text_value, role="assistant" + ), ) ], ) diff --git a/litellm/llms/azure_ai/agents/transformation.py b/litellm/llms/azure_ai/agents/transformation.py index 01945aad323..777509fa82c 100644 --- a/litellm/llms/azure_ai/agents/transformation.py +++ b/litellm/llms/azure_ai/agents/transformation.py @@ -56,9 +56,9 @@ class AzureAIAgentsConfig(BaseConfig): Azure AI Agent Service is a fully managed service for building AI agents that can understand natural language and perform tasks. - + Model format: azure_ai/agents/ - + The flow is: 1. Create a thread 2. Add user messages to the thread @@ -70,7 +70,7 @@ class AzureAIAgentsConfig(BaseConfig): # GA version: 2025-05-01, Preview: 2025-05-15-preview # See: https://learn.microsoft.com/en-us/azure/ai-foundry/agents/quickstart DEFAULT_API_VERSION = "2025-05-01" - + # Polling configuration MAX_POLL_ATTEMPTS = 60 POLL_INTERVAL_SECONDS = 1.0 @@ -82,7 +82,7 @@ class AzureAIAgentsConfig(BaseConfig): def is_azure_ai_agents_route(model: str) -> bool: """ Check if the model is an Azure AI Agents route. - + Model format: azure_ai/agents/ """ return "agents/" in model @@ -91,7 +91,7 @@ class AzureAIAgentsConfig(BaseConfig): def get_agent_id_from_model(model: str) -> str: """ Extract agent ID from the model string. - + Model format: azure_ai/agents/ -> or: agents/ -> """ @@ -153,12 +153,12 @@ class AzureAIAgentsConfig(BaseConfig): ) -> str: """ Get the base URL for Azure AI Agent Service. - + The actual endpoint will vary based on the operation: - /openai/threads for creating threads - /openai/threads/{thread_id}/messages for adding messages - /openai/threads/{thread_id}/runs for creating runs - + This returns the base URL that will be modified for each operation. """ if api_base is None: @@ -178,7 +178,9 @@ class AzureAIAgentsConfig(BaseConfig): model format: "azure_ai/agents/" or "agents/" or just "" """ - agent_id = optional_params.get("agent_id") or optional_params.get("assistant_id") + agent_id = optional_params.get("agent_id") or optional_params.get( + "assistant_id" + ) if agent_id: return agent_id @@ -195,7 +197,7 @@ class AzureAIAgentsConfig(BaseConfig): ) -> dict: """ Transform the request for Azure Agents. - + This stores the necessary data for the multi-step agent flow. The actual API calls happen in the custom handler. """ @@ -246,10 +248,10 @@ class AzureAIAgentsConfig(BaseConfig): ) -> dict: """ Validate and set up environment for Azure Foundry Agents requests. - + Azure Foundry Agents uses Bearer token authentication with Azure AD tokens. Get token via: az account get-access-token --resource 'https://ai.azure.com' - + See: https://learn.microsoft.com/en-us/azure/ai-foundry/agents/quickstart """ headers["Content-Type"] = "application/json" @@ -326,15 +328,15 @@ class AzureAIAgentsConfig(BaseConfig): ) -> Any: """ Dispatch method for Azure Foundry Agents completion. - + Routes to sync or async completion based on acompletion flag. Supports native streaming via SSE when stream=True and acompletion=True. - + Authentication: Uses Azure AD Bearer tokens. - Pass api_key directly as an Azure AD token - Or set up Azure AD credentials via environment variables for automatic token retrieval: - AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET (Service Principal) - + See: https://learn.microsoft.com/en-us/azure/ai-foundry/agents/quickstart """ from litellm.llms.azure.common_utils import get_azure_ad_token @@ -349,7 +351,7 @@ class AzureAIAgentsConfig(BaseConfig): azure_auth_params = dict(litellm_params) if litellm_params else {} azure_auth_params["azure_scope"] = "https://ai.azure.com/.default" api_key = get_azure_ad_token(GenericLiteLLMParams(**azure_auth_params)) - + if api_key is None: raise ValueError( "api_key (Azure AD token) is required for Azure Foundry Agents. " diff --git a/litellm/llms/azure_ai/anthropic/__init__.py b/litellm/llms/azure_ai/anthropic/__init__.py index 233f22999f0..931c71de3b3 100644 --- a/litellm/llms/azure_ai/anthropic/__init__.py +++ b/litellm/llms/azure_ai/anthropic/__init__.py @@ -6,7 +6,11 @@ from .transformation import AzureAnthropicConfig try: from .messages_transformation import AzureAnthropicMessagesConfig - __all__ = ["AzureAnthropicChatCompletion", "AzureAnthropicConfig", "AzureAnthropicMessagesConfig"] + + __all__ = [ + "AzureAnthropicChatCompletion", + "AzureAnthropicConfig", + "AzureAnthropicMessagesConfig", + ] except ImportError: __all__ = ["AzureAnthropicChatCompletion", "AzureAnthropicConfig"] - diff --git a/litellm/llms/azure_ai/anthropic/count_tokens/handler.py b/litellm/llms/azure_ai/anthropic/count_tokens/handler.py index 2cba27925c6..e24fc2097d2 100644 --- a/litellm/llms/azure_ai/anthropic/count_tokens/handler.py +++ b/litellm/llms/azure_ai/anthropic/count_tokens/handler.py @@ -87,7 +87,9 @@ class AzureAIAnthropicCountTokensHandler(AzureAIAnthropicCountTokensConfig): ) # Use provided timeout or fall back to litellm.request_timeout - request_timeout = timeout if timeout is not None else litellm.request_timeout + request_timeout = ( + timeout if timeout is not None else litellm.request_timeout + ) response = await async_client.post( endpoint_url, diff --git a/litellm/llms/azure_ai/anthropic/handler.py b/litellm/llms/azure_ai/anthropic/handler.py index fe4524fd5be..a2263e72a14 100644 --- a/litellm/llms/azure_ai/anthropic/handler.py +++ b/litellm/llms/azure_ai/anthropic/handler.py @@ -64,7 +64,7 @@ class AzureAnthropicChatCompletion(AnthropicChatCompletion): # Use AzureAnthropicConfig for both azure_anthropic and azure_ai Claude models config = AzureAnthropicConfig() - + headers = config.validate_environment( api_key=api_key, headers=headers, @@ -224,4 +224,3 @@ class AzureAnthropicChatCompletion(AnthropicChatCompletion): encoding=encoding, json_mode=json_mode, ) - diff --git a/litellm/llms/azure_ai/anthropic/messages_transformation.py b/litellm/llms/azure_ai/anthropic/messages_transformation.py index 8e60e84391b..59d8fb02c6d 100644 --- a/litellm/llms/azure_ai/anthropic/messages_transformation.py +++ b/litellm/llms/azure_ai/anthropic/messages_transformation.py @@ -125,6 +125,7 @@ class AzureAnthropicMessagesConfig(AnthropicMessagesConfig): Processes both `system` and `messages` content blocks. """ + def _sanitize(cache_control: Any) -> None: if isinstance(cache_control, dict): cache_control.pop("scope", None) @@ -163,4 +164,3 @@ class AzureAnthropicMessagesConfig(AnthropicMessagesConfig): ) self._remove_scope_from_cache_control(anthropic_messages_request) return anthropic_messages_request - diff --git a/litellm/llms/azure_ai/anthropic/transformation.py b/litellm/llms/azure_ai/anthropic/transformation.py index c5510db68b1..5d8f27b97df 100644 --- a/litellm/llms/azure_ai/anthropic/transformation.py +++ b/litellm/llms/azure_ai/anthropic/transformation.py @@ -49,7 +49,7 @@ class AzureAnthropicConfig(AnthropicConfig): # Set api_key if provided and not already set if api_key and not litellm_params_obj.api_key: litellm_params_obj.api_key = api_key - + # Use Azure authentication logic headers = BaseAzureLLM._base_validate_azure_environment( headers=headers, litellm_params=litellm_params_obj @@ -86,7 +86,6 @@ class AzureAnthropicConfig(AnthropicConfig): if "anthropic-version" not in headers: headers["anthropic-version"] = "2023-06-01" - return headers def transform_request( @@ -116,4 +115,3 @@ class AzureAnthropicConfig(AnthropicConfig): data.pop("stream_options", None) return data - diff --git a/litellm/llms/azure_ai/azure_model_router/transformation.py b/litellm/llms/azure_ai/azure_model_router/transformation.py index 3d6dc53c515..57acb147063 100644 --- a/litellm/llms/azure_ai/azure_model_router/transformation.py +++ b/litellm/llms/azure_ai/azure_model_router/transformation.py @@ -17,7 +17,7 @@ from litellm.types.utils import ModelResponse class AzureModelRouterConfig(AzureAIStudioConfig): """ Configuration for Azure AI Foundry Model Router. - + Handles: - Stripping model_router prefix before sending to Azure API - Preserving full model path in responses for cost tracking @@ -34,7 +34,7 @@ class AzureModelRouterConfig(AzureAIStudioConfig): ) -> dict: """ Transform request for Model Router. - + Strips the model_router/ prefix so only the deployment name is sent to Azure. Example: model_router/azure-model-router -> azure-model-router """ @@ -42,7 +42,7 @@ class AzureModelRouterConfig(AzureAIStudioConfig): # Get base model name (strips routing prefixes like model_router/) base_model: str = AzureFoundryModelInfo.get_base_model(model) - + return super().transform_request( base_model, messages, optional_params, litellm_params, headers ) @@ -63,25 +63,18 @@ class AzureModelRouterConfig(AzureAIStudioConfig): ) -> ModelResponse: """ Transform response for Model Router. - - Preserves the original model path (including model_router/ prefix) in the response - for proper cost tracking and logging. + + Extracts the actual model used from the Azure response (e.g., gpt-5-nano-2025-08-07) + and returns it with the azure_ai/ prefix for proper display and cost tracking. """ from litellm.llms.azure_ai.common_utils import AzureFoundryModelInfo - # Preserve the original model from litellm_params (includes routing prefixes like model_router/) - # This ensures cost tracking and logging use the full model path - original_model: str = litellm_params.get("model") or model - if not original_model.startswith("azure_ai/"): - # Add provider prefix if not already present - model_response.model = f"azure_ai/{original_model}" - else: - model_response.model = original_model - # Get base model for the parent call (strips routing prefixes for API compatibility) base_model: str = AzureFoundryModelInfo.get_base_model(model) - - return super().transform_response( + + # Call parent transform_response first - this will extract the actual model + # from the raw response (e.g., "gpt-5-nano-2025-08-07") + model_response = super().transform_response( model=base_model, raw_response=raw_response, model_response=model_response, @@ -94,32 +87,33 @@ class AzureModelRouterConfig(AzureAIStudioConfig): api_key=api_key, json_mode=json_mode, ) + return model_response def calculate_additional_costs( self, model: str, prompt_tokens: int, completion_tokens: int ) -> Optional[dict]: """ Calculate additional costs for Azure Model Router. - + Adds a flat infrastructure cost of $0.14 per M input tokens for using the Model Router. - + Args: model: The model name (should be a model router model) prompt_tokens: Number of prompt tokens completion_tokens: Number of completion tokens - + Returns: Dictionary with additional costs, or None if not applicable. """ from litellm.llms.azure_ai.cost_calculator import ( calculate_azure_model_router_flat_cost, ) - + flat_cost = calculate_azure_model_router_flat_cost( model=model, prompt_tokens=prompt_tokens ) - + if flat_cost > 0: return {"Azure Model Router Flat Cost": flat_cost} - + return None diff --git a/litellm/llms/azure_ai/chat/transformation.py b/litellm/llms/azure_ai/chat/transformation.py index 585efd3307d..529ec71c530 100644 --- a/litellm/llms/azure_ai/chat/transformation.py +++ b/litellm/llms/azure_ai/chat/transformation.py @@ -90,7 +90,10 @@ class AzureAIStudioConfig(OpenAIConfig): """ parsed_url = urlparse(api_base) host = parsed_url.hostname - if host and (host.endswith(".services.ai.azure.com") or host.endswith(".openai.azure.com")): + if host and ( + host.endswith(".services.ai.azure.com") + or host.endswith(".openai.azure.com") + ): return True return False @@ -137,9 +140,13 @@ class AzureAIStudioConfig(OpenAIConfig): # Add the path to the base URL if "services.ai.azure.com" in api_base: - new_url = _add_path_to_api_base(api_base=api_base, ending_path="/models/chat/completions") + new_url = _add_path_to_api_base( + api_base=api_base, ending_path="/models/chat/completions" + ) else: - new_url = _add_path_to_api_base(api_base=api_base, ending_path="/chat/completions") + new_url = _add_path_to_api_base( + api_base=api_base, ending_path="/chat/completions" + ) # Use the new query_params dictionary final_url = httpx.URL(new_url).copy_with(params=query_params) @@ -209,7 +216,11 @@ class AzureAIStudioConfig(OpenAIConfig): dynamic_api_key = api_key or get_secret_str("AZURE_AI_API_KEY") if self._is_azure_openai_model(model=model, api_base=api_base): - verbose_logger.debug("Model={} is Azure OpenAI model. Setting custom_llm_provider='azure'.".format(model)) + verbose_logger.debug( + "Model={} is Azure OpenAI model. Setting custom_llm_provider='azure'.".format( + model + ) + ) custom_llm_provider = "azure" return api_base, dynamic_api_key, custom_llm_provider @@ -225,7 +236,9 @@ class AzureAIStudioConfig(OpenAIConfig): if extra_body and isinstance(extra_body, dict): optional_params.update(extra_body) optional_params.pop("max_retries", None) - return super().transform_request(model, messages, optional_params, litellm_params, headers) + return super().transform_request( + model, messages, optional_params, litellm_params, headers + ) def transform_response( self, @@ -264,30 +277,47 @@ class AzureAIStudioConfig(OpenAIConfig): if should_drop_params and "Extra inputs are not permitted" in error_text: return True - elif "unknown field: parameter index is not a valid field" in error_text: # remove index from tool calls + elif ( + "unknown field: parameter index is not a valid field" in error_text + ): # remove index from tool calls return True elif ( - AzureFoundryErrorStrings.SET_EXTRA_PARAMETERS_TO_PASS_THROUGH.value in error_text + AzureFoundryErrorStrings.SET_EXTRA_PARAMETERS_TO_PASS_THROUGH.value + in error_text ): # remove extra-parameters from tool calls return True - return super().should_retry_llm_api_inside_llm_translation_on_http_error(e=e, litellm_params=litellm_params) + return super().should_retry_llm_api_inside_llm_translation_on_http_error( + e=e, litellm_params=litellm_params + ) @property def max_retry_on_unprocessable_entity_error(self) -> int: return 2 - def transform_request_on_unprocessable_entity_error(self, e: httpx.HTTPStatusError, request_data: dict) -> dict: + def transform_request_on_unprocessable_entity_error( + self, e: httpx.HTTPStatusError, request_data: dict + ) -> dict: _messages = cast(Optional[List[AllMessageValues]], request_data.get("messages")) - if "unknown field: parameter index is not a valid field" in e.response.text and _messages is not None: + if ( + "unknown field: parameter index is not a valid field" in e.response.text + and _messages is not None + ): litellm.remove_index_from_tool_calls( messages=_messages, ) - elif AzureFoundryErrorStrings.SET_EXTRA_PARAMETERS_TO_PASS_THROUGH.value in e.response.text: - request_data = self._drop_extra_params_from_request_data(request_data, e.response.text) + elif ( + AzureFoundryErrorStrings.SET_EXTRA_PARAMETERS_TO_PASS_THROUGH.value + in e.response.text + ): + request_data = self._drop_extra_params_from_request_data( + request_data, e.response.text + ) data = drop_params_from_unprocessable_entity_error(e=e, data=request_data) return data - def _drop_extra_params_from_request_data(self, request_data: dict, error_text: str) -> dict: + def _drop_extra_params_from_request_data( + self, request_data: dict, error_text: str + ) -> dict: params_to_drop = self._extract_params_to_drop_from_error_text(error_text) if params_to_drop: for param in params_to_drop: @@ -295,7 +325,9 @@ class AzureAIStudioConfig(OpenAIConfig): request_data.pop(param, None) return request_data - def _extract_params_to_drop_from_error_text(self, error_text: str) -> Optional[List[str]]: + def _extract_params_to_drop_from_error_text( + self, error_text: str + ) -> Optional[List[str]]: """ Error text looks like this" "Extra parameters ['stream_options', 'extra-parameters'] are not allowed when extra-parameters is not set or set to be 'error'. diff --git a/litellm/llms/azure_ai/common_utils.py b/litellm/llms/azure_ai/common_utils.py index 47d397d6e98..ecb36b20427 100644 --- a/litellm/llms/azure_ai/common_utils.py +++ b/litellm/llms/azure_ai/common_utils.py @@ -18,7 +18,7 @@ class AzureFoundryModelInfo(BaseLLMModelInfo): Get the Azure AI route for the given model. Similar to BedrockModelInfo.get_bedrock_route(). - + Supported routes: - agents: azure_ai/agents/ - model_router: azure_ai/model_router/ or models with "model-router"/"model_router" in name @@ -29,7 +29,7 @@ class AzureFoundryModelInfo(BaseLLMModelInfo): # Detect model router by prefix (model_router/) or by name containing "model-router"/"model_router" model_lower = model.lower() if ( - "model_router/" in model_lower + "model_router/" in model_lower or "model-router/" in model_lower or "model-router" in model_lower or "model_router" in model_lower @@ -78,7 +78,7 @@ class AzureFoundryModelInfo(BaseLLMModelInfo): ) -> List[str]: """ Returns a list of models supported by Azure AI. - + Azure AI doesn't have a standard model listing endpoint, so this returns an empty list. """ @@ -92,15 +92,15 @@ class AzureFoundryModelInfo(BaseLLMModelInfo): def strip_model_router_prefix(model: str) -> str: """ Strip the model_router prefix from model name. - + Examples: - "model_router/gpt-4o" -> "gpt-4o" - "model-router/gpt-4o" -> "gpt-4o" - "gpt-4o" -> "gpt-4o" - + Args: model: Model name potentially with model_router prefix - + Returns: Model name without the prefix """ @@ -109,15 +109,15 @@ class AzureFoundryModelInfo(BaseLLMModelInfo): if "model-router/" in model: return model.split("model-router/", 1)[1] return model - + @staticmethod def get_base_model(model: str) -> str: """ Get the base model name, stripping any Azure AI routing prefixes. - + Args: model: Model name potentially with routing prefixes - + Returns: Base model name """ @@ -129,32 +129,35 @@ class AzureFoundryModelInfo(BaseLLMModelInfo): def get_azure_ai_config_for_model(model: str): """ Get the appropriate Azure AI config class for the given model. - + Routes to specialized configs based on model type: - Model Router: AzureModelRouterConfig - - Claude models: AzureAnthropicConfig + - Claude models: AzureAnthropicConfig - Default: AzureAIStudioConfig - + Args: model: The model name - + Returns: The appropriate config instance """ azure_ai_route = AzureFoundryModelInfo.get_azure_ai_route(model) - + if azure_ai_route == "model_router": from litellm.llms.azure_ai.azure_model_router.transformation import ( AzureModelRouterConfig, ) + return AzureModelRouterConfig() elif "claude" in model.lower(): from litellm.llms.azure_ai.anthropic.transformation import ( AzureAnthropicConfig, ) + return AzureAnthropicConfig() else: from litellm.llms.azure_ai.chat.transformation import AzureAIStudioConfig + return AzureAIStudioConfig() def validate_environment( diff --git a/litellm/llms/azure_ai/cost_calculator.py b/litellm/llms/azure_ai/cost_calculator.py index 6fb29962677..3cca61b2186 100644 --- a/litellm/llms/azure_ai/cost_calculator.py +++ b/litellm/llms/azure_ai/cost_calculator.py @@ -14,22 +14,22 @@ from litellm.utils import get_model_info def _is_azure_model_router(model: str) -> bool: """ Check if the model is Azure AI Foundry Model Router. - + Detects patterns like: - "azure-model-router" - - "model-router" + - "model-router" - "model_router/" - "model-router/" - + Args: model: The model name - + Returns: bool: True if this is a model router model """ model_lower = model.lower() return ( - "model-router" in model_lower + "model-router" in model_lower or "model_router" in model_lower or model_lower == "azure-model-router" ) @@ -38,50 +38,50 @@ def _is_azure_model_router(model: str) -> bool: def calculate_azure_model_router_flat_cost(model: str, prompt_tokens: int) -> float: """ Calculate the flat cost for Azure AI Foundry Model Router. - + Args: model: The model name (should be a model router model) prompt_tokens: Number of prompt tokens - + Returns: float: The flat cost in USD, or 0.0 if not applicable """ if not _is_azure_model_router(model): return 0.0 - + # Get the model router pricing from model_prices_and_context_window.json # Use "model_router" as the key (without actual model name suffix) model_info = get_model_info(model="model_router", custom_llm_provider="azure_ai") router_flat_cost_per_token = model_info.get("input_cost_per_token", 0) - + if router_flat_cost_per_token > 0: return prompt_tokens * router_flat_cost_per_token - + return 0.0 def cost_per_token( - model: str, - usage: Usage, + model: str, + usage: Usage, response_time_ms: Optional[float] = 0.0, request_model: Optional[str] = None, ) -> Tuple[float, float]: """ Calculate the cost per token for Azure AI models. - + For Azure AI Foundry Model Router: - Adds a flat cost of $0.14 per million input tokens (from model_prices_and_context_window.json) - Plus the cost of the actual model used (handled by generic_cost_per_token) - + Args: model: str, the model name without provider prefix (from response) usage: LiteLLM Usage block response_time_ms: Optional response time in milliseconds request_model: Optional[str], the original request model name (to detect router usage) - + Returns: Tuple[float, float] - prompt_cost_in_usd, completion_cost_in_usd - + Raises: ValueError: If the model is not found in the cost map and cost cannot be calculated (except for Model Router models where we return just the routing flat cost) @@ -119,7 +119,9 @@ def cost_per_token( if is_router_request: # Use the request model for flat cost calculation if available, otherwise use response model router_model_for_calc = request_model if request_model else model - router_flat_cost = calculate_azure_model_router_flat_cost(router_model_for_calc, usage.prompt_tokens) + router_flat_cost = calculate_azure_model_router_flat_cost( + router_model_for_calc, usage.prompt_tokens + ) if router_flat_cost > 0: verbose_logger.debug( diff --git a/litellm/llms/azure_ai/image_edit/flux2_transformation.py b/litellm/llms/azure_ai/image_edit/flux2_transformation.py index 77d46ff9179..0de163a7714 100644 --- a/litellm/llms/azure_ai/image_edit/flux2_transformation.py +++ b/litellm/llms/azure_ai/image_edit/flux2_transformation.py @@ -101,10 +101,10 @@ class AzureFoundryFlux2ImageEditConfig(OpenAIImageEditConfig): """ if prompt is None: raise ValueError("FLUX 2 image edit requires a prompt.") - + if image is None: raise ValueError("FLUX 2 image edit requires an image.") - + image_b64 = self._convert_image_to_base64(image) # Build request body with required params @@ -170,4 +170,3 @@ class AzureFoundryFlux2ImageEditConfig(OpenAIImageEditConfig): model=model, api_version=api_version, ) - diff --git a/litellm/llms/azure_ai/image_generation/cost_calculator.py b/litellm/llms/azure_ai/image_generation/cost_calculator.py index 2fc7c554a34..b67de9cb70d 100644 --- a/litellm/llms/azure_ai/image_generation/cost_calculator.py +++ b/litellm/llms/azure_ai/image_generation/cost_calculator.py @@ -22,4 +22,6 @@ def cost_calculator( num_images = len(image_response.data) return output_cost_per_image * num_images else: - raise ValueError(f"image_response must be of type ImageResponse got type={type(image_response)}") + raise ValueError( + f"image_response must be of type ImageResponse got type={type(image_response)}" + ) diff --git a/litellm/llms/azure_ai/ocr/__init__.py b/litellm/llms/azure_ai/ocr/__init__.py index 7182a750b45..e49217a5baf 100644 --- a/litellm/llms/azure_ai/ocr/__init__.py +++ b/litellm/llms/azure_ai/ocr/__init__.py @@ -10,4 +10,3 @@ __all__ = [ "AzureDocumentIntelligenceOCRConfig", "get_azure_ai_ocr_config", ] - diff --git a/litellm/llms/azure_ai/ocr/common_utils.py b/litellm/llms/azure_ai/ocr/common_utils.py index ef470c74923..d736b891532 100644 --- a/litellm/llms/azure_ai/ocr/common_utils.py +++ b/litellm/llms/azure_ai/ocr/common_utils.py @@ -16,22 +16,22 @@ if TYPE_CHECKING: def get_azure_ai_ocr_config(model: str) -> Optional["BaseOCRConfig"]: """ Determine which Azure AI OCR configuration to use based on the model name. - + Azure AI supports multiple OCR services: - Azure Document Intelligence: azure_ai/doc-intelligence/ - Mistral OCR (via Azure AI): azure_ai/ - + Args: - model: The model name (e.g., "azure_ai/doc-intelligence/prebuilt-read", + model: The model name (e.g., "azure_ai/doc-intelligence/prebuilt-read", "azure_ai/pixtral-12b-2409") - + Returns: OCR configuration instance for the specified model - + Examples: >>> get_azure_ai_ocr_config("azure_ai/doc-intelligence/prebuilt-read") - + >>> get_azure_ai_ocr_config("azure_ai/pixtral-12b-2409") """ @@ -46,8 +46,7 @@ def get_azure_ai_ocr_config(model: str) -> Optional["BaseOCRConfig"]: f"Routing {model} to Azure Document Intelligence OCR config" ) return AzureDocumentIntelligenceOCRConfig() - + # Default to Mistral-based OCR for other azure_ai models verbose_logger.debug(f"Routing {model} to Azure AI (Mistral) OCR config") return AzureAIOCRConfig() - diff --git a/litellm/llms/azure_ai/ocr/document_intelligence/__init__.py b/litellm/llms/azure_ai/ocr/document_intelligence/__init__.py index 372a6a8d761..fb14fbbf0ac 100644 --- a/litellm/llms/azure_ai/ocr/document_intelligence/__init__.py +++ b/litellm/llms/azure_ai/ocr/document_intelligence/__init__.py @@ -2,4 +2,3 @@ from .transformation import AzureDocumentIntelligenceOCRConfig __all__ = ["AzureDocumentIntelligenceOCRConfig"] - diff --git a/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py b/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py index f6c6da24098..6ef309ca679 100644 --- a/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py +++ b/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py @@ -35,15 +35,15 @@ from litellm.secret_managers.main import get_secret_str class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig): """ Azure Document Intelligence OCR transformation configuration. - + Supports Azure Document Intelligence v4.0 (2024-11-30) API. Model route: azure_ai/doc-intelligence/ - + Supported models: - prebuilt-layout: Extracts text with markdown, tables, and structure (closest to Mistral OCR) - prebuilt-read: Basic text extraction optimized for reading - prebuilt-document: General document analysis - + Reference: https://learn.microsoft.com/en-us/azure/ai-services/document-intelligence/ """ @@ -53,7 +53,7 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig): def get_supported_ocr_params(self, model: str) -> list: """ Get supported OCR parameters for Azure Document Intelligence. - + Azure DI has minimal optional parameters compared to Mistral OCR. Most Mistral-specific params are ignored during transformation. """ @@ -70,7 +70,7 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig): ) -> Dict: """ Validate environment and return headers for Azure Document Intelligence. - + Authentication uses Ocp-Apim-Subscription-Key header. """ # Get API key from environment if not provided @@ -109,16 +109,16 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig): ) -> str: """ Get complete URL for Azure Document Intelligence endpoint. - + Format: {endpoint}/documentintelligence/documentModels/{modelId}:analyze?api-version=2024-11-30 - + Note: API version 2024-11-30 uses /documentintelligence/ path (not /formrecognizer/) - + Args: api_base: Azure Document Intelligence endpoint (e.g., https://your-resource.cognitiveservices.azure.com) model: Model ID (e.g., "prebuilt-layout", "prebuilt-read") optional_params: Optional parameters - + Returns: Complete URL for Azure DI analyze endpoint """ if api_base is None: @@ -146,10 +146,10 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig): def _extract_base64_from_data_uri(self, data_uri: str) -> str: """ Extract base64 content from a data URI. - + Args: data_uri: Data URI like "data:application/pdf;base64,..." - + Returns: Base64 string without the data URI prefix """ @@ -169,7 +169,7 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig): ) -> OCRRequestData: """ Transform OCR request to Azure Document Intelligence format. - + Mistral OCR format: { "document": { @@ -177,7 +177,7 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig): "document_url": "https://example.com/doc.pdf" } } - + Azure DI format: { "urlSource": "https://example.com/doc.pdf" @@ -186,13 +186,13 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig): { "base64Source": "base64_encoded_content" } - + Args: model: Model name document: Document dict from user (Mistral format) optional_params: Already mapped optional parameters headers: Request headers - + Returns: OCRRequestData with JSON data """ @@ -241,12 +241,12 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig): def _extract_page_markdown(self, page_data: Dict[str, Any]) -> str: """ Extract text from Azure DI page and format as markdown. - + Azure DI provides text in 'lines' array. We concatenate them with newlines. - + Args: page_data: Azure DI page object - + Returns: Markdown-formatted text """ @@ -265,14 +265,14 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig): ) -> OCRPageDimensions: """ Convert Azure DI dimensions to pixels. - + Azure DI provides dimensions in inches. We convert to pixels using configured DPI. - + Args: width: Width in specified unit height: Height in specified unit unit: Unit of measurement (e.g., "inch") - + Returns: OCRPageDimensions with pixel values """ @@ -292,11 +292,11 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig): def _check_timeout(start_time: float, timeout_secs: int) -> None: """ Check if operation has timed out. - + Args: start_time: Start time of the operation timeout_secs: Timeout duration in seconds - + Raises: TimeoutError: If operation has exceeded timeout """ @@ -309,10 +309,10 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig): def _get_retry_after(response: httpx.Response) -> int: """ Get retry-after duration from response headers. - + Args: response: HTTP response - + Returns: Retry-after duration in seconds (default: 2) """ @@ -324,13 +324,13 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig): def _check_operation_status(response: httpx.Response) -> str: """ Check Azure DI operation status from response. - + Args: response: HTTP response from operation endpoint - + Returns: Operation status string - + Raises: ValueError: If operation failed or status is unknown """ @@ -366,15 +366,15 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig): ) -> httpx.Response: """ Poll Azure Document Intelligence operation until completion (sync). - + Azure DI POST returns 202 with Operation-Location header. We need to poll that URL until status is "succeeded" or "failed". - + Args: operation_url: The Operation-Location URL to poll headers: Request headers (including auth) timeout_secs: Total timeout in seconds - + Returns: Final response with completed analysis """ @@ -409,12 +409,12 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig): ) -> httpx.Response: """ Poll Azure Document Intelligence operation until completion (async). - + Args: operation_url: The Operation-Location URL to poll headers: Request headers (including auth) timeout_secs: Total timeout in seconds - + Returns: Final response with completed analysis """ @@ -451,10 +451,10 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig): ) -> OCRResponse: """ Transform Azure Document Intelligence response to Mistral OCR format. - + Handles async operation polling: If response is 202 Accepted, polls Operation-Location until analysis completes. - + Azure DI response (after polling): { "status": "succeeded", @@ -471,7 +471,7 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig): ] } } - + Mistral OCR format: { "pages": [ @@ -485,12 +485,12 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig): "usage_info": {"pages_processed": 1}, "object": "ocr" } - + Args: model: Model name raw_response: Raw HTTP response from Azure DI (may be 202 Accepted) logging_obj: Logging object - + Returns: OCRResponse in Mistral format """ @@ -594,15 +594,15 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig): ) -> OCRResponse: """ Async transform Azure Document Intelligence response to Mistral OCR format. - + Handles async operation polling: If response is 202 Accepted, polls Operation-Location until analysis completes using async polling. - + Args: model: Model name raw_response: Raw HTTP response from Azure DI (may be 202 Accepted) logging_obj: Logging object - + Returns: OCRResponse in Mistral format """ @@ -696,4 +696,3 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig): f"Error parsing Azure Document Intelligence response (async): {e}" ) raise e - diff --git a/litellm/llms/azure_ai/ocr/transformation.py b/litellm/llms/azure_ai/ocr/transformation.py index 24fc9e86134..8f57bb3358b 100644 --- a/litellm/llms/azure_ai/ocr/transformation.py +++ b/litellm/llms/azure_ai/ocr/transformation.py @@ -16,12 +16,12 @@ from litellm.secret_managers.main import get_secret_str class AzureAIOCRConfig(MistralOCRConfig): """ Azure AI OCR transformation configuration. - + Azure AI uses Mistral's OCR API but with a different endpoint format. Inherits transformation logic from MistralOCRConfig since they use the same format. - + Reference: Azure AI Foundry OCR documentation - + Important: Azure AI only supports base64 data URIs (data:image/..., data:application/pdf;base64,...). Regular URLs are not supported. """ @@ -40,7 +40,7 @@ class AzureAIOCRConfig(MistralOCRConfig): ) -> Dict: """ Validate environment and return headers for Azure AI OCR. - + Azure AI uses Bearer token authentication with AZURE_AI_API_KEY. """ # Get API key from environment if not provided @@ -55,7 +55,7 @@ class AzureAIOCRConfig(MistralOCRConfig): # Validate API base is provided if api_base is None: api_base = get_secret_str("AZURE_AI_API_BASE") - + if api_base is None: raise ValueError( "Missing Azure AI API Base - Set AZURE_AI_API_BASE environment variable or pass api_base parameter" @@ -79,14 +79,14 @@ class AzureAIOCRConfig(MistralOCRConfig): ) -> str: """ Get complete URL for Azure AI OCR endpoint. - + Azure AI endpoint format: https:///providers/mistral/azure/ocr - + Args: api_base: Azure AI API base URL model: Model name (not used in URL construction) optional_params: Optional parameters - + Returns: Complete URL for Azure AI OCR endpoint """ if api_base is None: @@ -96,54 +96,62 @@ class AzureAIOCRConfig(MistralOCRConfig): # Ensure no trailing slash api_base = api_base.rstrip("/") - + # Azure AI OCR endpoint format return f"{api_base}/providers/mistral/azure/ocr" def _convert_url_to_data_uri_sync(self, url: str) -> str: """ Synchronously convert a URL to a base64 data URI. - + Azure AI OCR doesn't have internet access, so we need to fetch URLs and convert them to base64 data URIs. - + Args: url: The URL to convert - + Returns: Base64 data URI string """ - verbose_logger.debug(f"Azure AI OCR: Converting URL to base64 data URI (sync): {url}") - + verbose_logger.debug( + f"Azure AI OCR: Converting URL to base64 data URI (sync): {url}" + ) + # Fetch and convert to base64 data URI # convert_url_to_base64 already returns a full data URI like "data:image/jpeg;base64,..." data_uri = convert_url_to_base64(url=url) - - verbose_logger.debug(f"Azure AI OCR: Converted URL to data URI (length: {len(data_uri)})") - + + verbose_logger.debug( + f"Azure AI OCR: Converted URL to data URI (length: {len(data_uri)})" + ) + return data_uri async def _convert_url_to_data_uri_async(self, url: str) -> str: """ Asynchronously convert a URL to a base64 data URI. - + Azure AI OCR doesn't have internet access, so we need to fetch URLs and convert them to base64 data URIs. - + Args: url: The URL to convert - + Returns: Base64 data URI string """ - verbose_logger.debug(f"Azure AI OCR: Converting URL to base64 data URI (async): {url}") - + verbose_logger.debug( + f"Azure AI OCR: Converting URL to base64 data URI (async): {url}" + ) + # Fetch and convert to base64 data URI asynchronously # async_convert_url_to_base64 already returns a full data URI like "data:image/jpeg;base64,..." data_uri = await async_convert_url_to_base64(url=url) - - verbose_logger.debug(f"Azure AI OCR: Converted URL to data URI (length: {len(data_uri)})") - + + verbose_logger.debug( + f"Azure AI OCR: Converted URL to data URI (length: {len(data_uri)})" + ) + return data_uri def transform_ocr_request( @@ -156,29 +164,31 @@ class AzureAIOCRConfig(MistralOCRConfig): ) -> OCRRequestData: """ Transform OCR request for Azure AI, converting URLs to base64 data URIs (sync). - + Azure AI OCR doesn't have internet access, so we automatically fetch any URLs and convert them to base64 data URIs synchronously. - + Args: model: Model name document: Document dict from user optional_params: Already mapped optional parameters headers: Request headers **kwargs: Additional arguments - + Returns: OCRRequestData with JSON data """ - verbose_logger.debug(f"Azure AI OCR transform_ocr_request (sync) - model: {model}") - + verbose_logger.debug( + f"Azure AI OCR transform_ocr_request (sync) - model: {model}" + ) + if not isinstance(document, dict): raise ValueError(f"Expected document dict, got {type(document)}") - + # Check if we need to convert URL to base64 doc_type = document.get("type") transformed_document = document.copy() - + if doc_type == "document_url": document_url = document.get("document_url", "") # If it's not already a data URI, convert it @@ -197,7 +207,7 @@ class AzureAIOCRConfig(MistralOCRConfig): ) data_uri = self._convert_url_to_data_uri_sync(url=image_url) transformed_document["image_url"] = data_uri - + # Call parent's transform to build the request return super().transform_ocr_request( model=model, @@ -217,29 +227,31 @@ class AzureAIOCRConfig(MistralOCRConfig): ) -> OCRRequestData: """ Transform OCR request for Azure AI, converting URLs to base64 data URIs (async). - + Azure AI OCR doesn't have internet access, so we automatically fetch any URLs and convert them to base64 data URIs asynchronously. - + Args: model: Model name document: Document dict from user optional_params: Already mapped optional parameters headers: Request headers **kwargs: Additional arguments - + Returns: OCRRequestData with JSON data """ - verbose_logger.debug(f"Azure AI OCR async_transform_ocr_request - model: {model}") - + verbose_logger.debug( + f"Azure AI OCR async_transform_ocr_request - model: {model}" + ) + if not isinstance(document, dict): raise ValueError(f"Expected document dict, got {type(document)}") - + # Check if we need to convert URL to base64 doc_type = document.get("type") transformed_document = document.copy() - + if doc_type == "document_url": document_url = document.get("document_url", "") # If it's not already a data URI, convert it @@ -258,7 +270,7 @@ class AzureAIOCRConfig(MistralOCRConfig): ) data_uri = await self._convert_url_to_data_uri_async(url=image_url) transformed_document["image_url"] = data_uri - + # Call parent's transform to build the request return super().transform_ocr_request( model=model, @@ -267,4 +279,3 @@ class AzureAIOCRConfig(MistralOCRConfig): headers=headers, **kwargs, ) - diff --git a/litellm/llms/azure_ai/rerank/transformation.py b/litellm/llms/azure_ai/rerank/transformation.py index f577a42ed58..b5993040ea0 100644 --- a/litellm/llms/azure_ai/rerank/transformation.py +++ b/litellm/llms/azure_ai/rerank/transformation.py @@ -20,8 +20,8 @@ class AzureAIRerankConfig(CohereRerankConfig): """ def get_complete_url( - self, - api_base: Optional[str], + self, + api_base: Optional[str], model: str, optional_params: Optional[dict] = None, ) -> str: @@ -41,7 +41,9 @@ class AzureAIRerankConfig(CohereRerankConfig): # 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"): + 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" diff --git a/litellm/llms/azure_ai/vector_stores/__init__.py b/litellm/llms/azure_ai/vector_stores/__init__.py index 74ffe1afb17..d83363cbc5c 100644 --- a/litellm/llms/azure_ai/vector_stores/__init__.py +++ b/litellm/llms/azure_ai/vector_stores/__init__.py @@ -1,4 +1,3 @@ from litellm.llms.azure_ai.vector_stores.transformation import AzureAIVectorStoreConfig __all__ = ["AzureAIVectorStoreConfig"] - diff --git a/litellm/llms/azure_ai/vector_stores/transformation.py b/litellm/llms/azure_ai/vector_stores/transformation.py index 96cea064ce1..b62acb65166 100644 --- a/litellm/llms/azure_ai/vector_stores/transformation.py +++ b/litellm/llms/azure_ai/vector_stores/transformation.py @@ -58,7 +58,6 @@ class AzureAIVectorStoreConfig(BaseVectorStoreConfig, BaseAzureLLM): def validate_environment( self, headers: dict, litellm_params: Optional[GenericLiteLLMParams] ) -> dict: - basic_headers = self._base_validate_azure_environment(headers, litellm_params) basic_headers.update({"Content-Type": "application/json"}) return basic_headers diff --git a/litellm/llms/base_llm/base_model_iterator.py b/litellm/llms/base_llm/base_model_iterator.py index 6953b1c5878..18551d97142 100644 --- a/litellm/llms/base_llm/base_model_iterator.py +++ b/litellm/llms/base_llm/base_model_iterator.py @@ -125,26 +125,38 @@ class BaseModelResponseIterator: ) def __next__(self): - try: - chunk = self.response_iterator.__next__() - except StopIteration: - raise StopIteration - except ValueError as e: - raise RuntimeError(f"Error receiving chunk from stream: {e}") + while True: + try: + chunk = self.response_iterator.__next__() + except StopIteration: + raise StopIteration + except ValueError as e: + raise RuntimeError(f"Error receiving chunk from stream: {e}") - try: - str_line = chunk - if isinstance(chunk, bytes): # Handle binary data - str_line = chunk.decode("utf-8") # Convert bytes to string - index = str_line.find("data:") - if index != -1: - str_line = str_line[index:] - # chunk is a str at this point - return self._handle_string_chunk(str_line=str_line) - except StopIteration: - raise StopIteration - except ValueError as e: - raise RuntimeError(f"Error parsing chunk: {e},\nReceived chunk: {chunk}") + try: + str_line = chunk + if isinstance(chunk, bytes): # Handle binary data + str_line = chunk.decode("utf-8") # Convert bytes to string + index = str_line.find("data:") + if index != -1: + str_line = str_line[index:] + + # Skip empty lines (common in SSE streams between events). + # Only apply to str chunks — non-string objects (e.g. Pydantic + # BaseModel events from the Responses API) must pass through. + if isinstance(str_line, str) and ( + not str_line or not str_line.strip() + ): + continue + + # chunk is a str at this point + return self._handle_string_chunk(str_line=str_line) + except StopIteration: + raise StopIteration + except ValueError as e: + raise RuntimeError( + f"Error parsing chunk: {e},\nReceived chunk: {chunk}" + ) # Async iterator def __aiter__(self): @@ -152,30 +164,41 @@ class BaseModelResponseIterator: return self async def __anext__(self): - try: - chunk = await self.async_response_iterator.__anext__() + while True: + try: + chunk = await self.async_response_iterator.__anext__() - except StopAsyncIteration: - raise StopAsyncIteration - except ValueError as e: - raise RuntimeError(f"Error receiving chunk from stream: {e}") + except StopAsyncIteration: + raise StopAsyncIteration + except ValueError as e: + raise RuntimeError(f"Error receiving chunk from stream: {e}") - try: - str_line = chunk - if isinstance(chunk, bytes): # Handle binary data - str_line = chunk.decode("utf-8") # Convert bytes to string - index = str_line.find("data:") - if index != -1: - str_line = str_line[index:] + try: + str_line = chunk + if isinstance(chunk, bytes): # Handle binary data + str_line = chunk.decode("utf-8") # Convert bytes to string + index = str_line.find("data:") + if index != -1: + str_line = str_line[index:] - # chunk is a str at this point - chunk = self._handle_string_chunk(str_line=str_line) + # Skip empty lines (common in SSE streams between events). + # Only apply to str chunks — non-string objects (e.g. Pydantic + # BaseModel events from the Responses API) must pass through. + if isinstance(str_line, str) and ( + not str_line or not str_line.strip() + ): + continue - return chunk - except StopAsyncIteration: - raise StopAsyncIteration - except ValueError as e: - raise RuntimeError(f"Error parsing chunk: {e},\nReceived chunk: {chunk}") + # chunk is a str at this point + chunk = self._handle_string_chunk(str_line=str_line) + + return chunk + except StopAsyncIteration: + raise StopAsyncIteration + except ValueError as e: + raise RuntimeError( + f"Error parsing chunk: {e},\nReceived chunk: {chunk}" + ) class MockResponseIterator: # for returning ai21 streaming responses diff --git a/litellm/llms/base_llm/base_utils.py b/litellm/llms/base_llm/base_utils.py index ecff9053dc5..d2d3d5c0a96 100644 --- a/litellm/llms/base_llm/base_utils.py +++ b/litellm/llms/base_llm/base_utils.py @@ -98,7 +98,7 @@ class BaseLLMModelInfo(ABC): def get_token_counter(self) -> Optional[BaseTokenCounter]: """ Factory method to create a token counter for this provider. - + Returns: Optional TokenCounterInterface implementation for this provider, or None if token counting is not supported. diff --git a/litellm/llms/base_llm/batches/transformation.py b/litellm/llms/base_llm/batches/transformation.py index 9e67689fcd9..aedaf0687cb 100644 --- a/litellm/llms/base_llm/batches/transformation.py +++ b/litellm/llms/base_llm/batches/transformation.py @@ -26,7 +26,7 @@ else: class BaseBatchesConfig(ABC): """ Abstract base class for batch processing configurations across different LLM providers. - + This class defines the interface that all provider-specific batch configurations must implement to work with LiteLLM's unified batch processing system. """ @@ -73,7 +73,7 @@ class BaseBatchesConfig(ABC): ) -> dict: """ Validate and prepare environment-specific headers and parameters. - + Args: headers: HTTP headers dictionary model: Model name @@ -82,7 +82,7 @@ class BaseBatchesConfig(ABC): litellm_params: LiteLLM parameters api_key: API key api_base: API base URL - + Returns: Updated headers dictionary """ @@ -100,7 +100,7 @@ class BaseBatchesConfig(ABC): ) -> str: """ Get the complete URL for batch creation request. - + Args: api_base: Base API URL api_key: API key @@ -108,7 +108,7 @@ class BaseBatchesConfig(ABC): optional_params: Optional parameters litellm_params: LiteLLM parameters data: Batch creation request data - + Returns: Complete URL for the batch request """ @@ -124,13 +124,13 @@ class BaseBatchesConfig(ABC): ) -> Union[bytes, str, Dict[str, Any]]: """ Transform the batch creation request to provider-specific format. - + Args: model: Model name create_batch_data: Batch creation request data optional_params: Optional parameters litellm_params: LiteLLM parameters - + Returns: Transformed request data """ @@ -146,13 +146,13 @@ class BaseBatchesConfig(ABC): ) -> LiteLLMBatch: """ Transform provider-specific batch response to LiteLLM format. - + Args: model: Model name raw_response: Raw HTTP response logging_obj: Logging object litellm_params: LiteLLM parameters - + Returns: LiteLLM batch object """ @@ -167,12 +167,12 @@ class BaseBatchesConfig(ABC): ) -> Union[bytes, str, Dict[str, Any]]: """ Transform the batch retrieval request to provider-specific format. - + Args: batch_id: Batch ID to retrieve optional_params: Optional parameters litellm_params: LiteLLM parameters - + Returns: Transformed request data """ @@ -188,13 +188,13 @@ class BaseBatchesConfig(ABC): ) -> LiteLLMBatch: """ Transform provider-specific batch retrieval response to LiteLLM format. - + Args: model: Model name raw_response: Raw HTTP response logging_obj: Logging object litellm_params: LiteLLM parameters - + Returns: LiteLLM batch object """ @@ -206,12 +206,12 @@ class BaseBatchesConfig(ABC): ) -> "BaseLLMException": """ Get the appropriate error class for this provider. - + Args: error_message: Error message status_code: HTTP status code headers: Response headers - + Returns: Provider-specific exception class """ diff --git a/litellm/llms/base_llm/chat/transformation.py b/litellm/llms/base_llm/chat/transformation.py index f22c8ee0d95..b71ae0fddee 100644 --- a/litellm/llms/base_llm/chat/transformation.py +++ b/litellm/llms/base_llm/chat/transformation.py @@ -135,7 +135,10 @@ class BaseConfig(ABC): if 'thinking' is enabled and 'max_tokens' or 'max_completion_tokens' is not specified, set 'max_tokens' to the thinking token budget + DEFAULT_MAX_TOKENS """ is_thinking_enabled = self.is_thinking_enabled(optional_params) - if is_thinking_enabled and ("max_tokens" not in non_default_params and "max_completion_tokens" not in non_default_params): + if is_thinking_enabled and ( + "max_tokens" not in non_default_params + and "max_completion_tokens" not in non_default_params + ): thinking_token_budget = cast(dict, optional_params["thinking"]).get( "budget_tokens", None ) @@ -447,14 +450,14 @@ class BaseConfig(ABC): ) -> Optional[dict]: """ Calculate any additional costs beyond standard token costs. - + This is used for provider-specific infrastructure costs, routing fees, etc. - + Args: model: The model name prompt_tokens: Number of prompt tokens completion_tokens: Number of completion tokens - + Returns: Optional dictionary with cost names and amounts, e.g.: {"Infrastructure Fee": 0.001, "Routing Cost": 0.0005} diff --git a/litellm/llms/base_llm/containers/transformation.py b/litellm/llms/base_llm/containers/transformation.py index 5ce374c7734..dc75789156e 100644 --- a/litellm/llms/base_llm/containers/transformation.py +++ b/litellm/llms/base_llm/containers/transformation.py @@ -89,7 +89,7 @@ class BaseContainerConfig(ABC): litellm_params: dict, ) -> str: """Get the complete url for the request. - + OPTIONAL - Some providers need `model` in `api_base`. """ if api_base is None: @@ -106,7 +106,7 @@ class BaseContainerConfig(ABC): headers: dict, ) -> dict: """Transform the container creation request. - + Returns: dict: Request data for container creation. """ @@ -133,7 +133,7 @@ class BaseContainerConfig(ABC): extra_query: dict[str, Any] | None = None, ) -> tuple[str, dict]: """Transform the container list request into a URL and params. - + Returns: tuple[str, dict]: (url, params) for the container list request. """ @@ -157,7 +157,7 @@ class BaseContainerConfig(ABC): headers: dict, ) -> tuple[str, dict]: """Transform the container retrieve request into a URL and data/params. - + Returns: tuple[str, dict]: (url, params) for the container retrieve request. """ @@ -181,7 +181,7 @@ class BaseContainerConfig(ABC): headers: dict, ) -> tuple[str, dict]: """Transform the container delete request into a URL and data. - + Returns: tuple[str, dict]: (url, data) for the container delete request. """ @@ -209,7 +209,7 @@ class BaseContainerConfig(ABC): extra_query: dict[str, Any] | None = None, ) -> tuple[str, dict]: """Transform the container file list request into a URL and params. - + Returns: tuple[str, dict]: (url, params) for the container file list request. """ @@ -234,7 +234,7 @@ class BaseContainerConfig(ABC): headers: dict, ) -> tuple[str, dict]: """Transform the container file content request into a URL and params. - + Returns: tuple[str, dict]: (url, params) for the container file content request. """ @@ -247,16 +247,16 @@ class BaseContainerConfig(ABC): logging_obj: LiteLLMLoggingObj, ) -> bytes: """Transform the container file content response. - + Returns: bytes: The raw file content. """ ... def get_error_class( - self, - error_message: str, - status_code: int, + self, + error_message: str, + status_code: int, headers: dict | httpx.Headers, ) -> BaseLLMException: from ..chat.transformation import BaseLLMException @@ -266,4 +266,3 @@ class BaseContainerConfig(ABC): message=error_message, headers=headers, ) - diff --git a/litellm/llms/base_llm/files/azure_blob_storage_backend.py b/litellm/llms/base_llm/files/azure_blob_storage_backend.py index db3aa50d89a..a2155df4047 100644 --- a/litellm/llms/base_llm/files/azure_blob_storage_backend.py +++ b/litellm/llms/base_llm/files/azure_blob_storage_backend.py @@ -20,26 +20,26 @@ from litellm.integrations.azure_storage.azure_storage import AzureBlobStorageLog class AzureBlobStorageBackend(BaseFileStorageBackend, AzureBlobStorageLogger): """ Azure Blob Storage backend implementation. - + Inherits from AzureBlobStorageLogger to reuse: - Authentication (account key and Azure AD) - Service client management - Token management - All Azure Storage helper methods - + Reads configuration from the same environment variables as AzureBlobStorageLogger. """ def __init__(self, **kwargs): """ Initialize Azure Blob Storage backend. - + Inherits all functionality from AzureBlobStorageLogger which handles: - Reading environment variables - Authentication (account key and Azure AD) - Service client management - Token management - + Environment variables (same as AzureBlobStorageLogger): - AZURE_STORAGE_ACCOUNT_NAME (required) - AZURE_STORAGE_FILE_SYSTEM (required) @@ -47,12 +47,12 @@ class AzureBlobStorageBackend(BaseFileStorageBackend, AzureBlobStorageLogger): - AZURE_STORAGE_TENANT_ID (optional, if using Azure AD) - AZURE_STORAGE_CLIENT_ID (optional, if using Azure AD) - AZURE_STORAGE_CLIENT_SECRET (optional, if using Azure AD) - + Note: We skip periodic_flush since we're not using this as a logger. """ # Initialize AzureBlobStorageLogger (handles all auth and config) AzureBlobStorageLogger.__init__(self, **kwargs) - + # Disable logging functionality - we're only using this for file storage # The periodic_flush task will be created but will do nothing since we override it @@ -87,12 +87,16 @@ class AzureBlobStorageBackend(BaseFileStorageBackend, AzureBlobStorageLogger): return quote(original_filename, safe="") elif file_naming_strategy == "timestamp": # Use timestamp - extension = original_filename.split(".")[-1] if "." in original_filename else "" + extension = ( + original_filename.split(".")[-1] if "." in original_filename else "" + ) timestamp = int(time.time() * 1000) # milliseconds return f"{timestamp}.{extension}" if extension else str(timestamp) else: # default to "uuid" # Use UUID - extension = original_filename.split(".")[-1] if "." in original_filename else "" + extension = ( + original_filename.split(".")[-1] if "." in original_filename else "" + ) file_uuid = str(uuid.uuid4()) return f"{file_uuid}.{extension}" if extension else file_uuid @@ -106,13 +110,13 @@ class AzureBlobStorageBackend(BaseFileStorageBackend, AzureBlobStorageLogger): ) -> str: """ Upload a file to Azure Blob Storage. - + Returns the blob URL in format: https://{account}.blob.core.windows.net/{container}/{path} """ try: # Generate file name file_name = self._generate_file_name(filename, file_naming_strategy) - + # Build full path if path_prefix: # Remove leading/trailing slashes and normalize @@ -140,7 +144,9 @@ class AzureBlobStorageBackend(BaseFileStorageBackend, AzureBlobStorageLogger): return storage_url except Exception as e: - verbose_logger.exception(f"Error uploading file to Azure Blob Storage: {str(e)}") + verbose_logger.exception( + f"Error uploading file to Azure Blob Storage: {str(e)}" + ) raise async def _upload_file_with_account_key( @@ -156,20 +162,22 @@ class AzureBlobStorageBackend(BaseFileStorageBackend, AzureBlobStorageLogger): # Create filesystem (container) if it doesn't exist if not await file_system_client.exists(): await file_system_client.create_file_system() - verbose_logger.debug(f"Created filesystem: {self.azure_storage_file_system}") + verbose_logger.debug( + f"Created filesystem: {self.azure_storage_file_system}" + ) # Extract directory and filename (similar to logger's pattern) path_parts = full_path.split("/") if len(path_parts) > 1: directory_path = "/".join(path_parts[:-1]) file_name = path_parts[-1] - + # Create directory if needed (like logger does) directory_client = file_system_client.get_directory_client(directory_path) if not await directory_client.exists(): await directory_client.create_directory() verbose_logger.debug(f"Created directory: {directory_path}") - + # Get file client from directory (same pattern as logger) file_client = directory_client.get_file_client(file_name) else: @@ -178,7 +186,9 @@ class AzureBlobStorageBackend(BaseFileStorageBackend, AzureBlobStorageLogger): # Create, append, and flush (same pattern as logger's upload_to_azure_data_lake_with_azure_account_key) await file_client.create_file() - await file_client.append_data(data=file_content, offset=0, length=len(file_content)) + await file_client.append_data( + data=file_content, offset=0, length=len(file_content) + ) await file_client.flush_data(position=len(file_content), offset=0) # Return blob URL (not DFS URL) @@ -191,12 +201,12 @@ class AzureBlobStorageBackend(BaseFileStorageBackend, AzureBlobStorageLogger): """Upload file using REST API with Azure AD authentication.""" # Reuse the logger's token management await self.set_valid_azure_ad_token() - + from litellm.llms.custom_httpx.http_handler import ( get_async_httpx_client, httpxSpecialProvider, ) - + async_client = get_async_httpx_client( llm_provider=httpxSpecialProvider.LoggingCallback ) @@ -215,12 +225,10 @@ class AzureBlobStorageBackend(BaseFileStorageBackend, AzureBlobStorageLogger): blob_url = f"https://{self.azure_storage_account_name}.blob.core.windows.net/{self.azure_storage_file_system}/{full_path}" return blob_url - async def _append_data_bytes( - self, client, base_url: str, file_content: bytes - ): + async def _append_data_bytes(self, client, base_url: str, file_content: bytes): """Append binary data to file using REST API.""" from litellm.constants import AZURE_STORAGE_MSFT_VERSION - + headers = { "x-ms-version": AZURE_STORAGE_MSFT_VERSION, "Content-Type": "application/octet-stream", @@ -236,10 +244,10 @@ class AzureBlobStorageBackend(BaseFileStorageBackend, AzureBlobStorageLogger): async def download_file(self, storage_url: str) -> bytes: """ Download a file from Azure Blob Storage. - + Args: storage_url: Blob URL in format: https://{account}.blob.core.windows.net/{container}/{path} - + Returns: bytes: File content """ @@ -253,7 +261,9 @@ class AzureBlobStorageBackend(BaseFileStorageBackend, AzureBlobStorageLogger): container_and_path = storage_url.split(".blob.core.windows.net/", 1)[1] path_parts = container_and_path.split("/", 1) if len(path_parts) < 2: - raise ValueError(f"Invalid Azure Blob Storage URL format: {storage_url}") + raise ValueError( + f"Invalid Azure Blob Storage URL format: {storage_url}" + ) file_path = path_parts[1] # Path after container name if self.azure_storage_account_key: @@ -264,7 +274,9 @@ class AzureBlobStorageBackend(BaseFileStorageBackend, AzureBlobStorageLogger): return await self._download_file_with_azure_ad(file_path) except Exception as e: - verbose_logger.exception(f"Error downloading file from Azure Blob Storage: {str(e)}") + verbose_logger.exception( + f"Error downloading file from Azure Blob Storage: {str(e)}" + ) raise async def _download_file_with_account_key(self, file_path: str) -> bytes: @@ -276,7 +288,9 @@ class AzureBlobStorageBackend(BaseFileStorageBackend, AzureBlobStorageLogger): ) # Ensure filesystem exists (should already exist, but check for safety) if not await file_system_client.exists(): - raise ValueError(f"Filesystem {self.azure_storage_file_system} does not exist") + raise ValueError( + f"Filesystem {self.azure_storage_file_system} does not exist" + ) file_client = file_system_client.get_file_client(file_path) # Download file download_response = await file_client.download_file() @@ -287,7 +301,7 @@ class AzureBlobStorageBackend(BaseFileStorageBackend, AzureBlobStorageLogger): """Download file using REST API with Azure AD token.""" # Reuse the logger's token management await self.set_valid_azure_ad_token() - + from litellm.llms.custom_httpx.http_handler import ( get_async_httpx_client, httpxSpecialProvider, @@ -300,13 +314,12 @@ class AzureBlobStorageBackend(BaseFileStorageBackend, AzureBlobStorageLogger): # Use blob endpoint for download (simpler than DFS) blob_url = f"https://{self.azure_storage_account_name}.blob.core.windows.net/{self.azure_storage_file_system}/{file_path}" - + headers = { "x-ms-version": AZURE_STORAGE_MSFT_VERSION, "Authorization": f"Bearer {self.azure_auth_token}", } - + response = await async_client.get(blob_url, headers=headers) response.raise_for_status() return response.content - diff --git a/litellm/llms/base_llm/files/storage_backend.py b/litellm/llms/base_llm/files/storage_backend.py index d9570452950..31e68a7002a 100644 --- a/litellm/llms/base_llm/files/storage_backend.py +++ b/litellm/llms/base_llm/files/storage_backend.py @@ -12,7 +12,7 @@ from typing import Optional class BaseFileStorageBackend(ABC): """ Abstract base class for file storage backends. - + All storage backends (Azure Blob Storage, S3, GCS, etc.) must implement these methods to provide a consistent interface for file operations. """ @@ -28,17 +28,17 @@ class BaseFileStorageBackend(ABC): ) -> str: """ Upload a file to the storage backend. - + Args: file_content: The file content as bytes filename: Original filename (may be used for naming strategy) content_type: MIME type of the file path_prefix: Optional path prefix for organizing files file_naming_strategy: Strategy for naming files ("uuid", "timestamp", "original_filename") - + Returns: str: The storage URL where the file can be accessed/downloaded - + Raises: Exception: If upload fails """ @@ -48,13 +48,13 @@ class BaseFileStorageBackend(ABC): async def download_file(self, storage_url: str) -> bytes: """ Download a file from the storage backend. - + Args: storage_url: The storage URL returned from upload_file - + Returns: bytes: The file content - + Raises: Exception: If download fails """ @@ -63,17 +63,16 @@ class BaseFileStorageBackend(ABC): async def delete_file(self, storage_url: str) -> None: """ Delete a file from the storage backend. - + This is optional and can be overridden by backends that support deletion. Default implementation does nothing. - + Args: storage_url: The storage URL of the file to delete - + Raises: Exception: If deletion fails """ # Default implementation: no-op # Backends can override if they support deletion pass - diff --git a/litellm/llms/base_llm/files/storage_backend_factory.py b/litellm/llms/base_llm/files/storage_backend_factory.py index 1685f3fbd26..12047f1122e 100644 --- a/litellm/llms/base_llm/files/storage_backend_factory.py +++ b/litellm/llms/base_llm/files/storage_backend_factory.py @@ -15,22 +15,22 @@ from .storage_backend import BaseFileStorageBackend def get_storage_backend(backend_type: str) -> BaseFileStorageBackend: """ Factory function to create a storage backend instance. - + Backends are configured using the same environment variables as their corresponding callbacks. For example, "azure_storage" uses the same env vars as AzureBlobStorageLogger. - + Args: backend_type: Backend type identifier (e.g., "azure_storage") - + Returns: BaseFileStorageBackend: Instance of the appropriate storage backend - + Raises: ValueError: If backend_type is not supported """ verbose_logger.debug(f"Creating storage backend: type={backend_type}") - + if backend_type == "azure_storage": return AzureBlobStorageBackend() else: @@ -38,4 +38,3 @@ def get_storage_backend(backend_type: str) -> BaseFileStorageBackend: f"Unsupported storage backend type: {backend_type}. " f"Supported types: azure_storage" ) - diff --git a/litellm/llms/base_llm/files/transformation.py b/litellm/llms/base_llm/files/transformation.py index 58df15f0c46..c3abfafc552 100644 --- a/litellm/llms/base_llm/files/transformation.py +++ b/litellm/llms/base_llm/files/transformation.py @@ -81,7 +81,7 @@ class BaseFilesConfig(BaseConfig): ) -> Union[dict, str, bytes, "TwoStepFileUploadConfig"]: """ Transform OpenAI-style file creation request into provider-specific format. - + Returns: - dict: For pre-signed single-step uploads (e.g., Bedrock S3) - str/bytes: For traditional file uploads diff --git a/litellm/llms/base_llm/google_genai/transformation.py b/litellm/llms/base_llm/google_genai/transformation.py index 0a85e127bd7..e8b3bf1a576 100644 --- a/litellm/llms/base_llm/google_genai/transformation.py +++ b/litellm/llms/base_llm/google_genai/transformation.py @@ -18,7 +18,7 @@ else: GenerateContentResponse = Any LiteLLMLoggingObj = Any ToolConfigDict = Any - + from litellm.types.router import GenericLiteLLMParams @@ -58,8 +58,9 @@ class BaseGoogleGenAIGenerateContentConfig(ABC): Returns: List of supported parameter names """ - raise NotImplementedError("get_supported_generate_content_optional_params is not implemented") - + raise NotImplementedError( + "get_supported_generate_content_optional_params is not implemented" + ) @abstractmethod def map_generate_content_optional_params( @@ -77,15 +78,17 @@ class BaseGoogleGenAIGenerateContentConfig(ABC): Returns: Mapped parameters for the provider """ - raise NotImplementedError("map_generate_content_optional_params is not implemented") + raise NotImplementedError( + "map_generate_content_optional_params is not implemented" + ) @abstractmethod def validate_environment( - self, + self, api_key: Optional[str], headers: Optional[dict], model: str, - litellm_params: Optional[Union[GenericLiteLLMParams, dict]] + litellm_params: Optional[Union[GenericLiteLLMParams, dict]], ) -> dict: """ Validate the environment and return headers for the request. @@ -100,7 +103,7 @@ class BaseGoogleGenAIGenerateContentConfig(ABC): Updated headers """ raise NotImplementedError("validate_environment is not implemented") - + def sync_get_auth_token_and_url( self, api_base: Optional[str], @@ -121,7 +124,7 @@ class BaseGoogleGenAIGenerateContentConfig(ABC): Tuple of headers and API base """ raise NotImplementedError("sync_get_auth_token_and_url is not implemented") - + async def get_auth_token_and_url( self, api_base: Optional[str], diff --git a/litellm/llms/base_llm/image_generation/transformation.py b/litellm/llms/base_llm/image_generation/transformation.py index 151e2893d1c..7f13e6f3b4c 100644 --- a/litellm/llms/base_llm/image_generation/transformation.py +++ b/litellm/llms/base_llm/image_generation/transformation.py @@ -24,7 +24,7 @@ class BaseImageGenerationConfig(ABC): self, model: str ) -> List[OpenAIImageGenerationOptionalParams]: pass - + @abstractmethod def map_openai_params( self, @@ -35,7 +35,6 @@ class BaseImageGenerationConfig(ABC): ) -> dict: pass - def get_complete_url( self, api_base: Optional[str], diff --git a/litellm/llms/base_llm/interactions/transformation.py b/litellm/llms/base_llm/interactions/transformation.py index 4ceb3f5387b..be400628fd5 100644 --- a/litellm/llms/base_llm/interactions/transformation.py +++ b/litellm/llms/base_llm/interactions/transformation.py @@ -41,11 +41,11 @@ else: class BaseInteractionsAPIConfig(ABC): """ Base configuration class for Google Interactions API implementations. - + Per OpenAPI spec, the Interactions API supports two types of interactions: - Model interactions (with model parameter) - Agent interactions (with agent parameter) - + Implementations should override the abstract methods to provide provider-specific transformations for requests and responses. """ @@ -87,10 +87,7 @@ class BaseInteractionsAPIConfig(ABC): @abstractmethod def validate_environment( - self, - headers: dict, - model: str, - litellm_params: Optional[GenericLiteLLMParams] + self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams] ) -> dict: """ Validate and prepare environment settings including headers. @@ -108,16 +105,16 @@ class BaseInteractionsAPIConfig(ABC): ) -> str: """ Get the complete URL for the interaction request. - + Per OpenAPI spec: POST /{api_version}/interactions - + Args: api_base: Base URL for the API model: The model name (for model interactions) agent: The agent name (for agent interactions) litellm_params: LiteLLM parameters stream: Whether this is a streaming request - + Returns: The complete URL for the request """ @@ -137,11 +134,11 @@ class BaseInteractionsAPIConfig(ABC): ) -> Dict: """ Transform the input request into the provider's expected format. - + Per OpenAPI spec, the request body should be either: - CreateModelInteractionParams (with model) - CreateAgentInteractionParams (with agent) - + Args: model: The model name (for model interactions) agent: The agent name (for agent interactions) @@ -149,7 +146,7 @@ class BaseInteractionsAPIConfig(ABC): optional_params: Optional parameters for the request litellm_params: LiteLLM-specific parameters headers: Request headers - + Returns: The transformed request body as a dictionary """ @@ -164,7 +161,7 @@ class BaseInteractionsAPIConfig(ABC): ) -> InteractionsAPIResponse: """ Transform the raw HTTP response into an InteractionsAPIResponse. - + Per OpenAPI spec, the response is an Interaction object. """ pass @@ -178,7 +175,7 @@ class BaseInteractionsAPIConfig(ABC): ) -> InteractionsAPIStreamingResponse: """ Transform a parsed streaming response chunk into an InteractionsAPIStreamingResponse. - + Per OpenAPI spec, streaming uses SSE with various event types. """ pass @@ -186,7 +183,7 @@ class BaseInteractionsAPIConfig(ABC): # ========================================================= # GET INTERACTION TRANSFORMATION # ========================================================= - + @abstractmethod def transform_get_interaction_request( self, @@ -197,9 +194,9 @@ class BaseInteractionsAPIConfig(ABC): ) -> Tuple[str, Dict]: """ Transform the get interaction request into URL and query params. - + Per OpenAPI spec: GET /{api_version}/interactions/{interaction_id} - + Returns: Tuple of (URL, query_params) """ @@ -219,7 +216,7 @@ class BaseInteractionsAPIConfig(ABC): # ========================================================= # DELETE INTERACTION TRANSFORMATION # ========================================================= - + @abstractmethod def transform_delete_interaction_request( self, @@ -230,9 +227,9 @@ class BaseInteractionsAPIConfig(ABC): ) -> Tuple[str, Dict]: """ Transform the delete interaction request into URL and body. - + Per OpenAPI spec: DELETE /{api_version}/interactions/{interaction_id} - + Returns: Tuple of (URL, request_body) """ @@ -253,7 +250,7 @@ class BaseInteractionsAPIConfig(ABC): # ========================================================= # CANCEL INTERACTION TRANSFORMATION # ========================================================= - + @abstractmethod def transform_cancel_interaction_request( self, @@ -264,7 +261,7 @@ class BaseInteractionsAPIConfig(ABC): ) -> Tuple[str, Dict]: """ Transform the cancel interaction request into URL and body. - + Returns: Tuple of (URL, request_body) """ @@ -307,7 +304,7 @@ class BaseInteractionsAPIConfig(ABC): ) -> bool: """ Returns True if litellm should fake a stream for the given model. - + Override in subclasses if the provider doesn't support native streaming. """ return False diff --git a/litellm/llms/base_llm/managed_resources/base_managed_resource.py b/litellm/llms/base_llm/managed_resources/base_managed_resource.py index 3c8ce748ade..5422af76780 100644 --- a/litellm/llms/base_llm/managed_resources/base_managed_resource.py +++ b/litellm/llms/base_llm/managed_resources/base_managed_resource.py @@ -39,27 +39,27 @@ else: Router = Any # Generic type for resource objects -ResourceObjectType = TypeVar('ResourceObjectType') +ResourceObjectType = TypeVar("ResourceObjectType") class BaseManagedResource(ABC, Generic[ResourceObjectType]): """ Base class for managing resources with target_model_names support. - + This class provides common functionality for: - Storing unified resource IDs with model mappings - Retrieving resources by unified ID - Deleting resources across multiple models - Creating resources for multiple models - Filtering deployments based on model mappings - + Subclasses should implement: - resource_type: str property - table_name: str property - create_resource_for_model: method to create resource on a specific model - get_unified_resource_id_format: method to generate unified ID format """ - + def __init__( self, internal_usage_cache: InternalUsageCache, @@ -98,15 +98,15 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): ) -> str: """ Generate the format string for the unified resource ID. - + This should return a string that will be base64 encoded. Example for files: "litellm_proxy:application/json;unified_id,{uuid};target_model_names,{models};..." - + Args: resource_object: The resource object returned from the provider target_model_names_list: List of target model names - + Returns: Format string to be base64 encoded """ @@ -122,13 +122,13 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): ) -> ResourceObjectType: """ Create a resource for a specific model. - + Args: llm_router: LiteLLM router instance model: Model name to create resource for request_data: Request data for resource creation litellm_parent_otel_span: OpenTelemetry span for tracing - + Returns: Resource object from the provider """ @@ -149,7 +149,7 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): ) -> None: """ Store unified resource ID with model mappings in cache and database. - + Args: unified_resource_id: The unified resource ID (base64 encoded) resource_object: The resource object to store (can be None) @@ -161,7 +161,7 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): verbose_logger.info( f"Storing LiteLLM Managed {self.resource_type} with id={unified_resource_id} in cache" ) - + # Prepare cache data cache_data = { "unified_resource_id": unified_resource_id, @@ -171,11 +171,11 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): "created_by": user_api_key_dict.user_id, "updated_by": user_api_key_dict.user_id, } - + # Add additional fields if provided if additional_db_fields: cache_data.update(additional_db_fields) - + # Store in cache if resource_object is not None: await self.internal_usage_cache.async_set_cache( @@ -192,7 +192,7 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): "created_by": user_api_key_dict.user_id, "updated_by": user_api_key_dict.user_id, } - + # Add resource object if available if resource_object is not None: # Handle both dict and Pydantic models @@ -200,14 +200,14 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): db_data["resource_object"] = resource_object.model_dump_json() # type: ignore elif isinstance(resource_object, dict): db_data["resource_object"] = json.dumps(resource_object) - + # Extract storage metadata from hidden params if present hidden_params = getattr(resource_object, "_hidden_params", {}) or {} if "storage_backend" in hidden_params: db_data["storage_backend"] = hidden_params["storage_backend"] if "storage_url" in hidden_params: db_data["storage_url"] = hidden_params["storage_url"] - + # Add additional fields to database if additional_db_fields: db_data.update(additional_db_fields) @@ -215,7 +215,7 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): # Store in database table = getattr(self.prisma_client.db, self.table_name) result = await table.create(data=db_data) - + verbose_logger.debug( f"LiteLLM Managed {self.resource_type} with id={unified_resource_id} stored in db: {result}" ) @@ -227,11 +227,11 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): ) -> Optional[Dict[str, Any]]: """ Retrieve unified resource by ID from cache or database. - + Args: unified_resource_id: The unified resource ID to retrieve litellm_parent_otel_span: OpenTelemetry span for tracing - + Returns: Dictionary containing resource data or None if not found """ @@ -255,7 +255,7 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): if db_object: return db_object.model_dump() - + return None async def delete_unified_resource_id( @@ -265,11 +265,11 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): ) -> Optional[ResourceObjectType]: """ Delete unified resource from cache and database. - + Args: unified_resource_id: The unified resource ID to delete litellm_parent_otel_span: OpenTelemetry span for tracing - + Returns: The deleted resource object or None if not found """ @@ -278,22 +278,22 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): initial_value = await table.find_first( where={"unified_resource_id": unified_resource_id} ) - + if initial_value is None: raise Exception( f"LiteLLM Managed {self.resource_type} with id={unified_resource_id} not found" ) - + # Delete from cache await self.internal_usage_cache.async_set_cache( key=unified_resource_id, value=None, litellm_parent_otel_span=litellm_parent_otel_span, ) - + # Delete from database await table.delete(where={"unified_resource_id": unified_resource_id}) - + return initial_value.resource_object async def can_user_access_unified_resource_id( @@ -304,20 +304,20 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): ) -> bool: """ Check if user has access to the unified resource ID. - + Uses get_unified_resource_id() which checks cache first before hitting the database, avoiding direct DB queries in the critical request path. - + Args: unified_resource_id: The unified resource ID to check user_api_key_dict: User API key authentication details litellm_parent_otel_span: OpenTelemetry span for tracing - + Returns: True if user has access, False otherwise """ user_id = user_api_key_dict.user_id - + # Use cached method instead of direct DB query resource = await self.get_unified_resource_id( unified_resource_id, litellm_parent_otel_span @@ -325,7 +325,7 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): if resource: return resource.get("created_by") == user_id - + return False # ============================================================================ @@ -339,14 +339,14 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): ) -> Dict[str, Dict[str, str]]: """ Get model-specific resource IDs for a list of unified resource IDs. - + Args: resource_ids: List of unified resource IDs litellm_parent_otel_span: OpenTelemetry span for tracing - + Returns: Dictionary mapping unified_resource_id -> model_id -> provider_resource_id - + Example: { "unified_resource_id_1": { @@ -365,11 +365,11 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): if unified_resource_object: model_mappings = unified_resource_object.get("model_mappings", {}) - + # Handle both JSON string and dict if isinstance(model_mappings, str): model_mappings = json.loads(model_mappings) - + resource_id_mapping[resource_id] = model_mappings return resource_id_mapping @@ -387,19 +387,19 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): ) -> List[ResourceObjectType]: """ Create a resource for each model in the target list. - + Args: llm_router: LiteLLM router instance request_data: Request data for resource creation target_model_names_list: List of target model names litellm_parent_otel_span: OpenTelemetry span for tracing - + Returns: List of resource objects created for each model """ if llm_router is None: raise Exception("LLM Router not initialized. Ensure models added to proxy.") - + responses = [] for model in target_model_names_list: individual_response = await self.create_resource_for_model( @@ -418,11 +418,11 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): ) -> str: """ Generate a unified resource ID from multiple resource objects. - + Args: resource_objects: List of resource objects from different models target_model_names_list: List of target model names - + Returns: Base64 encoded unified resource ID """ @@ -431,12 +431,12 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): resource_object=resource_objects[0], target_model_names_list=target_model_names_list, ) - + # Convert to URL-safe base64 and strip padding base64_unified_id = ( base64.urlsafe_b64encode(unified_id_format.encode()).decode().rstrip("=") ) - + return base64_unified_id def extract_model_mappings_from_responses( @@ -445,10 +445,10 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): ) -> Dict[str, str]: """ Extract model mappings from resource objects. - + Args: resource_objects: List of resource objects from different models - + Returns: Dictionary mapping model_id -> provider_resource_id """ @@ -458,8 +458,10 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): # Get hidden params if available hidden_params = getattr(resource_object, "_hidden_params", {}) or {} model_resource_id_mapping = hidden_params.get("model_resource_id_mapping") - - if model_resource_id_mapping and isinstance(model_resource_id_mapping, dict): + + if model_resource_id_mapping and isinstance( + model_resource_id_mapping, dict + ): model_mappings.update(model_resource_id_mapping) return model_mappings @@ -478,17 +480,17 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): ) -> List[Dict]: """ Filter deployments based on model mappings for a resource. - + This is used by the router to select only deployments that have the resource available. - + Args: model: Model name healthy_deployments: List of healthy deployments request_kwargs: Request kwargs containing resource_id and mappings parent_otel_span: OpenTelemetry span for tracing resource_id_key: Key to use for resource ID in request_kwargs - + Returns: Filtered list of deployments """ @@ -500,7 +502,7 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): Optional[Dict[str, Dict[str, str]]], request_kwargs.get("model_resource_id_mapping"), ) - + allowed_model_ids = [] if resource_id and model_resource_id_mapping: model_id_dict = model_resource_id_mapping.get(resource_id, {}) @@ -522,7 +524,7 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): def get_unified_id_prefix(self) -> str: """ Get the prefix for unified IDs for this resource type. - + Returns: Prefix string (e.g., "litellm_proxy:") """ @@ -537,29 +539,29 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): ) -> Dict[str, Any]: """ List resources created by a user. - + Args: user_api_key_dict: User API key authentication details limit: Maximum number of resources to return after: Cursor for pagination additional_filters: Additional filters to apply - + Returns: Dictionary with list of resources and pagination info """ where_clause: Dict[str, Any] = {} - + # Filter by user who created the resource if user_api_key_dict.user_id: where_clause["created_by"] = user_api_key_dict.user_id - + if after: where_clause["id"] = {"gt": after} - + # Add additional filters if additional_filters: where_clause.update(additional_filters) - + # Fetch resources fetch_limit = limit or 20 table = getattr(self.prisma_client.db, self.table_name) @@ -568,7 +570,7 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): take=fetch_limit, order={"created_at": "desc"}, ) - + resource_objects: List[Any] = [] for resource in resources: try: @@ -580,13 +582,13 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): resource_data = resource.resource_object if isinstance(resource_data, str): resource_data = json.loads(resource_data) - + # Set unified ID if hasattr(resource_data, "id"): resource_data.id = resource.unified_resource_id elif isinstance(resource_data, dict): resource_data["id"] = resource.unified_resource_id - + resource_objects.append(resource_data) except Exception as e: @@ -595,7 +597,7 @@ class BaseManagedResource(ABC, Generic[ResourceObjectType]): f"{resource.unified_resource_id}: {e}" ) continue - + return { "object": "list", "data": resource_objects, diff --git a/litellm/llms/base_llm/managed_resources/utils.py b/litellm/llms/base_llm/managed_resources/utils.py index 0d843b6d128..59f5ff0d845 100644 --- a/litellm/llms/base_llm/managed_resources/utils.py +++ b/litellm/llms/base_llm/managed_resources/utils.py @@ -16,21 +16,21 @@ def is_base64_encoded_unified_id( ) -> Union[str, Literal[False]]: """ Check if a resource ID is a base64 encoded unified ID. - + Args: resource_id: The resource ID to check prefix: The expected prefix for unified IDs - + Returns: Decoded string if valid unified ID, False otherwise """ # Ensure resource_id is a string if not isinstance(resource_id, str): return False - + # Add padding back if needed padded = resource_id + "=" * (-len(resource_id) % 4) - + # Decode from base64 try: decoded = base64.urlsafe_b64decode(padded).decode() @@ -47,13 +47,13 @@ def extract_target_model_names_from_unified_id( ) -> List[str]: """ Extract target model names from a unified resource ID. - + Args: unified_id: The unified resource ID (decoded or encoded) - + Returns: List of target model names - + Example: unified_id = "litellm_proxy:vector_store;unified_id,uuid;target_model_names,gpt-4,gemini-2.0" returns: ["gpt-4", "gemini-2.0"] @@ -62,18 +62,18 @@ def extract_target_model_names_from_unified_id( # Ensure unified_id is a string if not isinstance(unified_id, str): return [] - + # Decode if it's base64 encoded decoded_id = is_base64_encoded_unified_id(unified_id) if decoded_id: unified_id = decoded_id - + # Extract model names using regex match = re.search(r"target_model_names,([^;]+)", unified_id) if match: # Split on comma and strip whitespace from each model name return [model.strip() for model in match.group(1).split(",")] - + return [] except Exception: return [] @@ -84,13 +84,13 @@ def extract_resource_type_from_unified_id( ) -> Optional[str]: """ Extract resource type from a unified resource ID. - + Args: unified_id: The unified resource ID (decoded or encoded) - + Returns: Resource type string or None - + Example: unified_id = "litellm_proxy:vector_store;unified_id,uuid;..." returns: "vector_store" @@ -99,17 +99,17 @@ def extract_resource_type_from_unified_id( # Ensure unified_id is a string if not isinstance(unified_id, str): return None - + # Decode if it's base64 encoded decoded_id = is_base64_encoded_unified_id(unified_id) if decoded_id: unified_id = decoded_id - + # Extract resource type (comes after prefix and before first semicolon) match = re.search(r"litellm_proxy:([^;]+)", unified_id) if match: return match.group(1).strip() - + return None except Exception: return None @@ -120,13 +120,13 @@ def extract_unified_uuid_from_unified_id( ) -> Optional[str]: """ Extract the UUID from a unified resource ID. - + Args: unified_id: The unified resource ID (decoded or encoded) - + Returns: UUID string or None - + Example: unified_id = "litellm_proxy:vector_store;unified_id,abc-123;..." returns: "abc-123" @@ -135,17 +135,17 @@ def extract_unified_uuid_from_unified_id( # Ensure unified_id is a string if not isinstance(unified_id, str): return None - + # Decode if it's base64 encoded decoded_id = is_base64_encoded_unified_id(unified_id) if decoded_id: unified_id = decoded_id - + # Extract UUID match = re.search(r"unified_id,([^;]+)", unified_id) if match: return match.group(1).strip() - + return None except Exception: return None @@ -156,13 +156,13 @@ def extract_model_id_from_unified_id( ) -> Optional[str]: """ Extract model ID from a unified resource ID. - + Args: unified_id: The unified resource ID (decoded or encoded) - + Returns: Model ID string or None - + Example: unified_id = "litellm_proxy:vector_store;...;model_id,gpt-4-model-id;..." returns: "gpt-4-model-id" @@ -171,17 +171,17 @@ def extract_model_id_from_unified_id( # Ensure unified_id is a string if not isinstance(unified_id, str): return None - + # Decode if it's base64 encoded decoded_id = is_base64_encoded_unified_id(unified_id) if decoded_id: unified_id = decoded_id - + # Extract model ID match = re.search(r"model_id,([^;]+)", unified_id) if match: return match.group(1).strip() - + return None except Exception: return None @@ -192,13 +192,13 @@ def extract_provider_resource_id_from_unified_id( ) -> Optional[str]: """ Extract provider resource ID from a unified resource ID. - + Args: unified_id: The unified resource ID (decoded or encoded) - + Returns: Provider resource ID string or None - + Example: unified_id = "litellm_proxy:vector_store;...;resource_id,vs_abc123;..." returns: "vs_abc123" @@ -207,24 +207,24 @@ def extract_provider_resource_id_from_unified_id( # Ensure unified_id is a string if not isinstance(unified_id, str): return None - + # Decode if it's base64 encoded decoded_id = is_base64_encoded_unified_id(unified_id) if decoded_id: unified_id = decoded_id - + # Extract resource ID (try multiple patterns for different resource types) patterns = [ r"resource_id,([^;]+)", r"vector_store_id,([^;]+)", r"file_id,([^;]+)", ] - + for pattern in patterns: match = re.search(pattern, unified_id) if match: return match.group(1).strip() - + return None except Exception: return None @@ -240,7 +240,7 @@ def generate_unified_id_string( ) -> str: """ Generate a unified ID string (before base64 encoding). - + Args: resource_type: Type of resource (e.g., "vector_store", "file") unified_uuid: UUID for this unified resource @@ -248,10 +248,10 @@ def generate_unified_id_string( provider_resource_id: Resource ID from the provider model_id: Model ID from the router additional_fields: Additional fields to include in the ID - + Returns: Unified ID string (not yet base64 encoded) - + Example: generate_unified_id_string( resource_type="vector_store", @@ -270,53 +270,49 @@ def generate_unified_id_string( f"resource_id,{provider_resource_id}", f"model_id,{model_id}", ] - + # Add additional fields if provided if additional_fields: for key, value in additional_fields.items(): parts.append(f"{key},{value}") - + return ";".join(parts) def encode_unified_id(unified_id_string: str) -> str: """ Encode a unified ID string to base64. - + Args: unified_id_string: The unified ID string to encode - + Returns: Base64 encoded unified ID (URL-safe, padding stripped) """ - return ( - base64.urlsafe_b64encode(unified_id_string.encode()) - .decode() - .rstrip("=") - ) + return base64.urlsafe_b64encode(unified_id_string.encode()).decode().rstrip("=") def decode_unified_id(encoded_unified_id: str) -> Optional[str]: """ Decode a base64 encoded unified ID. - + Args: encoded_unified_id: The base64 encoded unified ID - + Returns: Decoded unified ID string or None if invalid """ try: # Add padding back if needed padded = encoded_unified_id + "=" * (-len(encoded_unified_id) % 4) - + # Decode from base64 decoded = base64.urlsafe_b64decode(padded).decode() - + # Verify it starts with the expected prefix if decoded.startswith("litellm_proxy:"): return decoded - + return None except Exception: return None @@ -327,13 +323,13 @@ def parse_unified_id( ) -> Optional[dict]: """ Parse a unified ID into its components. - + Args: unified_id: The unified ID (encoded or decoded) - + Returns: Dictionary with parsed components or None if invalid - + Example: { "resource_type": "vector_store", @@ -352,12 +348,16 @@ def parse_unified_id( decoded_id = unified_id else: return None - + return { "resource_type": extract_resource_type_from_unified_id(decoded_id), "unified_uuid": extract_unified_uuid_from_unified_id(decoded_id), - "target_model_names": extract_target_model_names_from_unified_id(decoded_id), - "provider_resource_id": extract_provider_resource_id_from_unified_id(decoded_id), + "target_model_names": extract_target_model_names_from_unified_id( + decoded_id + ), + "provider_resource_id": extract_provider_resource_id_from_unified_id( + decoded_id + ), "model_id": extract_model_id_from_unified_id(decoded_id), } except Exception: diff --git a/litellm/llms/base_llm/ocr/transformation.py b/litellm/llms/base_llm/ocr/transformation.py index 29929a2bf62..7d16c696dba 100644 --- a/litellm/llms/base_llm/ocr/transformation.py +++ b/litellm/llms/base_llm/ocr/transformation.py @@ -23,6 +23,7 @@ DocumentType = Dict[str, str] class OCRPageDimensions(LiteLLMPydanticObjectBase): """Page dimensions from OCR response.""" + dpi: Optional[int] = None height: Optional[int] = None width: Optional[int] = None @@ -30,27 +31,30 @@ class OCRPageDimensions(LiteLLMPydanticObjectBase): class OCRPageImage(LiteLLMPydanticObjectBase): """Image extracted from OCR page.""" + image_base64: Optional[str] = None bbox: Optional[Dict[str, Any]] = None - + model_config = {"extra": "allow"} class OCRPage(LiteLLMPydanticObjectBase): """Single page from OCR response.""" + index: int markdown: str images: Optional[List[OCRPageImage]] = None dimensions: Optional[OCRPageDimensions] = None - + model_config = {"extra": "allow"} class OCRUsageInfo(LiteLLMPydanticObjectBase): """Usage information from OCR response.""" + pages_processed: Optional[int] = None doc_size_bytes: Optional[int] = None - + model_config = {"extra": "allow"} @@ -59,12 +63,13 @@ class OCRResponse(LiteLLMPydanticObjectBase): Standard OCR response format. Standardized to Mistral OCR format - other providers should transform to this format. """ + pages: List[OCRPage] model: str document_annotation: Optional[Any] = None usage_info: Optional[OCRUsageInfo] = None object: str = "ocr" - + model_config = {"extra": "allow"} # Define private attributes using PrivateAttr @@ -73,6 +78,7 @@ class OCRResponse(LiteLLMPydanticObjectBase): class OCRRequestData(LiteLLMPydanticObjectBase): """OCR request data structure.""" + data: Optional[Union[Dict, bytes]] = None files: Optional[Dict[str, Any]] = None @@ -142,21 +148,23 @@ class BaseOCRConfig: """ Transform OCR request to provider-specific format. Override in provider-specific implementations. - + Note: By the time this method is called, any file-type documents have already been converted to document_url/image_url format with base64 data URIs by the preprocessing in litellm/ocr/main.py. - + Args: model: Model name document: Document to process - always a dict with type="document_url" or type="image_url" optional_params: Optional parameters for the request headers: Request headers - + Returns: OCRRequestData with data and files fields """ - raise NotImplementedError("transform_ocr_request must be implemented by provider") + raise NotImplementedError( + "transform_ocr_request must be implemented by provider" + ) async def async_transform_ocr_request( self, @@ -170,15 +178,15 @@ class BaseOCRConfig: Async transform OCR request to provider-specific format. Optional method - providers can override if they need async transformations (e.g., Azure AI for URL-to-base64 conversion). - + Default implementation falls back to sync transform_ocr_request. - + Args: model: Model name document: Document to process (Mistral format dict, or file path, bytes, etc.) optional_params: Optional parameters for the request headers: Request headers - + Returns: OCRRequestData with data and files fields """ @@ -202,7 +210,9 @@ class BaseOCRConfig: Transform provider-specific OCR response to standard format. Override in provider-specific implementations. """ - raise NotImplementedError("transform_ocr_response must be implemented by provider") + raise NotImplementedError( + "transform_ocr_response must be implemented by provider" + ) async def async_transform_ocr_response( self, @@ -215,14 +225,14 @@ class BaseOCRConfig: Async transform provider-specific OCR response to standard format. Optional method - providers can override if they need async transformations (e.g., Azure Document Intelligence for async operation polling). - + Default implementation falls back to sync transform_ocr_response. - + Args: model: Model name raw_response: Raw HTTP response logging_obj: Logging object - + Returns: OCRResponse in standard format """ @@ -246,4 +256,3 @@ class BaseOCRConfig: message=error_message, headers=headers, ) - diff --git a/litellm/llms/base_llm/passthrough/transformation.py b/litellm/llms/base_llm/passthrough/transformation.py index f925e6819dc..9d4396dce47 100644 --- a/litellm/llms/base_llm/passthrough/transformation.py +++ b/litellm/llms/base_llm/passthrough/transformation.py @@ -39,16 +39,14 @@ class BasePassthroughConfig(BaseLLMModelInfo): import httpx - base = base_target_url.rstrip('/') - endpoint = endpoint.lstrip('/') + base = base_target_url.rstrip("/") + endpoint = endpoint.lstrip("/") full_url = f"{base}/{endpoint}" url = httpx.URL(full_url) if request_query_params: - url = url.copy_with( - query=urlencode(request_query_params).encode("ascii") - ) + url = url.copy_with(query=urlencode(request_query_params).encode("ascii")) return url diff --git a/litellm/llms/base_llm/realtime/http_transformation.py b/litellm/llms/base_llm/realtime/http_transformation.py new file mode 100644 index 00000000000..712ec42380f --- /dev/null +++ b/litellm/llms/base_llm/realtime/http_transformation.py @@ -0,0 +1,117 @@ +""" +Base transformation class for realtime HTTP endpoints (client_secrets, realtime_calls). + +These are HTTP (not WebSocket) endpoints used by the WebRTC flow: + POST /v1/realtime/client_secrets — obtains a short-lived ephemeral key + POST /v1/realtime/calls — exchanges an SDP offer using that key +""" + +from abc import ABC, abstractmethod +from typing import Optional, Union + +import httpx + + +class BaseRealtimeHTTPConfig(ABC): + """ + Abstract base for provider-specific realtime HTTP credential / URL logic. + + Implement one subclass per provider (OpenAI, Azure, …). + """ + + # ------------------------------------------------------------------ # + # Credential resolution # + # ------------------------------------------------------------------ # + + @abstractmethod + def get_api_base( + self, + api_base: Optional[str], + **kwargs, + ) -> str: + """ + Resolve the provider API base URL. + + Resolution order (provider-specific): + explicit api_base → litellm.api_base → env var → hard-coded default + """ + + @abstractmethod + def get_api_key( + self, + api_key: Optional[str], + **kwargs, + ) -> str: + """ + Resolve the provider API key. + + Resolution order (provider-specific): + explicit api_key → litellm.api_key → env var → "" + """ + + # ------------------------------------------------------------------ # + # client_secrets endpoint # + # ------------------------------------------------------------------ # + + @abstractmethod + def get_complete_url( + self, api_base: Optional[str], model: str, api_version: Optional[str] = None + ) -> str: + """Return the full URL for POST /realtime/client_secrets.""" + + @abstractmethod + def validate_environment( + self, + headers: dict, + model: str, + api_key: Optional[str] = None, + ) -> dict: + """ + Build and return the request headers for the client_secrets call. + + Merge `headers` (caller-supplied extras) with auth / content-type + headers required by this provider. + """ + + # ------------------------------------------------------------------ # + # realtime_calls endpoint # + # ------------------------------------------------------------------ # + + def get_realtime_calls_url( + self, api_base: Optional[str], model: str, api_version: Optional[str] = None + ) -> str: + """Return the full URL for POST /realtime/calls (SDP exchange).""" + base = (api_base or "").rstrip("/") + return f"{base}/v1/realtime/calls" + + def get_realtime_calls_headers(self, ephemeral_key: str) -> dict: + """ + Build headers for the realtime_calls POST. + + The Bearer token here is the ephemeral key obtained from + client_secrets, not the long-lived provider key. + """ + return { + "Authorization": f"Bearer {ephemeral_key}", + } + + # ------------------------------------------------------------------ # + # Error handling # + # ------------------------------------------------------------------ # + + def get_error_class( + self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] + ): + """ + Map HTTP errors to LiteLLM exception types. + + Default: generic exception. Override in subclasses for provider-specific + error mapping (e.g., Azure uses different error codes). + """ + from litellm.llms.base_llm.chat.transformation import BaseLLMException + + return BaseLLMException( + status_code=status_code, + message=error_message, + headers=headers, + ) diff --git a/litellm/llms/base_llm/rerank/transformation.py b/litellm/llms/base_llm/rerank/transformation.py index b22d85e82be..7874201f7f0 100644 --- a/litellm/llms/base_llm/rerank/transformation.py +++ b/litellm/llms/base_llm/rerank/transformation.py @@ -52,8 +52,8 @@ class BaseRerankConfig(ABC): @abstractmethod def get_complete_url( - self, - api_base: Optional[str], + self, + api_base: Optional[str], model: str, optional_params: Optional[dict] = None, ) -> str: diff --git a/litellm/llms/base_llm/responses/transformation.py b/litellm/llms/base_llm/responses/transformation.py index 4cc3583ed89..f429930e002 100644 --- a/litellm/llms/base_llm/responses/transformation.py +++ b/litellm/llms/base_llm/responses/transformation.py @@ -221,11 +221,11 @@ class BaseResponsesAPIConfig(ABC): def supports_native_websocket(self) -> bool: """ Returns True if the provider has a native WebSocket endpoint for Responses API. - + Providers with native websocket support can connect directly to wss:// endpoints. Providers without native support will use the ManagedResponsesWebSocketHandler which makes HTTP streaming calls and forwards events over the websocket. - + Default: False (use managed websocket handler) """ return False diff --git a/litellm/llms/base_llm/search/__init__.py b/litellm/llms/base_llm/search/__init__.py index 5a46482ed43..f185b4e5955 100644 --- a/litellm/llms/base_llm/search/__init__.py +++ b/litellm/llms/base_llm/search/__init__.py @@ -12,4 +12,3 @@ __all__ = [ "SearchResponse", "SearchResult", ] - diff --git a/litellm/llms/base_llm/search/transformation.py b/litellm/llms/base_llm/search/transformation.py index 14941911f17..1fbc5b670a9 100644 --- a/litellm/llms/base_llm/search/transformation.py +++ b/litellm/llms/base_llm/search/transformation.py @@ -17,12 +17,13 @@ else: class SearchResult(LiteLLMPydanticObjectBase): """Single search result.""" + title: str url: str snippet: str date: Optional[str] = None last_updated: Optional[str] = None - + model_config = {"extra": "allow"} @@ -31,9 +32,10 @@ class SearchResponse(LiteLLMPydanticObjectBase): Standard Search response format. Standardized to Perplexity Search format - other providers should transform to this format. """ + results: List[SearchResult] object: str = "search" - + model_config = {"extra": "allow"} # Define private attributes using PrivateAttr @@ -48,7 +50,7 @@ class BaseSearchConfig: def __init__(self) -> None: pass - + @staticmethod def ui_friendly_name() -> str: """ @@ -56,12 +58,12 @@ class BaseSearchConfig: Override in provider-specific implementations. """ return "Unknown Search Provider" - + def get_http_method(self) -> Literal["GET", "POST"]: """ Get HTTP method for search requests. Override in provider-specific implementations if needed. - + Returns: HTTP method ('GET' or 'POST'). Default is 'POST'. """ @@ -72,7 +74,7 @@ class BaseSearchConfig: """ Get the set of Perplexity unified search parameters. These are the standard parameters that providers should transform from. - + Returns: Set of parameter names that are part of the unified spec """ @@ -105,7 +107,7 @@ class BaseSearchConfig: ) -> str: """ Get complete URL for Search endpoint. - + Args: api_base: Base URL for the API optional_params: Optional parameters for the request @@ -114,10 +116,10 @@ class BaseSearchConfig: the request body to construct query parameters in the URL. Can be a dict or list of dicts depending on provider. **kwargs: Additional keyword arguments - + Returns: Complete URL for the search endpoint - + Note: Override in provider-specific implementations. """ @@ -132,15 +134,17 @@ class BaseSearchConfig: """ Transform Search request to provider-specific format. Override in provider-specific implementations. - + Args: query: Search query (string or list of strings) optional_params: Optional parameters for the request - + Returns: Dict with request data """ - raise NotImplementedError("transform_search_request must be implemented by provider") + raise NotImplementedError( + "transform_search_request must be implemented by provider" + ) def transform_search_response( self, @@ -152,7 +156,9 @@ class BaseSearchConfig: Transform provider-specific Search response to standard format. Override in provider-specific implementations. """ - raise NotImplementedError("transform_search_response must be implemented by provider") + raise NotImplementedError( + "transform_search_response must be implemented by provider" + ) def get_error_class( self, @@ -166,4 +172,3 @@ class BaseSearchConfig: message=error_message, headers=headers, ) - diff --git a/litellm/llms/base_llm/skills/__init__.py b/litellm/llms/base_llm/skills/__init__.py index 3c523a0d128..e0b860ffb7a 100644 --- a/litellm/llms/base_llm/skills/__init__.py +++ b/litellm/llms/base_llm/skills/__init__.py @@ -3,4 +3,3 @@ from .transformation import BaseSkillsAPIConfig __all__ = ["BaseSkillsAPIConfig"] - diff --git a/litellm/llms/base_llm/skills/transformation.py b/litellm/llms/base_llm/skills/transformation.py index 7c2ebc35298..017587c0b0c 100644 --- a/litellm/llms/base_llm/skills/transformation.py +++ b/litellm/llms/base_llm/skills/transformation.py @@ -43,11 +43,11 @@ class BaseSkillsAPIConfig(ABC): ) -> dict: """ Validate and update headers with provider-specific requirements - + Args: headers: Base headers dictionary litellm_params: LiteLLM parameters - + Returns: Updated headers dictionary """ @@ -62,12 +62,12 @@ class BaseSkillsAPIConfig(ABC): ) -> str: """ Get the complete URL for the API request - + Args: api_base: Base API URL endpoint: API endpoint (e.g., 'skills', 'skills/{id}') skill_id: Optional skill ID for specific skill operations - + Returns: Complete URL """ @@ -84,12 +84,12 @@ class BaseSkillsAPIConfig(ABC): ) -> Dict: """ Transform create skill request to provider-specific format - + Args: create_request: Skill creation parameters litellm_params: LiteLLM parameters headers: Request headers - + Returns: Provider-specific request body """ @@ -103,11 +103,11 @@ class BaseSkillsAPIConfig(ABC): ) -> Skill: """ Transform provider response to Skill object - + Args: raw_response: Raw HTTP response logging_obj: Logging object - + Returns: Skill object """ @@ -122,12 +122,12 @@ class BaseSkillsAPIConfig(ABC): ) -> Tuple[str, Dict]: """ Transform list skills request parameters - + Args: list_params: List parameters (pagination, filters) litellm_params: LiteLLM parameters headers: Request headers - + Returns: Tuple of (url, query_params) """ @@ -141,11 +141,11 @@ class BaseSkillsAPIConfig(ABC): ) -> ListSkillsResponse: """ Transform provider response to ListSkillsResponse - + Args: raw_response: Raw HTTP response logging_obj: Logging object - + Returns: ListSkillsResponse object """ @@ -161,13 +161,13 @@ class BaseSkillsAPIConfig(ABC): ) -> Tuple[str, Dict]: """ Transform get skill request - + Args: skill_id: Skill ID api_base: Base API URL litellm_params: LiteLLM parameters headers: Request headers - + Returns: Tuple of (url, headers) """ @@ -181,11 +181,11 @@ class BaseSkillsAPIConfig(ABC): ) -> Skill: """ Transform provider response to Skill object - + Args: raw_response: Raw HTTP response logging_obj: Logging object - + Returns: Skill object """ @@ -201,13 +201,13 @@ class BaseSkillsAPIConfig(ABC): ) -> Tuple[str, Dict]: """ Transform delete skill request - + Args: skill_id: Skill ID api_base: Base API URL litellm_params: LiteLLM parameters headers: Request headers - + Returns: Tuple of (url, headers) """ @@ -221,11 +221,11 @@ class BaseSkillsAPIConfig(ABC): ) -> DeleteSkillResponse: """ Transform provider response to DeleteSkillResponse - + Args: raw_response: Raw HTTP response logging_obj: Logging object - + Returns: DeleteSkillResponse object """ @@ -243,4 +243,3 @@ class BaseSkillsAPIConfig(ABC): message=error_message, headers=headers, ) - diff --git a/litellm/llms/base_llm/text_to_speech/transformation.py b/litellm/llms/base_llm/text_to_speech/transformation.py index 31f581cec0f..0e30ddae5fe 100644 --- a/litellm/llms/base_llm/text_to_speech/transformation.py +++ b/litellm/llms/base_llm/text_to_speech/transformation.py @@ -24,10 +24,11 @@ else: class TextToSpeechRequestData(TypedDict, total=False): """ Structured return type for text-to-speech transformations. - + This ensures a consistent interface across all TTS providers. Providers should set ONE of: dict_body, ssml_body, or text_body. """ + dict_body: Dict[str, Any] # JSON request body (e.g., OpenAI TTS) ssml_body: str # SSML/XML string body (e.g., Azure AVA TTS) headers: Dict[str, str] # Provider-specific headers to merge with base headers @@ -116,7 +117,7 @@ class BaseTextToSpeechConfig(ABC): ) -> TextToSpeechRequestData: """ Transform request to provider-specific format. - + Returns: TextToSpeechRequestData: A structured dict containing: - body: The request body (JSON dict, XML string, or binary data) @@ -146,4 +147,3 @@ class BaseTextToSpeechConfig(ABC): message=error_message, headers=headers, ) - diff --git a/litellm/llms/base_llm/vector_store/transformation.py b/litellm/llms/base_llm/vector_store/transformation.py index 935fd53c199..5fbf0a4b19f 100644 --- a/litellm/llms/base_llm/vector_store/transformation.py +++ b/litellm/llms/base_llm/vector_store/transformation.py @@ -27,7 +27,6 @@ else: class BaseVectorStoreConfig: - def get_supported_openai_params( self, model: str ) -> List[VECTOR_STORE_OPENAI_PARAMS]: @@ -61,7 +60,6 @@ class BaseVectorStoreConfig: litellm_logging_obj: LiteLLMLoggingObj, litellm_params: dict, ) -> Tuple[str, Dict]: - pass async def atransform_search_vector_store_request( diff --git a/litellm/llms/base_llm/vector_store_files/transformation.py b/litellm/llms/base_llm/vector_store_files/transformation.py index f751022faaf..f13de563821 100644 --- a/litellm/llms/base_llm/vector_store_files/transformation.py +++ b/litellm/llms/base_llm/vector_store_files/transformation.py @@ -58,9 +58,9 @@ class BaseVectorStoreFilesConfig(ABC): ... @abstractmethod - def get_vector_store_file_endpoints_by_type(self) -> Dict[ - str, Tuple[Tuple[str, str], ...] - ]: + def get_vector_store_file_endpoints_by_type( + self, + ) -> Dict[str, Tuple[Tuple[str, str], ...]]: ... @abstractmethod diff --git a/litellm/llms/base_llm/videos/transformation.py b/litellm/llms/base_llm/videos/transformation.py index 1ad91a43df8..2201a63363d 100644 --- a/litellm/llms/base_llm/videos/transformation.py +++ b/litellm/llms/base_llm/videos/transformation.py @@ -145,13 +145,13 @@ class BaseVideoConfig(ABC): Async transform video content download response to bytes. Optional method - providers can override if they need async transformations (e.g., RunwayML for downloading video from CloudFront URL). - + Default implementation falls back to sync transform_video_content_response. - + Args: raw_response: Raw HTTP response logging_obj: Logging object - + Returns: Video content as bytes """ @@ -173,7 +173,7 @@ class BaseVideoConfig(ABC): ) -> Tuple[str, Dict]: """ Transform the video remix request into a URL and data - + Returns: Tuple[str, Dict]: (url, data) for the video remix request """ @@ -201,7 +201,7 @@ class BaseVideoConfig(ABC): ) -> Tuple[str, Dict]: """ Transform the video list request into a URL and params - + Returns: Tuple[str, Dict]: (url, params) for the video list request """ @@ -213,7 +213,7 @@ class BaseVideoConfig(ABC): raw_response: httpx.Response, logging_obj: LiteLLMLoggingObj, custom_llm_provider: Optional[str] = None, - ) -> Dict[str,str]: + ) -> Dict[str, str]: pass @abstractmethod @@ -226,7 +226,7 @@ class BaseVideoConfig(ABC): ) -> Tuple[str, Dict]: """ Transform the video delete request into a URL and data - + Returns: Tuple[str, Dict]: (url, data) for the video delete request """ @@ -250,7 +250,7 @@ class BaseVideoConfig(ABC): ) -> Tuple[str, Dict]: """ Transform the video retrieve request into a URL and data/params - + Returns: Tuple[str, Dict]: (url, params) for the video retrieve request """ diff --git a/litellm/llms/baseten/chat.py b/litellm/llms/baseten/chat.py index 05fc9961ac5..1e49b346088 100644 --- a/litellm/llms/baseten/chat.py +++ b/litellm/llms/baseten/chat.py @@ -82,14 +82,16 @@ class BasetenConfig(OpenAIGPTConfig): optional_params[param] = value return optional_params - def _get_openai_compatible_provider_info(self, api_base: str, api_key: str) -> tuple: + def _get_openai_compatible_provider_info( + self, api_base: str, api_key: str + ) -> tuple: """ Get the OpenAI compatible provider info for Baseten """ # Default to Model API default_api_base = "https://inference.baseten.co/v1" default_api_key = api_key or "BASETEN_API_KEY" - + return default_api_base, default_api_key @staticmethod @@ -99,10 +101,11 @@ class BasetenConfig(OpenAIGPTConfig): """ # Remove 'baseten/' prefix if present model_id = model.replace("baseten/", "") - + # Check if it's an 8-digit alphanumeric code import re - return bool(re.match(r'^[a-zA-Z0-9]{8}$', model_id)) + + return bool(re.match(r"^[a-zA-Z0-9]{8}$", model_id)) @staticmethod def get_api_base_for_model(model: str) -> str: @@ -115,4 +118,4 @@ class BasetenConfig(OpenAIGPTConfig): return f"https://model-{model_id}.api.baseten.co/environments/production/sync/v1" else: # Use Model API - return "https://inference.baseten.co/v1" \ No newline at end of file + return "https://inference.baseten.co/v1" diff --git a/litellm/llms/bedrock/base_aws_llm.py b/litellm/llms/bedrock/base_aws_llm.py index 5da118a8f53..697fccd268b 100644 --- a/litellm/llms/bedrock/base_aws_llm.py +++ b/litellm/llms/bedrock/base_aws_llm.py @@ -747,7 +747,10 @@ class BaseAWSLLM: with open(web_identity_token_file, "r") as f: web_identity_token = f.read().strip() - irsa_sts_kwargs: dict = {"region_name": region, "verify": self._get_ssl_verify(ssl_verify)} + irsa_sts_kwargs: dict = { + "region_name": region, + "verify": self._get_ssl_verify(ssl_verify), + } if aws_sts_endpoint is not None: irsa_sts_kwargs["endpoint_url"] = aws_sts_endpoint @@ -814,7 +817,10 @@ class BaseAWSLLM: """Handle same-account role assumption for IRSA.""" import boto3 - irsa_sts_kwargs: dict = {"region_name": region, "verify": self._get_ssl_verify(ssl_verify)} + irsa_sts_kwargs: dict = { + "region_name": region, + "verify": self._get_ssl_verify(ssl_verify), + } if aws_sts_endpoint is not None: irsa_sts_kwargs["endpoint_url"] = aws_sts_endpoint @@ -889,7 +895,11 @@ class BaseAWSLLM: web_identity_token_file = os.getenv("AWS_WEB_IDENTITY_TOKEN_FILE") irsa_role_arn = os.getenv("AWS_ROLE_ARN") - region = aws_region_name or os.getenv("AWS_REGION") or os.getenv("AWS_DEFAULT_REGION") + region = ( + aws_region_name + or os.getenv("AWS_REGION") + or os.getenv("AWS_DEFAULT_REGION") + ) # If we have IRSA environment variables and no explicit credentials, # we need to use the web identity token flow diff --git a/litellm/llms/bedrock/batches/handler.py b/litellm/llms/bedrock/batches/handler.py index 4a26bd43348..e0c7c088362 100644 --- a/litellm/llms/bedrock/batches/handler.py +++ b/litellm/llms/bedrock/batches/handler.py @@ -12,6 +12,7 @@ class BedrockBatchesHandler: E.g. Twelve Labs Embedding Async Invoke """ + @staticmethod def _handle_async_invoke_status( batch_id: str, aws_region_name: str, logging_obj=None, **kwargs diff --git a/litellm/llms/bedrock/batches/transformation.py b/litellm/llms/bedrock/batches/transformation.py index a9bc1b26c88..5d008038ca9 100644 --- a/litellm/llms/bedrock/batches/transformation.py +++ b/litellm/llms/bedrock/batches/transformation.py @@ -29,7 +29,7 @@ class BedrockBatchesConfig(BaseAWSLLM, BaseBatchesConfig): """ Config for Bedrock Batches - handles batch job creation and management for Bedrock """ - + def __init__(self): super().__init__() self.common_utils = CommonBatchFilesUtils() @@ -69,19 +69,15 @@ class BedrockBatchesConfig(BaseAWSLLM, BaseBatchesConfig): Bedrock batch jobs are created via the model invocation job API. """ aws_region_name = self._get_aws_region_name(optional_params, model) - + # Bedrock model invocation job endpoint # Format: https://bedrock.{region}.amazonaws.com/model-invocation-job - bedrock_endpoint = f"https://bedrock.{aws_region_name}.amazonaws.com/model-invocation-job" - + bedrock_endpoint = ( + f"https://bedrock.{aws_region_name}.amazonaws.com/model-invocation-job" + ) + return bedrock_endpoint - - - - - - def transform_create_batch_request( self, model: str, @@ -91,7 +87,7 @@ class BedrockBatchesConfig(BaseAWSLLM, BaseBatchesConfig): ) -> Dict[str, Any]: """ Transform the batch creation request to Bedrock format. - + Bedrock batch inference requires: - modelId: The Bedrock model ID - jobName: Unique name for the batch job @@ -103,19 +99,21 @@ class BedrockBatchesConfig(BaseAWSLLM, BaseBatchesConfig): input_file_id = create_batch_data.get("input_file_id") if not input_file_id: raise ValueError("input_file_id is required for Bedrock batch creation") - + # Extract S3 information from file ID using common utility input_bucket, input_key = self.common_utils.parse_s3_uri(input_file_id) - + # Get output S3 configuration - output_bucket = litellm_params.get("s3_output_bucket_name") or os.getenv("AWS_S3_OUTPUT_BUCKET_NAME") + output_bucket = litellm_params.get("s3_output_bucket_name") or os.getenv( + "AWS_S3_OUTPUT_BUCKET_NAME" + ) if not output_bucket: # Use same bucket as input if no output bucket specified output_bucket = input_bucket - + # Get IAM role ARN role_arn = ( - litellm_params.get("aws_batch_role_arn") + litellm_params.get("aws_batch_role_arn") or optional_params.get("aws_batch_role_arn") or os.getenv("AWS_BATCH_ROLE_ARN") ) @@ -125,47 +123,47 @@ class BedrockBatchesConfig(BaseAWSLLM, BaseBatchesConfig): "Set 'aws_batch_role_arn' in litellm_params or AWS_BATCH_ROLE_ARN env var" ) - if not model: - raise ValueError("Could not determine Bedrock model ID. Please pass `model` in your request body.") - + raise ValueError( + "Could not determine Bedrock model ID. Please pass `model` in your request body." + ) + # Generate job name with the correct model ID using common utility job_name = self.common_utils.generate_unique_job_name(model, prefix="litellm") output_key = f"litellm-batch-outputs/{job_name}/" - + # Build input data config input_data_config: BedrockInputDataConfig = { "s3InputDataConfig": BedrockS3InputDataConfig( s3Uri=f"s3://{input_bucket}/{input_key}" ) } - + # Build output data config s3_output_config: BedrockS3OutputDataConfig = BedrockS3OutputDataConfig( s3Uri=f"s3://{output_bucket}/{output_key}" ) - + # Add optional KMS encryption key ID if provided - s3_encryption_key_id = ( - litellm_params.get("s3_encryption_key_id") - or get_secret_str("AWS_S3_ENCRYPTION_KEY_ID") - ) + s3_encryption_key_id = litellm_params.get( + "s3_encryption_key_id" + ) or get_secret_str("AWS_S3_ENCRYPTION_KEY_ID") if s3_encryption_key_id: s3_output_config["s3EncryptionKeyId"] = s3_encryption_key_id - + output_data_config: BedrockOutputDataConfig = { "s3OutputDataConfig": s3_output_config } - + # Create Bedrock batch request with proper typing bedrock_request: BedrockCreateBatchRequest = { "modelId": model, "jobName": job_name, "inputDataConfig": input_data_config, "outputDataConfig": output_data_config, - "roleArn": role_arn + "roleArn": role_arn, } - + # Add optional parameters if provided completion_window = create_batch_data.get("completion_window") if completion_window: @@ -182,15 +180,15 @@ class BedrockBatchesConfig(BaseAWSLLM, BaseBatchesConfig): data=bedrock_request, endpoint_url=endpoint_url, optional_params=optional_params, - method="POST" + method="POST", ) - + # Return a pre-signed request format that the HTTP handler can use return { "method": "POST", "url": endpoint_url, "headers": signed_headers, - "data": signed_data.decode('utf-8') + "data": signed_data.decode("utf-8"), } def transform_create_batch_response( @@ -207,17 +205,17 @@ class BedrockBatchesConfig(BaseAWSLLM, BaseBatchesConfig): response_data: BedrockCreateBatchResponse = raw_response.json() except Exception as e: raise ValueError(f"Failed to parse Bedrock batch response: {e}") - + # Extract information from typed Bedrock response job_arn = response_data.get("jobArn", "") status_str: str = str(response_data.get("status", "Submitted")) - + # Map Bedrock status to OpenAI-compatible status status_mapping: Dict[str, str] = { "Submitted": "validating", "Validating": "validating", "Scheduled": "in_progress", - "InProgress": "in_progress", + "InProgress": "in_progress", "PartiallyCompleted": "completed", "Completed": "completed", "Failed": "failed", @@ -225,12 +223,24 @@ class BedrockBatchesConfig(BaseAWSLLM, BaseBatchesConfig): "Stopped": "cancelled", "Expired": "expired", } - - openai_status = cast(Literal["validating", "failed", "in_progress", "finalizing", "completed", "expired", "cancelling", "cancelled"], status_mapping.get(status_str, "validating")) - + + openai_status = cast( + Literal[ + "validating", + "failed", + "in_progress", + "finalizing", + "completed", + "expired", + "cancelling", + "cancelled", + ], + status_mapping.get(status_str, "validating"), + ) + # Get original request data from litellm_params if available original_request = litellm_params.get("original_batch_request", {}) - + # Create LiteLLM batch object return LiteLLMBatch( id=job_arn, # Use ARN as the batch ID @@ -263,12 +273,12 @@ class BedrockBatchesConfig(BaseAWSLLM, BaseBatchesConfig): ) -> Dict[str, Any]: """ Transform batch retrieval request for Bedrock. - + Args: batch_id: Bedrock job ARN optional_params: Optional parameters litellm_params: LiteLLM parameters - + Returns: Transformed request data for Bedrock GetModelInvocationJob API """ @@ -276,66 +286,113 @@ class BedrockBatchesConfig(BaseAWSLLM, BaseBatchesConfig): # The GetModelInvocationJob API expects the full ARN as the identifier if not batch_id.startswith("arn:aws:bedrock:"): raise ValueError(f"Invalid batch_id format. Expected ARN, got: {batch_id}") - + # Extract the job identifier from the ARN - use the full ARN path part # ARN format: arn:aws:bedrock:region:account:model-invocation-job/job-name arn_parts = batch_id.split(":") if len(arn_parts) < 6: raise ValueError(f"Invalid ARN format: {batch_id}") - + region = arn_parts[3] # arn_parts[5] contains "model-invocation-job/{jobId}" - + # Build the endpoint URL for GetModelInvocationJob # AWS API format: GET /model-invocation-job/{jobIdentifier} # Use the FULL ARN as jobIdentifier and URL-encode it (includes ':' and '/') import urllib.parse as _ul + encoded_arn = _ul.quote(batch_id, safe="") - endpoint_url = f"https://bedrock.{region}.amazonaws.com/model-invocation-job/{encoded_arn}" - + endpoint_url = ( + f"https://bedrock.{region}.amazonaws.com/model-invocation-job/{encoded_arn}" + ) + # Use common utility for AWS signing signed_headers, _ = self.common_utils.sign_aws_request( service_name="bedrock", data={}, # GET request has no body endpoint_url=endpoint_url, optional_params=optional_params, - method="GET" + method="GET", ) - + # Return pre-signed request format return { "method": "GET", "url": endpoint_url, "headers": signed_headers, - "data": None + "data": None, } def _parse_timestamps_and_status(self, response_data, status_str: str): """Helper to parse timestamps based on status.""" import datetime + def parse_timestamp(ts_str: Optional[str]) -> Optional[int]: if not ts_str: return None try: - dt = datetime.datetime.fromisoformat(ts_str.replace('Z', '+00:00')) + dt = datetime.datetime.fromisoformat(ts_str.replace("Z", "+00:00")) return int(dt.timestamp()) except Exception: return None - - created_at = parse_timestamp(str(response_data.get("submitTime")) if response_data.get("submitTime") is not None else None) + + created_at = parse_timestamp( + str(response_data.get("submitTime")) + if response_data.get("submitTime") is not None + else None + ) in_progress_states = {"InProgress", "Validating", "Scheduled"} in_progress_at = ( - parse_timestamp(str(response_data.get("lastModifiedTime")) if response_data.get("lastModifiedTime") is not None else None) + parse_timestamp( + str(response_data.get("lastModifiedTime")) + if response_data.get("lastModifiedTime") is not None + else None + ) if status_str in in_progress_states else None ) - completed_at = parse_timestamp(str(response_data.get("endTime")) if response_data.get("endTime") is not None else None) if status_str in {"Completed", "PartiallyCompleted"} else None - failed_at = parse_timestamp(str(response_data.get("endTime")) if response_data.get("endTime") is not None else None) if status_str == "Failed" else None - cancelled_at = parse_timestamp(str(response_data.get("endTime")) if response_data.get("endTime") is not None else None) if status_str == "Stopped" else None - expires_at = parse_timestamp(str(response_data.get("jobExpirationTime")) if response_data.get("jobExpirationTime") is not None else None) - - return created_at, in_progress_at, completed_at, failed_at, cancelled_at, expires_at - + completed_at = ( + parse_timestamp( + str(response_data.get("endTime")) + if response_data.get("endTime") is not None + else None + ) + if status_str in {"Completed", "PartiallyCompleted"} + else None + ) + failed_at = ( + parse_timestamp( + str(response_data.get("endTime")) + if response_data.get("endTime") is not None + else None + ) + if status_str == "Failed" + else None + ) + cancelled_at = ( + parse_timestamp( + str(response_data.get("endTime")) + if response_data.get("endTime") is not None + else None + ) + if status_str == "Stopped" + else None + ) + expires_at = parse_timestamp( + str(response_data.get("jobExpirationTime")) + if response_data.get("jobExpirationTime") is not None + else None + ) + + return ( + created_at, + in_progress_at, + completed_at, + failed_at, + cancelled_at, + expires_at, + ) + def _extract_file_configs(self, response_data): """Helper to extract input and output file configurations.""" # Extract input file ID @@ -345,7 +402,7 @@ class BedrockBatchesConfig(BaseAWSLLM, BaseBatchesConfig): s3_input_config = input_data_config.get("s3InputDataConfig", {}) if isinstance(s3_input_config, dict): input_file_id = s3_input_config.get("s3Uri", "") - + # Extract output file ID output_file_id = None output_data_config = response_data.get("outputDataConfig", {}) @@ -353,9 +410,9 @@ class BedrockBatchesConfig(BaseAWSLLM, BaseBatchesConfig): s3_output_config = output_data_config.get("s3OutputDataConfig", {}) if isinstance(s3_output_config, dict): output_file_id = s3_output_config.get("s3Uri", "") - + return input_file_id, output_file_id - + def _extract_errors_and_metadata(self, response_data, raw_response): """Helper to extract errors and enriched metadata.""" # Extract errors @@ -364,11 +421,12 @@ class BedrockBatchesConfig(BaseAWSLLM, BaseBatchesConfig): if message: from openai.types.batch import Errors from openai.types.batch_error import BatchError + errors = Errors( data=[BatchError(message=message, code=str(raw_response.status_code))], - object="list" + object="list", ) - + # Enrich metadata with useful Bedrock fields enriched_metadata_raw: Dict[str, Any] = { "jobName": response_data.get("jobName"), @@ -379,6 +437,7 @@ class BedrockBatchesConfig(BaseAWSLLM, BaseBatchesConfig): "vpcConfig": response_data.get("vpcConfig"), } import json as _json + enriched_metadata: Dict[str, str] = {} for _k, _v in enriched_metadata_raw.items(): if _v is None: @@ -390,7 +449,7 @@ class BedrockBatchesConfig(BaseAWSLLM, BaseBatchesConfig): enriched_metadata[_k] = str(_v) else: enriched_metadata[_k] = str(_v) - + return errors, enriched_metadata def transform_retrieve_batch_response( @@ -404,31 +463,60 @@ class BedrockBatchesConfig(BaseAWSLLM, BaseBatchesConfig): Transform Bedrock batch retrieval response to LiteLLM format. """ from litellm.types.llms.bedrock import BedrockGetBatchResponse + try: response_data: BedrockGetBatchResponse = raw_response.json() except Exception as e: raise ValueError(f"Failed to parse Bedrock batch response: {e}") - + job_arn = response_data.get("jobArn", "") status_str: str = str(response_data.get("status", "Submitted")) - + # Map Bedrock status to OpenAI-compatible status status_mapping: Dict[str, str] = { - "Submitted": "validating", "Validating": "validating", "Scheduled": "in_progress", - "InProgress": "in_progress", "PartiallyCompleted": "completed", "Completed": "completed", - "Failed": "failed", "Stopping": "cancelling", "Stopped": "cancelled", "Expired": "expired" + "Submitted": "validating", + "Validating": "validating", + "Scheduled": "in_progress", + "InProgress": "in_progress", + "PartiallyCompleted": "completed", + "Completed": "completed", + "Failed": "failed", + "Stopping": "cancelling", + "Stopped": "cancelled", + "Expired": "expired", } - openai_status = cast(Literal["validating", "failed", "in_progress", "finalizing", "completed", "expired", "cancelling", "cancelled"], status_mapping.get(status_str, "validating")) - + openai_status = cast( + Literal[ + "validating", + "failed", + "in_progress", + "finalizing", + "completed", + "expired", + "cancelling", + "cancelled", + ], + status_mapping.get(status_str, "validating"), + ) + # Parse timestamps - created_at, in_progress_at, completed_at, failed_at, cancelled_at, expires_at = self._parse_timestamps_and_status(response_data, status_str) - + ( + created_at, + in_progress_at, + completed_at, + failed_at, + cancelled_at, + expires_at, + ) = self._parse_timestamps_and_status(response_data, status_str) + # Extract file configurations input_file_id, output_file_id = self._extract_file_configs(response_data) - + # Extract errors and metadata - errors, enriched_metadata = self._extract_errors_and_metadata(response_data, raw_response) - + errors, enriched_metadata = self._extract_errors_and_metadata( + response_data, raw_response + ) + return LiteLLMBatch( id=job_arn, object="batch", @@ -459,5 +547,3 @@ class BedrockBatchesConfig(BaseAWSLLM, BaseBatchesConfig): Get Bedrock-specific error class using common utility. """ return self.common_utils.get_error_class(error_message, status_code, headers) - - diff --git a/litellm/llms/bedrock/chat/agentcore/__init__.py b/litellm/llms/bedrock/chat/agentcore/__init__.py index a2f13876203..2c83261fc92 100644 --- a/litellm/llms/bedrock/chat/agentcore/__init__.py +++ b/litellm/llms/bedrock/chat/agentcore/__init__.py @@ -1,4 +1,3 @@ from .transformation import AmazonAgentCoreConfig __all__ = ["AmazonAgentCoreConfig"] - diff --git a/litellm/llms/bedrock/chat/agentcore/transformation.py b/litellm/llms/bedrock/chat/agentcore/transformation.py index 560fadad7c5..d6eb5a734c4 100644 --- a/litellm/llms/bedrock/chat/agentcore/transformation.py +++ b/litellm/llms/bedrock/chat/agentcore/transformation.py @@ -26,7 +26,15 @@ from litellm.types.llms.bedrock_agentcore import ( AgentCoreUsage, ) from litellm.types.llms.openai import AllMessageValues -from litellm.types.utils import Choices, Delta, Message, ModelResponse, ModelResponseStream, StreamingChoices, Usage +from litellm.types.utils import ( + Choices, + Delta, + Message, + ModelResponse, + ModelResponseStream, + StreamingChoices, + Usage, +) if TYPE_CHECKING: from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj @@ -364,9 +372,7 @@ class AmazonAgentCoreConfig(BaseConfig, BaseAWSLLM): ) # Strategy 2: {"response": [{"text": "..."}]} - Strands agent content blocks - if "response" in response_json and isinstance( - response_json["response"], list - ): + if "response" in response_json and isinstance(response_json["response"], list): content = self._extract_content_from_message( {"content": response_json["response"]} # type: ignore ) @@ -498,11 +504,11 @@ class AmazonAgentCoreConfig(BaseConfig, BaseAWSLLM): buffer += text_chunk # Process complete lines - while '\n' in buffer: - line, buffer = buffer.split('\n', 1) + while "\n" in buffer: + line, buffer = buffer.split("\n", 1) line = line.strip() - if not line or not line.startswith('data:'): + if not line or not line.startswith("data:"): continue json_str = line[5:].strip() @@ -556,11 +562,15 @@ class AmazonAgentCoreConfig(BaseConfig, BaseAWSLLM): ) ] usage_data: AgentCoreUsage = metadata["usage"] # type: ignore - setattr(chunk, "usage", Usage( - prompt_tokens=usage_data.get("inputTokens", 0), - completion_tokens=usage_data.get("outputTokens", 0), - total_tokens=usage_data.get("totalTokens", 0), - )) + setattr( + chunk, + "usage", + Usage( + prompt_tokens=usage_data.get("inputTokens", 0), + completion_tokens=usage_data.get("outputTokens", 0), + total_tokens=usage_data.get("totalTokens", 0), + ), + ) yield chunk # Process final message @@ -710,11 +720,11 @@ class AmazonAgentCoreConfig(BaseConfig, BaseAWSLLM): buffer += text_chunk # Process complete lines - while '\n' in buffer: - line, buffer = buffer.split('\n', 1) + while "\n" in buffer: + line, buffer = buffer.split("\n", 1) line = line.strip() - if not line or not line.startswith('data:'): + if not line or not line.startswith("data:"): continue json_str = line[5:].strip() @@ -768,11 +778,15 @@ class AmazonAgentCoreConfig(BaseConfig, BaseAWSLLM): ) ] usage_data: AgentCoreUsage = metadata["usage"] # type: ignore - setattr(chunk, "usage", Usage( - prompt_tokens=usage_data.get("inputTokens", 0), - completion_tokens=usage_data.get("outputTokens", 0), - total_tokens=usage_data.get("totalTokens", 0), - )) + setattr( + chunk, + "usage", + Usage( + prompt_tokens=usage_data.get("inputTokens", 0), + completion_tokens=usage_data.get("outputTokens", 0), + total_tokens=usage_data.get("totalTokens", 0), + ), + ) yield chunk # Process final message @@ -863,7 +877,9 @@ class AmazonAgentCoreConfig(BaseConfig, BaseAWSLLM): ) parsed = self._parse_json_response(response_json) - async def _json_as_async_stream() -> AsyncGenerator[ModelResponseStream, None]: + async def _json_as_async_stream() -> AsyncGenerator[ + ModelResponseStream, None + ]: # Content chunk content_chunk = ModelResponseStream( id=f"chatcmpl-{uuid.uuid4()}", diff --git a/litellm/llms/bedrock/chat/converse_handler.py b/litellm/llms/bedrock/chat/converse_handler.py index 26986aab586..ef46ae5c189 100644 --- a/litellm/llms/bedrock/chat/converse_handler.py +++ b/litellm/llms/bedrock/chat/converse_handler.py @@ -70,7 +70,9 @@ def make_sync_call( ) else: decoder = AWSEventStreamDecoder(model=model, json_mode=json_mode) - completion_stream = decoder.iter_bytes(response.iter_bytes(chunk_size=stream_chunk_size)) + completion_stream = decoder.iter_bytes( + response.iter_bytes(chunk_size=stream_chunk_size) + ) # LOGGING logging_obj.post_call( @@ -124,7 +126,7 @@ class BedrockConverseLLM(BaseAWSLLM): endpoint_url=api_base, data=data, headers=headers, - api_key=api_key + api_key=api_key, ) ## LOGGING @@ -184,7 +186,7 @@ class BedrockConverseLLM(BaseAWSLLM): headers=headers, ) data = json.dumps(request_data) - + prepped = self.get_request_headers( credentials=credentials, aws_region_name=litellm_params.get("aws_region_name") or "us-west-2", @@ -192,7 +194,7 @@ class BedrockConverseLLM(BaseAWSLLM): endpoint_url=api_base, data=data, headers=headers, - api_key=api_key + api_key=api_key, ) ## LOGGING @@ -278,7 +280,7 @@ class BedrockConverseLLM(BaseAWSLLM): _stripped = _model_for_id for rp in ["bedrock/converse/", "bedrock/", "converse/"]: if _stripped.startswith(rp): - _stripped = _stripped[len(rp):] + _stripped = _stripped[len(rp) :] break # Strip embedded region prefix (e.g. "bedrock/us-east-1/model" -> "model") # and capture it so it can be used as aws_region_name below. @@ -294,7 +296,10 @@ class BedrockConverseLLM(BaseAWSLLM): break modelId = self.encode_model_id(model_id=_model_for_id) # Inject region extracted from model path so _get_aws_region_name picks it up - if _region_from_model is not None and "aws_region_name" not in optional_params: + if ( + _region_from_model is not None + and "aws_region_name" not in optional_params + ): optional_params["aws_region_name"] = _region_from_model fake_stream = litellm.AmazonConverseConfig().should_fake_stream( @@ -304,7 +309,6 @@ class BedrockConverseLLM(BaseAWSLLM): custom_llm_provider="bedrock", ) - ### SET REGION NAME ### aws_region_name = self._get_aws_region_name( optional_params=optional_params, @@ -362,7 +366,7 @@ class BedrockConverseLLM(BaseAWSLLM): headers = {"Content-Type": "application/json"} if extra_headers is not None: headers = {"Content-Type": "application/json", **extra_headers} - + # Filter beta headers in HTTP headers before making the request headers = update_headers_with_filtered_beta( headers=headers, provider="bedrock_converse" @@ -408,7 +412,7 @@ class BedrockConverseLLM(BaseAWSLLM): timeout=timeout, client=client, credentials=credentials, - api_key=api_key + api_key=api_key, ) # type: ignore ## TRANSFORMATION ## @@ -421,7 +425,7 @@ class BedrockConverseLLM(BaseAWSLLM): headers=extra_headers, ) data = json.dumps(_data) - + prepped = self.get_request_headers( credentials=credentials, aws_region_name=aws_region_name, @@ -429,7 +433,7 @@ class BedrockConverseLLM(BaseAWSLLM): endpoint_url=proxy_endpoint_url, data=data, headers=headers, - api_key=api_key + api_key=api_key, ) ## LOGGING diff --git a/litellm/llms/bedrock/chat/converse_transformation.py b/litellm/llms/bedrock/chat/converse_transformation.py index d210f294c64..229457a73b4 100644 --- a/litellm/llms/bedrock/chat/converse_transformation.py +++ b/litellm/llms/bedrock/chat/converse_transformation.py @@ -51,6 +51,7 @@ from litellm.types.llms.openai import ( ) from litellm.types.utils import ( ChatCompletionMessageToolCall, + CompletionTokensDetailsWrapper, Function, Message, ModelResponse, @@ -63,6 +64,7 @@ from litellm.utils import ( has_tool_call_blocks, last_assistant_with_tool_calls_has_no_thinking_blocks, supports_reasoning, + token_counter, ) from ..common_utils import ( @@ -348,7 +350,9 @@ class AmazonConverseConfig(BaseConfig): # Check if the model is a Nova 2 model (matches nova-2-lite, nova-2-pro, etc.) # Also check for nova-2/ spec prefix for imported models - return model_without_region.startswith("amazon.nova-2-") or model_without_region.startswith("nova-2/") + return model_without_region.startswith( + "amazon.nova-2-" + ) or model_without_region.startswith("nova-2/") def _map_web_search_options( self, web_search_options: dict, model: str @@ -762,8 +766,7 @@ class AmazonConverseConfig(BaseConfig): def _supports_native_structured_outputs(model: str) -> bool: """Check if the Bedrock model supports native structured outputs (outputConfig.textFormat).""" return any( - substring in model - for substring in BEDROCK_NATIVE_STRUCTURED_OUTPUT_MODELS + substring in model for substring in BEDROCK_NATIVE_STRUCTURED_OUTPUT_MODELS ) @staticmethod @@ -917,9 +920,7 @@ class AmazonConverseConfig(BaseConfig): if param == "parallel_tool_calls": disable_parallel = not value optional_params["_parallel_tool_use_config"] = { - "tool_choice": { - "disable_parallel_tool_use": disable_parallel - } + "tool_choice": {"disable_parallel_tool_use": disable_parallel} } if param == "thinking": optional_params["thinking"] = value @@ -1199,13 +1200,21 @@ class AmazonConverseConfig(BaseConfig): + supported_config_params ) inference_params.pop("json_mode", None) # used for handling json_schema + # Anthropic-only key. Bedrock expects `outputConfig` (camelCase) and + # will reject `output_config` if it leaks through pass-through routes. + inference_params.pop("output_config", None) # Extract requestMetadata before processing other parameters request_metadata = inference_params.pop("requestMetadata", None) if request_metadata is not None: self._validate_request_metadata(request_metadata) - output_config: Optional[OutputConfigBlock] = inference_params.pop("outputConfig", None) + output_config: Optional[OutputConfigBlock] = inference_params.pop( + "outputConfig", None + ) + inference_params.pop( + "output_config", None + ) # Bedrock Converse doesn't support it # keep supported params in 'inference_params', and set all model-specific params in 'additional_request_params' additional_request_params = { @@ -1216,10 +1225,16 @@ class AmazonConverseConfig(BaseConfig): } # Handle parallel_tool_calls configuration - parallel_tool_use_config = additional_request_params.pop("_parallel_tool_use_config", None) + parallel_tool_use_config = additional_request_params.pop( + "_parallel_tool_use_config", None + ) if parallel_tool_use_config is not None and is_claude_4_5_on_bedrock(model): for key, value in parallel_tool_use_config.items(): - if key in additional_request_params and isinstance(additional_request_params[key], dict) and isinstance(value, dict): + if ( + key in additional_request_params + and isinstance(additional_request_params[key], dict) + and isinstance(value, dict) + ): additional_request_params[key].update(value) else: additional_request_params[key] = value @@ -1301,7 +1316,16 @@ class AmazonConverseConfig(BaseConfig): # "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 or "sonnet-4.6" in model_lower or "sonnet_4.6" in model_lower or "sonnet-4-6" in model_lower or "sonnet_4_6" in 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 + or "sonnet-4.6" in model_lower + or "sonnet_4.6" in model_lower + or "sonnet-4-6" in model_lower + or "sonnet_4_6" in model_lower + ): computer_use_header = "computer-use-2025-11-24" elif ( "opus-4.5" in model_lower @@ -1620,7 +1644,11 @@ class AmazonConverseConfig(BaseConfig): thinking_blocks_list.append(_redacted_block) return thinking_blocks_list - def _transform_usage(self, usage: ConverseTokenUsageBlock) -> Usage: + def _transform_usage( + self, + usage: ConverseTokenUsageBlock, + reasoning_content: Optional[str] = None, + ) -> Usage: input_tokens = usage["inputTokens"] output_tokens = usage["outputTokens"] total_tokens = usage["totalTokens"] @@ -1637,6 +1665,19 @@ class AmazonConverseConfig(BaseConfig): prompt_tokens_details = PromptTokensDetailsWrapper( cached_tokens=cache_read_input_tokens ) + reasoning_tokens = ( + token_counter(text=reasoning_content, count_response_tokens=True) + if reasoning_content + else 0 + ) + completion_tokens_details = CompletionTokensDetailsWrapper( + reasoning_tokens=reasoning_tokens, + text_tokens=( + output_tokens - reasoning_tokens + if reasoning_tokens > 0 + else output_tokens + ), + ) openai_usage = Usage( prompt_tokens=input_tokens, completion_tokens=output_tokens, @@ -1644,6 +1685,7 @@ class AmazonConverseConfig(BaseConfig): prompt_tokens_details=prompt_tokens_details, cache_creation_input_tokens=cache_creation_input_tokens, cache_read_input_tokens=cache_read_input_tokens, + completion_tokens_details=completion_tokens_details, ) return openai_usage @@ -1706,7 +1748,9 @@ class AmazonConverseConfig(BaseConfig): 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]], @@ -1723,9 +1767,9 @@ class AmazonConverseConfig(BaseConfig): """ 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): """ @@ -1838,9 +1882,7 @@ class AmazonConverseConfig(BaseConfig): verbose_logger.debug( "Processing JSON tool call response for response_format" ) - json_mode_content_str: Optional[str] = tools[0]["function"].get( - "arguments" - ) + json_mode_content_str: Optional[str] = tools[0]["function"].get("arguments") if json_mode_content_str is not None: json_mode_content_str = AmazonConverseConfig._unwrap_bedrock_properties( json_mode_content_str @@ -1938,9 +1980,9 @@ class AmazonConverseConfig(BaseConfig): 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: @@ -1959,17 +2001,17 @@ class AmazonConverseConfig(BaseConfig): 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 filtered_tools = self._filter_json_mode_tools( json_mode=json_mode, @@ -1980,7 +2022,10 @@ class AmazonConverseConfig(BaseConfig): chat_completion_message["tool_calls"] = filtered_tools ## CALCULATING USAGE - bedrock returns usage in the headers - usage = self._transform_usage(completion_response["usage"]) + usage = self._transform_usage( + completion_response["usage"], + reasoning_content=chat_completion_message.get("reasoning_content"), + ) ## HANDLE TOOL CALLS _message = Message(**chat_completion_message) diff --git a/litellm/llms/bedrock/chat/invoke_handler.py b/litellm/llms/bedrock/chat/invoke_handler.py index 9b06e198203..1077731779d 100644 --- a/litellm/llms/bedrock/chat/invoke_handler.py +++ b/litellm/llms/bedrock/chat/invoke_handler.py @@ -407,9 +407,9 @@ class BedrockLLM(BaseAWSLLM): # Claude 3+ indicators (all use Messages API) messages_api_indicators = [ - "claude-3", # Claude 3.x models - "claude-opus-4", # Claude Opus 4 - "claude-sonnet-4", # Claude Sonnet 4 + "claude-3", # Claude 3.x models + "claude-opus-4", # Claude Opus 4 + "claude-sonnet-4", # Claude Sonnet 4 "claude-haiku-4", # Claude Haiku 4 ] diff --git a/litellm/llms/bedrock/chat/invoke_transformations/amazon_mistral_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/amazon_mistral_transformation.py index 58dfa17a722..3992de4d4fc 100644 --- a/litellm/llms/bedrock/chat/invoke_transformations/amazon_mistral_transformation.py +++ b/litellm/llms/bedrock/chat/invoke_transformations/amazon_mistral_transformation.py @@ -87,7 +87,9 @@ class AmazonMistralConfig(AmazonInvokeConfig, BaseConfig): return optional_params @staticmethod - def get_outputText(completion_response: dict, model_response: "ModelResponse") -> str: + def get_outputText( + completion_response: dict, model_response: "ModelResponse" + ) -> str: """This function extracts the output text from a bedrock mistral completion. As a side effect, it updates the finish reason for a model response. @@ -101,11 +103,17 @@ class AmazonMistralConfig(AmazonInvokeConfig, BaseConfig): """ if "choices" in completion_response: outputText = completion_response["choices"][0]["message"]["content"] - model_response.choices[0].finish_reason = completion_response["choices"][0]["finish_reason"] + model_response.choices[0].finish_reason = completion_response["choices"][0][ + "finish_reason" + ] elif "outputs" in completion_response: outputText = completion_response["outputs"][0]["text"] - model_response.choices[0].finish_reason = completion_response["outputs"][0]["stop_reason"] + model_response.choices[0].finish_reason = completion_response["outputs"][0][ + "stop_reason" + ] else: - raise BedrockError(message="Unexpected mistral completion response", status_code=400) + raise BedrockError( + message="Unexpected mistral completion response", status_code=400 + ) return outputText diff --git a/litellm/llms/bedrock/chat/invoke_transformations/amazon_moonshot_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/amazon_moonshot_transformation.py index e53410760dd..3aeb65b58c7 100644 --- a/litellm/llms/bedrock/chat/invoke_transformations/amazon_moonshot_transformation.py +++ b/litellm/llms/bedrock/chat/invoke_transformations/amazon_moonshot_transformation.py @@ -32,11 +32,11 @@ else: class AmazonMoonshotConfig(AmazonInvokeConfig, MoonshotChatConfig): """ Configuration for Bedrock Moonshot AI (Kimi K2) models. - + Reference: https://aws.amazon.com/about-aws/whats-new/2025/12/amazon-bedrock-fully-managed-open-weight-models/ https://platform.moonshot.ai/docs/api/chat - + Supported Params for the Amazon / Moonshot models: - `max_tokens` (integer) max tokens - `temperature` (float) temperature for model (0-1 for Moonshot) @@ -44,10 +44,10 @@ class AmazonMoonshotConfig(AmazonInvokeConfig, MoonshotChatConfig): - `stream` (bool) whether to stream responses - `tools` (list) tool definitions (supported on kimi-k2-thinking) - `tool_choice` (str|dict) tool choice specification (supported on kimi-k2-thinking) - + NOT Supported on Bedrock: - `stop` sequences (Bedrock doesn't support stopSequences field for this model) - + Note: The kimi-k2-thinking model DOES support tool calls, unlike kimi-thinking-preview. """ @@ -62,7 +62,7 @@ class AmazonMoonshotConfig(AmazonInvokeConfig, MoonshotChatConfig): def _get_model_id(self, model: str) -> str: """ Extract the actual model ID from the LiteLLM model name. - + Removes routing prefixes like: - bedrock/invoke/moonshot.kimi-k2-thinking -> moonshot.kimi-k2-thinking - invoke/moonshot.kimi-k2-thinking -> moonshot.kimi-k2-thinking @@ -71,39 +71,44 @@ class AmazonMoonshotConfig(AmazonInvokeConfig, MoonshotChatConfig): # Remove bedrock/ prefix if present if model.startswith("bedrock/"): model = model[8:] - + # Remove invoke/ prefix if present if model.startswith("invoke/"): model = model[7:] - + # Remove any provider prefix (e.g., moonshot/) if "/" in model and not model.startswith("arn:"): parts = model.split("/", 1) if len(parts) == 2: model = parts[1] - + return model def get_supported_openai_params(self, model: str) -> List[str]: """ Get the supported OpenAI params for Moonshot AI models on Bedrock. - + Bedrock-specific limitations: - stopSequences field is not supported on Bedrock (unlike native Moonshot API) - functions parameter is not supported (use tools instead) - tool_choice doesn't support "required" value - + Note: kimi-k2-thinking DOES support tool calls (unlike kimi-thinking-preview) The parent MoonshotChatConfig class handles the kimi-thinking-preview exclusion. """ - excluded_params: List[str] = ["functions", "stop"] # Bedrock doesn't support stopSequences - - base_openai_params = super(MoonshotChatConfig, self).get_supported_openai_params(model=model) + excluded_params: List[str] = [ + "functions", + "stop", + ] # Bedrock doesn't support stopSequences + + base_openai_params = super( + MoonshotChatConfig, self + ).get_supported_openai_params(model=model) final_params: List[str] = [] for param in base_openai_params: if param not in excluded_params: final_params.append(param) - + return final_params def map_openai_params( @@ -115,7 +120,7 @@ class AmazonMoonshotConfig(AmazonInvokeConfig, MoonshotChatConfig): ) -> dict: """ Map OpenAI parameters to Moonshot AI parameters for Bedrock. - + Handles Moonshot AI specific limitations: - tool_choice doesn't support "required" value - Temperature <0.3 limitation for n>1 @@ -139,7 +144,7 @@ class AmazonMoonshotConfig(AmazonInvokeConfig, MoonshotChatConfig): ) -> dict: """ Transform the request for Bedrock Moonshot AI models. - + Uses the Moonshot transformation logic which handles: - Converting content lists to strings (Moonshot doesn't support list format) - Adding tool_choice="required" message if needed @@ -148,10 +153,10 @@ class AmazonMoonshotConfig(AmazonInvokeConfig, MoonshotChatConfig): """ # Filter out AWS credentials using the existing method from BaseAWSLLM self._get_boto_credentials_from_optional_params(optional_params, model) - + # Strip routing prefixes to get the actual model ID clean_model_id = self._get_model_id(model) - + # Use Moonshot's transform_request which handles message transformation # and tool_choice="required" workaround return MoonshotChatConfig.transform_request( @@ -163,34 +168,34 @@ class AmazonMoonshotConfig(AmazonInvokeConfig, MoonshotChatConfig): headers=headers, ) - def _extract_reasoning_from_content(self, content: str) -> tuple[Optional[str], str]: + def _extract_reasoning_from_content( + self, content: str + ) -> tuple[Optional[str], str]: """ Extract reasoning content from tags in the response. - + Moonshot AI's Kimi K2 Thinking model returns reasoning in tags. This method extracts that content and returns it separately. - + Args: content: The full content string from the API response - + Returns: tuple: (reasoning_content, main_content) """ if not content: return None, content - + # Match ... tags reasoning_match = re.match( - r"(.*?)\s*(.*)", - content, - re.DOTALL + r"(.*?)\s*(.*)", content, re.DOTALL ) - + if reasoning_match: reasoning_content = reasoning_match.group(1).strip() main_content = reasoning_match.group(2).strip() return reasoning_content, main_content - + return None, content def transform_response( @@ -209,7 +214,7 @@ class AmazonMoonshotConfig(AmazonInvokeConfig, MoonshotChatConfig): ) -> "ModelResponse": """ Transform the response from Bedrock Moonshot AI models. - + Moonshot AI uses OpenAI-compatible response format, but returns reasoning content in tags. This method: 1. Calls parent class transformation @@ -231,22 +236,27 @@ class AmazonMoonshotConfig(AmazonInvokeConfig, MoonshotChatConfig): api_key=api_key, json_mode=json_mode, ) - + # Extract reasoning content from tags if model_response.choices and len(model_response.choices) > 0: for choice in model_response.choices: # Only process Choices (not StreamingChoices) which have message attribute - if isinstance(choice, Choices) and choice.message and choice.message.content: - reasoning_content, main_content = self._extract_reasoning_from_content( - choice.message.content - ) - + if ( + isinstance(choice, Choices) + and choice.message + and choice.message.content + ): + ( + reasoning_content, + main_content, + ) = self._extract_reasoning_from_content(choice.message.content) + if reasoning_content: # Set the reasoning_content field choice.message.reasoning_content = reasoning_content # Update the main content without reasoning tags choice.message.content = main_content - + return model_response def get_error_class( diff --git a/litellm/llms/bedrock/chat/invoke_transformations/amazon_openai_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/amazon_openai_transformation.py index a438be17458..7b64c6066d0 100644 --- a/litellm/llms/bedrock/chat/invoke_transformations/amazon_openai_transformation.py +++ b/litellm/llms/bedrock/chat/invoke_transformations/amazon_openai_transformation.py @@ -28,14 +28,14 @@ else: class AmazonBedrockOpenAIConfig(OpenAIGPTConfig, BaseAWSLLM): """ Configuration for Bedrock imported models that use OpenAI Chat Completions format. - + This class handles the transformation of requests and responses for Bedrock imported models that accept the OpenAI API format directly. - + Inherits from OpenAIGPTConfig to leverage standard OpenAI parameter handling and response transformation, while adding Bedrock-specific URL generation and AWS request signing. - + Usage: model = "bedrock/openai/arn:aws:bedrock:us-east-1:123456789012:imported-model/abc123" """ @@ -51,18 +51,18 @@ class AmazonBedrockOpenAIConfig(OpenAIGPTConfig, BaseAWSLLM): def _get_openai_model_id(self, model: str) -> str: """ Extract the actual model ID from the LiteLLM model name. - + Input format: bedrock/openai/ Returns: """ # Remove bedrock/ prefix if present if model.startswith("bedrock/"): model = model[8:] - + # Remove openai/ prefix if model.startswith("openai/"): model = model[7:] - + return model def get_complete_url( @@ -76,16 +76,16 @@ class AmazonBedrockOpenAIConfig(OpenAIGPTConfig, BaseAWSLLM): ) -> str: """ Get the complete URL for the Bedrock invoke endpoint. - + Uses the standard Bedrock invoke endpoint format. """ model_id = self._get_openai_model_id(model) - + # Get AWS region aws_region_name = self._get_aws_region_name( optional_params=optional_params, model=model ) - + # Get runtime endpoint aws_bedrock_runtime_endpoint = optional_params.get( "aws_bedrock_runtime_endpoint", None @@ -98,13 +98,15 @@ class AmazonBedrockOpenAIConfig(OpenAIGPTConfig, BaseAWSLLM): # Encode model ID for ARNs (e.g., :imported-model/ -> :imported-model%2F) model_id = CommonUtils.encode_bedrock_runtime_modelid_arn(model_id) - + # Build the invoke URL if stream: - endpoint_url = f"{endpoint_url}/model/{model_id}/invoke-with-response-stream" + endpoint_url = ( + f"{endpoint_url}/model/{model_id}/invoke-with-response-stream" + ) else: endpoint_url = f"{endpoint_url}/model/{model_id}/invoke" - + return endpoint_url def sign_request( @@ -143,20 +145,20 @@ class AmazonBedrockOpenAIConfig(OpenAIGPTConfig, BaseAWSLLM): ) -> dict: """ Transform the request to OpenAI Chat Completions format for Bedrock imported models. - + Removes AWS-specific params and stream param (handled separately in URL), then delegates to parent class for standard OpenAI request transformation. """ # Remove stream from optional_params as it's handled separately in URL optional_params.pop("stream", None) - + # Remove AWS-specific params that shouldn't be in the request body inference_params = { k: v for k, v in optional_params.items() if k not in self.aws_authentication_params } - + # Use parent class transform_request for OpenAI format return super().transform_request( model=self._get_openai_model_id(model), @@ -178,7 +180,7 @@ class AmazonBedrockOpenAIConfig(OpenAIGPTConfig, BaseAWSLLM): ) -> dict: """ Validate the environment and return headers. - + For Bedrock, we don't need Bearer token auth since we use AWS SigV4. """ return headers diff --git a/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen2_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen2_transformation.py index fe0fd40b55d..c65e9e0b083 100644 --- a/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen2_transformation.py +++ b/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen2_transformation.py @@ -24,10 +24,10 @@ from litellm.types.utils import ModelResponse, Usage class AmazonQwen2Config(AmazonQwen3Config): """ Config for sending `qwen2` requests to `/bedrock/invoke/` - + Inherits from AmazonQwen3Config since Qwen2 and Qwen3 architectures are mostly similar. The main difference is in the response format: Qwen2 uses "text" field while Qwen3 uses "generation" field. - + Reference: https://docs.aws.amazon.com/bedrock/latest/userguide/invoke-imported-model.html """ @@ -47,30 +47,32 @@ class AmazonQwen2Config(AmazonQwen3Config): ) -> ModelResponse: """ Transform Qwen2 Bedrock response to OpenAI format - + Qwen2 uses "text" field, but we also support "generation" field for compatibility. """ try: - if hasattr(raw_response, 'json'): + if hasattr(raw_response, "json"): response_data = raw_response.json() else: response_data = raw_response - + # Extract the generated text - Qwen2 uses "text" field, but also support "generation" for compatibility - generated_text = response_data.get("generation", "") or response_data.get("text", "") - + generated_text = response_data.get("generation", "") or response_data.get( + "text", "" + ) + # Clean up the response (remove assistant start token if present) if generated_text.startswith("<|im_start|>assistant\n"): - generated_text = generated_text[len("<|im_start|>assistant\n"):] + generated_text = generated_text[len("<|im_start|>assistant\n") :] if generated_text.endswith("<|im_end|>"): - generated_text = generated_text[:-len("<|im_end|>")] - + generated_text = generated_text[: -len("<|im_end|>")] + # Set the content in the existing model_response structure - if hasattr(model_response, 'choices') and len(model_response.choices) > 0: + if hasattr(model_response, "choices") and len(model_response.choices) > 0: choice = model_response.choices[0] choice.message.content = generated_text choice.finish_reason = "stop" - + # Set usage information if available in response if "usage" in response_data: usage_data = response_data["usage"] @@ -83,9 +85,9 @@ class AmazonQwen2Config(AmazonQwen3Config): total_tokens=usage_data.get("total_tokens", 0), ), ) - + return model_response - + except Exception as e: if logging_obj: logging_obj.post_call( @@ -95,4 +97,3 @@ class AmazonQwen2Config(AmazonQwen3Config): additional_args={"error": str(e)}, ) raise e - diff --git a/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen3_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen3_transformation.py index 4be3e370fa0..6325c388181 100644 --- a/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen3_transformation.py +++ b/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen3_transformation.py @@ -22,7 +22,7 @@ from litellm.types.utils import ModelResponse, Usage class AmazonQwen3Config(AmazonInvokeConfig, BaseConfig): """ Config for sending `qwen3` requests to `/bedrock/invoke/` - + Reference: https://docs.aws.amazon.com/bedrock/latest/userguide/invoke-imported-model.html """ @@ -91,12 +91,12 @@ class AmazonQwen3Config(AmazonInvokeConfig, BaseConfig): """ # Convert messages to prompt format prompt = self._convert_messages_to_prompt(messages) - + # Build the request body request_body = { "prompt": prompt, } - + # Add optional parameters if "max_tokens" in optional_params: request_body["max_gen_len"] = optional_params["max_tokens"] @@ -108,7 +108,7 @@ class AmazonQwen3Config(AmazonInvokeConfig, BaseConfig): request_body["top_k"] = optional_params["top_k"] if "stop" in optional_params: request_body["stop"] = optional_params["stop"] - + return request_body def _convert_messages_to_prompt(self, messages: List[AllMessageValues]) -> str: @@ -117,12 +117,12 @@ class AmazonQwen3Config(AmazonInvokeConfig, BaseConfig): Supports tool calls, multimodal content, and various message types """ prompt_parts = [] - + for message in messages: role = message.get("role", "") content = message.get("content", "") tool_calls = message.get("tool_calls", []) - + if role == "system": prompt_parts.append(f"<|im_start|>system\n{content}<|im_end|>") elif role == "user": @@ -134,7 +134,9 @@ class AmazonQwen3Config(AmazonInvokeConfig, BaseConfig): text_content.append(item.get("text", "")) elif item.get("type") == "image_url": # For Qwen3, we can include image placeholders - text_content.append("<|vision_start|><|image_pad|><|vision_end|>") + text_content.append( + "<|vision_start|><|image_pad|><|vision_end|>" + ) content = "".join(text_content) prompt_parts.append(f"<|im_start|>user\n{content}<|im_end|>") elif role == "assistant": @@ -142,17 +144,21 @@ class AmazonQwen3Config(AmazonInvokeConfig, BaseConfig): # Handle tool calls for tool_call in tool_calls: function_name = tool_call.get("function", {}).get("name", "") - function_args = tool_call.get("function", {}).get("arguments", "") - prompt_parts.append(f"<|im_start|>assistant\n\n{{\"name\": \"{function_name}\", \"arguments\": \"{function_args}\"}}\n<|im_end|>") + function_args = tool_call.get("function", {}).get( + "arguments", "" + ) + prompt_parts.append( + f'<|im_start|>assistant\n\n{{"name": "{function_name}", "arguments": "{function_args}"}}\n<|im_end|>' + ) else: prompt_parts.append(f"<|im_start|>assistant\n{content}<|im_end|>") elif role == "tool": # Handle tool responses prompt_parts.append(f"<|im_start|>tool\n{content}<|im_end|>") - + # Add assistant start token for response generation prompt_parts.append("<|im_start|>assistant\n") - + return "\n".join(prompt_parts) def transform_response( @@ -173,26 +179,26 @@ class AmazonQwen3Config(AmazonInvokeConfig, BaseConfig): Transform Qwen3 Bedrock response to OpenAI format """ try: - if hasattr(raw_response, 'json'): + if hasattr(raw_response, "json"): response_data = raw_response.json() else: response_data = raw_response - + # Extract the generated text - Qwen3 uses "generation" field generated_text = response_data.get("generation", "") - + # Clean up the response (remove assistant start token if present) if generated_text.startswith("<|im_start|>assistant\n"): - generated_text = generated_text[len("<|im_start|>assistant\n"):] + generated_text = generated_text[len("<|im_start|>assistant\n") :] if generated_text.endswith("<|im_end|>"): - generated_text = generated_text[:-len("<|im_end|>")] - + generated_text = generated_text[: -len("<|im_end|>")] + # Set the content in the existing model_response structure - if hasattr(model_response, 'choices') and len(model_response.choices) > 0: + if hasattr(model_response, "choices") and len(model_response.choices) > 0: choice = model_response.choices[0] choice.message.content = generated_text choice.finish_reason = "stop" - + # Set usage information if available in response if "usage" in response_data: usage_data = response_data["usage"] @@ -205,9 +211,9 @@ class AmazonQwen3Config(AmazonInvokeConfig, BaseConfig): total_tokens=usage_data.get("total_tokens", 0), ), ) - + return model_response - + except Exception as e: if logging_obj: logging_obj.post_call( diff --git a/litellm/llms/bedrock/chat/invoke_transformations/amazon_twelvelabs_pegasus_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/amazon_twelvelabs_pegasus_transformation.py index 62e98f7472f..889480d31a5 100644 --- a/litellm/llms/bedrock/chat/invoke_transformations/amazon_twelvelabs_pegasus_transformation.py +++ b/litellm/llms/bedrock/chat/invoke_transformations/amazon_twelvelabs_pegasus_transformation.py @@ -70,12 +70,12 @@ class AmazonTwelveLabsPegasusConfig(AmazonInvokeConfig, BaseConfig): def _normalize_response_format(self, value: Any) -> Any: """Normalize response_format to TwelveLabs format. - + TwelveLabs expects: { "jsonSchema": {...} } - + But OpenAI format is: { "type": "json_schema", @@ -120,14 +120,14 @@ class AmazonTwelveLabsPegasusConfig(AmazonInvokeConfig, BaseConfig): for key in ("temperature", "maxOutputTokens"): if key in optional_params: request_data[key] = optional_params.get(key) - + # Handle responseFormat - transform to TwelveLabs format if "responseFormat" in optional_params: response_format = optional_params["responseFormat"] transformed_format = self._normalize_response_format(response_format) if transformed_format: request_data["responseFormat"] = transformed_format - + return request_data def _build_media_source(self, optional_params: dict) -> Optional[dict]: @@ -200,13 +200,13 @@ class AmazonTwelveLabsPegasusConfig(AmazonInvokeConfig, BaseConfig): ) -> ModelResponse: """ Transform TwelveLabs Pegasus response to LiteLLM format. - + TwelveLabs response format: { "message": "...", "finishReason": "stop" | "length" } - + LiteLLM format: ModelResponse with choices[0].message.content and finish_reason """ @@ -217,25 +217,26 @@ class AmazonTwelveLabsPegasusConfig(AmazonInvokeConfig, BaseConfig): message=f"Error parsing response: {raw_response.text}, error: {str(e)}", status_code=raw_response.status_code, ) - + verbose_logger.debug( "twelvelabs pegasus response: %s", json.dumps(completion_response, indent=4, default=str), ) - + # Extract message content message_content = completion_response.get("message", "") - + # Extract finish reason and map to LiteLLM format finish_reason_raw = completion_response.get("finishReason", "stop") finish_reason = map_finish_reason(finish_reason_raw) - + # Set the response content try: if ( message_content and hasattr(model_response.choices[0], "message") - and getattr(model_response.choices[0].message, "tool_calls", None) is None + and getattr(model_response.choices[0].message, "tool_calls", None) + is None ): model_response.choices[0].message.content = message_content # type: ignore model_response.choices[0].finish_reason = finish_reason @@ -246,7 +247,7 @@ class AmazonTwelveLabsPegasusConfig(AmazonInvokeConfig, BaseConfig): message=f"Error setting response content: {str(e)}. Response: {completion_response}", status_code=raw_response.status_code, ) - + # Calculate usage from headers bedrock_input_tokens = raw_response.headers.get( "x-amzn-bedrock-input-token-count", None @@ -254,11 +255,11 @@ class AmazonTwelveLabsPegasusConfig(AmazonInvokeConfig, BaseConfig): bedrock_output_tokens = raw_response.headers.get( "x-amzn-bedrock-output-token-count", None ) - + prompt_tokens = int( bedrock_input_tokens or litellm.token_counter(messages=messages) ) - + completion_tokens = int( bedrock_output_tokens or litellm.token_counter( @@ -266,7 +267,7 @@ class AmazonTwelveLabsPegasusConfig(AmazonInvokeConfig, BaseConfig): count_response_tokens=True, ) ) - + model_response.created = int(time.time()) model_response.model = model usage = Usage( @@ -275,6 +276,5 @@ class AmazonTwelveLabsPegasusConfig(AmazonInvokeConfig, BaseConfig): total_tokens=prompt_tokens + completion_tokens, ) setattr(model_response, "usage", usage) - - return model_response + return model_response diff --git a/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py index 328c3a0b977..7936b6ea644 100644 --- a/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py +++ b/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py @@ -63,7 +63,7 @@ class AmazonAnthropicClaudeConfig(AmazonInvokeConfig, AnthropicConfig): if "response_format" in non_default_params: # Use a model name that forces tool-based approach model = "claude-3-sonnet-20240229" - + optional_params = AnthropicConfig.map_openai_params( self, non_default_params, @@ -71,12 +71,11 @@ class AmazonAnthropicClaudeConfig(AmazonInvokeConfig, AnthropicConfig): model, drop_params, ) - + # Restore original model name model = original_model - - return optional_params + return optional_params def transform_request( self, @@ -94,12 +93,12 @@ class AmazonAnthropicClaudeConfig(AmazonInvokeConfig, AnthropicConfig): if k not in self.aws_authentication_params } filtered_params = self._normalize_bedrock_tool_search_tools(filtered_params) - + _anthropic_request = AnthropicConfig.transform_request( self, model=model, messages=messages, - optional_params=filtered_params, + optional_params=filtered_params, litellm_params=litellm_params, headers=headers, ) @@ -130,15 +129,14 @@ class AmazonAnthropicClaudeConfig(AmazonInvokeConfig, AnthropicConfig): model=model, optional_params=optional_params, computer_tool_used=self.is_computer_tool_used(tools), - prompt_caching_set=False, + prompt_caching_set=False, file_id_used=self.is_file_id_used(messages), mcp_server_used=self.is_mcp_server_used(optional_params.get("mcp_servers")), ) beta_set.update(auto_betas) - 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(): diff --git a/litellm/llms/bedrock/common_utils.py b/litellm/llms/bedrock/common_utils.py index 8e944988a95..9666aa68c99 100644 --- a/litellm/llms/bedrock/common_utils.py +++ b/litellm/llms/bedrock/common_utils.py @@ -455,7 +455,7 @@ def get_bedrock_base_model(model: str) -> str: stripped = model for rp in ["bedrock/converse/", "bedrock/", "converse/"]: if stripped.startswith(rp): - stripped = stripped[len(rp):] + stripped = stripped[len(rp) :] break if stripped.startswith("nova-2/"): return "amazon.nova-2-custom" @@ -638,7 +638,9 @@ class BedrockModelInfo(BaseLLMModelInfo): # Check for nova spec prefixes (nova/ and nova-2/) _model_after_bedrock = model.replace("bedrock/", "", 1) - if _model_after_bedrock.startswith("nova-2/") or _model_after_bedrock.startswith("nova/"): + if _model_after_bedrock.startswith( + "nova-2/" + ) or _model_after_bedrock.startswith("nova/"): return "converse" base_model = BedrockModelInfo.get_base_model(model) diff --git a/litellm/llms/bedrock/count_tokens/bedrock_token_counter.py b/litellm/llms/bedrock/count_tokens/bedrock_token_counter.py index 772eb169689..eb7755574ac 100644 --- a/litellm/llms/bedrock/count_tokens/bedrock_token_counter.py +++ b/litellm/llms/bedrock/count_tokens/bedrock_token_counter.py @@ -101,9 +101,7 @@ class BedrockTokenCounter(BaseTokenCounter): status_code=e.status_code, ) except Exception as e: - verbose_logger.warning( - f"Error calling Bedrock CountTokens API: {e}" - ) + verbose_logger.warning(f"Error calling Bedrock CountTokens API: {e}") return TokenCountResponse( total_tokens=0, request_model=request_model, diff --git a/litellm/llms/bedrock/count_tokens/handler.py b/litellm/llms/bedrock/count_tokens/handler.py index 9d2be6cca89..cfd32342d1e 100644 --- a/litellm/llms/bedrock/count_tokens/handler.py +++ b/litellm/llms/bedrock/count_tokens/handler.py @@ -84,14 +84,16 @@ class BedrockCountTokensHandler(BedrockCountTokensConfig): api_key=api_key, ) - async_client = get_async_httpx_client(llm_provider=litellm.LlmProviders.BEDROCK) + async_client = get_async_httpx_client( + llm_provider=litellm.LlmProviders.BEDROCK + ) response = await async_client.post( - endpoint_url, - headers=signed_headers, - data=signed_body, - timeout=30.0, - ) + endpoint_url, + headers=signed_headers, + data=signed_body, + timeout=30.0, + ) verbose_logger.debug(f"Response status: {response.status_code}") diff --git a/litellm/llms/bedrock/count_tokens/transformation.py b/litellm/llms/bedrock/count_tokens/transformation.py index 64f1098e640..fe9ab80ced4 100644 --- a/litellm/llms/bedrock/count_tokens/transformation.py +++ b/litellm/llms/bedrock/count_tokens/transformation.py @@ -91,7 +91,10 @@ class BedrockCountTokensConfig(BaseAWSLLM): # Transform messages user_messages = [] for message in messages: - transformed_message: Dict[str, Any] = {"role": message.get("role"), "content": []} + transformed_message: Dict[str, Any] = { + "role": message.get("role"), + "content": [], + } content = message.get("content", "") if isinstance(content, str): transformed_message["content"].append({"text": content}) @@ -121,10 +124,16 @@ class BedrockCountTokensConfig(BaseAWSLLM): return [{"text": system}] if isinstance(system, list): # Already in blocks format (e.g. [{"type": "text", "text": "..."}]) - return [{"text": block.get("text", "")} for block in system if isinstance(block, dict)] + return [ + {"text": block.get("text", "")} + for block in system + if isinstance(block, dict) + ] return [] - def _transform_tools(self, tools: Optional[List[Dict[str, Any]]]) -> Optional[Dict[str, Any]]: + def _transform_tools( + self, tools: Optional[List[Dict[str, Any]]] + ) -> Optional[Dict[str, Any]]: """Transform Anthropic tools to Bedrock toolConfig format.""" if not tools: return None @@ -139,15 +148,19 @@ class BedrockCountTokensConfig(BaseAWSLLM): name = name[:64] description = tool.get("description") or name - input_schema = tool.get("input_schema", {"type": "object", "properties": {}}) + input_schema = tool.get( + "input_schema", {"type": "object", "properties": {}} + ) - bedrock_tools.append({ - "toolSpec": { - "name": name, - "description": description, - "inputSchema": {"json": input_schema}, + bedrock_tools.append( + { + "toolSpec": { + "name": name, + "description": description, + "inputSchema": {"json": input_schema}, + } } - }) + ) return {"tools": bedrock_tools} diff --git a/litellm/llms/bedrock/embed/amazon_nova_transformation.py b/litellm/llms/bedrock/embed/amazon_nova_transformation.py index 40d2a21e1c7..c20b52a6e0d 100644 --- a/litellm/llms/bedrock/embed/amazon_nova_transformation.py +++ b/litellm/llms/bedrock/embed/amazon_nova_transformation.py @@ -14,13 +14,18 @@ Docs - https://docs.aws.amazon.com/bedrock/latest/userguide/nova-embed.html from typing import List, Optional -from litellm.types.utils import Embedding, EmbeddingResponse, PromptTokensDetailsWrapper, Usage +from litellm.types.utils import ( + Embedding, + EmbeddingResponse, + PromptTokensDetailsWrapper, + Usage, +) class AmazonNovaEmbeddingConfig: """ Reference: https://docs.aws.amazon.com/bedrock/latest/userguide/nova-embed.html - + Amazon Nova Multimodal Embeddings supports: - Text, image, video, and audio inputs - Synchronous (InvokeModel) and asynchronous (StartAsyncInvoke) APIs @@ -46,14 +51,14 @@ class AmazonNovaEmbeddingConfig: elif k in self.get_supported_openai_params(): optional_params[k] = v return optional_params - + def _parse_data_url(self, data_url: str) -> tuple: """ Parse a data URL to extract the media type and base64 data. - + Args: data_url: Data URL in format: data:image/jpeg;base64,/9j/4AAQ... - + Returns: tuple: (media_type, base64_data) media_type: e.g., "image/jpeg", "video/mp4", "audio/mpeg" @@ -61,23 +66,25 @@ class AmazonNovaEmbeddingConfig: """ if not data_url.startswith("data:"): raise ValueError(f"Invalid data URL format: {data_url[:50]}...") - + # Split by comma to separate metadata from data # Format: data:image/jpeg;base64, if "," not in data_url: - raise ValueError(f"Invalid data URL format (missing comma): {data_url[:50]}...") - + raise ValueError( + f"Invalid data URL format (missing comma): {data_url[:50]}..." + ) + metadata, base64_data = data_url.split(",", 1) - + # Extract media type from metadata # Remove 'data:' prefix and ';base64' suffix metadata = metadata[5:] # Remove 'data:' - + if ";" in metadata: media_type = metadata.split(";")[0] else: media_type = metadata - + return media_type, base64_data def _transform_request( @@ -90,111 +97,109 @@ class AmazonNovaEmbeddingConfig: ) -> dict: """ Transform OpenAI-style input to Nova format. - + Only handles OpenAI params (dimensions). All other Nova-specific params should be passed via inference_params and will be passed through as-is. - + Args: input: The input text or media reference inference_params: Additional parameters (will be passed through) async_invoke_route: Whether this is for async invoke model_id: Model ID (for async invoke) output_s3_uri: S3 URI for output (for async invoke) - + Returns: dict: Nova embedding request """ # Determine task type task_type = "SEGMENTED_EMBEDDING" if async_invoke_route else "SINGLE_EMBEDDING" - + # Build the base request structure request: dict = { "schemaVersion": "nova-multimodal-embed-v1", "taskType": task_type, } - + # Start with inference_params (user-provided params) embedding_params = inference_params.copy() - + embedding_params.pop("output_s3_uri", None) - + # Map OpenAI dimensions to embeddingDimension if provided if "dimensions" in embedding_params: embedding_params["embeddingDimension"] = embedding_params.pop("dimensions") elif "embedding_dimension" in embedding_params: - embedding_params["embeddingDimension"] = embedding_params.pop("embedding_dimension") - + embedding_params["embeddingDimension"] = embedding_params.pop( + "embedding_dimension" + ) + # Add required embeddingPurpose if not provided (required by Nova API) if "embeddingPurpose" not in embedding_params: embedding_params["embeddingPurpose"] = "GENERIC_INDEX" - + # Add required embeddingDimension if not provided (required by Nova API) if "embeddingDimension" not in embedding_params: embedding_params["embeddingDimension"] = 3072 - + # For text/media input, add basic structure if user hasn't provided text/image/video/audio - if "text" not in embedding_params and "image" not in embedding_params and "video" not in embedding_params and "audio" not in embedding_params: + if ( + "text" not in embedding_params + and "image" not in embedding_params + and "video" not in embedding_params + and "audio" not in embedding_params + ): # Check if input is a data URL (e.g., data:image/jpeg;base64,...) if input.startswith("data:"): # Parse the data URL to extract media type and base64 data media_type, base64_data = self._parse_data_url(input) - + if media_type.startswith("image/"): # Extract image format from MIME type (e.g., image/jpeg -> jpeg) image_format = media_type.split("/")[1].lower() # Nova API expects specific formats if image_format == "jpg": image_format = "jpeg" - + embedding_params["image"] = { "format": image_format, - "source": { - "bytes": base64_data - } + "source": {"bytes": base64_data}, } elif media_type.startswith("video/"): # Handle video data URLs video_format = media_type.split("/")[1].lower() embedding_params["video"] = { "format": video_format, - "source": { - "bytes": base64_data - } + "source": {"bytes": base64_data}, } elif media_type.startswith("audio/"): # Handle audio data URLs audio_format = media_type.split("/")[1].lower() embedding_params["audio"] = { "format": audio_format, - "source": { - "bytes": base64_data - } + "source": {"bytes": base64_data}, } else: # Fallback to text for unknown types - embedding_params["text"] = { - "value": input, - "truncationMode": "END" - } + embedding_params["text"] = {"value": input, "truncationMode": "END"} elif input.startswith("s3://"): # S3 URL - default to text for now, user should specify modality embedding_params["text"] = { "source": {"s3Location": {"uri": input}}, - "truncationMode": "END" # Required by Nova API + "truncationMode": "END", # Required by Nova API } else: # Plain text input embedding_params["text"] = { "value": input, - "truncationMode": "END" # Required by Nova API + "truncationMode": "END", # Required by Nova API } - + # Set the embedding params in the request if task_type == "SINGLE_EMBEDDING": request["singleEmbeddingParams"] = embedding_params else: request["segmentedEmbeddingParams"] = embedding_params - + # For async invoke, wrap in the async invoke format if async_invoke_route and model_id: return self._wrap_async_invoke_request( @@ -202,7 +207,7 @@ class AmazonNovaEmbeddingConfig: model_id=model_id, output_s3_uri=output_s3_uri, ) - + return request def _wrap_async_invoke_request( @@ -213,12 +218,12 @@ class AmazonNovaEmbeddingConfig: ) -> dict: """ Wrap the transformed request in the AWS Bedrock async invoke format. - + Args: model_input: The transformed Nova embedding request model_id: The model identifier (without async_invoke prefix) output_s3_uri: S3 URI for output data config - + Returns: dict: The wrapped async invoke request """ @@ -228,19 +233,15 @@ class AmazonNovaEmbeddingConfig: unquoted_model_id = urllib.parse.unquote(model_id) if unquoted_model_id.startswith("async_invoke/"): unquoted_model_id = unquoted_model_id.replace("async_invoke/", "") - + # Validate that the S3 URI is not empty if not output_s3_uri or output_s3_uri.strip() == "": raise ValueError("output_s3_uri is required for async invoke requests") - + return { "modelId": unquoted_model_id, "modelInput": model_input, - "outputDataConfig": { - "s3OutputDataConfig": { - "s3Uri": output_s3_uri - } - }, + "outputDataConfig": {"s3OutputDataConfig": {"s3Uri": output_s3_uri}}, } def _transform_response( @@ -326,36 +327,35 @@ class AmazonNovaEmbeddingConfig: ) -> EmbeddingResponse: """ Transform async invoke response (invocation ARN) to OpenAI format. - + AWS async invoke returns: { "invocationArn": "arn:aws:bedrock:us-east-1:123456789012:async-invoke/abc123" } - + We transform this to a job-like embedding response with the ARN in hidden params. """ invocation_arn = response.get("invocationArn", "") - + # Create a placeholder embedding object for the job embedding = Embedding( embedding=[], # Empty embedding for async jobs index=0, object="embedding", ) - + # Create usage object (empty for async jobs) usage = Usage(prompt_tokens=0, total_tokens=0) - + # Create hidden params with job ID from litellm.types.llms.base import HiddenParams - + hidden_params = HiddenParams() setattr(hidden_params, "_invocation_arn", invocation_arn) - + return EmbeddingResponse( data=[embedding], model=model, usage=usage, hidden_params=hidden_params, ) - diff --git a/litellm/llms/bedrock/embed/amazon_titan_multimodal_transformation.py b/litellm/llms/bedrock/embed/amazon_titan_multimodal_transformation.py index e59d3cbf776..07b04734c30 100644 --- a/litellm/llms/bedrock/embed/amazon_titan_multimodal_transformation.py +++ b/litellm/llms/bedrock/embed/amazon_titan_multimodal_transformation.py @@ -13,7 +13,12 @@ from litellm.types.llms.bedrock import ( AmazonTitanMultimodalEmbeddingRequest, AmazonTitanMultimodalEmbeddingResponse, ) -from litellm.types.utils import Embedding, EmbeddingResponse, PromptTokensDetailsWrapper, Usage +from litellm.types.utils import ( + Embedding, + EmbeddingResponse, + PromptTokensDetailsWrapper, + Usage, +) from litellm.utils import get_base64_str, is_base64_encoded diff --git a/litellm/llms/bedrock/embed/amazon_titan_v2_transformation.py b/litellm/llms/bedrock/embed/amazon_titan_v2_transformation.py index ff748b58e8e..ca0b95cd64e 100644 --- a/litellm/llms/bedrock/embed/amazon_titan_v2_transformation.py +++ b/litellm/llms/bedrock/embed/amazon_titan_v2_transformation.py @@ -30,7 +30,9 @@ class AmazonTitanV2Config: normalize: Optional[bool] = None dimensions: Optional[int] = None - def __init__(self, normalize: Optional[bool] = None, dimensions: Optional[int] = None) -> None: + def __init__( + self, normalize: Optional[bool] = None, dimensions: Optional[int] = None + ) -> None: locals_ = locals().copy() for key, value in locals_.items(): if key != "self" and value is not None: @@ -57,7 +59,9 @@ class AmazonTitanV2Config: def get_supported_openai_params(self) -> List[str]: return ["dimensions", "encoding_format"] - def map_openai_params(self, non_default_params: dict, optional_params: dict) -> dict: + def map_openai_params( + self, non_default_params: dict, optional_params: dict + ) -> dict: for k, v in non_default_params.items(): if k == "dimensions": optional_params["dimensions"] = v @@ -73,10 +77,14 @@ class AmazonTitanV2Config: optional_params["embeddingTypes"] = ["float"] return optional_params - def _transform_request(self, input: str, inference_params: dict) -> AmazonTitanV2EmbeddingRequest: + def _transform_request( + self, input: str, inference_params: dict + ) -> AmazonTitanV2EmbeddingRequest: return AmazonTitanV2EmbeddingRequest(inputText=input, **inference_params) # type: ignore - def _transform_response(self, response_list: List[dict], model: str) -> EmbeddingResponse: + def _transform_response( + self, response_list: List[dict], model: str + ) -> EmbeddingResponse: total_prompt_tokens = 0 transformed_responses: List[Embedding] = [] @@ -88,12 +96,16 @@ class AmazonTitanV2Config: # Otherwise, use float data from embeddingsByType or fallback to embedding field embedding_data: Union[List[float], List[int]] - if ("embeddingsByType" in _parsed_response and - "binary" in _parsed_response["embeddingsByType"]): + if ( + "embeddingsByType" in _parsed_response + and "binary" in _parsed_response["embeddingsByType"] + ): # Use binary data if available (for encoding_format="base64") embedding_data = _parsed_response["embeddingsByType"]["binary"] - elif ("embeddingsByType" in _parsed_response and - "float" in _parsed_response["embeddingsByType"]): + elif ( + "embeddingsByType" in _parsed_response + and "float" in _parsed_response["embeddingsByType"] + ): # Use float data from embeddingsByType embedding_data = _parsed_response["embeddingsByType"]["float"] elif "embedding" in _parsed_response: diff --git a/litellm/llms/bedrock/embed/embedding.py b/litellm/llms/bedrock/embed/embedding.py index 783345d78da..27dc785bf57 100644 --- a/litellm/llms/bedrock/embed/embedding.py +++ b/litellm/llms/bedrock/embed/embedding.py @@ -287,7 +287,9 @@ class BedrockEmbedding(BaseAWSLLM): "headers": prepped.headers, }, ) - headers_for_request = dict(prepped.headers) if hasattr(prepped, 'headers') else {} + headers_for_request = ( + dict(prepped.headers) if hasattr(prepped, "headers") else {} + ) response = self._make_sync_call( client=client, timeout=timeout, @@ -357,7 +359,9 @@ class BedrockEmbedding(BaseAWSLLM): ) # Convert CaseInsensitiveDict to regular dict for httpx compatibility # This ensures custom headers are properly forwarded, especially with IAM roles and custom api_base - headers_for_request = dict(prepped.headers) if hasattr(prepped, 'headers') else {} + headers_for_request = ( + dict(prepped.headers) if hasattr(prepped, "headers") else {} + ) response = await self._make_async_call( client=client, timeout=timeout, @@ -570,7 +574,9 @@ class BedrockEmbedding(BaseAWSLLM): ## ROUTING ## # Convert CaseInsensitiveDict to regular dict for httpx compatibility - headers_for_request = dict(prepped.headers) if hasattr(prepped, 'headers') else {} + headers_for_request = ( + dict(prepped.headers) if hasattr(prepped, "headers") else {} + ) return cohere_embedding( model=model, input=input, @@ -612,7 +618,6 @@ class BedrockEmbedding(BaseAWSLLM): aws_region_name=aws_region_name, ) - from urllib.parse import quote # Encode the ARN for use in URL path @@ -627,9 +632,7 @@ class BedrockEmbedding(BaseAWSLLM): from botocore.auth import SigV4Auth from botocore.awsrequest import AWSRequest except ImportError: - raise ImportError( - "Missing boto3 to call bedrock. Run 'pip install boto3'." - ) + raise ImportError("Missing boto3 to call bedrock. Run 'pip install boto3'.") # Create AWSRequest with GET method and encoded URL request = AWSRequest( @@ -638,11 +641,11 @@ class BedrockEmbedding(BaseAWSLLM): data=None, # GET request, no body headers=headers, ) - + # Sign the request - SigV4Auth will create canonical string from request URL sigv4 = SigV4Auth(credentials, "bedrock", aws_region_name) sigv4.add_auth(request) - + # Prepare the request prepped = request.prepare() diff --git a/litellm/llms/bedrock/embed/twelvelabs_marengo_transformation.py b/litellm/llms/bedrock/embed/twelvelabs_marengo_transformation.py index c85c388eebc..56339ed2230 100644 --- a/litellm/llms/bedrock/embed/twelvelabs_marengo_transformation.py +++ b/litellm/llms/bedrock/embed/twelvelabs_marengo_transformation.py @@ -93,7 +93,9 @@ class TwelveLabsMarengoEmbeddingConfig: # Get input_type or default to "text" input_type = cast( TWELVELABS_EMBEDDING_INPUT_TYPES, - inference_params.get("inputType") or inference_params.get("input_type") or "text" + inference_params.get("inputType") + or inference_params.get("input_type") + or "text", ) # Validate that async-invoke is used for video/audio @@ -130,6 +132,7 @@ class TwelveLabsMarengoEmbeddingConfig: else: # Direct base64 string from litellm.utils import get_base64_str + b64_str = get_base64_str(input) transformed_request["mediaSource"] = {"base64String": b64_str} diff --git a/litellm/llms/bedrock/files/handler.py b/litellm/llms/bedrock/files/handler.py index 0350271dc44..13bd87a1f01 100644 --- a/litellm/llms/bedrock/files/handler.py +++ b/litellm/llms/bedrock/files/handler.py @@ -18,7 +18,7 @@ from ..base_aws_llm import BaseAWSLLM class BedrockFilesHandler(BaseAWSLLM): """ Handles downloading files from S3 for Bedrock batch processing. - + This implementation downloads files from S3 buckets where Bedrock stores batch output files. """ @@ -32,14 +32,14 @@ class BedrockFilesHandler(BaseAWSLLM): def _extract_s3_uri_from_file_id(self, file_id: str) -> str: """ Extract S3 URI from encoded file ID. - + The file ID can be in two formats: 1. Base64-encoded unified file ID containing: llm_output_file_id,s3://bucket/path 2. Direct S3 URI: s3://bucket/path - + Args: file_id: Encoded file ID or direct S3 URI - + Returns: S3 URI (e.g., "s3://bucket-name/path/to/file") """ @@ -48,7 +48,7 @@ class BedrockFilesHandler(BaseAWSLLM): # Add padding if needed padded = file_id + "=" * (-len(file_id) % 4) decoded = base64.urlsafe_b64decode(padded).decode() - + # Check if it's a unified file ID format if decoded.startswith(SpecialEnums.LITELM_MANAGED_FILE_ID_PREFIX.value): # Extract llm_output_file_id from the decoded string @@ -57,36 +57,38 @@ class BedrockFilesHandler(BaseAWSLLM): return s3_uri except Exception: pass - + # If not base64 encoded or doesn't contain llm_output_file_id, assume it's already an S3 URI if file_id.startswith("s3://"): return file_id - + # If it doesn't start with s3://, assume it's a direct S3 URI and add the prefix return f"s3://{file_id}" def _parse_s3_uri(self, s3_uri: str) -> Tuple[str, str]: """ Parse S3 URI to extract bucket name and object key. - + Args: s3_uri: S3 URI (e.g., "s3://bucket-name/path/to/file") - + Returns: Tuple of (bucket_name, object_key) """ if not s3_uri.startswith("s3://"): - raise ValueError(f"Invalid S3 URI format: {s3_uri}. Expected format: s3://bucket-name/path/to/file") - + raise ValueError( + f"Invalid S3 URI format: {s3_uri}. Expected format: s3://bucket-name/path/to/file" + ) + # Remove 's3://' prefix path = s3_uri[5:] - + if "/" in path: bucket_name, object_key = path.split("/", 1) else: bucket_name = path object_key = "" - + return bucket_name, object_key async def afile_content( @@ -98,27 +100,27 @@ class BedrockFilesHandler(BaseAWSLLM): ) -> HttpxBinaryResponseContent: """ Download file content from S3 bucket for Bedrock files. - + Args: file_content_request: Contains file_id (encoded or S3 URI) optional_params: Optional parameters containing AWS credentials timeout: Request timeout max_retries: Max retry attempts - + Returns: HttpxBinaryResponseContent: Binary content wrapped in compatible response format """ import boto3 from botocore.credentials import Credentials - + file_id = file_content_request.get("file_id") if not file_id: raise ValueError("file_id is required in file_content_request") - + # Extract S3 URI from file ID s3_uri = self._extract_s3_uri_from_file_id(file_id) bucket_name, object_key = self._parse_s3_uri(s3_uri) - + # Get AWS credentials aws_region_name = self._get_aws_region_name( optional_params=optional_params, model="" @@ -134,7 +136,7 @@ class BedrockFilesHandler(BaseAWSLLM): aws_web_identity_token=optional_params.get("aws_web_identity_token"), aws_sts_endpoint=optional_params.get("aws_sts_endpoint"), ) - + # Create S3 client s3_client = boto3.client( "s3", @@ -144,14 +146,16 @@ class BedrockFilesHandler(BaseAWSLLM): region_name=aws_region_name, verify=self._get_ssl_verify(), ) - + # Download file from S3 try: response = s3_client.get_object(Bucket=bucket_name, Key=object_key) file_content = response["Body"].read() except Exception as e: - raise ValueError(f"Failed to download file from S3: {s3_uri}. Error: {str(e)}") - + raise ValueError( + f"Failed to download file from S3: {s3_uri}. Error: {str(e)}" + ) + # Create mock HTTP response mock_response = httpx.Response( status_code=200, @@ -159,7 +163,7 @@ class BedrockFilesHandler(BaseAWSLLM): headers={"content-type": "application/octet-stream"}, request=httpx.Request(method="GET", url=s3_uri), ) - + return HttpxBinaryResponseContent(response=mock_response) def file_content( @@ -176,7 +180,7 @@ class BedrockFilesHandler(BaseAWSLLM): """ Download file content from S3 bucket for Bedrock files. Supports both sync and async operations. - + Args: _is_async: Whether to run asynchronously file_content_request: Contains file_id (encoded or S3 URI) @@ -184,7 +188,7 @@ class BedrockFilesHandler(BaseAWSLLM): optional_params: Optional parameters containing AWS credentials timeout: Request timeout max_retries: Max retry attempts - + Returns: HttpxBinaryResponseContent or Coroutine: Binary content wrapped in compatible response format """ @@ -204,4 +208,3 @@ class BedrockFilesHandler(BaseAWSLLM): max_retries=max_retries, ) ) - diff --git a/litellm/llms/bedrock/files/transformation.py b/litellm/llms/bedrock/files/transformation.py index e29b07ca3a5..096371749b5 100644 --- a/litellm/llms/bedrock/files/transformation.py +++ b/litellm/llms/bedrock/files/transformation.py @@ -36,7 +36,7 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig): """ Config for Bedrock Files - handles S3 uploads for Bedrock batch processing """ - + def __init__(self): self.jsonl_transformation = BedrockJsonlFilesTransformation() super().__init__() @@ -65,8 +65,6 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig): # No additional headers needed for S3 uploads - AWS credentials handled by BaseAWSLLM return headers - - def _get_content_from_openai_file(self, openai_file_content: FileTypes) -> str: """ Helper to extract content from various OpenAI file types and return as string. @@ -117,10 +115,10 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig): # Remove bedrock/ prefix if present if _model.startswith("bedrock/"): _model = _model[8:] - + # Replace colons with hyphens for Bedrock S3 URI compliance _model = _model.replace(":", "-") - + object_name = f"litellm-bedrock-files-{_model}-{uuid.uuid4()}.jsonl" return object_name @@ -167,12 +165,16 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig): """ Get the complete S3 URL for the file upload request """ - bucket_name = litellm_params.get("s3_bucket_name") or os.getenv("AWS_S3_BUCKET_NAME") + bucket_name = litellm_params.get("s3_bucket_name") or os.getenv( + "AWS_S3_BUCKET_NAME" + ) if not bucket_name: - raise ValueError("S3 bucket_name is required. Set 's3_bucket_name' in litellm_params or AWS_S3_BUCKET_NAME env var") - + raise ValueError( + "S3 bucket_name is required. Set 's3_bucket_name' in litellm_params or AWS_S3_BUCKET_NAME env var" + ) + aws_region_name = self._get_aws_region_name(optional_params, model) - + file_data = data.get("file") purpose = data.get("purpose") if file_data is None: @@ -181,10 +183,13 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig): raise ValueError("purpose is required") extracted_file_data = extract_file_data(file_data) object_name = self.get_object_name(extracted_file_data, purpose) - + # S3 endpoint URL format - s3_endpoint_url = optional_params.get("s3_endpoint_url") or f"https://s3.{aws_region_name}.amazonaws.com" - + s3_endpoint_url = ( + optional_params.get("s3_endpoint_url") + or f"https://s3.{aws_region_name}.amazonaws.com" + ) + return f"{s3_endpoint_url}/{bucket_name}/{object_name}" def get_supported_openai_params( @@ -201,7 +206,6 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig): ) -> dict: return optional_params - # Providers whose InvokeModel body uses the Converse API format # (messages + inferenceConfig + image blocks). Nova is the primary # example; add others here as they adopt the same schema. @@ -286,24 +290,24 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig): ) -> List[Dict[str, Any]]: """ Transforms OpenAI JSONL content to Bedrock batch format - + Bedrock batch format: { "recordId": "alphanumeric string", "modelInput": {JSON body} } Example: { - "recordId": "CALL0000001", + "recordId": "CALL0000001", "modelInput": { - "anthropic_version": "bedrock-2023-05-31", + "anthropic_version": "bedrock-2023-05-31", "max_tokens": 1024, - "messages": [ - { - "role": "user", + "messages": [ + { + "role": "user", "content": [{"type": "text", "text": "Hello"}] } ] } } """ - + bedrock_jsonl_content = [] for idx, _openai_jsonl_content in enumerate(openai_jsonl_content): # Extract the request body from OpenAI format @@ -312,28 +316,28 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig): try: model, _, _, _ = get_llm_provider( - model=model, - custom_llm_provider=None, - ) + model=model, + custom_llm_provider=None, + ) except Exception as e: - verbose_logger.exception(f"litellm.llms.bedrock.files.transformation.py::_transform_openai_jsonl_content_to_bedrock_jsonl_content() - Error inferring custom_llm_provider - {str(e)}") - + verbose_logger.exception( + f"litellm.llms.bedrock.files.transformation.py::_transform_openai_jsonl_content_to_bedrock_jsonl_content() - Error inferring custom_llm_provider - {str(e)}" + ) + # Determine provider from model name provider = self.get_bedrock_invoke_provider(model) - + # Transform to Bedrock modelInput format model_input = self._map_openai_to_bedrock_params( - openai_request_body=openai_body, - provider=provider + openai_request_body=openai_body, provider=provider ) - + # Create Bedrock batch record - record_id = _openai_jsonl_content.get("custom_id", f"CALL{str(idx).zfill(7)}") - bedrock_record = { - "recordId": record_id, - "modelInput": model_input - } - + record_id = _openai_jsonl_content.get( + "custom_id", f"CALL{str(idx).zfill(7)}" + ) + bedrock_record = {"recordId": record_id, "modelInput": model_input} + bedrock_jsonl_content.append(bedrock_record) return bedrock_jsonl_content @@ -353,10 +357,10 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig): raise ValueError("file is required") extracted_file_data = extract_file_data(file_data) extracted_file_data_content = extracted_file_data.get("content") - + if extracted_file_data_content is None: raise ValueError("file content is required") - + # Get and transform the file content if FilesAPIUtils.is_batch_jsonl_file( create_file_data=create_file_data, @@ -367,7 +371,9 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig): extracted_file_data_content ) openai_jsonl_content = [ - json.loads(line) for line in original_file_content.splitlines() if line.strip() + json.loads(line) + for line in original_file_content.splitlines() + if line.strip() ] bedrock_jsonl_content = ( self._transform_openai_jsonl_content_to_bedrock_jsonl_content( @@ -376,12 +382,12 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig): ) file_content = "\n".join(json.dumps(item) for item in bedrock_jsonl_content) elif isinstance(extracted_file_data_content, bytes): - file_content = extracted_file_data_content.decode('utf-8') + file_content = extracted_file_data_content.decode("utf-8") elif isinstance(extracted_file_data_content, str): file_content = extracted_file_data_content else: raise ValueError("Unsupported file content type") - + # Get the S3 URL for upload api_base = self.get_complete_file_url( api_base=None, @@ -391,7 +397,7 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig): litellm_params=litellm_params, data=create_file_data, ) - + # Sign the request and return a pre-signed request object signed_headers, signed_body = self._sign_s3_request( content=file_content, @@ -400,7 +406,7 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig): ) litellm_params["upload_url"] = api_base - + # Return a dict that tells the HTTP handler exactly what to do return { "method": "PUT", @@ -443,7 +449,7 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig): aws_web_identity_token=optional_params.get("aws_web_identity_token"), aws_sts_endpoint=optional_params.get("aws_sts_endpoint"), ) - + # Calculate SHA256 hash of the content (REQUIRED for S3) content_hash = hashlib.sha256(content.encode("utf-8")).hexdigest() @@ -466,33 +472,33 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig): data=prepped.body, headers=prepped.headers, ) - + # Get region name for non-LLM API calls (same as s3_v2.py) signing_region = self.get_aws_region_name_for_non_llm_api_calls( aws_region_name=aws_region_name ) - + SigV4Auth(credentials, "s3", signing_region).add_auth(aws_request) # Return signed headers and body signed_body = aws_request.body if isinstance(signed_body, bytes): - signed_body = signed_body.decode('utf-8') + signed_body = signed_body.decode("utf-8") elif signed_body is None: signed_body = content # Fallback to original content - + return dict(aws_request.headers), signed_body def _convert_https_url_to_s3_uri(self, https_url: str) -> tuple[str, str]: """ Convert HTTPS S3 URL to s3:// URI format. - + Args: https_url: HTTPS S3 URL (e.g., "https://s3.us-west-2.amazonaws.com/bucket/key") - + Returns: Tuple of (s3_uri, filename) - + Example: Input: "https://s3.us-west-2.amazonaws.com/litellm-proxy/file.jsonl" Output: ("s3://litellm-proxy/file.jsonl", "file.jsonl") @@ -502,13 +508,13 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig): # Match HTTPS S3 URL patterns # Pattern 1: https://s3.region.amazonaws.com/bucket/key # Pattern 2: https://bucket.s3.region.amazonaws.com/key - + pattern1 = r"https://s3\.([^.]+)\.amazonaws\.com/([^/]+)/(.+)" pattern2 = r"https://([^.]+)\.s3\.([^.]+)\.amazonaws\.com/(.+)" - + match1 = re.match(pattern1, https_url) match2 = re.match(pattern2, https_url) - + if match1: # Pattern: https://s3.region.amazonaws.com/bucket/key region, bucket, key = match1.groups() @@ -520,17 +526,18 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig): else: # Fallback: try to extract bucket and key from URL path from urllib.parse import urlparse + parsed = urlparse(https_url) - path_parts = parsed.path.lstrip('/').split('/', 1) + path_parts = parsed.path.lstrip("/").split("/", 1) if len(path_parts) >= 2: bucket, key = path_parts[0], path_parts[1] s3_uri = f"s3://{bucket}/{key}" else: raise ValueError(f"Unable to parse S3 URL: {https_url}") - + # Extract filename from key filename = key.split("/")[-1] if "/" in key else key - + return s3_uri, filename def transform_create_file_response( @@ -548,7 +555,7 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig): # Extract S3 object information from the response # S3 PUT object returns ETag and other metadata in headers content_length = response_headers.get("Content-Length", "0") - + # Use the actual upload URL that was used for the S3 upload upload_url = litellm_params.get("upload_url") file_id: str = "" @@ -628,7 +635,9 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig): optional_params: dict, litellm_params: dict, ) -> tuple[str, dict]: - raise NotImplementedError("BedrockFilesConfig does not support file content retrieval") + raise NotImplementedError( + "BedrockFilesConfig does not support file content retrieval" + ) def transform_file_content_response( self, @@ -636,7 +645,9 @@ class BedrockFilesConfig(BaseAWSLLM, BaseFilesConfig): logging_obj: LiteLLMLoggingObj, litellm_params: dict, ) -> HttpxBinaryResponseContent: - raise NotImplementedError("BedrockFilesConfig does not support file content retrieval") + raise NotImplementedError( + "BedrockFilesConfig does not support file content retrieval" + ) class BedrockJsonlFilesTransformation: @@ -680,7 +691,9 @@ class BedrockJsonlFilesTransformation: Delegate to the main BedrockFilesConfig transformation method """ config = BedrockFilesConfig() - return config._transform_openai_jsonl_content_to_bedrock_jsonl_content(openai_jsonl_content) + return config._transform_openai_jsonl_content_to_bedrock_jsonl_content( + openai_jsonl_content + ) def _get_s3_object_name( self, @@ -698,8 +711,6 @@ class BedrockJsonlFilesTransformation: object_name = f"litellm-bedrock-files-{_model}-{uuid.uuid4()}.jsonl" return object_name - - def _get_content_from_openai_file(self, openai_file_content: FileTypes) -> str: """ Helper to extract content from various OpenAI file types and return as string. @@ -746,10 +757,10 @@ class BedrockJsonlFilesTransformation: # S3 response typically contains ETag, key, etc. object_key = s3_upload_response.get("Key", "") bucket_name = s3_upload_response.get("Bucket", "") - + # Extract filename from object key filename = object_key.split("/")[-1] if "/" in object_key else object_key - + return OpenAIFileObject( purpose=create_file_data.get("purpose", "batch"), id=f"s3://{bucket_name}/{object_key}", diff --git a/litellm/llms/bedrock/image_edit/__init__.py b/litellm/llms/bedrock/image_edit/__init__.py index f3a0e61067d..ea6d13a676c 100644 --- a/litellm/llms/bedrock/image_edit/__init__.py +++ b/litellm/llms/bedrock/image_edit/__init__.py @@ -7,4 +7,3 @@ Handles image edit operations for Bedrock stability models. from .handler import BedrockImageEdit __all__ = ["BedrockImageEdit"] - diff --git a/litellm/llms/bedrock/image_edit/handler.py b/litellm/llms/bedrock/image_edit/handler.py index ef441fa5039..867944f8796 100644 --- a/litellm/llms/bedrock/image_edit/handler.py +++ b/litellm/llms/bedrock/image_edit/handler.py @@ -307,4 +307,3 @@ class BedrockImageEdit(BaseAWSLLM): ) return model_response - diff --git a/litellm/llms/bedrock/image_edit/stability_transformation.py b/litellm/llms/bedrock/image_edit/stability_transformation.py index db4e3a0a7a7..6a8b95e7e39 100644 --- a/litellm/llms/bedrock/image_edit/stability_transformation.py +++ b/litellm/llms/bedrock/image_edit/stability_transformation.py @@ -54,7 +54,7 @@ class BedrockStabilityImageEditConfig(BaseImageEditConfig): def _is_stability_edit_model(cls, model: Optional[str] = None) -> bool: """ Returns True if the model is a Bedrock Stability edit model. - + Bedrock Stability edit models follow this pattern: stability.stable-conservative-upscale-v1:0 stability.stable-creative-upscale-v1:0 @@ -66,25 +66,25 @@ class BedrockStabilityImageEditConfig(BaseImageEditConfig): """ if model: model_lower = model.lower() - if "stability." in model_lower and any([ - "upscale" in model_lower, - "outpaint" in model_lower, - "inpaint" in model_lower, - "erase" in model_lower, - "remove-background" in model_lower, - "search-recolor" in model_lower, - "search-replace" in model_lower, - "control-sketch" in model_lower, - "control-structure" in model_lower, - "style-guide" in model_lower, - "style-transfer" in model_lower, - ]): + if "stability." in model_lower and any( + [ + "upscale" in model_lower, + "outpaint" in model_lower, + "inpaint" in model_lower, + "erase" in model_lower, + "remove-background" in model_lower, + "search-recolor" in model_lower, + "search-replace" in model_lower, + "control-sketch" in model_lower, + "control-structure" in model_lower, + "style-guide" in model_lower, + "style-transfer" in model_lower, + ] + ): return True return False - def get_supported_openai_params( - self, model: str - ) -> list: + def get_supported_openai_params(self, model: str) -> list: """ Return list of OpenAI params supported by Bedrock Stability. """ @@ -149,7 +149,7 @@ class BedrockStabilityImageEditConfig(BaseImageEditConfig): return mapped_params - def transform_image_edit_request( #noqa: PLR0915 + def transform_image_edit_request( # noqa: PLR0915 self, model: str, prompt: Optional[str], @@ -167,27 +167,27 @@ class BedrockStabilityImageEditConfig(BaseImageEditConfig): data: Dict[str, Any] = { "output_format": "png", # Default to PNG } - + # Add prompt only if provided (some models don't require it) if prompt is not None and prompt != "": data["prompt"] = prompt - + # Convert image to base64 if provided if image is not None: image_b64: str - if hasattr(image, 'read') and callable(getattr(image, 'read', None)): + if hasattr(image, "read") and callable(getattr(image, "read", None)): # File-like object (e.g., BufferedReader from open()) image_bytes = image.read() # type: ignore - image_b64 = base64.b64encode(image_bytes).decode('utf-8') # type: ignore + image_b64 = base64.b64encode(image_bytes).decode("utf-8") # type: ignore elif isinstance(image, bytes): # Raw bytes - image_b64 = base64.b64encode(image).decode('utf-8') + image_b64 = base64.b64encode(image).decode("utf-8") elif isinstance(image, str): # Already a base64 string image_b64 = image else: # Try to handle as bytes - image_b64 = base64.b64encode(bytes(image)).decode('utf-8') # type: ignore + image_b64 = base64.b64encode(bytes(image)).decode("utf-8") # type: ignore # For style-transfer models, map image to init_image model_lower = model.lower() @@ -208,8 +208,10 @@ class BedrockStabilityImageEditConfig(BaseImageEditConfig): file_value = value if isinstance(value, list) and len(value) > 0: file_value = value[0] - - if hasattr(file_value, 'read') and callable(getattr(file_value, 'read', None)): + + if hasattr(file_value, "read") and callable( + getattr(file_value, "read", None) + ): file_bytes = file_value.read() # type: ignore elif isinstance(file_value, bytes): file_bytes = file_value @@ -219,14 +221,14 @@ class BedrockStabilityImageEditConfig(BaseImageEditConfig): continue else: file_bytes = file_value # type: ignore - + if isinstance(file_bytes, bytes): - file_b64 = base64.b64encode(file_bytes).decode('utf-8') + file_b64 = base64.b64encode(file_bytes).decode("utf-8") else: file_b64 = str(file_bytes) data[key] = file_b64 continue - + # Numeric fields that need to be converted to int/float numeric_int_fields = ["left", "right", "up", "down", "seed"] numeric_float_fields = [ @@ -239,7 +241,7 @@ class BedrockStabilityImageEditConfig(BaseImageEditConfig): "style_strength", "change_strength", ] - + if key in numeric_int_fields: # Convert to int (these are pixel values for outpaint) try: @@ -329,13 +331,15 @@ class BedrockStabilityImageEditConfig(BaseImageEditConfig): model_response._hidden_params = {} if "additional_headers" not in model_response._hidden_params: model_response._hidden_params["additional_headers"] = {} - + # Set cost based on model model_info = get_model_info(model, custom_llm_provider="bedrock") cost_per_image = model_info.get("output_cost_per_image", 0) if cost_per_image is not None: - model_response._hidden_params["additional_headers"]["llm_provider-x-litellm-response-cost"] = float(cost_per_image) - + model_response._hidden_params["additional_headers"][ + "llm_provider-x-litellm-response-cost" + ] = float(cost_per_image) + return model_response def use_multipart_form_data(self) -> bool: @@ -352,11 +356,11 @@ class BedrockStabilityImageEditConfig(BaseImageEditConfig): ) -> str: """ Get the complete URL for the Bedrock Image Edit API. - + For Bedrock, this is handled by the handler which constructs the endpoint URL based on the model ID and AWS region. This method is required by the base class but the actual URL construction happens in BedrockImageEdit.image_edit(). - + Returns a placeholder - the real endpoint is constructed in the handler. """ # Bedrock URLs are constructed in the handler using boto3 @@ -371,25 +375,25 @@ class BedrockStabilityImageEditConfig(BaseImageEditConfig): ) -> dict: """ Validate environment for Bedrock Stability image edit. - + For Bedrock, AWS credentials are managed by the BaseAWSLLM class. This method validates that headers are properly set up. - + Args: headers: The request headers to validate/update model: The model name being used api_key: Optional API key (not used for Bedrock, which uses AWS credentials) - + Returns: Updated headers dict """ if headers is None: headers = {} - + # Bedrock uses AWS credentials, not API keys # Headers are set up by the handler's get_request_headers() method # This just ensures basic headers are present if "Content-Type" not in headers: headers["Content-Type"] = "application/json" - + return headers diff --git a/litellm/llms/bedrock/image_generation/amazon_nova_canvas_transformation.py b/litellm/llms/bedrock/image_generation/amazon_nova_canvas_transformation.py index 18366999583..86c005bbfad 100644 --- a/litellm/llms/bedrock/image_generation/amazon_nova_canvas_transformation.py +++ b/litellm/llms/bedrock/image_generation/amazon_nova_canvas_transformation.py @@ -217,4 +217,4 @@ class AmazonNovaCanvasConfig: num_images: int = 0 if image_response.data: num_images = len(image_response.data) - return output_cost_per_image * num_images \ No newline at end of file + return output_cost_per_image * num_images diff --git a/litellm/llms/bedrock/image_generation/amazon_stability1_transformation.py b/litellm/llms/bedrock/image_generation/amazon_stability1_transformation.py index 07f82cec232..1d88aaf35f7 100644 --- a/litellm/llms/bedrock/image_generation/amazon_stability1_transformation.py +++ b/litellm/llms/bedrock/image_generation/amazon_stability1_transformation.py @@ -115,7 +115,7 @@ class AmazonStabilityConfig: return { "text_prompts": [{"text": prompt, "weight": 1}], - **inference_params, + **inference_params, } @classmethod @@ -161,4 +161,4 @@ class AmazonStabilityConfig: num_images: int = 0 if image_response.data: num_images = len(image_response.data) - return output_cost_per_image * num_images \ No newline at end of file + return output_cost_per_image * num_images diff --git a/litellm/llms/bedrock/image_generation/amazon_stability3_transformation.py b/litellm/llms/bedrock/image_generation/amazon_stability3_transformation.py index 160d0af8e80..8aff24fe9a7 100644 --- a/litellm/llms/bedrock/image_generation/amazon_stability3_transformation.py +++ b/litellm/llms/bedrock/image_generation/amazon_stability3_transformation.py @@ -109,11 +109,11 @@ class AmazonStability3Config: @classmethod def cost_calculator( - cls, - model: str, - image_response: ImageResponse, - size: Optional[str] = None, - optional_params: Optional[dict] = None, + cls, + model: str, + image_response: ImageResponse, + size: Optional[str] = None, + optional_params: Optional[dict] = None, ) -> float: get_model_info = get_cached_model_info() model_info = get_model_info( diff --git a/litellm/llms/bedrock/image_generation/image_handler.py b/litellm/llms/bedrock/image_generation/image_handler.py index 7270b96ab88..d6053278cbd 100644 --- a/litellm/llms/bedrock/image_generation/image_handler.py +++ b/litellm/llms/bedrock/image_generation/image_handler.py @@ -180,12 +180,12 @@ class BedrockImageGeneration(BaseAWSLLM): headers = {} guardrail_identifier = optional_params.pop("guardrailIdentifier", None) guardrail_version = optional_params.pop("guardrailVersion", None) - + if guardrail_identifier is not None: headers["x-amz-bedrock-guardrail-identifier"] = guardrail_identifier if guardrail_version is not None: headers["x-amz-bedrock-guardrail-version"] = guardrail_version - + return headers def _prepare_request( @@ -292,7 +292,9 @@ class BedrockImageGeneration(BaseAWSLLM): dict: The request body to use for the Bedrock Image Generation API """ config_class = self.get_config_class(model=model) - request_body = config_class.transform_request_body(text=prompt, optional_params=optional_params) + request_body = config_class.transform_request_body( + text=prompt, optional_params=optional_params + ) return dict(request_body) def _transform_response_dict_to_openai_response( 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 b11215e7f6b..e31820d7631 100644 --- a/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py +++ b/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py @@ -276,7 +276,7 @@ class AmazonAnthropicClaudeMessagesConfig( "opus_4.6", "opus-4-6", "opus_4_6", - #sonnet 4.6 + # sonnet 4.6 "sonnet-4.6", "sonnet_4.6", "sonnet-4-6", @@ -462,7 +462,7 @@ class AmazonAnthropicClaudeMessagesConfig( if "tool-search-tool-2025-10-19" in beta_set: beta_set.add("tool-examples-2025-10-29") - + if beta_set: anthropic_messages_request["anthropic_beta"] = list(beta_set) diff --git a/litellm/llms/bedrock/passthrough/transformation.py b/litellm/llms/bedrock/passthrough/transformation.py index 5efd3ba1d9f..274b0282acc 100644 --- a/litellm/llms/bedrock/passthrough/transformation.py +++ b/litellm/llms/bedrock/passthrough/transformation.py @@ -27,28 +27,30 @@ class BedrockPassthroughConfig( def _encode_model_id_for_endpoint(self, model_id: str) -> str: """ Encode model_id (especially ARNs) for use in Bedrock endpoints. - + ARNs contain special characters like colons and slashes that need to be properly URL-encoded when used in HTTP request paths. For example: arn:aws:bedrock:us-east-1:123:application-inference-profile/abc123 becomes: arn:aws:bedrock:us-east-1:123:application-inference-profile%2Fabc123 - + Args: model_id: The model ID or ARN to encode - + Returns: The encoded model_id suitable for use in endpoint URLs """ from litellm.passthrough.utils import CommonUtils import re - + # Create a temporary endpoint with the model_id to check if encoding is needed temp_endpoint = f"/model/{model_id}/converse" - encoded_temp_endpoint = CommonUtils.encode_bedrock_runtime_modelid_arn(temp_endpoint) - + encoded_temp_endpoint = CommonUtils.encode_bedrock_runtime_modelid_arn( + temp_endpoint + ) + # Extract the encoded model_id from the temporary endpoint - encoded_model_id_match = re.search(r'/model/([^/]+)/', encoded_temp_endpoint) + encoded_model_id_match = re.search(r"/model/([^/]+)/", encoded_temp_endpoint) if encoded_model_id_match: return encoded_model_id_match.group(1) else: @@ -73,7 +75,9 @@ class BedrockPassthroughConfig( model_id=model_id, ) - aws_bedrock_runtime_endpoint = optional_params.get("aws_bedrock_runtime_endpoint") + aws_bedrock_runtime_endpoint = optional_params.get( + "aws_bedrock_runtime_endpoint" + ) endpoint_url, _ = self.get_runtime_endpoint( api_base=api_base, aws_bedrock_runtime_endpoint=aws_bedrock_runtime_endpoint, @@ -85,13 +89,16 @@ class BedrockPassthroughConfig( # instead of the translated model name if model_id is not None: import re - + # Encode the model_id if it's an ARN to properly handle special characters encoded_model_id = self._encode_model_id_for_endpoint(model_id) - + # Replace the model name in the endpoint with the encoded model_id - endpoint = re.sub(r'model/[^/]+/', f'model/{encoded_model_id}/', endpoint) - return self.format_url(endpoint, endpoint_url, request_query_params or {}), endpoint_url + endpoint = re.sub(r"model/[^/]+/", f"model/{encoded_model_id}/", endpoint) + return ( + self.format_url(endpoint, endpoint_url, request_query_params or {}), + endpoint_url, + ) def sign_request( self, diff --git a/litellm/llms/bedrock/realtime/handler.py b/litellm/llms/bedrock/realtime/handler.py index 9b6a80f4a2f..cde9f3e6fce 100644 --- a/litellm/llms/bedrock/realtime/handler.py +++ b/litellm/llms/bedrock/realtime/handler.py @@ -97,8 +97,10 @@ class BedrockRealtime(BaseAWSLLM): try: # Initialize the bidirectional stream - bedrock_stream = await bedrock_client.invoke_model_with_bidirectional_stream( - InvokeModelWithBidirectionalStreamOperationInput(model_id=model) + bedrock_stream = ( + await bedrock_client.invoke_model_with_bidirectional_stream( + InvokeModelWithBidirectionalStreamOperationInput(model_id=model) + ) ) verbose_proxy_logger.debug( @@ -232,7 +234,7 @@ class BedrockRealtime(BaseAWSLLM): # 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" @@ -251,13 +253,11 @@ class BedrockRealtime(BaseAWSLLM): ), } - transformed_response = ( - transformation_config.transform_realtime_response( - message=bedrock_response, - model=model, - logging_obj=logging_obj, - realtime_response_transform_input=realtime_response_transform_input, - ) + 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 diff --git a/litellm/llms/bedrock/realtime/transformation.py b/litellm/llms/bedrock/realtime/transformation.py index 1dde1b47fe3..13d5bf35466 100644 --- a/litellm/llms/bedrock/realtime/transformation.py +++ b/litellm/llms/bedrock/realtime/transformation.py @@ -43,13 +43,13 @@ class BedrockRealtimeConfig(BaseRealtimeConfig): 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 @@ -58,7 +58,7 @@ class BedrockRealtimeConfig(BaseRealtimeConfig): 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 @@ -66,7 +66,7 @@ class BedrockRealtimeConfig(BaseRealtimeConfig): self.input_encoding = "base64" self.input_audio_type = "SPEECH" self.input_media_type = "audio/lpcm" - + # Text configuration self.text_media_type = "text/plain" @@ -86,7 +86,9 @@ class BedrockRealtimeConfig(BaseRealtimeConfig): """Bedrock requires session configuration.""" return True - def session_configuration_request(self, model: str, tools: Optional[List[dict]] = None) -> str: + def session_configuration_request( + self, model: str, tools: Optional[List[dict]] = None + ) -> str: """ Create initial session configuration for Bedrock Nova Sonic. @@ -158,20 +160,22 @@ class BedrockRealtimeConfig(BaseRealtimeConfig): "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: + 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 """ @@ -195,15 +199,15 @@ class BedrockRealtimeConfig(BaseRealtimeConfig): """ 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"] @@ -212,14 +216,14 @@ class BedrockRealtimeConfig(BaseRealtimeConfig): 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"] @@ -313,7 +317,9 @@ class BedrockRealtimeConfig(BaseRealtimeConfig): return messages - def transform_input_audio_buffer_append_event(self, json_message: dict) -> List[str]: + def transform_input_audio_buffer_append_event( + self, json_message: dict + ) -> List[str]: """ Transform input_audio_buffer.append event to Bedrock audio input. @@ -365,7 +371,9 @@ class BedrockRealtimeConfig(BaseRealtimeConfig): return messages - def transform_input_audio_buffer_commit_event(self, json_message: dict) -> List[str]: + def transform_input_audio_buffer_commit_event( + self, json_message: dict + ) -> List[str]: """ Transform input_audio_buffer.commit event to Bedrock audio content end. @@ -410,7 +418,9 @@ class BedrockRealtimeConfig(BaseRealtimeConfig): # Handle tool result if item_type == "function_call_output": - return self.transform_conversation_item_create_tool_result_event(json_message) + return self.transform_conversation_item_create_tool_result_event( + json_message + ) # Handle regular message if item_type == "message": @@ -549,14 +559,14 @@ class BedrockRealtimeConfig(BaseRealtimeConfig): 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, @@ -592,7 +602,13 @@ class BedrockRealtimeConfig(BaseRealtimeConfig): role = content_start.get("role") if role != "ASSISTANT": - return [], current_response_id, current_output_item_id, current_conversation_id, None + return ( + [], + current_response_id, + current_output_item_id, + current_conversation_id, + None, + ) verbose_logger.debug("Handling ASSISTANT contentStart") @@ -606,7 +622,9 @@ class BedrockRealtimeConfig(BaseRealtimeConfig): # Determine content type content_type = content_start.get("type", "TEXT") - current_delta_type: ALL_DELTA_TYPES = "text" if content_type == "TEXT" else "audio" + current_delta_type: ALL_DELTA_TYPES = ( + "text" if content_type == "TEXT" else "audio" + ) returned_messages: List[OpenAIRealtimeEvents] = [] @@ -850,7 +868,12 @@ class BedrockRealtimeConfig(BaseRealtimeConfig): event: dict, current_response_id: Optional[str], current_conversation_id: Optional[str], - ) -> tuple[List[OpenAIRealtimeEvents], Optional[str], Optional[str], Optional[ALL_DELTA_TYPES]]: + ) -> tuple[ + List[OpenAIRealtimeEvents], + Optional[str], + Optional[str], + Optional[ALL_DELTA_TYPES], + ]: """ Transform Bedrock promptEnd event to OpenAI response.done. @@ -915,7 +938,11 @@ class BedrockRealtimeConfig(BaseRealtimeConfig): 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"] + tool_input = ( + json.loads(tool_use["input"]) + if isinstance(tool_use["input"], str) + else tool_use["input"] + ) except json.JSONDecodeError: tool_input = {} @@ -925,6 +952,7 @@ class BedrockRealtimeConfig(BaseRealtimeConfig): # 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()}", @@ -936,9 +964,15 @@ class BedrockRealtimeConfig(BaseRealtimeConfig): "arguments": json.dumps(tool_input), } - return [cast(OpenAIRealtimeEvents, function_call_event)], tool_call_id, tool_name + 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]: + def transform_conversation_item_create_tool_result_event( + self, json_message: dict + ) -> List[str]: """ Transform conversation.item.create with tool result to Bedrock format. @@ -969,10 +1003,8 @@ class BedrockRealtimeConfig(BaseRealtimeConfig): "toolResultInputConfiguration": { "toolUseId": call_id, "type": "TEXT", - "textInputConfiguration": { - "mediaType": "text/plain" - } - } + "textInputConfiguration": {"mediaType": "text/plain"}, + }, } } } @@ -984,7 +1016,9 @@ class BedrockRealtimeConfig(BaseRealtimeConfig): "toolResult": { "promptName": self.prompt_name, "contentName": tool_content_name, - "content": output if isinstance(output, str) else json.dumps(output) + "content": output + if isinstance(output, str) + else json.dumps(output), } } } @@ -1025,7 +1059,11 @@ class BedrockRealtimeConfig(BaseRealtimeConfig): 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] + 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": [], diff --git a/litellm/llms/bedrock/rerank/handler.py b/litellm/llms/bedrock/rerank/handler.py index 37167e7c330..812ca116c27 100644 --- a/litellm/llms/bedrock/rerank/handler.py +++ b/litellm/llms/bedrock/rerank/handler.py @@ -35,7 +35,12 @@ class BedrockRerankHandler(BaseAWSLLM): if client is None: client = get_async_httpx_client(llm_provider=litellm.LlmProviders.BEDROCK) try: - response = await client.post(url=prepared_request["endpoint_url"], headers=dict(prepared_request["prepped"].headers), data=prepared_request["body"], timeout=timeout) + response = await client.post( + url=prepared_request["endpoint_url"], + headers=dict(prepared_request["prepped"].headers), + data=prepared_request["body"], + timeout=timeout, + ) response.raise_for_status() except httpx.HTTPStatusError as err: error_code = err.response.status_code @@ -96,7 +101,12 @@ class BedrockRerankHandler(BaseAWSLLM): if client is None or not isinstance(client, HTTPHandler): client = _get_httpx_client() try: - response = client.post(url=prepared_request["endpoint_url"], headers=dict(prepared_request["prepped"].headers), data=prepared_request["body"], timeout=timeout) + response = client.post( + url=prepared_request["endpoint_url"], + headers=dict(prepared_request["prepped"].headers), + data=prepared_request["body"], + timeout=timeout, + ) response.raise_for_status() except httpx.HTTPStatusError as err: error_code = err.response.status_code diff --git a/litellm/llms/bedrock/vector_stores/transformation.py b/litellm/llms/bedrock/vector_stores/transformation.py index 72e1e1470d3..4da0a7c7791 100644 --- a/litellm/llms/bedrock/vector_stores/transformation.py +++ b/litellm/llms/bedrock/vector_stores/transformation.py @@ -152,7 +152,6 @@ class BedrockVectorStoreConfig(BaseVectorStoreConfig, BaseAWSLLM): if param == "max_num_results": optional_params["numberOfResults"] = value elif param == "filters" and value is not None: - # map the openai filters to the aws kb filters format # openai filters = {"key": , "value": , "operator": } OR {"and" | "or": [{"key": , "value": , "operator": }]} # aws kb filters = {"operator": {"": }} OR {"andAll | orAll": [{"operator": {"": }}]} diff --git a/litellm/llms/black_forest_labs/image_edit/handler.py b/litellm/llms/black_forest_labs/image_edit/handler.py index 44a102ec48d..dea2683a049 100644 --- a/litellm/llms/black_forest_labs/image_edit/handler.py +++ b/litellm/llms/black_forest_labs/image_edit/handler.py @@ -356,7 +356,12 @@ class BlackForestLabsImageEdit: if status == "Ready": return response - elif status in ["Error", "Failed", "Content Moderated", "Request Moderated"]: + elif status in [ + "Error", + "Failed", + "Content Moderated", + "Request Moderated", + ]: raise BlackForestLabsError( status_code=400, message=f"Image generation failed: {status}", @@ -436,7 +441,12 @@ class BlackForestLabsImageEdit: if status == "Ready": return response - elif status in ["Error", "Failed", "Content Moderated", "Request Moderated"]: + elif status in [ + "Error", + "Failed", + "Content Moderated", + "Request Moderated", + ]: raise BlackForestLabsError( status_code=400, message=f"Image generation failed: {status}", diff --git a/litellm/llms/black_forest_labs/image_edit/transformation.py b/litellm/llms/black_forest_labs/image_edit/transformation.py index 78898345bf6..63413787c0d 100644 --- a/litellm/llms/black_forest_labs/image_edit/transformation.py +++ b/litellm/llms/black_forest_labs/image_edit/transformation.py @@ -14,6 +14,7 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import httpx from httpx._types import RequestFiles +from litellm.constants import DEFAULT_MAX_RECURSE_DEPTH from litellm.llms.base_llm.image_edit.transformation import BaseImageEditConfig from litellm.secret_managers.main import get_secret_str from litellm.types.images.main import ImageEditOptionalRequestParams @@ -179,23 +180,28 @@ class BlackForestLabsImageEditConfig(BaseImageEditConfig): """ Get the complete URL for the Black Forest Labs API request. """ - base_url: str = ( - api_base - or get_secret_str("BFL_API_BASE") - or DEFAULT_API_BASE - ) + base_url: str = api_base or get_secret_str("BFL_API_BASE") or DEFAULT_API_BASE base_url = base_url.rstrip("/") endpoint = self._get_model_endpoint(model) return f"{base_url}{endpoint}" - def _read_image_bytes(self, image: Any) -> bytes: + def _read_image_bytes( + self, + image: Any, + depth: int = 0, + max_depth: int = DEFAULT_MAX_RECURSE_DEPTH, + ) -> bytes: """Read image bytes from various input types.""" + if depth > max_depth: + raise ValueError( + f"Max recursion depth {max_depth} reached while reading image bytes for Black Forest Labs image edit." + ) if isinstance(image, bytes): return image elif isinstance(image, list): # If it's a list, take the first image - return self._read_image_bytes(image[0]) + return self._read_image_bytes(image[0], depth=depth + 1, max_depth=max_depth) elif isinstance(image, str): if image.startswith(("http://", "https://")): # Download image from URL @@ -224,8 +230,8 @@ class BlackForestLabsImageEditConfig(BaseImageEditConfig): def transform_image_edit_request( self, model: str, - prompt: str, - image: FileTypes, + prompt: Optional[str], + image: Optional[FileTypes], image_edit_optional_request_params: Dict, litellm_params: GenericLiteLLMParams, headers: dict, @@ -247,9 +253,18 @@ class BlackForestLabsImageEditConfig(BaseImageEditConfig): # Add optional params (only BFL-recognized parameters) bfl_request_params = [ - "seed", "output_format", "safety_tolerance", "prompt_upsampling", - "aspect_ratio", "steps", "guidance", "grow_mask", - "top", "bottom", "left", "right", + "seed", + "output_format", + "safety_tolerance", + "prompt_upsampling", + "aspect_ratio", + "steps", + "guidance", + "grow_mask", + "top", + "bottom", + "left", + "right", ] for key, value in image_edit_optional_request_params.items(): if key in bfl_request_params and value is not None: diff --git a/litellm/llms/black_forest_labs/image_generation/handler.py b/litellm/llms/black_forest_labs/image_generation/handler.py index 99dc2feca3c..5a1d885e527 100644 --- a/litellm/llms/black_forest_labs/image_generation/handler.py +++ b/litellm/llms/black_forest_labs/image_generation/handler.py @@ -342,7 +342,12 @@ class BlackForestLabsImageGeneration: if status == "Ready": return response - elif status in ["Error", "Failed", "Content Moderated", "Request Moderated"]: + elif status in [ + "Error", + "Failed", + "Content Moderated", + "Request Moderated", + ]: raise BlackForestLabsError( status_code=400, message=f"Image generation failed: {status}", @@ -422,7 +427,12 @@ class BlackForestLabsImageGeneration: if status == "Ready": return response - elif status in ["Error", "Failed", "Content Moderated", "Request Moderated"]: + elif status in [ + "Error", + "Failed", + "Content Moderated", + "Request Moderated", + ]: raise BlackForestLabsError( status_code=400, message=f"Image generation failed: {status}", diff --git a/litellm/llms/black_forest_labs/image_generation/transformation.py b/litellm/llms/black_forest_labs/image_generation/transformation.py index fd664b3ea7e..18c7c173300 100644 --- a/litellm/llms/black_forest_labs/image_generation/transformation.py +++ b/litellm/llms/black_forest_labs/image_generation/transformation.py @@ -203,9 +203,7 @@ class BlackForestLabsImageGenerationConfig(BaseImageGenerationConfig): """ Get the complete URL for the Black Forest Labs API request. """ - base_url: str = ( - api_base or get_secret_str("BFL_API_BASE") or DEFAULT_API_BASE - ) + base_url: str = api_base or get_secret_str("BFL_API_BASE") or DEFAULT_API_BASE base_url = base_url.rstrip("/") endpoint = self._get_model_endpoint(model) @@ -261,7 +259,12 @@ class BlackForestLabsImageGenerationConfig(BaseImageGenerationConfig): raw_response: httpx.Response, model_response: ImageResponse, logging_obj: LiteLLMLoggingObj, - **kwargs, + request_data: dict, + optional_params: dict, + litellm_params: dict, + encoding: Any, + api_key: Optional[str] = None, + json_mode: Optional[bool] = None, ) -> ImageResponse: """ Transform Black Forest Labs response to OpenAI-compatible ImageResponse. diff --git a/litellm/llms/brave/search/transformation.py b/litellm/llms/brave/search/transformation.py index a73029b0409..9dfcd6bc75a 100644 --- a/litellm/llms/brave/search/transformation.py +++ b/litellm/llms/brave/search/transformation.py @@ -5,7 +5,7 @@ Documentation: https://api-dashboard.search.brave.com/app/documentation/web-sear from __future__ import annotations from datetime import datetime, timezone -from dateutil import parser +from dateutil import parser # type: ignore[import-untyped] from typing import Dict, List, Literal, Optional, TypedDict, Union import httpx import re diff --git a/litellm/llms/bytez/chat/transformation.py b/litellm/llms/bytez/chat/transformation.py index ccd3c216458..a72f732a303 100644 --- a/litellm/llms/bytez/chat/transformation.py +++ b/litellm/llms/bytez/chat/transformation.py @@ -91,13 +91,11 @@ class BytezChatConfig(BaseConfig): model: str, drop_params: bool, ) -> dict: - adapted_params = {} all_params = {**non_default_params, **optional_params} for key, value in all_params.items(): - alias = self.openai_to_bytez_param_map.get(key) if alias is False: @@ -124,7 +122,6 @@ class BytezChatConfig(BaseConfig): api_key: Optional[str] = None, api_base: Optional[str] = None, ) -> dict: - headers.update( { "content-type": "application/json", @@ -141,7 +138,6 @@ class BytezChatConfig(BaseConfig): if not api_key: raise Exception("Missing api_key, make sure you pass in your api key") - return headers def get_complete_url( @@ -193,7 +189,6 @@ class BytezChatConfig(BaseConfig): api_key: Optional[str] = None, json_mode: Optional[bool] = None, ) -> ModelResponse: - json = raw_response.json() # noqa: F811 error = json.get("error") @@ -387,13 +382,11 @@ open_ai_to_bytez_content_item_map = { def adapt_messages_to_bytez_standard(messages: List[Dict]): - messages = _adapt_string_only_content_to_lists(messages) new_messages = [] for message in messages: - role = message["role"] content: list = message["content"] @@ -433,7 +426,6 @@ def _adapt_string_only_content_to_lists(messages: List[Dict]): new_messages = [] for message in messages: - role = message.get("role") content = message.get("content") @@ -446,7 +438,6 @@ def _adapt_string_only_content_to_lists(messages: List[Dict]): new_content.append(content) elif isinstance(content, list): - new_content_items = [] for content_item in content: if isinstance(content_item, str): diff --git a/litellm/llms/bytez/common_utils.py b/litellm/llms/bytez/common_utils.py index 2fedd2aad03..d6593a06b71 100644 --- a/litellm/llms/bytez/common_utils.py +++ b/litellm/llms/bytez/common_utils.py @@ -22,4 +22,4 @@ class BytezError(BaseLLMException): status_code=status_code, message=message, headers=headers, - ) \ No newline at end of file + ) diff --git a/litellm/llms/chatgpt/authenticator.py b/litellm/llms/chatgpt/authenticator.py index ff053730c35..e35b04a3fb3 100644 --- a/litellm/llms/chatgpt/authenticator.py +++ b/litellm/llms/chatgpt/authenticator.py @@ -206,7 +206,9 @@ class Authenticator: "interval": str(interval or "5"), } - def _poll_for_authorization_code(self, device_code: Dict[str, str]) -> Dict[str, str]: + def _poll_for_authorization_code( + self, device_code: Dict[str, str] + ) -> Dict[str, str]: client = _get_httpx_client() interval = int(device_code.get("interval", "5")) start_time = time.time() @@ -284,7 +286,9 @@ class Authenticator: status_code=400, ) - if not all(key in data for key in ("access_token", "refresh_token", "id_token")): + if not all( + key in data for key in ("access_token", "refresh_token", "id_token") + ): raise GetAccessTokenError( message=f"Token exchange response missing fields: {data}", status_code=400, @@ -377,11 +381,11 @@ class Authenticator: auth_data = self._read_auth_file() if auth_data: access_token = auth_data.get("access_token") - if access_token and not self._is_token_expired( - auth_data, access_token - ): + if access_token and not self._is_token_expired(auth_data, access_token): return access_token - sleep_for = min(DEVICE_CODE_POLL_SLEEP_SECONDS, max(0.0, deadline - time.time())) + sleep_for = min( + DEVICE_CODE_POLL_SLEEP_SECONDS, max(0.0, deadline - time.time()) + ) if sleep_for <= 0: break time.sleep(sleep_for) diff --git a/litellm/llms/chatgpt/chat/streaming_utils.py b/litellm/llms/chatgpt/chat/streaming_utils.py index 3232b452a37..e9cf2d15c20 100644 --- a/litellm/llms/chatgpt/chat/streaming_utils.py +++ b/litellm/llms/chatgpt/chat/streaming_utils.py @@ -24,7 +24,9 @@ class ChatGPTToolCallNormalizer: self._stream = stream self._seen_ids: Dict[str, int] = {} # tool_call_id -> assigned_index self._next_index: int = 0 - self._last_id: Optional[str] = None # tracks which tool call the next delta belongs to + self._last_id: Optional[ + str + ] = None # tracks which tool call the next delta belongs to def __getattr__(self, name: str) -> Any: return getattr(self._stream, name) diff --git a/litellm/llms/chatgpt/common_utils.py b/litellm/llms/chatgpt/common_utils.py index d80487cde24..9cbcd6a4f46 100644 --- a/litellm/llms/chatgpt/common_utils.py +++ b/litellm/llms/chatgpt/common_utils.py @@ -145,9 +145,7 @@ def _safe_header_value(value: str) -> str: def _sanitize_user_agent_token(value: str) -> str: if not value: return "" - return "".join( - ch if (ch.isalnum() or ch in "-_./") else "_" for ch in value - ) + return "".join(ch if (ch.isalnum() or ch in "-_./") else "_" for ch in value) def _terminal_user_agent() -> str: @@ -159,9 +157,7 @@ def _terminal_user_agent() -> str: wezterm_version = os.getenv("WEZTERM_VERSION") if wezterm_version is not None: - token = ( - f"WezTerm/{wezterm_version}" if wezterm_version else "WezTerm" - ) + token = f"WezTerm/{wezterm_version}" if wezterm_version else "WezTerm" return _sanitize_user_agent_token(token) or "WezTerm" if ( @@ -182,9 +178,7 @@ def _terminal_user_agent() -> str: konsole_version = os.getenv("KONSOLE_VERSION") if konsole_version is not None: - token = ( - f"Konsole/{konsole_version}" if konsole_version else "Konsole" - ) + token = f"Konsole/{konsole_version}" if konsole_version else "Konsole" return _sanitize_user_agent_token(token) or "Konsole" if os.getenv("GNOME_TERMINAL_SCREEN"): diff --git a/litellm/llms/chatgpt/responses/transformation.py b/litellm/llms/chatgpt/responses/transformation.py index 66acd933416..3c59ca16581 100644 --- a/litellm/llms/chatgpt/responses/transformation.py +++ b/litellm/llms/chatgpt/responses/transformation.py @@ -77,9 +77,9 @@ class ChatGPTResponsesAPIConfig(OpenAIResponsesAPIConfig): existing_instructions = request.get("instructions") if existing_instructions: if base_instructions not in existing_instructions: - request["instructions"] = ( - f"{base_instructions}\n\n{existing_instructions}" - ) + request[ + "instructions" + ] = f"{base_instructions}\n\n{existing_instructions}" else: request["instructions"] = base_instructions request["store"] = False diff --git a/litellm/llms/clarifai/chat/transformation.py b/litellm/llms/clarifai/chat/transformation.py index 48884ff0139..d07f6eba057 100644 --- a/litellm/llms/clarifai/chat/transformation.py +++ b/litellm/llms/clarifai/chat/transformation.py @@ -25,6 +25,7 @@ class ClarifaiConfig(OpenAIGPTConfig): Configuration class for Clarifai chat completions. Since Clarifai is OpenAI-compatible, we extend OpenAIGPTConfig. """ + def get_supported_openai_params(self, model: str) -> list: """ Get the supported OpenAI params for the given model @@ -42,18 +43,15 @@ class ClarifaiConfig(OpenAIGPTConfig): "frequency_penalty", "stream_options", ] - + @staticmethod def get_api_key(api_key: Optional[str] = None) -> Optional[str]: - return ( - api_key - or get_secret_str("CLARIFAI_API_KEY") - ) - + return api_key or get_secret_str("CLARIFAI_API_KEY") + @staticmethod def get_api_base(api_base: Optional[str] = None) -> Optional[str]: return api_base or "https://api.clarifai.com/v2/ext/openai/v1" - + @staticmethod def get_base_model(model: Optional[str] = None) -> Optional[str]: if model: @@ -72,11 +70,15 @@ class ClarifaiConfig(OpenAIGPTConfig): api_base = api_base or "https://api.clarifai.com/v2/ext/openai/v1" dynamic_api_key = api_key or get_secret_str("CLARIFAI_API_KEY") or "" return api_base, dynamic_api_key - - def transform_request(self, model, messages, optional_params, litellm_params, headers): + + def transform_request( + self, model, messages, optional_params, litellm_params, headers + ): model = self.get_base_model(model) or model - return super().transform_request(model, messages, optional_params, litellm_params, headers) - + return super().transform_request( + model, messages, optional_params, litellm_params, headers + ) + def transform_response( self, model: str, @@ -95,7 +97,7 @@ class ClarifaiConfig(OpenAIGPTConfig): Transform the Clarifai response to a standard ModelResponse. Since Clarifai is OpenAI-compatible, we use OpenAI response transformation. """ - ## Logging + ## Logging logging_obj.post_call( input=messages, api_key=api_key, @@ -111,9 +113,9 @@ class ClarifaiConfig(OpenAIGPTConfig): message=f"Failed to parse Clarifai response: {str(e)}", headers=raw_response.headers, ) from e - + response = ModelResponse(**completion_response) - + if response.model is not None: response.model = "clarifai/" + model @@ -130,4 +132,4 @@ class ClarifaiConfig(OpenAIGPTConfig): status_code=status_code, message=error_message, headers=headers, - ) \ No newline at end of file + ) diff --git a/litellm/llms/cohere/chat/v2_transformation.py b/litellm/llms/cohere/chat/v2_transformation.py index 8f6dde1967c..190491adfc7 100644 --- a/litellm/llms/cohere/chat/v2_transformation.py +++ b/litellm/llms/cohere/chat/v2_transformation.py @@ -7,7 +7,7 @@ import litellm from litellm.llms.base_llm.chat.transformation import BaseLLMException from litellm.types.llms.cohere import CohereV2ChatResponse from litellm.types.llms.openai import ( - AllMessageValues, + AllMessageValues, ChatCompletionToolCallChunk, ChatCompletionAnnotation, ChatCompletionAnnotationURLCitation, @@ -172,8 +172,10 @@ class CohereV2ChatConfig(OpenAIGPTConfig): """ Cohere v2 chat api is in openai format, so we can use the openai transform request function to transform the request. """ - data = super().transform_request(model, messages, optional_params, litellm_params, headers) - + data = super().transform_request( + model, messages, optional_params, litellm_params, headers + ) + return data def transform_response( @@ -215,10 +217,13 @@ class CohereV2ChatConfig(OpenAIGPTConfig): ## ADD CITATIONS AS ANNOTATIONS annotations: Optional[List[ChatCompletionAnnotation]] = None citations = None - - if "message" in cohere_v2_chat_response and "citations" in cohere_v2_chat_response["message"]: + + if ( + "message" in cohere_v2_chat_response + and "citations" in cohere_v2_chat_response["message"] + ): citations = cohere_v2_chat_response["message"]["citations"] - + if citations: annotations = self._translate_citations_to_openai_annotations(citations) @@ -293,13 +298,15 @@ class CohereV2ChatConfig(OpenAIGPTConfig): ) -> BaseLLMException: return CohereError(status_code=status_code, message=error_message) - def _translate_citations_to_openai_annotations(self, citations: List[dict]) -> List[ChatCompletionAnnotation]: + def _translate_citations_to_openai_annotations( + self, citations: List[dict] + ) -> List[ChatCompletionAnnotation]: """ Transform Cohere citations to OpenAI annotations format. - + Creates separate annotations for each source in a citation, allowing multiple annotations with the same start/end index if they reference different sources. - + Args: citations: List of Cohere citation objects with format: { @@ -318,40 +325,40 @@ class CohereV2ChatConfig(OpenAIGPTConfig): } ] } - + Returns: List of OpenAI ChatCompletionAnnotation objects (one per source) """ annotations: List[ChatCompletionAnnotation] = [] - + for citation in citations: start_index = citation.get("start", 0) end_index = citation.get("end", 0) - + # Extract source information - loop through all sources sources = citation.get("sources", []) if not sources: continue - + # Create an annotation for each source for source in sources: if source.get("type") == "document" and "document" in source: document = source["document"] title = document.get("title", "") url = source.get("url") or f"source:{source.get('id', 'unknown')}" - + url_citation: ChatCompletionAnnotationURLCitation = { "start_index": start_index, "end_index": end_index, "title": title, "url": url, } - + annotation: ChatCompletionAnnotation = { "type": "url_citation", "url_citation": url_citation, } - + annotations.append(annotation) - - return annotations \ No newline at end of file + + return annotations diff --git a/litellm/llms/cohere/common_utils.py b/litellm/llms/cohere/common_utils.py index 333916fffa3..05e3cec5444 100644 --- a/litellm/llms/cohere/common_utils.py +++ b/litellm/llms/cohere/common_utils.py @@ -66,25 +66,26 @@ class CohereModelInfo(BaseLLMModelInfo): This function will return `anthropic.claude-3-opus-20240229-v1:0` """ pass - + @staticmethod def get_cohere_route(model: str) -> Literal["v1", "v2"]: """ Get the Cohere route for the given model. - + Args: model: The model name (e.g., "cohere_chat/v2/command-r-plus", "command-r-plus") - + Returns: "v2" for standard Cohere v2 API (default), "v1" for Cohere v1 API """ # Check for explicit v1 route if "v1/" in model: return "v1" - + # Default to v2 for all other cases return "v2" + def validate_environment( headers: dict, model: str, @@ -216,9 +217,10 @@ class ModelResponseIterator: except ValueError as e: raise RuntimeError(f"Error parsing chunk: {e},\nReceived chunk: {chunk}") + class CohereV2ModelResponseIterator: """V2-specific response iterator for Cohere streaming""" - + def __init__( self, streaming_response, sync_stream: bool, json_mode: Optional[bool] = False ): @@ -239,7 +241,9 @@ class CohereV2ModelResponseIterator: return content return "" - def _parse_tool_call_delta(self, chunk: dict) -> Optional[ChatCompletionToolCallChunk]: + def _parse_tool_call_delta( + self, chunk: dict + ) -> Optional[ChatCompletionToolCallChunk]: """Parse tool-call-delta chunks to extract tool calls.""" delta = chunk.get("delta", {}) tool_calls = delta.get("tool_calls", []) @@ -249,8 +253,8 @@ class CohereV2ModelResponseIterator: "type": "function", "function": { "name": tool_calls[0].get("name", ""), - "arguments": tool_calls[0].get("arguments", "") - } + "arguments": tool_calls[0].get("arguments", ""), + }, } # type: ignore return None @@ -276,18 +280,20 @@ class CohereV2ModelResponseIterator: "end": citations.get("end", 0), "text": citations.get("text", ""), "sources": citations.get("sources", []), - "type": citations.get("type", "TEXT_CONTENT") + "type": citations.get("type", "TEXT_CONTENT"), } return {"citations": [citation_data]} return None - def _parse_message_end(self, chunk: dict) -> Tuple[bool, str, Optional[ChatCompletionUsageBlock]]: + def _parse_message_end( + self, chunk: dict + ) -> Tuple[bool, str, Optional[ChatCompletionUsageBlock]]: """Parse message-end events to extract finish info and usage.""" data = chunk.get("data", {}) delta = data.get("delta", {}) is_finished = True finish_reason = delta.get("finish_reason", "stop") - + usage = None usage_data = delta.get("usage", {}) if usage_data: @@ -295,15 +301,16 @@ class CohereV2ModelResponseIterator: usage = ChatCompletionUsageBlock( prompt_tokens=tokens_data.get("input_tokens", 0), completion_tokens=tokens_data.get("output_tokens", 0), - total_tokens=tokens_data.get("input_tokens", 0) + tokens_data.get("output_tokens", 0) + total_tokens=tokens_data.get("input_tokens", 0) + + tokens_data.get("output_tokens", 0), ) - + return is_finished, finish_reason, usage def chunk_parser(self, chunk: dict) -> GenericStreamingChunk: """ Parse Cohere v2 streaming chunks. - + v2 format: - Content: chunk.type == "content-delta" -> chunk.delta.message.content.text - Tool calls: chunk.type == "tool-call-delta" -> chunk.delta.tool_calls @@ -408,4 +415,3 @@ class CohereV2ModelResponseIterator: raise StopAsyncIteration except ValueError as e: raise RuntimeError(f"Error parsing chunk: {e},\nReceived chunk: {chunk}") - diff --git a/litellm/llms/cohere/rerank/transformation.py b/litellm/llms/cohere/rerank/transformation.py index d085cb13c44..531b94d1805 100644 --- a/litellm/llms/cohere/rerank/transformation.py +++ b/litellm/llms/cohere/rerank/transformation.py @@ -21,8 +21,8 @@ class CohereRerankConfig(BaseRerankConfig): pass def get_complete_url( - self, - api_base: Optional[str], + self, + api_base: Optional[str], model: str, optional_params: Optional[dict] = None, ) -> str: @@ -63,14 +63,16 @@ class CohereRerankConfig(BaseRerankConfig): No mapping required - returns all supported params """ - return dict(OptionalRerankParams( - query=query, - documents=documents, - top_n=top_n, - rank_fields=rank_fields, - return_documents=return_documents, - max_chunks_per_doc=max_chunks_per_doc, - )) + return dict( + OptionalRerankParams( + query=query, + documents=documents, + top_n=top_n, + rank_fields=rank_fields, + return_documents=return_documents, + max_chunks_per_doc=max_chunks_per_doc, + ) + ) def validate_environment( self, diff --git a/litellm/llms/cohere/rerank_v2/transformation.py b/litellm/llms/cohere/rerank_v2/transformation.py index 01309d937f9..60d22ff4be0 100644 --- a/litellm/llms/cohere/rerank_v2/transformation.py +++ b/litellm/llms/cohere/rerank_v2/transformation.py @@ -13,8 +13,8 @@ class CohereRerankV2Config(CohereRerankConfig): pass def get_complete_url( - self, - api_base: Optional[str], + self, + api_base: Optional[str], model: str, optional_params: Optional[dict] = None, ) -> str: @@ -55,14 +55,16 @@ class CohereRerankV2Config(CohereRerankConfig): No mapping required - returns all supported params """ - return dict(OptionalRerankParams( - query=query, - documents=documents, - top_n=top_n, - rank_fields=rank_fields, - return_documents=return_documents, - max_tokens_per_doc=max_tokens_per_doc, - )) + return dict( + OptionalRerankParams( + query=query, + documents=documents, + top_n=top_n, + rank_fields=rank_fields, + return_documents=return_documents, + max_tokens_per_doc=max_tokens_per_doc, + ) + ) def transform_rerank_request( self, diff --git a/litellm/llms/cometapi/chat/transformation.py b/litellm/llms/cometapi/chat/transformation.py index fedb8f61e5b..1e15ee188c6 100644 --- a/litellm/llms/cometapi/chat/transformation.py +++ b/litellm/llms/cometapi/chat/transformation.py @@ -21,11 +21,11 @@ from ..common_utils import CometAPIException class CometAPIConfig(OpenAIGPTConfig): """ CometAPI configuration class, inherits from OpenAIGPTConfig - + Since CometAPI is OpenAI-compatible API, we inherit from OpenAIGPTConfig and only need to override necessary methods to handle CometAPI-specific features """ - + def map_openai_params( self, non_default_params: dict, @@ -47,10 +47,10 @@ class CometAPIConfig(OpenAIGPTConfig): # custom_param = non_default_params.pop("custom_param", None) # if custom_param is not None: # extra_body["custom_param"] = custom_param - + if extra_body: mapped_openai_params["extra_body"] = extra_body - + return mapped_openai_params def remove_cache_control_flag_from_messages_and_tools( @@ -129,10 +129,7 @@ class CometAPIConfig(OpenAIGPTConfig): return f"{api_base}/{endpoint}" def get_error_class( - self, - error_message: str, - status_code: int, - headers: Union[dict, httpx.Headers] + self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ) -> BaseLLMException: """ Return CometAPI-specific error class @@ -163,7 +160,7 @@ class CometAPIChatCompletionStreamingHandler(BaseModelResponseIterator): """ Handler for CometAPI streaming chat completion responses """ - + def chunk_parser(self, chunk: dict) -> ModelResponseStream: """ Parse individual chunks from streaming response @@ -186,9 +183,11 @@ class CometAPIChatCompletionStreamingHandler(BaseModelResponseIterator): for choice in chunk["choices"]: # Handle reasoning content if present if "delta" in choice and "reasoning" in choice["delta"]: - choice["delta"]["reasoning_content"] = choice["delta"].get("reasoning") + choice["delta"]["reasoning_content"] = choice["delta"].get( + "reasoning" + ) new_choices.append(choice) - + return ModelResponseStream( id=chunk["id"], object="chat.completion.chunk", diff --git a/litellm/llms/cometapi/common_utils.py b/litellm/llms/cometapi/common_utils.py index 2e5e3e5fab7..8cb0a304026 100644 --- a/litellm/llms/cometapi/common_utils.py +++ b/litellm/llms/cometapi/common_utils.py @@ -3,4 +3,5 @@ from litellm.llms.base_llm.chat.transformation import BaseLLMException class CometAPIException(BaseLLMException): """CometAPI exception handling class""" + pass diff --git a/litellm/llms/cometapi/embed/transformation.py b/litellm/llms/cometapi/embed/transformation.py index 5cfd1253149..d1972def8b7 100644 --- a/litellm/llms/cometapi/embed/transformation.py +++ b/litellm/llms/cometapi/embed/transformation.py @@ -19,7 +19,7 @@ from ..common_utils import CometAPIException class CometAPIEmbeddingConfig(BaseEmbeddingConfig): """ Configuration class for CometAPI Embedding API. - + Since CometAPI is OpenAI-compatible, this class provides OpenAI-standard embedding functionality with CometAPI-specific authentication and endpoints. """ diff --git a/litellm/llms/cometapi/image_generation/cost_calculator.py b/litellm/llms/cometapi/image_generation/cost_calculator.py index b10c9d09087..987e79e18da 100644 --- a/litellm/llms/cometapi/image_generation/cost_calculator.py +++ b/litellm/llms/cometapi/image_generation/cost_calculator.py @@ -22,4 +22,6 @@ def cost_calculator( num_images = len(image_response.data) return output_cost_per_image * num_images else: - raise ValueError(f"image_response must be of type ImageResponse got type={type(image_response)}") + raise ValueError( + f"image_response must be of type ImageResponse got type={type(image_response)}" + ) diff --git a/litellm/llms/cometapi/image_generation/transformation.py b/litellm/llms/cometapi/image_generation/transformation.py index bf1ca9ddde6..bc6bd3f3ecc 100644 --- a/litellm/llms/cometapi/image_generation/transformation.py +++ b/litellm/llms/cometapi/image_generation/transformation.py @@ -23,7 +23,7 @@ else: class CometAPIImageGenerationConfig(BaseImageGenerationConfig): DEFAULT_BASE_URL: str = "https://api.cometapi.com" IMAGE_GENERATION_ENDPOINT: str = "v1/images/generations" - + def get_supported_openai_params( self, model: str ) -> List[OpenAIImageGenerationOptionalParams]: @@ -37,7 +37,7 @@ class CometAPIImageGenerationConfig(BaseImageGenerationConfig): "size", "style", ] - + def map_openai_params( self, non_default_params: dict, @@ -46,7 +46,7 @@ class CometAPIImageGenerationConfig(BaseImageGenerationConfig): drop_params: bool, ) -> dict: supported_params = self.get_supported_openai_params(model) - + for k in non_default_params.keys(): if k not in optional_params.keys(): if k in supported_params: @@ -74,7 +74,7 @@ class CometAPIImageGenerationConfig(BaseImageGenerationConfig): Get the complete url for the request """ complete_url: str = ( - api_base + api_base or get_secret_str("COMETAPI_BASE_URL") or get_secret_str("COMETAPI_API_BASE") or self.DEFAULT_BASE_URL @@ -95,15 +95,15 @@ class CometAPIImageGenerationConfig(BaseImageGenerationConfig): api_base: Optional[str] = None, ) -> dict: final_api_key: Optional[str] = ( - api_key or - get_secret_str("COMETAPI_KEY") or - get_secret_str("COMETAPI_API_KEY") + api_key + or get_secret_str("COMETAPI_KEY") + or get_secret_str("COMETAPI_API_KEY") ) if not final_api_key: raise ValueError("COMETAPI_KEY or COMETAPI_API_KEY is not set") - + headers["Authorization"] = f"Bearer {final_api_key}" - headers["Content-Type"] = "application/json" + headers["Content-Type"] = "application/json" return headers def transform_image_generation_request( @@ -153,10 +153,10 @@ class CometAPIImageGenerationConfig(BaseImageGenerationConfig): status_code=raw_response.status_code, headers=raw_response.headers, ) - + if not model_response.data: model_response.data = [] - + # CometAPI returns OpenAI-compatible format # Expected format: {"created": timestamp, "data": [{"url": "...", "b64_json": "..."}]} if "data" in response_data: @@ -166,5 +166,5 @@ class CometAPIImageGenerationConfig(BaseImageGenerationConfig): url=image_data.get("url"), ) model_response.data.append(image_obj) - + return model_response diff --git a/litellm/llms/compactifai/__init__.py b/litellm/llms/compactifai/__init__.py index 16b0c04cdab..d081dd7cf6e 100644 --- a/litellm/llms/compactifai/__init__.py +++ b/litellm/llms/compactifai/__init__.py @@ -1 +1 @@ -# CompactifAI provider for LiteLLM \ No newline at end of file +# CompactifAI provider for LiteLLM diff --git a/litellm/llms/compactifai/chat/__init__.py b/litellm/llms/compactifai/chat/__init__.py index d1a4463166b..221b0e02196 100644 --- a/litellm/llms/compactifai/chat/__init__.py +++ b/litellm/llms/compactifai/chat/__init__.py @@ -1 +1 @@ -# CompactifAI chat completions \ No newline at end of file +# CompactifAI chat completions diff --git a/litellm/llms/compactifai/chat/transformation.py b/litellm/llms/compactifai/chat/transformation.py index 5cb8cd9a4ab..d4b9c5a83ae 100644 --- a/litellm/llms/compactifai/chat/transformation.py +++ b/litellm/llms/compactifai/chat/transformation.py @@ -76,7 +76,9 @@ class CompactifAIChatConfig(OpenAIGPTConfig): # Convert tool calls to content for JSON mode tool_calls = message.get("tool_calls", []) if len(tool_calls) == 1: - message["content"] = tool_calls[0]["function"].get("arguments", "") + message["content"] = tool_calls[0]["function"].get( + "arguments", "" + ) message["tool_calls"] = None returned_response = ModelResponse(**response_json) @@ -97,4 +99,4 @@ class CompactifAIChatConfig(OpenAIGPTConfig): status_code=status_code, message=error_message, headers=headers, - ) \ No newline at end of file + ) diff --git a/litellm/llms/custom_httpx/aiohttp_transport.py b/litellm/llms/custom_httpx/aiohttp_transport.py index 60f34a2a825..132191c946c 100644 --- a/litellm/llms/custom_httpx/aiohttp_transport.py +++ b/litellm/llms/custom_httpx/aiohttp_transport.py @@ -83,7 +83,9 @@ class AiohttpResponseStream(httpx.AsyncByteStream): async def __aiter__(self) -> typing.AsyncIterator[bytes]: try: - async for chunk in self._aiohttp_response.content.iter_chunked(self.CHUNK_SIZE): + async for chunk in self._aiohttp_response.content.iter_chunked( + self.CHUNK_SIZE + ): yield chunk except ( aiohttp.ClientPayloadError, @@ -101,7 +103,9 @@ class AiohttpResponseStream(httpx.AsyncByteStream): # with message "Connection closed.". Treat this as a graceful # end-of-stream so downstream consumers don't error. if "Connection closed" in str(e): - verbose_logger.debug("Upstream closed streaming connection; ending iterator gracefully") + verbose_logger.debug( + "Upstream closed streaming connection; ending iterator gracefully" + ) return raise except aiohttp.http_exceptions.TransferEncodingError as e: @@ -191,7 +195,11 @@ class LiteLLMAiohttpTransport(AiohttpTransport): current_loop = asyncio.get_running_loop() # If session is from a different or closed loop, recreate it - if session_loop is None or session_loop != current_loop or session_loop.is_closed(): + if ( + session_loop is None + or session_loop != current_loop + or session_loop.is_closed() + ): # Close old session to prevent leaks old_session = self.client try: @@ -200,7 +208,9 @@ class LiteLLMAiohttpTransport(AiohttpTransport): asyncio.create_task(old_session.close()) except RuntimeError: # Different event loop - can't schedule task, rely on GC - verbose_logger.debug("Old session from different loop, relying on GC") + verbose_logger.debug( + "Old session from different loop, relying on GC" + ) except Exception as e: verbose_logger.debug(f"Error closing old session: {e}") @@ -305,7 +315,9 @@ class LiteLLMAiohttpTransport(AiohttpTransport): except RuntimeError as e: # Handle the case where session was closed between our check and actual use if "Session is closed" in str(e): - verbose_logger.debug(f"Session closed during request, retrying with new session: {e}") + verbose_logger.debug( + f"Session closed during request, retrying with new session: {e}" + ) # Force creation of a new session if hasattr(self, "_client_factory") and callable(self._client_factory): self.client = self._client_factory() @@ -336,7 +348,10 @@ class LiteLLMAiohttpTransport(AiohttpTransport): async def _get_proxy_settings(self, request: httpx.Request): proxy = None - if not (litellm.disable_aiohttp_trust_env or str_to_bool(os.getenv("DISABLE_AIOHTTP_TRUST_ENV", "False"))): + if not ( + litellm.disable_aiohttp_trust_env + or str_to_bool(os.getenv("DISABLE_AIOHTTP_TRUST_ENV", "False")) + ): try: proxy = self._proxy_from_env(request.url) except Exception as e: # pragma: no cover - best effort diff --git a/litellm/llms/custom_httpx/async_client_cleanup.py b/litellm/llms/custom_httpx/async_client_cleanup.py index abbc61dc96d..22629383ac2 100644 --- a/litellm/llms/custom_httpx/async_client_cleanup.py +++ b/litellm/llms/custom_httpx/async_client_cleanup.py @@ -28,17 +28,17 @@ async def close_litellm_async_clients(): pass # Handle AsyncHTTPHandler instances (used by Gemini and other providers) - elif hasattr(handler, 'client'): + elif hasattr(handler, "client"): client = handler.client # Check if the httpx client has an aiohttp transport - if hasattr(client, '_transport') and hasattr(client._transport, 'aclose'): + if hasattr(client, "_transport") and hasattr(client._transport, "aclose"): try: await client._transport.aclose() except Exception: # Silently ignore errors during cleanup pass # Also close the httpx client itself - if hasattr(client, 'aclose') and not client.is_closed: + if hasattr(client, "aclose") and not client.is_closed: try: await client.aclose() except Exception: @@ -46,7 +46,7 @@ async def close_litellm_async_clients(): pass # Handle any other objects with aclose method - elif hasattr(handler, 'aclose'): + elif hasattr(handler, "aclose"): try: await handler.aclose() except Exception: @@ -55,9 +55,11 @@ async def close_litellm_async_clients(): # Close the global base_llm_aiohttp_handler instance (issue #12443) # This is used by Gemini and other providers that use aiohttp - if hasattr(litellm, 'base_llm_aiohttp_handler'): - base_handler = getattr(litellm, 'base_llm_aiohttp_handler', None) - if isinstance(base_handler, BaseLLMAIOHTTPHandler) and hasattr(base_handler, 'close'): + if hasattr(litellm, "base_llm_aiohttp_handler"): + base_handler = getattr(litellm, "base_llm_aiohttp_handler", None) + if isinstance(base_handler, BaseLLMAIOHTTPHandler) and hasattr( + base_handler, "close" + ): try: await base_handler.close() except Exception: diff --git a/litellm/llms/custom_httpx/container_handler.py b/litellm/llms/custom_httpx/container_handler.py index 73017eaaf30..3767949375d 100644 --- a/litellm/llms/custom_httpx/container_handler.py +++ b/litellm/llms/custom_httpx/container_handler.py @@ -60,15 +60,15 @@ def _build_url( path_params: Dict[str, str], ) -> str: """Build the full URL by substituting path parameters. - + The api_base from get_complete_url already includes /containers, so we need to strip that prefix from the path_template. """ # api_base ends with /containers, path_template starts with /containers # So we need to strip /containers from the path if path_template.startswith("/containers"): - path_template = path_template[len("/containers"):] - + path_template = path_template[len("/containers") :] + url = f"{api_base.rstrip('/')}{path_template}" for param, value in path_params.items(): url = url.replace(f"{{{param}}}", value) @@ -94,36 +94,36 @@ def _prepare_multipart_file_upload( ) -> tuple: """ Prepare file and headers for multipart upload. - + Returns: Tuple of (files_dict, headers_without_content_type) """ from litellm.litellm_core_utils.prompt_templates.common_utils import ( extract_file_data, ) - + extracted = extract_file_data(file) filename = extracted.get("filename") or "file" content = extracted.get("content") or b"" content_type = extracted.get("content_type") or "application/octet-stream" files = {"file": (filename, content, content_type)} - + # Remove content-type header - httpx will set it automatically for multipart headers_copy = headers.copy() headers_copy.pop("content-type", None) headers_copy.pop("Content-Type", None) - + return files, headers_copy class GenericContainerHandler: """ Generic handler for container file API endpoints. - + This single handler can process any endpoint defined in endpoints.json, eliminating the need for individual handler methods per endpoint. """ - + def handle( self, endpoint_name: str, @@ -139,7 +139,7 @@ class GenericContainerHandler: ) -> Union[Any, Coroutine[Any, Any, Any]]: """ Generic handler for any container file endpoint. - + Args: endpoint_name: Name of the endpoint (e.g., "list_container_files") container_provider_config: Provider-specific configuration @@ -164,7 +164,7 @@ class GenericContainerHandler: client=client, **kwargs, ) - + return self._sync_handle( endpoint_name=endpoint_name, container_provider_config=container_provider_config, @@ -176,7 +176,7 @@ class GenericContainerHandler: client=client, **kwargs, ) - + def _sync_handle( self, endpoint_name: str, @@ -193,7 +193,7 @@ class GenericContainerHandler: endpoint_config = _get_endpoint_config(endpoint_name) if not endpoint_config: raise ValueError(f"Unknown endpoint: {endpoint_name}") - + # Get HTTP client if client is None or not isinstance(client, HTTPHandler): http_client = _get_httpx_client( @@ -201,7 +201,7 @@ class GenericContainerHandler: ) else: http_client = client - + # Build request headers = container_provider_config.validate_environment( headers=extra_headers or {}, @@ -209,21 +209,25 @@ class GenericContainerHandler: ) if extra_headers: headers.update(extra_headers) - + api_base = container_provider_config.get_complete_url( api_base=litellm_params.get("api_base", None), litellm_params=dict(litellm_params), ) - + # Build URL with path params - path_params = {p: kwargs.get(p, "") for p in endpoint_config.get("path_params", [])} + path_params = { + p: kwargs.get(p, "") for p in endpoint_config.get("path_params", []) + } url = _build_url(api_base, endpoint_config["path"], path_params) - + # Build query params - query_params = _build_query_params(endpoint_config.get("query_params", []), kwargs) + query_params = _build_query_params( + endpoint_config.get("query_params", []), kwargs + ) if extra_query: query_params.update(extra_query) - + # Log request logging_obj.pre_call( input="", @@ -234,50 +238,63 @@ class GenericContainerHandler: "params": query_params, }, ) - + # Make request method = endpoint_config["method"].upper() returns_binary = endpoint_config.get("returns_binary", False) is_multipart = endpoint_config.get("is_multipart", False) - + try: if method == "GET": - response = http_client.get(url=url, headers=headers, params=query_params) + response = http_client.get( + url=url, headers=headers, params=query_params + ) elif method == "DELETE": - response = http_client.delete(url=url, headers=headers, params=query_params) + response = http_client.delete( + url=url, headers=headers, params=query_params + ) elif method == "POST": if is_multipart and "file" in kwargs: - files, headers = _prepare_multipart_file_upload(kwargs["file"], headers) - response = http_client.post(url=url, headers=headers, params=query_params, files=files) + files, headers = _prepare_multipart_file_upload( + kwargs["file"], headers + ) + response = http_client.post( + url=url, headers=headers, params=query_params, files=files + ) else: - response = http_client.post(url=url, headers=headers, params=query_params) + response = http_client.post( + url=url, headers=headers, params=query_params + ) else: raise ValueError(f"Unsupported HTTP method: {method}") - + # For binary responses, return raw content if returns_binary: return response.content - + # Check for error response response_json = response.json() if "error" in response_json: from litellm.llms.base_llm.chat.transformation import BaseLLMException - error_msg = response_json.get("error", {}).get("message", str(response_json)) + + error_msg = response_json.get("error", {}).get( + "message", str(response_json) + ) raise BaseLLMException( status_code=response.status_code, message=error_msg, headers=dict(response.headers), ) - + # Parse response response_type = RESPONSE_TYPES.get(endpoint_config["response_type"]) if response_type: return response_type(**response_json) return response_json - + except Exception as e: raise e - + async def _async_handle( self, endpoint_name: str, @@ -294,7 +311,7 @@ class GenericContainerHandler: endpoint_config = _get_endpoint_config(endpoint_name) if not endpoint_config: raise ValueError(f"Unknown endpoint: {endpoint_name}") - + # Get HTTP client if client is None or not isinstance(client, AsyncHTTPHandler): http_client = get_async_httpx_client( @@ -303,7 +320,7 @@ class GenericContainerHandler: ) else: http_client = client - + # Build request headers = container_provider_config.validate_environment( headers=extra_headers or {}, @@ -311,21 +328,25 @@ class GenericContainerHandler: ) if extra_headers: headers.update(extra_headers) - + api_base = container_provider_config.get_complete_url( api_base=litellm_params.get("api_base", None), litellm_params=dict(litellm_params), ) - + # Build URL with path params - path_params = {p: kwargs.get(p, "") for p in endpoint_config.get("path_params", [])} + path_params = { + p: kwargs.get(p, "") for p in endpoint_config.get("path_params", []) + } url = _build_url(api_base, endpoint_config["path"], path_params) - + # Build query params - query_params = _build_query_params(endpoint_config.get("query_params", []), kwargs) + query_params = _build_query_params( + endpoint_config.get("query_params", []), kwargs + ) if extra_query: query_params.update(extra_query) - + # Log request logging_obj.pre_call( input="", @@ -336,51 +357,63 @@ class GenericContainerHandler: "params": query_params, }, ) - + # Make request method = endpoint_config["method"].upper() returns_binary = endpoint_config.get("returns_binary", False) is_multipart = endpoint_config.get("is_multipart", False) - + try: if method == "GET": - response = await http_client.get(url=url, headers=headers, params=query_params) + response = await http_client.get( + url=url, headers=headers, params=query_params + ) elif method == "DELETE": - response = await http_client.delete(url=url, headers=headers, params=query_params) + response = await http_client.delete( + url=url, headers=headers, params=query_params + ) elif method == "POST": if is_multipart and "file" in kwargs: - files, headers = _prepare_multipart_file_upload(kwargs["file"], headers) - response = await http_client.post(url=url, headers=headers, params=query_params, files=files) + files, headers = _prepare_multipart_file_upload( + kwargs["file"], headers + ) + response = await http_client.post( + url=url, headers=headers, params=query_params, files=files + ) else: - response = await http_client.post(url=url, headers=headers, params=query_params) + response = await http_client.post( + url=url, headers=headers, params=query_params + ) else: raise ValueError(f"Unsupported HTTP method: {method}") - + # For binary responses, return raw content if returns_binary: return response.content - + # Check for error response response_json = response.json() if "error" in response_json: from litellm.llms.base_llm.chat.transformation import BaseLLMException - error_msg = response_json.get("error", {}).get("message", str(response_json)) + + error_msg = response_json.get("error", {}).get( + "message", str(response_json) + ) raise BaseLLMException( status_code=response.status_code, message=error_msg, headers=dict(response.headers), ) - + # Parse response response_type = RESPONSE_TYPES.get(endpoint_config["response_type"]) if response_type: return response_type(**response_json) return response_json - + except Exception as e: raise e # Singleton instance generic_container_handler = GenericContainerHandler() - diff --git a/litellm/llms/custom_httpx/http_handler.py b/litellm/llms/custom_httpx/http_handler.py index 3dfef07d426..001547557d4 100644 --- a/litellm/llms/custom_httpx/http_handler.py +++ b/litellm/llms/custom_httpx/http_handler.py @@ -51,6 +51,7 @@ try: except Exception: version = "0.0.0" + def get_default_headers() -> dict: """ Get default headers for HTTP requests. @@ -64,6 +65,7 @@ def get_default_headers() -> dict: return {"User-Agent": f"litellm/{version}"} + # Initialize headers (User-Agent) headers = get_default_headers() @@ -1235,7 +1237,9 @@ def get_async_httpx_client( if params is not None: # Filter out params that are only used for cache key, not for AsyncHTTPHandler.__init__ - handler_params = {k: v for k, v in params.items() if k != "disable_aiohttp_transport"} + handler_params = { + k: v for k, v in params.items() if k != "disable_aiohttp_transport" + } handler_params["shared_session"] = shared_session _new_client = AsyncHTTPHandler(**handler_params) else: @@ -1284,7 +1288,9 @@ def _get_httpx_client(params: Optional[dict] = None) -> HTTPHandler: if params is not None: # Filter out params that are only used for cache key, not for HTTPHandler.__init__ - handler_params = {k: v for k, v in params.items() if k != "disable_aiohttp_transport"} + handler_params = { + k: v for k, v in params.items() if k != "disable_aiohttp_transport" + } _new_client = HTTPHandler(**handler_params) else: _new_client = HTTPHandler(timeout=httpx.Timeout(timeout=600.0, connect=5.0)) diff --git a/litellm/llms/custom_httpx/httpx_handler.py b/litellm/llms/custom_httpx/httpx_handler.py index 491cd97f7db..ce587946710 100644 --- a/litellm/llms/custom_httpx/httpx_handler.py +++ b/litellm/llms/custom_httpx/httpx_handler.py @@ -8,6 +8,7 @@ try: except Exception: version = "0.0.0" + def get_default_headers() -> dict: """ Get default headers for HTTP requests. @@ -21,6 +22,7 @@ def get_default_headers() -> dict: return {"User-Agent": f"litellm/{version}"} + class HTTPHandler: def __init__(self, concurrent_limit=1000): headers = get_default_headers() diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py index 1cef3e9ce15..a8d649064ac 100644 --- a/litellm/llms/custom_httpx/llm_http_handler.py +++ b/litellm/llms/custom_httpx/llm_http_handler.py @@ -445,7 +445,9 @@ class BaseLLMHTTPHandler: # Check if stream was converted for WebSearch interception # This is set by the async_pre_request_hook in WebSearchInterceptionLogger if litellm_params.get("_websearch_interception_converted_stream", False): - logging_obj.model_call_details["websearch_interception_converted_stream"] = True + logging_obj.model_call_details[ + "websearch_interception_converted_stream" + ] = True if acompletion is True: if stream is True: @@ -1355,6 +1357,7 @@ class BaseLLMHTTPHandler: Returns: (headers, complete_url, data, files) """ from litellm.llms.base_llm.ocr.transformation import OCRRequestData + headers = provider_config.validate_environment( api_key=api_key, api_base=api_base, @@ -1847,9 +1850,11 @@ class BaseLLMHTTPHandler: Optional[litellm.types.utils.ProviderSpecificHeader], kwargs.get("provider_specific_header", None), ) - provider_specific_headers = ProviderSpecificHeaderUtils.get_provider_specific_headers( - provider_specific_header=provider_specific_header, - custom_llm_provider=custom_llm_provider, + provider_specific_headers = ( + ProviderSpecificHeaderUtils.get_provider_specific_headers( + provider_specific_header=provider_specific_header, + custom_llm_provider=custom_llm_provider, + ) ) forwarded_headers = kwargs.get("headers", None) # Also check for extra_headers in kwargs (from config or direct calls) @@ -1874,7 +1879,7 @@ class BaseLLMHTTPHandler: api_key=api_key, api_base=api_base, ) - + headers = update_headers_with_filtered_beta( headers=headers, provider=custom_llm_provider ) @@ -2848,12 +2853,12 @@ class BaseLLMHTTPHandler: ) -> tuple[Optional[str], Optional[dict]]: """ Extract upload URL from initial file creation response. - + Args: response: HTTP response from initial file creation request upload_url_location: Where to find URL ('headers' or 'body') upload_url_key: Key name for URL in response body (default: 'upload_url') - + Returns: Tuple of (upload_url, response_data) - upload_url: The extracted upload URL, or None if not found @@ -2934,7 +2939,10 @@ class BaseLLMHTTPHandler: else: sync_httpx_client = client - if isinstance(transformed_request, dict) and "initial_request" in transformed_request: + if ( + isinstance(transformed_request, dict) + and "initial_request" in transformed_request + ): # Handle two-step uploads (TwoStepFileUploadConfig) # Used by providers like Manus, Google Cloud Storage try: @@ -2950,24 +2958,33 @@ class BaseLLMHTTPHandler: ) # Extract upload URL from response - upload_url, initial_response_data = self._extract_upload_url_from_response( + ( + upload_url, + initial_response_data, + ) = self._extract_upload_url_from_response( response=initial_response, - upload_url_location=transformed_request.get("upload_url_location", "headers"), - upload_url_key=transformed_request.get("upload_url_key", "upload_url"), + upload_url_location=transformed_request.get( + "upload_url_location", "headers" + ), + upload_url_key=transformed_request.get( + "upload_url_key", "upload_url" + ), ) if not upload_url: raise ValueError("Failed to get upload URL from initial request") # Step 2: Upload the actual file - upload_method = transformed_request["upload_request"].get("method", "POST").lower() + upload_method = ( + transformed_request["upload_request"].get("method", "POST").lower() + ) upload_response = getattr(sync_httpx_client, upload_method)( url=upload_url, headers=transformed_request["upload_request"]["headers"], data=transformed_request["upload_request"]["data"], timeout=timeout, ) - + # Store initial response for transformation if initial_response_data: litellm_params["initial_file_response"] = initial_response_data @@ -2976,7 +2993,11 @@ class BaseLLMHTTPHandler: e=e, provider_config=provider_config, ) - elif isinstance(transformed_request, dict) and "method" in transformed_request and "initial_request" not in transformed_request: + elif ( + isinstance(transformed_request, dict) + and "method" in transformed_request + and "initial_request" not in transformed_request + ): # Handle pre-signed requests (e.g., from Bedrock S3 uploads) # Type narrowing: this is a plain dict, not TwoStepFileUploadConfig presigned_request = cast(Dict[str, Any], transformed_request) @@ -3012,8 +3033,20 @@ class BaseLLMHTTPHandler: data=transformed_request, timeout=timeout, ) + elif isinstance(transformed_request, dict) and "file" in transformed_request: + # Handle multipart form-data uploads (e.g., Anthropic Files API) + # The dict contains tuples suitable for httpx's `files` parameter + file_request = cast(Dict[str, Any], transformed_request) + upload_response = sync_httpx_client.post( + url=api_base, + headers=headers, + files=file_request, + timeout=timeout, + ) else: - raise ValueError(f"Unsupported transformed_request type: {type(transformed_request)}") + raise ValueError( + f"Unsupported transformed_request type: {type(transformed_request)}" + ) # Store the upload URL in litellm_params for the transformation method # Honour the URL already set by transform_create_file_request (e.g. Bedrock pre-signed S3 uploads), @@ -3063,7 +3096,10 @@ class BaseLLMHTTPHandler: }, ) - if isinstance(transformed_request, dict) and "initial_request" in transformed_request: + if ( + isinstance(transformed_request, dict) + and "initial_request" in transformed_request + ): # Handle two-step uploads (TwoStepFileUploadConfig) # Used by providers like Manus, Google Cloud Storage try: @@ -3079,24 +3115,33 @@ class BaseLLMHTTPHandler: ) # Extract upload URL from response - upload_url, initial_response_data = self._extract_upload_url_from_response( + ( + upload_url, + initial_response_data, + ) = self._extract_upload_url_from_response( response=initial_response, - upload_url_location=transformed_request.get("upload_url_location", "headers"), - upload_url_key=transformed_request.get("upload_url_key", "upload_url"), + upload_url_location=transformed_request.get( + "upload_url_location", "headers" + ), + upload_url_key=transformed_request.get( + "upload_url_key", "upload_url" + ), ) if not upload_url: raise ValueError("Failed to get upload URL from initial request") # Step 2: Upload the actual file - upload_method = transformed_request["upload_request"].get("method", "POST").lower() + upload_method = ( + transformed_request["upload_request"].get("method", "POST").lower() + ) upload_response = await getattr(async_httpx_client, upload_method)( url=upload_url, headers=transformed_request["upload_request"]["headers"], data=transformed_request["upload_request"]["data"], timeout=timeout, ) - + # Store initial response for transformation if initial_response_data: litellm_params["initial_file_response"] = initial_response_data @@ -3106,7 +3151,11 @@ class BaseLLMHTTPHandler: e=e, provider_config=provider_config, ) - elif isinstance(transformed_request, dict) and "method" in transformed_request and "initial_request" not in transformed_request: + elif ( + isinstance(transformed_request, dict) + and "method" in transformed_request + and "initial_request" not in transformed_request + ): # Handle pre-signed requests (e.g., from Bedrock S3 uploads) # Type narrowing: this is a plain dict, not TwoStepFileUploadConfig presigned_request = cast(Dict[str, Any], transformed_request) @@ -3140,8 +3189,19 @@ class BaseLLMHTTPHandler: data=transformed_request, timeout=timeout, ) + elif isinstance(transformed_request, dict) and "file" in transformed_request: + # Handle multipart form-data uploads (e.g., Anthropic Files API) + # The dict contains tuples suitable for httpx's `files` parameter + upload_response = await async_httpx_client.post( + url=api_base, + headers=headers, + files=transformed_request, + timeout=timeout, + ) else: - raise ValueError(f"Unsupported transformed_request type: {type(transformed_request)}") + raise ValueError( + f"Unsupported transformed_request type: {type(transformed_request)}" + ) return provider_config.transform_create_file_response( model=None, @@ -3740,7 +3800,10 @@ class BaseLLMHTTPHandler: litellm_params=dict(litellm_params), ) - url, data = responses_api_provider_config.transform_compact_response_api_request( + ( + url, + data, + ) = responses_api_provider_config.transform_compact_response_api_request( model=model, input=input, response_api_optional_request_params=response_api_optional_request_params, @@ -3819,7 +3882,10 @@ class BaseLLMHTTPHandler: litellm_params=dict(litellm_params), ) - url, data = responses_api_provider_config.transform_compact_response_api_request( + ( + url, + data, + ) = responses_api_provider_config.transform_compact_response_api_request( model=model, input=input, response_api_optional_request_params=response_api_optional_request_params, @@ -3913,9 +3979,7 @@ class BaseLLMHTTPHandler: ) try: - response = sync_httpx_client.get( - url=url, headers=headers, params=params - ) + response = sync_httpx_client.get(url=url, headers=headers, params=params) except Exception as e: raise self._handle_error(e=e, provider_config=provider_config) @@ -4043,9 +4107,7 @@ class BaseLLMHTTPHandler: ) try: - response = sync_httpx_client.delete( - url=url, headers=headers, params=params - ) + response = sync_httpx_client.delete(url=url, headers=headers, params=params) except Exception as e: raise self._handle_error(e=e, provider_config=provider_config) @@ -4173,9 +4235,7 @@ class BaseLLMHTTPHandler: ) try: - response = sync_httpx_client.get( - url=url, headers=headers, params=params - ) + response = sync_httpx_client.get(url=url, headers=headers, params=params) except Exception as e: raise self._handle_error(e=e, provider_config=provider_config) @@ -4255,7 +4315,9 @@ class BaseLLMHTTPHandler: _is_async: bool = False, client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, timeout: Optional[Union[float, httpx.Timeout]] = None, - ) -> Union["HttpxBinaryResponseContent", Coroutine[Any, Any, "HttpxBinaryResponseContent"]]: + ) -> Union[ + "HttpxBinaryResponseContent", Coroutine[Any, Any, "HttpxBinaryResponseContent"] + ]: """ Retrieve file content by ID """ @@ -4303,9 +4365,7 @@ class BaseLLMHTTPHandler: ) try: - response = sync_httpx_client.get( - url=url, headers=headers, params=params - ) + response = sync_httpx_client.get(url=url, headers=headers, params=params) except Exception as e: raise self._handle_error(e=e, provider_config=provider_config) @@ -4413,32 +4473,33 @@ class BaseLLMHTTPHandler: from litellm._logging import verbose_logger from litellm.integrations.custom_logger import CustomLogger - callbacks = litellm.callbacks + ( - logging_obj.dynamic_success_callbacks or [] - ) + callbacks = litellm.callbacks + (logging_obj.dynamic_success_callbacks or []) tools = anthropic_messages_optional_request_params.get("tools", []) for callback in callbacks: try: if isinstance(callback, CustomLogger): # First: Check if agentic loop should run - should_run, tool_calls = ( - await callback.async_should_run_agentic_loop( - response=response, - model=model, - messages=messages, - tools=tools, - stream=stream, - custom_llm_provider=custom_llm_provider, - kwargs=kwargs, - ) + ( + should_run, + tool_calls, + ) = await callback.async_should_run_agentic_loop( + response=response, + model=model, + messages=messages, + tools=tools, + stream=stream, + custom_llm_provider=custom_llm_provider, + kwargs=kwargs, ) if should_run: # Second: Execute agentic loop # Add custom_llm_provider to kwargs so the agentic loop can reconstruct the full model name kwargs_with_provider = kwargs.copy() if kwargs else {} - kwargs_with_provider["custom_llm_provider"] = custom_llm_provider + kwargs_with_provider[ + "custom_llm_provider" + ] = custom_llm_provider agentic_response = await callback.async_run_agentic_loop( tools=tool_calls, model=model, @@ -4458,7 +4519,9 @@ class BaseLLMHTTPHandler: verbose_logger.exception( "LiteLLM.AgenticHookError: Exception in agentic completion hooks " "[call_id=%s model=%s]: %s", - _call_id, model, str(e), + _call_id, + model, + str(e), ) # Check if we need to convert response to fake stream @@ -4467,11 +4530,13 @@ class BaseLLMHTTPHandler: # 2. No agentic loop ran (LLM didn't use the tool) # 3. We have a non-streaming response that needs to be converted to streaming websearch_converted_stream = ( - logging_obj.model_call_details.get("websearch_interception_converted_stream", False) + logging_obj.model_call_details.get( + "websearch_interception_converted_stream", False + ) if logging_obj is not None else False ) - + if websearch_converted_stream: from typing import cast @@ -4482,11 +4547,11 @@ class BaseLLMHTTPHandler: from litellm.types.llms.anthropic_messages.anthropic_response import ( AnthropicMessagesResponse, ) - + verbose_logger.debug( "WebSearchInterception: No tool call made, converting non-streaming response to fake stream" ) - + # Convert the non-streaming response to a fake stream # The response should be an AnthropicMessagesResponse (dict) if isinstance(response, dict): @@ -4495,7 +4560,7 @@ class BaseLLMHTTPHandler: response=cast(AnthropicMessagesResponse, response) ) return fake_stream - + return None async def _call_agentic_chat_completion_hooks( @@ -4520,45 +4585,50 @@ class BaseLLMHTTPHandler: from litellm._logging import verbose_logger from litellm.integrations.custom_logger import CustomLogger - callbacks = litellm.callbacks + ( - logging_obj.dynamic_success_callbacks or [] - ) + callbacks = litellm.callbacks + (logging_obj.dynamic_success_callbacks or []) tools = optional_params.get("tools", []) for callback in callbacks: try: if isinstance(callback, CustomLogger): # Check if callback has the chat completion agentic loop method - if not hasattr(callback, "async_should_run_chat_completion_agentic_loop"): + if not hasattr( + callback, "async_should_run_chat_completion_agentic_loop" + ): continue # First: Check if agentic loop should run - should_run, tool_calls = ( - await callback.async_should_run_chat_completion_agentic_loop( - response=response, - model=model, - messages=messages, - tools=tools, - stream=stream, - custom_llm_provider=custom_llm_provider, - kwargs=kwargs, - ) + ( + should_run, + tool_calls, + ) = await callback.async_should_run_chat_completion_agentic_loop( + response=response, + model=model, + messages=messages, + tools=tools, + stream=stream, + custom_llm_provider=custom_llm_provider, + kwargs=kwargs, ) if should_run: # Second: Execute agentic loop # Add custom_llm_provider to kwargs so the agentic loop can reconstruct the full model name kwargs_with_provider = kwargs.copy() if kwargs else {} - kwargs_with_provider["custom_llm_provider"] = custom_llm_provider - agentic_response = await callback.async_run_chat_completion_agentic_loop( - tools=tool_calls, - model=model, - messages=messages, - response=response, - optional_params=optional_params, - logging_obj=logging_obj, - stream=stream, - kwargs=kwargs_with_provider, + kwargs_with_provider[ + "custom_llm_provider" + ] = custom_llm_provider + agentic_response = ( + await callback.async_run_chat_completion_agentic_loop( + tools=tool_calls, + model=model, + messages=messages, + response=response, + optional_params=optional_params, + logging_obj=logging_obj, + stream=stream, + kwargs=kwargs_with_provider, + ) ) # First hook that runs agentic loop wins return agentic_response @@ -4574,27 +4644,29 @@ class BaseLLMHTTPHandler: # 2. No agentic loop ran (LLM didn't use the tool) # 3. We have a non-streaming response that needs to be converted to streaming websearch_converted_stream = ( - logging_obj.model_call_details.get("websearch_interception_converted_stream", False) + logging_obj.model_call_details.get( + "websearch_interception_converted_stream", False + ) if logging_obj is not None else False ) - + if websearch_converted_stream: from litellm._logging import verbose_logger from litellm.llms.base_llm.base_model_iterator import ( convert_model_response_to_streaming, ) - + verbose_logger.debug( "WebSearchInterception: No tool call made, converting non-streaming chat completion to fake stream" ) - + # Convert the non-streaming ModelResponse to a fake stream if hasattr(response, "choices"): # Use the existing converter for ModelResponse fake_stream = convert_model_response_to_streaming(response) return fake_stream - + return None def _handle_error( @@ -4694,7 +4766,9 @@ class BaseLLMHTTPHandler: # (e.g. Gemini/Vertex AI Live needs a `setup` message before any realtime_input) _session_config: Optional[str] = None if provider_config.requires_session_configuration(): - _session_config = provider_config.session_configuration_request(model) + _session_config = provider_config.session_configuration_request( + model + ) if _session_config: await backend_ws.send(_session_config) @@ -4735,6 +4809,161 @@ class BaseLLMHTTPHandler: f"Unexpected error while closing WebSocket: {close_error}" ) + async def async_realtime_client_secret_handler( + self, + api_base: str, + api_key: str, + request_data: Dict[str, Any], + logging_obj: LiteLLMLoggingObj, + timeout: Union[float, httpx.Timeout], + provider_config: Optional[Any] = None, + model: Optional[str] = None, + extra_headers: Optional[Dict[str, Any]] = None, + client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, + api_version: Optional[str] = None, + ) -> httpx.Response: + """ + Forward POST /v1/realtime/client_secrets to upstream provider. + + Uses provider_config (BaseRealtimeHTTPConfig) for URL construction and + header auth when available; falls back to the legacy OpenAI-style defaults. + """ + if client is None or not isinstance(client, AsyncHTTPHandler): + async_httpx_client = get_async_httpx_client( + llm_provider=litellm.LlmProviders.OPENAI, + ) + else: + async_httpx_client = client + + if provider_config is not None: + url = provider_config.get_complete_url( + api_base=api_base, model=model or "", api_version=api_version + ) + headers: Dict[str, Any] = provider_config.validate_environment( + headers={}, model=model or "", api_key=api_key + ) + else: + url = f"{api_base.rstrip('/')}/v1/realtime/client_secrets" + headers = { + "Authorization": f"Bearer {api_key}", + "Content-Type": "application/json", + "OpenAI-Beta": "realtime=v1", + } + + if extra_headers: + headers.update(extra_headers) + + logging_obj.pre_call( + input=request_data, + api_key="", + additional_args={ + "complete_input_dict": request_data, + "api_base": url, + "headers": headers, + }, + ) + + try: + return await async_httpx_client.post( + url=url, + headers=headers, + json=request_data, + timeout=timeout, + ) + except Exception as e: + if provider_config is not None: + raise self._handle_error( + e=e, + provider_config=provider_config, + ) + raise + + async def async_realtime_calls_handler( + self, + api_base: str, + openai_ephemeral_key: str, + sdp_body: bytes, + logging_obj: LiteLLMLoggingObj, + timeout: Union[float, httpx.Timeout], + provider_config: Optional[Any] = None, + model: Optional[str] = None, + session_config: Optional[Dict[str, Any]] = None, + extra_headers: Optional[Dict[str, Any]] = None, + client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, + api_version: Optional[str] = None, + ) -> httpx.Response: + """ + Forward POST /v1/realtime/calls (SDP exchange) to upstream provider. + + Uses provider_config (BaseRealtimeHTTPConfig) for URL construction and + header auth when available; falls back to the legacy OpenAI-style defaults. + + OpenAI's GA realtime API expects multipart/form-data with: + - sdp: the SDP offer (text) + - session: JSON string with {"type": "realtime", "model": "...", ...} + """ + if client is None or not isinstance(client, AsyncHTTPHandler): + async_httpx_client = get_async_httpx_client( + llm_provider=litellm.LlmProviders.OPENAI, + ) + else: + async_httpx_client = client + + if provider_config is not None: + url = provider_config.get_realtime_calls_url( + api_base=api_base, model=model or "", api_version=api_version + ) + headers: Dict[str, Any] = provider_config.get_realtime_calls_headers( + ephemeral_key=openai_ephemeral_key + ) + else: + url = f"{api_base.rstrip('/')}/v1/realtime/calls" + headers = { + "Authorization": f"Bearer {openai_ephemeral_key}", + } + + if extra_headers: + headers.update(extra_headers) + + # Build multipart form data: sdp + session JSON + session_data = session_config or {} + if "type" not in session_data: + session_data["type"] = "realtime" + if "model" not in session_data and model: + session_data["model"] = model + + sdp_text = sdp_body.decode("utf-8") if isinstance(sdp_body, bytes) else sdp_body + + files = { + "sdp": (None, sdp_text, "text/plain"), + "session": (None, json.dumps(session_data), "application/json"), + } + + logging_obj.pre_call( + input="realtime_sdp_offer", + api_key="", + additional_args={ + "api_base": url, + "headers": headers, + "session": session_data, + }, + ) + + try: + return await async_httpx_client.post( + url=url, + headers=headers, + files=files, + timeout=timeout, + ) + except Exception as e: + if provider_config is not None: + raise self._handle_error( + e=e, + provider_config=provider_config, + ) + raise + async def async_responses_websocket( self, model: str, @@ -4760,7 +4989,10 @@ class BaseLLMHTTPHandler: - Uses ManagedResponsesWebSocketHandler which makes HTTP streaming calls - Forwards events over the websocket connection """ - if responses_api_provider_config is None or not responses_api_provider_config.supports_native_websocket(): + if ( + responses_api_provider_config is None + or not responses_api_provider_config.supports_native_websocket() + ): from litellm.responses.streaming_iterator import ( ManagedResponsesWebSocketHandler, ) @@ -4869,10 +5101,7 @@ class BaseLLMHTTPHandler: _is_async: bool = False, fake_stream: bool = False, litellm_metadata: Optional[Dict[str, Any]] = None, - ) -> Union[ - ImageResponse, - Coroutine[Any, Any, ImageResponse], - ]: + ) -> Union[ImageResponse, Coroutine[Any, Any, ImageResponse],]: """ Handles image edit requests. @@ -5084,10 +5313,7 @@ class BaseLLMHTTPHandler: fake_stream: bool = False, litellm_metadata: Optional[Dict[str, Any]] = None, api_key: Optional[str] = None, - ) -> Union[ - ImageResponse, - Coroutine[Any, Any, ImageResponse], - ]: + ) -> Union[ImageResponse, Coroutine[Any, Any, ImageResponse],]: """ Handles image generation requests. When _is_async=True, returns a coroutine instead of making the call directly. @@ -5327,10 +5553,7 @@ class BaseLLMHTTPHandler: fake_stream: bool = False, litellm_metadata: Optional[Dict[str, Any]] = None, api_key: Optional[str] = None, - ) -> Union[ - VideoObject, - Coroutine[Any, Any, VideoObject], - ]: + ) -> Union[VideoObject, Coroutine[Any, Any, VideoObject],]: """ Handles video generation requests. When _is_async=True, returns a coroutine instead of making the call directly. @@ -5368,7 +5591,7 @@ class BaseLLMHTTPHandler: model=model, litellm_params=litellm_params, ) - + if extra_headers: headers.update(extra_headers) @@ -5378,7 +5601,11 @@ class BaseLLMHTTPHandler: litellm_params=dict(litellm_params), ) - data, files, api_base = video_generation_provider_config.transform_video_create_request( + ( + data, + files, + api_base, + ) = video_generation_provider_config.transform_video_create_request( model=model, prompt=prompt, video_create_optional_request_params=video_generation_optional_request_params, @@ -5479,7 +5706,11 @@ class BaseLLMHTTPHandler: litellm_params=dict(litellm_params), ) - data, files, api_base = video_generation_provider_config.transform_video_create_request( + ( + data, + files, + api_base, + ) = video_generation_provider_config.transform_video_create_request( model=model, prompt=prompt, api_base=api_base, @@ -5500,7 +5731,7 @@ class BaseLLMHTTPHandler: ) try: - #Use JSON when no files, otherwise use form data with files + # Use JSON when no files, otherwise use form data with files if files is None or len(files) == 0: response = await async_httpx_client.post( url=api_base, @@ -6154,7 +6385,10 @@ class BaseLLMHTTPHandler: ) # Transform the request using the provider config - url, data = video_status_provider_config.transform_video_status_retrieve_request( + ( + url, + data, + ) = video_status_provider_config.transform_video_status_retrieve_request( video_id=video_id, api_base=api_base, litellm_params=litellm_params, @@ -6188,10 +6422,12 @@ class BaseLLMHTTPHandler: headers=headers, ) - return video_status_provider_config.transform_video_status_retrieve_response( - raw_response=response, - logging_obj=logging_obj, - custom_llm_provider=custom_llm_provider, + return ( + video_status_provider_config.transform_video_status_retrieve_response( + raw_response=response, + logging_obj=logging_obj, + custom_llm_provider=custom_llm_provider, + ) ) except Exception as e: @@ -6241,7 +6477,10 @@ class BaseLLMHTTPHandler: ) # Transform the request using the provider config - url, data = video_status_provider_config.transform_video_status_retrieve_request( + ( + url, + data, + ) = video_status_provider_config.transform_video_status_retrieve_request( video_id=video_id, api_base=api_base, litellm_params=litellm_params, @@ -6274,10 +6513,12 @@ class BaseLLMHTTPHandler: url=url, headers=headers, ) - return video_status_provider_config.transform_video_status_retrieve_response( - raw_response=response, - logging_obj=logging_obj, - custom_llm_provider=custom_llm_provider, + return ( + video_status_provider_config.transform_video_status_retrieve_response( + raw_response=response, + logging_obj=logging_obj, + custom_llm_provider=custom_llm_provider, + ) ) except Exception as e: @@ -6285,7 +6526,7 @@ class BaseLLMHTTPHandler: e=e, provider_config=video_status_provider_config, ) - + ###### CONTAINER HANDLER ###### def container_create_handler( self, @@ -6325,7 +6566,7 @@ class BaseLLMHTTPHandler: headers=extra_headers or {}, api_key=litellm_params.get("api_key", None), ) - + # Add Content-Type header for JSON requests headers["Content-Type"] = "application/json" @@ -6375,7 +6616,7 @@ class BaseLLMHTTPHandler: e=e, provider_config=container_provider_config, ) - + async def async_container_create_handler( self, name: str, @@ -6401,7 +6642,7 @@ class BaseLLMHTTPHandler: headers=extra_headers or {}, api_key=litellm_params.get("api_key", None), ) - + # Add Content-Type header for JSON requests headers["Content-Type"] = "application/json" @@ -6451,7 +6692,7 @@ class BaseLLMHTTPHandler: e=e, provider_config=container_provider_config, ) - + def container_list_handler( self, container_provider_config: "BaseContainerConfig", @@ -6543,7 +6784,7 @@ class BaseLLMHTTPHandler: e=e, provider_config=container_provider_config, ) - + async def async_container_list_handler( self, container_provider_config: "BaseContainerConfig", @@ -6620,7 +6861,7 @@ class BaseLLMHTTPHandler: e=e, provider_config=container_provider_config, ) - + def container_retrieve_handler( self, container_id: str, @@ -6676,7 +6917,7 @@ class BaseLLMHTTPHandler: litellm_params=litellm_params, headers=headers, ) - + # Add any extra query parameters if extra_query: params.update(extra_query) @@ -6710,7 +6951,7 @@ class BaseLLMHTTPHandler: e=e, provider_config=container_provider_config, ) - + async def async_container_retrieve_handler( self, container_id: str, @@ -6753,7 +6994,7 @@ class BaseLLMHTTPHandler: litellm_params=litellm_params, headers=headers, ) - + # Add any extra query parameters if extra_query: params.update(extra_query) @@ -6787,7 +7028,7 @@ class BaseLLMHTTPHandler: e=e, provider_config=container_provider_config, ) - + def container_delete_handler( self, container_id: str, @@ -6843,7 +7084,7 @@ class BaseLLMHTTPHandler: litellm_params=litellm_params, headers=headers, ) - + # Add any extra query parameters if extra_query: params.update(extra_query) @@ -6877,7 +7118,7 @@ class BaseLLMHTTPHandler: e=e, provider_config=container_provider_config, ) - + async def async_container_delete_handler( self, container_id: str, @@ -6920,7 +7161,7 @@ class BaseLLMHTTPHandler: litellm_params=litellm_params, headers=headers, ) - + # Add any extra query parameters if extra_query: params.update(extra_query) @@ -6969,7 +7210,9 @@ class BaseLLMHTTPHandler: timeout: Union[float, httpx.Timeout] = 600, _is_async: bool = False, client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, - ) -> Union["ContainerFileListResponse", Coroutine[Any, Any, "ContainerFileListResponse"]]: + ) -> Union[ + "ContainerFileListResponse", Coroutine[Any, Any, "ContainerFileListResponse"] + ]: if _is_async: return self.async_container_file_list_handler( container_id=container_id, @@ -7176,7 +7419,10 @@ class BaseLLMHTTPHandler: ) # Transform the request using the provider config - url, params = container_provider_config.transform_container_file_content_request( + ( + url, + params, + ) = container_provider_config.transform_container_file_content_request( container_id=container_id, file_id=file_id, api_base=api_base, @@ -7249,7 +7495,10 @@ class BaseLLMHTTPHandler: ) # Transform the request using the provider config - url, params = container_provider_config.transform_container_file_content_request( + ( + url, + params, + ) = container_provider_config.transform_container_file_content_request( container_id=container_id, file_id=file_id, api_base=api_base, @@ -7323,7 +7572,9 @@ class BaseLLMHTTPHandler: ) # Check if provider has async transform method - if hasattr(vector_store_provider_config, "atransform_search_vector_store_request"): + if hasattr( + vector_store_provider_config, "atransform_search_vector_store_request" + ): ( url, request_body, @@ -7371,7 +7622,6 @@ class BaseLLMHTTPHandler: ) try: - response = await async_httpx_client.post( url=url, headers=headers, @@ -7625,6 +7875,536 @@ class BaseLLMHTTPHandler: response=response, ) + async def async_vector_store_retrieve_handler( + self, + vector_store_id: str, + vector_store_provider_config: BaseVectorStoreConfig, + custom_llm_provider: str, + litellm_params: GenericLiteLLMParams, + logging_obj: LiteLLMLoggingObj, + extra_headers: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, + ) -> VectorStoreCreateResponse: + if client is None or not isinstance(client, AsyncHTTPHandler): + async_httpx_client = get_async_httpx_client( + llm_provider=litellm.LlmProviders(custom_llm_provider), + params={"ssl_verify": litellm_params.get("ssl_verify", None)}, + ) + else: + async_httpx_client = client + + headers = vector_store_provider_config.validate_environment( + headers=extra_headers or {}, litellm_params=litellm_params + ) + + if extra_headers: + headers.update(extra_headers) + + api_base = vector_store_provider_config.get_complete_url( + api_base=litellm_params.api_base, + litellm_params=dict(litellm_params), + ) + + url = f"{api_base}/{vector_store_id}" + + logging_obj.pre_call( + input="", + api_key="", + additional_args={ + "api_base": api_base, + "headers": headers, + }, + ) + + try: + response = await async_httpx_client.get(url=url, headers=headers) + except Exception as e: + raise self._handle_error(e=e, provider_config=vector_store_provider_config) + + return vector_store_provider_config.transform_create_vector_store_response( + response=response, + ) + + def vector_store_retrieve_handler( + self, + vector_store_id: str, + vector_store_provider_config: BaseVectorStoreConfig, + custom_llm_provider: str, + litellm_params: GenericLiteLLMParams, + logging_obj: LiteLLMLoggingObj, + extra_headers: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, + _is_async: bool = False, + ) -> Union[ + VectorStoreCreateResponse, Coroutine[Any, Any, VectorStoreCreateResponse] + ]: + if _is_async: + return self.async_vector_store_retrieve_handler( + vector_store_id=vector_store_id, + vector_store_provider_config=vector_store_provider_config, + litellm_params=litellm_params, + logging_obj=logging_obj, + custom_llm_provider=custom_llm_provider, + extra_headers=extra_headers, + extra_body=extra_body, + timeout=timeout, + client=client, + ) + + if client is None or not isinstance(client, HTTPHandler): + sync_httpx_client = _get_httpx_client( + params={"ssl_verify": litellm_params.get("ssl_verify", None)} + ) + else: + sync_httpx_client = client + + headers = vector_store_provider_config.validate_environment( + headers=extra_headers or {}, litellm_params=litellm_params + ) + + if extra_headers: + headers.update(extra_headers) + + api_base = vector_store_provider_config.get_complete_url( + api_base=litellm_params.api_base, + litellm_params=dict(litellm_params), + ) + + url = f"{api_base}/{vector_store_id}" + + logging_obj.pre_call( + input="", + api_key="", + additional_args={ + "api_base": api_base, + "headers": headers, + }, + ) + + try: + response = sync_httpx_client.get(url=url, headers=headers) + except Exception as e: + raise self._handle_error(e=e, provider_config=vector_store_provider_config) + + return vector_store_provider_config.transform_create_vector_store_response( + response=response, + ) + + async def async_vector_store_list_handler( + self, + after: Optional[str], + before: Optional[str], + limit: Optional[int], + order: Optional[str], + vector_store_provider_config: BaseVectorStoreConfig, + custom_llm_provider: str, + litellm_params: GenericLiteLLMParams, + logging_obj: LiteLLMLoggingObj, + extra_headers: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, + ): + if client is None or not isinstance(client, AsyncHTTPHandler): + async_httpx_client = get_async_httpx_client( + llm_provider=litellm.LlmProviders(custom_llm_provider), + params={"ssl_verify": litellm_params.get("ssl_verify", None)}, + ) + else: + async_httpx_client = client + + headers = vector_store_provider_config.validate_environment( + headers=extra_headers or {}, litellm_params=litellm_params + ) + + if extra_headers: + headers.update(extra_headers) + + api_base = vector_store_provider_config.get_complete_url( + api_base=litellm_params.api_base, + litellm_params=dict(litellm_params), + ) + + url = api_base + + params: Dict[str, Any] = {} + if after is not None: + params["after"] = after + if before is not None: + params["before"] = before + if limit is not None: + params["limit"] = limit + if order is not None: + params["order"] = order + + logging_obj.pre_call( + input="", + api_key="", + additional_args={ + "api_base": api_base, + "headers": headers, + "params": params, + }, + ) + + try: + response = await async_httpx_client.get( + url=url, headers=headers, params=params + ) + except Exception as e: + raise self._handle_error(e=e, provider_config=vector_store_provider_config) + + return response.json() + + def vector_store_list_handler( + self, + after: Optional[str], + before: Optional[str], + limit: Optional[int], + order: Optional[str], + vector_store_provider_config: BaseVectorStoreConfig, + custom_llm_provider: str, + litellm_params: GenericLiteLLMParams, + logging_obj: LiteLLMLoggingObj, + extra_headers: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, + _is_async: bool = False, + ): + if _is_async: + return self.async_vector_store_list_handler( + after=after, + before=before, + limit=limit, + order=order, + vector_store_provider_config=vector_store_provider_config, + litellm_params=litellm_params, + logging_obj=logging_obj, + custom_llm_provider=custom_llm_provider, + extra_headers=extra_headers, + extra_body=extra_body, + timeout=timeout, + client=client, + ) + + if client is None or not isinstance(client, HTTPHandler): + sync_httpx_client = _get_httpx_client( + params={"ssl_verify": litellm_params.get("ssl_verify", None)} + ) + else: + sync_httpx_client = client + + headers = vector_store_provider_config.validate_environment( + headers=extra_headers or {}, litellm_params=litellm_params + ) + + if extra_headers: + headers.update(extra_headers) + + api_base = vector_store_provider_config.get_complete_url( + api_base=litellm_params.api_base, + litellm_params=dict(litellm_params), + ) + + url = api_base + + params: Dict[str, Any] = {} + if after is not None: + params["after"] = after + if before is not None: + params["before"] = before + if limit is not None: + params["limit"] = limit + if order is not None: + params["order"] = order + + logging_obj.pre_call( + input="", + api_key="", + additional_args={ + "api_base": api_base, + "headers": headers, + "params": params, + }, + ) + + try: + response = sync_httpx_client.get(url=url, headers=headers, params=params) + except Exception as e: + raise self._handle_error(e=e, provider_config=vector_store_provider_config) + + return response.json() + + async def async_vector_store_update_handler( + self, + vector_store_id: str, + vector_store_update_optional_params: VectorStoreCreateOptionalRequestParams, + vector_store_provider_config: BaseVectorStoreConfig, + custom_llm_provider: str, + litellm_params: GenericLiteLLMParams, + logging_obj: LiteLLMLoggingObj, + extra_headers: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, + ) -> VectorStoreCreateResponse: + if client is None or not isinstance(client, AsyncHTTPHandler): + async_httpx_client = get_async_httpx_client( + llm_provider=litellm.LlmProviders(custom_llm_provider), + params={"ssl_verify": litellm_params.get("ssl_verify", None)}, + ) + else: + async_httpx_client = client + + headers = vector_store_provider_config.validate_environment( + headers=extra_headers or {}, litellm_params=litellm_params + ) + + if extra_headers: + headers.update(extra_headers) + + api_base = vector_store_provider_config.get_complete_url( + api_base=litellm_params.api_base, + litellm_params=dict(litellm_params), + ) + + url = f"{api_base}/{vector_store_id}" + + request_body: Dict[str, Any] = dict(vector_store_update_optional_params) + + # Clean metadata to only include string values (OpenAI requirement) + if "metadata" in request_body and request_body["metadata"] is not None: + from litellm.utils import add_openai_metadata + + request_body["metadata"] = add_openai_metadata(request_body["metadata"]) + + if extra_body: + request_body.update(extra_body) + + logging_obj.pre_call( + input="", + api_key="", + additional_args={ + "complete_input_dict": request_body, + "api_base": api_base, + "headers": headers, + }, + ) + + try: + response = await async_httpx_client.post( + url=url, headers=headers, json=request_body, timeout=timeout + ) + except Exception as e: + raise self._handle_error(e=e, provider_config=vector_store_provider_config) + + return vector_store_provider_config.transform_create_vector_store_response( + response=response, + ) + + def vector_store_update_handler( + self, + vector_store_id: str, + vector_store_update_optional_params: VectorStoreCreateOptionalRequestParams, + vector_store_provider_config: BaseVectorStoreConfig, + custom_llm_provider: str, + litellm_params: GenericLiteLLMParams, + logging_obj: LiteLLMLoggingObj, + extra_headers: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, + _is_async: bool = False, + ) -> Union[ + VectorStoreCreateResponse, Coroutine[Any, Any, VectorStoreCreateResponse] + ]: + if _is_async: + return self.async_vector_store_update_handler( + vector_store_id=vector_store_id, + vector_store_update_optional_params=vector_store_update_optional_params, + vector_store_provider_config=vector_store_provider_config, + litellm_params=litellm_params, + logging_obj=logging_obj, + custom_llm_provider=custom_llm_provider, + extra_headers=extra_headers, + extra_body=extra_body, + timeout=timeout, + client=client, + ) + + if client is None or not isinstance(client, HTTPHandler): + sync_httpx_client = _get_httpx_client( + params={"ssl_verify": litellm_params.get("ssl_verify", None)} + ) + else: + sync_httpx_client = client + + headers = vector_store_provider_config.validate_environment( + headers=extra_headers or {}, litellm_params=litellm_params + ) + + if extra_headers: + headers.update(extra_headers) + + api_base = vector_store_provider_config.get_complete_url( + api_base=litellm_params.api_base, + litellm_params=dict(litellm_params), + ) + + url = f"{api_base}/{vector_store_id}" + + request_body: Dict[str, Any] = dict(vector_store_update_optional_params) + + # Clean metadata to only include string values (OpenAI requirement) + if "metadata" in request_body and request_body["metadata"] is not None: + from litellm.utils import add_openai_metadata + + request_body["metadata"] = add_openai_metadata(request_body["metadata"]) + + if extra_body: + request_body.update(extra_body) + + logging_obj.pre_call( + input="", + api_key="", + additional_args={ + "complete_input_dict": request_body, + "api_base": api_base, + "headers": headers, + }, + ) + + try: + response = sync_httpx_client.post( + url=url, headers=headers, json=request_body + ) + except Exception as e: + raise self._handle_error(e=e, provider_config=vector_store_provider_config) + + return vector_store_provider_config.transform_create_vector_store_response( + response=response, + ) + + async def async_vector_store_delete_handler( + self, + vector_store_id: str, + vector_store_provider_config: BaseVectorStoreConfig, + custom_llm_provider: str, + litellm_params: GenericLiteLLMParams, + logging_obj: LiteLLMLoggingObj, + extra_headers: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, + ): + if client is None or not isinstance(client, AsyncHTTPHandler): + async_httpx_client = get_async_httpx_client( + llm_provider=litellm.LlmProviders(custom_llm_provider), + params={"ssl_verify": litellm_params.get("ssl_verify", None)}, + ) + else: + async_httpx_client = client + + headers = vector_store_provider_config.validate_environment( + headers=extra_headers or {}, litellm_params=litellm_params + ) + + if extra_headers: + headers.update(extra_headers) + + api_base = vector_store_provider_config.get_complete_url( + api_base=litellm_params.api_base, + litellm_params=dict(litellm_params), + ) + + url = f"{api_base}/{vector_store_id}" + + logging_obj.pre_call( + input="", + api_key="", + additional_args={ + "api_base": api_base, + "headers": headers, + }, + ) + + try: + response = await async_httpx_client.delete( + url=url, headers=headers, timeout=timeout + ) + except Exception as e: + raise self._handle_error(e=e, provider_config=vector_store_provider_config) + + return response.json() + + def vector_store_delete_handler( + self, + vector_store_id: str, + vector_store_provider_config: BaseVectorStoreConfig, + custom_llm_provider: str, + litellm_params: GenericLiteLLMParams, + logging_obj: LiteLLMLoggingObj, + extra_headers: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, + _is_async: bool = False, + ): + if _is_async: + return self.async_vector_store_delete_handler( + vector_store_id=vector_store_id, + vector_store_provider_config=vector_store_provider_config, + litellm_params=litellm_params, + logging_obj=logging_obj, + custom_llm_provider=custom_llm_provider, + extra_headers=extra_headers, + extra_body=extra_body, + timeout=timeout, + client=client, + ) + + if client is None or not isinstance(client, HTTPHandler): + sync_httpx_client = _get_httpx_client( + params={"ssl_verify": litellm_params.get("ssl_verify", None)} + ) + else: + sync_httpx_client = client + + headers = vector_store_provider_config.validate_environment( + headers=extra_headers or {}, litellm_params=litellm_params + ) + + if extra_headers: + headers.update(extra_headers) + + api_base = vector_store_provider_config.get_complete_url( + api_base=litellm_params.api_base, + litellm_params=dict(litellm_params), + ) + + url = f"{api_base}/{vector_store_id}" + + logging_obj.pre_call( + input="", + api_key="", + additional_args={ + "api_base": api_base, + "headers": headers, + }, + ) + + try: + response = sync_httpx_client.delete(url=url, headers=headers) + except Exception as e: + raise self._handle_error(e=e, provider_config=vector_store_provider_config) + + return response.json() + ##################################################################### ################ Vector Store Files HANDLERS ######################## ##################################################################### @@ -7973,12 +8753,13 @@ class BaseLLMHTTPHandler: litellm_params=dict(litellm_params), ) - url, request_params = ( - vector_store_files_provider_config.transform_retrieve_vector_store_file_request( - vector_store_id=vector_store_id, - file_id=file_id, - api_base=api_base, - ) + ( + url, + request_params, + ) = vector_store_files_provider_config.transform_retrieve_vector_store_file_request( + vector_store_id=vector_store_id, + file_id=file_id, + api_base=api_base, ) logging_obj.pre_call( @@ -8050,12 +8831,13 @@ class BaseLLMHTTPHandler: litellm_params=dict(litellm_params), ) - url, request_params = ( - vector_store_files_provider_config.transform_retrieve_vector_store_file_request( - vector_store_id=vector_store_id, - file_id=file_id, - api_base=api_base, - ) + ( + url, + request_params, + ) = vector_store_files_provider_config.transform_retrieve_vector_store_file_request( + vector_store_id=vector_store_id, + file_id=file_id, + api_base=api_base, ) logging_obj.pre_call( @@ -8114,12 +8896,13 @@ class BaseLLMHTTPHandler: litellm_params=dict(litellm_params), ) - url, request_params = ( - vector_store_files_provider_config.transform_retrieve_vector_store_file_content_request( - vector_store_id=vector_store_id, - file_id=file_id, - api_base=api_base, - ) + ( + url, + request_params, + ) = vector_store_files_provider_config.transform_retrieve_vector_store_file_content_request( + vector_store_id=vector_store_id, + file_id=file_id, + api_base=api_base, ) logging_obj.pre_call( @@ -8194,12 +8977,13 @@ class BaseLLMHTTPHandler: litellm_params=dict(litellm_params), ) - url, request_params = ( - vector_store_files_provider_config.transform_retrieve_vector_store_file_content_request( - vector_store_id=vector_store_id, - file_id=file_id, - api_base=api_base, - ) + ( + url, + request_params, + ) = vector_store_files_provider_config.transform_retrieve_vector_store_file_content_request( + vector_store_id=vector_store_id, + file_id=file_id, + api_base=api_base, ) logging_obj.pre_call( @@ -8417,12 +9201,13 @@ class BaseLLMHTTPHandler: litellm_params=dict(litellm_params), ) - url, request_params = ( - vector_store_files_provider_config.transform_delete_vector_store_file_request( - vector_store_id=vector_store_id, - file_id=file_id, - api_base=api_base, - ) + ( + url, + request_params, + ) = vector_store_files_provider_config.transform_delete_vector_store_file_request( + vector_store_id=vector_store_id, + file_id=file_id, + api_base=api_base, ) logging_obj.pre_call( @@ -8497,12 +9282,13 @@ class BaseLLMHTTPHandler: litellm_params=dict(litellm_params), ) - url, request_params = ( - vector_store_files_provider_config.transform_delete_vector_store_file_request( - vector_store_id=vector_store_id, - file_id=file_id, - api_base=api_base, - ) + ( + url, + request_params, + ) = vector_store_files_provider_config.transform_delete_vector_store_file_request( + vector_store_id=vector_store_id, + file_id=file_id, + api_base=api_base, ) logging_obj.pre_call( @@ -8998,29 +9784,29 @@ class BaseLLMHTTPHandler: ) -> tuple[Optional[Dict], Optional[list]]: """ Helper to prepare multipart/form-data request for skills API. - + Args: request_body: Request body containing files and other fields headers: Request headers - + Returns: Tuple of (data_dict, files_list) for multipart request, or (None, None) if no files """ if "files" not in request_body or not request_body["files"]: return None, None - + # Remove content-type header if present - httpx will set it automatically for multipart if "content-type" in headers: del headers["content-type"] - + # Prepare files for multipart upload files = [] for file_obj in request_body["files"]: files.append(("files[]", file_obj)) - + # Prepare data (non-file fields) data = {k: v for k, v in request_body.items() if k != "files"} - + return data, files def create_skill_handler( @@ -9076,7 +9862,7 @@ class BaseLLMHTTPHandler: data, files = self._prepare_skill_multipart_request( request_body=request_body, headers=headers ) - + if files is not None: response = sync_httpx_client.post( url=url, headers=headers, data=data, files=files, timeout=timeout @@ -9136,7 +9922,7 @@ class BaseLLMHTTPHandler: data, files = self._prepare_skill_multipart_request( request_body=request_body, headers=headers ) - + if files is not None: response = await async_httpx_client.post( url=url, headers=headers, data=data, files=files, timeout=timeout @@ -9360,9 +10146,7 @@ class BaseLLMHTTPHandler: ) try: - response = await async_httpx_client.get( - url=url, headers=headers - ) + response = await async_httpx_client.get(url=url, headers=headers) except Exception as e: raise self._handle_error( e=e, @@ -9800,9 +10584,7 @@ class BaseLLMHTTPHandler: ) try: - response = await async_httpx_client.get( - url=url, headers=headers - ) + response = await async_httpx_client.get(url=url, headers=headers) except Exception as e: raise self._handle_error( e=e, @@ -10459,9 +11241,7 @@ class BaseLLMHTTPHandler: ) try: - response = await async_httpx_client.get( - url=url, headers=headers - ) + response = await async_httpx_client.get(url=url, headers=headers) except Exception as e: raise self._handle_error( e=e, diff --git a/litellm/llms/custom_httpx/mock_transport.py b/litellm/llms/custom_httpx/mock_transport.py index 262d0dff12d..c9844753e0e 100644 --- a/litellm/llms/custom_httpx/mock_transport.py +++ b/litellm/llms/custom_httpx/mock_transport.py @@ -18,6 +18,7 @@ import httpx # Pre-built response templates # --------------------------------------------------------------------------- + def _mock_id() -> str: return f"chatcmpl-mock-{uuid.uuid4().hex[:8]}" diff --git a/litellm/llms/databricks/chat/transformation.py b/litellm/llms/databricks/chat/transformation.py index 7c2a9569c58..8ae02bd65ed 100644 --- a/litellm/llms/databricks/chat/transformation.py +++ b/litellm/llms/databricks/chat/transformation.py @@ -60,6 +60,7 @@ from ...anthropic.chat.transformation import AnthropicConfig from ...openai_like.chat.transformation import OpenAILikeChatConfig from ..common_utils import DatabricksBase, DatabricksException + def _sanitize_empty_content(message_dict: dict[str, Any]) -> None: """ Remove or filter content so empty text blocks are not sent. @@ -330,8 +331,7 @@ class DatabricksConfig(DatabricksBase, OpenAILikeChatConfig, AnthropicConfig): if "reasoning_effort" in non_default_params and "claude" in model: optional_params["thinking"] = AnthropicConfig._map_reasoning_effort( - reasoning_effort=non_default_params.get("reasoning_effort"), - model=model + reasoning_effort=non_default_params.get("reasoning_effort"), model=model ) optional_params.pop("reasoning_effort", None) ## handle thinking tokens diff --git a/litellm/llms/dataforseo/search/__init__.py b/litellm/llms/dataforseo/search/__init__.py index 28990c1af3e..66f16d1e03a 100644 --- a/litellm/llms/dataforseo/search/__init__.py +++ b/litellm/llms/dataforseo/search/__init__.py @@ -8,4 +8,3 @@ DataForSEO offers comprehensive search engine data with high accuracy. from .transformation import DataForSEOSearchConfig __all__ = ["DataForSEOSearchConfig"] - diff --git a/litellm/llms/dataforseo/search/transformation.py b/litellm/llms/dataforseo/search/transformation.py index 86b472f61b8..940f1ca6007 100644 --- a/litellm/llms/dataforseo/search/transformation.py +++ b/litellm/llms/dataforseo/search/transformation.py @@ -20,23 +20,25 @@ from litellm.secret_managers.main import get_secret_str class DataForSEOSearchConfig(BaseSearchConfig): """ Configuration for DataForSEO SERP API search. - + DataForSEO uses HTTP Basic Auth with login:password credentials. API endpoint: https://api.dataforseo.com/v3/serp/google/organic/live/advanced """ - - DATAFORSEO_API_BASE = "https://api.dataforseo.com/v3/serp/google/organic/live/advanced" - + + DATAFORSEO_API_BASE = ( + "https://api.dataforseo.com/v3/serp/google/organic/live/advanced" + ) + @staticmethod def ui_friendly_name() -> str: return "DataForSEO" - + def get_http_method(self) -> Literal["GET", "POST"]: """ DataForSEO uses POST requests with JSON body. """ return "POST" - + def validate_environment( self, headers: Dict, @@ -46,7 +48,7 @@ class DataForSEOSearchConfig(BaseSearchConfig): ) -> Dict: """ Validate DataForSEO environment and set up authentication. - + DataForSEO uses HTTP Basic Auth with login:password format. The credentials should be in DATAFORSEO_LOGIN and DATAFORSEO_PASSWORD env vars, or passed as api_key in "login:password" format. @@ -56,23 +58,27 @@ class DataForSEOSearchConfig(BaseSearchConfig): # Get login and password login = get_secret_str("DATAFORSEO_LOGIN") password = get_secret_str("DATAFORSEO_PASSWORD") - + # If api_key is provided in "login:password" format, use it if api_key and ":" in api_key: login, password = api_key.split(":", 1) - + if not login: - raise ValueError("DATAFORSEO_LOGIN is not set. Set `DATAFORSEO_LOGIN` environment variable or pass credentials in api_key parameter.") - + raise ValueError( + "DATAFORSEO_LOGIN is not set. Set `DATAFORSEO_LOGIN` environment variable or pass credentials in api_key parameter." + ) + if not password: - raise ValueError("DATAFORSEO_PASSWORD is not set. Set `DATAFORSEO_PASSWORD` environment variable or pass credentials in api_key parameter.") - + raise ValueError( + "DATAFORSEO_PASSWORD is not set. Set `DATAFORSEO_PASSWORD` environment variable or pass credentials in api_key parameter." + ) + # Create Basic Auth header credentials = f"{login}:{password}" encoded_credentials = base64.b64encode(credentials.encode()).decode() headers["Authorization"] = f"Basic {encoded_credentials}" headers["Content-Type"] = "application/json" - + return headers def get_complete_url( @@ -84,10 +90,14 @@ class DataForSEOSearchConfig(BaseSearchConfig): ) -> str: """ Get complete URL for DataForSEO SERP API endpoint. - + DataForSEO uses POST requests, so no query parameters in URL. """ - return api_base or get_secret_str("DATAFORSEO_API_BASE") or self.DATAFORSEO_API_BASE + return ( + api_base + or get_secret_str("DATAFORSEO_API_BASE") + or self.DATAFORSEO_API_BASE + ) def transform_search_request( self, @@ -98,7 +108,7 @@ class DataForSEOSearchConfig(BaseSearchConfig): ) -> Union[Dict, List[Dict]]: """ Transform Search request to DataForSEO SERP API format. - + Args: query: Search query (string or list of strings). DataForSEO supports single string queries. optional_params: Optional parameters for the request @@ -107,48 +117,54 @@ class DataForSEOSearchConfig(BaseSearchConfig): - search_domain_filter: Domain to filter results → maps to `domain` - Plus any DataForSEO-specific parameters (location_code, language_code, device, os, etc.) api_key: DataForSEO credentials (login:password format) - + Returns: List[Dict]: Request body for DataForSEO API (array of task objects as required by API) """ # DataForSEO expects an array of task objects task: Dict[str, Any] = {} - + # Convert query to string if it's a list if isinstance(query, list): query = query[0] if query else "" - + # Required field: keyword task["keyword"] = query - + # Map unified parameters to DataForSEO parameters if "max_results" in optional_params and optional_params["max_results"]: # DataForSEO uses 'depth' for number of results (max 700) depth = min(int(optional_params["max_results"]), 700) task["depth"] = depth - + if "country" in optional_params and optional_params["country"]: # DataForSEO uses location_code (e.g., 2840 for USA) # For simplicity, we'll use location_name which accepts country names task["location_name"] = optional_params["country"] - - if "search_domain_filter" in optional_params and optional_params["search_domain_filter"]: + + if ( + "search_domain_filter" in optional_params + and optional_params["search_domain_filter"] + ): # DataForSEO uses 'domain' parameter to filter by domain task["domain"] = optional_params["search_domain_filter"] - + # Add defaults if not specified if "language_code" not in task and "language_name" not in task: task["language_code"] = "en" - + # DataForSEO requires a location - use default from constants if not specified if "location_code" not in task and "location_name" not in task: task["location_code"] = DEFAULT_DATAFORSEO_LOCATION_CODE - + # Pass through all other parameters as-is for param, value in optional_params.items(): - if param not in self.get_supported_perplexity_optional_params() and param not in task: + if ( + param not in self.get_supported_perplexity_optional_params() + and param not in task + ): task[param] = value - + # DataForSEO API expects an array of tasks return [task] @@ -160,35 +176,35 @@ class DataForSEOSearchConfig(BaseSearchConfig): ) -> SearchResponse: """ Transform DataForSEO SERP API response to LiteLLM unified SearchResponse format. - + DataForSEO → LiteLLM mappings: - tasks[0].result[*].items[*].title → SearchResult.title - tasks[0].result[*].items[*].url → SearchResult.url - tasks[0].result[*].items[*].description → SearchResult.snippet - No date/last_updated fields in standard response (set to None) - + Args: raw_response: Raw httpx response from DataForSEO API logging_obj: Logging object for tracking - + Returns: SearchResponse with standardized format """ response_json = raw_response.json() - + # Transform results to SearchResult objects results = [] - + # DataForSEO wraps results in tasks array if "tasks" in response_json and len(response_json["tasks"]) > 0: task = response_json["tasks"][0] - + # Check if task was successful if task.get("status_code") == 20000 and "result" in task: # Result is an array, take first element if len(task["result"]) > 0: result = task["result"][0] - + # Items contain the actual search results for item in result.get("items", []): # Only process organic search results @@ -201,9 +217,8 @@ class DataForSEOSearchConfig(BaseSearchConfig): last_updated=None, ) results.append(search_result) - + return SearchResponse( results=results, object="search", ) - diff --git a/litellm/llms/deepinfra/chat/transformation.py b/litellm/llms/deepinfra/chat/transformation.py index 5198260a24b..c36b490abca 100644 --- a/litellm/llms/deepinfra/chat/transformation.py +++ b/litellm/llms/deepinfra/chat/transformation.py @@ -14,6 +14,7 @@ class DeepInfraConfig(OpenAIGPTConfig): The class `DeepInfra` provides configuration for the DeepInfra's Chat Completions API interface. Below are the parameters: """ + @property def custom_llm_provider(self) -> Optional[str]: return "deepinfra" @@ -73,7 +74,7 @@ class DeepInfraConfig(OpenAIGPTConfig): "top_p", "response_format", "tools", - "tool_choice" + "tool_choice", ] if litellm.supports_reasoning( @@ -119,17 +120,19 @@ class DeepInfraConfig(OpenAIGPTConfig): optional_params[param] = value return optional_params - def _transform_tool_message_content(self, messages: List[AllMessageValues]) -> List[AllMessageValues]: + def _transform_tool_message_content( + self, messages: List[AllMessageValues] + ) -> List[AllMessageValues]: """ Transform tool message content from array to string format for DeepInfra compatibility. - + DeepInfra requires tool message content to be a string, not an array. This method converts tool message content from array format to string format. - + Example transformation: - Input: {"role": "tool", "content": [{"type": "text", "text": "20"}]} - Output: {"role": "tool", "content": "20"} - + Or if content is complex: - Input: {"role": "tool", "content": [{"type": "text", "text": "result"}]} - Output: {"role": "tool", "content": "[{\"type\": \"text\", \"text\": \"result\"}]"} @@ -137,13 +140,13 @@ class DeepInfraConfig(OpenAIGPTConfig): for message in messages: if message.get("role") == "tool": content = message.get("content") - + # If content is a list/array, convert it to string if isinstance(content, list): # Check if it's a simple single text item if ( - len(content) == 1 - and isinstance(content[0], dict) + len(content) == 1 + and isinstance(content[0], dict) and content[0].get("type") == "text" and "text" in content[0] ): @@ -152,7 +155,7 @@ class DeepInfraConfig(OpenAIGPTConfig): else: # For complex content, serialize the entire array as JSON string message["content"] = json.dumps(content) - + return messages @overload @@ -163,7 +166,10 @@ class DeepInfraConfig(OpenAIGPTConfig): @overload def _transform_messages( - self, messages: List[AllMessageValues], model: str, is_async: Literal[False] = False + self, + messages: List[AllMessageValues], + model: str, + is_async: Literal[False] = False, ) -> List[AllMessageValues]: ... @@ -183,6 +189,7 @@ class DeepInfraConfig(OpenAIGPTConfig): ) transformed_messages = await parent_result return self._transform_tool_message_content(transformed_messages) + return _async_transform() else: # Call parent with is_async=False (literal) for sync case diff --git a/litellm/llms/deepinfra/rerank/transformation.py b/litellm/llms/deepinfra/rerank/transformation.py index 47f47418cb2..71e300d258c 100644 --- a/litellm/llms/deepinfra/rerank/transformation.py +++ b/litellm/llms/deepinfra/rerank/transformation.py @@ -29,8 +29,8 @@ class DeepinfraRerankConfig(BaseRerankConfig): """ def get_complete_url( - self, - api_base: Optional[str], + self, + api_base: Optional[str], model: str, optional_params: Optional[dict] = None, ) -> str: diff --git a/litellm/llms/docker_model_runner/chat/transformation.py b/litellm/llms/docker_model_runner/chat/transformation.py index 3d84b24a01c..4b81502bf81 100644 --- a/litellm/llms/docker_model_runner/chat/transformation.py +++ b/litellm/llms/docker_model_runner/chat/transformation.py @@ -18,7 +18,7 @@ from ...openai.chat.gpt_transformation import OpenAIGPTConfig class DockerModelRunnerChatConfig(OpenAIGPTConfig): """ Configuration for Docker Model Runner API. - + Docker Model Runner uses URLs in the format: /engines/{engine}/v1/chat/completions The engine name (e.g., "llama.cpp") is part of the API endpoint path. """ @@ -59,7 +59,7 @@ class DockerModelRunnerChatConfig(OpenAIGPTConfig): ) -> Tuple[Optional[str], Optional[str]]: """ Get API base and key for Docker Model Runner. - + Default API base: http://localhost:22088/engines/llama.cpp The engine path should be included in the api_base. """ @@ -69,7 +69,9 @@ class DockerModelRunnerChatConfig(OpenAIGPTConfig): or "http://localhost:22088/engines/llama.cpp" ) # type: ignore # Docker Model Runner may not require authentication for local instances - dynamic_api_key = api_key or get_secret_str("DOCKER_MODEL_RUNNER_API_KEY") or "dummy-key" + dynamic_api_key = ( + api_key or get_secret_str("DOCKER_MODEL_RUNNER_API_KEY") or "dummy-key" + ) return api_base, dynamic_api_key def get_complete_url( @@ -83,13 +85,13 @@ class DockerModelRunnerChatConfig(OpenAIGPTConfig): ) -> str: """ Build the complete URL for Docker Model Runner API. - + Docker Model Runner uses URLs in the format: /engines/{engine}/v1/chat/completions - + The engine name should be specified in the api_base: - api_base="http://model-runner.docker.internal/engines/llama.cpp" - Default: "http://localhost:22088/engines/llama.cpp" - + Args: api_base: Base URL for the Docker Model Runner instance including engine path api_key: API key (may not be required for local instances) @@ -97,26 +99,26 @@ class DockerModelRunnerChatConfig(OpenAIGPTConfig): optional_params: Optional parameters litellm_params: LiteLLM parameters stream: Whether streaming is enabled - + Returns: Complete URL for the API call """ if not api_base: api_base = "http://localhost:22088/engines/llama.cpp" - + # Remove trailing slashes from api_base api_base = api_base.rstrip("/") - + # Build the URL: {api_base}/v1/chat/completions # api_base is expected to already contain the engine path complete_url = f"{api_base}/v1/chat/completions" - + return complete_url def get_supported_openai_params(self, model: str) -> list: """ Get the supported OpenAI params for Docker Model Runner. - + Docker Model Runner is OpenAI-compatible and supports standard parameters. """ return super().get_supported_openai_params(model=model) @@ -130,7 +132,7 @@ class DockerModelRunnerChatConfig(OpenAIGPTConfig): ) -> dict: """ Map OpenAI parameters to Docker Model Runner parameters. - + Docker Model Runner is OpenAI-compatible, so most parameters map directly. """ supported_openai_params = self.get_supported_openai_params(model) @@ -141,4 +143,3 @@ class DockerModelRunnerChatConfig(OpenAIGPTConfig): optional_params[param] = value return optional_params - diff --git a/litellm/llms/duckduckgo/search/transformation.py b/litellm/llms/duckduckgo/search/transformation.py index 509d69041fb..c754338153a 100644 --- a/litellm/llms/duckduckgo/search/transformation.py +++ b/litellm/llms/duckduckgo/search/transformation.py @@ -19,6 +19,7 @@ from litellm.secret_managers.main import get_secret_str class _DuckDuckGoSearchRequestRequired(TypedDict): """Required fields for DuckDuckGo Search API request.""" + q: str # Required - search query @@ -27,6 +28,7 @@ class DuckDuckGoSearchRequest(_DuckDuckGoSearchRequestRequired, total=False): DuckDuckGo Instant Answer API request format. Based on: https://duckduckgo.com/api """ + format: str # Optional - output format ('json', 'xml'), default 'json' pretty: int # Optional - pretty print (0 or 1), default 1 no_redirect: int # Optional - skip HTTP redirects (0 or 1), default 0 @@ -36,21 +38,21 @@ class DuckDuckGoSearchRequest(_DuckDuckGoSearchRequestRequired, total=False): class DuckDuckGoSearchConfig(BaseSearchConfig): DUCKDUCKGO_API_BASE = "https://api.duckduckgo.com" - + @staticmethod def ui_friendly_name() -> str: return "DuckDuckGo" - + def get_http_method(self) -> Literal["GET", "POST"]: """ Get HTTP method for search requests. DuckDuckGo Instant Answer API uses GET requests. - + Returns: HTTP method 'GET' """ return "GET" - + def validate_environment( self, headers: Dict, @@ -77,16 +79,19 @@ class DuckDuckGoSearchConfig(BaseSearchConfig): Get complete URL for Search endpoint. DuckDuckGo uses query parameters, so we construct the URL with the query. """ - api_base = api_base or get_secret_str("DUCKDUCKGO_API_BASE") or self.DUCKDUCKGO_API_BASE - + api_base = ( + api_base + or get_secret_str("DUCKDUCKGO_API_BASE") + or self.DUCKDUCKGO_API_BASE + ) + # Build query parameters from the transformed request body if data and isinstance(data, dict) and "_duckduckgo_params" in data: params = data["_duckduckgo_params"] query_string = urlencode(params, doseq=True) return f"{api_base}/?{query_string}" - + return api_base - def transform_search_request( self, @@ -96,7 +101,7 @@ class DuckDuckGoSearchConfig(BaseSearchConfig): ) -> Dict: """ Transform Search request to DuckDuckGo API format. - + Args: query: Search query (string or list of strings). DuckDuckGo only supports single string queries. optional_params: Optional parameters for the request @@ -106,7 +111,7 @@ class DuckDuckGoSearchConfig(BaseSearchConfig): - no_redirect: Skip HTTP redirects (0 or 1) - no_html: Remove HTML from text (0 or 1) - skip_disambig: Skip disambiguation results (0 or 1) - + Returns: Dict with typed request data following DuckDuckGoSearchRequest spec """ @@ -118,19 +123,19 @@ class DuckDuckGoSearchConfig(BaseSearchConfig): "q": query, "format": "json", # Always use JSON format } - + # Convert to dict before dynamic key assignments result_data = dict(request_data) - + if "max_results" in optional_params: result_data["_max_results"] = optional_params["max_results"] - + # Pass through DuckDuckGo-specific parameters ddg_params = ["pretty", "no_redirect", "no_html", "skip_disambig"] for param in ddg_params: if param in optional_params: result_data[param] = optional_params[param] - + return { "_duckduckgo_params": result_data, } @@ -143,22 +148,22 @@ class DuckDuckGoSearchConfig(BaseSearchConfig): ) -> SearchResponse: """ Transform DuckDuckGo API response to LiteLLM unified SearchResponse format. - + DuckDuckGo → LiteLLM mappings: - RelatedTopics[].Text → SearchResult.title + snippet - RelatedTopics[].FirstURL → SearchResult.url - RelatedTopics[].Text → SearchResult.snippet - No date/last_updated fields in DuckDuckGo response (set to None) - + Args: raw_response: Raw httpx response from DuckDuckGo API logging_obj: Logging object for tracking - + Returns: SearchResponse with standardized format """ response_json = raw_response.json() - + # Extract max_results from the request URL params query_params = raw_response.request.url.params if raw_response.request else {} max_results = None @@ -167,13 +172,13 @@ class DuckDuckGoSearchConfig(BaseSearchConfig): max_results = int(query_params["_max_results"]) except (ValueError, TypeError): pass - + # Transform results to SearchResult objects results = [] - + # DuckDuckGo can return results in different fields # Priority: Abstract > Answer > RelatedTopics - + # Check if there's an Abstract with URL if response_json.get("AbstractURL") and response_json.get("AbstractText"): abstract_result = SearchResult( @@ -184,20 +189,20 @@ class DuckDuckGoSearchConfig(BaseSearchConfig): last_updated=None, ) results.append(abstract_result) - + # Process RelatedTopics related_topics = response_json.get("RelatedTopics", []) for topic in related_topics: # Stop if we've reached max_results if max_results is not None and len(results) >= max_results: break - + if isinstance(topic, dict): # Check if it's a direct result if "FirstURL" in topic and "Text" in topic: text = topic.get("Text", "") url = topic.get("FirstURL", "") - + # Try to split title and snippet if " - " in text: parts = text.split(" - ", 1) @@ -206,7 +211,7 @@ class DuckDuckGoSearchConfig(BaseSearchConfig): else: title = text[:50] + "..." if len(text) > 50 else text snippet = text - + search_result = SearchResult( title=title, url=url, @@ -215,7 +220,7 @@ class DuckDuckGoSearchConfig(BaseSearchConfig): last_updated=None, ) results.append(search_result) - + # Check if it contains nested topics elif "Topics" in topic: nested_topics = topic.get("Topics", []) @@ -223,11 +228,11 @@ class DuckDuckGoSearchConfig(BaseSearchConfig): # Stop if we've reached max_results if max_results is not None and len(results) >= max_results: break - + if "FirstURL" in nested_topic and "Text" in nested_topic: text = nested_topic.get("Text", "") url = nested_topic.get("FirstURL", "") - + # Try to split title and snippet if " - " in text: parts = text.split(" - ", 1) @@ -236,7 +241,7 @@ class DuckDuckGoSearchConfig(BaseSearchConfig): else: title = text[:50] + "..." if len(text) > 50 else text snippet = text - + search_result = SearchResult( title=title, url=url, @@ -245,7 +250,7 @@ class DuckDuckGoSearchConfig(BaseSearchConfig): last_updated=None, ) results.append(search_result) - + return SearchResponse( results=results, object="search", diff --git a/litellm/llms/elevenlabs/audio_transcription/transformation.py b/litellm/llms/elevenlabs/audio_transcription/transformation.py index e56e83b4dec..8746e92d9f6 100644 --- a/litellm/llms/elevenlabs/audio_transcription/transformation.py +++ b/litellm/llms/elevenlabs/audio_transcription/transformation.py @@ -66,20 +66,19 @@ class ElevenLabsAudioTranscriptionConfig(BaseAudioTranscriptionConfig): ) -> AudioTranscriptionRequestData: """ Transforms the audio transcription request for ElevenLabs API. - + Returns AudioTranscriptionRequestData with both form data and files. - + Returns: AudioTranscriptionRequestData: Structured data with form data and files """ - + # Use common utility to process the audio file processed_audio = process_audio_file(audio_file) - + # Prepare form data form_data = {"model_id": model} - ######################################################### # Add OpenAI Compatible Parameters ######################################################### @@ -87,29 +86,31 @@ class ElevenLabsAudioTranscriptionConfig(BaseAudioTranscriptionConfig): if key in self.get_supported_openai_params(model) and value is not None: # Convert values to strings for form data, but skip None values form_data[key] = str(value) - + ######################################################### # Add Provider Specific Parameters ######################################################### provider_specific_params = self.get_provider_specific_params( model=model, optional_params=optional_params, - openai_params=self.get_supported_openai_params(model) + openai_params=self.get_supported_openai_params(model), ) for key, value in provider_specific_params.items(): form_data[key] = str(value) ######################################################### ######################################################### - - # Prepare files - files = {"file": (processed_audio.filename, processed_audio.file_content, processed_audio.content_type)} - - return AudioTranscriptionRequestData( - data=form_data, - files=files - ) + # Prepare files + files = { + "file": ( + processed_audio.filename, + processed_audio.file_content, + processed_audio.content_type, + ) + } + + return AudioTranscriptionRequestData(data=form_data, files=files) def transform_audio_transcription_response( self, @@ -130,18 +131,20 @@ class ElevenLabsAudioTranscriptionConfig(BaseAudioTranscriptionConfig): # Add additional metadata matching OpenAI format response["task"] = "transcribe" response["language"] = response_json.get("language_code", "unknown") - + # Map ElevenLabs words to OpenAI format if "words" in response_json: response["words"] = [] for word_data in response_json["words"]: # Only include actual words, skip spacing and audio events if word_data.get("type") == "word": - response["words"].append({ - "word": word_data.get("text", ""), - "start": word_data.get("start", 0), - "end": word_data.get("end", 0) - }) + response["words"].append( + { + "word": word_data.get("text", ""), + "start": word_data.get("start", 0), + "end": word_data.get("end", 0), + } + ) # Store full response in hidden params response._hidden_params = response_json @@ -194,4 +197,4 @@ class ElevenLabsAudioTranscriptionConfig(BaseAudioTranscriptionConfig): } headers.update(auth_header) - return headers \ No newline at end of file + return headers diff --git a/litellm/llms/elevenlabs/common_utils.py b/litellm/llms/elevenlabs/common_utils.py index c1421b619f3..d3221933ebf 100644 --- a/litellm/llms/elevenlabs/common_utils.py +++ b/litellm/llms/elevenlabs/common_utils.py @@ -2,4 +2,4 @@ from litellm.llms.base_llm.chat.transformation import BaseLLMException class ElevenLabsException(BaseLLMException): - pass \ No newline at end of file + pass diff --git a/litellm/llms/elevenlabs/text_to_speech/transformation.py b/litellm/llms/elevenlabs/text_to_speech/transformation.py index b78d0bafc50..4dac2b8ba92 100644 --- a/litellm/llms/elevenlabs/text_to_speech/transformation.py +++ b/litellm/llms/elevenlabs/text_to_speech/transformation.py @@ -192,17 +192,17 @@ class ElevenLabsTextToSpeechConfig(BaseTextToSpeechConfig): "xi-api-key": api_key, "Content-Type": "application/json", } - ) - + ) + return headers - + def get_error_class( self, error_message: str, status_code: int, headers: Union[dict, Headers] ) -> BaseLLMException: return ElevenLabsException( message=error_message, status_code=status_code, headers=headers ) - + def transform_text_to_speech_request( self, model: str, @@ -311,9 +311,7 @@ class ElevenLabsTextToSpeechConfig(BaseTextToSpeechConfig): Construct the ElevenLabs endpoint URL, including path voice_id and query params. """ base_url = ( - api_base - or get_secret_str("ELEVENLABS_API_BASE") - or self.TTS_BASE_URL + api_base or get_secret_str("ELEVENLABS_API_BASE") or self.TTS_BASE_URL ) base_url = base_url.rstrip("/") @@ -329,4 +327,4 @@ class ElevenLabsTextToSpeechConfig(BaseTextToSpeechConfig): if query_params: url = f"{url}?{urlencode(query_params)}" - return url \ No newline at end of file + return url diff --git a/litellm/llms/exa_ai/search/__init__.py b/litellm/llms/exa_ai/search/__init__.py index b647d2cd80f..db1f0804646 100644 --- a/litellm/llms/exa_ai/search/__init__.py +++ b/litellm/llms/exa_ai/search/__init__.py @@ -4,4 +4,3 @@ Exa AI Search API module. from litellm.llms.exa_ai.search.transformation import ExaAISearchConfig __all__ = ["ExaAISearchConfig"] - diff --git a/litellm/llms/exa_ai/search/transformation.py b/litellm/llms/exa_ai/search/transformation.py index 6b51c6cf25d..fb352f3f93e 100644 --- a/litellm/llms/exa_ai/search/transformation.py +++ b/litellm/llms/exa_ai/search/transformation.py @@ -18,6 +18,7 @@ from litellm.secret_managers.main import get_secret_str class _ExaAISearchRequestRequired(TypedDict): """Required fields for Exa AI Search API request.""" + query: str # Required - search query @@ -26,6 +27,7 @@ class ExaAISearchRequest(_ExaAISearchRequestRequired, total=False): Exa AI Search API request format. Based on: https://docs.exa.ai/reference/search """ + type: str # Optional - search type ('keyword', 'neural', 'fast', 'auto'), default 'auto' category: str # Optional - data category ('company', 'research paper', 'news', 'pdf', 'github', 'tweet', 'personal site', 'linkedin profile', 'financial report') userLocation: str # Optional - two-letter ISO country code @@ -37,7 +39,9 @@ class ExaAISearchRequest(_ExaAISearchRequestRequired, total=False): startPublishedDate: str # Optional - published date filter (ISO 8601 format) endPublishedDate: str # Optional - published date filter (ISO 8601 format) includeText: List[str] # Optional - strings that must be present in webpage text - excludeText: List[str] # Optional - strings that must not be present in webpage text + excludeText: List[ + str + ] # Optional - strings that must not be present in webpage text context: Union[bool, dict] # Optional - format results for LLMs moderation: bool # Optional - enable content moderation, default false contents: dict # Optional - content retrieval options @@ -45,11 +49,11 @@ class ExaAISearchRequest(_ExaAISearchRequestRequired, total=False): class ExaAISearchConfig(BaseSearchConfig): EXA_AI_API_BASE = "https://api.exa.ai" - + @staticmethod def ui_friendly_name() -> str: return "Exa AI" - + def validate_environment( self, headers: Dict, @@ -62,7 +66,9 @@ class ExaAISearchConfig(BaseSearchConfig): """ api_key = api_key or get_secret_str("EXA_API_KEY") if not api_key: - raise ValueError("EXA_API_KEY is not set. Set `EXA_API_KEY` environment variable.") + raise ValueError( + "EXA_API_KEY is not set. Set `EXA_API_KEY` environment variable." + ) headers["x-api-key"] = api_key headers["Content-Type"] = "application/json" return headers @@ -78,13 +84,12 @@ class ExaAISearchConfig(BaseSearchConfig): Get complete URL for Search endpoint. """ api_base = api_base or get_secret_str("EXA_API_BASE") or self.EXA_AI_API_BASE - + # Append "/search" to the api base if it's not already there if not api_base.endswith("/search"): api_base = f"{api_base}/search" return api_base - def transform_search_request( self, @@ -94,20 +99,20 @@ class ExaAISearchConfig(BaseSearchConfig): ) -> Dict: """ Transform Search request to Exa AI API format. - + Transforms Perplexity unified spec parameters: - query → query (same) - max_results → numResults - search_domain_filter → includeDomains - country → userLocation - max_tokens_per_page → (not applicable, ignored) - + All other Exa-specific parameters are passed through as-is. - + Args: query: Search query (string or list of strings). Exa AI only supports single string queries. optional_params: Optional parameters for the request - + Returns: Dict with typed request data following ExaAISearchRequest spec """ @@ -118,30 +123,33 @@ class ExaAISearchConfig(BaseSearchConfig): request_data: ExaAISearchRequest = { "query": query, } - + # Transform Perplexity unified spec parameters to Exa format if "max_results" in optional_params: request_data["numResults"] = optional_params["max_results"] - + if "search_domain_filter" in optional_params: request_data["includeDomains"] = optional_params["search_domain_filter"] - + if "country" in optional_params: request_data["userLocation"] = optional_params["country"] - + # Convert to dict before dynamic key assignments result_data = dict(request_data) - + # pass through all other parameters as-is for param, value in optional_params.items(): - if param not in self.get_supported_perplexity_optional_params() and param not in result_data: + if ( + param not in self.get_supported_perplexity_optional_params() + and param not in result_data + ): result_data[param] = value - + # By default, request text content if not explicitly specified # Exa AI doesn't return content/text unless explicitly requested if "contents" not in result_data: result_data["contents"] = {"text": True} - + return result_data def transform_search_response( @@ -152,23 +160,23 @@ class ExaAISearchConfig(BaseSearchConfig): ) -> SearchResponse: """ Transform Exa AI API response to LiteLLM unified SearchResponse format. - + Exa AI → LiteLLM mappings: - results[].title → SearchResult.title - results[].url → SearchResult.url - results[].text → SearchResult.snippet - results[].publishedDate → SearchResult.date - No last_updated field in Exa AI response (set to None) - + Args: raw_response: Raw httpx response from Exa AI API logging_obj: Logging object for tracking - + Returns: SearchResponse with standardized format """ response_json = raw_response.json() - + # Transform results to SearchResult objects results = [] for result in response_json.get("results", []): @@ -180,9 +188,8 @@ class ExaAISearchConfig(BaseSearchConfig): last_updated=None, # Exa AI doesn't provide last_updated in response ) results.append(search_result) - + return SearchResponse( results=results, object="search", ) - diff --git a/litellm/llms/fal_ai/__init__.py b/litellm/llms/fal_ai/__init__.py index 34cac014ce9..0de526a8eb7 100644 --- a/litellm/llms/fal_ai/__init__.py +++ b/litellm/llms/fal_ai/__init__.py @@ -25,4 +25,3 @@ __all__ = [ "FalAIStableDiffusionConfig", "get_fal_ai_image_generation_config", ] - diff --git a/litellm/llms/fal_ai/cost_calculator.py b/litellm/llms/fal_ai/cost_calculator.py index b7caae3834f..9cdd0cd485b 100644 --- a/litellm/llms/fal_ai/cost_calculator.py +++ b/litellm/llms/fal_ai/cost_calculator.py @@ -22,5 +22,6 @@ def cost_calculator( num_images = len(image_response.data) return output_cost_per_image * num_images else: - raise ValueError(f"image_response must be of type ImageResponse got type={type(image_response)}") - + raise ValueError( + f"image_response must be of type ImageResponse got type={type(image_response)}" + ) diff --git a/litellm/llms/fal_ai/image_generation/__init__.py b/litellm/llms/fal_ai/image_generation/__init__.py index 27817ae5a5f..9deeb403c46 100644 --- a/litellm/llms/fal_ai/image_generation/__init__.py +++ b/litellm/llms/fal_ai/image_generation/__init__.py @@ -35,15 +35,15 @@ __all__ = [ def get_fal_ai_image_generation_config(model: str) -> BaseImageGenerationConfig: """ Get the appropriate Fal AI image generation configuration based on the model. - + Args: model: The Fal AI model name (e.g., "fal-ai/imagen4/preview", "fal-ai/recraft/v3/text-to-image") - + Returns: The appropriate configuration class for the specified model """ model_lower = model.lower() - + # Map model names to their corresponding configuration classes if "imagen4" in model_lower or "imagen-4" in model_lower: return FalAIImagen4Config() @@ -55,7 +55,11 @@ def get_fal_ai_image_generation_config(model: str) -> BaseImageGenerationConfig: if "ultra" in model_lower: return FalAIFluxProV11UltraConfig() return FalAIFluxProV11Config() - elif "flux/schnell" in model_lower or "flux-schnell" in model_lower or "schnell" in model_lower: + elif ( + "flux/schnell" in model_lower + or "flux-schnell" in model_lower + or "schnell" in model_lower + ): return FalAIFluxSchnellConfig() elif "bytedance/seedream" in model_lower: return FalAIBytedanceSeedreamV3Config() @@ -65,7 +69,6 @@ def get_fal_ai_image_generation_config(model: str) -> BaseImageGenerationConfig: return FalAIIdeogramV3Config() elif "stable-diffusion" in model_lower: return FalAIStableDiffusionConfig() - + # Default to generic Fal AI configuration return FalAIImageGenerationConfig() - diff --git a/litellm/llms/fal_ai/image_generation/bria_transformation.py b/litellm/llms/fal_ai/image_generation/bria_transformation.py index cb5aa6b761d..dd6e737324e 100644 --- a/litellm/llms/fal_ai/image_generation/bria_transformation.py +++ b/litellm/llms/fal_ai/image_generation/bria_transformation.py @@ -18,15 +18,16 @@ else: class FalAIBriaConfig(FalAIBaseConfig): """ Configuration for Bria Text-to-Image 3.2 model. - + Bria 3.2 is a commercial-grade text-to-image model with prompt enhancement and multiple aspect ratio options. - + Model endpoint: bria/text-to-image/3.2 Documentation: https://fal.ai/models/bria/text-to-image/3.2 """ + IMAGE_GENERATION_ENDPOINT: str = "bria/text-to-image/3.2" - + def get_supported_openai_params( self, model: str ) -> List[OpenAIImageGenerationOptionalParams]: @@ -38,7 +39,7 @@ class FalAIBriaConfig(FalAIBaseConfig): "response_format", "size", ] - + def map_openai_params( self, non_default_params: dict, @@ -48,26 +49,26 @@ class FalAIBriaConfig(FalAIBaseConfig): ) -> dict: """ Map OpenAI parameters to Bria 3.2 parameters. - + Mappings: - size -> aspect_ratio (1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9) - response_format -> ignored (Bria returns URLs) - n -> ignored (Bria doesn't support multiple images in one call) """ supported_params = self.get_supported_openai_params(model) - + # Map OpenAI params to Bria params param_mapping = { "size": "aspect_ratio", } - + for k in non_default_params.keys(): if k not in optional_params.keys(): if k in supported_params: # Use mapped parameter name if exists mapped_key = param_mapping.get(k, k) mapped_value = non_default_params[k] - + # Transform specific parameters if k == "response_format": # Bria always returns URLs, so we can ignore this @@ -78,7 +79,7 @@ class FalAIBriaConfig(FalAIBaseConfig): elif k == "size": # Map OpenAI size format to Bria aspect ratio mapped_value = self._map_aspect_ratio(mapped_value) - + optional_params[mapped_key] = mapped_value elif drop_params: pass @@ -92,7 +93,7 @@ class FalAIBriaConfig(FalAIBaseConfig): def _map_aspect_ratio(self, size: str) -> str: """ Map OpenAI size format to Bria aspect ratio format. - + OpenAI format: "1024x1024", "1792x1024", etc. Bria format: "1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9" """ @@ -107,20 +108,20 @@ class FalAIBriaConfig(FalAIBaseConfig): "1280x960": "4:3", "960x1280": "3:4", } - + if size in size_to_aspect_ratio: return size_to_aspect_ratio[size] - + # Parse custom size format "WIDTHxHEIGHT" and calculate aspect ratio if "x" in size: try: width_str, height_str = size.split("x") width = int(width_str) height = int(height_str) - + # Calculate aspect ratio and find closest match ratio = width / height - + # Map to closest supported aspect ratio if 0.95 <= ratio <= 1.05: # Close to 1:1 return "1:1" @@ -142,7 +143,7 @@ class FalAIBriaConfig(FalAIBaseConfig): return "4:5" except (ValueError, AttributeError, ZeroDivisionError): pass - + # Default to 1:1 return "1:1" @@ -156,10 +157,10 @@ class FalAIBriaConfig(FalAIBaseConfig): ) -> dict: """ Transform the image generation request to Bria 3.2 request body. - + Required parameters: - prompt: Prompt for image generation - + Optional parameters: - aspect_ratio: "1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9" (default: "1:1") - prompt_enhancer: Improve the prompt (default: true) @@ -174,7 +175,7 @@ class FalAIBriaConfig(FalAIBaseConfig): "prompt": prompt, **optional_params, } - + return bria_request_body def transform_image_generation_response( @@ -192,7 +193,7 @@ class FalAIBriaConfig(FalAIBaseConfig): ) -> ImageResponse: """ Transform the Bria 3.2 response to litellm ImageResponse format. - + Expected response format: { "image": { @@ -213,10 +214,10 @@ class FalAIBriaConfig(FalAIBaseConfig): status_code=raw_response.status_code, headers=raw_response.headers, ) - + if not model_response.data: model_response.data = [] - + # Handle Bria response format - uses "image" (singular) not "images" image_data = response_data.get("image") if image_data and isinstance(image_data, dict): @@ -226,6 +227,5 @@ class FalAIBriaConfig(FalAIBaseConfig): b64_json=None, # Bria returns URLs only ) ) - - return model_response + return model_response diff --git a/litellm/llms/fal_ai/image_generation/bytedance_transformation.py b/litellm/llms/fal_ai/image_generation/bytedance_transformation.py index d6aa242edc4..b52d08dd9e4 100644 --- a/litellm/llms/fal_ai/image_generation/bytedance_transformation.py +++ b/litellm/llms/fal_ai/image_generation/bytedance_transformation.py @@ -102,5 +102,3 @@ class FalAIBytedanceDreaminaV31Config(FalAIBytedanceBaseConfig): """ IMAGE_GENERATION_ENDPOINT: str = "fal-ai/bytedance/dreamina/v3.1/text-to-image" - - diff --git a/litellm/llms/fal_ai/image_generation/flux_pro_v11_transformation.py b/litellm/llms/fal_ai/image_generation/flux_pro_v11_transformation.py index 682ee0c2670..5226419a29e 100644 --- a/litellm/llms/fal_ai/image_generation/flux_pro_v11_transformation.py +++ b/litellm/llms/fal_ai/image_generation/flux_pro_v11_transformation.py @@ -87,5 +87,3 @@ class FalAIFluxProV11Config(FalAIFluxProV11UltraConfig): pass return "landscape_4_3" - - diff --git a/litellm/llms/fal_ai/image_generation/flux_pro_v11_ultra_transformation.py b/litellm/llms/fal_ai/image_generation/flux_pro_v11_ultra_transformation.py index 664f11d40dc..fef292d3311 100644 --- a/litellm/llms/fal_ai/image_generation/flux_pro_v11_ultra_transformation.py +++ b/litellm/llms/fal_ai/image_generation/flux_pro_v11_ultra_transformation.py @@ -18,15 +18,16 @@ else: class FalAIFluxProV11UltraConfig(FalAIBaseConfig): """ Configuration for Fal AI Flux Pro v1.1-ultra model. - + FLUX Pro v1.1-ultra is a high-quality text-to-image model with enhanced detail and support for image prompts. - + Model endpoint: fal-ai/flux-pro/v1.1-ultra Documentation: https://fal.ai/models/fal-ai/flux-pro/v1.1-ultra """ + IMAGE_GENERATION_ENDPOINT: str = "fal-ai/flux-pro/v1.1-ultra" - + def get_supported_openai_params( self, model: str ) -> List[OpenAIImageGenerationOptionalParams]: @@ -38,7 +39,7 @@ class FalAIFluxProV11UltraConfig(FalAIBaseConfig): "response_format", "size", ] - + def map_openai_params( self, non_default_params: dict, @@ -48,28 +49,28 @@ class FalAIFluxProV11UltraConfig(FalAIBaseConfig): ) -> dict: """ Map OpenAI parameters to Flux Pro v1.1-ultra parameters. - + Mappings: - n -> num_images (1-4, default 1) - response_format -> output_format (jpeg or png) - size -> aspect_ratio (21:9, 16:9, 4:3, 3:2, 1:1, 2:3, 3:4, 9:16, 9:21) """ supported_params = self.get_supported_openai_params(model) - + # Map OpenAI params to Flux Pro v1.1-ultra params param_mapping = { "n": "num_images", "response_format": "output_format", "size": "aspect_ratio", } - + for k in non_default_params.keys(): if k not in optional_params.keys(): if k in supported_params: # Use mapped parameter name if exists mapped_key = param_mapping.get(k, k) mapped_value = non_default_params[k] - + # Transform specific parameters if k == "response_format": # Map OpenAI response formats to image formats @@ -78,7 +79,7 @@ class FalAIFluxProV11UltraConfig(FalAIBaseConfig): elif k == "size": # Map OpenAI size format to Flux aspect ratio mapped_value = self._map_aspect_ratio(mapped_value) - + optional_params[mapped_key] = mapped_value elif drop_params: pass @@ -92,10 +93,10 @@ class FalAIFluxProV11UltraConfig(FalAIBaseConfig): def _map_aspect_ratio(self, size: str) -> str: """ Map OpenAI size format to Flux Pro aspect ratio format. - + OpenAI format: "1024x1024", "1792x1024", etc. Flux format: "21:9", "16:9", "4:3", "3:2", "1:1", "2:3", "3:4", "9:16", "9:21" - + Default: "16:9" """ # Map common OpenAI sizes to Flux aspect ratios @@ -111,20 +112,20 @@ class FalAIFluxProV11UltraConfig(FalAIBaseConfig): "2048x876": "21:9", "876x2048": "9:21", } - + if size in size_to_aspect_ratio: return size_to_aspect_ratio[size] - + # Parse custom size format "WIDTHxHEIGHT" and calculate aspect ratio if "x" in size: try: width_str, height_str = size.split("x") width = int(width_str) height = int(height_str) - + # Calculate aspect ratio and find closest match ratio = width / height - + # Map to closest supported aspect ratio if 0.95 <= ratio <= 1.05: # Close to 1:1 return "1:1" @@ -146,7 +147,7 @@ class FalAIFluxProV11UltraConfig(FalAIBaseConfig): return "9:21" except (ValueError, AttributeError, ZeroDivisionError): pass - + # Default to 16:9 return "16:9" @@ -160,10 +161,10 @@ class FalAIFluxProV11UltraConfig(FalAIBaseConfig): ) -> dict: """ Transform the image generation request to Flux Pro v1.1-ultra request body. - + Required parameters: - prompt: The prompt to generate an image from - + Optional parameters: - num_images: Number of images (1-4, default: 1) - aspect_ratio: Aspect ratio (default: "16:9") @@ -181,7 +182,7 @@ class FalAIFluxProV11UltraConfig(FalAIBaseConfig): "prompt": prompt, **optional_params, } - + return flux_pro_request_body def transform_image_generation_response( @@ -199,7 +200,7 @@ class FalAIFluxProV11UltraConfig(FalAIBaseConfig): ) -> ImageResponse: """ Transform the Flux Pro v1.1-ultra response to litellm ImageResponse format. - + Expected response format: { "images": [ @@ -224,10 +225,10 @@ class FalAIFluxProV11UltraConfig(FalAIBaseConfig): status_code=raw_response.status_code, headers=raw_response.headers, ) - + if not model_response.data: model_response.data = [] - + # Handle Flux Pro v1.1-ultra response format images = response_data.get("images", []) if isinstance(images, list): @@ -247,7 +248,7 @@ class FalAIFluxProV11UltraConfig(FalAIBaseConfig): b64_json=None, ) ) - + # Add additional metadata from Flux Pro response if hasattr(model_response, "_hidden_params"): if "seed" in response_data: @@ -258,6 +259,5 @@ class FalAIFluxProV11UltraConfig(FalAIBaseConfig): model_response._hidden_params["has_nsfw_concepts"] = response_data[ "has_nsfw_concepts" ] - - return model_response + return model_response diff --git a/litellm/llms/fal_ai/image_generation/flux_schnell_transformation.py b/litellm/llms/fal_ai/image_generation/flux_schnell_transformation.py index ed6ed37fb44..7a59fae6c1a 100644 --- a/litellm/llms/fal_ai/image_generation/flux_schnell_transformation.py +++ b/litellm/llms/fal_ai/image_generation/flux_schnell_transformation.py @@ -85,4 +85,3 @@ class FalAIFluxSchnellConfig(FalAIFluxProV11UltraConfig): pass return "landscape_4_3" - diff --git a/litellm/llms/fal_ai/image_generation/ideogram_v3_transformation.py b/litellm/llms/fal_ai/image_generation/ideogram_v3_transformation.py index f05ffa888ef..14e136d5d6f 100644 --- a/litellm/llms/fal_ai/image_generation/ideogram_v3_transformation.py +++ b/litellm/llms/fal_ai/image_generation/ideogram_v3_transformation.py @@ -189,5 +189,3 @@ class FalAIIdeogramV3Config(FalAIBaseConfig): model_response._hidden_params["seed"] = response_data["seed"] return model_response - - diff --git a/litellm/llms/fal_ai/image_generation/imagen4_transformation.py b/litellm/llms/fal_ai/image_generation/imagen4_transformation.py index 4e7708c9f40..ea6e7c1f3c9 100644 --- a/litellm/llms/fal_ai/image_generation/imagen4_transformation.py +++ b/litellm/llms/fal_ai/image_generation/imagen4_transformation.py @@ -18,18 +18,19 @@ else: class FalAIImagen4Config(FalAIBaseConfig): """ Configuration for Fal AI Imagen4 model. - + Google's highest quality image generation model available through Fal AI. - + Model variants: - fal-ai/imagen4/preview (Standard): $0.05 per image - fal-ai/imagen4/preview/fast (Fast): $0.02 per image - fal-ai/imagen4/preview/ultra (Ultra): $0.06 per image - + Documentation: https://fal.ai/models/fal-ai/imagen4/preview """ + IMAGE_GENERATION_ENDPOINT: str = "fal-ai/imagen4/preview" - + def get_supported_openai_params( self, model: str ) -> List[OpenAIImageGenerationOptionalParams]: @@ -41,7 +42,7 @@ class FalAIImagen4Config(FalAIBaseConfig): "response_format", "size", ] - + def map_openai_params( self, non_default_params: dict, @@ -51,27 +52,27 @@ class FalAIImagen4Config(FalAIBaseConfig): ) -> dict: """ Map OpenAI parameters to Imagen4 parameters. - + Mappings: - n -> num_images (1-4, default 1) - size -> aspect_ratio (1:1, 16:9, 9:16, 3:4, 4:3) - response_format -> ignored (Imagen4 returns URLs) """ supported_params = self.get_supported_openai_params(model) - + # Map OpenAI params to Imagen4 params param_mapping = { "n": "num_images", "size": "aspect_ratio", } - + for k in non_default_params.keys(): if k not in optional_params.keys(): if k in supported_params: # Use mapped parameter name if exists mapped_key = param_mapping.get(k, k) mapped_value = non_default_params[k] - + # Transform specific parameters if k == "response_format": # Imagen4 always returns URLs, so we can ignore this @@ -79,7 +80,7 @@ class FalAIImagen4Config(FalAIBaseConfig): elif k == "size": # Map OpenAI size format to Imagen4 aspect ratio mapped_value = self._map_aspect_ratio(mapped_value) - + optional_params[mapped_key] = mapped_value elif drop_params: pass @@ -93,10 +94,10 @@ class FalAIImagen4Config(FalAIBaseConfig): def _map_aspect_ratio(self, size: str) -> str: """ Map OpenAI size format to Imagen4 aspect ratio format. - + OpenAI format: "1024x1024", "1792x1024", etc. Imagen4 format: "1:1", "16:9", "9:16", "3:4", "4:3" - + Available aspect ratios: - 1:1 (default) - 16:9 @@ -113,20 +114,20 @@ class FalAIImagen4Config(FalAIBaseConfig): "1024x768": "4:3", "768x1024": "3:4", } - + if size in size_to_aspect_ratio: return size_to_aspect_ratio[size] - + # Parse custom size format "WIDTHxHEIGHT" and calculate aspect ratio if "x" in size: try: width_str, height_str = size.split("x") width = int(width_str) height = int(height_str) - + # Calculate aspect ratio and find closest match ratio = width / height - + # Map to closest supported aspect ratio if 0.95 <= ratio <= 1.05: # Close to 1:1 return "1:1" @@ -140,7 +141,7 @@ class FalAIImagen4Config(FalAIBaseConfig): return "3:4" except (ValueError, AttributeError, ZeroDivisionError): pass - + # Default to 1:1 return "1:1" @@ -154,10 +155,10 @@ class FalAIImagen4Config(FalAIBaseConfig): ) -> dict: """ Transform the image generation request to Imagen4 request body. - + Required parameters: - prompt: The text prompt describing what you want to see - + Optional parameters: - aspect_ratio: "1:1", "16:9", "9:16", "3:4", "4:3" (default: "1:1") - num_images: Number of images (1-4, default: 1) @@ -169,7 +170,7 @@ class FalAIImagen4Config(FalAIBaseConfig): "prompt": prompt, **optional_params, } - + return imagen4_request_body def transform_image_generation_response( @@ -187,7 +188,7 @@ class FalAIImagen4Config(FalAIBaseConfig): ) -> ImageResponse: """ Transform the Imagen4 response to litellm ImageResponse format. - + Expected response format: { "images": [ @@ -209,10 +210,10 @@ class FalAIImagen4Config(FalAIBaseConfig): status_code=raw_response.status_code, headers=raw_response.headers, ) - + if not model_response.data: model_response.data = [] - + # Handle Imagen4 response format images = response_data.get("images", []) if isinstance(images, list): @@ -232,11 +233,10 @@ class FalAIImagen4Config(FalAIBaseConfig): b64_json=None, ) ) - + # Add seed metadata from Imagen4 response if hasattr(model_response, "_hidden_params"): if "seed" in response_data: model_response._hidden_params["seed"] = response_data["seed"] - - return model_response + return model_response diff --git a/litellm/llms/fal_ai/image_generation/recraft_v3_transformation.py b/litellm/llms/fal_ai/image_generation/recraft_v3_transformation.py index 572a8a0f1c3..72ee165b51a 100644 --- a/litellm/llms/fal_ai/image_generation/recraft_v3_transformation.py +++ b/litellm/llms/fal_ai/image_generation/recraft_v3_transformation.py @@ -18,15 +18,16 @@ else: class FalAIRecraftV3Config(FalAIBaseConfig): """ Configuration for Fal AI Recraft v3 Text-to-Image model. - + Recraft v3 is a text-to-image model with multiple style options including realistic images, digital illustrations, and vector illustrations. - + Model endpoint: fal-ai/recraft/v3/text-to-image Documentation: https://fal.ai/models/fal-ai/recraft/v3/text-to-image """ + IMAGE_GENERATION_ENDPOINT: str = "fal-ai/recraft/v3/text-to-image" - + def get_supported_openai_params( self, model: str ) -> List[OpenAIImageGenerationOptionalParams]: @@ -38,7 +39,7 @@ class FalAIRecraftV3Config(FalAIBaseConfig): "response_format", "size", ] - + def map_openai_params( self, non_default_params: dict, @@ -48,26 +49,26 @@ class FalAIRecraftV3Config(FalAIBaseConfig): ) -> dict: """ Map OpenAI parameters to Recraft v3 parameters. - + Mappings: - size -> image_size (can be preset or custom width/height) - response_format -> ignored (Recraft returns URLs) - n -> ignored (Recraft doesn't support multiple images) """ supported_params = self.get_supported_openai_params(model) - + # Map OpenAI params to Recraft v3 params param_mapping = { "size": "image_size", } - + for k in non_default_params.keys(): if k not in optional_params.keys(): if k in supported_params: # Use mapped parameter name if exists mapped_key = param_mapping.get(k, k) mapped_value = non_default_params[k] - + # Transform specific parameters if k == "response_format": # Recraft always returns URLs, so we can ignore this @@ -78,7 +79,7 @@ class FalAIRecraftV3Config(FalAIBaseConfig): elif k == "size": # Map OpenAI size format to Recraft image_size mapped_value = self._map_image_size(mapped_value) - + optional_params[mapped_key] = mapped_value elif drop_params: pass @@ -92,10 +93,10 @@ class FalAIRecraftV3Config(FalAIBaseConfig): def _map_image_size(self, size: str) -> Any: """ Map OpenAI size format to Recraft v3 image_size format. - + OpenAI format: "1024x1024", "1792x1024", etc. Recraft format: Can be preset strings or {"width": int, "height": int} - + Available presets: - square_hd (default) - square @@ -113,10 +114,10 @@ class FalAIRecraftV3Config(FalAIBaseConfig): "1024x768": "landscape_4_3", "1024x576": "landscape_16_9", } - + if size in size_mapping: return size_mapping[size] - + # Parse custom size format "WIDTHxHEIGHT" if "x" in size: try: @@ -127,7 +128,7 @@ class FalAIRecraftV3Config(FalAIBaseConfig): } except (ValueError, AttributeError): pass - + # Default to square_hd return "square_hd" @@ -141,10 +142,10 @@ class FalAIRecraftV3Config(FalAIBaseConfig): ) -> dict: """ Transform the image generation request to Recraft v3 request body. - + Required parameters: - prompt: Text prompt (max 1000 characters) - + Optional parameters: - image_size: Preset or {"width": int, "height": int} (default: "square_hd") - style: Style preset (default: "realistic_image") @@ -152,14 +153,14 @@ class FalAIRecraftV3Config(FalAIBaseConfig): - colors: Array of RGB color objects [{"r": 0-255, "g": 0-255, "b": 0-255}] - enable_safety_checker: Enable safety checker (default: false) - style_id: UUID for custom style reference - + Note: Vector illustrations cost 2X as much. """ recraft_request_body = { "prompt": prompt, **optional_params, } - + return recraft_request_body def transform_image_generation_response( @@ -177,7 +178,7 @@ class FalAIRecraftV3Config(FalAIBaseConfig): ) -> ImageResponse: """ Transform the Recraft v3 response to litellm ImageResponse format. - + Expected response format: { "images": [ @@ -198,10 +199,10 @@ class FalAIRecraftV3Config(FalAIBaseConfig): status_code=raw_response.status_code, headers=raw_response.headers, ) - + if not model_response.data: model_response.data = [] - + # Handle Recraft v3 response format images = response_data.get("images", []) if isinstance(images, list): @@ -221,6 +222,5 @@ class FalAIRecraftV3Config(FalAIBaseConfig): b64_json=None, ) ) - - return model_response + return model_response diff --git a/litellm/llms/fal_ai/image_generation/stable_diffusion_transformation.py b/litellm/llms/fal_ai/image_generation/stable_diffusion_transformation.py index 10e2c6b4161..f0077c6a674 100644 --- a/litellm/llms/fal_ai/image_generation/stable_diffusion_transformation.py +++ b/litellm/llms/fal_ai/image_generation/stable_diffusion_transformation.py @@ -18,17 +18,18 @@ else: class FalAIStableDiffusionConfig(FalAIBaseConfig): """ Configuration for Fal AI Stable Diffusion models. - + Supports Stable Diffusion v3.5 variants and other Stable Diffusion models on Fal AI. - + Example models: - fal-ai/stable-diffusion-v35-medium - fal-ai/stable-diffusion-v35-large - + Documentation: https://fal.ai/models/fal-ai/stable-diffusion-v35-medium """ + IMAGE_GENERATION_ENDPOINT: str = "" # Will be set from model name - + def get_complete_url( self, api_base: Optional[str], @@ -40,19 +41,17 @@ class FalAIStableDiffusionConfig(FalAIBaseConfig): ) -> str: """ Get the complete url for the request. - + For Stable Diffusion models, extract the endpoint from the model name. """ from litellm.secret_managers.main import get_secret_str - + complete_url: str = ( - api_base - or get_secret_str("FAL_AI_API_BASE") - or self.DEFAULT_BASE_URL + api_base or get_secret_str("FAL_AI_API_BASE") or self.DEFAULT_BASE_URL ) - + complete_url = complete_url.rstrip("/") - + # Extract endpoint from model name # e.g., "fal-ai/stable-diffusion-v35-medium" or "stable-diffusion-v35-medium" endpoint = model @@ -62,10 +61,10 @@ class FalAIStableDiffusionConfig(FalAIBaseConfig): elif not model.startswith("fal-ai/"): # If model is just "stable-diffusion-v35-medium", prepend fal-ai endpoint = f"fal-ai/{model}" - + complete_url = f"{complete_url}/{endpoint}" return complete_url - + def get_supported_openai_params( self, model: str ) -> List[OpenAIImageGenerationOptionalParams]: @@ -77,7 +76,7 @@ class FalAIStableDiffusionConfig(FalAIBaseConfig): "response_format", "size", ] - + def map_openai_params( self, non_default_params: dict, @@ -87,28 +86,28 @@ class FalAIStableDiffusionConfig(FalAIBaseConfig): ) -> dict: """ Map OpenAI parameters to Stable Diffusion parameters. - + Mappings: - n -> num_images (1-4, default 1) - response_format -> output_format (jpeg or png) - size -> image_size (can be preset or custom width/height) """ supported_params = self.get_supported_openai_params(model) - + # Map OpenAI params to Stable Diffusion params param_mapping = { "n": "num_images", "response_format": "output_format", "size": "image_size", } - + for k in non_default_params.keys(): if k not in optional_params.keys(): if k in supported_params: # Use mapped parameter name if exists mapped_key = param_mapping.get(k, k) mapped_value = non_default_params[k] - + # Transform specific parameters if k == "response_format": # Map OpenAI response formats to image formats @@ -117,7 +116,7 @@ class FalAIStableDiffusionConfig(FalAIBaseConfig): elif k == "size": # Map OpenAI size format to Stable Diffusion image_size mapped_value = self._map_image_size(mapped_value) - + optional_params[mapped_key] = mapped_value elif drop_params: pass @@ -131,10 +130,10 @@ class FalAIStableDiffusionConfig(FalAIBaseConfig): def _map_image_size(self, size: str) -> Any: """ Map OpenAI size format to Stable Diffusion image_size format. - + OpenAI format: "1024x1024", "1792x1024", etc. Stable Diffusion format: Can be preset strings or {"width": int, "height": int} - + Available presets: - square_hd - square @@ -152,10 +151,10 @@ class FalAIStableDiffusionConfig(FalAIBaseConfig): "1024x768": "landscape_4_3", "1024x576": "landscape_16_9", } - + if size in size_mapping: return size_mapping[size] - + # Parse custom size format "WIDTHxHEIGHT" if "x" in size: try: @@ -166,7 +165,7 @@ class FalAIStableDiffusionConfig(FalAIBaseConfig): } except (ValueError, AttributeError): pass - + # Default to landscape_4_3 return "landscape_4_3" @@ -180,10 +179,10 @@ class FalAIStableDiffusionConfig(FalAIBaseConfig): ) -> dict: """ Transform the image generation request to Stable Diffusion request body. - + Required parameters: - prompt: The prompt to generate an image from - + Optional parameters: - num_images: Number of images (1-4, default: 1) - image_size: Size preset or {"width": int, "height": int} (default: landscape_4_3) @@ -199,7 +198,7 @@ class FalAIStableDiffusionConfig(FalAIBaseConfig): "prompt": prompt, **optional_params, } - + return stable_diffusion_request_body def transform_image_generation_response( @@ -217,7 +216,7 @@ class FalAIStableDiffusionConfig(FalAIBaseConfig): ) -> ImageResponse: """ Transform the Stable Diffusion response to litellm ImageResponse format. - + Expected response format: { "images": [ @@ -242,10 +241,10 @@ class FalAIStableDiffusionConfig(FalAIBaseConfig): status_code=raw_response.status_code, headers=raw_response.headers, ) - + if not model_response.data: model_response.data = [] - + # Handle Stable Diffusion response format images = response_data.get("images", []) if isinstance(images, list): @@ -265,7 +264,7 @@ class FalAIStableDiffusionConfig(FalAIBaseConfig): b64_json=None, ) ) - + # Add additional metadata from Stable Diffusion response if hasattr(model_response, "_hidden_params"): if "seed" in response_data: @@ -276,6 +275,5 @@ class FalAIStableDiffusionConfig(FalAIBaseConfig): model_response._hidden_params["has_nsfw_concepts"] = response_data[ "has_nsfw_concepts" ] - - return model_response + return model_response diff --git a/litellm/llms/fal_ai/image_generation/transformation.py b/litellm/llms/fal_ai/image_generation/transformation.py index 04b7b167523..4a0dea48a10 100644 --- a/litellm/llms/fal_ai/image_generation/transformation.py +++ b/litellm/llms/fal_ai/image_generation/transformation.py @@ -25,6 +25,7 @@ class FalAIBaseConfig(BaseImageGenerationConfig): Base configuration for Fal AI image generation models. Handles common functionality like URL construction and authentication. """ + DEFAULT_BASE_URL: str = "https://fal.run" IMAGE_GENERATION_ENDPOINT: str = "" @@ -43,9 +44,7 @@ class FalAIBaseConfig(BaseImageGenerationConfig): Some providers need `model` in `api_base` """ complete_url: str = ( - api_base - or get_secret_str("FAL_AI_API_BASE") - or self.DEFAULT_BASE_URL + api_base or get_secret_str("FAL_AI_API_BASE") or self.DEFAULT_BASE_URL ) complete_url = complete_url.rstrip("/") @@ -63,14 +62,11 @@ class FalAIBaseConfig(BaseImageGenerationConfig): api_key: Optional[str] = None, api_base: Optional[str] = None, ) -> dict: - final_api_key: Optional[str] = ( - api_key or - get_secret_str("FAL_AI_API_KEY") - ) + final_api_key: Optional[str] = api_key or get_secret_str("FAL_AI_API_KEY") if not final_api_key: raise ValueError("FAL_AI_API_KEY is not set") - - headers["Authorization"] = f"Key {final_api_key}" + + headers["Authorization"] = f"Key {final_api_key}" return headers def transform_image_generation_response( @@ -99,23 +95,27 @@ class FalAIBaseConfig(BaseImageGenerationConfig): ) if not model_response.data: model_response.data = [] - + # Handle fal.ai response format images = response_data.get("images", []) if isinstance(images, list): for image_data in images: if isinstance(image_data, dict): - model_response.data.append(ImageObject( - url=image_data.get("url", None), - b64_json=image_data.get("b64_json", None), - )) + model_response.data.append( + ImageObject( + url=image_data.get("url", None), + b64_json=image_data.get("b64_json", None), + ) + ) elif isinstance(image_data, str): # If images is just a list of URLs - model_response.data.append(ImageObject( - url=image_data, - b64_json=None, - )) - + model_response.data.append( + ImageObject( + url=image_data, + b64_json=None, + ) + ) + return model_response @@ -123,7 +123,7 @@ class FalAIImageGenerationConfig(FalAIBaseConfig): """ Default Fal AI image generation configuration for generic models. """ - + def get_supported_openai_params( self, model: str ) -> List[OpenAIImageGenerationOptionalParams]: @@ -135,7 +135,7 @@ class FalAIImageGenerationConfig(FalAIBaseConfig): "response_format", "size", ] - + def map_openai_params( self, non_default_params: dict, @@ -173,4 +173,3 @@ class FalAIImageGenerationConfig(FalAIBaseConfig): **optional_params, } return fal_ai_image_generation_request_body - diff --git a/litellm/llms/firecrawl/__init__.py b/litellm/llms/firecrawl/__init__.py index bacf1eac070..b43d2da3214 100644 --- a/litellm/llms/firecrawl/__init__.py +++ b/litellm/llms/firecrawl/__init__.py @@ -4,4 +4,3 @@ Firecrawl API integration module. from litellm.llms.firecrawl.search.transformation import FirecrawlSearchConfig __all__ = ["FirecrawlSearchConfig"] - diff --git a/litellm/llms/firecrawl/search/__init__.py b/litellm/llms/firecrawl/search/__init__.py index 999dce655d5..46619d05b63 100644 --- a/litellm/llms/firecrawl/search/__init__.py +++ b/litellm/llms/firecrawl/search/__init__.py @@ -4,4 +4,3 @@ Firecrawl Search API module. from litellm.llms.firecrawl.search.transformation import FirecrawlSearchConfig __all__ = ["FirecrawlSearchConfig"] - diff --git a/litellm/llms/firecrawl/search/transformation.py b/litellm/llms/firecrawl/search/transformation.py index af501a8eac0..61b589218cc 100644 --- a/litellm/llms/firecrawl/search/transformation.py +++ b/litellm/llms/firecrawl/search/transformation.py @@ -18,6 +18,7 @@ from litellm.secret_managers.main import get_secret_str class _FirecrawlSearchRequestRequired(TypedDict): """Required fields for Firecrawl Search API request.""" + query: str # Required - search query @@ -26,9 +27,14 @@ class FirecrawlSearchRequest(_FirecrawlSearchRequestRequired, total=False): Firecrawl Search API request format. Based on: https://docs.firecrawl.dev/api-reference/endpoint/search """ + limit: int # Optional - maximum number of results to return (default 5, max 100) - sources: List[str] # Optional - sources to search ('web', 'images', 'news'), default ['web'] - categories: List[Dict[str, str]] # Optional - categories to filter by (github, research, pdf) + sources: List[ + str + ] # Optional - sources to search ('web', 'images', 'news'), default ['web'] + categories: List[ + Dict[str, str] + ] # Optional - categories to filter by (github, research, pdf) tbs: str # Optional - time-based search parameter location: str # Optional - location parameter for geo-targeting country: str # Optional - ISO country code (default 'US') @@ -39,11 +45,11 @@ class FirecrawlSearchRequest(_FirecrawlSearchRequestRequired, total=False): class FirecrawlSearchConfig(BaseSearchConfig): FIRECRAWL_API_BASE = "https://api.firecrawl.dev/v2" - + @staticmethod def ui_friendly_name() -> str: return "Firecrawl" - + def validate_environment( self, headers: Dict, @@ -56,7 +62,9 @@ class FirecrawlSearchConfig(BaseSearchConfig): """ api_key = api_key or get_secret_str("FIRECRAWL_API_KEY") if not api_key: - raise ValueError("FIRECRAWL_API_KEY is not set. Set `FIRECRAWL_API_KEY` environment variable.") + raise ValueError( + "FIRECRAWL_API_KEY is not set. Set `FIRECRAWL_API_KEY` environment variable." + ) headers["Authorization"] = f"Bearer {api_key}" headers["Content-Type"] = "application/json" return headers @@ -71,14 +79,15 @@ class FirecrawlSearchConfig(BaseSearchConfig): """ Get complete URL for Search endpoint. """ - api_base = api_base or get_secret_str("FIRECRAWL_API_BASE") or self.FIRECRAWL_API_BASE - + api_base = ( + api_base or get_secret_str("FIRECRAWL_API_BASE") or self.FIRECRAWL_API_BASE + ) + # Append "/search" to the api base if it's not already there if not api_base.endswith("/search"): api_base = f"{api_base}/search" return api_base - def transform_search_request( self, @@ -88,20 +97,20 @@ class FirecrawlSearchConfig(BaseSearchConfig): ) -> Dict: """ Transform Search request to Firecrawl API format. - + Transforms Perplexity unified spec parameters: - query → query (same) - max_results → limit - search_domain_filter → (not directly supported, can use scrapeOptions) - country → country - max_tokens_per_page → (not applicable, ignored) - + All other Firecrawl-specific parameters are passed through as-is. - + Args: query: Search query (string or list of strings). Firecrawl only supports single string queries. optional_params: Optional parameters for the request - + Returns: Dict with typed request data following FirecrawlSearchRequest spec """ @@ -112,30 +121,33 @@ class FirecrawlSearchConfig(BaseSearchConfig): request_data: FirecrawlSearchRequest = { "query": query, } - + # Transform Perplexity unified spec parameters to Firecrawl format if "max_results" in optional_params: request_data["limit"] = optional_params["max_results"] - + if "country" in optional_params: request_data["country"] = optional_params["country"] - + # Convert to dict before dynamic key assignments result_data = dict(request_data) - + # pass through all other parameters as-is for param, value in optional_params.items(): - if param not in self.get_supported_perplexity_optional_params() and param not in result_data: + if ( + param not in self.get_supported_perplexity_optional_params() + and param not in result_data + ): result_data[param] = value - + # By default, request markdown content if not explicitly specified # Firecrawl doesn't return content unless explicitly requested via scrapeOptions if "scrapeOptions" not in result_data: result_data["scrapeOptions"] = { "formats": ["markdown"], - "onlyMainContent": True + "onlyMainContent": True, } - + return result_data def transform_search_response( @@ -146,37 +158,37 @@ class FirecrawlSearchConfig(BaseSearchConfig): ) -> SearchResponse: """ Transform Firecrawl API response to LiteLLM unified SearchResponse format. - + Firecrawl → LiteLLM mappings: - data.web[].title → SearchResult.title - data.web[].url → SearchResult.url - data.web[].description OR data.web[].markdown → SearchResult.snippet - No date field in web results (set to None) - No last_updated field in Firecrawl response (set to None) - + Note: Firecrawl v2 returns results organized by source type (web, images, news). We primarily use web results for the unified format. - + Args: raw_response: Raw httpx response from Firecrawl API logging_obj: Logging object for tracking - + Returns: SearchResponse with standardized format """ response_json = raw_response.json() - + # Transform results to SearchResult objects results = [] - + # Process web results (primary source) data = response_json.get("data", {}) web_results = data.get("web", []) - + for result in web_results: # Use markdown if available, otherwise fall back to description snippet = result.get("markdown") or result.get("description", "") - + search_result = SearchResult( title=result.get("title", ""), url=result.get("url", ""), @@ -185,12 +197,12 @@ class FirecrawlSearchConfig(BaseSearchConfig): last_updated=None, # Firecrawl doesn't provide last_updated in response ) results.append(search_result) - + # Process news results if available (they have date field) news_results = data.get("news", []) for result in news_results: snippet = result.get("markdown") or result.get("snippet", "") - + search_result = SearchResult( title=result.get("title", ""), url=result.get("url", ""), @@ -199,9 +211,8 @@ class FirecrawlSearchConfig(BaseSearchConfig): last_updated=None, ) results.append(search_result) - + return SearchResponse( results=results, object="search", ) - diff --git a/litellm/llms/fireworks_ai/chat/transformation.py b/litellm/llms/fireworks_ai/chat/transformation.py index 7ec32fecc46..8407e8ab695 100644 --- a/litellm/llms/fireworks_ai/chat/transformation.py +++ b/litellm/llms/fireworks_ai/chat/transformation.py @@ -257,30 +257,33 @@ class FireworksAIConfig(OpenAIGPTConfig): "gpt-oss-120b", "gpt-oss-20b", ] - + # Normalize model name - remove prefix if present normalized_model = model if model.startswith("fireworks_ai/"): normalized_model = model.replace("fireworks_ai/", "") if normalized_model.startswith("accounts/fireworks/models/"): - normalized_model = normalized_model.replace("accounts/fireworks/models/", "") - + normalized_model = normalized_model.replace( + "accounts/fireworks/models/", "" + ) + # Check if model supports reasoning supports_reasoning_value = any( - reasoning_model in normalized_model for reasoning_model in reasoning_supported_models + reasoning_model in normalized_model + for reasoning_model in reasoning_supported_models ) - + provider_specific_model_info: ProviderSpecificModelInfo = { "supports_function_calling": True, "supports_prompt_caching": True, # https://docs.fireworks.ai/guides/prompt-caching "supports_pdf_input": True, # via document inlining "supports_vision": True, # via document inlining } - + # Only include supports_reasoning if True if supports_reasoning_value: provider_specific_model_info["supports_reasoning"] = True - + return provider_specific_model_info def transform_request( @@ -426,8 +429,11 @@ class FireworksAIConfig(OpenAIGPTConfig): "FIREWORKS_ACCOUNT_ID is not set. Please set the environment variable, to query Fireworks AI's `/models` endpoint." ) + base = api_base.rstrip("/") + if base.endswith("/v1"): + base = base[: -len("/v1")] response = litellm.module_level_client.get( - url=f"{api_base}/v1/accounts/{account_id}/models", + url=f"{base}/v1/accounts/{account_id}/models", headers={"Authorization": f"Bearer {api_key}"}, ) diff --git a/litellm/llms/fireworks_ai/rerank/__init__.py b/litellm/llms/fireworks_ai/rerank/__init__.py index b8e99317a2d..2312d016aba 100644 --- a/litellm/llms/fireworks_ai/rerank/__init__.py +++ b/litellm/llms/fireworks_ai/rerank/__init__.py @@ -1,2 +1 @@ # Fireworks AI Rerank - diff --git a/litellm/llms/fireworks_ai/rerank/transformation.py b/litellm/llms/fireworks_ai/rerank/transformation.py index e2893464bdb..eb92399a058 100644 --- a/litellm/llms/fireworks_ai/rerank/transformation.py +++ b/litellm/llms/fireworks_ai/rerank/transformation.py @@ -75,26 +75,26 @@ class FireworksAIRerankConfig(FireworksAIMixin, BaseRerankConfig): "query": query, "documents": documents, } - + if top_n is not None: params["top_n"] = top_n - + if return_documents is not None: params["return_documents"] = return_documents - + # Fireworks AI doesn't support these params if rank_fields is not None: # Silently ignore rank_fields as Fireworks AI doesn't support it pass - + if max_chunks_per_doc is not None: # Silently ignore max_chunks_per_doc as Fireworks AI doesn't support it pass - + if max_tokens_per_doc is not None: # Silently ignore max_tokens_per_doc as Fireworks AI doesn't support it pass - + return params def validate_environment( # type: ignore[override] @@ -140,7 +140,7 @@ class FireworksAIRerankConfig(FireworksAIMixin, BaseRerankConfig): # Remove fireworks_ai/ prefix if present if model.startswith("fireworks_ai/"): model = model.replace("fireworks_ai/", "") - + # If model doesn't start with "fireworks/", add it # But don't add if it already has the prefix if not model.startswith("fireworks/"): @@ -152,11 +152,19 @@ class FireworksAIRerankConfig(FireworksAIMixin, BaseRerankConfig): "documents": optional_rerank_params["documents"], } - if "top_n" in optional_rerank_params and optional_rerank_params["top_n"] is not None: + if ( + "top_n" in optional_rerank_params + and optional_rerank_params["top_n"] is not None + ): request_data["top_n"] = optional_rerank_params["top_n"] - if "return_documents" in optional_rerank_params and optional_rerank_params["return_documents"] is not None: - request_data["return_documents"] = optional_rerank_params["return_documents"] + if ( + "return_documents" in optional_rerank_params + and optional_rerank_params["return_documents"] is not None + ): + request_data["return_documents"] = optional_rerank_params[ + "return_documents" + ] return request_data @@ -191,7 +199,7 @@ class FireworksAIRerankConfig(FireworksAIMixin, BaseRerankConfig): # { # "index": 0, # "relevance_score": 0.95, - # "document": "..." + # "document": "..." # } # ], # "usage": { @@ -203,9 +211,7 @@ class FireworksAIRerankConfig(FireworksAIMixin, BaseRerankConfig): # Extract usage information usage = raw_response_json.get("usage", {}) - _billed_units = RerankBilledUnits( - search_units=usage.get("total_tokens", 0) - ) + _billed_units = RerankBilledUnits(search_units=usage.get("total_tokens", 0)) _tokens = RerankTokens( input_tokens=usage.get("prompt_tokens", 0), output_tokens=usage.get("completion_tokens", 0), @@ -213,7 +219,9 @@ class FireworksAIRerankConfig(FireworksAIMixin, BaseRerankConfig): rerank_meta = RerankResponseMeta(billed_units=_billed_units, tokens=_tokens) # Extract results - Fireworks AI uses "data" instead of "results" - _results: Optional[List[dict]] = raw_response_json.get("data") or raw_response_json.get("results") + _results: Optional[List[dict]] = raw_response_json.get( + "data" + ) or raw_response_json.get("results") if _results is None: raise ValueError(f"No results found in the response={raw_response_json}") @@ -251,11 +259,14 @@ class FireworksAIRerankConfig(FireworksAIMixin, BaseRerankConfig): rerank_results.append(rerank_result) # Use model name as id if no id is provided - response_id = raw_response_json.get("id") or raw_response_json.get("model") or str(uuid.uuid4()) + response_id = ( + raw_response_json.get("id") + or raw_response_json.get("model") + or str(uuid.uuid4()) + ) return RerankResponse( id=response_id, results=rerank_results, meta=rerank_meta, ) - diff --git a/litellm/llms/gemini/chat/transformation.py b/litellm/llms/gemini/chat/transformation.py index d5a5ab667a6..5f8dead2043 100644 --- a/litellm/llms/gemini/chat/transformation.py +++ b/litellm/llms/gemini/chat/transformation.py @@ -126,13 +126,15 @@ class GoogleAIStudioGeminiConfig(VertexGeminiConfig): image_obj = convert_to_anthropic_image_obj( _image_url, format=format ) - converted_image_url = convert_generic_image_chunk_to_openai_image_obj( - image_obj + converted_image_url = ( + convert_generic_image_chunk_to_openai_image_obj( + image_obj + ) ) if detail is not None: img_element["image_url"] = { # type: ignore "url": converted_image_url, - "detail": detail + "detail": detail, } else: img_element["image_url"] = converted_image_url # type: ignore diff --git a/litellm/llms/gemini/common_utils.py b/litellm/llms/gemini/common_utils.py index 17b9c78123f..87c107fab37 100644 --- a/litellm/llms/gemini/common_utils.py +++ b/litellm/llms/gemini/common_utils.py @@ -45,7 +45,11 @@ class GeminiModelInfo(BaseLLMModelInfo): @staticmethod def get_api_key(api_key: Optional[str] = None) -> Optional[str]: - return api_key or (get_secret_str("GOOGLE_API_KEY")) or (get_secret_str("GEMINI_API_KEY")) + return ( + api_key + or (get_secret_str("GOOGLE_API_KEY")) + or (get_secret_str("GEMINI_API_KEY")) + ) @staticmethod def get_base_model(model: str) -> Optional[str]: @@ -90,11 +94,11 @@ class GeminiModelInfo(BaseLLMModelInfo): return GeminiError( status_code=status_code, message=error_message, headers=headers ) - + def get_token_counter(self) -> Optional[BaseTokenCounter]: """ Factory method to create a token counter for this provider. - + Returns: Optional TokenCounterInterface implementation for this provider, or None if token counting is not supported. @@ -152,13 +156,15 @@ def get_api_key_from_env() -> Optional[str]: class GoogleAIStudioTokenCounter(BaseTokenCounter): """Token counter implementation for Google AI Studio provider.""" + def should_use_token_counting_api( - self, + self, custom_llm_provider: Optional[str] = None, ) -> bool: from litellm.types.utils import LlmProviders + return custom_llm_provider == LlmProviders.GEMINI.value - + async def count_tokens( self, model_to_use: str, @@ -172,8 +178,11 @@ class GoogleAIStudioTokenCounter(BaseTokenCounter): import copy from litellm.llms.gemini.count_tokens.handler import GoogleAIStudioTokenCounter + deployment = deployment or {} - count_tokens_params_request = copy.deepcopy(deployment.get("litellm_params", {})) + count_tokens_params_request = copy.deepcopy( + deployment.get("litellm_params", {}) + ) count_tokens_params = { "model": model_to_use, "contents": contents, @@ -182,7 +191,7 @@ class GoogleAIStudioTokenCounter(BaseTokenCounter): result = await GoogleAIStudioTokenCounter().acount_tokens( **count_tokens_params_request, ) - + if result is not None: return TokenCountResponse( total_tokens=result.get("totalTokens", 0), @@ -191,5 +200,5 @@ class GoogleAIStudioTokenCounter(BaseTokenCounter): tokenizer_type=result.get("tokenizer_used", ""), original_response=result, ) - - return None \ No newline at end of file + + return None diff --git a/litellm/llms/gemini/cost_calculator.py b/litellm/llms/gemini/cost_calculator.py index 79242fe01d1..45850e0d668 100644 --- a/litellm/llms/gemini/cost_calculator.py +++ b/litellm/llms/gemini/cost_calculator.py @@ -21,7 +21,10 @@ def cost_per_token( from litellm.litellm_core_utils.llm_cost_calc.utils import generic_cost_per_token return generic_cost_per_token( - model=model, usage=usage, custom_llm_provider="gemini", service_tier=service_tier + model=model, + usage=usage, + custom_llm_provider="gemini", + service_tier=service_tier, ) diff --git a/litellm/llms/gemini/files/transformation.py b/litellm/llms/gemini/files/transformation.py index cc799cfd6aa..bdfb0ee1e52 100644 --- a/litellm/llms/gemini/files/transformation.py +++ b/litellm/llms/gemini/files/transformation.py @@ -52,8 +52,10 @@ class GoogleAIStudioFilesHandler(GeminiModelInfo, BaseFilesConfig): """ resolved_api_key = self.get_api_key(api_key) if not resolved_api_key: - raise ValueError("GEMINI_API_KEY is required for Google AI Studio file operations") - + raise ValueError( + "GEMINI_API_KEY is required for Google AI Studio file operations" + ) + headers["x-goog-api-key"] = resolved_api_key return headers @@ -206,7 +208,7 @@ class GoogleAIStudioFilesHandler(GeminiModelInfo, BaseFilesConfig): ) -> tuple[str, dict]: """ Get the URL to retrieve a file from Google AI Studio. - + We expect file_id to be the URI (e.g. https://generativelanguage.googleapis.com/v1beta/files/...) as returned by the upload response. """ @@ -218,7 +220,10 @@ class GoogleAIStudioFilesHandler(GeminiModelInfo, BaseFilesConfig): url = "{}?key={}".format(file_id, api_key) else: # Fallback for just file name (files/...) - api_base = self.get_api_base(litellm_params.get("api_base")) or "https://generativelanguage.googleapis.com" + api_base = ( + self.get_api_base(litellm_params.get("api_base")) + or "https://generativelanguage.googleapis.com" + ) api_base = api_base.rstrip("/") url = "{}/v1beta/{}?key={}".format(api_base, file_id, api_key) @@ -236,7 +241,7 @@ class GoogleAIStudioFilesHandler(GeminiModelInfo, BaseFilesConfig): """ try: response_json = raw_response.json() - + # Map Gemini state to OpenAI status gemini_state = response_json.get("state", "STATE_UNSPECIFIED") # Explicitly type status as the Literal union @@ -246,7 +251,7 @@ class GoogleAIStudioFilesHandler(GeminiModelInfo, BaseFilesConfig): status = "error" else: status = "uploaded" - + return OpenAIFileObject( id=response_json.get("uri", ""), bytes=int(response_json.get("sizeBytes", 0)), @@ -262,7 +267,9 @@ class GoogleAIStudioFilesHandler(GeminiModelInfo, BaseFilesConfig): object="file", purpose="user_data", status=status, - status_details=str(response_json.get("error", "")) if gemini_state == "FAILED" else None, + status_details=str(response_json.get("error", "")) + if gemini_state == "FAILED" + else None, ) except Exception as e: verbose_logger.exception(f"Error parsing file retrieve response: {str(e)}") @@ -276,24 +283,24 @@ class GoogleAIStudioFilesHandler(GeminiModelInfo, BaseFilesConfig): ) -> tuple[str, dict]: """ Transform delete file request for Google AI Studio. - + Args: file_id: The file URI (e.g., "files/abc123" or full URI) optional_params: Optional parameters litellm_params: LiteLLM parameters containing api_key - + Returns: tuple[str, dict]: (url, params) for the DELETE request """ api_base = self.get_api_base(litellm_params.get("api_base")) if not api_base: raise ValueError("api_base is required") - + # Get API key from multiple sources (same pattern as get_complete_url) api_key = litellm_params.get("api_key") or self.get_api_key() if not api_key: raise ValueError("api_key is required") - + # Extract file name from URI if full URI is provided # file_id could be "files/abc123" or "https://generativelanguage.googleapis.com/v1beta/files/abc123" if file_id.startswith("http"): @@ -301,13 +308,13 @@ class GoogleAIStudioFilesHandler(GeminiModelInfo, BaseFilesConfig): file_name = file_id.split("/v1beta/")[-1] else: 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}" - + # Add API key as header (Google AI Studio uses x-goog-api-key header) params: dict = {} - + return url, params def transform_delete_file_response( @@ -318,7 +325,7 @@ class GoogleAIStudioFilesHandler(GeminiModelInfo, BaseFilesConfig): ) -> FileDeleted: """ Transform Gemini's file delete response into OpenAI-style FileDeleted. - + Google AI Studio returns an empty JSON object {} on successful deletion. """ try: @@ -333,12 +340,8 @@ class GoogleAIStudioFilesHandler(GeminiModelInfo, BaseFilesConfig): # Add the files/ prefix if not present if not file_id.startswith("files/"): file_id = f"files/{file_id}" - - return FileDeleted( - id=file_id, - deleted=True, - object="file" - ) + + return FileDeleted(id=file_id, deleted=True, object="file") else: raise ValueError(f"Failed to delete file: {raw_response.text}") except Exception as e: @@ -351,7 +354,9 @@ class GoogleAIStudioFilesHandler(GeminiModelInfo, BaseFilesConfig): optional_params: dict, litellm_params: dict, ) -> tuple[str, dict]: - raise NotImplementedError("GoogleAIStudioFilesHandler does not support file listing") + raise NotImplementedError( + "GoogleAIStudioFilesHandler does not support file listing" + ) def transform_list_files_response( self, @@ -359,7 +364,9 @@ class GoogleAIStudioFilesHandler(GeminiModelInfo, BaseFilesConfig): logging_obj: LiteLLMLoggingObj, litellm_params: dict, ) -> List[OpenAIFileObject]: - raise NotImplementedError("GoogleAIStudioFilesHandler does not support file listing") + raise NotImplementedError( + "GoogleAIStudioFilesHandler does not support file listing" + ) def transform_file_content_request( self, @@ -367,7 +374,9 @@ class GoogleAIStudioFilesHandler(GeminiModelInfo, BaseFilesConfig): optional_params: dict, litellm_params: dict, ) -> tuple[str, dict]: - raise NotImplementedError("GoogleAIStudioFilesHandler does not support file content retrieval") + raise NotImplementedError( + "GoogleAIStudioFilesHandler does not support file content retrieval" + ) def transform_file_content_response( self, @@ -375,4 +384,6 @@ class GoogleAIStudioFilesHandler(GeminiModelInfo, BaseFilesConfig): logging_obj: LiteLLMLoggingObj, litellm_params: dict, ) -> HttpxBinaryResponseContent: - raise NotImplementedError("GoogleAIStudioFilesHandler does not support file content retrieval") + raise NotImplementedError( + "GoogleAIStudioFilesHandler does not support file content retrieval" + ) diff --git a/litellm/llms/gemini/google_genai/transformation.py b/litellm/llms/gemini/google_genai/transformation.py index 48046dd9dfa..7c4c7dba626 100644 --- a/litellm/llms/gemini/google_genai/transformation.py +++ b/litellm/llms/gemini/google_genai/transformation.py @@ -75,7 +75,7 @@ class GoogleGenAIConfig(BaseGoogleGenAIGenerateContentConfig, VertexLLM): "seed", "response_mime_type", "response_schema", - "response_json_schema", + "response_json_schema", "routing_config", "model_selection_config", "safety_settings", @@ -111,29 +111,33 @@ class GoogleGenAIConfig(BaseGoogleGenAIGenerateContentConfig, VertexLLM): _camel_to_snake, _snake_to_camel, ) - + _generate_content_config_dict: Dict[str, Any] = {} supported_google_genai_params = ( self.get_supported_generate_content_optional_params(model) ) # Create a set with both camelCase and snake_case versions for faster lookup supported_params_set = set(supported_google_genai_params) - supported_params_set.update(_snake_to_camel(p) for p in supported_google_genai_params) - supported_params_set.update(_camel_to_snake(p) for p in supported_google_genai_params if "_" not in p) - + supported_params_set.update( + _snake_to_camel(p) for p in supported_google_genai_params + ) + supported_params_set.update( + _camel_to_snake(p) for p in supported_google_genai_params if "_" not in p + ) + for param, value in generate_content_config_dict.items(): # Google GenAI API expects camelCase, so we'll always output in camelCase # Check if param (or its variants) is supported param_snake = _camel_to_snake(param) param_camel = _snake_to_camel(param) - + # Check if param is supported in any format is_supported = ( - param in supported_google_genai_params or - param_snake in supported_google_genai_params or - param_camel in supported_google_genai_params + param in supported_google_genai_params + or param_snake in supported_google_genai_params + or param_camel in supported_google_genai_params ) - + if is_supported: # Always output in camelCase for Google GenAI API output_key = param_camel if param != param_camel else param @@ -234,9 +238,11 @@ class GoogleGenAIConfig(BaseGoogleGenAIGenerateContentConfig, VertexLLM): """ Sync version of get_auth_token_and_url. """ - vertex_credentials, vertex_project, vertex_location = ( - self._get_common_auth_components(litellm_params) - ) + ( + vertex_credentials, + vertex_project, + vertex_location, + ) = self._get_common_auth_components(litellm_params) _auth_header, vertex_project = self._ensure_access_token( credentials=vertex_credentials, @@ -273,9 +279,11 @@ class GoogleGenAIConfig(BaseGoogleGenAIGenerateContentConfig, VertexLLM): Returns: Tuple of headers and API base """ - vertex_credentials, vertex_project, vertex_location = ( - self._get_common_auth_components(litellm_params) - ) + ( + vertex_credentials, + vertex_project, + vertex_location, + ) = self._get_common_auth_components(litellm_params) _auth_header, vertex_project = await self._ensure_access_token_async( credentials=vertex_credentials, @@ -315,7 +323,7 @@ class GoogleGenAIConfig(BaseGoogleGenAIGenerateContentConfig, VertexLLM): ) request_dict = cast(dict, typed_generate_content_request) - + if system_instruction is not None: request_dict["systemInstruction"] = system_instruction return request_dict @@ -359,9 +367,13 @@ class GoogleGenAIConfig(BaseGoogleGenAIGenerateContentConfig, VertexLLM): """ if "candidates" in response: for candidate in response["candidates"]: - if "citationMetadata" in candidate and isinstance(candidate["citationMetadata"], dict): + if "citationMetadata" in candidate and isinstance( + candidate["citationMetadata"], dict + ): citation_metadata = candidate["citationMetadata"] # Transform citationSources to citations to match expected schema if "citationSources" in citation_metadata: - citation_metadata["citations"] = citation_metadata.pop("citationSources") - return response \ No newline at end of file + citation_metadata["citations"] = citation_metadata.pop( + "citationSources" + ) + return response diff --git a/litellm/llms/gemini/image_edit/__init__.py b/litellm/llms/gemini/image_edit/__init__.py index 6181015b811..cb097d3eee6 100644 --- a/litellm/llms/gemini/image_edit/__init__.py +++ b/litellm/llms/gemini/image_edit/__init__.py @@ -8,4 +8,3 @@ __all__ = ["GeminiImageEditConfig", "get_gemini_image_edit_config", "cost_calcul def get_gemini_image_edit_config(model: str) -> BaseImageEditConfig: return GeminiImageEditConfig() - diff --git a/litellm/llms/gemini/image_edit/cost_calculator.py b/litellm/llms/gemini/image_edit/cost_calculator.py index 31f35345d84..2e332a7fc00 100644 --- a/litellm/llms/gemini/image_edit/cost_calculator.py +++ b/litellm/llms/gemini/image_edit/cost_calculator.py @@ -32,4 +32,3 @@ def cost_calculator( num_images = len(image_response.data or []) return output_cost_per_image * num_images - diff --git a/litellm/llms/gemini/image_edit/transformation.py b/litellm/llms/gemini/image_edit/transformation.py index c3ea63ad43b..5d9b1255d09 100644 --- a/litellm/llms/gemini/image_edit/transformation.py +++ b/litellm/llms/gemini/image_edit/transformation.py @@ -73,7 +73,9 @@ class GeminiImageEditConfig(BaseImageEditConfig): api_base: Optional[str], litellm_params: dict, ) -> str: - base_url = api_base or get_secret_str("GEMINI_API_BASE") or self.DEFAULT_BASE_URL + base_url = ( + api_base or get_secret_str("GEMINI_API_BASE") or self.DEFAULT_BASE_URL + ) base_url = base_url.rstrip("/") return f"{base_url}/models/{model}:generateContent" @@ -109,9 +111,9 @@ class GeminiImageEditConfig(BaseImageEditConfig): # Move aspectRatio into imageConfig inside generationConfig if "imageConfig" not in generation_config: generation_config["imageConfig"] = {} - generation_config["imageConfig"]["aspectRatio"] = image_edit_optional_request_params[ + generation_config["imageConfig"][ "aspectRatio" - ] + ] = image_edit_optional_request_params["aspectRatio"] if generation_config: request_body["generationConfig"] = generation_config @@ -206,4 +208,4 @@ class GeminiImageEditConfig(BaseImageEditConfig): data = image.read() image.seek(current_pos) return data - raise ValueError("Unsupported image type for Gemini image edit.") \ No newline at end of file + raise ValueError("Unsupported image type for Gemini image edit.") diff --git a/litellm/llms/gemini/image_generation/cost_calculator.py b/litellm/llms/gemini/image_generation/cost_calculator.py index 941ab0d50f7..3c8e69374af 100644 --- a/litellm/llms/gemini/image_generation/cost_calculator.py +++ b/litellm/llms/gemini/image_generation/cost_calculator.py @@ -39,4 +39,6 @@ def cost_calculator( num_images = len(image_response.data) return output_cost_per_image * num_images else: - raise ValueError(f"image_response must be of type ImageResponse got type={type(image_response)}") + raise ValueError( + f"image_response must be of type ImageResponse got type={type(image_response)}" + ) diff --git a/litellm/llms/gemini/image_generation/transformation.py b/litellm/llms/gemini/image_generation/transformation.py index 73aef15e4c7..3e3f6162fce 100644 --- a/litellm/llms/gemini/image_generation/transformation.py +++ b/litellm/llms/gemini/image_generation/transformation.py @@ -28,7 +28,7 @@ else: class GoogleImageGenConfig(BaseImageGenerationConfig): DEFAULT_BASE_URL: str = "https://generativelanguage.googleapis.com/v1beta" - + def get_supported_openai_params( self, model: str ) -> List[OpenAIImageGenerationOptionalParams]: @@ -36,11 +36,8 @@ class GoogleImageGenConfig(BaseImageGenerationConfig): Google AI Imagen API supported parameters https://ai.google.dev/gemini-api/docs/imagen """ - return [ - "n", - "size" - ] - + return ["n", "size"] + def map_openai_params( self, non_default_params: dict, @@ -50,7 +47,7 @@ class GoogleImageGenConfig(BaseImageGenerationConfig): ) -> dict: supported_params = self.get_supported_openai_params(model) mapped_params = {} - + for k, v in non_default_params.items(): if k not in optional_params.keys(): if k in supported_params: @@ -61,9 +58,8 @@ class GoogleImageGenConfig(BaseImageGenerationConfig): # Map OpenAI size format to Google aspectRatio mapped_params["aspectRatio"] = self._map_size_to_aspect_ratio(v) else: - mapped_params[k] = v + mapped_params[k] = v return mapped_params - def _map_size_to_aspect_ratio(self, size: str) -> str: """ @@ -72,13 +68,13 @@ class GoogleImageGenConfig(BaseImageGenerationConfig): """ aspect_ratio_map = { "1024x1024": "1:1", - "1792x1024": "16:9", + "1792x1024": "16:9", "1024x1792": "9:16", "1280x896": "4:3", "896x1280": "3:4", } return aspect_ratio_map.get(size, "1:1") - + def _transform_image_usage(self, usage_metadata: dict) -> ImageUsage: """ Transform Gemini usageMetadata to ImageUsage format @@ -87,7 +83,7 @@ class GoogleImageGenConfig(BaseImageGenerationConfig): image_tokens=0, text_tokens=0, ) - + # Extract detailed token counts from promptTokensDetails tokens_details = usage_metadata.get("promptTokensDetails", []) for details in tokens_details: @@ -98,7 +94,7 @@ class GoogleImageGenConfig(BaseImageGenerationConfig): input_tokens_details.text_tokens = token_count elif modality == "IMAGE": input_tokens_details.image_tokens = token_count - + return ImageUsage( input_tokens=usage_metadata.get("promptTokenCount", 0), input_tokens_details=input_tokens_details, @@ -122,9 +118,7 @@ class GoogleImageGenConfig(BaseImageGenerationConfig): Other Imagen models: :predict """ complete_url: str = ( - api_base - or get_secret_str("GEMINI_API_BASE") - or self.DEFAULT_BASE_URL + api_base or get_secret_str("GEMINI_API_BASE") or self.DEFAULT_BASE_URL ) complete_url = complete_url.rstrip("/") @@ -148,13 +142,10 @@ class GoogleImageGenConfig(BaseImageGenerationConfig): api_key: Optional[str] = None, api_base: Optional[str] = None, ) -> dict: - final_api_key: Optional[str] = ( - api_key or - get_secret_str("GEMINI_API_KEY") - ) + final_api_key: Optional[str] = api_key or get_secret_str("GEMINI_API_KEY") if not final_api_key: raise ValueError("GEMINI_API_KEY is not set") - + headers["x-goog-api-key"] = final_api_key headers["Content-Type"] = "application/json" return headers @@ -187,16 +178,8 @@ class GoogleImageGenConfig(BaseImageGenerationConfig): # For Gemini Flash Image Preview models, use standard Gemini format if "gemini" in model: request_body: dict = { - "contents": [ - { - "parts": [ - {"text": prompt} - ] - } - ], - "generationConfig": { - "response_modalities": ["IMAGE", "TEXT"] - } + "contents": [{"parts": [{"text": prompt}]}], + "generationConfig": {"response_modalities": ["IMAGE", "TEXT"]}, } return request_body else: @@ -205,13 +188,12 @@ class GoogleImageGenConfig(BaseImageGenerationConfig): GeminiImageGenerationInstance, GeminiImageGenerationParameters, ) - request_body_obj: GeminiImageGenerationRequest = GeminiImageGenerationRequest( - instances=[ - GeminiImageGenerationInstance( - prompt=prompt - ) - ], - parameters=GeminiImageGenerationParameters(**optional_params) + + request_body_obj: GeminiImageGenerationRequest = ( + GeminiImageGenerationRequest( + instances=[GeminiImageGenerationInstance(prompt=prompt)], + parameters=GeminiImageGenerationParameters(**optional_params), + ) ) return request_body_obj.model_dump(exclude_none=True) @@ -239,7 +221,7 @@ class GoogleImageGenConfig(BaseImageGenerationConfig): status_code=raw_response.status_code, headers=raw_response.headers, ) - + if not model_response.data: model_response.data = [] @@ -256,22 +238,32 @@ class GoogleImageGenConfig(BaseImageGenerationConfig): 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, - )) - + 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 if "usageMetadata" in response_data: - model_response.usage = self._transform_image_usage(response_data["usageMetadata"]) + model_response.usage = self._transform_image_usage( + response_data["usageMetadata"] + ) else: # Original Imagen format - predictions with generated images predictions = response_data.get("predictions", []) for prediction in predictions: # Google AI returns base64 encoded images in the prediction - model_response.data.append(ImageObject( - b64_json=prediction.get("bytesBase64Encoded", None), - url=None, # Google AI returns base64, not URLs - )) - return model_response \ No newline at end of file + model_response.data.append( + ImageObject( + b64_json=prediction.get("bytesBase64Encoded", None), + url=None, # Google AI returns base64, not URLs + ) + ) + return model_response diff --git a/litellm/llms/gemini/interactions/transformation.py b/litellm/llms/gemini/interactions/transformation.py index d21775eb236..772530342e1 100644 --- a/litellm/llms/gemini/interactions/transformation.py +++ b/litellm/llms/gemini/interactions/transformation.py @@ -39,7 +39,7 @@ else: class GoogleAIStudioInteractionsConfig(BaseInteractionsAPIConfig): """ Configuration for Google AI Studio Interactions API. - + Minimal config - we follow the OpenAPI spec directly with no transformation. """ @@ -54,9 +54,18 @@ class GoogleAIStudioInteractionsConfig(BaseInteractionsAPIConfig): def get_supported_params(self, model: str) -> List[str]: """Per OpenAPI spec CreateModelInteractionParams.""" return [ - "model", "agent", "input", "tools", "system_instruction", - "generation_config", "stream", "store", "background", - "response_modalities", "response_format", "response_mime_type", + "model", + "agent", + "input", + "tools", + "system_instruction", + "generation_config", + "stream", + "store", + "background", + "response_modalities", + "response_format", + "response_mime_type", "previous_interaction_id", ] @@ -83,16 +92,16 @@ class GoogleAIStudioInteractionsConfig(BaseInteractionsAPIConfig): litellm_params = litellm_params or {} api_base = GeminiModelInfo.get_api_base(api_base) api_key = GeminiModelInfo.get_api_key(litellm_params.get("api_key")) - + if not api_key: raise ValueError( "Google API key is required. Set GOOGLE_API_KEY or GEMINI_API_KEY environment variable." ) - + query_params = f"key={api_key}" if stream: query_params += "&alt=sse" - + return f"{api_base}/{self.api_version}/interactions?{query_params}" def transform_request( @@ -108,7 +117,7 @@ class GoogleAIStudioInteractionsConfig(BaseInteractionsAPIConfig): Build request body per OpenAPI spec - minimal transformation. """ request_body: Dict[str, Any] = {} - + # Model or Agent (one required) if model: request_body["model"] = GeminiModelInfo.get_base_model(model) or model @@ -116,21 +125,28 @@ class GoogleAIStudioInteractionsConfig(BaseInteractionsAPIConfig): request_body["agent"] = agent else: raise ValueError("Either 'model' or 'agent' must be provided") - + # Input if input is not None: request_body["input"] = input - + # Pass through optional params directly (they match the spec) optional_keys = [ - "tools", "system_instruction", "generation_config", "stream", "store", - "background", "response_modalities", "response_format", - "response_mime_type", "previous_interaction_id", + "tools", + "system_instruction", + "generation_config", + "stream", + "store", + "background", + "response_modalities", + "response_format", + "response_mime_type", + "previous_interaction_id", ] for key in optional_keys: if optional_params.get(key) is not None: request_body[key] = optional_params[key] - + return request_body def transform_response( @@ -152,13 +168,15 @@ class GoogleAIStudioInteractionsConfig(BaseInteractionsAPIConfig): status_code=raw_response.status_code, headers=dict(raw_response.headers), ) - + verbose_logger.debug("Google AI Interactions response: %s", raw_json) - + response = InteractionsAPIResponse(**raw_json) response._hidden_params["headers"] = dict(raw_response.headers) - response._hidden_params["additional_headers"] = process_response_headers(dict(raw_response.headers)) - + response._hidden_params["additional_headers"] = process_response_headers( + dict(raw_response.headers) + ) + return response def transform_streaming_response( @@ -172,7 +190,7 @@ class GoogleAIStudioInteractionsConfig(BaseInteractionsAPIConfig): return InteractionsAPIStreamingResponse(**parsed_chunk) # GET / DELETE / CANCEL - just build URLs, responses match spec directly - + def transform_get_interaction_request( self, interaction_id: str, @@ -185,7 +203,10 @@ class GoogleAIStudioInteractionsConfig(BaseInteractionsAPIConfig): api_key = GeminiModelInfo.get_api_key(litellm_params.api_key) if not api_key: raise ValueError("Google API key is required") - return f"{resolved_api_base}/{self.api_version}/interactions/{interaction_id}?key={api_key}", {} + return ( + f"{resolved_api_base}/{self.api_version}/interactions/{interaction_id}?key={api_key}", + {}, + ) def transform_get_interaction_response( self, @@ -216,7 +237,10 @@ class GoogleAIStudioInteractionsConfig(BaseInteractionsAPIConfig): api_key = GeminiModelInfo.get_api_key(litellm_params.api_key) if not api_key: raise ValueError("Google API key is required") - return f"{resolved_api_base}/{self.api_version}/interactions/{interaction_id}?key={api_key}", {} + return ( + f"{resolved_api_base}/{self.api_version}/interactions/{interaction_id}?key={api_key}", + {}, + ) def transform_delete_interaction_response( self, @@ -244,7 +268,10 @@ class GoogleAIStudioInteractionsConfig(BaseInteractionsAPIConfig): api_key = GeminiModelInfo.get_api_key(litellm_params.api_key) if not api_key: raise ValueError("Google API key is required") - return f"{resolved_api_base}/{self.api_version}/interactions/{interaction_id}:cancel?key={api_key}", {} + return ( + f"{resolved_api_base}/{self.api_version}/interactions/{interaction_id}:cancel?key={api_key}", + {}, + ) def transform_cancel_interaction_response( self, diff --git a/litellm/llms/gemini/realtime/transformation.py b/litellm/llms/gemini/realtime/transformation.py index a3eedd36a64..2bb7bcd8b4f 100644 --- a/litellm/llms/gemini/realtime/transformation.py +++ b/litellm/llms/gemini/realtime/transformation.py @@ -186,10 +186,10 @@ class GeminiRealtimeConfig(BaseRealtimeConfig): ) vertex_gemini_config = VertexGeminiConfig() - optional_params["generationConfig"]["tools"] = ( - vertex_gemini_config._map_function( - value=value, optional_params=optional_params - ) + optional_params["generationConfig"][ + "tools" + ] = vertex_gemini_config._map_function( + value=value, optional_params=optional_params ) elif key == "input_audio_transcription" and value is not None: optional_params["inputAudioTranscription"] = {} @@ -201,10 +201,10 @@ class GeminiRealtimeConfig(BaseRealtimeConfig): if ( len(transformed_audio_activity_config) > 0 ): # if the config is not empty, add it to the optional params - optional_params["realtimeInputConfig"] = ( - BidiGenerateContentRealtimeInputConfig( - automaticActivityDetection=transformed_audio_activity_config - ) + optional_params[ + "realtimeInputConfig" + ] = BidiGenerateContentRealtimeInputConfig( + automaticActivityDetection=transformed_audio_activity_config ) if len(optional_params["generationConfig"]) == 0: optional_params.pop("generationConfig") @@ -235,9 +235,7 @@ class GeminiRealtimeConfig(BaseRealtimeConfig): optional_params={}, non_default_params=json_message["session"] ) client_session_configuration_request["model"] = f"models/{model}" - messages.append( - json.dumps({"setup": client_session_configuration_request}) - ) + messages.append(json.dumps({"setup": client_session_configuration_request})) return messages ## HANDLE response.create — Gemini responds automatically; nothing to forward ## @@ -320,7 +318,7 @@ class GeminiRealtimeConfig(BaseRealtimeConfig): if "/models/" in _model: session["model"] = _model.split("/models/")[-1] elif _model.startswith("models/"): - session["model"] = _model[len("models/"):] + session["model"] = _model[len("models/") :] else: session["model"] = _model @@ -779,8 +777,12 @@ class GeminiRealtimeConfig(BaseRealtimeConfig): # Use IDs from the done event — transform_content_done_event may have # generated UUID fallbacks when the originals were None. - resolved_item_id = transformed_content_done_event.get("item_id") or current_output_item_id - resolved_response_id = transformed_content_done_event.get("response_id") or current_response_id + resolved_item_id = ( + transformed_content_done_event.get("item_id") or current_output_item_id + ) + resolved_response_id = ( + transformed_content_done_event.get("response_id") or current_response_id + ) additional_items = self.return_additional_content_done_events( current_output_item_id=resolved_item_id, @@ -862,9 +864,9 @@ class GeminiRealtimeConfig(BaseRealtimeConfig): "session_configuration_request" ] current_item_chunks = realtime_response_transform_input["current_item_chunks"] - current_delta_type: Optional[ALL_DELTA_TYPES] = ( - realtime_response_transform_input["current_delta_type"] - ) + current_delta_type: Optional[ + ALL_DELTA_TYPES + ] = realtime_response_transform_input["current_delta_type"] returned_message: List[OpenAIRealtimeEvents] = [] # Handle transcription events that arrive independently from model @@ -875,32 +877,45 @@ class GeminiRealtimeConfig(BaseRealtimeConfig): input_tx = server_content.get("inputTranscription") if isinstance(input_tx, dict) and input_tx.get("text"): returned_message.append( - cast(OpenAIRealtimeEvents, { - "type": "conversation.item.input_audio_transcription.completed", - "event_id": "event_{}".format(uuid.uuid4()), - "transcript": input_tx["text"], - "item_id": "item_{}".format(uuid.uuid4()), - "content_index": 0, - }) + cast( + OpenAIRealtimeEvents, + { + "type": "conversation.item.input_audio_transcription.completed", + "event_id": "event_{}".format(uuid.uuid4()), + "transcript": input_tx["text"], + "item_id": "item_{}".format(uuid.uuid4()), + "content_index": 0, + }, + ) ) output_tx = server_content.get("outputTranscription") if isinstance(output_tx, dict) and output_tx.get("text"): returned_message.append( - cast(OpenAIRealtimeEvents, { - "type": "response.audio_transcript.delta", - "event_id": "event_{}".format(uuid.uuid4()), - "delta": output_tx["text"], - "item_id": current_output_item_id or "item_{}".format(uuid.uuid4()), - "response_id": current_response_id or "resp_{}".format(uuid.uuid4()), - "output_index": 0, - "content_index": 0, - }) + cast( + OpenAIRealtimeEvents, + { + "type": "response.audio_transcript.delta", + "event_id": "event_{}".format(uuid.uuid4()), + "delta": output_tx["text"], + "item_id": current_output_item_id + or "item_{}".format(uuid.uuid4()), + "response_id": current_response_id + or "resp_{}".format(uuid.uuid4()), + "output_index": 0, + "content_index": 0, + }, + ) ) # If serverContent only contained transcription(s) and no model # content, return early — the main loop would fail on unknown keys. - _model_content_keys = {"modelTurn", "turnComplete", "interrupted", "generationComplete"} + _model_content_keys = { + "modelTurn", + "turnComplete", + "interrupted", + "generationComplete", + } if not any(k in server_content for k in _model_content_keys): return { "response": returned_message, diff --git a/litellm/llms/gemini/vector_stores/__init__.py b/litellm/llms/gemini/vector_stores/__init__.py index 613b5775b66..b2d276ac21e 100644 --- a/litellm/llms/gemini/vector_stores/__init__.py +++ b/litellm/llms/gemini/vector_stores/__init__.py @@ -3,4 +3,3 @@ from .transformation import GeminiVectorStoreConfig __all__ = ["GeminiVectorStoreConfig"] - diff --git a/litellm/llms/gemini/vector_stores/transformation.py b/litellm/llms/gemini/vector_stores/transformation.py index 4d76f691e51..11fd77aecae 100644 --- a/litellm/llms/gemini/vector_stores/transformation.py +++ b/litellm/llms/gemini/vector_stores/transformation.py @@ -54,7 +54,7 @@ class GeminiVectorStoreConfig(BaseVectorStoreConfig): def get_vector_store_endpoints_by_type(self) -> VectorStoreIndexEndpoints: """ Gemini File Search endpoints. - + Note: Search is done via generateContent with file_search tool, not a dedicated search endpoint. """ @@ -79,22 +79,22 @@ class GeminiVectorStoreConfig(BaseVectorStoreConfig): api_key = litellm_params.get("api_key") or get_api_key_from_env() if api_key: self._cached_api_key = api_key - + return headers def get_complete_url(self, api_base: Optional[str], litellm_params: dict) -> str: """ Get the complete base URL for Gemini API. - + Note: This returns the base URL WITHOUT the API key. The API key will be appended to specific endpoint URLs in the transform methods. """ if api_base is None: api_base = GeminiModelInfo.get_api_base() - + if api_base is None: raise ValueError("GEMINI_API_BASE is not set") - + # Ensure we're using the v1beta version for File Search api_version = "v1beta" return f"{api_base}/{api_version}" @@ -120,7 +120,7 @@ class GeminiVectorStoreConfig(BaseVectorStoreConfig): ) -> Tuple[str, Dict]: """ Transform search request to Gemini's generateContent format. - + Gemini File Search works by calling generateContent with a file_search tool. """ # Convert query list to single string if needed @@ -157,23 +157,15 @@ class GeminiVectorStoreConfig(BaseVectorStoreConfig): if isinstance(value, str): filter_parts.append(f'{key} = "{value}"') else: - filter_parts.append(f'{key} = {value}') + filter_parts.append(f"{key} = {value}") file_search_config["metadata_filter"] = " AND ".join(filter_parts) else: file_search_config["metadata_filter"] = metadata_filter # Build request body request_body: Dict[str, Any] = { - "contents": [ - { - "parts": [{"text": query}] - } - ], - "tools": [ - { - "file_search": file_search_config - } - ], + "contents": [{"parts": [{"text": query}]}], + "tools": [{"file_search": file_search_config}], } # Add max_num_results if specified @@ -193,7 +185,7 @@ class GeminiVectorStoreConfig(BaseVectorStoreConfig): ) -> VectorStoreSearchResponse: """ Transform Gemini's generateContent response to standard format. - + Extracts grounding metadata and citations from the response. """ try: @@ -202,28 +194,30 @@ class GeminiVectorStoreConfig(BaseVectorStoreConfig): # Extract candidates and grounding metadata candidates = response_data.get("candidates", []) - + for candidate in candidates: grounding_metadata = candidate.get("groundingMetadata", {}) grounding_chunks = grounding_metadata.get("groundingChunks", []) - + # Process each grounding chunk for chunk in grounding_chunks: retrieved_context = chunk.get("retrievedContext") - + if retrieved_context: # This is from file search text = retrieved_context.get("text", "") uri = retrieved_context.get("uri", "") title = retrieved_context.get("title", "") - + # Extract file_id from URI if available file_id = uri if uri else None - + results.append( VectorStoreSearchResult( score=None, # Gemini doesn't provide explicit scores - content=[VectorStoreResultContent(text=text, type="text")], + content=[ + VectorStoreResultContent(text=text, type="text") + ], file_id=file_id, filename=title if title else None, attributes={ @@ -238,13 +232,13 @@ class GeminiVectorStoreConfig(BaseVectorStoreConfig): for support in grounding_supports: segment = support.get("segment", {}) text = segment.get("text", "") - + grounding_chunk_indices = support.get("groundingChunkIndices", []) confidence_scores = support.get("confidenceScores", []) - + # Use first confidence score as relevance score score = confidence_scores[0] if confidence_scores else None - + # Only add if we have meaningful text and it's not a duplicate if text: already_exists = False @@ -258,7 +252,9 @@ class GeminiVectorStoreConfig(BaseVectorStoreConfig): results.append( VectorStoreSearchResult( score=score, - content=[VectorStoreResultContent(text=text, type="text")], + content=[ + VectorStoreResultContent(text=text, type="text") + ], attributes={ "grounding_chunk_indices": grounding_chunk_indices, }, @@ -266,7 +262,7 @@ class GeminiVectorStoreConfig(BaseVectorStoreConfig): ) query = litellm_logging_obj.model_call_details.get("query", "") - + return VectorStoreSearchResponse( object="vector_store.search_results.page", search_query=query, @@ -289,7 +285,7 @@ class GeminiVectorStoreConfig(BaseVectorStoreConfig): Transform create request to Gemini's fileSearchStores format. """ url = f"{api_base}/fileSearchStores" - + # Append API key as query parameter (required by Gemini) api_key = self._cached_api_key or get_api_key_from_env() if api_key: @@ -312,7 +308,7 @@ class GeminiVectorStoreConfig(BaseVectorStoreConfig): """ try: response_data = response.json() - + # Extract store name (format: fileSearchStores/xxxxxxx) store_name = response_data.get("name", "") display_name = response_data.get("displayName", "") @@ -320,10 +316,13 @@ class GeminiVectorStoreConfig(BaseVectorStoreConfig): # Convert ISO timestamp to Unix timestamp import datetime + created_at = None if create_time: try: - dt = datetime.datetime.fromisoformat(create_time.replace("Z", "+00:00")) + dt = datetime.datetime.fromisoformat( + create_time.replace("Z", "+00:00") + ) created_at = int(dt.timestamp()) except Exception: created_at = None @@ -354,4 +353,3 @@ class GeminiVectorStoreConfig(BaseVectorStoreConfig): status_code=response.status_code, headers=response.headers, ) - diff --git a/litellm/llms/gemini/videos/__init__.py b/litellm/llms/gemini/videos/__init__.py index c5aed2db2d0..b8e0452cb0a 100644 --- a/litellm/llms/gemini/videos/__init__.py +++ b/litellm/llms/gemini/videos/__init__.py @@ -2,4 +2,3 @@ from .transformation import GeminiVideoConfig __all__ = ["GeminiVideoConfig"] - diff --git a/litellm/llms/gemini/videos/transformation.py b/litellm/llms/gemini/videos/transformation.py index 7daeb75b651..c16b20fe579 100644 --- a/litellm/llms/gemini/videos/transformation.py +++ b/litellm/llms/gemini/videos/transformation.py @@ -13,7 +13,12 @@ from litellm.types.videos.utils import ( ) from litellm.images.utils import ImageEditRequestUtils import litellm -from litellm.types.llms.gemini import GeminiLongRunningOperationResponse, GeminiVideoGenerationInstance, GeminiVideoGenerationParameters, GeminiVideoGenerationRequest +from litellm.types.llms.gemini import ( + GeminiLongRunningOperationResponse, + GeminiVideoGenerationInstance, + GeminiVideoGenerationParameters, + GeminiVideoGenerationRequest, +) from litellm.constants import DEFAULT_GOOGLE_VIDEO_DURATION_SECONDS from litellm.llms.base_llm.videos.transformation import BaseVideoConfig @@ -31,30 +36,27 @@ else: def _convert_image_to_gemini_format(image_file) -> Dict[str, str]: """ Convert image file to Gemini format with base64 encoding and MIME type. - + Args: image_file: File-like object opened in binary mode (e.g., open("path", "rb")) - + Returns: Dict with bytesBase64Encoded and mimeType """ mime_type = ImageEditRequestUtils.get_image_content_type(image_file) - - if hasattr(image_file, 'seek'): + + if hasattr(image_file, "seek"): image_file.seek(0) image_bytes = image_file.read() base64_encoded = base64.b64encode(image_bytes).decode("utf-8") - - return { - "bytesBase64Encoded": base64_encoded, - "mimeType": mime_type - } + + return {"bytesBase64Encoded": base64_encoded, "mimeType": mime_type} class GeminiVideoConfig(BaseVideoConfig): """ Configuration class for Gemini (Veo) video generation. - + Veo uses a long-running operation model: 1. POST to :predictLongRunning returns operation name 2. Poll operation until done=true @@ -70,13 +72,7 @@ class GeminiVideoConfig(BaseVideoConfig): Get the list of supported OpenAI parameters for Veo video generation. Veo supports minimal parameters compared to OpenAI. """ - return [ - "model", - "prompt", - "input_reference", - "seconds", - "size" - ] + return ["model", "prompt", "input_reference", "seconds", "size"] def map_openai_params( self, @@ -86,28 +82,29 @@ class GeminiVideoConfig(BaseVideoConfig): ) -> Dict[str, Any]: """ Map OpenAI-style parameters to Veo format. - + Mappings: - prompt → prompt - input_reference → image - size → aspectRatio (e.g., "1280x720" → "16:9") - seconds → durationSeconds (defaults to 4 seconds if not provided) - + All other params are passed through as-is to support Gemini-specific parameters. """ mapped_params: Dict[str, Any] = {} - + # Get supported OpenAI params (exclude "model" and "prompt" which are handled separately) supported_openai_params = self.get_supported_openai_params(model) openai_params_to_map = { - param for param in supported_openai_params + param + for param in supported_openai_params if param not in {"model", "prompt"} } - + # Map input_reference to image if "input_reference" in video_create_optional_params: mapped_params["image"] = video_create_optional_params["input_reference"] - + # Map size to aspectRatio if "size" in video_create_optional_params: size = video_create_optional_params["size"] @@ -115,7 +112,7 @@ class GeminiVideoConfig(BaseVideoConfig): aspect_ratio = self._convert_size_to_aspect_ratio(size) if aspect_ratio: mapped_params["aspectRatio"] = aspect_ratio - + # Map seconds to durationSeconds, default to 4 seconds (matching OpenAI) if "seconds" in video_create_optional_params: seconds = video_create_optional_params["seconds"] @@ -126,34 +123,33 @@ class GeminiVideoConfig(BaseVideoConfig): except (ValueError, TypeError): # If conversion fails, use default pass - + # Pass through any other params that weren't mapped (Gemini-specific params) for key, value in video_create_optional_params.items(): if key not in openai_params_to_map and key not in mapped_params: mapped_params[key] = value - + return mapped_params - + def _convert_size_to_aspect_ratio(self, size: str) -> Optional[str]: """ Convert OpenAI size format to Veo aspectRatio format. - + https://cloud.google.com/vertex-ai/generative-ai/docs/image/generate-videos - + Supported aspect ratios: 9:16 (portrait), 16:9 (landscape) """ if not size: return None - + aspect_ratio_map = { "1280x720": "16:9", "1920x1080": "16:9", "720x1280": "9:16", "1080x1920": "9:16", } - - return aspect_ratio_map.get(size, "16:9") + return aspect_ratio_map.get(size, "16:9") def validate_environment( self, @@ -169,24 +165,26 @@ class GeminiVideoConfig(BaseVideoConfig): # Use api_key from litellm_params if available, otherwise fall back to other sources if litellm_params and litellm_params.api_key: api_key = api_key or litellm_params.api_key - + api_key = ( api_key or litellm.api_key or get_secret_str("GOOGLE_API_KEY") or get_secret_str("GEMINI_API_KEY") ) - + if not api_key: raise ValueError( "GEMINI_API_KEY or GOOGLE_API_KEY is required for Veo video generation. " "Set it via environment variable or pass it as api_key parameter." ) - - headers.update({ - "x-goog-api-key": api_key, - "Content-Type": "application/json", - }) + + headers.update( + { + "x-goog-api-key": api_key, + "Content-Type": "application/json", + } + ) return headers def get_complete_url( @@ -201,14 +199,17 @@ class GeminiVideoConfig(BaseVideoConfig): For status/delete: returns base URL only """ if api_base is None: - api_base = get_secret_str("GEMINI_API_BASE") or "https://generativelanguage.googleapis.com" - + api_base = ( + get_secret_str("GEMINI_API_BASE") + or "https://generativelanguage.googleapis.com" + ) + if not model or model == "": - return api_base.rstrip('/') - + return api_base.rstrip("/") + model_name = model.replace("gemini/", "") url = f"{api_base.rstrip('/')}/v1beta/models/{model_name}:predictLongRunning" - + return url def transform_video_create_request( @@ -222,7 +223,7 @@ class GeminiVideoConfig(BaseVideoConfig): ) -> Tuple[Dict, RequestFiles, str]: """ Transform the video creation request for Veo API. - + Veo expects: { "instances": [ @@ -238,22 +239,21 @@ class GeminiVideoConfig(BaseVideoConfig): } """ instance = GeminiVideoGenerationInstance(prompt=prompt) - + params_copy = video_create_optional_request_params.copy() - + if "image" in params_copy and params_copy["image"] is not None: image_data = _convert_image_to_gemini_format(params_copy["image"]) params_copy["image"] = image_data - + parameters = GeminiVideoGenerationParameters(**params_copy) - + request_body_obj = GeminiVideoGenerationRequest( - instances=[instance], - parameters=parameters + instances=[instance], parameters=parameters ) - + request_data = request_body_obj.model_dump(exclude_none=True) - + return request_data, [], api_base def transform_video_create_response( @@ -266,7 +266,7 @@ class GeminiVideoConfig(BaseVideoConfig): ) -> VideoObject: """ Transform the Veo video creation response. - + Veo returns: { "name": "operations/generate_1234567890", @@ -274,46 +274,51 @@ class GeminiVideoConfig(BaseVideoConfig): "done": false, "error": {...} } - + We return this as a VideoObject with: - id: operation name (used for polling) - status: "processing" - usage: includes duration_seconds for cost calculation - """ + """ response_data = raw_response.json() - + # Parse response using Pydantic model for type safety try: operation_response = GeminiLongRunningOperationResponse(**response_data) except Exception as e: raise ValueError(f"Failed to parse operation response: {e}") - + operation_name = operation_response.name if not operation_name: raise ValueError(f"No operation name in Veo response: {response_data}") - + if custom_llm_provider: - video_id = encode_video_id_with_provider(operation_name, custom_llm_provider, model) + video_id = encode_video_id_with_provider( + operation_name, custom_llm_provider, model + ) else: video_id = operation_name - + video_obj = VideoObject( id=video_id, object="video", status="processing", model=model, ) - + usage_data = {} if request_data: parameters = request_data.get("parameters", {}) - duration = parameters.get("durationSeconds") or DEFAULT_GOOGLE_VIDEO_DURATION_SECONDS + duration = ( + parameters.get("durationSeconds") + or DEFAULT_GOOGLE_VIDEO_DURATION_SECONDS + ) if duration is not None: try: usage_data["duration_seconds"] = float(duration) except (ValueError, TypeError): pass - + video_obj.usage = usage_data return video_obj @@ -326,14 +331,14 @@ class GeminiVideoConfig(BaseVideoConfig): ) -> Tuple[str, Dict]: """ Transform the video status retrieve request for Veo API. - + Veo polls operations at: GET https://generativelanguage.googleapis.com/v1beta/{operation_name} """ operation_name = extract_original_video_id(video_id) url = f"{api_base.rstrip('/')}/v1beta/{operation_name}" params: Dict[str, Any] = {} - + return url, params def transform_video_status_retrieve_response( @@ -344,13 +349,13 @@ class GeminiVideoConfig(BaseVideoConfig): ) -> VideoObject: """ Transform the Veo operation status response. - + Veo returns: { "name": "operations/generate_1234567890", "done": false # or true when complete } - + When done=true: { "name": "operations/generate_1234567890", @@ -367,23 +372,25 @@ class GeminiVideoConfig(BaseVideoConfig): } } } - """ + """ response_data = raw_response.json() # Parse response using Pydantic model for type safety operation_response = GeminiLongRunningOperationResponse(**response_data) - + operation_name = operation_response.name is_done = operation_response.done - + if custom_llm_provider: - video_id = encode_video_id_with_provider(operation_name, custom_llm_provider, None) + video_id = encode_video_id_with_provider( + operation_name, custom_llm_provider, None + ) else: video_id = operation_name - + video_obj = VideoObject( id=video_id, object="video", - status="processing" if not is_done else "completed" + status="processing" if not is_done else "completed", ) return video_obj @@ -401,15 +408,15 @@ class GeminiVideoConfig(BaseVideoConfig): For Veo, we need to: 1. Get operation status to extract video URI 2. Return download URL for the video - """ + """ operation_name = extract_original_video_id(video_id) - + status_url = f"{api_base.rstrip('/')}/v1beta/{operation_name}" client = litellm.module_level_client status_response = client.get(url=status_url, headers=headers) status_response.raise_for_status() response_data = status_response.json() - + operation_response = GeminiLongRunningOperationResponse(**response_data) if not operation_response.done: @@ -417,15 +424,17 @@ class GeminiVideoConfig(BaseVideoConfig): "Video generation is not complete yet. " "Please check status with video_status() before downloading." ) - + if not operation_response.response: raise ValueError("No response data in completed operation") - - generated_samples = operation_response.response.generateVideoResponse.generatedSamples + + generated_samples = ( + operation_response.response.generateVideoResponse.generatedSamples + ) download_url = generated_samples[0].video.uri - + params: Dict[str, Any] = {} - + return download_url, params def transform_video_content_response( @@ -525,4 +534,3 @@ class GeminiVideoConfig(BaseVideoConfig): message=error_message, headers=headers, ) - diff --git a/litellm/llms/gigachat/authenticator.py b/litellm/llms/gigachat/authenticator.py index e61015a4a21..59942a9c038 100644 --- a/litellm/llms/gigachat/authenticator.py +++ b/litellm/llms/gigachat/authenticator.py @@ -104,7 +104,9 @@ def get_access_token( token, expires_at = _request_token_sync(credentials, scope, auth_url) # Cache token - ttl_seconds = max(0, (expires_at - TOKEN_EXPIRY_BUFFER_MS - time.time() * 1000) / 1000) + ttl_seconds = max( + 0, (expires_at - TOKEN_EXPIRY_BUFFER_MS - time.time() * 1000) / 1000 + ) if ttl_seconds > 0: _token_cache.set_cache(cache_key, (token, expires_at), ttl=ttl_seconds) @@ -140,7 +142,9 @@ async def get_access_token_async( token, expires_at = await _request_token_async(credentials, scope, auth_url) # Cache token - ttl_seconds = max(0, (expires_at - TOKEN_EXPIRY_BUFFER_MS - time.time() * 1000) / 1000) + ttl_seconds = max( + 0, (expires_at - TOKEN_EXPIRY_BUFFER_MS - time.time() * 1000) / 1000 + ) if ttl_seconds > 0: _token_cache.set_cache(cache_key, (token, expires_at), ttl=ttl_seconds) diff --git a/litellm/llms/gigachat/chat/streaming.py b/litellm/llms/gigachat/chat/streaming.py index 3565559e43c..4f10f8bb658 100644 --- a/litellm/llms/gigachat/chat/streaming.py +++ b/litellm/llms/gigachat/chat/streaming.py @@ -6,7 +6,10 @@ import json import uuid from typing import Any, Optional -from litellm.types.llms.openai import ChatCompletionToolCallChunk, ChatCompletionToolCallFunctionChunk +from litellm.types.llms.openai import ( + ChatCompletionToolCallChunk, + ChatCompletionToolCallFunctionChunk, +) from litellm.types.utils import GenericStreamingChunk diff --git a/litellm/llms/gigachat/chat/transformation.py b/litellm/llms/gigachat/chat/transformation.py index f546f356e11..cef80768762 100644 --- a/litellm/llms/gigachat/chat/transformation.py +++ b/litellm/llms/gigachat/chat/transformation.py @@ -254,7 +254,7 @@ class GigaChatConfig(BaseConfig): func_name = tool_choice.get("function", {}).get("name") if func_name: return {"name": func_name} - + # Default to None (don't set function_call) return None diff --git a/litellm/llms/github_copilot/authenticator.py b/litellm/llms/github_copilot/authenticator.py index 7d7ef522a43..85c22516f95 100644 --- a/litellm/llms/github_copilot/authenticator.py +++ b/litellm/llms/github_copilot/authenticator.py @@ -357,7 +357,6 @@ class Authenticator: print( # noqa: T201 f"Please visit {verification_uri} and enter code {user_code} to authenticate.", - # When this is running in docker, it may not be flushed immediately # so we force flush to ensure the user sees the message flush=True, diff --git a/litellm/llms/github_copilot/common_utils.py b/litellm/llms/github_copilot/common_utils.py index 7870f56b842..d3169e3ca94 100644 --- a/litellm/llms/github_copilot/common_utils.py +++ b/litellm/llms/github_copilot/common_utils.py @@ -15,6 +15,7 @@ USER_AGENT = f"GitHubCopilotChat/{COPILOT_VERSION}" API_VERSION = "2025-04-01" GITHUB_COPILOT_API_BASE = "https://api.githubcopilot.com" + class GithubCopilotError(BaseLLMException): def __init__( self, diff --git a/litellm/llms/github_copilot/embedding/transformation.py b/litellm/llms/github_copilot/embedding/transformation.py index 01466010271..fa7bd4e3223 100644 --- a/litellm/llms/github_copilot/embedding/transformation.py +++ b/litellm/llms/github_copilot/embedding/transformation.py @@ -100,9 +100,7 @@ class GithubCopilotEmbeddingConfig(BaseEmbeddingConfig): """ # Use provided api_base or fall back to authenticator's base or default api_base = ( - self.authenticator.get_api_base() - or api_base - or GITHUB_COPILOT_API_BASE + self.authenticator.get_api_base() or api_base or GITHUB_COPILOT_API_BASE ) # Remove trailing slashes @@ -121,7 +119,7 @@ class GithubCopilotEmbeddingConfig(BaseEmbeddingConfig): """ Transform embedding request to GitHub Copilot format. """ - + # Ensure input is a list if isinstance(input, str): input = [input] @@ -151,10 +149,10 @@ class GithubCopilotEmbeddingConfig(BaseEmbeddingConfig): Transform embedding response from GitHub Copilot format. """ logging_obj.post_call(original_response=raw_response.text) - + # GitHub Copilot returns standard OpenAI-compatible embedding response response_json = raw_response.json() - + return convert_to_model_response_object( response_object=response_json, model_response_object=model_response, @@ -189,4 +187,3 @@ class GithubCopilotEmbeddingConfig(BaseEmbeddingConfig): return OpenAIConfig().get_error_class( error_message=error_message, status_code=status_code, headers=headers ) - diff --git a/litellm/llms/github_copilot/responses/transformation.py b/litellm/llms/github_copilot/responses/transformation.py index 73240d46512..46efc124b1d 100644 --- a/litellm/llms/github_copilot/responses/transformation.py +++ b/litellm/llms/github_copilot/responses/transformation.py @@ -166,9 +166,7 @@ class GithubCopilotResponsesAPIConfig(OpenAIResponsesAPIConfig): """ # Use provided api_base or fall back to authenticator's base or default api_base = ( - api_base - or self.authenticator.get_api_base() - or GITHUB_COPILOT_API_BASE + api_base or self.authenticator.get_api_base() or GITHUB_COPILOT_API_BASE ) # Remove trailing slashes @@ -308,7 +306,9 @@ class GithubCopilotResponsesAPIConfig(OpenAIResponsesAPIConfig): # Check arrays if isinstance(value, list): return any( - self._contains_vision_content(item, depth=depth + 1, max_depth=max_depth) + self._contains_vision_content( + item, depth=depth + 1, max_depth=max_depth + ) for item in value ) @@ -324,7 +324,9 @@ class GithubCopilotResponsesAPIConfig(OpenAIResponsesAPIConfig): # Check content field recursively if "content" in value and isinstance(value["content"], list): return any( - self._contains_vision_content(item, depth=depth + 1, max_depth=max_depth) + self._contains_vision_content( + item, depth=depth + 1, max_depth=max_depth + ) for item in value["content"] ) diff --git a/litellm/llms/google_pse/search/__init__.py b/litellm/llms/google_pse/search/__init__.py index cda3f360f9d..0fcfff82c38 100644 --- a/litellm/llms/google_pse/search/__init__.py +++ b/litellm/llms/google_pse/search/__init__.py @@ -4,5 +4,3 @@ Google Programmable Search Engine (PSE) API module. from litellm.llms.google_pse.search.transformation import GooglePSESearchConfig __all__ = ["GooglePSESearchConfig"] - - diff --git a/litellm/llms/google_pse/search/transformation.py b/litellm/llms/google_pse/search/transformation.py index c1ba9cfe629..2fabbc5d16e 100644 --- a/litellm/llms/google_pse/search/transformation.py +++ b/litellm/llms/google_pse/search/transformation.py @@ -18,6 +18,7 @@ from litellm.secret_managers.main import get_secret_str class _GooglePSESearchRequestRequired(TypedDict): """Required fields for Google PSE Search API request.""" + q: str # Required - search query cx: str # Required - Programmable Search Engine ID key: str # Required - API key @@ -28,6 +29,7 @@ class GooglePSESearchRequest(_GooglePSESearchRequestRequired, total=False): Google Programmable Search Engine API request format. Based on: https://developers.google.com/custom-search/v1/reference/rest/v1/cse/list """ + num: int # Optional - number of results (1-10), default 10 start: int # Optional - index of first result (default 1) cr: str # Optional - country restrict (e.g., 'countryUS', 'countryGB') @@ -54,17 +56,17 @@ class GooglePSESearchRequest(_GooglePSESearchRequestRequired, total=False): class GooglePSESearchConfig(BaseSearchConfig): GOOGLE_PSE_API_BASE = "https://www.googleapis.com/customsearch/v1" - + @staticmethod def ui_friendly_name() -> str: return "Google PSE" - + def get_http_method(self) -> Literal["GET", "POST"]: """ Google PSE uses GET requests with query parameters. """ return "GET" - + def validate_environment( self, headers: Dict, @@ -74,19 +76,25 @@ class GooglePSESearchConfig(BaseSearchConfig): ) -> Dict: """ Validate environment and return headers. - + Google PSE uses API key as a query parameter, not in headers. This method is called but headers are not used for authentication. """ api_key = api_key or get_secret_str("GOOGLE_PSE_API_KEY") if not api_key: - raise ValueError("GOOGLE_PSE_API_KEY is not set. Set `GOOGLE_PSE_API_KEY` environment variable.") - + raise ValueError( + "GOOGLE_PSE_API_KEY is not set. Set `GOOGLE_PSE_API_KEY` environment variable." + ) + # Also check for search engine ID - search_engine_id = kwargs.get("search_engine_id") or get_secret_str("GOOGLE_PSE_ENGINE_ID") + search_engine_id = kwargs.get("search_engine_id") or get_secret_str( + "GOOGLE_PSE_ENGINE_ID" + ) if not search_engine_id: - raise ValueError("GOOGLE_PSE_ENGINE_ID is not set. Set `GOOGLE_PSE_ENGINE_ID` environment variable or pass `search_engine_id` parameter.") - + raise ValueError( + "GOOGLE_PSE_ENGINE_ID is not set. Set `GOOGLE_PSE_ENGINE_ID` environment variable or pass `search_engine_id` parameter." + ) + headers["Content-Type"] = "application/json" return headers @@ -99,22 +107,25 @@ class GooglePSESearchConfig(BaseSearchConfig): ) -> str: """ Get complete URL for Search endpoint with query parameters. - + Google PSE uses GET requests, so we build the full URL with query params here. The transformed request body (data) contains the parameters needed for the URL. """ from urllib.parse import urlencode - - api_base = api_base or get_secret_str("GOOGLE_PSE_API_BASE") or self.GOOGLE_PSE_API_BASE - + + api_base = ( + api_base + or get_secret_str("GOOGLE_PSE_API_BASE") + or self.GOOGLE_PSE_API_BASE + ) + # Build query parameters from the transformed request body if data and isinstance(data, dict) and "_google_pse_params" in data: params = data["_google_pse_params"] query_string = urlencode(params) return f"{api_base}?{query_string}" - + return api_base - def transform_search_request( self, @@ -126,22 +137,22 @@ class GooglePSESearchConfig(BaseSearchConfig): ) -> Dict: """ Transform Search request to Google PSE API format. - + Transforms Perplexity unified spec parameters: - query → q (same) - max_results → num - search_domain_filter → siteSearch - country → gl - max_tokens_per_page → (not applicable, ignored) - + All other Google PSE-specific parameters are passed through as-is. - + Args: query: Search query (string or list of strings). Google PSE supports single string queries. optional_params: Optional parameters for the request api_key: Google API key search_engine_id: Google Programmable Search Engine ID (cx parameter) - + Returns: Dict with typed request data following GooglePSESearchRequest spec """ @@ -152,7 +163,7 @@ class GooglePSESearchConfig(BaseSearchConfig): # Get API credentials api_key = api_key or get_secret_str("GOOGLE_PSE_API_KEY") search_engine_id = search_engine_id or get_secret_str("GOOGLE_PSE_ENGINE_ID") - + if not api_key: raise ValueError("GOOGLE_PSE_API_KEY is required") if not search_engine_id: @@ -163,13 +174,13 @@ class GooglePSESearchConfig(BaseSearchConfig): "cx": search_engine_id, "key": api_key, } - + # Transform unified spec parameters to Google PSE format if "max_results" in optional_params: # Google PSE supports 1-10 results per request num_results = min(optional_params["max_results"], 10) request_data["num"] = num_results - + if "search_domain_filter" in optional_params: # Convert list to single domain (take first if multiple) domains = optional_params["search_domain_filter"] @@ -179,19 +190,22 @@ class GooglePSESearchConfig(BaseSearchConfig): elif isinstance(domains, str): request_data["siteSearch"] = domains request_data["siteSearchFilter"] = "i" # include - + if "country" in optional_params: # Google PSE uses 2-letter country codes for gl parameter request_data["gl"] = optional_params["country"].upper() - + # Convert to dict before dynamic key assignments result_data = dict(request_data) - + # Pass through all other parameters as-is for param, value in optional_params.items(): - if param not in self.get_supported_perplexity_optional_params() and param not in result_data: + if ( + param not in self.get_supported_perplexity_optional_params() + and param not in result_data + ): result_data[param] = value - + # Store params in special key for URL building (Google PSE uses GET not POST) # Return a wrapper dict that stores params for get_complete_url to use return { @@ -206,22 +220,22 @@ class GooglePSESearchConfig(BaseSearchConfig): ) -> SearchResponse: """ Transform Google PSE API response to LiteLLM unified SearchResponse format. - + Google PSE → LiteLLM mappings: - items[].title → SearchResult.title - items[].link → SearchResult.url - items[].snippet → SearchResult.snippet - No date/last_updated fields in Google PSE response (set to None) - + Args: raw_response: Raw httpx response from Google PSE API logging_obj: Logging object for tracking - + Returns: SearchResponse with standardized format """ response_json = raw_response.json() - + # Transform results to SearchResult objects results = [] for item in response_json.get("items", []): @@ -233,10 +247,8 @@ class GooglePSESearchConfig(BaseSearchConfig): last_updated=None, # Google PSE doesn't provide last_updated in response ) results.append(search_result) - + return SearchResponse( results=results, object="search", ) - - diff --git a/litellm/llms/gradient_ai/chat/transformation.py b/litellm/llms/gradient_ai/chat/transformation.py index d631affdef8..1bc5e8896b1 100644 --- a/litellm/llms/gradient_ai/chat/transformation.py +++ b/litellm/llms/gradient_ai/chat/transformation.py @@ -12,7 +12,6 @@ GRADIENT_AI_SERVERLESS_ENDPOINT = "https://inference.do-ai.run" class GradientAIConfig(OpenAILikeChatConfig): - k: Optional[int] = None kb_filters: Optional[List[Dict]] = None filter_kb_content_by_query_metadata: Optional[bool] = None @@ -21,7 +20,9 @@ class GradientAIConfig(OpenAILikeChatConfig): include_retrieval_info: Optional[bool] = None include_guardrails_info: Optional[bool] = None provide_citations: Optional[bool] = None - retrieval_method: Optional[Literal["rewrite", "step_back", "sub_queries", "none"]] = None + retrieval_method: Optional[ + Literal["rewrite", "step_back", "sub_queries", "none"] + ] = None def __init__( self, @@ -76,14 +77,16 @@ class GradientAIConfig(OpenAILikeChatConfig): ] return supported_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): + 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, + ): api_key = api_key or get_secret_str("GRADIENT_AI_API_KEY") if api_key is None: raise ValueError("GradientAI API key not found") @@ -107,7 +110,10 @@ class GradientAIConfig(OpenAILikeChatConfig): if api_base and api_base != GRADIENT_AI_SERVERLESS_ENDPOINT: complete_url = f"{api_base}/api/v1/chat/completions" - elif gradient_ai_endpoint and gradient_ai_endpoint != GRADIENT_AI_SERVERLESS_ENDPOINT: + elif ( + gradient_ai_endpoint + and gradient_ai_endpoint != GRADIENT_AI_SERVERLESS_ENDPOINT + ): complete_url = f"{gradient_ai_endpoint}/api/v1/chat/completions" return complete_url @@ -139,9 +145,10 @@ class GradientAIConfig(OpenAILikeChatConfig): optional_params[param] = value elif not drop_params: from litellm.utils import UnsupportedParamsError + raise UnsupportedParamsError( status_code=400, - message=f"GradientAI does not support parameter '{param}'. To drop unsupported params, set `drop_params=True`." + message=f"GradientAI does not support parameter '{param}'. To drop unsupported params, set `drop_params=True`.", ) return optional_params diff --git a/litellm/llms/heroku/chat/transformation.py b/litellm/llms/heroku/chat/transformation.py index a64d8afe63a..d95e953636f 100644 --- a/litellm/llms/heroku/chat/transformation.py +++ b/litellm/llms/heroku/chat/transformation.py @@ -12,10 +12,12 @@ from litellm.litellm_core_utils.prompt_templates.common_utils import ( from litellm.types.llms.openai import AllMessageValues from litellm.llms.openai.chat.gpt_transformation import OpenAIGPTConfig + # Base error class for Heroku class HerokuError(Exception): pass + class HerokuChatConfig(OpenAIGPTConfig): @overload def _transform_messages( @@ -49,19 +51,31 @@ class HerokuChatConfig(OpenAIGPTConfig): messages=messages, model=model, is_async=False ) - def _get_openai_compatible_provider_info(self, api_base: Optional[str], api_key: Optional[str]) -> Tuple[Optional[str], Optional[str]]: + def _get_openai_compatible_provider_info( + self, api_base: Optional[str], api_key: Optional[str] + ) -> Tuple[Optional[str], Optional[str]]: api_base = api_base or os.getenv("HEROKU_API_BASE") api_key = api_key or os.getenv("HEROKU_API_KEY") - + return api_base, api_key - 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: + 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: api_base, _ = self._get_openai_compatible_provider_info(api_base, api_key) if not api_base: - raise HerokuError("No api base was set. Please provide an api_base, or set the HEROKU_API_BASE environment variable.") - - if not api_base.endswith("/v1/chat/completions"): - api_base = f"{api_base}/v1/chat/completions" + raise HerokuError( + "No api base was set. Please provide an api_base, or set the HEROKU_API_BASE environment variable." + ) - return api_base \ No newline at end of file + if not api_base.endswith("/v1/chat/completions"): + api_base = f"{api_base}/v1/chat/completions" + + return api_base diff --git a/litellm/llms/hosted_vllm/chat/transformation.py b/litellm/llms/hosted_vllm/chat/transformation.py index 35dfa8a3851..05db1544a2b 100644 --- a/litellm/llms/hosted_vllm/chat/transformation.py +++ b/litellm/llms/hosted_vllm/chat/transformation.py @@ -153,9 +153,7 @@ class HostedVLLMChatConfig(OpenAIGPTConfig): ] existing_content = message.get("content") if isinstance(existing_content, str): - new_content.append( - {"type": "text", "text": existing_content} - ) + new_content.append({"type": "text", "text": existing_content}) elif isinstance(existing_content, list): new_content.extend(existing_content) message["content"] = new_content # type: ignore diff --git a/litellm/llms/hosted_vllm/rerank/transformation.py b/litellm/llms/hosted_vllm/rerank/transformation.py index 8316e923df3..8066e53afc7 100644 --- a/litellm/llms/hosted_vllm/rerank/transformation.py +++ b/litellm/llms/hosted_vllm/rerank/transformation.py @@ -38,8 +38,8 @@ class HostedVLLMRerankConfig(BaseRerankConfig): pass def get_complete_url( - self, - api_base: Optional[str], + self, + api_base: Optional[str], model: str, optional_params: Optional[dict] = None, ) -> str: @@ -82,14 +82,16 @@ class HostedVLLMRerankConfig(BaseRerankConfig): """ if max_chunks_per_doc is not None: raise ValueError("Hosted VLLM does not support max_chunks_per_doc") - - return dict(OptionalRerankParams( - query=query, - documents=documents, - top_n=top_n, - rank_fields=rank_fields, - return_documents=return_documents, - )) + + return dict( + OptionalRerankParams( + query=query, + documents=documents, + top_n=top_n, + rank_fields=rank_fields, + return_documents=return_documents, + ) + ) def validate_environment( self, @@ -124,7 +126,7 @@ class HostedVLLMRerankConfig(BaseRerankConfig): raise ValueError("query is required for Hosted VLLM rerank") if "documents" not in optional_rerank_params: raise ValueError("documents is required for Hosted VLLM rerank") - + rerank_request = RerankRequest( model=model, query=optional_rerank_params["query"], @@ -161,12 +163,16 @@ class HostedVLLMRerankConfig(BaseRerankConfig): def get_error_class( self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ) -> BaseLLMException: - return HostedVLLMRerankError(message=error_message, status_code=status_code, headers=headers) + return HostedVLLMRerankError( + message=error_message, status_code=status_code, headers=headers + ) def _transform_response(self, response: dict) -> RerankResponse: # Extract usage information usage_data = response.get("usage", {}) - _billed_units = RerankBilledUnits(total_tokens=usage_data.get("total_tokens", 0)) + _billed_units = RerankBilledUnits( + total_tokens=usage_data.get("total_tokens", 0) + ) _tokens = RerankTokens(input_tokens=usage_data.get("total_tokens", 0)) rerank_meta = RerankResponseMeta(billed_units=_billed_units, tokens=_tokens) @@ -207,4 +213,4 @@ class HostedVLLMRerankConfig(BaseRerankConfig): id=response.get("id") or str(uuid.uuid4()), results=rerank_results, meta=rerank_meta, - ) \ No newline at end of file + ) diff --git a/litellm/llms/huggingface/embedding/transformation.py b/litellm/llms/huggingface/embedding/transformation.py index 88d42cfcdcc..03088d6e151 100644 --- a/litellm/llms/huggingface/embedding/transformation.py +++ b/litellm/llms/huggingface/embedding/transformation.py @@ -40,17 +40,17 @@ class HuggingFaceEmbeddingConfig(BaseConfig): Reference: https://huggingface.github.io/text-generation-inference/#/Text%20Generation%20Inference/compat_generate """ - hf_task: Optional[hf_tasks] = ( - None # litellm-specific param, used to know the api spec to use when calling huggingface api - ) + hf_task: Optional[ + hf_tasks + ] = None # litellm-specific param, used to know the api spec to use when calling huggingface api best_of: Optional[int] = None decoder_input_details: Optional[bool] = None details: Optional[bool] = True # enables returning logprobs + best of max_new_tokens: Optional[int] = None repetition_penalty: Optional[float] = None - return_full_text: Optional[bool] = ( - False # by default don't return the input as part of the output - ) + return_full_text: Optional[ + bool + ] = False # by default don't return the input as part of the output seed: Optional[int] = None temperature: Optional[float] = None top_k: Optional[int] = None @@ -120,9 +120,9 @@ class HuggingFaceEmbeddingConfig(BaseConfig): optional_params["top_p"] = value if param == "n": optional_params["best_of"] = value - optional_params["do_sample"] = ( - True # Need to sample if you want best of for hf inference endpoints - ) + optional_params[ + "do_sample" + ] = True # Need to sample if you want best of for hf inference endpoints if param == "stream": optional_params["stream"] = value if param == "stop": @@ -363,9 +363,9 @@ class HuggingFaceEmbeddingConfig(BaseConfig): "content-type": "application/json", } if api_key is not None: - default_headers["Authorization"] = ( - f"Bearer {api_key}" # Huggingface Inference Endpoint default is to accept bearer tokens - ) + default_headers[ + "Authorization" + ] = f"Bearer {api_key}" # Huggingface Inference Endpoint default is to accept bearer tokens headers = {**headers, **default_headers} return headers diff --git a/litellm/llms/huggingface/rerank/transformation.py b/litellm/llms/huggingface/rerank/transformation.py index b386daf1c83..3f83b8e422d 100644 --- a/litellm/llms/huggingface/rerank/transformation.py +++ b/litellm/llms/huggingface/rerank/transformation.py @@ -61,8 +61,8 @@ class HuggingFaceRerankConfig(BaseRerankConfig): return "https://api-inference.huggingface.co" def get_complete_url( - self, - api_base: Optional[str], + self, + api_base: Optional[str], model: str, optional_params: Optional[dict] = None, ) -> str: diff --git a/litellm/llms/infinity/common_utils.py b/litellm/llms/infinity/common_utils.py index 089818c829f..67c54caff98 100644 --- a/litellm/llms/infinity/common_utils.py +++ b/litellm/llms/infinity/common_utils.py @@ -6,11 +6,8 @@ from litellm.llms.base_llm.chat.transformation import BaseLLMException class InfinityError(BaseLLMException): def __init__( - self, - status_code: int, - message: str, - headers: Union[dict, httpx.Headers] = {} - ): + self, status_code: int, message: str, headers: Union[dict, httpx.Headers] = {} + ): self.status_code = status_code self.message = message self.request = httpx.Request( diff --git a/litellm/llms/infinity/rerank/transformation.py b/litellm/llms/infinity/rerank/transformation.py index 1c15de714b6..314bf2f8a36 100644 --- a/litellm/llms/infinity/rerank/transformation.py +++ b/litellm/llms/infinity/rerank/transformation.py @@ -27,8 +27,8 @@ from ..common_utils import InfinityError class InfinityRerankConfig(CohereRerankConfig): def get_complete_url( - self, - api_base: Optional[str], + self, + api_base: Optional[str], model: str, optional_params: Optional[dict] = None, ) -> str: diff --git a/litellm/llms/jina_ai/rerank/transformation.py b/litellm/llms/jina_ai/rerank/transformation.py index 0fddd754a9c..48d876f8ea2 100644 --- a/litellm/llms/jina_ai/rerank/transformation.py +++ b/litellm/llms/jina_ai/rerank/transformation.py @@ -51,13 +51,15 @@ class JinaAIRerankConfig(BaseRerankConfig): for k, v in non_default_params.items(): if k in supported_params: optional_params[k] = v - return dict(OptionalRerankParams( - **optional_params, - )) + return dict( + OptionalRerankParams( + **optional_params, + ) + ) def get_complete_url( - self, - api_base: Optional[str], + self, + api_base: Optional[str], model: str, optional_params: Optional[dict] = None, ) -> str: @@ -127,9 +129,9 @@ class JinaAIRerankConfig(BaseRerankConfig): ) # Return response def validate_environment( - self, - headers: Dict, - model: str, + self, + headers: Dict, + model: str, api_key: Optional[str] = None, optional_params: Optional[dict] = None, ) -> Dict: diff --git a/litellm/llms/lambda_ai/chat/transformation.py b/litellm/llms/lambda_ai/chat/transformation.py index 2d481d66824..262a189428d 100644 --- a/litellm/llms/lambda_ai/chat/transformation.py +++ b/litellm/llms/lambda_ai/chat/transformation.py @@ -13,7 +13,7 @@ class LambdaAIChatConfig(OpenAILikeChatConfig): """ Lambda AI is OpenAI-compatible with standard endpoints """ - + @property def custom_llm_provider(self) -> Optional[str]: return "lambda_ai" @@ -28,4 +28,4 @@ class LambdaAIChatConfig(OpenAILikeChatConfig): or "https://api.lambda.ai/v1" # Default Lambda API base URL ) # type: ignore dynamic_api_key = api_key or get_secret_str("LAMBDA_API_KEY") - return api_base, dynamic_api_key \ No newline at end of file + return api_base, dynamic_api_key diff --git a/litellm/llms/langgraph/__init__.py b/litellm/llms/langgraph/__init__.py index aa075dc96c1..6d7b490ed67 100644 --- a/litellm/llms/langgraph/__init__.py +++ b/litellm/llms/langgraph/__init__.py @@ -1,4 +1,3 @@ from litellm.llms.langgraph.chat.transformation import LangGraphConfig __all__ = ["LangGraphConfig"] - diff --git a/litellm/llms/langgraph/chat/__init__.py b/litellm/llms/langgraph/chat/__init__.py index aa075dc96c1..6d7b490ed67 100644 --- a/litellm/llms/langgraph/chat/__init__.py +++ b/litellm/llms/langgraph/chat/__init__.py @@ -1,4 +1,3 @@ from litellm.llms.langgraph.chat.transformation import LangGraphConfig __all__ = ["LangGraphConfig"] - diff --git a/litellm/llms/langgraph/chat/sse_iterator.py b/litellm/llms/langgraph/chat/sse_iterator.py index cf81998055a..2eb17b4d4b4 100644 --- a/litellm/llms/langgraph/chat/sse_iterator.py +++ b/litellm/llms/langgraph/chat/sse_iterator.py @@ -232,4 +232,3 @@ class LangGraphSSEStreamIterator: except Exception as e: verbose_logger.error(f"Error in LangGraph SSE stream: {str(e)}") raise StopAsyncIteration - diff --git a/litellm/llms/langgraph/chat/transformation.py b/litellm/llms/langgraph/chat/transformation.py index b6afa5ab1af..00cc3a8f516 100644 --- a/litellm/llms/langgraph/chat/transformation.py +++ b/litellm/llms/langgraph/chat/transformation.py @@ -66,9 +66,7 @@ class LangGraphConfig(BaseConfig): from litellm.secret_managers.main import get_secret_str api_base = ( - api_base - or get_secret_str("LANGGRAPH_API_BASE") - or "http://localhost:2024" + api_base or get_secret_str("LANGGRAPH_API_BASE") or "http://localhost:2024" ) api_key = api_key or get_secret_str("LANGGRAPH_API_KEY") @@ -166,7 +164,7 @@ class LangGraphConfig(BaseConfig): # Handle content that might be a list if isinstance(content, list): content = convert_content_list_to_str(msg) - + # Ensure content is a string if not isinstance(content, str): content = str(content) @@ -510,4 +508,3 @@ class LangGraphConfig(BaseConfig): LangGraph has native streaming support, so we don't need to fake stream. """ return False - diff --git a/litellm/llms/lemonade/chat/transformation.py b/litellm/llms/lemonade/chat/transformation.py index 8cba844435e..a9039388a49 100644 --- a/litellm/llms/lemonade/chat/transformation.py +++ b/litellm/llms/lemonade/chat/transformation.py @@ -63,20 +63,20 @@ class LemonadeChatConfig(OpenAILikeChatConfig): def get_models(self, api_key: Optional[str] = None, api_base: Optional[str] = None): """ Get available models from Lemonade API. - + This method queries the Lemonade /models endpoint to retrieve the list of available models. - + Args: api_key: Optional API key (Lemonade doesn't require authentication) api_base: Optional API base URL (defaults to LEMONADE_API_BASE env var or http://localhost:8000) - + Returns: List of model names prefixed with "lemonade/" """ api_base, api_key = self._get_openai_compatible_provider_info( api_base=api_base, api_key=api_key ) - + if api_base is None: raise ValueError( "LEMONADE_API_BASE is not set. Please set the environment variable to query Lemonade's /models endpoint." @@ -113,7 +113,6 @@ class LemonadeChatConfig(OpenAILikeChatConfig): key = "lemonade" return api_base, key - def transform_response( self, model: str, @@ -146,4 +145,3 @@ class LemonadeChatConfig(OpenAILikeChatConfig): setattr(model_response, "model", "lemonade/" + model) return model_response - \ No newline at end of file diff --git a/litellm/llms/lemonade/cost_calculator.py b/litellm/llms/lemonade/cost_calculator.py index 27e1ca275f8..2042f6d0d4d 100644 --- a/litellm/llms/lemonade/cost_calculator.py +++ b/litellm/llms/lemonade/cost_calculator.py @@ -15,21 +15,21 @@ def cost_per_token( ) -> Tuple[float, float]: """ Calculate cost per token for Lemonade models. - + Since Lemonade is a local/self-hosted deployment, there are no per-token costs. This function returns (0.0, 0.0) for all models to allow cost tracking to work without errors for any Lemonade model, regardless of whether it's in the model_prices_and_context_window.json file. - + Args: model: The model name (with or without "lemonade/" prefix) usage: Usage object containing token counts - + Returns: Tuple of (prompt_cost, completion_cost) - always (0.0, 0.0) for Lemonade """ # Lemonade is self-hosted/local, so cost is always 0 prompt_cost = 0.0 completion_cost = 0.0 - + return prompt_cost, completion_cost diff --git a/litellm/llms/linkup/__init__.py b/litellm/llms/linkup/__init__.py index b1553a17379..c761584b07c 100644 --- a/litellm/llms/linkup/__init__.py +++ b/litellm/llms/linkup/__init__.py @@ -4,4 +4,3 @@ Linkup API integration module. from litellm.llms.linkup.search.transformation import LinkupSearchConfig __all__ = ["LinkupSearchConfig"] - diff --git a/litellm/llms/linkup/search/__init__.py b/litellm/llms/linkup/search/__init__.py index b47af3f3057..667c4630238 100644 --- a/litellm/llms/linkup/search/__init__.py +++ b/litellm/llms/linkup/search/__init__.py @@ -4,4 +4,3 @@ Linkup Search API module. from litellm.llms.linkup.search.transformation import LinkupSearchConfig __all__ = ["LinkupSearchConfig"] - diff --git a/litellm/llms/linkup/search/transformation.py b/litellm/llms/linkup/search/transformation.py index bbe76664b4c..0554b8ab341 100644 --- a/litellm/llms/linkup/search/transformation.py +++ b/litellm/llms/linkup/search/transformation.py @@ -79,9 +79,7 @@ class LinkupSearchConfig(BaseSearchConfig): """ Get complete URL for Search endpoint. """ - api_base = ( - api_base or get_secret_str("LINKUP_API_BASE") or self.LINKUP_API_BASE - ) + api_base = api_base or get_secret_str("LINKUP_API_BASE") or self.LINKUP_API_BASE # Append "/search" to the api base if it's not already there if not api_base.endswith("/search"): @@ -203,4 +201,3 @@ class LinkupSearchConfig(BaseSearchConfig): results=results, object="search", ) - diff --git a/litellm/llms/litellm_proxy/image_generation/transformation.py b/litellm/llms/litellm_proxy/image_generation/transformation.py index 6174424154d..3932070e964 100644 --- a/litellm/llms/litellm_proxy/image_generation/transformation.py +++ b/litellm/llms/litellm_proxy/image_generation/transformation.py @@ -8,6 +8,7 @@ from litellm.secret_managers.main import get_secret_str class LiteLLMProxyImageGenerationConfig(GPTImageGenerationConfig): """Configuration for image generation requests routed through LiteLLM Proxy.""" + def validate_environment( self, headers: dict, diff --git a/litellm/llms/litellm_proxy/responses/transformation.py b/litellm/llms/litellm_proxy/responses/transformation.py index a122b768751..e5bbaa78d1d 100644 --- a/litellm/llms/litellm_proxy/responses/transformation.py +++ b/litellm/llms/litellm_proxy/responses/transformation.py @@ -15,7 +15,7 @@ from litellm.types.utils import LlmProviders class LiteLLMProxyResponsesAPIConfig(OpenAIResponsesAPIConfig): """ Configuration for LiteLLM Proxy Responses API support. - + Extends OpenAI's config since the proxy follows OpenAI's API spec, but uses LITELLM_PROXY_API_BASE for the base URL. """ @@ -31,11 +31,11 @@ class LiteLLMProxyResponsesAPIConfig(OpenAIResponsesAPIConfig): ) -> str: """ Get the endpoint for LiteLLM Proxy responses API. - + Uses LITELLM_PROXY_API_BASE environment variable if api_base is not provided. """ api_base = api_base or get_secret_str("LITELLM_PROXY_API_BASE") - + if api_base is None: raise ValueError( "api_base not set for LiteLLM Proxy responses API. " diff --git a/litellm/llms/litellm_proxy/skills/code_execution.py b/litellm/llms/litellm_proxy/skills/code_execution.py index d307b8b36d9..2b567f03760 100644 --- a/litellm/llms/litellm_proxy/skills/code_execution.py +++ b/litellm/llms/litellm_proxy/skills/code_execution.py @@ -22,17 +22,18 @@ from litellm._logging import verbose_logger class LiteLLMInternalTools(str, Enum): """ Enum for internal LiteLLM tools that are injected into requests. - + These tools are handled automatically by LiteLLM hooks and are not passed to the underlying LLM provider directly. """ + CODE_EXECUTION = "litellm_code_execution" def get_litellm_code_execution_tool() -> Dict[str, Any]: """ Returns the litellm_code_execution tool definition in OpenAI format. - + This tool enables automatic code execution in a sandboxed environment when skills include executable Python code. """ @@ -44,21 +45,18 @@ def get_litellm_code_execution_tool() -> Dict[str, Any]: "parameters": { "type": "object", "properties": { - "code": { - "type": "string", - "description": "Python code to execute" - } + "code": {"type": "string", "description": "Python code to execute"} }, - "required": ["code"] - } - } + "required": ["code"], + }, + }, } def get_litellm_code_execution_tool_anthropic() -> Dict[str, Any]: """ Returns the litellm_code_execution tool definition in Anthropic/messages API format. - + This tool enables automatic code execution in a sandboxed environment when skills include executable Python code. """ @@ -68,13 +66,10 @@ def get_litellm_code_execution_tool_anthropic() -> Dict[str, Any]: "input_schema": { "type": "object", "properties": { - "code": { - "type": "string", - "description": "Python code to execute" - } + "code": {"type": "string", "description": "Python code to execute"} }, - "required": ["code"] - } + "required": ["code"], + }, } @@ -85,12 +80,12 @@ LITELLM_CODE_EXECUTION_TOOL = get_litellm_code_execution_tool() class CodeExecutionHandler: """ Handles automatic code execution for LiteLLM skills. - + When enabled, this handler intercepts LLM responses with code execution tool calls, executes them in a sandbox, and continues the conversation automatically until completion. """ - + def __init__( self, max_iterations: Optional[int] = None, @@ -100,10 +95,10 @@ class CodeExecutionHandler: DEFAULT_MAX_ITERATIONS, DEFAULT_SANDBOX_TIMEOUT, ) - + self.max_iterations = max_iterations or DEFAULT_MAX_ITERATIONS self.sandbox_timeout = sandbox_timeout or DEFAULT_SANDBOX_TIMEOUT - + async def execute_with_code_execution( self, model: str, @@ -115,14 +110,14 @@ class CodeExecutionHandler: ) -> Dict[str, Any]: """ Execute an LLM call with automatic code execution handling. - + This method: 1. Makes the initial LLM call 2. If model calls litellm_code_execution, executes the code 3. Continues conversation with results 4. Repeats until model stops calling tools 5. Returns final response with generated files inline - + Args: model: Model to use messages: Initial messages @@ -130,7 +125,7 @@ class CodeExecutionHandler: skill_files: Dict of skill files for execution skill_id: Optional skill ID for tracking **kwargs: Additional args for litellm.acompletion - + Returns: Dict with: - response: Final LLM response @@ -141,19 +136,19 @@ class CodeExecutionHandler: from litellm.llms.litellm_proxy.skills.sandbox_executor import ( SkillsSandboxExecutor, ) - + current_messages = list(messages) generated_files: List[Dict[str, Any]] = [] # Files returned directly execution_results: List[Dict] = [] - + executor = SkillsSandboxExecutor(timeout=self.sandbox_timeout) response: Any = None # Initialize to avoid possibly unbound error - + for iteration in range(self.max_iterations): verbose_logger.debug( f"CodeExecutionHandler: Iteration {iteration + 1}/{self.max_iterations}" ) - + # Make LLM call response = await litellm.acompletion( model=model, @@ -161,10 +156,10 @@ class CodeExecutionHandler: tools=tools, **kwargs, ) - + assistant_message = response.choices[0].message # type: ignore stop_reason = response.choices[0].finish_reason # type: ignore - + # Build assistant message for conversation history assistant_msg_dict: Dict[str, Any] = { "role": "assistant", @@ -177,13 +172,13 @@ class CodeExecutionHandler: "type": "function", "function": { "name": tc.function.name, - "arguments": tc.function.arguments - } + "arguments": tc.function.arguments, + }, } for tc in assistant_message.tool_calls ] current_messages.append(assistant_msg_dict) - + # Check if we're done (no tool calls or not tool_calls finish reason) if stop_reason != "tool_calls" or not assistant_message.tool_calls: verbose_logger.debug( @@ -195,21 +190,21 @@ class CodeExecutionHandler: "execution_results": execution_results, "messages": current_messages, } - + # Handle tool calls for tool_call in assistant_message.tool_calls: tool_name = tool_call.function.name - + if tool_name == LiteLLMInternalTools.CODE_EXECUTION.value: # Execute code in sandbox try: args = json.loads(tool_call.function.arguments) code = args.get("code", "") - + verbose_logger.debug( f"CodeExecutionHandler: Executing code ({len(code)} chars)" ) - + exec_result = executor.execute( code=code, skill_files=skill_files, @@ -218,62 +213,74 @@ class CodeExecutionHandler: verbose_logger.debug( f"CodeExecutionHandler: Execution result: {exec_result}" ) - - execution_results.append({ - "iteration": iteration, - "success": exec_result["success"], - "output": exec_result["output"], - "error": exec_result["error"], - "files": [f["name"] for f in exec_result["files"]], - }) - + + execution_results.append( + { + "iteration": iteration, + "success": exec_result["success"], + "output": exec_result["output"], + "error": exec_result["error"], + "files": [f["name"] for f in exec_result["files"]], + } + ) + # Build tool result content tool_result = exec_result["output"] or "" - + # Collect generated files (returned directly, no storage) if exec_result["files"]: tool_result += "\n\nGenerated files:" for f in exec_result["files"]: file_content = base64.b64decode(f["content_base64"]) # Add to generated files list (returned in response) - generated_files.append({ - "name": f["name"], - "mime_type": f["mime_type"], - "content_base64": f["content_base64"], - "size": len(file_content), - }) - tool_result += f"\n- {f['name']} ({len(file_content)} bytes)" - + generated_files.append( + { + "name": f["name"], + "mime_type": f["mime_type"], + "content_base64": f["content_base64"], + "size": len(file_content), + } + ) + tool_result += ( + f"\n- {f['name']} ({len(file_content)} bytes)" + ) + verbose_logger.debug( f"CodeExecutionHandler: Generated file {f['name']} ({len(file_content)} bytes)" ) - + if exec_result["error"]: tool_result += f"\n\nError:\n{exec_result['error']}" - + except Exception as e: tool_result = f"Code execution failed: {str(e)}" - execution_results.append({ - "iteration": iteration, - "success": False, - "error": str(e), - }) - + execution_results.append( + { + "iteration": iteration, + "success": False, + "error": str(e), + } + ) + # Add tool result to messages - current_messages.append({ - "role": "tool", - "tool_call_id": tool_call.id, - "content": tool_result, - }) + current_messages.append( + { + "role": "tool", + "tool_call_id": tool_call.id, + "content": tool_result, + } + ) else: # Non-code-execution tool - pass through # In a full implementation, this would call other tool handlers - current_messages.append({ - "role": "tool", - "tool_call_id": tool_call.id, - "content": f"Tool '{tool_name}' not handled by code execution handler", - }) - + current_messages.append( + { + "role": "tool", + "tool_call_id": tool_call.id, + "content": f"Tool '{tool_name}' not handled by code execution handler", + } + ) + # Max iterations reached verbose_logger.warning( f"CodeExecutionHandler: Max iterations ({self.max_iterations}) reached" @@ -308,4 +315,3 @@ def add_code_execution_tool(tools: Optional[List[Dict]]) -> List[Dict]: # Global handler instance code_execution_handler = CodeExecutionHandler() - diff --git a/litellm/llms/litellm_proxy/skills/constants.py b/litellm/llms/litellm_proxy/skills/constants.py index a2be6961db6..a8c2697fcee 100644 --- a/litellm/llms/litellm_proxy/skills/constants.py +++ b/litellm/llms/litellm_proxy/skills/constants.py @@ -10,4 +10,3 @@ DEFAULT_MAX_ITERATIONS: int = 10 DEFAULT_SANDBOX_TIMEOUT: int = 120 """Default timeout in seconds for sandbox code execution.""" - diff --git a/litellm/llms/litellm_proxy/skills/handler.py b/litellm/llms/litellm_proxy/skills/handler.py index f44ac4cda92..8e5070c2724 100644 --- a/litellm/llms/litellm_proxy/skills/handler.py +++ b/litellm/llms/litellm_proxy/skills/handler.py @@ -15,13 +15,13 @@ from litellm.proxy._types import LiteLLM_SkillsTable, NewSkillRequest def _prisma_skill_to_litellm(prisma_skill) -> LiteLLM_SkillsTable: """ Convert a Prisma skill record to LiteLLM_SkillsTable. - + Handles Base64 decoding of file_content field. """ import base64 data = prisma_skill.model_dump() - + # Decode Base64 file_content back to bytes # model_dump() converts Base64 field to base64-encoded string if data.get("file_content") is not None: @@ -30,7 +30,7 @@ def _prisma_skill_to_litellm(prisma_skill) -> LiteLLM_SkillsTable: elif isinstance(data["file_content"], bytes): # Already bytes, no conversion needed pass - + return LiteLLM_SkillsTable(**data) diff --git a/litellm/llms/litellm_proxy/skills/prompt_injection.py b/litellm/llms/litellm_proxy/skills/prompt_injection.py index 17469274c1c..2b86f74122b 100644 --- a/litellm/llms/litellm_proxy/skills/prompt_injection.py +++ b/litellm/llms/litellm_proxy/skills/prompt_injection.py @@ -16,7 +16,7 @@ from litellm.proxy._types import LiteLLM_SkillsTable class SkillPromptInjectionHandler: """ Handles skill content extraction and system prompt injection. - + Responsibilities: - Extract SKILL.md content from skill ZIP files - Extract ALL files from ZIP for code execution @@ -27,19 +27,19 @@ class SkillPromptInjectionHandler: def extract_skill_content(self, skill: LiteLLM_SkillsTable) -> Optional[str]: """ Extract skill content from the stored zip file. - + Looks for SKILL.md or README.md in the zip and returns its content. This content describes the skill's capabilities and instructions. - + Args: skill: The skill from LiteLLM database - + Returns: The skill content as a string, or None if not available """ if not skill.file_content: return skill.instructions - + try: zip_buffer = BytesIO(skill.file_content) with zipfile.ZipFile(zip_buffer, "r") as zf: @@ -49,14 +49,14 @@ class SkillPromptInjectionHandler: content = zf.read(name).decode("utf-8") if content: return f"## Skill: {skill.display_title or skill.skill_id}\n\n{content}" - + # Fall back to README.md for name in zf.namelist(): if name.endswith("README.md"): content = zf.read(name).decode("utf-8") if content: return f"## Skill: {skill.display_title or skill.skill_id}\n\n{content}" - + # Fall back to any .md file for name in zf.namelist(): if name.endswith(".md"): @@ -67,27 +67,27 @@ class SkillPromptInjectionHandler: verbose_logger.warning( f"SkillPromptInjectionHandler: Error extracting content from skill {skill.skill_id}: {e}" ) - + return skill.instructions def extract_all_files(self, skill: LiteLLM_SkillsTable) -> Dict[str, bytes]: """ Extract ALL files from skill ZIP for code execution. - + Returns a dict mapping file paths to their binary content. The paths have the skill folder prefix removed (e.g., "slack-gif-creator/core/..." -> "core/..."). - + Args: skill: The skill from LiteLLM database - + Returns: Dict mapping file paths to binary content """ files: Dict[str, bytes] = {} - + if not skill.file_content: return files - + try: zip_buffer = BytesIO(skill.file_content) with zipfile.ZipFile(zip_buffer, "r") as zf: @@ -95,21 +95,21 @@ class SkillPromptInjectionHandler: # Skip directories if name.endswith("/"): continue - + # Remove skill folder prefix (first path component) parts = name.split("/") if len(parts) > 1: clean_path = "/".join(parts[1:]) else: clean_path = name - + if clean_path: files[clean_path] = zf.read(name) except Exception as e: verbose_logger.warning( f"SkillPromptInjectionHandler: Error extracting files from skill {skill.skill_id}: {e}" ) - + return files def inject_skill_content_to_messages( @@ -117,27 +117,29 @@ class SkillPromptInjectionHandler: ) -> dict: """ Inject skill content into the system prompt. - + For Anthropic messages API (use_anthropic_format=True): - Injects into top-level 'system' parameter (not in messages array) - + For OpenAI-style APIs (use_anthropic_format=False): - Injects into messages array with role="system" - + Args: data: The request data dict skill_contents: List of skill content strings to inject use_anthropic_format: If True, use top-level 'system' param for Anthropic - + Returns: Modified data dict with skill content in system prompt """ if not skill_contents: return data - + # Build the skill injection text - skill_section = "\n\n---\n\n# Available Skills\n\n" + "\n\n---\n\n".join(skill_contents) - + skill_section = "\n\n---\n\n# Available Skills\n\n" + "\n\n---\n\n".join( + skill_contents + ) + if use_anthropic_format: # Anthropic messages API: use top-level 'system' parameter current_system = data.get("system", "") @@ -146,19 +148,19 @@ class SkillPromptInjectionHandler: else: data["system"] = skill_section.strip() return data - + # OpenAI-style: inject into messages array messages = data.get("messages", []) if not messages: return data - + # Find or create system message system_msg_idx = None for i, msg in enumerate(messages): if isinstance(msg, dict) and msg.get("role") == "system": system_msg_idx = i break - + if system_msg_idx is not None: # Append to existing system message current_content = messages[system_msg_idx].get("content", "") @@ -166,20 +168,20 @@ class SkillPromptInjectionHandler: else: # Create new system message at the beginning messages.insert(0, {"role": "system", "content": skill_section.strip()}) - + data["messages"] = messages return data def create_execute_code_tool(self, skill_modules: List[str]) -> Dict[str, Any]: """ Create the execute_code tool definition. - + This tool allows the model to execute Python code with access to the skill's modules (e.g., 'from core.gif_builder import GIFBuilder'). - + Args: skill_modules: List of available module paths (e.g., ["core/gif_builder.py"]) - + Returns: OpenAI-style tool definition """ @@ -190,11 +192,11 @@ class SkillPromptInjectionHandler: # Convert path to import: "core/gif_builder.py" -> "from core.gif_builder import ..." import_path = mod.replace("/", ".").replace(".py", "") module_examples.append(f"from {import_path} import ...") - + module_hint = "" if module_examples: module_hint = f" Available modules: {', '.join(module_examples)}" - + return { "type": "function", "function": { @@ -205,12 +207,12 @@ class SkillPromptInjectionHandler: "properties": { "code": { "type": "string", - "description": "Python code to execute. You can import skill modules and use standard libraries." + "description": "Python code to execute. You can import skill modules and use standard libraries.", } }, - "required": ["code"] - } - } + "required": ["code"], + }, + }, } def convert_skill_to_tool(self, skill: LiteLLM_SkillsTable) -> Dict[str, Any]: @@ -263,7 +265,9 @@ class SkillPromptInjectionHandler: return tool - def convert_skill_to_anthropic_tool(self, skill: LiteLLM_SkillsTable) -> Dict[str, Any]: + def convert_skill_to_anthropic_tool( + self, skill: LiteLLM_SkillsTable + ) -> Dict[str, Any]: """ Convert a LiteLLM skill to an Anthropic-style tool (messages API format). @@ -302,4 +306,3 @@ class SkillPromptInjectionHandler: "description": description, "input_schema": input_schema, } - diff --git a/litellm/llms/litellm_proxy/skills/sandbox_executor.py b/litellm/llms/litellm_proxy/skills/sandbox_executor.py index 7676ade5cd0..a5c0a539c96 100644 --- a/litellm/llms/litellm_proxy/skills/sandbox_executor.py +++ b/litellm/llms/litellm_proxy/skills/sandbox_executor.py @@ -15,7 +15,7 @@ from litellm._logging import verbose_logger class SkillsSandboxExecutor: """ Executes skill code in llm-sandbox Docker container. - + Responsibilities: - Create sandbox session with skill files - Install requirements @@ -31,7 +31,7 @@ class SkillsSandboxExecutor: ): """ Initialize the sandbox executor. - + Args: timeout: Maximum execution time in seconds backend: Sandbox backend ("docker", "podman", "kubernetes") @@ -50,12 +50,12 @@ class SkillsSandboxExecutor: ) -> Dict[str, Any]: """ Execute code with skill files in sandbox. - + Args: code: Python code to execute skill_files: Dict mapping file paths to binary content requirements: Optional requirements.txt content - + Returns: { "success": bool, @@ -84,10 +84,10 @@ class SkillsSandboxExecutor: "lang": "python", "verbose": False, } - + if self.image: session_kwargs["image"] = self.image - + with SandboxSession(**session_kwargs) as session: # 1. Copy skill files into sandbox using copy_to_runtime import tempfile @@ -100,15 +100,15 @@ class SkillsSandboxExecutor: os.makedirs(os.path.dirname(local_path), exist_ok=True) with open(local_path, "wb") as f: f.write(content) - + # Copy to sandbox sandbox_path = f"/sandbox/{path}" session.copy_to_runtime(local_path, sandbox_path) - + verbose_logger.debug( f"SkillsSandboxExecutor: Copied {len(skill_files)} files to sandbox" ) - + # 2. Install requirements if present req_packages = None if requirements: @@ -116,7 +116,7 @@ class SkillsSandboxExecutor: elif "requirements.txt" in skill_files: req_content = skill_files["requirements.txt"].decode("utf-8") req_packages = req_content.strip().replace("\n", " ") - + if req_packages: # Run pip install as code pip_code = f""" @@ -127,7 +127,7 @@ subprocess.run(['pip', 'install'] + '{req_packages}'.split(), check=True) verbose_logger.debug( "SkillsSandboxExecutor: Installed requirements" ) - + # 3. Execute the code # Wrap code to run from /sandbox directory wrapped_code = f""" @@ -139,11 +139,11 @@ sys.path.insert(0, '/sandbox') {code} """ result = session.run(wrapped_code) - + success = result.exit_code == 0 output = result.stdout or "" error = result.stderr or "" - + if success: verbose_logger.debug( "SkillsSandboxExecutor: Code execution succeeded" @@ -158,21 +158,19 @@ sys.path.insert(0, '/sandbox') verbose_logger.debug( f"SkillsSandboxExecutor: stdout: {output[:500] if output else 'No stdout'}" ) - + # 4. Collect generated files generated_files = self._collect_generated_files(session, skill_files) - + return { "success": success, "output": output, "error": error, "files": generated_files, } - + except Exception as e: - verbose_logger.error( - f"SkillsSandboxExecutor: Execution failed: {e}" - ) + verbose_logger.error(f"SkillsSandboxExecutor: Execution failed: {e}") return { "success": False, "output": "", @@ -187,19 +185,19 @@ sys.path.insert(0, '/sandbox') ) -> List[Dict[str, Any]]: """ Collect files generated during execution. - + Looks for new files in /sandbox that weren't in the original skill files. Focuses on common output types: GIF, PNG, JPG, PDF, CSV, etc. - + Args: session: The sandbox session original_files: Original skill files (to exclude) - + Returns: List of generated files with base64 content """ generated_files: List[Dict[str, Any]] = [] - + try: import tempfile @@ -215,43 +213,46 @@ for root, dirs, filenames in os.walk('/sandbox'): print(json.dumps(files)) """ result = session.run(list_code) - + if result.exit_code == 0 and result.stdout: import json + try: filepaths = json.loads(result.stdout.strip()) except json.JSONDecodeError: filepaths = [] - + for filepath in filepaths: if not filepath: continue - + # Get relative path rel_path = filepath.replace("/sandbox/", "") - + # Skip if it was an original file if rel_path in original_files: continue - + # Copy file from sandbox using copy_from_runtime with tempfile.NamedTemporaryFile(delete=False) as tmp: tmp_path = tmp.name - + try: session.copy_from_runtime(filepath, tmp_path) - + with open(tmp_path, "rb") as f: content = f.read() - + content_b64 = base64.b64encode(content).decode("utf-8") - generated_files.append({ - "name": os.path.basename(filepath), - "path": rel_path, - "content_base64": content_b64, - "mime_type": self._get_mime_type(filepath), - }) - + generated_files.append( + { + "name": os.path.basename(filepath), + "path": rel_path, + "content_base64": content_b64, + "mime_type": self._get_mime_type(filepath), + } + ) + verbose_logger.debug( f"SkillsSandboxExecutor: Collected generated file: {rel_path}" ) @@ -262,12 +263,12 @@ print(json.dumps(files)) finally: if os.path.exists(tmp_path): os.unlink(tmp_path) - + except Exception as e: verbose_logger.warning( f"SkillsSandboxExecutor: Error collecting generated files: {e}" ) - + return generated_files def _get_mime_type(self, filename: str) -> str: @@ -283,4 +284,3 @@ print(json.dumps(files)) "json": "application/json", "txt": "text/plain", }.get(ext, "application/octet-stream") - diff --git a/litellm/llms/litellm_proxy/skills/transformation.py b/litellm/llms/litellm_proxy/skills/transformation.py index e7c999eacec..cd000829ca4 100644 --- a/litellm/llms/litellm_proxy/skills/transformation.py +++ b/litellm/llms/litellm_proxy/skills/transformation.py @@ -23,7 +23,7 @@ if TYPE_CHECKING: class LiteLLMSkillsTransformationHandler: """ Transformation handler for skills API requests to LiteLLM database operations. - + This is used when custom_llm_provider="litellm_proxy" to store/retrieve skills from the LiteLLM proxy database instead of calling an external API. """ @@ -51,7 +51,7 @@ class LiteLLMSkillsTransformationHandler: ) -> Union[Skill, Coroutine[Any, Any, Skill]]: """ Create a skill in LiteLLM database. - + Args: display_title: Display title for the skill description: Description of the skill @@ -63,7 +63,7 @@ class LiteLLMSkillsTransformationHandler: metadata: Additional metadata user_id: User ID for tracking _is_async: Whether to return a coroutine - + Returns: Skill object or coroutine that returns Skill """ @@ -84,7 +84,9 @@ class LiteLLMSkillsTransformationHandler: if isinstance(first_file, tuple) and len(first_file) >= 2: file_name = first_file[0] file_content = first_file[1] - file_type = first_file[2] if len(first_file) > 2 else "application/zip" + file_type = ( + first_file[2] if len(first_file) > 2 else "application/zip" + ) if _is_async: return self._async_create_skill( @@ -97,8 +99,9 @@ class LiteLLMSkillsTransformationHandler: metadata=metadata, user_id=user_id, ) - + import asyncio + return asyncio.get_event_loop().run_until_complete( self._async_create_skill( display_title=display_title, @@ -156,14 +159,14 @@ class LiteLLMSkillsTransformationHandler: ) -> Union[ListSkillsResponse, Coroutine[Any, Any, ListSkillsResponse]]: """ List skills from LiteLLM database. - + Args: limit: Maximum number of skills to return offset: Number of skills to skip _is_async: Whether to return a coroutine logging_obj: LiteLLM logging object litellm_call_id: Call ID for logging - + Returns: ListSkillsResponse or coroutine that returns ListSkillsResponse """ @@ -178,8 +181,9 @@ class LiteLLMSkillsTransformationHandler: if _is_async: return self._async_list_skills(limit=limit, offset=offset) - + import asyncio + return asyncio.get_event_loop().run_until_complete( self._async_list_skills(limit=limit, offset=offset) ) @@ -215,13 +219,13 @@ class LiteLLMSkillsTransformationHandler: ) -> Union[Skill, Coroutine[Any, Any, Skill]]: """ Get a skill from LiteLLM database. - + Args: skill_id: The skill ID to retrieve _is_async: Whether to return a coroutine logging_obj: LiteLLM logging object litellm_call_id: Call ID for logging - + Returns: Skill or coroutine that returns Skill """ @@ -236,8 +240,9 @@ class LiteLLMSkillsTransformationHandler: if _is_async: return self._async_get_skill(skill_id=skill_id) - + import asyncio + return asyncio.get_event_loop().run_until_complete( self._async_get_skill(skill_id=skill_id) ) @@ -260,13 +265,13 @@ class LiteLLMSkillsTransformationHandler: ) -> Union[DeleteSkillResponse, Coroutine[Any, Any, DeleteSkillResponse]]: """ Delete a skill from LiteLLM database. - + Args: skill_id: The skill ID to delete _is_async: Whether to return a coroutine logging_obj: LiteLLM logging object litellm_call_id: Call ID for logging - + Returns: DeleteSkillResponse or coroutine that returns DeleteSkillResponse """ @@ -281,8 +286,9 @@ class LiteLLMSkillsTransformationHandler: if _is_async: return self._async_delete_skill(skill_id=skill_id) - + import asyncio + return asyncio.get_event_loop().run_until_complete( self._async_delete_skill(skill_id=skill_id) ) @@ -301,16 +307,16 @@ class LiteLLMSkillsTransformationHandler: def _db_skill_to_response(self, db_skill: Any) -> Skill: """ Convert a database skill record to Anthropic-compatible Skill response. - + Args: db_skill: LiteLLM_SkillsTable record - + Returns: Skill object """ created_at = "" updated_at = "" - + if hasattr(db_skill, "created_at") and db_skill.created_at: created_at = ( db_skill.created_at.isoformat() @@ -333,4 +339,3 @@ class LiteLLMSkillsTransformationHandler: source=db_skill.source or "custom", type="skill", ) - diff --git a/litellm/llms/llamafile/chat/transformation.py b/litellm/llms/llamafile/chat/transformation.py index b0f8cd3fc3b..3387a0eb6aa 100644 --- a/litellm/llms/llamafile/chat/transformation.py +++ b/litellm/llms/llamafile/chat/transformation.py @@ -15,7 +15,9 @@ class LlamafileChatConfig(OpenAIGPTConfig): If both are None, a fake API key is returned. """ - return api_key or get_secret_str("LLAMAFILE_API_KEY") or "fake-api-key" # llamafile does not require an API key + return ( + api_key or get_secret_str("LLAMAFILE_API_KEY") or "fake-api-key" + ) # llamafile does not require an API key @staticmethod def _resolve_api_base(api_base: Optional[str] = None) -> Optional[str]: @@ -25,13 +27,10 @@ class LlamafileChatConfig(OpenAIGPTConfig): If both are None, a default Llamafile server URL is returned. See: https://github.com/Mozilla-Ocho/llamafile/blob/bd1bbe9aabb1ee12dbdcafa8936db443c571eb9d/README.md#L61 """ - return api_base or get_secret_str("LLAMAFILE_API_BASE") or "http://127.0.0.1:8080/v1" # type: ignore - + return api_base or get_secret_str("LLAMAFILE_API_BASE") or "http://127.0.0.1:8080/v1" # type: ignore def _get_openai_compatible_provider_info( - self, - api_base: Optional[str], - api_key: Optional[str] + self, api_base: Optional[str], api_key: Optional[str] ) -> Tuple[Optional[str], Optional[str]]: """Attempts to ensure that the API base and key are set, preferring user-provided values, before falling back to secret manager values (``LLAMAFILE_API_BASE`` and ``LLAMAFILE_API_KEY`` diff --git a/litellm/llms/lm_studio/chat/transformation.py b/litellm/llms/lm_studio/chat/transformation.py index 7b188ff33f8..64ed38467de 100644 --- a/litellm/llms/lm_studio/chat/transformation.py +++ b/litellm/llms/lm_studio/chat/transformation.py @@ -18,7 +18,7 @@ class LMStudioChatConfig(OpenAIGPTConfig): api_key or get_secret_str("LM_STUDIO_API_KEY") or "fake-api-key" ) # LM Studio does not require an api key, but OpenAI client requires non-None value return api_base, dynamic_api_key - + def map_openai_params( self, non_default_params: dict, @@ -46,4 +46,4 @@ class LMStudioChatConfig(OpenAIGPTConfig): optional_params=optional_params, model=model, drop_params=drop_params, - ) \ No newline at end of file + ) diff --git a/litellm/llms/manus/__init__.py b/litellm/llms/manus/__init__.py index 81eef025461..03f1707d446 100644 --- a/litellm/llms/manus/__init__.py +++ b/litellm/llms/manus/__init__.py @@ -1,2 +1 @@ # Manus provider implementation - diff --git a/litellm/llms/manus/files/__init__.py b/litellm/llms/manus/files/__init__.py index 66d23ca0340..3659eef17c8 100644 --- a/litellm/llms/manus/files/__init__.py +++ b/litellm/llms/manus/files/__init__.py @@ -1,2 +1 @@ # Manus Files API implementation - diff --git a/litellm/llms/manus/files/transformation.py b/litellm/llms/manus/files/transformation.py index a7965011969..3381a5327e8 100644 --- a/litellm/llms/manus/files/transformation.py +++ b/litellm/llms/manus/files/transformation.py @@ -74,11 +74,7 @@ class ManusFilesConfig(BaseFilesConfig): Manus uses API_KEY header instead of Authorization: Bearer. For file uploads, don't set Content-Type - httpx will set it for multipart. """ - api_key = ( - api_key - or litellm.api_key - or get_secret_str("MANUS_API_KEY") - ) + api_key = api_key or litellm.api_key or get_secret_str("MANUS_API_KEY") if not api_key: raise ValueError( @@ -194,14 +190,14 @@ class ManusFilesConfig(BaseFilesConfig): optional_params=optional_params, litellm_params=litellm_params, ) - + # Get API key api_key = ( litellm_params.get("api_key") or litellm.api_key or get_secret_str("MANUS_API_KEY") ) - + if not api_key: raise ValueError( "Manus API key is required. Set MANUS_API_KEY environment variable or pass api_key parameter." @@ -436,4 +432,3 @@ class ManusFilesConfig(BaseFilesConfig): ) -> HttpxBinaryResponseContent: """Transform file content response.""" return HttpxBinaryResponseContent(response=raw_response) - diff --git a/litellm/llms/manus/responses/__init__.py b/litellm/llms/manus/responses/__init__.py index e8cabc54266..7df60c923b7 100644 --- a/litellm/llms/manus/responses/__init__.py +++ b/litellm/llms/manus/responses/__init__.py @@ -1,2 +1 @@ # Manus Responses API implementation - diff --git a/litellm/llms/manus/responses/transformation.py b/litellm/llms/manus/responses/transformation.py index bf1a6fab503..510c41304a8 100644 --- a/litellm/llms/manus/responses/transformation.py +++ b/litellm/llms/manus/responses/transformation.py @@ -33,12 +33,12 @@ MANUS_API_BASE = "https://api.manus.im" class ManusResponsesAPIConfig(OpenAIResponsesAPIConfig): """ Configuration for Manus API's Responses API. - + Manus API is OpenAI-compatible but has some differences: - API key passed via `API_KEY` header (not `Authorization: Bearer`) - Model format: `manus/{agent_profile}` (e.g., `manus/manus-1.6`) - Requires `extra_body` with `task_mode: "agent"` and `agent_profile` - + Reference: https://open.manus.im/docs/openai-compatibility """ @@ -62,10 +62,10 @@ class ManusResponsesAPIConfig(OpenAIResponsesAPIConfig): def _extract_agent_profile(self, model: str) -> str: """ Extract agent profile from model name. - + Model format: `manus/{agent_profile}` Examples: `manus/manus-1.6`, `manus/manus-1.6-lite`, `manus/manus-1.6-max` - + Returns: str: The agent profile (e.g., "manus-1.6") """ @@ -79,21 +79,19 @@ class ManusResponsesAPIConfig(OpenAIResponsesAPIConfig): ) -> dict: """ Validate environment and set up headers for Manus API. - + Manus uses `API_KEY` header instead of `Authorization: Bearer`. """ litellm_params = litellm_params or GenericLiteLLMParams() api_key = ( - litellm_params.api_key - or litellm.api_key - or get_secret_str("MANUS_API_KEY") + litellm_params.api_key or litellm.api_key or get_secret_str("MANUS_API_KEY") ) - + if not api_key: raise ValueError( "Manus API key is required. Set MANUS_API_KEY environment variable or pass api_key parameter." ) - + # Manus uses API_KEY header, not Authorization: Bearer # Content-Type is required for all requests (including GET) headers.update( @@ -111,7 +109,7 @@ class ManusResponsesAPIConfig(OpenAIResponsesAPIConfig): ) -> str: """ Get the complete URL for Manus Responses API endpoint. - + Returns: str: The full URL for the Manus /v1/responses endpoint """ @@ -121,10 +119,10 @@ class ManusResponsesAPIConfig(OpenAIResponsesAPIConfig): or get_secret_str("MANUS_API_BASE") or MANUS_API_BASE ) - + # Remove trailing slashes api_base = api_base.rstrip("/") - + # Manus API uses /v1/responses endpoint (OpenAI-compatible) if api_base.endswith("/v1"): return f"{api_base}/responses" @@ -140,7 +138,7 @@ class ManusResponsesAPIConfig(OpenAIResponsesAPIConfig): ) -> Dict: """ Transform the request for Manus API. - + Manus requires: - `task_mode: "agent"` in the request body - `agent_profile` extracted from model name in the request body @@ -153,24 +151,24 @@ class ManusResponsesAPIConfig(OpenAIResponsesAPIConfig): litellm_params=litellm_params, headers=headers, ) - + # Extract agent profile from model name agent_profile = self._extract_agent_profile(model=model) - + # Add Manus-specific parameters directly to the request body # These will be sent as part of the request base_request["task_mode"] = "agent" base_request["agent_profile"] = agent_profile - + # Merge any existing extra_body into the request extra_body = response_api_optional_request_params.get("extra_body", {}) or {} if extra_body: base_request.update(extra_body) - + verbose_logger.debug( f"Manus: Using agent_profile={agent_profile}, task_mode=agent" ) - + return base_request def transform_response_api_response( @@ -181,7 +179,7 @@ class ManusResponsesAPIConfig(OpenAIResponsesAPIConfig): ) -> ResponsesAPIResponse: """ Transform Manus API response to OpenAI-compatible format. - + Manus uses camelCase (createdAt) instead of snake_case (created_at). """ try: @@ -190,13 +188,16 @@ class ManusResponsesAPIConfig(OpenAIResponsesAPIConfig): additional_args={"complete_input_dict": {}}, ) raw_response_json = raw_response.json() - + # Manus uses camelCase "createdAt" instead of snake_case "created_at" - if "createdAt" in raw_response_json and "created_at" not in raw_response_json: + if ( + "createdAt" in raw_response_json + and "created_at" not in raw_response_json + ): raw_response_json["created_at"] = _safe_convert_created_field( raw_response_json["createdAt"] ) - + # Ensure created_at is set if "created_at" in raw_response_json: raw_response_json["created_at"] = _safe_convert_created_field( @@ -206,20 +207,23 @@ class ManusResponsesAPIConfig(OpenAIResponsesAPIConfig): raise OpenAIError( message=raw_response.text, status_code=raw_response.status_code ) - + raw_response_headers = dict(raw_response.headers) processed_headers = process_response_headers(raw_response_headers) - + # Ensure reasoning is an empty dict if not present, OpenAI SDK does not allow None - if "reasoning" not in raw_response_json or raw_response_json.get("reasoning") is None: + if ( + "reasoning" not in raw_response_json + or raw_response_json.get("reasoning") is None + ): raw_response_json["reasoning"] = {} - + if "text" not in raw_response_json or raw_response_json.get("text") is None: raw_response_json["text"] = {} - + if "output" not in raw_response_json or raw_response_json.get("output") is None: raw_response_json["output"] = [] - + # Ensure usage is present with default values if not provided if "usage" not in raw_response_json or raw_response_json.get("usage") is None: raw_response_json["usage"] = ResponseAPIUsage( @@ -227,13 +231,13 @@ class ManusResponsesAPIConfig(OpenAIResponsesAPIConfig): output_tokens=0, total_tokens=0, ) - + # Ensure id is present - failed responses may not include it if "id" not in raw_response_json or raw_response_json.get("id") is None: # Generate a placeholder id for failed responses # This allows the response object to be created even when the API doesn't return an id raw_response_json["id"] = f"unknown-{uuid.uuid4().hex[:8]}" - + try: response = ResponsesAPIResponse(**raw_response_json) except Exception: @@ -241,7 +245,7 @@ class ManusResponsesAPIConfig(OpenAIResponsesAPIConfig): f"Error constructing ResponsesAPIResponse: {raw_response_json}, using model_construct" ) response = ResponsesAPIResponse.model_construct(**raw_response_json) - + # Store processed headers in additional_headers so they get returned to the client response._hidden_params["additional_headers"] = processed_headers response._hidden_params["headers"] = raw_response_headers @@ -260,10 +264,10 @@ class ManusResponsesAPIConfig(OpenAIResponsesAPIConfig): ) -> Tuple[str, Dict]: """ Transform the get response API request into a URL and data. - + Manus API follows OpenAI-compatible format: - GET /v1/responses/{response_id} - + Reference: https://open.manus.im/docs/openai-compatibility """ url = f"{api_base}/{response_id}" @@ -277,7 +281,7 @@ class ManusResponsesAPIConfig(OpenAIResponsesAPIConfig): ) -> ResponsesAPIResponse: """ Transform Manus API GET response to OpenAI-compatible format. - + Manus uses camelCase (createdAt) instead of snake_case (created_at). Same transformation as transform_response_api_response. """ @@ -287,13 +291,16 @@ class ManusResponsesAPIConfig(OpenAIResponsesAPIConfig): additional_args={"complete_input_dict": {}}, ) raw_response_json = raw_response.json() - + # Manus uses camelCase "createdAt" instead of snake_case "created_at" - if "createdAt" in raw_response_json and "created_at" not in raw_response_json: + if ( + "createdAt" in raw_response_json + and "created_at" not in raw_response_json + ): raw_response_json["created_at"] = _safe_convert_created_field( raw_response_json["createdAt"] ) - + # Ensure created_at is set if "created_at" in raw_response_json: raw_response_json["created_at"] = _safe_convert_created_field( @@ -303,32 +310,35 @@ class ManusResponsesAPIConfig(OpenAIResponsesAPIConfig): raise OpenAIError( message=raw_response.text, status_code=raw_response.status_code ) - + raw_response_headers = dict(raw_response.headers) processed_headers = process_response_headers(raw_response_headers) - + # Ensure reasoning, text, output, and usage are present with defaults - if "reasoning" not in raw_response_json or raw_response_json.get("reasoning") is None: + if ( + "reasoning" not in raw_response_json + or raw_response_json.get("reasoning") is None + ): raw_response_json["reasoning"] = {} - + if "text" not in raw_response_json or raw_response_json.get("text") is None: raw_response_json["text"] = {} - + if "output" not in raw_response_json or raw_response_json.get("output") is None: raw_response_json["output"] = [] - + if "usage" not in raw_response_json or raw_response_json.get("usage") is None: raw_response_json["usage"] = ResponseAPIUsage( input_tokens=0, output_tokens=0, total_tokens=0, ) - + # Ensure id is present - failed responses may not include it if "id" not in raw_response_json or raw_response_json.get("id") is None: # Generate a placeholder id for failed responses raw_response_json["id"] = f"unknown-{uuid.uuid4().hex[:8]}" - + try: response = ResponsesAPIResponse(**raw_response_json) except Exception: @@ -336,9 +346,8 @@ class ManusResponsesAPIConfig(OpenAIResponsesAPIConfig): f"Error constructing ResponsesAPIResponse: {raw_response_json}, using model_construct" ) response = ResponsesAPIResponse.model_construct(**raw_response_json) - + # Store processed headers in additional_headers so they get returned to the client response._hidden_params["additional_headers"] = processed_headers response._hidden_params["headers"] = raw_response_headers return response - diff --git a/litellm/llms/minimax/__init__.py b/litellm/llms/minimax/__init__.py index 19093c2dadb..e1b0e602e92 100644 --- a/litellm/llms/minimax/__init__.py +++ b/litellm/llms/minimax/__init__.py @@ -11,4 +11,3 @@ __all__ = [ "MinimaxTextToSpeechConfig", "MinimaxException", ] - diff --git a/litellm/llms/minimax/chat/__init__.py b/litellm/llms/minimax/chat/__init__.py index 45bcfd03b49..eeeba74326d 100644 --- a/litellm/llms/minimax/chat/__init__.py +++ b/litellm/llms/minimax/chat/__init__.py @@ -1,4 +1,3 @@ """ MiniMax OpenAI-compatible chat API """ - diff --git a/litellm/llms/minimax/chat/transformation.py b/litellm/llms/minimax/chat/transformation.py index 3e9dc0209f2..4095e57a8ae 100644 --- a/litellm/llms/minimax/chat/transformation.py +++ b/litellm/llms/minimax/chat/transformation.py @@ -15,7 +15,7 @@ class MinimaxChatConfig(OpenAIGPTConfig): MiniMax provides an OpenAI-compatible API at: - International: https://api.minimax.io/v1 - China: https://api.minimaxi.com/v1 - + Supported models: - MiniMax-M2.1 - MiniMax-M2.1-lightning @@ -27,11 +27,7 @@ class MinimaxChatConfig(OpenAIGPTConfig): """ Get MiniMax API key from environment or parameters. """ - return ( - api_key - or get_secret_str("MINIMAX_API_KEY") - or litellm.api_key - ) + return api_key or get_secret_str("MINIMAX_API_KEY") or litellm.api_key @staticmethod def get_api_base( @@ -63,7 +59,7 @@ class MinimaxChatConfig(OpenAIGPTConfig): """ # Get the base URL (either provided or default MiniMax endpoint) base_url = self.get_api_base(api_base=api_base) - + # Ensure it ends with /chat/completions if base_url.endswith("/chat/completions"): return base_url @@ -94,13 +90,12 @@ class MinimaxChatConfig(OpenAIGPTConfig): """ base_params = super().get_supported_openai_params(model=model) additional_params = ["reasoning_split"] - + # Add thinking parameter if model supports reasoning try: if litellm.supports_reasoning(model=model, custom_llm_provider="minimax"): additional_params.append("thinking") except Exception: pass - - return base_params + additional_params + return base_params + additional_params diff --git a/litellm/llms/minimax/messages/transformation.py b/litellm/llms/minimax/messages/transformation.py index 27d28f02d83..13ed6ad3863 100644 --- a/litellm/llms/minimax/messages/transformation.py +++ b/litellm/llms/minimax/messages/transformation.py @@ -16,7 +16,7 @@ class MinimaxMessagesConfig(AnthropicMessagesConfig): MiniMax provides an Anthropic-compatible API at: - International: https://api.minimax.io/anthropic - China: https://api.minimaxi.com/anthropic - + Supported models: - MiniMax-M2.1 - MiniMax-M2.1-lightning @@ -32,11 +32,7 @@ class MinimaxMessagesConfig(AnthropicMessagesConfig): """ Get MiniMax API key from environment or parameters. """ - return ( - api_key - or get_secret_str("MINIMAX_API_KEY") - or litellm.api_key - ) + return api_key or get_secret_str("MINIMAX_API_KEY") or litellm.api_key @staticmethod def get_api_base( @@ -68,14 +64,13 @@ class MinimaxMessagesConfig(AnthropicMessagesConfig): """ # Get the base URL (either provided or default MiniMax endpoint) base_url = self.get_api_base(api_base=api_base) - + # If the base URL already includes the full path, return it if base_url.endswith("/v1/messages"): return base_url - + # Otherwise append the messages endpoint if base_url.endswith("/"): return f"{base_url}v1/messages" else: return f"{base_url}/v1/messages" - diff --git a/litellm/llms/minimax/text_to_speech/__init__.py b/litellm/llms/minimax/text_to_speech/__init__.py index e3fcddeb05f..bf4ac9010a4 100644 --- a/litellm/llms/minimax/text_to_speech/__init__.py +++ b/litellm/llms/minimax/text_to_speech/__init__.py @@ -5,4 +5,3 @@ MiniMax Text-to-Speech module from .transformation import MinimaxException, MinimaxTextToSpeechConfig __all__ = ["MinimaxTextToSpeechConfig", "MinimaxException"] - diff --git a/litellm/llms/minimax/text_to_speech/transformation.py b/litellm/llms/minimax/text_to_speech/transformation.py index a3a75d220ff..2a7d6897edc 100644 --- a/litellm/llms/minimax/text_to_speech/transformation.py +++ b/litellm/llms/minimax/text_to_speech/transformation.py @@ -43,7 +43,7 @@ class MinimaxTextToSpeechConfig(BaseTextToSpeechConfig): Configuration for MiniMax Text-to-Speech Reference: https://platform.minimax.io/docs - + MiniMax TTS API supports both WebSocket and HTTP endpoints. This implementation uses the HTTP endpoint for simplicity. """ @@ -186,11 +186,7 @@ class MinimaxTextToSpeechConfig(BaseTextToSpeechConfig): """ Validate MiniMax environment and set up authentication headers """ - api_key = ( - api_key - or litellm.api_key - or get_secret_str("MINIMAX_API_KEY") - ) + api_key = api_key or litellm.api_key or get_secret_str("MINIMAX_API_KEY") if api_key is None: raise ValueError( @@ -224,7 +220,7 @@ class MinimaxTextToSpeechConfig(BaseTextToSpeechConfig): ) -> TextToSpeechRequestData: """ Build the MiniMax TTS request payload. - + MiniMax uses a different structure than OpenAI: - model: The TTS model to use - text: The input text @@ -237,16 +233,18 @@ class MinimaxTextToSpeechConfig(BaseTextToSpeechConfig): voice_id = params.pop("voice_id", voice or "male-qn-qingse") speed = params.pop("speed", 1.0) audio_format = params.pop("format", "mp3") - + # Extract additional voice settings vol = params.pop("vol", 1.0) # Volume (0.1 to 10) pitch = params.pop("pitch", 0) # Pitch adjustment (-12 to 12) - + # Extract audio settings sample_rate = params.pop("sample_rate", 32000) # 16000, 24000, 32000 - bitrate = params.pop("bitrate", 128000) # For MP3: 64000, 128000, 192000, 256000 + bitrate = params.pop( + "bitrate", 128000 + ) # For MP3: 64000, 128000, 192000, 256000 channel = params.pop("channel", 1) # 1 for mono, 2 for stereo - + # Output format: 'url' or 'hex' (default is 'hex') output_format = params.pop("output_format", "hex") @@ -289,14 +287,14 @@ class MinimaxTextToSpeechConfig(BaseTextToSpeechConfig): ) -> "HttpxBinaryResponseContent": """ Transform MiniMax response to standard format. - + MiniMax returns JSON with base64-encoded audio data: { "base_resp": {"status_code": 0, "status_msg": "success"}, "audio_file": "", "extra_info": {...} } - + We need to decode the base64 audio and return it as binary content. """ import base64 @@ -307,12 +305,12 @@ class MinimaxTextToSpeechConfig(BaseTextToSpeechConfig): try: # Parse JSON response response_json = raw_response.json() - + # MiniMax API response format check # The API can return different structures: # 1. {"data": {"audio": "..."}, "status": 0, ...} for HTTP endpoint # 2. {"base_resp": {"status_code": 0, ...}, "audio_file": "..."} for older versions - + # Check for errors - MiniMax uses "status" field in HTTP endpoint response # status: 0 = success, 2 = invalid api key, etc. status = response_json.get("status") @@ -324,11 +322,11 @@ class MinimaxTextToSpeechConfig(BaseTextToSpeechConfig): message=f"MiniMax TTS error: {error_detail}", headers=dict(raw_response.headers), ) - + # Extract audio data # MiniMax returns audio in "data" field data = response_json.get("data", {}) - + # Check if response contains a URL (output_format='url') audio_url = data.get("audio_url", None) if audio_url: @@ -339,17 +337,17 @@ class MinimaxTextToSpeechConfig(BaseTextToSpeechConfig): message=f"URL output format is not yet supported. Use 'hex' format or fetch from URL: {audio_url}", headers=dict(raw_response.headers), ) - + # Get hex-encoded audio data audio_hex = data.get("audio", "") or response_json.get("audio_file", "") - + if not audio_hex: raise MinimaxException( status_code=500, message=f"No audio data in MiniMax response. Response keys: {list(response_json.keys())}", headers=dict(raw_response.headers), ) - + # MiniMax returns hex-encoded audio by default # Try hex decoding first, fall back to base64 if that fails try: @@ -364,15 +362,15 @@ class MinimaxTextToSpeechConfig(BaseTextToSpeechConfig): message=f"Failed to decode audio data: {str(e)}", headers=dict(raw_response.headers), ) - + # Create a new response with binary audio content # We need to create a response that contains the decoded audio bytes # Remove gzip encoding headers to avoid decompression issues clean_headers = dict(raw_response.headers) - clean_headers.pop('content-encoding', None) - clean_headers.pop('transfer-encoding', None) - clean_headers['content-length'] = str(len(audio_bytes)) - + clean_headers.pop("content-encoding", None) + clean_headers.pop("transfer-encoding", None) + clean_headers["content-length"] = str(len(audio_bytes)) + # Create a new response object with the binary content binary_response = httpx.Response( status_code=200, @@ -380,9 +378,9 @@ class MinimaxTextToSpeechConfig(BaseTextToSpeechConfig): content=audio_bytes, request=raw_response.request, ) - + return HttpxBinaryResponseContent(binary_response) - + except json.JSONDecodeError as e: raise MinimaxException( status_code=500, @@ -407,15 +405,10 @@ class MinimaxTextToSpeechConfig(BaseTextToSpeechConfig): """ Construct the MiniMax endpoint URL. """ - base_url = ( - api_base - or get_secret_str("MINIMAX_API_BASE") - or self.TTS_BASE_URL - ) + base_url = api_base or get_secret_str("MINIMAX_API_BASE") or self.TTS_BASE_URL base_url = base_url.rstrip("/") # MiniMax uses a simple endpoint path url = f"{base_url}{self.TTS_ENDPOINT_PATH}" return url - diff --git a/litellm/llms/mistral/audio_transcription/transformation.py b/litellm/llms/mistral/audio_transcription/transformation.py index fd84d63c4fa..4d294063499 100644 --- a/litellm/llms/mistral/audio_transcription/transformation.py +++ b/litellm/llms/mistral/audio_transcription/transformation.py @@ -60,9 +60,7 @@ class MistralAudioTranscriptionConfig(BaseAudioTranscriptionConfig): stream: Optional[bool] = None, ) -> str: api_base = ( - "https://api.mistral.ai/v1" - if api_base is None - else api_base.rstrip("/") + "https://api.mistral.ai/v1" if api_base is None else api_base.rstrip("/") ) return f"{api_base}/audio/transcriptions" @@ -121,7 +119,9 @@ class MistralAudioTranscriptionConfig(BaseAudioTranscriptionConfig): openai_params=self.get_supported_openai_params(model), ) for key, value in provider_specific_params.items(): - form_fields[key] = str(value).lower() if isinstance(value, bool) else str(value) + form_fields[key] = ( + str(value).lower() if isinstance(value, bool) else str(value) + ) files = { "file": ( diff --git a/litellm/llms/mistral/chat/transformation.py b/litellm/llms/mistral/chat/transformation.py index 26738623375..23fbe467fc8 100644 --- a/litellm/llms/mistral/chat/transformation.py +++ b/litellm/llms/mistral/chat/transformation.py @@ -244,7 +244,7 @@ class MistralConfig(OpenAIGPTConfig): - if `name` is passed, then drop it for mistral API: https://github.com/BerriAI/litellm/issues/6696 Motivation: mistral api doesn't support content as a list. - The above statement is not valid now. Need to plan to remove all the #1,2,3 + The above statement is not valid now. Need to plan to remove all the #1,2,3 Mistral API supports content as a list. """ ## 1. If 'image_url' or 'file' in content, then transform with base class and mistral-specific handling @@ -276,8 +276,8 @@ class MistralConfig(OpenAIGPTConfig): else: return super()._transform_messages(new_messages, model, False) - async def _transform_messages_async(self, - messages: List[AllMessageValues], model: str + async def _transform_messages_async( + self, messages: List[AllMessageValues], model: str ) -> List[AllMessageValues]: """ Handle modification of messages for Mistral API in an async context. @@ -288,11 +288,10 @@ class MistralConfig(OpenAIGPTConfig): messages = self._handle_message_with_file(messages) return messages - def _transform_messages_sync(self, - messages: List[AllMessageValues], model: str + def _transform_messages_sync( + self, messages: List[AllMessageValues], model: str ) -> List[AllMessageValues]: - """ Handle modification of messages for Mistral API in a sync context. - """ + """Handle modification of messages for Mistral API in a sync context.""" # Call parent sync method to handle basic transformations # and then apply Mistral-specific handling for files # This is the sync version of the async method above @@ -301,23 +300,25 @@ class MistralConfig(OpenAIGPTConfig): return messages def _handle_message_with_file( - self, - messages: List[AllMessageValues]) -> List[AllMessageValues]: + self, messages: List[AllMessageValues] + ) -> List[AllMessageValues]: """ Mistral API supports only 'file_id' in message content with type 'file'. """ for m in messages: _content_block = m.get("content") - if _content_block and isinstance(_content_block, list): + if _content_block and isinstance(_content_block, list): if any(c.get("type") == "file" for c in _content_block): # If file content is present, we get file_id from 'file' attribute of content block # then replace 'file' with 'file_id' and assign the value of 'file_id' attribute to it. - file_contents = [c for c in _content_block if c.get("type") == "file"] + file_contents = [ + c for c in _content_block if c.get("type") == "file" + ] for file_content in file_contents: file_id = file_content.get("file", {}).get("file_id") if file_id: # Replace 'file' with 'file_id' - file_content["file_id"] = file_id # type: ignore + file_content["file_id"] = file_id # type: ignore file_content.pop("file", None) return messages @@ -343,9 +344,9 @@ class MistralConfig(OpenAIGPTConfig): # Handle both string and list content, preserving original format if isinstance(existing_content, str): # String content - prepend reasoning prompt - new_content: Union[str, list] = ( - f"{reasoning_prompt}\n\n{existing_content}" - ) + new_content: Union[ + str, list + ] = f"{reasoning_prompt}\n\n{existing_content}" elif isinstance(existing_content, list): # List content - prepend reasoning prompt as text block new_content = [ @@ -679,5 +680,7 @@ class MistralChatResponseIterator(OpenAIChatCompletionStreamingHandler): text_segments.append(block.get("text", "")) normalized_text = "".join(text_segments) if text_segments else None - reasoning_content = "\n".join(reasoning_segments) if reasoning_segments else None + reasoning_content = ( + "\n".join(reasoning_segments) if reasoning_segments else None + ) return normalized_text, thinking_blocks, reasoning_content diff --git a/litellm/llms/mistral/embedding.py b/litellm/llms/mistral/embedding.py index 0aae35ad7f7..4861674a191 100644 --- a/litellm/llms/mistral/embedding.py +++ b/litellm/llms/mistral/embedding.py @@ -1,4 +1,4 @@ """ Calls handled in openai/ as mistral is an openai-compatible endpoint. -""" \ No newline at end of file +""" diff --git a/litellm/llms/mistral/ocr/__init__.py b/litellm/llms/mistral/ocr/__init__.py index 40cc62696be..54eed416c1e 100644 --- a/litellm/llms/mistral/ocr/__init__.py +++ b/litellm/llms/mistral/ocr/__init__.py @@ -1,2 +1 @@ """Mistral OCR transformation module.""" - diff --git a/litellm/llms/mistral/ocr/guardrail_translation/handler.py b/litellm/llms/mistral/ocr/guardrail_translation/handler.py index 87d79a3ce60..697bd2daa3d 100644 --- a/litellm/llms/mistral/ocr/guardrail_translation/handler.py +++ b/litellm/llms/mistral/ocr/guardrail_translation/handler.py @@ -108,9 +108,7 @@ class OCRHandler(BaseTranslation): Modified OCRResponse with guardrailed page text """ if not hasattr(response, "pages") or not response.pages: - verbose_proxy_logger.debug( - "OCR guardrail: No pages found in OCR response" - ) + verbose_proxy_logger.debug("OCR guardrail: No pages found in OCR response") return response # Extract markdown text from all pages diff --git a/litellm/llms/mistral/ocr/transformation.py b/litellm/llms/mistral/ocr/transformation.py index ed5e2359395..11848f8acf4 100644 --- a/litellm/llms/mistral/ocr/transformation.py +++ b/litellm/llms/mistral/ocr/transformation.py @@ -18,7 +18,7 @@ from litellm.secret_managers.main import get_secret_str class MistralOCRConfig(BaseOCRConfig): """ Mistral OCR transformation configuration. - + Reference: https://docs.mistral.ai/api/#tag/ocr """ @@ -28,7 +28,7 @@ class MistralOCRConfig(BaseOCRConfig): def get_supported_ocr_params(self, model: str) -> list: """ Get supported OCR parameters for Mistral OCR. - + Mistral OCR supports: - pages: List of page numbers to process - include_image_base64: Whether to include base64 encoded images @@ -45,7 +45,7 @@ class MistralOCRConfig(BaseOCRConfig): "bbox_annotation_format", "document_annotation_format", ] - + def map_ocr_params( self, non_default_params: dict, @@ -54,18 +54,18 @@ class MistralOCRConfig(BaseOCRConfig): ) -> dict: """ Map OCR parameters to Mistral-specific format. - + Mistral accepts these parameters directly, so no transformation needed. Just filter out unsupported params. """ supported_params = self.get_supported_ocr_params(model=model) - + # Only include params that are in the supported list mapped_params = {} for param, value in non_default_params.items(): if param in supported_params: mapped_params[param] = value - + return mapped_params def validate_environment( @@ -82,9 +82,7 @@ class MistralOCRConfig(BaseOCRConfig): """ # Get API key from environment if not provided if api_key is None: - api_key = ( - get_secret_str("MISTRAL_API_KEY") - ) + api_key = get_secret_str("MISTRAL_API_KEY") if api_key is None: raise ValueError( @@ -95,7 +93,7 @@ class MistralOCRConfig(BaseOCRConfig): "Authorization": f"Bearer {api_key}", **headers, } - + # Don't set Content-Type for multipart/form-data - httpx will handle it return headers @@ -110,7 +108,7 @@ class MistralOCRConfig(BaseOCRConfig): ) -> str: """ Get complete URL for Mistral OCR endpoint. - + Returns: https://api.mistral.ai/v1/ocr """ if api_base is None: @@ -118,14 +116,13 @@ class MistralOCRConfig(BaseOCRConfig): # Ensure no trailing slash api_base = api_base.rstrip("/") - + # Remove /v1 if it's already in the base to avoid duplication if api_base.endswith("/v1"): return f"{api_base}/ocr" return f"{api_base}/v1/ocr" - def transform_ocr_request( self, model: str, @@ -136,7 +133,7 @@ class MistralOCRConfig(BaseOCRConfig): ) -> OCRRequestData: """ Transform OCR request to Mistral-specific format. - + Mistral OCR API accepts: { "model": "mistral-ocr-latest", @@ -148,32 +145,32 @@ class MistralOCRConfig(BaseOCRConfig): "include_image_base64": false, # optional ... } - + Args: model: Model name (e.g., "mistral-ocr-latest") document: Document dict from user (Mistral format) - already validated in main.py optional_params: Already mapped optional parameters headers: Request headers - + Returns: OCRRequestData with JSON data """ verbose_logger.debug(f"Mistral OCR transform_ocr_request - model: {model}") - + # Document parameter is the Mistral-format dict from the user # Just pass it through as-is to the Mistral API if not isinstance(document, dict): raise ValueError(f"Expected document dict, got {type(document)}") - + # Build request data - use document dict directly data = { "model": model, "document": document, # Pass through the Mistral-format document dict } - + # Add all optional parameters from the already-mapped optional_params data.update(optional_params) - + # No multipart files - using JSON return OCRRequestData(data=data, files=None) @@ -186,10 +183,10 @@ class MistralOCRConfig(BaseOCRConfig): ) -> OCRResponse: """ Return Mistral OCR response in native format. - + Mistral OCR is the standard format for LiteLLM OCR responses. No transformation needed - return native response. - + Mistral OCR returns: { "pages": [ @@ -208,9 +205,9 @@ class MistralOCRConfig(BaseOCRConfig): """ try: response_json = raw_response.json() - + verbose_logger.debug(f"Mistral OCR response keys: {response_json.keys()}") - + # Return native Mistral format - no transformation return OCRResponse( pages=response_json.get("pages", []), @@ -222,4 +219,3 @@ class MistralOCRConfig(BaseOCRConfig): except Exception as e: verbose_logger.error(f"Error parsing Mistral OCR response: {e}") raise e - diff --git a/litellm/llms/moonshot/chat/transformation.py b/litellm/llms/moonshot/chat/transformation.py index 72c51bf74ff..3ed08f51c8d 100644 --- a/litellm/llms/moonshot/chat/transformation.py +++ b/litellm/llms/moonshot/chat/transformation.py @@ -95,24 +95,24 @@ class MoonshotChatConfig(OpenAIGPTConfig): def get_supported_openai_params(self, model: str) -> list: """ Get the supported OpenAI params for Moonshot AI models - + Moonshot AI limitations: - functions parameter is not supported (use tools instead) - tool_choice doesn't support "required" value - kimi-thinking-preview doesn't support tool calls at all """ excluded_params: List[str] = ["functions"] - + # kimi-thinking-preview has additional limitations if "kimi-thinking-preview" in model: excluded_params.extend(["tools", "tool_choice"]) - + base_openai_params = super().get_supported_openai_params(model=model) final_params: List[str] = [] for param in base_openai_params: if param not in excluded_params: final_params.append(param) - + return final_params def map_openai_params( @@ -124,7 +124,7 @@ class MoonshotChatConfig(OpenAIGPTConfig): ) -> dict: """ Map OpenAI parameters to Moonshot AI parameters - + Handles Moonshot AI specific limitations: - tool_choice doesn't support "required" value - Temperature <0.3 limitation for n>1 @@ -139,7 +139,7 @@ class MoonshotChatConfig(OpenAIGPTConfig): ########################################## # temperature limitations # 1. `temperature` on KIMI API is [0, 1] but OpenAI is [0, 2] - # 2. If temperature < 0.3 and n > 1, KIMI will raise an exception. + # 2. If temperature < 0.3 and n > 1, KIMI will raise an exception. # If we enter this condition, we set the temperature to 0.3 as suggested by Moonshot AI ########################################## if "temperature" in optional_params: @@ -148,7 +148,6 @@ class MoonshotChatConfig(OpenAIGPTConfig): if optional_params["temperature"] < 0.3 and optional_params.get("n", 1) > 1: optional_params["temperature"] = 0.3 return optional_params - def transform_request( self, @@ -178,17 +177,20 @@ class MoonshotChatConfig(OpenAIGPTConfig): litellm_params=litellm_params, headers=headers, ) - - def _add_tool_choice_required_message(self, messages: List[AllMessageValues], optional_params: dict) -> List[AllMessageValues]: + def _add_tool_choice_required_message( + self, messages: List[AllMessageValues], optional_params: dict + ) -> List[AllMessageValues]: """ Add a message to the messages list to indicate that the tool choice is required. https://platform.moonshot.ai/docs/guide/migrating-from-openai-to-kimi#about-tool_choice """ - messages.append({ - "role": "user", - "content": "Please select a tool to handle the current issue.", # Usually, the Kimi large language model understands the intention to invoke a tool and selects one for invocation - }) + messages.append( + { + "role": "user", + "content": "Please select a tool to handle the current issue.", # Usually, the Kimi large language model understands the intention to invoke a tool and selects one for invocation + } + ) optional_params.pop("tool_choice") return messages diff --git a/litellm/llms/nvidia_nim/rerank/common_utils.py b/litellm/llms/nvidia_nim/rerank/common_utils.py index 2bd8c123c90..738fb09364a 100644 --- a/litellm/llms/nvidia_nim/rerank/common_utils.py +++ b/litellm/llms/nvidia_nim/rerank/common_utils.py @@ -6,13 +6,13 @@ Common utilities for NVIDIA NIM rerank provider. def get_nvidia_nim_rerank_config(model: str): """ Get the appropriate NVIDIA NIM rerank config based on the model. - + Args: model: The model string (e.g., "nvidia/llama-3.2-nv-rerankqa-1b-v2" or "ranking/nvidia/llama-3.2-nv-rerankqa-1b-v2") - + Returns: NvidiaNimRankingConfig if model starts with "ranking/", else NvidiaNimRerankConfig - + Example: - "ranking/nvidia/llama-3.2-nv-rerankqa-1b-v2" -> NvidiaNimRankingConfig - "nvidia/llama-3.2-nv-rerankqa-1b-v2" -> NvidiaNimRerankConfig @@ -25,4 +25,3 @@ def get_nvidia_nim_rerank_config(model: str): if model.startswith("ranking/"): return NvidiaNimRankingConfig() return NvidiaNimRerankConfig() - diff --git a/litellm/llms/nvidia_nim/rerank/ranking_transformation.py b/litellm/llms/nvidia_nim/rerank/ranking_transformation.py index d97c47bcb22..757d874bf31 100644 --- a/litellm/llms/nvidia_nim/rerank/ranking_transformation.py +++ b/litellm/llms/nvidia_nim/rerank/ranking_transformation.py @@ -31,10 +31,10 @@ class NvidiaNimRankingConfig(NvidiaNimRerankConfig): """Strip 'nvidia_nim/' and 'ranking/' prefixes from model name.""" # First strip nvidia_nim/ prefix if present if model.startswith("nvidia_nim/"): - model = model[len("nvidia_nim/"):] + model = model[len("nvidia_nim/") :] # Then strip ranking/ prefix if present if model.startswith("ranking/"): - model = model[len("ranking/"):] + model = model[len("ranking/") :] return model def get_complete_url( @@ -45,7 +45,7 @@ class NvidiaNimRankingConfig(NvidiaNimRerankConfig): ) -> str: """ Construct the Nvidia NIM ranking URL. - + Format: {api_base}/v1/ranking """ if not api_base: @@ -76,4 +76,3 @@ class NvidiaNimRankingConfig(NvidiaNimRerankConfig): optional_rerank_params=optional_rerank_params, headers=headers, ) - diff --git a/litellm/llms/nvidia_nim/rerank/transformation.py b/litellm/llms/nvidia_nim/rerank/transformation.py index c7b1b249daa..bd5abac60c8 100644 --- a/litellm/llms/nvidia_nim/rerank/transformation.py +++ b/litellm/llms/nvidia_nim/rerank/transformation.py @@ -45,11 +45,12 @@ class NvidiaNimRerankResponse(TypedDict): class NvidiaNimRerankConfig(BaseRerankConfig): """ Reference: https://docs.api.nvidia.com/nim/reference/nvidia-llama-3_2-nv-rerankqa-1b-v2-infer - + Nvidia NIM rerank API uses a different format: - query is an object with 'text' field - documents are called 'passages' and have 'text' field """ + DEFAULT_NIM_RERANK_API_BASE = "https://ai.api.nvidia.com" def __init__(self) -> None: @@ -58,39 +59,39 @@ class NvidiaNimRerankConfig(BaseRerankConfig): def _get_clean_model_name(self, model: str) -> str: """Strip 'nvidia_nim/' prefix from model name if present.""" if model.startswith("nvidia_nim/"): - return model[len("nvidia_nim/"):] + return model[len("nvidia_nim/") :] return model def get_complete_url( - self, - api_base: Optional[str], + self, + api_base: Optional[str], model: str, optional_params: Optional[dict] = None, ) -> str: """ Construct the Nvidia NIM rerank URL. - + Format: {api_base}/v1/retrieval/{model}/reranking - + If the user provides a full URL (e.g., {api_base}/v1/retrieval/{model}/reranking), it will be used as-is. """ if not api_base: api_base = self.DEFAULT_NIM_RERANK_API_BASE - + api_base = api_base.rstrip("/") - + # Check if user already provided the full URL with /retrieval/ path if "/retrieval/" in api_base: return api_base - + # Ensure we don't have duplicate /v1 if api_base.endswith("/v1"): api_base = api_base[:-3] - + # Strip nvidia_nim/ prefix from model name if present clean_model = self._get_clean_model_name(model) - + return f"{api_base}/v1/retrieval/{clean_model}/reranking" def get_supported_cohere_rerank_params(self, model: str) -> list: @@ -119,10 +120,10 @@ class NvidiaNimRerankConfig(BaseRerankConfig): ) -> Dict: """ Map Cohere/OpenAI rerank params to Nvidia NIM format. - + Parameter mapping: - top_n (Cohere) -> top_k (Nvidia) - + Nvidia NIM specific params (passed through as-is from non_default_params): - truncate: How to truncate input if too long (NONE, END) """ @@ -130,11 +131,11 @@ class NvidiaNimRerankConfig(BaseRerankConfig): "query": query, "documents": documents, } - + # Map Cohere's top_n to Nvidia's top_k if top_n is not None: optional_nvidia_nim_rerank_params["top_k"] = top_n - + # Pass through Nvidia-specific params from non_default_params if non_default_params: optional_nvidia_nim_rerank_params.update(non_default_params) @@ -151,10 +152,7 @@ class NvidiaNimRerankConfig(BaseRerankConfig): Validate that the Nvidia NIM API key is present. """ if api_key is None: - api_key = ( - get_secret_str("NVIDIA_NIM_API_KEY") - or litellm.api_key - ) + api_key = get_secret_str("NVIDIA_NIM_API_KEY") or litellm.api_key if api_key is None: raise ValueError( @@ -182,12 +180,12 @@ class NvidiaNimRerankConfig(BaseRerankConfig): ) -> dict: """ Transform request to Nvidia NIM format. - + Nvidia NIM expects: - query as {text: "..."} - documents as passages: [{text: "..."}, ...] - Optional: truncate (NONE or END), top_k - + Note: optional_rerank_params may contain provider-specific params like 'top_k' and 'truncate' that aren't in the OptionalRerankParams TypedDict but are passed through at runtime. The mapping from Cohere's 'top_n' to Nvidia's 'top_k' already happened in map_cohere_rerank_params. @@ -199,10 +197,10 @@ class NvidiaNimRerankConfig(BaseRerankConfig): query = optional_rerank_params["query"] documents = optional_rerank_params["documents"] - + # Transform query to object format query_obj: NvidiaNimQueryObject = {"text": query} - + # Transform documents to passages format passages: List[NvidiaNimPassageObject] = [] for doc in documents: @@ -215,35 +213,36 @@ class NvidiaNimRerankConfig(BaseRerankConfig): else: # Otherwise, stringify the dict import json + passages.append({"text": json.dumps(doc)}) else: passages.append({"text": str(doc)}) - + # Strip nvidia_nim/ prefix from model name if present clean_model = self._get_clean_model_name(model) - + # Note: URL path uses underscores (llama-3_2) but JSON body uses periods (llama-3.2) # Convert underscores back to periods for the model field in request body model_for_body = clean_model.replace("_", ".") - + # Build request using TypedDict request_data: NvidiaNimRerankRequest = { "model": model_for_body, "query": query_obj, "passages": passages, } - + # Add optional top_k parameter if provided (already mapped from top_n in map_cohere_rerank_params) if "top_k" in optional_rerank_params and optional_rerank_params.get("top_k") is not None: # type: ignore request_data["top_k"] = optional_rerank_params.get("top_k") # type: ignore - + # Add Nvidia-specific truncate parameter if provided # This is passed through from non_default_params, not in base OptionalRerankParams if "truncate" in optional_rerank_params and optional_rerank_params.get("truncate") is not None: # type: ignore truncate_value = optional_rerank_params.get("truncate") # type: ignore if truncate_value in ["NONE", "END"]: request_data["truncate"] = truncate_value # type: ignore - + return dict(request_data) def transform_rerank_response( @@ -259,7 +258,7 @@ class NvidiaNimRerankConfig(BaseRerankConfig): ) -> RerankResponse: """ Transform Nvidia NIM rerank response to LiteLLM format. - + Nvidia NIM returns (NvidiaNimRerankResponse): { "rankings": [ @@ -269,7 +268,7 @@ class NvidiaNimRerankConfig(BaseRerankConfig): } ] } - + LiteLLM expects (RerankResponse): { "results": [ @@ -292,40 +291,40 @@ class NvidiaNimRerankConfig(BaseRerankConfig): # Parse as NvidiaNimRerankResponse nvidia_response: NvidiaNimRerankResponse = raw_response_json - + # Transform Nvidia NIM response to LiteLLM format results: List[RerankResponseResult] = [] rankings = nvidia_response.get("rankings", []) - + # Get original documents from request if we need to include them - original_passages: List[NvidiaNimPassageObject] = request_data.get("passages", []) - + original_passages: List[NvidiaNimPassageObject] = request_data.get( + "passages", [] + ) + for ranking in rankings: result_item: RerankResponseResult = { "index": ranking["index"], "relevance_score": ranking["logit"], } - + # Include document if it was in the original request index: int = ranking["index"] if index < len(original_passages): result_item["document"] = {"text": original_passages[index]["text"]} # type: ignore - + results.append(result_item) - + # Construct metadata with billed_units # Nvidia NIM uses "usage" field with "total_tokens" usage = raw_response_json.get("usage", {}) total_tokens = usage.get("total_tokens", 0) - + billed_units: RerankBilledUnits = { "total_tokens": total_tokens if total_tokens > 0 else len(results) } - - meta: RerankResponseMeta = { - "billed_units": billed_units - } - + + meta: RerankResponseMeta = {"billed_units": billed_units} + return RerankResponse( id=raw_response_json.get("id") or str(uuid.uuid4()), results=results, @@ -340,4 +339,3 @@ class NvidiaNimRerankConfig(BaseRerankConfig): message=error_message, headers=headers, ) - diff --git a/litellm/llms/oci/chat/transformation.py b/litellm/llms/oci/chat/transformation.py index 1c22602b483..b1af7ed2ec3 100644 --- a/litellm/llms/oci/chat/transformation.py +++ b/litellm/llms/oci/chat/transformation.py @@ -3,7 +3,17 @@ import datetime import hashlib import json from dataclasses import dataclass -from typing import TYPE_CHECKING, Any, AsyncIterator, Dict, List, Optional, Protocol, Tuple, Union +from typing import ( + TYPE_CHECKING, + Any, + AsyncIterator, + Dict, + List, + Optional, + Protocol, + Tuple, + Union, +) from urllib.parse import urlparse import httpx @@ -74,7 +84,9 @@ class OCISignerProtocol(Protocol): See: https://docs.oracle.com/en-us/iaas/tools/python/latest/api/signing.html """ - def do_request_sign(self, request: Any, *, enforce_content_headers: bool = False) -> None: + def do_request_sign( + self, request: Any, *, enforce_content_headers: bool = False + ) -> None: """ Sign an HTTP request by adding authentication headers. @@ -93,6 +105,7 @@ class OCIRequestWrapper: This class wraps request data in a format compatible with OCI SDK signers, which expect objects with method, url, headers, body, and path_url attributes. """ + method: str url: str headers: dict @@ -222,7 +235,9 @@ class OCIChatConfig(BaseConfig): } # Cohere and Gemini use the same parameter mapping as GENERIC - self.openai_to_oci_cohere_param_map = self.openai_to_oci_generic_param_map.copy() + self.openai_to_oci_cohere_param_map = ( + self.openai_to_oci_generic_param_map.copy() + ) def get_supported_openai_params(self, model: str) -> List[str]: supported_params = [] @@ -310,14 +325,13 @@ class OCIChatConfig(BaseConfig): prepared_headers.setdefault("content-length", str(len(body))) request_wrapper = OCIRequestWrapper( - method=method, - url=api_base, - headers=prepared_headers, - body=body + method=method, url=api_base, headers=prepared_headers, body=body ) if oci_signer is None: - raise ValueError("oci_signer cannot be None when calling _sign_with_oci_signer") + raise ValueError( + "oci_signer cannot be None when calling _sign_with_oci_signer" + ) try: oci_signer.do_request_sign(request_wrapper, enforce_content_headers=True) @@ -329,7 +343,7 @@ class OCIChatConfig(BaseConfig): "The signer must implement the OCI SDK Signer interface with a " "do_request_sign(request, enforce_content_headers=True) method. " "See: https://docs.oracle.com/en-us/iaas/tools/python/latest/api/signing.html" - ) + ), ) from e headers.update(request_wrapper.headers) @@ -442,7 +456,9 @@ class OCIChatConfig(BaseConfig): private_key = ( load_private_key_from_str(oci_key_content) if oci_key_content - else load_private_key_from_file(oci_key_file) if oci_key_file else None + else load_private_key_from_file(oci_key_file) + if oci_key_file + else None ) if private_key is None: @@ -539,10 +555,14 @@ class OCIChatConfig(BaseConfig): # If a signer is provided, use it for request signing if oci_signer is not None: - return self._sign_with_oci_signer(headers, optional_params, request_data, api_base) + return self._sign_with_oci_signer( + headers, optional_params, request_data, api_base + ) # Standard manual credential signing - return self._sign_with_manual_credentials(headers, optional_params, request_data, api_base) + return self._sign_with_manual_credentials( + headers, optional_params, request_data, api_base + ) def validate_environment( self, @@ -653,7 +673,7 @@ class OCIChatConfig(BaseConfig): "temperature": 1, "topK": 0, "topP": 0.75, - "frequencyPenalty": 0 + "frequencyPenalty": 0, } else: open_ai_to_oci_param_map = self.openai_to_oci_generic_param_map @@ -665,7 +685,11 @@ class OCIChatConfig(BaseConfig): # Also check for already-mapped OCI params (for backward compatibility) for oci_value in open_ai_to_oci_param_map.values(): - if oci_value and oci_value in optional_params and oci_value not in selected_params: + if ( + oci_value + and oci_value in optional_params + and oci_value not in selected_params + ): selected_params[oci_value] = optional_params[oci_value] # type: ignore[index] if "tools" in selected_params: @@ -709,7 +733,9 @@ class OCIChatConfig(BaseConfig): return selected_params - def adapt_messages_to_cohere_standard(self, messages: List[AllMessageValues]) -> List[CohereMessage]: + def adapt_messages_to_cohere_standard( + self, messages: List[AllMessageValues] + ) -> List[CohereMessage]: """Build chat history for Cohere models.""" chat_history = [] for msg in messages[:-1]: # All messages except the last one @@ -720,7 +746,10 @@ class OCIChatConfig(BaseConfig): # Extract text from content array text_content = "" for content_item in content: - if isinstance(content_item, dict) and content_item.get("type") == "text": + if ( + isinstance(content_item, dict) + and content_item.get("type") == "text" + ): text_content += content_item.get("text", "") content = text_content @@ -734,7 +763,9 @@ class OCIChatConfig(BaseConfig): tool_calls = [] for tool_call in msg["tool_calls"]: # type: ignore[union-attr,typeddict-item] # Parse arguments if they're a JSON string - raw_arguments: Any = tool_call.get("function", {}).get("arguments", {}) + raw_arguments: Any = tool_call.get("function", {}).get( + "arguments", {} + ) if isinstance(raw_arguments, str): try: arguments: Dict[str, Any] = json.loads(raw_arguments) @@ -743,26 +774,34 @@ class OCIChatConfig(BaseConfig): else: arguments = raw_arguments - tool_calls.append(CohereToolCall( - name=str(tool_call.get("function", {}).get("name", "")), - parameters=arguments - )) + tool_calls.append( + CohereToolCall( + name=str(tool_call.get("function", {}).get("name", "")), + parameters=arguments, + ) + ) if role == "user": chat_history.append(CohereMessage(role="USER", message=content)) elif role == "assistant": - chat_history.append(CohereMessage(role="CHATBOT", message=content, toolCalls=tool_calls)) + chat_history.append( + CohereMessage(role="CHATBOT", message=content, toolCalls=tool_calls) + ) elif role == "tool": # Tool messages need special handling - chat_history.append(CohereMessage( - role="TOOL", - message=content, - toolCalls=None # Tool messages don't have tool calls - )) + chat_history.append( + CohereMessage( + role="TOOL", + message=content, + toolCalls=None, # Tool messages don't have tool calls + ) + ) return chat_history - def adapt_tool_definitions_to_cohere_standard(self, tools: List[Dict[str, Any]]) -> List[CohereTool]: + def adapt_tool_definitions_to_cohere_standard( + self, tools: List[Dict[str, Any]] + ) -> List[CohereTool]: """Adapt tool definitions to Cohere format.""" cohere_tools = [] for tool in tools: @@ -775,14 +814,16 @@ class OCIChatConfig(BaseConfig): parameter_definitions[param_name] = CohereParameterDefinition( description=param_schema.get("description", ""), type=param_schema.get("type", "string"), - isRequired=param_name in required + isRequired=param_name in required, ) - cohere_tools.append(CohereTool( - name=function_def.get("name", ""), - description=function_def.get("description", ""), - parameterDefinitions=parameter_definitions - )) + cohere_tools.append( + CohereTool( + name=function_def.get("name", ""), + description=function_def.get("description", ""), + parameterDefinitions=parameter_definitions, + ) + ) return cohere_tools @@ -793,7 +834,10 @@ class OCIChatConfig(BaseConfig): elif isinstance(content, list): text_content = "" for content_item in content: - if isinstance(content_item, dict) and content_item.get("type") == "text": + if ( + isinstance(content_item, dict) + and content_item.get("type") == "text" + ): text_content += content_item.get("text", "") return text_content return str(content) @@ -843,25 +887,28 @@ class OCIChatConfig(BaseConfig): preamble_override = None if system_messages: preamble = "\n".join( - self._extract_text_content(msg["content"]) for msg in system_messages + self._extract_text_content(msg["content"]) + for msg in system_messages ) if preamble: preamble_override = preamble # Create Cohere-specific chat request - optional_cohere_params = self._get_optional_params(OCIVendors.COHERE, optional_params) + optional_cohere_params = self._get_optional_params( + OCIVendors.COHERE, optional_params + ) chat_request = CohereChatRequest( apiFormat="COHERE", message=self._extract_text_content(user_messages[-1]["content"]), chatHistory=self.adapt_messages_to_cohere_standard(messages), preambleOverride=preamble_override, - **optional_cohere_params + **optional_cohere_params, ) data = OCICompletionPayload( compartmentId=oci_compartment_id, servingMode=servingMode, - chatRequest=chat_request + chatRequest=chat_request, ) else: # Use generic format for other vendors @@ -878,10 +925,7 @@ class OCIChatConfig(BaseConfig): return data.model_dump(exclude_none=True) def _handle_cohere_response( - self, - json_response: dict, - model: str, - model_response: ModelResponse + self, json_response: dict, model: str, model_response: ModelResponse ) -> ModelResponse: """Handle Cohere-specific response format.""" cohere_response = CohereChatResult(**json_response) @@ -909,35 +953,39 @@ class OCIChatConfig(BaseConfig): if cohere_response.chatResponse.toolCalls: tool_calls = [] for tool_call in cohere_response.chatResponse.toolCalls: - tool_calls.append({ - "id": f"call_{len(tool_calls)}", # Generate a simple ID - "type": "function", - "function": { - "name": tool_call.name, - "arguments": json.dumps(tool_call.parameters) + tool_calls.append( + { + "id": f"call_{len(tool_calls)}", # Generate a simple ID + "type": "function", + "function": { + "name": tool_call.name, + "arguments": json.dumps(tool_call.parameters), + }, } - }) + ) # Create choice from litellm.types.utils import Choices + choice = Choices( index=0, message={ "role": "assistant", "content": response_text, - "tool_calls": tool_calls + "tool_calls": tool_calls, }, - finish_reason=finish_reason + finish_reason=finish_reason, ) model_response.choices = [choice] # Extract usage info usage_info = cohere_response.chatResponse.usage from litellm.types.utils import Usage + model_response.usage = Usage( # type: ignore[attr-defined] prompt_tokens=usage_info.promptTokens, # type: ignore[union-attr] completion_tokens=usage_info.completionTokens, # type: ignore[union-attr] - total_tokens=usage_info.totalTokens # type: ignore[union-attr] + total_tokens=usage_info.totalTokens, # type: ignore[union-attr] ) return model_response @@ -947,7 +995,7 @@ class OCIChatConfig(BaseConfig): json: dict, model: str, model_response: ModelResponse, - raw_response: httpx.Response + raw_response: httpx.Response, ) -> ModelResponse: """Handle generic OCI response format.""" try: @@ -1018,7 +1066,9 @@ class OCIChatConfig(BaseConfig): if vendor == OCIVendors.COHERE: model_response = self._handle_cohere_response(json, model, model_response) else: - model_response = self._handle_generic_response(json, model, model_response, raw_response) + model_response = self._handle_generic_response( + json, model, model_response, raw_response + ) model_response._hidden_params["additional_headers"] = raw_response.headers @@ -1174,7 +1224,9 @@ def adapt_messages_to_generic_oci_standard_content_message( if isinstance(image_url, dict): image_url = image_url.get("url") if not isinstance(image_url, str): - raise Exception("Prop `image_url` must be a string or an object with a `url` property") + raise Exception( + "Prop `image_url` must be a string or an object with a `url` property" + ) new_content.append(OCIImageContentPart(imageUrl=OCIImageUrl(url=image_url))) return OCIMessage( diff --git a/litellm/llms/ollama/chat/transformation.py b/litellm/llms/ollama/chat/transformation.py index bc5aa654aad..3d9618dfed0 100644 --- a/litellm/llms/ollama/chat/transformation.py +++ b/litellm/llms/ollama/chat/transformation.py @@ -396,7 +396,6 @@ class OllamaChatConfig(BaseConfig): model_response.choices[0].message = message # type: ignore model_response.choices[0].finish_reason = "tool_calls" else: - _message = litellm.Message(**response_json_message) model_response.choices[0].message = _message # type: ignore # Set finish_reason to "tool_calls" when tool_calls are present @@ -505,7 +504,10 @@ class OllamaChatCompletionResponseIterator(BaseModelResponseIterator): reasoning_content = chunk["message"].get("thinking") self.started_reasoning_content = True elif chunk["message"].get("content") is not None: - if self.started_reasoning_content and not self.finished_reasoning_content: + if ( + self.started_reasoning_content + and not self.finished_reasoning_content + ): self.finished_reasoning_content = True message_content = chunk["message"].get("content") diff --git a/litellm/llms/ollama/common_utils.py b/litellm/llms/ollama/common_utils.py index 166ceee27fc..8aedd9b3500 100644 --- a/litellm/llms/ollama/common_utils.py +++ b/litellm/llms/ollama/common_utils.py @@ -71,7 +71,6 @@ class OllamaModelInfo(BaseLLMModelInfo): or get_secret_str("OLLAMA_API_KEY") ) - @staticmethod def get_api_base(api_base: Optional[str] = None) -> str: from litellm.secret_managers.main import get_secret_str @@ -86,7 +85,7 @@ class OllamaModelInfo(BaseLLMModelInfo): base = self.get_api_base(api_base) api_key = self.get_api_key() - headers = { "Authorization": f"Bearer {api_key}" } if api_key else {} + headers = {"Authorization": f"Bearer {api_key}"} if api_key else {} names: set[str] = set() try: diff --git a/litellm/llms/ollama/completion/handler.py b/litellm/llms/ollama/completion/handler.py index 71956158f52..97e4f13b560 100644 --- a/litellm/llms/ollama/completion/handler.py +++ b/litellm/llms/ollama/completion/handler.py @@ -13,9 +13,8 @@ from litellm.types.utils import EmbeddingResponse def _prepare_ollama_embedding_payload( model: str, prompts: List[str], optional_params: Dict[str, Any] ) -> Dict[str, Any]: - data: Dict[str, Any] = {"model": model, "input": prompts} - special_optional_params = ["truncate", "options", "keep_alive","dimensions"] + special_optional_params = ["truncate", "options", "keep_alive", "dimensions"] for k, v in optional_params.items(): if k in special_optional_params: diff --git a/litellm/llms/ollama/completion/transformation.py b/litellm/llms/ollama/completion/transformation.py index ed14b6a3318..6a03325e6c7 100644 --- a/litellm/llms/ollama/completion/transformation.py +++ b/litellm/llms/ollama/completion/transformation.py @@ -93,9 +93,9 @@ class OllamaConfig(BaseConfig): repeat_penalty: Optional[float] = None temperature: Optional[float] = None seed: Optional[int] = None - stop: Optional[list] = ( - None # stop is a list based on this - https://github.com/ollama/ollama/pull/442 - ) + stop: Optional[ + list + ] = None # stop is a list based on this - https://github.com/ollama/ollama/pull/442 tfs_z: Optional[float] = None num_predict: Optional[int] = None top_k: Optional[int] = None @@ -234,9 +234,7 @@ class OllamaConfig(BaseConfig): if model.startswith("ollama/") or model.startswith("ollama_chat/"): model = model.split("/", 1)[1] api_base = ( - api_base - or get_secret_str("OLLAMA_API_BASE") - or "http://localhost:11434" + api_base or get_secret_str("OLLAMA_API_BASE") or "http://localhost:11434" ) api_key = self.get_api_key() headers = {"Authorization": f"Bearer {api_key}"} if api_key else {} @@ -598,7 +596,7 @@ class OllamaTextCompletionResponseIterator(BaseModelResponseIterator): ) else: # In this case, 'thinking' is not present in the chunk, chunk["done"] is false, - # and chunk["response"] is falsy (None or empty string), + # and chunk["response"] is falsy (None or empty string), # but Ollama is just starting to stream, so it should be processed as a normal dict return ModelResponseStream( choices=[ diff --git a/litellm/llms/openai/chat/gpt_5_transformation.py b/litellm/llms/openai/chat/gpt_5_transformation.py index beb76f3d80a..bb5783011a3 100644 --- a/litellm/llms/openai/chat/gpt_5_transformation.py +++ b/litellm/llms/openai/chat/gpt_5_transformation.py @@ -25,6 +25,22 @@ def _normalize_reasoning_effort_for_chat_completion( return None +def _get_effort_level(value: Union[str, dict, None]) -> Optional[str]: + """Extract the effective effort level from reasoning_effort (string or dict). + + Use this for guards that compare effort level (e.g. xhigh validation, "none" checks). + Ensures dict inputs like {"effort": "none", "summary": "detailed"} are correctly + treated as effort="none" for validation purposes. + """ + if value is None: + return None + if isinstance(value, str): + return value + if isinstance(value, dict) and "effort" in value: + return value["effort"] + return None + + class OpenAIGPT5Config(OpenAIGPTConfig): """Configuration for gpt-5 models including GPT-5-Codex variants. @@ -70,6 +86,19 @@ class OpenAIGPT5Config(OpenAIGPTConfig): model_name = model.split("/")[-1] return model_name.startswith("gpt-5.4") + @classmethod + def is_model_gpt_5_4_plus_model(cls, model: str) -> bool: + """Check if the model is gpt-5.4 or newer (5.4, 5.5, 5.6, etc., including pro).""" + model_name = model.split("/")[-1] + if not model_name.startswith("gpt-5."): + return False + try: + version_str = model_name.replace("gpt-5.", "").split("-")[0] + major = version_str.split(".")[0] + return int(major) >= 4 + except (ValueError, IndexError): + return False + @classmethod def _supports_reasoning_effort_level(cls, model: str, level: str) -> bool: """Check if the model supports a specific reasoning_effort level. @@ -150,21 +179,28 @@ class OpenAIGPT5Config(OpenAIGPTConfig): drop_params=drop_params, ) - # Normalize reasoning_effort: chat completion API expects a string, not a dict - # (e.g. {'effort': 'high', 'summary': 'detailed'} -> 'high') - raw_reasoning_effort = ( - non_default_params.get("reasoning_effort") - or optional_params.get("reasoning_effort") - ) - normalized = _normalize_reasoning_effort_for_chat_completion(raw_reasoning_effort) - if raw_reasoning_effort is not None and normalized is not None: - if "reasoning_effort" in non_default_params: - non_default_params["reasoning_effort"] = normalized - if "reasoning_effort" in optional_params: - optional_params["reasoning_effort"] = normalized + # Get raw reasoning_effort and effective effort level for all guards. + # Use effective_effort (extracted string) for xhigh validation, "none" checks, and + # tool/sampling guards — dict inputs like {"effort": "none", "summary": "detailed"} + # must be treated as effort="none" to avoid incorrect tool-drop or sampling errors. + raw_reasoning_effort = non_default_params.get( + "reasoning_effort" + ) or optional_params.get("reasoning_effort") + effective_effort = _get_effort_level(raw_reasoning_effort) - reasoning_effort = normalized or raw_reasoning_effort - if reasoning_effort is not None and reasoning_effort == "xhigh": + # Normalize dict reasoning_effort to string for Chat Completions API. + # Example: {"effort": "high", "summary": "detailed"} -> "high" + if isinstance(raw_reasoning_effort, dict) and "effort" in raw_reasoning_effort: + normalized = _normalize_reasoning_effort_for_chat_completion( + raw_reasoning_effort + ) + if normalized is not None: + if "reasoning_effort" in non_default_params: + non_default_params["reasoning_effort"] = normalized + if "reasoning_effort" in optional_params: + optional_params["reasoning_effort"] = normalized + + if effective_effort is not None and effective_effort == "xhigh": if not self._supports_reasoning_effort_level(model, "xhigh"): if litellm.drop_params or drop_params: non_default_params.pop("reasoning_effort", None) @@ -185,23 +221,12 @@ class OpenAIGPT5Config(OpenAIGPTConfig): "max_tokens" ) - # gpt-5.4: function calls not supported when reasoning_effort != "none" - # Drop reasoning_effort when tools are present (small minority of volume) - if self.is_model_gpt_5_4_model(model): - has_tools = bool( - non_default_params.get("tools") or optional_params.get("tools") - ) - if has_tools and reasoning_effort not in (None, "none"): - non_default_params.pop("reasoning_effort", None) - optional_params.pop("reasoning_effort", None) - reasoning_effort = None - # gpt-5.1/5.2 support logprobs, top_p, top_logprobs only when reasoning_effort="none" supports_none = self._supports_reasoning_effort_level(model, "none") if supports_none: sampling_params = ["logprobs", "top_logprobs", "top_p"] has_sampling = any(p in non_default_params for p in sampling_params) - if has_sampling and reasoning_effort not in (None, "none"): + if has_sampling and effective_effort not in (None, "none"): if litellm.drop_params or drop_params: for p in sampling_params: non_default_params.pop(p, None) @@ -211,7 +236,7 @@ class OpenAIGPT5Config(OpenAIGPTConfig): "gpt-5.1/5.2/5.4 only support logprobs, top_p, top_logprobs when " "reasoning_effort='none'. Current reasoning_effort='{}'. " "To drop unsupported params set `litellm.drop_params = True`" - ).format(reasoning_effort), + ).format(effective_effort), status_code=400, ) @@ -219,7 +244,9 @@ class OpenAIGPT5Config(OpenAIGPTConfig): temperature_value: Optional[float] = non_default_params.pop("temperature") if temperature_value is not None: # models supporting reasoning_effort="none" also support flexible temperature - if supports_none and (reasoning_effort == "none" or reasoning_effort is None): + if supports_none and ( + effective_effort == "none" or effective_effort is None + ): optional_params["temperature"] = temperature_value elif temperature_value == 1: optional_params["temperature"] = temperature_value diff --git a/litellm/llms/openai/chat/gpt_transformation.py b/litellm/llms/openai/chat/gpt_transformation.py index d19210d31ab..63beb82ded8 100644 --- a/litellm/llms/openai/chat/gpt_transformation.py +++ b/litellm/llms/openai/chat/gpt_transformation.py @@ -174,7 +174,9 @@ class OpenAIGPTConfig(BaseLLMModelInfo, BaseConfig): model_specific_params.append("response_format") # Normalize model name for responses API (e.g., "responses/gpt-4.1" -> "gpt-4.1") - model_for_check = model.split("responses/", 1)[1] if "responses/" in model else model + model_for_check = ( + model.split("responses/", 1)[1] if "responses/" in model else model + ) if ( model_for_check in litellm.open_ai_chat_completion_models ) or model_for_check in litellm.open_ai_text_completion_models: @@ -367,10 +369,10 @@ class OpenAIGPTConfig(BaseLLMModelInfo, BaseConfig): List[OpenAIMessageContentListBlock], message_content ) for i, content_item in enumerate(message_content_types): - message_content_types[i] = ( - await self._async_transform_content_item( - cast(OpenAIMessageContentListBlock, content_item), - ) + message_content_types[ + i + ] = await self._async_transform_content_item( + cast(OpenAIMessageContentListBlock, content_item), ) return messages @@ -457,12 +459,13 @@ class OpenAIGPTConfig(BaseLLMModelInfo, BaseConfig): transformed_messages = await self._transform_messages( messages=messages, model=model, is_async=True ) - transformed_messages, tools = ( - self.remove_cache_control_flag_from_messages_and_tools( - model=model, - messages=transformed_messages, - tools=optional_params.get("tools", []), - ) + ( + transformed_messages, + tools, + ) = self.remove_cache_control_flag_from_messages_and_tools( + model=model, + messages=transformed_messages, + tools=optional_params.get("tools", []), ) if tools is not None and len(tools) > 0: optional_params["tools"] = tools @@ -592,9 +595,7 @@ class OpenAIGPTConfig(BaseLLMModelInfo, BaseConfig): ) translated_choice.finish_reason = map_finish_reason( - self._get_finish_reason( - translated_message, choice["finish_reason"] - ) + self._get_finish_reason(translated_message, choice["finish_reason"]) ) transformed_choices.append(translated_choice) @@ -783,13 +784,13 @@ class OpenAIChatCompletionStreamingHandler(BaseModelResponseIterator): def _map_reasoning_to_reasoning_content(self, choices: list) -> list: """ Map 'reasoning' field to 'reasoning_content' field in delta. - - Some OpenAI-compatible providers (e.g., GLM-5, hosted_vllm) return + + Some OpenAI-compatible providers (e.g., GLM-5, hosted_vllm) return delta.reasoning, but LiteLLM expects delta.reasoning_content. - + Args: choices: List of choice objects from the streaming chunk - + Returns: List of choices with reasoning field mapped to reasoning_content """ @@ -798,12 +799,12 @@ class OpenAIChatCompletionStreamingHandler(BaseModelResponseIterator): if "reasoning" in delta: delta["reasoning_content"] = delta.pop("reasoning") return choices - + def chunk_parser(self, chunk: dict) -> ModelResponseStream: try: choices = chunk.get("choices", []) choices = self._map_reasoning_to_reasoning_content(choices) - + kwargs = { "id": chunk["id"], "object": "chat.completion.chunk", diff --git a/litellm/llms/openai/chat/guardrail_translation/handler.py b/litellm/llms/openai/chat/guardrail_translation/handler.py index 10b0b58b6ac..bab4c3b5eb7 100644 --- a/litellm/llms/openai/chat/guardrail_translation/handler.py +++ b/litellm/llms/openai/chat/guardrail_translation/handler.py @@ -558,7 +558,9 @@ class OpenAIChatCompletionsHandler(BaseTranslation): for streaming_choice in response.choices: if isinstance(streaming_choice, litellm.StreamingChoices): # Check for text content - if streaming_choice.delta.content and isinstance(streaming_choice.delta.content, str): + if streaming_choice.delta.content and isinstance( + streaming_choice.delta.content, str + ): return True # Check for tool calls if streaming_choice.delta.tool_calls and isinstance( diff --git a/litellm/llms/openai/chat/o_series_transformation.py b/litellm/llms/openai/chat/o_series_transformation.py index 0c5ee90b332..fe8aec9bc2b 100644 --- a/litellm/llms/openai/chat/o_series_transformation.py +++ b/litellm/llms/openai/chat/o_series_transformation.py @@ -132,7 +132,9 @@ class OpenAIOSeriesConfig(OpenAIGPTConfig): def is_model_o_series_model(self, model: str) -> bool: model = model.split("/")[-1] # could be "openai/o3" or "o3" return ( - len(model) > 1 and model[0] == "o" and model[1].isdigit() + len(model) > 1 + and model[0] == "o" + and model[1].isdigit() and model in litellm.open_ai_chat_completion_models ) @@ -174,4 +176,4 @@ class OpenAIOSeriesConfig(OpenAIGPTConfig): else: return super()._transform_messages( messages, model, is_async=cast(Literal[False], False) - ) \ No newline at end of file + ) diff --git a/litellm/llms/openai/common_utils.py b/litellm/llms/openai/common_utils.py index b6b302782e8..35723ccd637 100644 --- a/litellm/llms/openai/common_utils.py +++ b/litellm/llms/openai/common_utils.py @@ -7,7 +7,17 @@ import inspect import json import os import ssl -from typing import TYPE_CHECKING, Any, Dict, List, Literal, NamedTuple, Optional, Tuple, Union +from typing import ( + TYPE_CHECKING, + Any, + Dict, + List, + Literal, + NamedTuple, + Optional, + Tuple, + Union, +) import httpx import openai @@ -271,10 +281,7 @@ def get_openai_credentials( or None ) resolved_api_key = ( - api_key - or litellm.api_key - or litellm.openai_key - or os.getenv("OPENAI_API_KEY") + api_key or litellm.api_key or litellm.openai_key or os.getenv("OPENAI_API_KEY") ) return OpenAICredentials( api_base=resolved_api_base, diff --git a/litellm/llms/openai/completion/transformation.py b/litellm/llms/openai/completion/transformation.py index 77dc0b54fe0..44a4949d455 100644 --- a/litellm/llms/openai/completion/transformation.py +++ b/litellm/llms/openai/completion/transformation.py @@ -111,9 +111,9 @@ class OpenAITextCompletionConfig(BaseTextCompletionConfig, OpenAIGPTConfig): if "model" in response_object: model_response_object.model = response_object["model"] - model_response_object._hidden_params["original_response"] = ( - response_object # track original response, if users make a litellm.text_completion() request, we can return the original response - ) + model_response_object._hidden_params[ + "original_response" + ] = response_object # track original response, if users make a litellm.text_completion() request, we can return the original response return model_response_object except Exception as e: raise e diff --git a/litellm/llms/openai/containers/transformation.py b/litellm/llms/openai/containers/transformation.py index b89204230ac..645538fdd9c 100644 --- a/litellm/llms/openai/containers/transformation.py +++ b/litellm/llms/openai/containers/transformation.py @@ -31,15 +31,13 @@ else: class OpenAIContainerConfig(BaseContainerConfig): - """Configuration class for OpenAI container API. - """ + """Configuration class for OpenAI container API.""" def __init__(self): super().__init__() def get_supported_openai_params(self) -> list: - """Get the list of supported OpenAI parameters for container API. - """ + """Get the list of supported OpenAI parameters for container API.""" return [ "name", "expires_after", @@ -78,8 +76,7 @@ class OpenAIContainerConfig(BaseContainerConfig): api_base: Optional[str], litellm_params: dict, ) -> str: - """Get the complete URL for OpenAI container API. - """ + """Get the complete URL for OpenAI container API.""" api_base = ( api_base or litellm.api_base @@ -97,11 +94,11 @@ class OpenAIContainerConfig(BaseContainerConfig): litellm_params: GenericLiteLLMParams, headers: dict, ) -> Dict: - """Transform the container creation request for OpenAI API. - """ + """Transform the container creation request for OpenAI API.""" # Remove extra_headers from optional params as they're handled separately container_create_optional_request_params = { - k: v for k, v in container_create_optional_request_params.items() + k: v + for k, v in container_create_optional_request_params.items() if k not in ["extra_headers"] } @@ -118,8 +115,7 @@ class OpenAIContainerConfig(BaseContainerConfig): raw_response: httpx.Response, logging_obj: LiteLLMLoggingObj, ) -> ContainerObject: - """Transform the OpenAI container creation response. - """ + """Transform the OpenAI container creation response.""" response_data = raw_response.json() # Transform the response data @@ -132,12 +128,17 @@ class OpenAIContainerConfig(BaseContainerConfig): sessions=1, provider="openai", ) - - if not hasattr(container_obj, "_hidden_params") or container_obj._hidden_params is None: + + if ( + not hasattr(container_obj, "_hidden_params") + or container_obj._hidden_params is None + ): container_obj._hidden_params = {} if "additional_headers" not in container_obj._hidden_params: container_obj._hidden_params["additional_headers"] = {} - container_obj._hidden_params["additional_headers"]["llm_provider-x-litellm-response-cost"] = container_cost + container_obj._hidden_params["additional_headers"][ + "llm_provider-x-litellm-response-cost" + ] = container_cost return container_obj @@ -152,7 +153,7 @@ class OpenAIContainerConfig(BaseContainerConfig): extra_query: Optional[Dict[str, Any]] = None, ) -> Tuple[str, Dict]: """Transform the container list request for OpenAI API. - + OpenAI API expects the following request: - GET /v1/containers """ @@ -179,8 +180,7 @@ class OpenAIContainerConfig(BaseContainerConfig): raw_response: httpx.Response, logging_obj: LiteLLMLoggingObj, ) -> ContainerListResponse: - """Transform the OpenAI container list response. - """ + """Transform the OpenAI container list response.""" response_data = raw_response.json() # Transform the response data @@ -195,8 +195,7 @@ class OpenAIContainerConfig(BaseContainerConfig): litellm_params: GenericLiteLLMParams, headers: dict, ) -> Tuple[str, Dict]: - """Transform the OpenAI container retrieve request. - """ + """Transform the OpenAI container retrieve request.""" # For container retrieve, we just need to construct the URL url = f"{api_base.rstrip('/')}/{container_id}" @@ -210,8 +209,7 @@ class OpenAIContainerConfig(BaseContainerConfig): raw_response: httpx.Response, logging_obj: LiteLLMLoggingObj, ) -> ContainerObject: - """Transform the OpenAI container retrieve response. - """ + """Transform the OpenAI container retrieve response.""" response_data = raw_response.json() # Transform the response data container_obj = ContainerObject(**response_data) # type: ignore[arg-type] @@ -226,7 +224,7 @@ class OpenAIContainerConfig(BaseContainerConfig): headers: dict, ) -> Tuple[str, Dict]: """Transform the container delete request for OpenAI API. - + OpenAI API expects the following request: - DELETE /v1/containers/{container_id} """ @@ -243,8 +241,7 @@ class OpenAIContainerConfig(BaseContainerConfig): raw_response: httpx.Response, logging_obj: LiteLLMLoggingObj, ) -> DeleteContainerResult: - """Transform the OpenAI container delete response. - """ + """Transform the OpenAI container delete response.""" response_data = raw_response.json() # Transform the response data @@ -264,7 +261,7 @@ class OpenAIContainerConfig(BaseContainerConfig): extra_query: Optional[Dict[str, Any]] = None, ) -> Tuple[str, Dict]: """Transform the container file list request for OpenAI API. - + OpenAI API expects the following request: - GET /v1/containers/{container_id}/files """ @@ -291,8 +288,7 @@ class OpenAIContainerConfig(BaseContainerConfig): raw_response: httpx.Response, logging_obj: LiteLLMLoggingObj, ) -> ContainerFileListResponse: - """Transform the OpenAI container file list response. - """ + """Transform the OpenAI container file list response.""" response_data = raw_response.json() # Transform the response data @@ -309,7 +305,7 @@ class OpenAIContainerConfig(BaseContainerConfig): headers: dict, ) -> Tuple[str, Dict]: """Transform the container file content request for OpenAI API. - + OpenAI API expects the following request: - GET /v1/containers/{container_id}/files/{file_id}/content """ @@ -327,13 +323,16 @@ class OpenAIContainerConfig(BaseContainerConfig): logging_obj: LiteLLMLoggingObj, ) -> bytes: """Transform the OpenAI container file content response. - + Returns the raw binary content of the file. """ return raw_response.content def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers], + self, + error_message: str, + status_code: int, + headers: Union[dict, httpx.Headers], ) -> BaseLLMException: from ...base_llm.chat.transformation import BaseLLMException @@ -342,4 +341,3 @@ class OpenAIContainerConfig(BaseContainerConfig): message=error_message, headers=headers, ) - diff --git a/litellm/llms/openai/image_edit/__init__.py b/litellm/llms/openai/image_edit/__init__.py index c1898326b72..5d933b8186d 100644 --- a/litellm/llms/openai/image_edit/__init__.py +++ b/litellm/llms/openai/image_edit/__init__.py @@ -3,24 +3,27 @@ from litellm.llms.base_llm.image_edit.transformation import BaseImageEditConfig from .dalle2_transformation import DallE2ImageEditConfig from .transformation import OpenAIImageEditConfig -__all__ = ["OpenAIImageEditConfig", "DallE2ImageEditConfig", "get_openai_image_edit_config"] +__all__ = [ + "OpenAIImageEditConfig", + "DallE2ImageEditConfig", + "get_openai_image_edit_config", +] def get_openai_image_edit_config(model: str) -> BaseImageEditConfig: """ Get the appropriate OpenAI image edit config based on the model. - + Args: model: The model name (e.g., "dall-e-2", "gpt-image-1") - + Returns: The appropriate config instance for the model """ model_normalized = model.lower().replace("-", "").replace("_", "") - + if model_normalized == "dalle2": return DallE2ImageEditConfig() else: # Default to standard OpenAI config for gpt-image-1 and other models return OpenAIImageEditConfig() - diff --git a/litellm/llms/openai/image_edit/dalle2_transformation.py b/litellm/llms/openai/image_edit/dalle2_transformation.py index fd697b210ee..04995ce9514 100644 --- a/litellm/llms/openai/image_edit/dalle2_transformation.py +++ b/litellm/llms/openai/image_edit/dalle2_transformation.py @@ -22,7 +22,7 @@ else: class DallE2ImageEditConfig(OpenAIImageEditConfig): """ DALL-E-2 specific configuration for image edit API. - + DALL-E-2 only supports editing a single image (not an array). Uses "image" field name instead of "image[]". """ @@ -40,7 +40,7 @@ class DallE2ImageEditConfig(OpenAIImageEditConfig): Transform image edit request for DALL-E-2. DALL-E-2 only accepts a single image with field name "image" (not "image[]"). - """ + """ request_params = { "model": model, **image_edit_optional_request_params, @@ -49,11 +49,10 @@ class DallE2ImageEditConfig(OpenAIImageEditConfig): request_params["image"] = image if prompt is not None: request_params["prompt"] = prompt - + request = ImageEditRequestParams(**request_params) request_dict = cast(Dict, request) - ######################################################### # Separate images and masks as `files` and send other parameters as `data` ######################################################### @@ -103,4 +102,3 @@ class DallE2ImageEditConfig(OpenAIImageEditConfig): files_list.append(("mask", ("mask.png", _mask, mask_content_type))) return data_without_files, files_list - diff --git a/litellm/llms/openai/image_edit/transformation.py b/litellm/llms/openai/image_edit/transformation.py index a92a89eac65..6917e8d7990 100644 --- a/litellm/llms/openai/image_edit/transformation.py +++ b/litellm/llms/openai/image_edit/transformation.py @@ -101,7 +101,7 @@ class OpenAIImageEditConfig(BaseImageEditConfig): request_params["image"] = image if prompt is not None: request_params["prompt"] = prompt - + request = ImageEditRequestParams(**request_params) request_dict = cast(Dict, request) diff --git a/litellm/llms/openai/image_generation/cost_calculator.py b/litellm/llms/openai/image_generation/cost_calculator.py index 988d5626134..8bca75172fa 100644 --- a/litellm/llms/openai/image_generation/cost_calculator.py +++ b/litellm/llms/openai/image_generation/cost_calculator.py @@ -47,8 +47,8 @@ def cost_calculator( # ImageUsage has the same format as ResponseAPIUsage from litellm.responses.utils import ResponseAPILoggingUtils - chat_usage = ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage( - usage + chat_usage = ( + ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(usage) ) # Use generic_cost_per_token for cost calculation diff --git a/litellm/llms/openai/openai.py b/litellm/llms/openai/openai.py index 5a8b4aafe01..be542677480 100644 --- a/litellm/llms/openai/openai.py +++ b/litellm/llms/openai/openai.py @@ -522,17 +522,14 @@ class OpenAIChatCompletion(BaseLLM, BaseOpenAILLM): from litellm._logging import verbose_logger from litellm.integrations.custom_logger import CustomLogger - callbacks = litellm.callbacks + ( - logging_obj.dynamic_success_callbacks or [] - ) + callbacks = litellm.callbacks + (logging_obj.dynamic_success_callbacks or []) # Avoid logging full callback objects to prevent leaking sensitive data - verbose_logger.debug( - "LiteLLM.AgenticHooks: callbacks_count=%s", len(callbacks) - ) + verbose_logger.debug("LiteLLM.AgenticHooks: callbacks_count=%s", len(callbacks)) tools = optional_params.get("tools", []) # Avoid logging full tools payloads; they may contain sensitive parameters verbose_logger.debug( - "LiteLLM.AgenticHooks: tools_count=%s", len(tools) if isinstance(tools, list) else 1 if tools else 0 + "LiteLLM.AgenticHooks: tools_count=%s", + len(tools) if isinstance(tools, list) else 1 if tools else 0, ) # Get custom_llm_provider from litellm_params custom_llm_provider = litellm_params.get("custom_llm_provider", "openai") @@ -541,37 +538,46 @@ class OpenAIChatCompletion(BaseLLM, BaseOpenAILLM): try: if isinstance(callback, CustomLogger): # Check if the callback has the chat completion agentic loop methods - if not hasattr(callback, 'async_should_run_chat_completion_agentic_loop'): + if not hasattr( + callback, "async_should_run_chat_completion_agentic_loop" + ): continue - + # First: Check if agentic loop should run (using chat completion method) - should_run, tool_calls = ( - await callback.async_should_run_chat_completion_agentic_loop( - response=response, - model=model, - messages=messages, - tools=tools, - stream=stream, - custom_llm_provider=custom_llm_provider, - kwargs=litellm_params, - ) + ( + should_run, + tool_calls, + ) = await callback.async_should_run_chat_completion_agentic_loop( + response=response, + model=model, + messages=messages, + tools=tools, + stream=stream, + custom_llm_provider=custom_llm_provider, + kwargs=litellm_params, ) if should_run: # Second: Execute agentic loop - kwargs_with_provider = litellm_params.copy() if litellm_params else {} - kwargs_with_provider["custom_llm_provider"] = custom_llm_provider - + kwargs_with_provider = ( + litellm_params.copy() if litellm_params else {} + ) + kwargs_with_provider[ + "custom_llm_provider" + ] = custom_llm_provider + # For OpenAI Chat Completions, use the chat completion agentic loop method - agentic_response = await callback.async_run_chat_completion_agentic_loop( - tools=tool_calls, - model=model, - messages=messages, - response=response, - optional_params=optional_params, - logging_obj=logging_obj, - stream=stream, - kwargs=kwargs_with_provider, + agentic_response = ( + await callback.async_run_chat_completion_agentic_loop( + tools=tool_calls, + model=model, + messages=messages, + response=response, + optional_params=optional_params, + logging_obj=logging_obj, + stream=stream, + kwargs=kwargs_with_provider, + ) ) # First hook that runs agentic loop wins return agentic_response @@ -951,7 +957,7 @@ class OpenAIChatCompletion(BaseLLM, BaseOpenAILLM): stream=False, litellm_params=litellm_params, ) - + if agentic_response is not None: final_response_obj = agentic_response diff --git a/litellm/llms/openai/realtime/handler.py b/litellm/llms/openai/realtime/handler.py index 05915e36a69..c04857fc25f 100644 --- a/litellm/llms/openai/realtime/handler.py +++ b/litellm/llms/openai/realtime/handler.py @@ -18,28 +18,28 @@ from ..openai import OpenAIChatCompletion 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 """ @@ -47,31 +47,31 @@ class OpenAIRealtime(OpenAIChatCompletion): "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'). @@ -104,7 +104,7 @@ class OpenAIRealtime(OpenAIChatCompletion): ): import websockets from websockets.asyncio.client import ClientConnection - + if api_base is None: api_base = self._get_default_api_base() if api_key is None: @@ -118,10 +118,10 @@ class OpenAIRealtime(OpenAIChatCompletion): try: # 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, diff --git a/litellm/llms/openai/realtime/http_transformation.py b/litellm/llms/openai/realtime/http_transformation.py new file mode 100644 index 00000000000..1663fcd1fcd --- /dev/null +++ b/litellm/llms/openai/realtime/http_transformation.py @@ -0,0 +1,54 @@ +"""OpenAI realtime HTTP transformation config (client_secrets + realtime_calls).""" + +from typing import Optional + +import litellm +from litellm.llms.base_llm.realtime.http_transformation import BaseRealtimeHTTPConfig +from litellm.secret_managers.main import get_secret_str + + +class OpenAIRealtimeHTTPConfig(BaseRealtimeHTTPConfig): + def get_api_base(self, api_base: Optional[str], **kwargs) -> str: + return ( + api_base + or litellm.api_base + or get_secret_str("OPENAI_API_BASE") + or "https://api.openai.com" + ) + + def get_api_key(self, api_key: Optional[str], **kwargs) -> str: + return ( + api_key + or litellm.api_key + or litellm.openai_key + or get_secret_str("OPENAI_API_KEY") + or "" + ) + + def get_complete_url( + self, api_base: Optional[str], model: str, api_version: Optional[str] = None + ) -> str: + base = self.get_api_base(api_base).rstrip("/") + if base.endswith("/v1"): + base = base[:-3] + return f"{base}/v1/realtime/client_secrets" + + def get_realtime_calls_url( + self, api_base: Optional[str], model: str, api_version: Optional[str] = None + ) -> str: + base = self.get_api_base(api_base).rstrip("/") + if base.endswith("/v1"): + base = base[:-3] + return f"{base}/v1/realtime/calls" + + def validate_environment( + self, + headers: dict, + model: str, + api_key: Optional[str] = None, + ) -> dict: + return { + **headers, + "Authorization": f"Bearer {api_key or ''}", + "Content-Type": "application/json", + } diff --git a/litellm/llms/openai/responses/count_tokens/handler.py b/litellm/llms/openai/responses/count_tokens/handler.py index 721d07796ee..7fb5f6dad78 100644 --- a/litellm/llms/openai/responses/count_tokens/handler.py +++ b/litellm/llms/openai/responses/count_tokens/handler.py @@ -66,7 +66,9 @@ class OpenAICountTokensHandler(OpenAICountTokensConfig): llm_provider=litellm.LlmProviders.OPENAI ) - request_timeout = timeout if timeout is not None else litellm.request_timeout + request_timeout = ( + timeout if timeout is not None else litellm.request_timeout + ) response = await async_client.post( endpoint_url, diff --git a/litellm/llms/openai/responses/count_tokens/transformation.py b/litellm/llms/openai/responses/count_tokens/transformation.py index 3893775fc01..41d1a01ec66 100644 --- a/litellm/llms/openai/responses/count_tokens/transformation.py +++ b/litellm/llms/openai/responses/count_tokens/transformation.py @@ -52,9 +52,7 @@ class OpenAICountTokensConfig: "Authorization": f"Bearer {api_key}", } - def validate_request( - self, model: str, input: Union[str, List[Any]] - ) -> None: + def validate_request(self, model: str, input: Union[str, List[Any]]) -> None: if not model: raise ValueError("model parameter is required") @@ -139,20 +137,24 @@ class OpenAICountTokensConfig: if tool_calls: for tc in tool_calls: func = tc.get("function", {}) - input_items.append({ - "type": "function_call", - "call_id": tc.get("id", ""), - "name": func.get("name", ""), - "arguments": func.get("arguments", ""), - }) + input_items.append( + { + "type": "function_call", + "call_id": tc.get("id", ""), + "name": func.get("name", ""), + "arguments": func.get("arguments", ""), + } + ) elif not content: input_items.append({"role": "assistant", "content": content}) elif role == "tool": - input_items.append({ - "type": "function_call_output", - "call_id": msg.get("tool_call_id", ""), - "output": content if isinstance(content, str) else str(content), - }) + input_items.append( + { + "type": "function_call_output", + "call_id": msg.get("tool_call_id", ""), + "output": content if isinstance(content, str) else str(content), + } + ) instructions = "\n".join(instructions_parts) if instructions_parts else None return input_items, instructions diff --git a/litellm/llms/openai/responses/guardrail_translation/handler.py b/litellm/llms/openai/responses/guardrail_translation/handler.py index 7c3354cf88e..466e2e76f18 100644 --- a/litellm/llms/openai/responses/guardrail_translation/handler.py +++ b/litellm/llms/openai/responses/guardrail_translation/handler.py @@ -30,22 +30,27 @@ Output: response.output is List[GenericResponseOutputItem] where each has: from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, cast -from openai.types.responses.response_function_tool_call import \ - ResponseFunctionToolCall +from openai.types.responses.response_function_tool_call import ResponseFunctionToolCall from pydantic import BaseModel from litellm._logging import verbose_proxy_logger from litellm.completion_extras.litellm_responses_transformation.transformation import ( LiteLLMResponsesTransformationHandler, - OpenAiResponsesToChatCompletionStreamIterator) -from litellm.llms.base_llm.guardrail_translation.base_translation import \ - BaseTranslation -from litellm.responses.litellm_completion_transformation.transformation import \ - LiteLLMCompletionResponsesConfig -from litellm.types.llms.openai import (ChatCompletionToolCallChunk, - ChatCompletionToolParam) -from litellm.types.responses.main import (GenericResponseOutputItem, - OutputFunctionToolCall, OutputText) + OpenAiResponsesToChatCompletionStreamIterator, +) +from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation +from litellm.responses.litellm_completion_transformation.transformation import ( + LiteLLMCompletionResponsesConfig, +) +from litellm.types.llms.openai import ( + ChatCompletionToolCallChunk, + ChatCompletionToolParam, +) +from litellm.types.responses.main import ( + GenericResponseOutputItem, + OutputFunctionToolCall, + OutputText, +) from litellm.types.utils import GenericGuardrailAPIInputs if TYPE_CHECKING: diff --git a/litellm/llms/openai/responses/transformation.py b/litellm/llms/openai/responses/transformation.py index 28080103661..9d909fd4017 100644 --- a/litellm/llms/openai/responses/transformation.py +++ b/litellm/llms/openai/responses/transformation.py @@ -181,7 +181,7 @@ class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig): f"Error constructing ResponsesAPIResponse: {raw_response_json}, using model_construct" ) response = ResponsesAPIResponse.model_construct(**raw_response_json) - + # Store processed headers in additional_headers so they get returned to the client response._hidden_params["additional_headers"] = processed_headers response._hidden_params["headers"] = raw_response_headers @@ -411,7 +411,7 @@ class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig): ) -> ResponsesAPIResponse: """ Transform the get response API response into a ResponsesAPIResponse - """ + """ try: raw_response_json = raw_response.json() except Exception: @@ -423,7 +423,7 @@ class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig): response = ResponsesAPIResponse(**raw_response_json) response._hidden_params["additional_headers"] = processed_headers response._hidden_params["headers"] = raw_response_headers - + return response ######################################################### @@ -503,11 +503,11 @@ class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig): ) raw_response_headers = dict(raw_response.headers) processed_headers = process_response_headers(raw_response_headers) - + response = ResponsesAPIResponse(**raw_response_json) response._hidden_params["additional_headers"] = processed_headers response._hidden_params["headers"] = raw_response_headers - + return response ######################################################### @@ -532,14 +532,14 @@ class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig): parsed_url = httpx.URL(api_base) compact_path = parsed_url.path.rstrip("/") + "/compact" url = str(parsed_url.copy_with(path=compact_path)) - + input = self._validate_input_param(input) data = dict( ResponsesAPIRequestParams( model=model, input=input, **response_api_optional_request_params ) ) - + return url, data def transform_compact_response_api_response( @@ -565,7 +565,7 @@ class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig): ) raw_response_headers = dict(raw_response.headers) processed_headers = process_response_headers(raw_response_headers) - + try: response = ResponsesAPIResponse(**raw_response_json) except Exception: @@ -573,8 +573,8 @@ class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig): f"Error constructing ResponsesAPIResponse: {raw_response_json}, using model_construct" ) response = ResponsesAPIResponse.model_construct(**raw_response_json) - + response._hidden_params["additional_headers"] = processed_headers response._hidden_params["headers"] = raw_response_headers - + return response diff --git a/litellm/llms/openai/transcriptions/handler.py b/litellm/llms/openai/transcriptions/handler.py index 397b4c9956f..e079a170874 100644 --- a/litellm/llms/openai/transcriptions/handler.py +++ b/litellm/llms/openai/transcriptions/handler.py @@ -37,7 +37,6 @@ class OpenAIAudioTranscription(OpenAIChatCompletion): - call openai_aclient.audio.transcriptions.create by default """ try: - raw_response = ( await openai_aclient.audio.transcriptions.with_raw_response.create( **data, timeout=timeout diff --git a/litellm/llms/openai/transcriptions/whisper_transformation.py b/litellm/llms/openai/transcriptions/whisper_transformation.py index fa507e1bc26..1a7f47ae56e 100644 --- a/litellm/llms/openai/transcriptions/whisper_transformation.py +++ b/litellm/llms/openai/transcriptions/whisper_transformation.py @@ -110,9 +110,9 @@ class OpenAIWhisperAudioTranscriptionConfig(BaseAudioTranscriptionConfig): if "response_format" not in data or ( data["response_format"] == "text" or data["response_format"] == "json" ): - data["response_format"] = ( - "verbose_json" # ensures 'duration' is received - used for cost calculation - ) + data[ + "response_format" + ] = "verbose_json" # ensures 'duration' is received - used for cost calculation return AudioTranscriptionRequestData( data=data, diff --git a/litellm/llms/openai/vector_store_files/transformation.py b/litellm/llms/openai/vector_store_files/transformation.py index 8953e404f3e..cd5f10251bb 100644 --- a/litellm/llms/openai/vector_store_files/transformation.py +++ b/litellm/llms/openai/vector_store_files/transformation.py @@ -41,9 +41,9 @@ class OpenAIVectorStoreFilesConfig(BaseVectorStoreFilesConfig): } } - def get_vector_store_file_endpoints_by_type(self) -> Dict[ - str, Tuple[Tuple[str, str], ...] - ]: + def get_vector_store_file_endpoints_by_type( + self, + ) -> Dict[str, Tuple[Tuple[str, str], ...]]: return { "read": ( ("GET", "/vector_stores/{vector_store_id}/files"), diff --git a/litellm/llms/openai/videos/transformation.py b/litellm/llms/openai/videos/transformation.py index 5c880ab6658..e224097fb02 100644 --- a/litellm/llms/openai/videos/transformation.py +++ b/litellm/llms/openai/videos/transformation.py @@ -69,7 +69,7 @@ class OpenAIVideoConfig(BaseVideoConfig): # Use api_key from litellm_params if available, otherwise fall back to other sources if litellm_params and litellm_params.api_key: api_key = api_key or litellm_params.api_key - + api_key = ( api_key or litellm.api_key @@ -94,7 +94,7 @@ class OpenAIVideoConfig(BaseVideoConfig): """ if api_base is None: api_base = "https://api.openai.com/v1" - + return f"{api_base.rstrip('/')}/videos" def transform_video_create_request( @@ -111,15 +111,14 @@ class OpenAIVideoConfig(BaseVideoConfig): """ # Remove model and extra_headers from optional params as they're handled separately video_create_optional_request_params = { - k: v for k, v in video_create_optional_request_params.items() + k: v + for k, v in video_create_optional_request_params.items() if k not in ["model", "extra_headers", "prompt"] } - + # Create the request data video_create_request = CreateVideoRequest( - model=model, - prompt=prompt, - **video_create_optional_request_params + model=model, prompt=prompt, **video_create_optional_request_params ) request_dict = cast(Dict, video_create_request) @@ -149,21 +148,23 @@ class OpenAIVideoConfig(BaseVideoConfig): ) -> VideoObject: """Transform the OpenAI video creation response.""" response_data = raw_response.json() - + video_obj = VideoObject(**response_data) # type: ignore[arg-type] - + if custom_llm_provider and video_obj.id: - video_obj.id = encode_video_id_with_provider(video_obj.id, custom_llm_provider, model) - + video_obj.id = encode_video_id_with_provider( + video_obj.id, custom_llm_provider, model + ) + usage_data = {} if video_obj: - if hasattr(video_obj, 'seconds') and video_obj.seconds: + if hasattr(video_obj, "seconds") and video_obj.seconds: try: usage_data["duration_seconds"] = float(video_obj.seconds) except (ValueError, TypeError): pass video_obj.usage = usage_data - + return video_obj def transform_video_content_request( @@ -204,24 +205,24 @@ class OpenAIVideoConfig(BaseVideoConfig): ) -> Tuple[str, Dict]: """ Transform the video remix request for OpenAI API. - + OpenAI API expects the following request: - POST /v1/videos/{video_id}/remix """ original_video_id = extract_original_video_id(video_id) - + # Construct the URL for video remix url = f"{api_base.rstrip('/')}/{original_video_id}/remix" - + # Prepare the request data data = {"prompt": prompt} - + # Add any extra body parameters if extra_body: data.update(extra_body) - + return url, data - + def transform_video_content_response( self, raw_response: httpx.Response, @@ -240,18 +241,20 @@ class OpenAIVideoConfig(BaseVideoConfig): Transform the OpenAI video remix response. """ response_data = raw_response.json() - + # Transform the response data video_obj = VideoObject(**response_data) # type: ignore[arg-type] - + if custom_llm_provider and video_obj.id: - video_obj.id = encode_video_id_with_provider(video_obj.id, custom_llm_provider, None) - + video_obj.id = encode_video_id_with_provider( + video_obj.id, custom_llm_provider, None + ) + # Create usage object with duration information for cost calculation # Video remix API doesn't provide usage, so we create one with duration usage_data = {} if video_obj: - if hasattr(video_obj, 'seconds') and video_obj.seconds: + if hasattr(video_obj, "seconds") and video_obj.seconds: try: usage_data["duration_seconds"] = float(video_obj.seconds) except (ValueError, TypeError): @@ -346,18 +349,18 @@ class OpenAIVideoConfig(BaseVideoConfig): ) -> Tuple[str, Dict]: """ Transform the video delete request for OpenAI API. - + OpenAI API expects the following request: - DELETE /v1/videos/{video_id} """ original_video_id = extract_original_video_id(video_id) - + # Construct the URL for video delete url = f"{api_base.rstrip('/')}/{original_video_id}" - + # No data needed for DELETE request data: Dict[str, Any] = {} - + return url, data def transform_video_delete_response( @@ -369,7 +372,7 @@ class OpenAIVideoConfig(BaseVideoConfig): Transform the OpenAI video delete response. """ response_data = raw_response.json() - + # Transform the response data video_obj = VideoObject(**response_data) # type: ignore[arg-type] # type: ignore[arg-type] @@ -387,13 +390,13 @@ class OpenAIVideoConfig(BaseVideoConfig): """ # Extract the original video_id (remove provider encoding if present) original_video_id = extract_original_video_id(video_id) - + # For video retrieve, we just need to construct the URL url = f"{api_base.rstrip('/')}/{original_video_id}" - + # No additional data needed for GET request data: Dict[str, Any] = {} - + return url, data def transform_video_status_retrieve_response( @@ -408,9 +411,11 @@ class OpenAIVideoConfig(BaseVideoConfig): response_data = raw_response.json() # Transform the response data video_obj = VideoObject(**response_data) # type: ignore[arg-type] - + if custom_llm_provider and video_obj.id: - video_obj.id = encode_video_id_with_provider(video_obj.id, custom_llm_provider, None) + video_obj.id = encode_video_id_with_provider( + video_obj.id, custom_llm_provider, None + ) return video_obj @@ -437,4 +442,6 @@ class OpenAIVideoConfig(BaseVideoConfig): if isinstance(image, BufferedReader): files_list.append((field_name, (image.name, image, image_content_type))) else: - files_list.append((field_name, ("input_reference.png", image, image_content_type))) + files_list.append( + (field_name, ("input_reference.png", image, image_content_type)) + ) diff --git a/litellm/llms/openai_like/dynamic_config.py b/litellm/llms/openai_like/dynamic_config.py index 8be749f34a3..3d66556e522 100644 --- a/litellm/llms/openai_like/dynamic_config.py +++ b/litellm/llms/openai_like/dynamic_config.py @@ -44,11 +44,11 @@ def create_config_class(provider: SimpleProviderConfig): self, messages: List[AllMessageValues], model: str, is_async: bool = False ) -> Union[List[AllMessageValues], Coroutine[Any, Any, List[AllMessageValues]]]: """Transform messages based on special_handling config""" - + # Handle content list to string conversion if configured if provider.special_handling.get("convert_content_list_to_string"): messages = handle_messages_with_content_list_to_str_conversion(messages) - + if is_async: return super()._transform_messages( messages=messages, model=model, is_async=True @@ -108,7 +108,13 @@ def create_config_class(provider: SimpleProviderConfig): ) if not _supports_fc: - tool_params = ["tools", "tool_choice", "function_call", "functions", "parallel_tool_calls"] + tool_params = [ + "tools", + "tool_choice", + "function_call", + "functions", + "parallel_tool_calls", + ] for param in tool_params: if param in supported_params: supported_params.remove(param) @@ -129,7 +135,7 @@ def create_config_class(provider: SimpleProviderConfig): """Apply parameter mappings and constraints""" supported_params = self.get_supported_openai_params(model) - + # Apply supported params for param, value in non_default_params.items(): # Check parameter mappings first @@ -197,10 +203,7 @@ def create_responses_config_class(provider: SimpleProviderConfig): litellm_params: Optional[GenericLiteLLMParams], ) -> dict: litellm_params = litellm_params or GenericLiteLLMParams() - api_key = ( - litellm_params.api_key - or get_secret_str(provider.api_key_env) - ) + api_key = litellm_params.api_key or get_secret_str(provider.api_key_env) if api_key: headers["Authorization"] = f"Bearer {api_key}" return headers @@ -217,9 +220,7 @@ def create_responses_config_class(provider: SimpleProviderConfig): api_base = provider.base_url if api_base is None: - raise ValueError( - f"api_base is required for provider {provider.slug}" - ) + raise ValueError(f"api_base is required for provider {provider.slug}") api_base = api_base.rstrip("/") return f"{api_base}/responses" diff --git a/litellm/llms/openai_like/embedding/handler.py b/litellm/llms/openai_like/embedding/handler.py index d0d26d5959f..e3884fa56d7 100644 --- a/litellm/llms/openai_like/embedding/handler.py +++ b/litellm/llms/openai_like/embedding/handler.py @@ -105,7 +105,9 @@ class OpenAILikeEmbeddingHandler(OpenAILikeBase): custom_endpoint=custom_endpoint, ) model = model - filtered_optional_params = {k: v for k, v in optional_params.items() if v not in (None, '')} + filtered_optional_params = { + k: v for k, v in optional_params.items() if v not in (None, "") + } data = {"model": model, "input": input, **filtered_optional_params} ## LOGGING diff --git a/litellm/llms/openai_like/json_loader.py b/litellm/llms/openai_like/json_loader.py index 8b55fe4b618..c6ff0f7a394 100644 --- a/litellm/llms/openai_like/json_loader.py +++ b/litellm/llms/openai_like/json_loader.py @@ -37,7 +37,7 @@ class JSONProviderRegistry: return json_path = Path(__file__).parent / "providers.json" - + if not json_path.exists(): # No JSON file yet, that's okay cls._loaded = True @@ -52,7 +52,9 @@ class JSONProviderRegistry: cls._loaded = True except Exception as e: - verbose_logger.warning(f"Warning: Failed to load JSON provider configs: {e}") + verbose_logger.warning( + f"Warning: Failed to load JSON provider configs: {e}" + ) cls._loaded = True @classmethod diff --git a/litellm/llms/openrouter/chat/transformation.py b/litellm/llms/openrouter/chat/transformation.py index e3770dbbf49..86e63fd0c41 100644 --- a/litellm/llms/openrouter/chat/transformation.py +++ b/litellm/llms/openrouter/chat/transformation.py @@ -24,6 +24,7 @@ from ..common_utils import OpenRouterException class CacheControlSupportedModels(str, Enum): """Models that support cache_control in content blocks.""" + CLAUDE = "claude" GEMINI = "gemini" MINIMAX = "minimax" @@ -69,15 +70,15 @@ class OpenrouterConfig(OpenAIGPTConfig): extra_body["models"] = models if route is not None: extra_body["route"] = route - mapped_openai_params["extra_body"] = ( - extra_body # openai client supports `extra_body` param - ) + mapped_openai_params[ + "extra_body" + ] = extra_body # openai client supports `extra_body` param return mapped_openai_params def _supports_cache_control_in_content(self, model: str) -> bool: """ Check if the model supports cache_control in content blocks. - + Returns: bool: True if model supports cache_control (Claude or Gemini models) """ @@ -106,7 +107,7 @@ class OpenrouterConfig(OpenAIGPTConfig): """ Move cache_control from message level to content blocks. OpenRouter requires cache_control to be inside content blocks, not at message level. - + To avoid exceeding Anthropic's limit of 4 cache breakpoints, cache_control is only added to the LAST content block in each message. """ @@ -114,10 +115,10 @@ class OpenrouterConfig(OpenAIGPTConfig): for message in messages: message_dict = dict(message) cache_control = message_dict.pop("cache_control", None) - + if cache_control is not None: content = message_dict.get("content") - + if isinstance(content, list): # Content is already a list, add cache_control only to the last block if len(content) > 0: @@ -138,10 +139,10 @@ class OpenrouterConfig(OpenAIGPTConfig): "cache_control": cache_control, } ] - + # Cast back to AllMessageValues after modification transformed_messages.append(cast(AllMessageValues, message_dict)) - + return transformed_messages def transform_request( @@ -160,7 +161,7 @@ class OpenrouterConfig(OpenAIGPTConfig): """ if self._supports_cache_control_in_content(model): messages = self._move_cache_control_to_content(messages) - + extra_body = optional_params.pop("extra_body", {}) response = super().transform_request( model, messages, optional_params, litellm_params, headers @@ -223,7 +224,9 @@ class OpenrouterConfig(OpenAIGPTConfig): model_response._hidden_params = {} if "additional_headers" not in model_response._hidden_params: model_response._hidden_params["additional_headers"] = {} - model_response._hidden_params["additional_headers"]["llm_provider-x-litellm-response-cost"] = float(response_cost) + model_response._hidden_params["additional_headers"][ + "llm_provider-x-litellm-response-cost" + ] = float(response_cost) except Exception: # If we can't extract cost, continue without it - don't fail the response pass diff --git a/litellm/llms/openrouter/image_edit/transformation.py b/litellm/llms/openrouter/image_edit/transformation.py index 7a4cef1798d..9e5e313aad0 100644 --- a/litellm/llms/openrouter/image_edit/transformation.py +++ b/litellm/llms/openrouter/image_edit/transformation.py @@ -55,7 +55,13 @@ from litellm.llms.openrouter.common_utils import OpenRouterException from litellm.secret_managers.main import get_secret_str from litellm.types.images.main import ImageEditOptionalRequestParams from litellm.types.router import GenericLiteLLMParams -from litellm.types.utils import FileTypes, ImageObject, ImageResponse, ImageUsage, ImageUsageInputTokensDetails +from litellm.types.utils import ( + FileTypes, + ImageObject, + ImageResponse, + ImageUsage, + ImageUsageInputTokensDetails, +) if TYPE_CHECKING: from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj @@ -91,7 +97,9 @@ class OpenRouterImageEditConfig(BaseImageEditConfig): if key == "size": if "image_config" not in mapped_params: mapped_params["image_config"] = {} - mapped_params["image_config"]["aspect_ratio"] = self._map_size_to_aspect_ratio(cast(str, value)) + mapped_params["image_config"][ + "aspect_ratio" + ] = self._map_size_to_aspect_ratio(cast(str, value)) elif key == "quality": image_size = self._map_quality_to_image_size(cast(str, value)) if image_size: @@ -109,11 +117,7 @@ class OpenRouterImageEditConfig(BaseImageEditConfig): model: str, api_key: Optional[str] = None, ) -> dict: - api_key = ( - api_key - or litellm.api_key - or get_secret_str("OPENROUTER_API_KEY") - ) + api_key = api_key or litellm.api_key or get_secret_str("OPENROUTER_API_KEY") if not api_key: raise ValueError("OPENROUTER_API_KEY is not set") headers.update( @@ -133,7 +137,11 @@ class OpenRouterImageEditConfig(BaseImageEditConfig): api_base: Optional[str], litellm_params: dict, ) -> str: - base_url = api_base or get_secret_str("OPENROUTER_API_BASE") or "https://openrouter.ai/api/v1" + base_url = ( + api_base + or get_secret_str("OPENROUTER_API_BASE") + or "https://openrouter.ai/api/v1" + ) base_url = base_url.rstrip("/") if not base_url.endswith("/chat/completions"): return f"{base_url}/chat/completions" @@ -162,9 +170,7 @@ class OpenRouterImageEditConfig(BaseImageEditConfig): content_parts.append( { "type": "image_url", - "image_url": { - "url": f"data:{mime_type};base64,{b64_data}" - }, + "image_url": {"url": f"data:{mime_type};base64,{b64_data}"}, } ) @@ -344,7 +350,9 @@ class OpenRouterImageEditConfig(BaseImageEditConfig): if cost_details: if "response_cost_details" not in model_response._hidden_params: model_response._hidden_params["response_cost_details"] = {} - model_response._hidden_params["response_cost_details"].update(cost_details) + model_response._hidden_params["response_cost_details"].update( + cost_details + ) model_response._hidden_params["model"] = response_json.get("model", model) diff --git a/litellm/llms/openrouter/image_generation/__init__.py b/litellm/llms/openrouter/image_generation/__init__.py index f2d06439d40..af5dc036e46 100644 --- a/litellm/llms/openrouter/image_generation/__init__.py +++ b/litellm/llms/openrouter/image_generation/__init__.py @@ -10,4 +10,4 @@ __all__ = [ def get_openrouter_image_generation_config(model: str) -> BaseImageGenerationConfig: - return OpenRouterImageGenerationConfig() \ No newline at end of file + return OpenRouterImageGenerationConfig() diff --git a/litellm/llms/openrouter/image_generation/transformation.py b/litellm/llms/openrouter/image_generation/transformation.py index 92084b533af..a55716a5e50 100644 --- a/litellm/llms/openrouter/image_generation/transformation.py +++ b/litellm/llms/openrouter/image_generation/transformation.py @@ -37,8 +37,16 @@ from litellm.llms.base_llm.image_generation.transformation import ( BaseImageGenerationConfig, ) from litellm.secret_managers.main import get_secret_str -from litellm.types.llms.openai import OpenAIImageGenerationOptionalParams, AllMessageValues -from litellm.types.utils import ImageObject, ImageResponse, ImageUsage, ImageUsageInputTokensDetails +from litellm.types.llms.openai import ( + OpenAIImageGenerationOptionalParams, + AllMessageValues, +) +from litellm.types.utils import ( + ImageObject, + ImageResponse, + ImageUsage, + ImageUsageInputTokensDetails, +) from litellm.llms.openrouter.common_utils import OpenRouterException @@ -51,7 +59,7 @@ else: class OpenRouterImageGenerationConfig(BaseImageGenerationConfig): """ Configuration for OpenRouter image generation via chat completions. - + OpenRouter uses chat completion endpoints for image generation, so we need to transform image generation requests to chat format and extract images from chat responses. @@ -62,7 +70,7 @@ class OpenRouterImageGenerationConfig(BaseImageGenerationConfig): ) -> List[OpenAIImageGenerationOptionalParams]: """ Get supported OpenAI parameters for OpenRouter image generation. - + Since OpenRouter uses chat completions for image generation, we support standard image generation params. """ @@ -81,13 +89,13 @@ class OpenRouterImageGenerationConfig(BaseImageGenerationConfig): ) -> dict: """ Map image generation params to OpenRouter chat completion format. - + Maps OpenAI parameters to OpenRouter's image_config format: - size -> image_config.aspect_ratio - quality -> image_config.image_size """ supported_params = self.get_supported_openai_params(model) - + for key, value in non_default_params.items(): if key in supported_params: if key == "size": @@ -109,13 +117,13 @@ class OpenRouterImageGenerationConfig(BaseImageGenerationConfig): elif not drop_params: # If not supported and drop_params is False, pass through optional_params[key] = value - + return optional_params - + def _map_size_to_aspect_ratio(self, size: str) -> str: """ Map OpenAI size format to OpenRouter aspect_ratio format. - + OpenAI sizes: - 1024x1024 (square) - 1536x1024 (landscape) @@ -124,7 +132,7 @@ class OpenRouterImageGenerationConfig(BaseImageGenerationConfig): - 1024x1792 (tall portrait, dall-e-3) - 256x256, 512x512 (dall-e-2) - auto (default) - + OpenRouter aspect_ratios: - 1:1 → 1024×1024 (default) - 2:3 → 832×1248 @@ -152,16 +160,16 @@ class OpenRouterImageGenerationConfig(BaseImageGenerationConfig): "auto": "1:1", } return size_to_aspect_ratio.get(size, "1:1") - + def _map_quality_to_image_size(self, quality: str) -> Optional[str]: """ Map OpenAI quality to OpenRouter image_size format. - + OpenAI quality values: - auto (default) - automatically select best quality - high, medium, low - for GPT image models - hd, standard - for dall-e-3 - + OpenRouter image_size values (Gemini only): - 1K → Standard resolution (default) - 2K → Higher resolution @@ -178,7 +186,7 @@ class OpenRouterImageGenerationConfig(BaseImageGenerationConfig): "auto": "1K", } return quality_to_image_size.get(quality) - + def _set_usage_and_cost( self, model_response: ImageResponse, @@ -187,7 +195,7 @@ class OpenRouterImageGenerationConfig(BaseImageGenerationConfig): ) -> None: """ Extract and set usage and cost information from OpenRouter response. - + Args: model_response: ImageResponse object to populate response_json: Parsed JSON response from OpenRouter @@ -197,10 +205,10 @@ class OpenRouterImageGenerationConfig(BaseImageGenerationConfig): if usage_data: prompt_tokens = usage_data.get("prompt_tokens", 0) total_tokens = usage_data.get("total_tokens", 0) - + completion_tokens_details = usage_data.get("completion_tokens_details", {}) image_tokens = completion_tokens_details.get("image_tokens", 0) - + model_response.usage = ImageUsage( input_tokens=prompt_tokens, input_tokens_details=ImageUsageInputTokensDetails( @@ -210,7 +218,7 @@ class OpenRouterImageGenerationConfig(BaseImageGenerationConfig): output_tokens=image_tokens, total_tokens=total_tokens, ) - + cost = usage_data.get("cost") if cost is not None: if not hasattr(model_response, "_hidden_params"): @@ -220,13 +228,15 @@ class OpenRouterImageGenerationConfig(BaseImageGenerationConfig): model_response._hidden_params["additional_headers"][ "llm_provider-x-litellm-response-cost" ] = float(cost) - + cost_details = usage_data.get("cost_details", {}) if cost_details: if "response_cost_details" not in model_response._hidden_params: model_response._hidden_params["response_cost_details"] = {} - model_response._hidden_params["response_cost_details"].update(cost_details) - + model_response._hidden_params["response_cost_details"].update( + cost_details + ) + model_response._hidden_params["model"] = response_json.get("model", model) def get_complete_url( @@ -240,7 +250,7 @@ class OpenRouterImageGenerationConfig(BaseImageGenerationConfig): ) -> str: """ Get the complete URL for OpenRouter image generation. - + OpenRouter uses chat completions endpoint for image generation. Default: https://openrouter.ai/api/v1/chat/completions """ @@ -249,7 +259,7 @@ class OpenRouterImageGenerationConfig(BaseImageGenerationConfig): api_base = api_base.rstrip("/") return f"{api_base}/chat/completions" return api_base - + return "https://openrouter.ai/api/v1/chat/completions" def validate_environment( @@ -262,11 +272,7 @@ class OpenRouterImageGenerationConfig(BaseImageGenerationConfig): api_key: Optional[str] = None, api_base: Optional[str] = None, ) -> dict: - api_key = ( - api_key - or litellm.api_key - or get_secret_str("OPENROUTER_API_KEY") - ) + api_key = api_key or litellm.api_key or get_secret_str("OPENROUTER_API_KEY") headers.update( { "Authorization": f"Bearer {api_key}", @@ -284,32 +290,27 @@ class OpenRouterImageGenerationConfig(BaseImageGenerationConfig): ) -> dict: """ Transform image generation request to OpenRouter chat completion format. - + Args: model: The model name prompt: The image generation prompt optional_params: Optional parameters (including image_config) litellm_params: LiteLLM parameters headers: Request headers - + Returns: dict: Request body in chat completion format with image_config """ request_body = { "model": model, - "messages": [ - { - "role": "user", - "content": prompt - } - ] + "messages": [{"role": "user", "content": prompt}], } - + # These will be passed through to OpenRouter for key, value in optional_params.items(): if key not in ["model", "messages", "modalities"]: request_body[key] = value - + return request_body def transform_image_generation_response( @@ -327,9 +328,9 @@ class OpenRouterImageGenerationConfig(BaseImageGenerationConfig): ) -> ImageResponse: """ Transform OpenRouter chat completion response to ImageResponse format. - + Extracts images from the message content and maps usage/cost information. - + Args: model: The model name raw_response: Raw HTTP response from OpenRouter @@ -341,7 +342,7 @@ class OpenRouterImageGenerationConfig(BaseImageGenerationConfig): encoding: Encoding api_key: API key json_mode: JSON mode flag - + Returns: ImageResponse: Populated image response """ @@ -353,28 +354,28 @@ class OpenRouterImageGenerationConfig(BaseImageGenerationConfig): status_code=raw_response.status_code, headers=raw_response.headers, ) - + if not model_response.data: model_response.data = [] - + try: choices = response_json.get("choices", []) - + for choice in choices: message = choice.get("message", {}) images = message.get("images", []) - + for image_data in images: image_url_obj = image_data.get("image_url", {}) image_url = image_url_obj.get("url") - + if image_url: if image_url.startswith("data:"): # Extract base64 data # Format: data:image/png;base64, parts = image_url.split(",", 1) b64_data = parts[1] if len(parts) > 1 else None - + model_response.data.append( ImageObject( b64_json=b64_data, @@ -390,12 +391,12 @@ class OpenRouterImageGenerationConfig(BaseImageGenerationConfig): revised_prompt=None, ) ) - + # Extract and set usage and cost information self._set_usage_and_cost(model_response, response_json, model) - + return model_response - + except Exception as e: raise OpenRouterException( message=f"Error transforming OpenRouter image generation response: {str(e)}", diff --git a/litellm/llms/ovhcloud/audio_transcription/transformation.py b/litellm/llms/ovhcloud/audio_transcription/transformation.py index 7233d911b07..7ff6dc986be 100644 --- a/litellm/llms/ovhcloud/audio_transcription/transformation.py +++ b/litellm/llms/ovhcloud/audio_transcription/transformation.py @@ -31,7 +31,13 @@ class OVHCloudAudioTranscriptionConfig(BaseAudioTranscriptionConfig): ) -> List[OpenAIAudioTranscriptionOptionalParams]: # OVHCloud implements the OpenAI-compatible Whisper interface. # We pass through the same optional params as the OpenAI Whisper API. - return ["language", "prompt", "response_format", "timestamp_granularities", "temperature"] + return [ + "language", + "prompt", + "response_format", + "timestamp_granularities", + "temperature", + ] def map_openai_params( self, @@ -152,5 +158,3 @@ class OVHCloudAudioTranscriptionConfig(BaseAudioTranscriptionConfig): response._hidden_params = response_json return response - - diff --git a/litellm/llms/ovhcloud/chat/transformation.py b/litellm/llms/ovhcloud/chat/transformation.py index e9dc5be3eed..e2a9fea7897 100644 --- a/litellm/llms/ovhcloud/chat/transformation.py +++ b/litellm/llms/ovhcloud/chat/transformation.py @@ -15,6 +15,7 @@ from litellm.llms.base_llm.base_model_iterator import BaseModelResponseIterator from litellm.llms.base_llm.chat.transformation import BaseLLMException from litellm.types.llms.openai import AllMessageValues + class OVHCloudChatConfig(OpenAIGPTConfig): @property def custom_llm_provider(self) -> Optional[str]: @@ -45,7 +46,7 @@ class OVHCloudChatConfig(OpenAIGPTConfig): optional_params.remove("function_call") optional_params.remove("response_format") return optional_params - + def get_complete_url( self, api_base: Optional[str], @@ -55,15 +56,16 @@ class OVHCloudChatConfig(OpenAIGPTConfig): litellm_params: dict, stream: Optional[bool] = None, ) -> str: - api_base = "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1" if api_base is None else api_base.rstrip("/") + api_base = ( + "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1" + if api_base is None + else api_base.rstrip("/") + ) complete_url = f"{api_base}/chat/completions" return complete_url - + def get_error_class( - self, - error_message: str, - status_code: int, - headers: Union[dict, httpx.Headers] + self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ) -> BaseLLMException: return OVHCloudException( message=error_message, @@ -82,7 +84,7 @@ class OVHCloudChatConfig(OpenAIGPTConfig): non_default_params, optional_params, model, drop_params ) return mapped_openai_params - + def transform_request( self, model: str, @@ -98,6 +100,7 @@ class OVHCloudChatConfig(OpenAIGPTConfig): response.update(extra_body) return response + class OVHCloudChatCompletionStreamingHandler(BaseModelResponseIterator): """ Handler for OVHCloud AI Endpoints streaming chat completion responses @@ -122,7 +125,9 @@ class OVHCloudChatCompletionStreamingHandler(BaseModelResponseIterator): new_choices = [] for choice in chunk["choices"]: if "delta" in choice and "reasoning" in choice["delta"]: - choice["delta"]["reasoning_content"] = choice["delta"].get("reasoning") + choice["delta"]["reasoning_content"] = choice["delta"].get( + "reasoning" + ) new_choices.append(choice) return ModelResponseStream( @@ -140,4 +145,4 @@ class OVHCloudChatCompletionStreamingHandler(BaseModelResponseIterator): headers={"Content-Type": "application/json"}, ) except Exception as e: - raise e \ No newline at end of file + raise e diff --git a/litellm/llms/ovhcloud/embedding/transformation.py b/litellm/llms/ovhcloud/embedding/transformation.py index 1266f74c0a2..38e88da125f 100644 --- a/litellm/llms/ovhcloud/embedding/transformation.py +++ b/litellm/llms/ovhcloud/embedding/transformation.py @@ -29,7 +29,11 @@ class OVHCloudEmbeddingConfig(BaseEmbeddingConfig): litellm_params: dict, stream: Optional[bool] = None, ) -> str: - api_base = "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1" if api_base is None else api_base.rstrip("/") + api_base = ( + "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1" + if api_base is None + else api_base.rstrip("/") + ) complete_url = f"{api_base}/embeddings" return complete_url diff --git a/litellm/llms/ovhcloud/utils.py b/litellm/llms/ovhcloud/utils.py index 9ae4dfb1efd..046df4bca1b 100644 --- a/litellm/llms/ovhcloud/utils.py +++ b/litellm/llms/ovhcloud/utils.py @@ -3,4 +3,5 @@ from litellm.llms.base_llm.chat.transformation import BaseLLMException class OVHCloudException(BaseLLMException): """OVHCloud AI Endpoints exception handling class""" - pass \ No newline at end of file + + pass diff --git a/litellm/llms/parallel_ai/search/__init__.py b/litellm/llms/parallel_ai/search/__init__.py index cc2ff91ea33..b96914f13dd 100644 --- a/litellm/llms/parallel_ai/search/__init__.py +++ b/litellm/llms/parallel_ai/search/__init__.py @@ -4,4 +4,3 @@ Parallel AI Search API module. from litellm.llms.parallel_ai.search.transformation import ParallelAISearchConfig __all__ = ["ParallelAISearchConfig"] - diff --git a/litellm/llms/parallel_ai/search/transformation.py b/litellm/llms/parallel_ai/search/transformation.py index 95919b85c2f..e19bc5400d1 100644 --- a/litellm/llms/parallel_ai/search/transformation.py +++ b/litellm/llms/parallel_ai/search/transformation.py @@ -18,12 +18,14 @@ from litellm.secret_managers.main import get_secret_str class _ParallelAISourcePolicy(TypedDict, total=False): """Source policy for Parallel AI search results.""" + allowed_domains: List[str] # Optional - list of allowed domains disallowed_domains: List[str] # Optional - list of disallowed domains class _ParallelAISearchRequestRequired(TypedDict): """Required fields for Parallel AI Search API request.""" + # Note: At least one of objective or search_queries must be provided pass @@ -33,6 +35,7 @@ class ParallelAISearchRequest(_ParallelAISearchRequestRequired, total=False): Parallel AI Search API request format. Based on: https://docs.parallel.ai/api-reference/search-and-extract-api-beta/search """ + objective: str # Optional - natural-language description of search goal search_queries: List[str] # Optional - list of keyword search queries processor: str # Optional - search processor ('base', 'pro'), default 'base' @@ -44,11 +47,11 @@ class ParallelAISearchRequest(_ParallelAISearchRequestRequired, total=False): class ParallelAISearchConfig(BaseSearchConfig): PARALLEL_AI_API_BASE = "https://api.parallel.ai" PARALLEL_HEADER_SEARCH_EXTRACT_VALUE = "search-extract-2025-10-10" - + @staticmethod def ui_friendly_name() -> str: return "Parallel AI" - + def validate_environment( self, headers: Dict, @@ -59,9 +62,15 @@ class ParallelAISearchConfig(BaseSearchConfig): """ Validate environment and return headers. """ - api_key = api_key or get_secret_str("PARALLEL_AI_API_KEY") or get_secret_str("PARALLEL_API_KEY") + api_key = ( + api_key + or get_secret_str("PARALLEL_AI_API_KEY") + or get_secret_str("PARALLEL_API_KEY") + ) if not api_key: - raise ValueError("PARALLEL_API_KEY is not set. Set `PARALLEL_API_KEY` environment variable.") + raise ValueError( + "PARALLEL_API_KEY is not set. Set `PARALLEL_API_KEY` environment variable." + ) headers["x-api-key"] = api_key headers["Content-Type"] = "application/json" headers["parallel-beta"] = self.PARALLEL_HEADER_SEARCH_EXTRACT_VALUE @@ -77,8 +86,12 @@ class ParallelAISearchConfig(BaseSearchConfig): """ Get complete URL for Search endpoint. """ - api_base = api_base or get_secret_str("PARALLEL_AI_API_BASE") or self.PARALLEL_AI_API_BASE - + api_base = ( + api_base + or get_secret_str("PARALLEL_AI_API_BASE") + or self.PARALLEL_AI_API_BASE + ) + # Parallel AI search endpoint is at /v1beta/search if not api_base.endswith("/v1beta/search"): if api_base.endswith("/"): @@ -87,7 +100,7 @@ class ParallelAISearchConfig(BaseSearchConfig): api_base = f"{api_base}/v1beta/search" return api_base - + def _transform_query_to_objective(self, query: Union[str, List[str]]) -> str: """ Transform query to objective. @@ -95,7 +108,6 @@ class ParallelAISearchConfig(BaseSearchConfig): if isinstance(query, list): return " ".join(query) return query - def transform_search_request( self, @@ -105,7 +117,7 @@ class ParallelAISearchConfig(BaseSearchConfig): ) -> Dict: """ Transform Search request to Parallel AI API format. - + Args: query: Search query (string or list of strings) - If string: maps to `objective` (natural language) @@ -116,42 +128,45 @@ class ParallelAISearchConfig(BaseSearchConfig): - exclude_domains: List of domains to exclude -> maps to `source_policy.disallowed_domains` - processor: Search processor ('base', 'pro') - max_chars_per_result: Max characters per result excerpt - + Returns: Dict with typed request data following ParallelAISearchRequest spec """ request_data: ParallelAISearchRequest = {} - + # Map query to objective (string or list both become objective) if isinstance(query, list): request_data["objective"] = self._transform_query_to_objective(query) else: request_data["objective"] = query - + # Transform Perplexity unified spec parameters to Parallel AI format if "max_results" in optional_params: request_data["max_results"] = optional_params["max_results"] - + # Map domain filters to source_policy source_policy: _ParallelAISourcePolicy = {} - + if "search_domain_filter" in optional_params: source_policy["allowed_domains"] = optional_params["search_domain_filter"] - + if "exclude_domains" in optional_params: source_policy["disallowed_domains"] = optional_params["exclude_domains"] - + if source_policy: request_data["source_policy"] = source_policy - + # Convert to dict before dynamic key assignments result_data = dict(request_data) - + # pass through all other parameters as-is for param, value in optional_params.items(): - if param not in self.get_supported_perplexity_optional_params() and param not in result_data: + if ( + param not in self.get_supported_perplexity_optional_params() + and param not in result_data + ): result_data[param] = value - + return result_data def transform_search_response( @@ -162,29 +177,29 @@ class ParallelAISearchConfig(BaseSearchConfig): ) -> SearchResponse: """ Transform Parallel AI API response to LiteLLM unified SearchResponse format. - + Parallel AI → LiteLLM mappings: - results[].title → SearchResult.title - results[].url → SearchResult.url - results[].excerpts (array) → SearchResult.snippet (joined string) - No date/last_updated fields in Parallel AI response (set to None) - + Args: raw_response: Raw httpx response from Parallel AI API logging_obj: Logging object for tracking - + Returns: SearchResponse with standardized format """ response_json = raw_response.json() - + # Transform results to SearchResult objects results = [] for result in response_json.get("results", []): # Join excerpts array into a single snippet string excerpts = result.get("excerpts", []) snippet = " ... ".join(excerpts) if excerpts else "" - + search_result = SearchResult( title=result.get("title", ""), url=result.get("url", ""), @@ -193,9 +208,8 @@ class ParallelAISearchConfig(BaseSearchConfig): last_updated=None, # Parallel AI doesn't provide last_updated in response ) results.append(search_result) - + return SearchResponse( results=results, object="search", ) - diff --git a/litellm/llms/perplexity/chat/transformation.py b/litellm/llms/perplexity/chat/transformation.py index 27e6415ff8b..48299529ff4 100644 --- a/litellm/llms/perplexity/chat/transformation.py +++ b/litellm/llms/perplexity/chat/transformation.py @@ -61,7 +61,7 @@ class PerplexityChatConfig(OpenAIGPTConfig): base_openai_params.append("reasoning_effort") except Exception as e: verbose_logger.debug(f"Error checking if model supports reasoning: {e}") - + try: if litellm.supports_web_search( model=model, custom_llm_provider=self.custom_llm_provider @@ -69,7 +69,7 @@ class PerplexityChatConfig(OpenAIGPTConfig): base_openai_params.append("web_search_options") except Exception as e: verbose_logger.debug(f"Error checking if model supports web search: {e}") - + return base_openai_params def transform_response( @@ -109,7 +109,9 @@ class PerplexityChatConfig(OpenAIGPTConfig): ) self._add_citations_as_annotations(model_response, raw_response_json) except Exception as e: - verbose_logger.debug(f"Error extracting Perplexity-specific usage fields: {e}") + verbose_logger.debug( + f"Error extracting Perplexity-specific usage fields: {e}" + ) return model_response @@ -123,9 +125,7 @@ class PerplexityChatConfig(OpenAIGPTConfig): if not hasattr(model_response, "usage") or model_response.usage is None: # Create a usage object if it doesn't exist (when usage was None) model_response.usage = Usage( # type: ignore[attr-defined] - prompt_tokens=0, - completion_tokens=0, - total_tokens=0 + prompt_tokens=0, completion_tokens=0, total_tokens=0 ) usage = model_response.usage # type: ignore[attr-defined] @@ -146,7 +146,7 @@ class PerplexityChatConfig(OpenAIGPTConfig): # Extract search queries count from usage or response metadata # Perplexity might include this in the usage object or as separate metadata perplexity_usage = raw_response_json.get("usage", {}) - + # Try to extract search queries from usage field first, then root level num_search_queries = perplexity_usage.get("num_search_queries") if num_search_queries is None: @@ -155,18 +155,18 @@ class PerplexityChatConfig(OpenAIGPTConfig): num_search_queries = perplexity_usage.get("search_queries") if num_search_queries is None: num_search_queries = raw_response_json.get("search_queries") - + # Create or update prompt_tokens_details to include web search requests and citation tokens if citation_tokens > 0 or ( num_search_queries is not None and num_search_queries > 0 ): if usage.prompt_tokens_details is None: usage.prompt_tokens_details = PromptTokensDetailsWrapper() - + # Store citation tokens count for cost calculation if citation_tokens > 0: setattr(usage, "citation_tokens", citation_tokens) - + # Store search queries count in the standard web_search_requests field if num_search_queries is not None and num_search_queries > 0: usage.prompt_tokens_details.web_search_requests = num_search_queries @@ -248,4 +248,4 @@ class PerplexityChatConfig(OpenAIGPTConfig): if citations: setattr(model_response, "citations", citations) if search_results: - setattr(model_response, "search_results", search_results) \ No newline at end of file + setattr(model_response, "search_results", search_results) diff --git a/litellm/llms/perplexity/cost_calculator.py b/litellm/llms/perplexity/cost_calculator.py index 463d897901b..0f9c3cad841 100644 --- a/litellm/llms/perplexity/cost_calculator.py +++ b/litellm/llms/perplexity/cost_calculator.py @@ -34,7 +34,9 @@ def cost_per_token(model: str, usage: Usage) -> Tuple[float, float]: ## GET MODEL INFO model_info = get_model_info(model=model, custom_llm_provider="perplexity") - def _safe_float_cast(value: Union[str, int, float, None, object], default: float = 0.0) -> float: + def _safe_float_cast( + value: Union[str, int, float, None, object], default: float = 0.0 + ) -> float: """Safely cast a value to float with proper type handling for mypy.""" if value is None: return default @@ -61,9 +63,15 @@ def cost_per_token(model: str, usage: Usage) -> Tuple[float, float]: ## ADD REASONING TOKENS COST (if present) reasoning_tokens = getattr(usage, "reasoning_tokens", 0) or 0 # Also check completion_tokens_details if reasoning_tokens is not directly available - if reasoning_tokens == 0 and hasattr(usage, "completion_tokens_details") and usage.completion_tokens_details: - reasoning_tokens = getattr(usage.completion_tokens_details, "reasoning_tokens", 0) or 0 - + if ( + reasoning_tokens == 0 + and hasattr(usage, "completion_tokens_details") + and usage.completion_tokens_details + ): + reasoning_tokens = ( + getattr(usage.completion_tokens_details, "reasoning_tokens", 0) or 0 + ) + reasoning_cost_value = model_info.get("output_cost_per_reasoning_token") if reasoning_tokens > 0 and reasoning_cost_value is not None: reasoning_cost_per_token = _safe_float_cast(reasoning_cost_value) @@ -72,19 +80,26 @@ def cost_per_token(model: str, usage: Usage) -> Tuple[float, float]: ## ADD SEARCH QUERIES COST (if present) num_search_queries = 0 if hasattr(usage, "prompt_tokens_details") and usage.prompt_tokens_details: - num_search_queries = getattr(usage.prompt_tokens_details, "web_search_requests", 0) or 0 - + num_search_queries = ( + getattr(usage.prompt_tokens_details, "web_search_requests", 0) or 0 + ) + # Check both possible keys for search cost (legacy and current) - search_cost_value = model_info.get("search_queries_cost_per_query") or model_info.get("search_context_cost_per_query") + search_cost_value = model_info.get( + "search_queries_cost_per_query" + ) or model_info.get("search_context_cost_per_query") if num_search_queries > 0 and search_cost_value is not None: # Handle both dict and float formats if isinstance(search_cost_value, dict): # Use the "low" size as default - tests expect 0.005 / 1000 - search_cost_per_query = _safe_float_cast(search_cost_value.get("search_context_size_low", 0)) / 1000 + search_cost_per_query = ( + _safe_float_cast(search_cost_value.get("search_context_size_low", 0)) + / 1000 + ) else: search_cost_per_query = _safe_float_cast(search_cost_value) search_cost = num_search_queries * search_cost_per_query # Add search cost to completion cost (similar to how other providers handle it) completion_cost += search_cost - return prompt_cost, completion_cost \ No newline at end of file + return prompt_cost, completion_cost diff --git a/litellm/llms/perplexity/responses/transformation.py b/litellm/llms/perplexity/responses/transformation.py index f365ef07a61..c7ec1313566 100644 --- a/litellm/llms/perplexity/responses/transformation.py +++ b/litellm/llms/perplexity/responses/transformation.py @@ -23,7 +23,6 @@ from litellm.types.utils import LlmProviders class PerplexityResponsesConfig(OpenAIResponsesAPIConfig): - def get_supported_openai_params(self, model: str) -> list: """Ref: https://docs.perplexity.ai/api-reference/responses-post""" return [ @@ -55,21 +54,28 @@ class PerplexityResponsesConfig(OpenAIResponsesAPIConfig): return headers def get_complete_url(self, api_base: Optional[str], litellm_params: dict) -> str: - api_base = api_base or get_secret_str("PERPLEXITY_API_BASE") or "https://api.perplexity.ai" + api_base = ( + api_base + or get_secret_str("PERPLEXITY_API_BASE") + or "https://api.perplexity.ai" + ) return f"{api_base.rstrip('/')}/v1/responses" def _ensure_message_type( self, input: Union[str, ResponseInputParam] - ) -> Union[str, List[Dict[str, Any]]]: + ) -> Union[str, ResponseInputParam]: """Ensure list input items have type='message' (required by Perplexity).""" if isinstance(input, str): return input if isinstance(input, list): - result = [] + result: List[Any] = [] for item in input: if isinstance(item, dict) and "type" not in item: - item = {**item, "type": "message"} - result.append(item) + new_item = dict(item) # convert to plain dict to avoid TypedDict checking + new_item["type"] = "message" + result.append(new_item) + else: + result.append(item) return result return input @@ -86,7 +92,7 @@ class PerplexityResponsesConfig(OpenAIResponsesAPIConfig): if model.startswith("preset/"): input = self._validate_input_param(input) data: Dict = { - "preset": model[len("preset/"):], + "preset": model[len("preset/") :], "input": input, } data.update(response_api_optional_request_params) diff --git a/litellm/llms/perplexity/search/transformation.py b/litellm/llms/perplexity/search/transformation.py index f1dc0909b4d..f89d5565498 100644 --- a/litellm/llms/perplexity/search/transformation.py +++ b/litellm/llms/perplexity/search/transformation.py @@ -16,6 +16,7 @@ from litellm.secret_managers.main import get_secret_str class _PerplexitySearchRequestRequired(TypedDict): """Required fields for Perplexity Search API request.""" + query: Union[str, List[str]] # Required - search query or queries @@ -24,6 +25,7 @@ class PerplexitySearchRequest(_PerplexitySearchRequestRequired, total=False): Perplexity Search API request format. Based on: https://docs.perplexity.ai/api-reference/search-post """ + max_results: int # Optional - maximum number of results (1-20), default 10 search_domain_filter: List[str] # Optional - list of domains to filter (max 20) max_tokens_per_page: int # Optional - max tokens per page, default 1024 @@ -32,11 +34,11 @@ class PerplexitySearchRequest(_PerplexitySearchRequestRequired, total=False): class PerplexitySearchConfig(BaseSearchConfig): PERPLEXITY_API_BASE = "https://api.perplexity.ai" - + @staticmethod def ui_friendly_name() -> str: return "Perplexity" - + def validate_environment( self, headers: Dict, @@ -49,7 +51,9 @@ class PerplexitySearchConfig(BaseSearchConfig): """ api_key = api_key or get_secret_str("PERPLEXITYAI_API_KEY") if not api_key: - raise ValueError("PERPLEXITYAI_API_KEY is not set. Set `PERPLEXITYAI_API_KEY` environment variable.") + raise ValueError( + "PERPLEXITYAI_API_KEY is not set. Set `PERPLEXITYAI_API_KEY` environment variable." + ) headers["Authorization"] = f"Bearer {api_key}" headers["Content-Type"] = "application/json" return headers @@ -64,14 +68,17 @@ class PerplexitySearchConfig(BaseSearchConfig): """ Get complete URL for Search endpoint. """ - api_base = api_base or get_secret_str("PERPLEXITY_API_BASE") or self.PERPLEXITY_API_BASE - + api_base = ( + api_base + or get_secret_str("PERPLEXITY_API_BASE") + or self.PERPLEXITY_API_BASE + ) + # append "/search" to the api base if it's not already there if not api_base.endswith("/search"): api_base = f"{api_base}/search" return api_base - def transform_search_request( self, @@ -85,9 +92,9 @@ class PerplexitySearchConfig(BaseSearchConfig): Note: LiteLLM's native spec is the perplexity search spec. There's no transformation needed for the request data. - + https://docs.perplexity.ai/api-reference/search-post - + Args: query: Search query (string or list of strings) optional_params: Optional parameters for the request @@ -95,31 +102,31 @@ class PerplexitySearchConfig(BaseSearchConfig): - search_domain_filter: List of domains to filter (max 20) - max_tokens_per_page: Max tokens per page (default 1024) - country: Country code filter (e.g., 'US', 'GB', 'DE') - + Returns: Dict with typed request data following PerplexitySearchRequest spec """ request_data: PerplexitySearchRequest = { "query": query, } - + # Add optional parameters following Perplexity API spec (only if not None) max_results = optional_params.get("max_results") if max_results is not None: request_data["max_results"] = max_results - + search_domain_filter = optional_params.get("search_domain_filter") if search_domain_filter is not None: request_data["search_domain_filter"] = search_domain_filter - + max_tokens_per_page = optional_params.get("max_tokens_per_page") if max_tokens_per_page is not None: request_data["max_tokens_per_page"] = max_tokens_per_page - + country = optional_params.get("country") if country is not None: request_data["country"] = country - + return dict(request_data) def transform_search_response( @@ -130,16 +137,16 @@ class PerplexitySearchConfig(BaseSearchConfig): ) -> SearchResponse: """ Transform Perplexity API response to standard SearchResponse format. - + Args: raw_response: Raw httpx response from Perplexity API logging_obj: Logging object for tracking - + Returns: SearchResponse with standardized format """ response_json = raw_response.json() - + # Transform results to SearchResult objects results = [] for result in response_json.get("results", []): @@ -151,9 +158,8 @@ class PerplexitySearchConfig(BaseSearchConfig): last_updated=result.get("last_updated"), ) results.append(search_result) - + return SearchResponse( results=results, object="search", ) - diff --git a/litellm/llms/pg_vector/vector_stores/transformation.py b/litellm/llms/pg_vector/vector_stores/transformation.py index 5d10faeba50..ba87a8f2b01 100644 --- a/litellm/llms/pg_vector/vector_stores/transformation.py +++ b/litellm/llms/pg_vector/vector_stores/transformation.py @@ -10,6 +10,7 @@ if TYPE_CHECKING: else: LiteLLMLoggingObj = Any + class PGVectorStoreConfig(OpenAIVectorStoreConfig): """ PG Vector Store configuration that inherits from OpenAI since it's OpenAI-compatible. @@ -19,7 +20,7 @@ class PGVectorStoreConfig(OpenAIVectorStoreConfig): https://github.com/BerriAI/litellm-pgvector You just need to connect litellm proxy to this deployed server. - + Requires: - api_base: The base URL for the PG vector service - api_key: API key for authentication with the PG vector service @@ -32,16 +33,15 @@ class PGVectorStoreConfig(OpenAIVectorStoreConfig): Validate environment and set headers for PG vector service authentication """ litellm_params = litellm_params or GenericLiteLLMParams() - + # Get API key from various sources - api_key = ( - litellm_params.api_key - or get_secret_str("PG_VECTOR_API_KEY") - ) - + api_key = litellm_params.api_key or get_secret_str("PG_VECTOR_API_KEY") + if not api_key: - raise ValueError("PG Vector API key is required. Set PG_VECTOR_API_KEY environment variable or pass api_key in litellm_params.") - + raise ValueError( + "PG Vector API key is required. Set PG_VECTOR_API_KEY environment variable or pass api_key in litellm_params." + ) + headers.update( { "Authorization": f"Bearer {api_key}", @@ -60,19 +60,17 @@ class PGVectorStoreConfig(OpenAIVectorStoreConfig): Get the complete URL for PG vector service endpoints """ # Get API base from various sources - api_base = ( - api_base - or get_secret_str("PG_VECTOR_API_BASE") - ) - + api_base = api_base or get_secret_str("PG_VECTOR_API_BASE") + if not api_base: - raise ValueError("PG Vector API base URL is required. Set PG_VECTOR_API_BASE environment variable or pass api_base in litellm_params.") + raise ValueError( + "PG Vector API base URL is required. Set PG_VECTOR_API_BASE environment variable or pass api_base in litellm_params." + ) # Remove trailing slashes api_base = api_base.rstrip("/") - return f"{api_base}/v1/vector_stores" - + return f"{api_base}/v1/vector_stores" def transform_search_vector_store_request( self, @@ -83,7 +81,7 @@ class PGVectorStoreConfig(OpenAIVectorStoreConfig): litellm_logging_obj: LiteLLMLoggingObj, litellm_params: dict, ) -> Tuple[str, Dict]: - url = f"{api_base}/{vector_store_id}/search" + url = f"{api_base}/{vector_store_id}/search" _, request_body = super().transform_search_vector_store_request( vector_store_id=vector_store_id, query=query, @@ -92,4 +90,4 @@ class PGVectorStoreConfig(OpenAIVectorStoreConfig): litellm_logging_obj=litellm_logging_obj, litellm_params=litellm_params, ) - return url, request_body \ No newline at end of file + return url, request_body diff --git a/litellm/llms/ragflow/__init__.py b/litellm/llms/ragflow/__init__.py index 17d12bed31c..3ca54e38551 100644 --- a/litellm/llms/ragflow/__init__.py +++ b/litellm/llms/ragflow/__init__.py @@ -5,4 +5,3 @@ RAGFlow provides OpenAI-compatible APIs with unique path structures: - Chat endpoint: /api/v1/chats_openai/{chat_id}/chat/completions - Agent endpoint: /api/v1/agents_openai/{agent_id}/chat/completions """ - diff --git a/litellm/llms/ragflow/chat/__init__.py b/litellm/llms/ragflow/chat/__init__.py index 0e0f47d07b6..4f84cce42b0 100644 --- a/litellm/llms/ragflow/chat/__init__.py +++ b/litellm/llms/ragflow/chat/__init__.py @@ -1,4 +1,3 @@ """ RAGFlow chat completion configuration. """ - diff --git a/litellm/llms/ragflow/chat/transformation.py b/litellm/llms/ragflow/chat/transformation.py index 58fbfa83c98..d49a5fd370f 100644 --- a/litellm/llms/ragflow/chat/transformation.py +++ b/litellm/llms/ragflow/chat/transformation.py @@ -21,7 +21,7 @@ from litellm.types.llms.openai import AllMessageValues class RAGFlowConfig(OpenAIConfig): """ Configuration for RAGFlow OpenAI-compatible API. - + Handles both chat and agent endpoints by parsing the model name format: - ragflow/chat/{chat_id}/{model_name} for chat endpoints - ragflow/agent/{agent_id}/{model_name} for agent endpoints @@ -30,13 +30,13 @@ class RAGFlowConfig(OpenAIConfig): def _parse_ragflow_model(self, model: str) -> Tuple[str, str, str]: """ Parse RAGFlow model name format: ragflow/{endpoint_type}/{id}/{model_name} - + Args: model: Model name in format ragflow/chat/{chat_id}/{model} or ragflow/agent/{agent_id}/{model} - + Returns: Tuple of (endpoint_type, id, model_name) - + Raises: ValueError: If model format is invalid """ @@ -46,21 +46,23 @@ class RAGFlowConfig(OpenAIConfig): f"Invalid RAGFlow model format: {model}. " f"Expected format: ragflow/chat/{{chat_id}}/{{model}} or ragflow/agent/{{agent_id}}/{{model}}" ) - + if parts[0] != "ragflow": raise ValueError( f"Invalid RAGFlow model format: {model}. Must start with 'ragflow/'" ) - + endpoint_type = parts[1] if endpoint_type not in ["chat", "agent"]: raise ValueError( f"Invalid RAGFlow endpoint type: {endpoint_type}. Must be 'chat' or 'agent'" ) - + entity_id = parts[2] - model_name = "/".join(parts[3:]) # Handle model names that might contain slashes - + model_name = "/".join( + parts[3:] + ) # Handle model names that might contain slashes + return endpoint_type, entity_id, model_name def get_complete_url( @@ -74,11 +76,11 @@ class RAGFlowConfig(OpenAIConfig): ) -> str: """ Get the complete URL for the RAGFlow API call. - + Constructs URL based on endpoint type: - Chat: /api/v1/chats_openai/{chat_id}/chat/completions - Agent: /api/v1/agents_openai/{agent_id}/chat/completions - + Args: api_base: Base API URL (e.g., http://ragflow-server:port or http://ragflow-server:port/v1) api_key: API key (not used in URL construction) @@ -86,47 +88,53 @@ class RAGFlowConfig(OpenAIConfig): optional_params: Optional parameters litellm_params: LiteLLM parameters (may contain api_base) stream: Whether streaming is enabled - + Returns: Complete URL for the API call """ # Get api_base from multiple sources: input param, litellm_params, environment, or global litellm setting - if litellm_params and hasattr(litellm_params, 'api_base') and litellm_params.api_base: + if ( + litellm_params + and hasattr(litellm_params, "api_base") + and litellm_params.api_base + ): api_base = api_base or litellm_params.api_base - + api_base = ( api_base or litellm.api_base or get_secret("RAGFLOW_API_BASE") or get_secret_str("RAGFLOW_API_BASE") ) - + if api_base is None: - raise ValueError("api_base is required for RAGFlow provider. Set it via api_base parameter, RAGFLOW_API_BASE environment variable, or litellm.api_base") - + raise ValueError( + "api_base is required for RAGFlow provider. Set it via api_base parameter, RAGFLOW_API_BASE environment variable, or litellm.api_base" + ) + # Parse model name to extract endpoint type and ID endpoint_type, entity_id, _ = self._parse_ragflow_model(model) - + # Remove trailing slash from api_base if present api_base = api_base.rstrip("/") - + # Strip /v1 or /api/v1 from api_base if present, since we'll add the full path # Check /api/v1 first because /api/v1 ends with /v1 if api_base.endswith("/api/v1"): api_base = api_base[:-7] # Remove /api/v1 elif api_base.endswith("/v1"): api_base = api_base[:-3] # Remove /v1 - + # Construct the RAGFlow-specific path if endpoint_type == "chat": path = f"/api/v1/chats_openai/{entity_id}/chat/completions" else: # agent path = f"/api/v1/agents_openai/{entity_id}/chat/completions" - + # Ensure path starts with / if not path.startswith("/"): path = "/" + path - + return f"{api_base}{path}" def _get_openai_compatible_provider_info( @@ -138,20 +146,20 @@ class RAGFlowConfig(OpenAIConfig): ) -> Tuple[Optional[str], Optional[str], str]: """ Get OpenAI-compatible provider information for RAGFlow. - + Args: model: Model name (will be parsed to extract actual model name) api_base: Base API URL (from input params) api_key: API key (from input params) custom_llm_provider: Custom LLM provider name - + Returns: Tuple of (api_base, api_key, custom_llm_provider) """ # Parse model to extract the actual model name # The model name will be stored in litellm_params for use in requests _, _, actual_model = self._parse_ragflow_model(model) - + # Get api_base from multiple sources: input param, environment, or global litellm setting dynamic_api_base = ( api_base @@ -159,14 +167,12 @@ class RAGFlowConfig(OpenAIConfig): or get_secret("RAGFLOW_API_BASE") or get_secret_str("RAGFLOW_API_BASE") ) - + # Get api_key from multiple sources: input param, environment, or global litellm setting dynamic_api_key = ( - api_key - or litellm.api_key - or get_secret_str("RAGFLOW_API_KEY") + api_key or litellm.api_key or get_secret_str("RAGFLOW_API_KEY") ) - + return dynamic_api_base, dynamic_api_key, custom_llm_provider def validate_environment( @@ -181,7 +187,7 @@ class RAGFlowConfig(OpenAIConfig): ) -> dict: """ Validate environment and set up headers for RAGFlow API. - + Args: headers: Request headers model: Model name @@ -190,28 +196,28 @@ class RAGFlowConfig(OpenAIConfig): litellm_params: LiteLLM parameters (may contain api_key) api_key: API key (from input params) api_base: Base API URL - + Returns: Updated headers dictionary """ # Use api_key from litellm_params if available, otherwise fall back to other sources - if litellm_params and hasattr(litellm_params, 'api_key') and litellm_params.api_key: + if ( + litellm_params + and hasattr(litellm_params, "api_key") + and litellm_params.api_key + ): api_key = api_key or litellm_params.api_key - + # Get api_key from multiple sources: input param, litellm_params, environment, or global litellm setting - api_key = ( - api_key - or litellm.api_key - or get_secret_str("RAGFLOW_API_KEY") - ) - + api_key = api_key or litellm.api_key or get_secret_str("RAGFLOW_API_KEY") + if api_key is not None: headers["Authorization"] = f"Bearer {api_key}" - + # Ensure Content-Type is set to application/json if "content-type" not in headers and "Content-Type" not in headers: headers["Content-Type"] = "application/json" - + # Parse model to extract actual model name and store it # The actual model name should be used in the request body try: @@ -221,7 +227,7 @@ class RAGFlowConfig(OpenAIConfig): except ValueError: # If parsing fails, use the original model name pass - + return headers def transform_request( @@ -234,16 +240,16 @@ class RAGFlowConfig(OpenAIConfig): ) -> dict: """ Transform request for RAGFlow API. - + Uses the actual model name extracted from the RAGFlow model format. - + Args: model: Model name in RAGFlow format messages: Chat messages optional_params: Optional parameters litellm_params: LiteLLM parameters (may contain _ragflow_actual_model) headers: Request headers - + Returns: Transformed request dictionary """ @@ -256,9 +262,8 @@ class RAGFlowConfig(OpenAIConfig): except ValueError: # If parsing fails, use the original model name actual_model = model - + # Use parent's transform_request with the actual model name return super().transform_request( actual_model, messages, optional_params, litellm_params, headers ) - diff --git a/litellm/llms/ragflow/vector_stores/__init__.py b/litellm/llms/ragflow/vector_stores/__init__.py index 3be29310b39..f36e35f168c 100644 --- a/litellm/llms/ragflow/vector_stores/__init__.py +++ b/litellm/llms/ragflow/vector_stores/__init__.py @@ -1,2 +1 @@ # RAGFlow vector stores module - diff --git a/litellm/llms/ragflow/vector_stores/transformation.py b/litellm/llms/ragflow/vector_stores/transformation.py index b6401a4b8d7..ed5397eef0c 100644 --- a/litellm/llms/ragflow/vector_stores/transformation.py +++ b/litellm/llms/ragflow/vector_stores/transformation.py @@ -32,7 +32,9 @@ class RAGFlowVectorStoreConfig(BaseVectorStoreConfig): # Try to get from environment variable api_key = get_secret_str("RAGFLOW_API_KEY") if api_key is None: - raise ValueError("api_key is required (set RAGFLOW_API_KEY env var or pass in litellm_params)") + raise ValueError( + "api_key is required (set RAGFLOW_API_KEY env var or pass in litellm_params)" + ) return { "headers": { "Authorization": f"Bearer {api_key}", @@ -51,14 +53,13 @@ class RAGFlowVectorStoreConfig(BaseVectorStoreConfig): ) -> dict: """Validate environment and set headers for RAGFlow API.""" litellm_params = litellm_params or GenericLiteLLMParams() - api_key = ( - litellm_params.api_key - or get_secret_str("RAGFLOW_API_KEY") - ) - + api_key = litellm_params.api_key or get_secret_str("RAGFLOW_API_KEY") + if api_key is None: - raise ValueError("RAGFLOW_API_KEY is required (set env var or pass in litellm_params)") - + raise ValueError( + "RAGFLOW_API_KEY is required (set env var or pass in litellm_params)" + ) + headers.update( { "Authorization": f"Bearer {api_key}", @@ -74,7 +75,7 @@ class RAGFlowVectorStoreConfig(BaseVectorStoreConfig): ) -> str: """ Get the complete URL for RAGFlow datasets API. - + Supports: - RAGFLOW_API_BASE env var - api_base in litellm_params @@ -122,22 +123,22 @@ class RAGFlowVectorStoreConfig(BaseVectorStoreConfig): ) -> Tuple[str, Dict]: """ Transform create request to RAGFlow POST /api/v1/datasets format. - + Maps LiteLLM params to RAGFlow dataset creation parameters. RAGFlow-specific fields can be passed via metadata. """ url = api_base # Already includes /api/v1/datasets from get_complete_url - + # Extract name (required by RAGFlow) name = vector_store_create_optional_params.get("name") if not name: raise ValueError("name is required for RAGFlow dataset creation") - + # Build request body request_body: Dict[str, Any] = { "name": name, } - + # Extract RAGFlow-specific fields from metadata metadata = vector_store_create_optional_params.get("metadata") if metadata: @@ -152,22 +153,22 @@ class RAGFlowVectorStoreConfig(BaseVectorStoreConfig): "parse_type", "pipeline_id", ] - + for field in ragflow_fields: if field in metadata: request_body[field] = metadata[field] - + # Validate: chunk_method and pipeline_id are mutually exclusive if "chunk_method" in request_body and "pipeline_id" in request_body: raise ValueError( "chunk_method and pipeline_id are mutually exclusive. " "Specify either chunk_method or pipeline_id, not both." ) - + # If neither chunk_method nor pipeline_id is specified, default to naive if "chunk_method" not in request_body and "pipeline_id" not in request_body: request_body["chunk_method"] = "naive" - + return url, request_body def transform_create_vector_store_response( @@ -175,7 +176,7 @@ class RAGFlowVectorStoreConfig(BaseVectorStoreConfig): ) -> VectorStoreCreateResponse: """ Transform RAGFlow response to VectorStoreCreateResponse format. - + RAGFlow response format: { "code": 0, @@ -189,7 +190,7 @@ class RAGFlowVectorStoreConfig(BaseVectorStoreConfig): """ try: response_json = response.json() - + # Check for RAGFlow error response if response_json.get("code") != 0: error_message = response_json.get("message", "Unknown error") @@ -198,21 +199,21 @@ class RAGFlowVectorStoreConfig(BaseVectorStoreConfig): status_code=response.status_code, headers=response.headers, ) - + data = response_json.get("data", {}) - + # Extract dataset ID dataset_id = data.get("id") if not dataset_id: raise ValueError("RAGFlow response missing dataset id") - + # Extract name name = data.get("name") - + # Convert create_time from milliseconds to seconds (Unix timestamp) create_time_ms = data.get("create_time", 0) created_at = int(create_time_ms / 1000) if create_time_ms else None - + # Build VectorStoreCreateResponse return VectorStoreCreateResponse( id=dataset_id, @@ -246,4 +247,3 @@ class RAGFlowVectorStoreConfig(BaseVectorStoreConfig): status_code=response.status_code, headers=response.headers, ) - diff --git a/litellm/llms/recraft/cost_calculator.py b/litellm/llms/recraft/cost_calculator.py index 5ab47e9395e..27b9108e5fe 100644 --- a/litellm/llms/recraft/cost_calculator.py +++ b/litellm/llms/recraft/cost_calculator.py @@ -22,4 +22,6 @@ def cost_calculator( num_images = len(image_response.data) return output_cost_per_image * num_images else: - raise ValueError(f"image_response must be of type ImageResponse got type={type(image_response)}") + raise ValueError( + f"image_response must be of type ImageResponse got type={type(image_response)}" + ) diff --git a/litellm/llms/recraft/image_edit/transformation.py b/litellm/llms/recraft/image_edit/transformation.py index d2a56236819..4c199bc78d8 100644 --- a/litellm/llms/recraft/image_edit/transformation.py +++ b/litellm/llms/recraft/image_edit/transformation.py @@ -25,19 +25,17 @@ class RecraftImageEditConfig(BaseImageEditConfig): DEFAULT_BASE_URL: str = "https://external.api.recraft.ai" IMAGE_EDIT_ENDPOINT: str = "v1/images/imageToImage" DEFAULT_STRENGTH: float = 0.2 - - def get_supported_openai_params( - self, model: str - ) -> List: + + def get_supported_openai_params(self, model: str) -> List: """ Supported OpenAI parameters that can be mapped to Recraft image edit API. - + Based on Recraft API docs: https://www.recraft.ai/docs#image-to-image """ return [ - "n", # Maps to n (number of images) - "response_format", # Maps to response_format (url or b64_json) - "style" # Maps to style parameter + "n", # Maps to n (number of images) + "response_format", # Maps to response_format (url or b64_json) + "style", # Maps to style parameter ] def map_openai_params( @@ -52,14 +50,13 @@ class RecraftImageEditConfig(BaseImageEditConfig): """ # Start with all params like OpenAI does all_params = dict(image_edit_optional_params) - + # Filter to only supported Recraft parameters supported_params = self.get_supported_openai_params(model) filtered_params = {k: v for k, v in all_params.items() if k in supported_params} - + return filtered_params - def get_complete_url( self, model: str, @@ -72,9 +69,7 @@ class RecraftImageEditConfig(BaseImageEditConfig): Some providers need `model` in `api_base` """ complete_url: str = ( - api_base - or get_secret_str("RECRAFT_API_BASE") - or self.DEFAULT_BASE_URL + api_base or get_secret_str("RECRAFT_API_BASE") or self.DEFAULT_BASE_URL ) complete_url = complete_url.rstrip("/") @@ -87,16 +82,12 @@ class RecraftImageEditConfig(BaseImageEditConfig): model: str, api_key: Optional[str] = None, ) -> dict: - final_api_key: Optional[str] = ( - api_key or - get_secret_str("RECRAFT_API_KEY") - ) + final_api_key: Optional[str] = api_key or get_secret_str("RECRAFT_API_KEY") if not final_api_key: raise ValueError("RECRAFT_API_KEY is not set") - - headers["Authorization"] = f"Bearer {final_api_key}" - return headers + headers["Authorization"] = f"Bearer {final_api_key}" + return headers def transform_image_edit_request( self, @@ -113,32 +104,35 @@ class RecraftImageEditConfig(BaseImageEditConfig): https://www.recraft.ai/docs#image-to-image """ - + request_params = { "model": model, - "strength": image_edit_optional_request_params.pop("strength", self.DEFAULT_STRENGTH), + "strength": image_edit_optional_request_params.pop( + "strength", self.DEFAULT_STRENGTH + ), **image_edit_optional_request_params, } if prompt is not None: request_params["prompt"] = prompt - + request_body = RecraftImageEditRequestParams(**request_params) request_dict = cast(Dict, request_body) ######################################################### # Reuse OpenAI logic: Separate images as `files` and send other parameters as `data` ######################################################### - files_list = self._get_image_files_for_request(image=image) if image is not None else [] + files_list = ( + self._get_image_files_for_request(image=image) if image is not None else [] + ) data_without_images = {k: v for k, v in request_dict.items() if k != "image"} - + return data_without_images, files_list - def _get_image_files_for_request( self, image: Optional[FileTypes], ) -> List[Tuple[str, Any]]: files_list: List[Tuple[str, Any]] = [] - + # Handle single image (Recraft expects single image, not array) if image: # OpenAI wraps images in arrays, but for Recraft we need single image @@ -146,9 +140,11 @@ class RecraftImageEditConfig(BaseImageEditConfig): _image = image[0] if image else None # Take first image for Recraft else: _image = image - + if _image is not None: - image_content_type: str = ImageEditRequestUtils.get_image_content_type(_image) + image_content_type: str = ImageEditRequestUtils.get_image_content_type( + _image + ) if isinstance(_image, BufferedReader): files_list.append( ("image", (_image.name, _image, image_content_type)) @@ -159,7 +155,7 @@ class RecraftImageEditConfig(BaseImageEditConfig): ) return files_list - + def transform_image_edit_response( self, model: str, @@ -177,11 +173,13 @@ class RecraftImageEditConfig(BaseImageEditConfig): ) if not model_response.data: model_response.data = [] - + for image_data in response_data["data"]: - model_response.data.append(ImageObject( - url=image_data.get("url", None), - b64_json=image_data.get("b64_json", None), - )) - - return model_response \ No newline at end of file + model_response.data.append( + ImageObject( + url=image_data.get("url", None), + b64_json=image_data.get("b64_json", None), + ) + ) + + return model_response diff --git a/litellm/llms/recraft/image_generation/transformation.py b/litellm/llms/recraft/image_generation/transformation.py index f632b49f3ae..4a00512dfb9 100644 --- a/litellm/llms/recraft/image_generation/transformation.py +++ b/litellm/llms/recraft/image_generation/transformation.py @@ -24,20 +24,15 @@ else: class RecraftImageGenerationConfig(BaseImageGenerationConfig): DEFAULT_BASE_URL: str = "https://external.api.recraft.ai" IMAGE_GENERATION_ENDPOINT: str = "v1/images/generations" - + def get_supported_openai_params( self, model: str ) -> List[OpenAIImageGenerationOptionalParams]: """ https://www.recraft.ai/docs#generate-image """ - return [ - "n", - "response_format", - "size", - "style" - ] - + return ["n", "response_format", "size", "style"] + def map_openai_params( self, non_default_params: dict, @@ -74,9 +69,7 @@ class RecraftImageGenerationConfig(BaseImageGenerationConfig): Some providers need `model` in `api_base` """ complete_url: str = ( - api_base - or get_secret_str("RECRAFT_API_BASE") - or self.DEFAULT_BASE_URL + api_base or get_secret_str("RECRAFT_API_BASE") or self.DEFAULT_BASE_URL ) complete_url = complete_url.rstrip("/") @@ -93,18 +86,13 @@ class RecraftImageGenerationConfig(BaseImageGenerationConfig): api_key: Optional[str] = None, api_base: Optional[str] = None, ) -> dict: - final_api_key: Optional[str] = ( - api_key or - get_secret_str("RECRAFT_API_KEY") - ) + final_api_key: Optional[str] = api_key or get_secret_str("RECRAFT_API_KEY") if not final_api_key: raise ValueError("RECRAFT_API_KEY is not set") - - headers["Authorization"] = f"Bearer {final_api_key}" + + headers["Authorization"] = f"Bearer {final_api_key}" return headers - - def transform_image_generation_request( self, model: str, @@ -118,10 +106,12 @@ class RecraftImageGenerationConfig(BaseImageGenerationConfig): https://www.recraft.ai/docs#generate-image """ - recratft_image_generation_request_body: RecraftImageGenerationRequestParams = RecraftImageGenerationRequestParams( - prompt=prompt, - model=model, - **optional_params, + recratft_image_generation_request_body: RecraftImageGenerationRequestParams = ( + RecraftImageGenerationRequestParams( + prompt=prompt, + model=model, + **optional_params, + ) ) return dict(recratft_image_generation_request_body) @@ -153,11 +143,13 @@ class RecraftImageGenerationConfig(BaseImageGenerationConfig): ) if not model_response.data: model_response.data = [] - + for image_data in response_data["data"]: - model_response.data.append(ImageObject( - url=image_data.get("url", None), - b64_json=image_data.get("b64_json", None), - )) - - return model_response \ No newline at end of file + model_response.data.append( + ImageObject( + url=image_data.get("url", None), + b64_json=image_data.get("b64_json", None), + ) + ) + + return model_response diff --git a/litellm/llms/replicate/chat/handler.py b/litellm/llms/replicate/chat/handler.py index c37473b3183..cc4c61e397b 100644 --- a/litellm/llms/replicate/chat/handler.py +++ b/litellm/llms/replicate/chat/handler.py @@ -88,7 +88,9 @@ async def async_handle_prediction_response_streaming( response_data = response.json() status = response_data.get("status", "") # Check that "output" exists and is not None or empty - output_present = "output" in response_data and response_data["output"] is not None + output_present = ( + "output" in response_data and response_data["output"] is not None + ) if output_present: try: # If output is None or not a list, treat as empty string @@ -219,10 +221,10 @@ def completion( litellm.DEFAULT_REPLICATE_POLLING_DELAY_SECONDS + 2 * retry ) # wait to allow response to be generated by replicate - else partial output is generated with status=="processing" response = httpx_client.get(url=prediction_url, headers=headers) - if ( - response.status_code == 200 - and response.json().get("status") in ["processing", "starting"] - ): + if response.status_code == 200 and response.json().get("status") in [ + "processing", + "starting", + ]: continue return litellm.ReplicateConfig().transform_response( model=model, @@ -290,10 +292,10 @@ async def async_completion( litellm.DEFAULT_REPLICATE_POLLING_DELAY_SECONDS + 2 * retry ) # wait to allow response to be generated by replicate - else partial output is generated with status=="processing" response = await async_handler.get(url=prediction_url, headers=headers) - if ( - response.status_code == 200 - and response.json().get("status") in ["processing", "starting"] - ): + if response.status_code == 200 and response.json().get("status") in [ + "processing", + "starting", + ]: continue return litellm.ReplicateConfig().transform_response( model=model, diff --git a/litellm/llms/runwayml/cost_calculator.py b/litellm/llms/runwayml/cost_calculator.py index fa3cd26d08a..35b6086f196 100644 --- a/litellm/llms/runwayml/cost_calculator.py +++ b/litellm/llms/runwayml/cost_calculator.py @@ -10,7 +10,7 @@ def cost_calculator( ) -> float: """ RunwayML image generation cost calculator. - + RunwayML charges per image generated, not per pixel. Pricing is stored in model_prices_and_context_window.json with output_cost_per_image. """ @@ -28,4 +28,3 @@ def cost_calculator( raise ValueError( f"image_response must be of type ImageResponse, got type={type(image_response)}" ) - diff --git a/litellm/llms/runwayml/image_generation/transformation.py b/litellm/llms/runwayml/image_generation/transformation.py index e92ffa8e9c7..448dcd4a67b 100644 --- a/litellm/llms/runwayml/image_generation/transformation.py +++ b/litellm/llms/runwayml/image_generation/transformation.py @@ -31,6 +31,7 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): """ Configuration for RunwayML image generation models. """ + DEFAULT_BASE_URL: str = "https://api.dev.runwayml.com" IMAGE_GENERATION_ENDPOINT: str = "v1/text_to_image" @@ -49,9 +50,7 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): Some providers need `model` in `api_base` """ complete_url: str = ( - api_base - or get_secret_str("RUNWAYML_API_BASE") - or self.DEFAULT_BASE_URL + api_base or get_secret_str("RUNWAYML_API_BASE") or self.DEFAULT_BASE_URL ) complete_url = complete_url.rstrip("/") @@ -70,14 +69,14 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): api_base: Optional[str] = None, ) -> dict: final_api_key: Optional[str] = ( - api_key or - get_secret_str("RUNWAYML_API_SECRET") or - get_secret_str("RUNWAYML_API_KEY") + api_key + or get_secret_str("RUNWAYML_API_SECRET") + or get_secret_str("RUNWAYML_API_KEY") ) if not final_api_key: raise ValueError("RUNWAYML_API_SECRET or RUNWAYML_API_KEY is not set") - - headers["Authorization"] = f"Bearer {final_api_key}" + + headers["Authorization"] = f"Bearer {final_api_key}" headers["X-Runway-Version"] = RUNWAYML_DEFAULT_API_VERSION return headers @@ -88,7 +87,7 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): ) -> ImageResponse: """ Transform RunwayML response format to OpenAI ImageResponse format. - + RunwayML response format (after polling): { "id": "task_123...", @@ -96,7 +95,7 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): "output": ["https://cloudfront.net/.../image.png"], "completedAt": "2025-11-13T..." } - + OpenAI ImageResponse format: { "data": [ @@ -106,47 +105,51 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): } ] } - + Args: response_data: JSON response from RunwayML (after polling completes) model_response: ImageResponse object to populate - + Returns: Populated ImageResponse in OpenAI format """ if not model_response.data: model_response.data = [] - + # Handle RunwayML response format # Response contains task.output with image URL(s) output = response_data.get("output", []) - + if isinstance(output, list): for image_item in output: if isinstance(image_item, str): # If output is a list of URL strings - model_response.data.append(ImageObject( - url=image_item, - b64_json=None, - )) + model_response.data.append( + ImageObject( + url=image_item, + b64_json=None, + ) + ) elif isinstance(image_item, dict): # If output contains dict with url/b64_json - model_response.data.append(ImageObject( - url=image_item.get("url", None), - b64_json=image_item.get("b64_json", None), - )) - + model_response.data.append( + ImageObject( + url=image_item.get("url", None), + b64_json=image_item.get("b64_json", None), + ) + ) + return model_response @staticmethod def _check_timeout(start_time: float, timeout_secs: float) -> None: """ Check if operation has timed out. - + Args: start_time: Start time of the operation timeout_secs: Timeout duration in seconds - + Raises: TimeoutError: If operation has exceeded timeout """ @@ -159,22 +162,22 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): def _check_task_status(response_data: Dict[str, Any]) -> str: """ Check RunwayML task status from response. - + RunwayML statuses: PENDING, RUNNING, SUCCEEDED, FAILED, CANCELLED, THROTTLED - + Args: response_data: JSON response from RunwayML task endpoint - + Returns: Normalized status string: "running", "succeeded", or raises on failure - + Raises: ValueError: If task failed or status is unknown """ status = response_data.get("status", "").upper() - + verbose_logger.debug(f"RunwayML task status: {status}") - + if status == "SUCCEEDED": return "succeeded" elif status == "FAILED": @@ -199,16 +202,16 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): ) -> httpx.Response: """ Poll RunwayML task until completion (sync). - + RunwayML POST returns immediately with a task that has status PENDING/RUNNING. We need to poll GET /v1/tasks/{task_id} until status is SUCCEEDED or FAILED. - + Args: task_id: The task ID to poll api_base: Base URL for RunwayML API headers: Request headers (including auth) timeout_secs: Total timeout in seconds (default: 600s = 10 minutes) - + Returns: Final response with completed task """ @@ -216,25 +219,25 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): client = _get_httpx_client() start_time = time.time() - + # Build task status URL api_base = api_base.rstrip("/") task_url = f"{api_base}/v1/tasks/{task_id}" - + verbose_logger.debug(f"Polling RunwayML task: {task_url}") - + while True: self._check_timeout(start_time=start_time, timeout_secs=timeout_secs) - + # Poll the task status response = client.get(url=task_url, headers=headers) response.raise_for_status() - + response_data = response.json() - + # Check task status status = self._check_task_status(response_data=response_data) - + if status == "succeeded": return response elif status == "running": @@ -250,13 +253,13 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): ) -> httpx.Response: """ Poll RunwayML task until completion (async). - + Args: task_id: The task ID to poll api_base: Base URL for RunwayML API headers: Request headers (including auth) timeout_secs: Total timeout in seconds (default: 600s = 10 minutes) - + Returns: Final response with completed task """ @@ -265,25 +268,25 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): client = get_async_httpx_client(llm_provider=litellm.LlmProviders.RUNWAYML) start_time = time.time() - + # Build task status URL api_base = api_base.rstrip("/") task_url = f"{api_base}/v1/tasks/{task_id}" - + verbose_logger.debug(f"Polling RunwayML task (async): {task_url}") - + while True: self._check_timeout(start_time=start_time, timeout_secs=timeout_secs) - + # Poll the task status response = await client.get(url=task_url, headers=headers) response.raise_for_status() - + response_data = response.json() - + # Check task status status = self._check_task_status(response_data=response_data) - + if status == "succeeded": return response elif status == "running": @@ -305,17 +308,17 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): ) -> ImageResponse: """ Transform the image generation response to the litellm image response. - + RunwayML returns a task immediately with status PENDING/RUNNING. We need to poll the task until it completes (status SUCCEEDED). - + Initial response: { "id": "task_123...", "status": "PENDING" | "RUNNING", "createdAt": "2025-11-13T..." } - + After polling: { "id": "task_123...", @@ -332,23 +335,22 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): status_code=raw_response.status_code, headers=raw_response.headers, ) - - verbose_logger.debug( - "RunwayML starting polling..." - ) - + verbose_logger.debug("RunwayML starting polling...") + # Get task ID task_id = response_data.get("id") if not task_id: raise ValueError("RunwayML response missing task ID") - + # Get headers for polling (need auth) poll_headers = { "Authorization": raw_response.request.headers.get("Authorization", ""), - "X-Runway-Version": raw_response.request.headers.get("X-Runway-Version", RUNWAYML_DEFAULT_API_VERSION), + "X-Runway-Version": raw_response.request.headers.get( + "X-Runway-Version", RUNWAYML_DEFAULT_API_VERSION + ), } - + # Poll until task completes raw_response = self._poll_task_sync( task_id=task_id, @@ -356,12 +358,12 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): headers=poll_headers, timeout_secs=RUNWAYML_POLLING_TIMEOUT, ) - + # Update response_data with polled result response_data = raw_response.json() - + verbose_logger.debug("RunwayML polling complete, transforming to OpenAI format") - + # Transform RunwayML response to OpenAI format return self._transform_runwayml_response_to_openai( response_data=response_data, @@ -383,7 +385,7 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): ) -> ImageResponse: """ Async transform the image generation response to the litellm image response. - + RunwayML returns a task immediately with status PENDING/RUNNING. We need to poll the task until it completes (status SUCCEEDED) using async polling. """ @@ -395,22 +397,22 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): status_code=raw_response.status_code, headers=raw_response.headers, ) - - verbose_logger.debug( - "RunwayML starting polling (async)..." - ) - + + verbose_logger.debug("RunwayML starting polling (async)...") + # Get task ID task_id = response_data.get("id") if not task_id: raise ValueError("RunwayML response missing task ID") - + # Get headers for polling (need auth) poll_headers = { "Authorization": raw_response.request.headers.get("Authorization", ""), - "X-Runway-Version": raw_response.request.headers.get("X-Runway-Version", RUNWAYML_DEFAULT_API_VERSION), + "X-Runway-Version": raw_response.request.headers.get( + "X-Runway-Version", RUNWAYML_DEFAULT_API_VERSION + ), } - + # Poll until task completes (async) raw_response = await self._poll_task_async( task_id=task_id, @@ -418,18 +420,20 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): headers=poll_headers, timeout_secs=RUNWAYML_POLLING_TIMEOUT, ) - + # Update response_data with polled result response_data = raw_response.json() - - verbose_logger.debug("RunwayML polling complete (async), transforming to OpenAI format") - + + verbose_logger.debug( + "RunwayML polling complete (async), transforming to OpenAI format" + ) + # Transform RunwayML response to OpenAI format return self._transform_runwayml_response_to_openai( response_data=response_data, model_response=model_response, ) - + def get_supported_openai_params( self, model: str ) -> List[OpenAIImageGenerationOptionalParams]: @@ -439,7 +443,7 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): return [ "size", ] - + def map_openai_params( self, non_default_params: dict, @@ -448,7 +452,7 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): drop_params: bool, ) -> dict: supported_params = self.get_supported_openai_params(model) - + # Map OpenAI 'size' parameter to RunwayML 'ratio' parameter if "size" in non_default_params: size = non_default_params["size"] @@ -461,7 +465,7 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): "1080x1920": "1080:1920", } optional_params["ratio"] = size_to_ratio_map.get(size, "1920:1080") - + for k in non_default_params.keys(): if k not in optional_params.keys(): if k in supported_params: @@ -485,7 +489,7 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): ) -> dict: """ Transform the image generation request to the RunwayML image generation request body - + RunwayML expects: - model: The model to use (e.g., 'gen4_image') - promptText: The text prompt @@ -495,7 +499,7 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): "model": model or "gen4_image", "promptText": prompt, } - + # Add any RunwayML-specific parameters if "ratio" in optional_params: runwayml_request_body["ratio"] = optional_params["ratio"] @@ -503,11 +507,9 @@ class RunwayMLImageGenerationConfig(BaseImageGenerationConfig): # Set default ratio if not provided runwayml_request_body["ratio"] = "1920:1080" - # Add any other optional parameters for k, v in optional_params.items(): if k not in runwayml_request_body and k not in ["size"]: runwayml_request_body[k] = v - - return runwayml_request_body + return runwayml_request_body diff --git a/litellm/llms/runwayml/text_to_speech/__init__.py b/litellm/llms/runwayml/text_to_speech/__init__.py index 491e8449e0a..98337a8321a 100644 --- a/litellm/llms/runwayml/text_to_speech/__init__.py +++ b/litellm/llms/runwayml/text_to_speech/__init__.py @@ -2,4 +2,3 @@ from .transformation import RunwayMLTextToSpeechConfig __all__ = ["RunwayMLTextToSpeechConfig"] - diff --git a/litellm/llms/runwayml/text_to_speech/transformation.py b/litellm/llms/runwayml/text_to_speech/transformation.py index ac926beb227..dfcb92bc68b 100644 --- a/litellm/llms/runwayml/text_to_speech/transformation.py +++ b/litellm/llms/runwayml/text_to_speech/transformation.py @@ -32,25 +32,25 @@ else: class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): """ Configuration for RunwayML Text-to-Speech - + Reference: https://api.dev.runwayml.com/v1/text_to_speech """ - + DEFAULT_BASE_URL: str = "https://api.dev.runwayml.com" TTS_ENDPOINT_PATH: str = "v1/text_to_speech" DEFAULT_MODEL: str = "eleven_multilingual_v2" DEFAULT_VOICE_TYPE: str = "runway-preset" DEFAULT_VOICE_PRESET_ID: str = "Bernard" - + # Voice mappings from OpenAI voices to RunwayML preset IDs # OpenAI voices mapped to similar-sounding RunwayML voices VOICE_MAPPINGS = { - "alloy": "Maya", # Neutral, balanced female voice - "echo": "James", # Male voice - "fable": "Bernard", # Warm, storytelling voice - "onyx": "Vincent", # Deep male voice - "nova": "Serene", # Warm, expressive female voice - "shimmer": "Ella", # Clear, friendly female voice + "alloy": "Maya", # Neutral, balanced female voice + "echo": "James", # Male voice + "fable": "Bernard", # Warm, storytelling voice + "onyx": "Vincent", # Deep male voice + "nova": "Serene", # Warm, expressive female voice + "shimmer": "Ella", # Clear, friendly female voice } def dispatch_text_to_speech( @@ -74,9 +74,9 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): ]: """ Dispatch method to handle RunwayML TTS requests - + This method encapsulates RunwayML-specific credential resolution and parameter handling - + Args: base_llm_http_handler: The BaseLLMHTTPHandler instance from main.py """ @@ -88,7 +88,7 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): or get_secret_str("RUNWAYML_API_BASE") or self.DEFAULT_BASE_URL ) - + # Resolve api_key from multiple sources api_key = ( api_key @@ -97,7 +97,7 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): or get_secret_str("RUNWAYML_API_SECRET") or get_secret_str("RUNWAYML_API_KEY") ) - + # Convert voice to appropriate format voice_param: Optional[Union[str, Dict]] = voice if isinstance(voice, str): @@ -106,12 +106,14 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): elif isinstance(voice, dict): # Already in dict format, pass through voice_param = voice - - litellm_params_dict.update({ - "api_key": api_key, - "api_base": api_base, - }) - + + litellm_params_dict.update( + { + "api_key": api_key, + "api_base": api_base, + } + ) + # Call the text_to_speech_handler response = base_llm_http_handler.text_to_speech_handler( model=model, @@ -127,7 +129,7 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): client=None, _is_async=aspeech, ) - + return response def get_supported_openai_params(self, model: str) -> list: @@ -146,15 +148,15 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): ) -> Tuple[Optional[str], Dict]: """ Map OpenAI parameters to RunwayML TTS parameters - + Returns: Tuple of (mapped_voice_string, mapped_params) - + Note: Since RunwayML requires voice as a dict, we store it in mapped_params["runwayml_voice"] and return None for the voice string. """ mapped_params = {} - + # Map voice parameter to RunwayML format dict voice_dict: Optional[Dict] = None if isinstance(voice, str): @@ -174,14 +176,14 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): elif isinstance(voice, dict): # Already in RunwayML format, use as-is voice_dict = voice - + # Store the voice dict in optional_params for later use if voice_dict is not None: mapped_params["runwayml_voice"] = voice_dict - + # No other OpenAI params are currently supported by RunwayML TTS # (response_format, speed, etc. are not supported) - + # Return None for voice string since RunwayML uses dict format return None, mapped_params @@ -196,20 +198,20 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): Validate RunwayML environment and set up authentication headers """ validated_headers = headers.copy() - + final_api_key = ( - api_key - or get_secret_str("RUNWAYML_API_SECRET") + api_key + or get_secret_str("RUNWAYML_API_SECRET") or get_secret_str("RUNWAYML_API_KEY") ) - + if not final_api_key: raise ValueError("RUNWAYML_API_SECRET or RUNWAYML_API_KEY is not set") - + validated_headers["Authorization"] = f"Bearer {final_api_key}" validated_headers["X-Runway-Version"] = RUNWAYML_DEFAULT_API_VERSION validated_headers["Content-Type"] = "application/json" - + return validated_headers def get_complete_url( @@ -222,11 +224,9 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): Get the complete URL for RunwayML TTS request """ complete_url = ( - api_base - or get_secret_str("RUNWAYML_API_BASE") - or self.DEFAULT_BASE_URL + api_base or get_secret_str("RUNWAYML_API_BASE") or self.DEFAULT_BASE_URL ) - + complete_url = complete_url.rstrip("/") return f"{complete_url}/{self.TTS_ENDPOINT_PATH}" @@ -234,11 +234,11 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): def _check_timeout(start_time: float, timeout_secs: float) -> None: """ Check if operation has timed out. - + Args: start_time: Start time of the operation timeout_secs: Timeout duration in seconds - + Raises: TimeoutError: If operation has exceeded timeout """ @@ -251,22 +251,22 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): def _check_task_status(response_data: Dict[str, Any]) -> str: """ Check RunwayML task status from response. - + RunwayML statuses: PENDING, RUNNING, SUCCEEDED, FAILED, CANCELLED, THROTTLED - + Args: response_data: JSON response from RunwayML task endpoint - + Returns: Normalized status string: "running", "succeeded", or raises on failure - + Raises: ValueError: If task failed or status is unknown """ status = response_data.get("status", "").upper() - + verbose_logger.debug(f"RunwayML TTS task status: {status}") - + if status == "SUCCEEDED": return "succeeded" elif status == "FAILED": @@ -291,16 +291,16 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): ) -> httpx.Response: """ Poll RunwayML task until completion (sync). - + RunwayML POST returns immediately with a task that has status PENDING/RUNNING. We need to poll GET /v1/tasks/{task_id} until status is SUCCEEDED or FAILED. - + Args: task_id: The task ID to poll api_base: Base URL for RunwayML API headers: Request headers (including auth) timeout_secs: Total timeout in seconds (default: 600s = 10 minutes) - + Returns: Final response with completed task """ @@ -308,25 +308,25 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): client = _get_httpx_client() start_time = time.time() - + # Build task status URL api_base = api_base.rstrip("/") task_url = f"{api_base}/v1/tasks/{task_id}" - + verbose_logger.debug(f"Polling RunwayML TTS task: {task_url}") - + while True: self._check_timeout(start_time=start_time, timeout_secs=timeout_secs) - + # Poll the task status response = client.get(url=task_url, headers=headers) response.raise_for_status() - + response_data = response.json() - + # Check task status status = self._check_task_status(response_data=response_data) - + if status == "succeeded": return response elif status == "running": @@ -342,13 +342,13 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): ) -> httpx.Response: """ Poll RunwayML task until completion (async). - + Args: task_id: The task ID to poll api_base: Base URL for RunwayML API headers: Request headers (including auth) timeout_secs: Total timeout in seconds (default: 600s = 10 minutes) - + Returns: Final response with completed task """ @@ -356,25 +356,25 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): client = get_async_httpx_client(llm_provider=litellm.LlmProviders.RUNWAYML) start_time = time.time() - + # Build task status URL api_base = api_base.rstrip("/") task_url = f"{api_base}/v1/tasks/{task_id}" - + verbose_logger.debug(f"Polling RunwayML TTS task (async): {task_url}") - + while True: self._check_timeout(start_time=start_time, timeout_secs=timeout_secs) - + # Poll the task status response = await client.get(url=task_url, headers=headers) response.raise_for_status() - + response_data = response.json() - + # Check task status status = self._check_task_status(response_data=response_data) - + if status == "succeeded": return response elif status == "running": @@ -392,7 +392,7 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): ) -> TextToSpeechRequestData: """ Transform OpenAI TTS request to RunwayML TTS format - + RunwayML expects: - model: The model to use (e.g., 'eleven_multilingual_v2') - promptText: The text to convert to speech @@ -401,7 +401,7 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): "type": "runway-preset", "presetId": "Bernard" } - + Returns: TextToSpeechRequestData: Contains JSON body and headers """ @@ -413,19 +413,19 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): "type": self.DEFAULT_VOICE_TYPE, "presetId": self.DEFAULT_VOICE_PRESET_ID, } - + # Build request body request_body = { "model": model or self.DEFAULT_MODEL, "promptText": input, "voice": runwayml_voice, } - + # Add any other optional parameters (except runwayml_voice which we already used) for k, v in optional_params.items(): if k not in request_body and k != "runwayml_voice": request_body[k] = v - + return { "dict_body": request_body, "headers": headers, @@ -439,17 +439,17 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): ) -> "HttpxBinaryResponseContent": """ Transform RunwayML TTS response to standard format - + RunwayML returns a task immediately with status PENDING/RUNNING. We need to poll the task until it completes, then download the audio. - + Initial response: { "id": "task_123...", "status": "PENDING" | "RUNNING", "createdAt": "2025-11-13T..." } - + After polling: { "id": "task_123...", @@ -468,14 +468,14 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): status_code=raw_response.status_code, headers=dict(raw_response.headers), ) - + verbose_logger.debug("RunwayML TTS starting polling...") - + # Get task ID task_id = response_data.get("id") if not task_id: raise ValueError("RunwayML TTS response missing task ID") - + # Get headers for polling (need auth) poll_headers = { "Authorization": raw_response.request.headers.get("Authorization", ""), @@ -483,7 +483,7 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): "X-Runway-Version", RUNWAYML_DEFAULT_API_VERSION ), } - + # Poll until task completes polled_response = self._poll_task_sync( task_id=task_id, @@ -491,30 +491,30 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): headers=poll_headers, timeout_secs=RUNWAYML_POLLING_TIMEOUT, ) - + # Get the completed task data task_data = polled_response.json() - + verbose_logger.debug("RunwayML TTS polling complete, downloading audio") - + # Get audio URL from output output = task_data.get("output", []) if not output or not isinstance(output, list) or len(output) == 0: raise ValueError("RunwayML TTS response missing audio URL in output") - + audio_url = output[0] if not isinstance(audio_url, str): raise ValueError(f"RunwayML TTS audio URL is not a string: {audio_url}") - + # Download the audio file from litellm.llms.custom_httpx.http_handler import _get_httpx_client client = _get_httpx_client() audio_response = client.get(url=audio_url) audio_response.raise_for_status() - + verbose_logger.debug("RunwayML TTS audio downloaded successfully") - + # Return the audio data wrapped in HttpxBinaryResponseContent return HttpxBinaryResponseContent(audio_response) @@ -526,7 +526,7 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): ) -> "HttpxBinaryResponseContent": """ Async transform RunwayML TTS response to standard format - + Same as sync version but uses async polling and download """ from litellm.types.llms.openai import HttpxBinaryResponseContent @@ -539,14 +539,14 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): status_code=raw_response.status_code, headers=dict(raw_response.headers), ) - + verbose_logger.debug("RunwayML TTS starting polling (async)...") - + # Get task ID task_id = response_data.get("id") if not task_id: raise ValueError("RunwayML TTS response missing task ID") - + # Get headers for polling (need auth) poll_headers = { "Authorization": raw_response.request.headers.get("Authorization", ""), @@ -554,7 +554,7 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): "X-Runway-Version", RUNWAYML_DEFAULT_API_VERSION ), } - + # Poll until task completes (async) polled_response = await self._poll_task_async( task_id=task_id, @@ -562,30 +562,29 @@ class RunwayMLTextToSpeechConfig(BaseTextToSpeechConfig): headers=poll_headers, timeout_secs=RUNWAYML_POLLING_TIMEOUT, ) - + # Get the completed task data task_data = polled_response.json() - + verbose_logger.debug("RunwayML TTS polling complete (async), downloading audio") - + # Get audio URL from output output = task_data.get("output", []) if not output or not isinstance(output, list) or len(output) == 0: raise ValueError("RunwayML TTS response missing audio URL in output") - + audio_url = output[0] if not isinstance(audio_url, str): raise ValueError(f"RunwayML TTS audio URL is not a string: {audio_url}") - + # Download the audio file (async) from litellm.llms.custom_httpx.http_handler import get_async_httpx_client client = get_async_httpx_client(llm_provider=litellm.LlmProviders.RUNWAYML) audio_response = await client.get(url=audio_url) audio_response.raise_for_status() - + verbose_logger.debug("RunwayML TTS audio downloaded successfully (async)") - + # Return the audio data wrapped in HttpxBinaryResponseContent return HttpxBinaryResponseContent(audio_response) - diff --git a/litellm/llms/runwayml/videos/__init__.py b/litellm/llms/runwayml/videos/__init__.py index 9c72dec29a0..6d6f2b65e97 100644 --- a/litellm/llms/runwayml/videos/__init__.py +++ b/litellm/llms/runwayml/videos/__init__.py @@ -1,2 +1 @@ # RunwayML video generation - diff --git a/litellm/llms/runwayml/videos/transformation.py b/litellm/llms/runwayml/videos/transformation.py index 318a732dc2a..3fc656a92bd 100644 --- a/litellm/llms/runwayml/videos/transformation.py +++ b/litellm/llms/runwayml/videos/transformation.py @@ -33,7 +33,7 @@ else: class RunwayMLVideoConfig(BaseVideoConfig): """ Configuration class for RunwayML video generation. - + RunwayML uses a task-based API where: 1. POST /v1/image_to_video creates a task 2. The task returns immediately with a task ID @@ -70,43 +70,47 @@ class RunwayMLVideoConfig(BaseVideoConfig): ) -> Dict: """ Map OpenAI parameters to RunwayML format. - + Mappings: - prompt -> promptText - - input_reference -> promptImage + - input_reference -> promptImage - size -> ratio (convert "WIDTHxHEIGHT" to "WIDTH:HEIGHT") - seconds -> duration (convert to integer) """ mapped_params: Dict[str, Any] = {} - + # Handle input_reference parameter - map to promptImage if "input_reference" in video_create_optional_params: input_reference = video_create_optional_params["input_reference"] # RunwayML supports URLs and data URIs directly mapped_params["promptImage"] = input_reference - + # Handle size parameter - convert "1280x720" to "1280:720" if "size" in video_create_optional_params: size = video_create_optional_params["size"] if isinstance(size, str) and "x" in size: mapped_params["ratio"] = size.replace("x", ":") - + # Handle seconds parameter - convert to integer if "seconds" in video_create_optional_params: seconds = video_create_optional_params["seconds"] if seconds is not None: try: - mapped_params["duration"] = int(float(seconds)) if isinstance(seconds, str) else int(seconds) + mapped_params["duration"] = ( + int(float(seconds)) + if isinstance(seconds, str) + else int(seconds) + ) except (ValueError, TypeError): # If conversion fails, use default duration pass - + # Pass through other parameters that aren't OpenAI-specific supported_openai_params = self.get_supported_openai_params(model) for key, value in video_create_optional_params.items(): if key not in supported_openai_params: mapped_params[key] = value - + return mapped_params def validate_environment( @@ -123,25 +127,27 @@ class RunwayMLVideoConfig(BaseVideoConfig): # Use api_key from litellm_params if available, otherwise fall back to other sources if litellm_params and litellm_params.api_key: api_key = api_key or litellm_params.api_key - + api_key = ( api_key or litellm.api_key or get_secret_str("RUNWAYML_API_SECRET") or get_secret_str("RUNWAYML_API_KEY") ) - + if api_key is None: raise ValueError( "RunwayML API key is required. Set RUNWAYML_API_SECRET environment variable " "or pass api_key parameter." ) - - headers.update({ - "Authorization": f"Bearer {api_key}", - "X-Runway-Version": RUNWAYML_DEFAULT_API_VERSION, - "Content-Type": "application/json", - }) + + headers.update( + { + "Authorization": f"Bearer {api_key}", + "X-Runway-Version": RUNWAYML_DEFAULT_API_VERSION, + "Content-Type": "application/json", + } + ) return headers def get_complete_url( @@ -156,8 +162,8 @@ class RunwayMLVideoConfig(BaseVideoConfig): """ if api_base is None: api_base = "https://api.dev.runwayml.com/v1" - - return api_base.rstrip('/') + + return api_base.rstrip("/") def transform_video_create_request( self, @@ -170,7 +176,7 @@ class RunwayMLVideoConfig(BaseVideoConfig): ) -> Tuple[Dict, RequestFiles, str]: """ Transform the video creation request for RunwayML API. - + RunwayML expects: { "model": "gen4_turbo", @@ -179,22 +185,22 @@ class RunwayMLVideoConfig(BaseVideoConfig): "ratio": "1280:720", "duration": 5 } - """ + """ # Build the request data request_data: Dict[str, Any] = { "model": model, "promptText": prompt, } - + # Add mapped parameters request_data.update(video_create_optional_request_params) - + # RunwayML uses JSON body, no files multipart files_list: List[Tuple[str, Any]] = [] - + # Append the specific endpoint for video generation full_api_base = f"{api_base}/image_to_video" - + return request_data, files_list, full_api_base def transform_video_create_response( @@ -207,18 +213,18 @@ class RunwayMLVideoConfig(BaseVideoConfig): ) -> VideoObject: """ Transform the RunwayML video creation response. - + RunwayML returns a task object that looks like: { "id": "task_123...", "status": "PENDING" | "RUNNING" | "SUCCEEDED" | "FAILED", "output": ["https://...video.mp4"] (when succeeded) } - + We map this to OpenAI VideoObject format. """ response_data = raw_response.json() - + # Map RunwayML task response to VideoObject format video_data: Dict[str, Any] = { "id": response_data.get("id", ""), @@ -226,21 +232,27 @@ class RunwayMLVideoConfig(BaseVideoConfig): "status": self._map_runway_status(response_data.get("status", "pending")), "created_at": self._parse_runway_timestamp(response_data.get("createdAt")), } - + # Add optional fields if present if "output" in response_data and response_data["output"]: # RunwayML returns output as array of URLs when task succeeds - video_data["output_url"] = response_data["output"][0] if isinstance(response_data["output"], list) else response_data["output"] - + video_data["output_url"] = ( + response_data["output"][0] + if isinstance(response_data["output"], list) + else response_data["output"] + ) + if "completedAt" in response_data: - video_data["completed_at"] = self._parse_runway_timestamp(response_data.get("completedAt")) - + video_data["completed_at"] = self._parse_runway_timestamp( + response_data.get("completedAt") + ) + if "failureCode" in response_data or "failure" in response_data: video_data["error"] = { "code": response_data.get("failureCode", "unknown"), - "message": response_data.get("failure", "Video generation failed") + "message": response_data.get("failure", "Video generation failed"), } - + # Add model and size info if available from request if request_data: if "model" in request_data: @@ -252,27 +264,29 @@ class RunwayMLVideoConfig(BaseVideoConfig): video_data["size"] = ratio.replace(":", "x") if "duration" in request_data: video_data["seconds"] = str(request_data["duration"]) - + video_obj = VideoObject(**video_data) # type: ignore[arg-type] - + if custom_llm_provider and video_obj.id: - video_obj.id = encode_video_id_with_provider(video_obj.id, custom_llm_provider, model) - + video_obj.id = encode_video_id_with_provider( + video_obj.id, custom_llm_provider, model + ) + # Add usage data for cost tracking usage_data = {} - if video_obj and hasattr(video_obj, 'seconds') and video_obj.seconds: + if video_obj and hasattr(video_obj, "seconds") and video_obj.seconds: try: usage_data["duration_seconds"] = float(video_obj.seconds) except (ValueError, TypeError): pass video_obj.usage = usage_data - + return video_obj def _map_runway_status(self, runway_status: str) -> str: """ Map RunwayML status to OpenAI status format. - + RunwayML statuses: PENDING, RUNNING, SUCCEEDED, FAILED, CANCELLED OpenAI statuses: queued, in_progress, completed, failed """ @@ -285,20 +299,20 @@ class RunwayMLVideoConfig(BaseVideoConfig): "THROTTLED": "queued", } return status_map.get(runway_status.upper(), "queued") - + def _parse_runway_timestamp(self, timestamp_str: Optional[str]) -> int: """ Convert RunwayML ISO 8601 timestamp to Unix timestamp. - + RunwayML returns timestamps like: "2025-11-11T21:48:50.448Z" We need to convert to Unix timestamp (seconds since epoch). """ if not timestamp_str: return 0 - + try: # Parse ISO 8601 timestamp - dt = datetime.fromisoformat(timestamp_str.replace('Z', '+00:00')) + dt = datetime.fromisoformat(timestamp_str.replace("Z", "+00:00")) # Convert to Unix timestamp return int(dt.timestamp()) except (ValueError, AttributeError): @@ -320,12 +334,12 @@ class RunwayMLVideoConfig(BaseVideoConfig): We'll retrieve the task and extract the video URL. """ original_video_id = extract_original_video_id(video_id) - + # Get task status to retrieve video URL url = f"{api_base}/tasks/{original_video_id}" - + params: Dict[str, Any] = {} - + return url, params def _extract_video_url_from_response(self, response_data: Dict[str, Any]) -> str: @@ -338,18 +352,22 @@ class RunwayMLVideoConfig(BaseVideoConfig): if "output" in response_data and response_data["output"]: output = response_data["output"] video_url = output[0] if isinstance(output, list) else output - + if not video_url: # Check if the video generation failed or is still processing status = response_data.get("status", "UNKNOWN") if status in ["PENDING", "RUNNING", "THROTTLED"]: - raise ValueError(f"Video is still processing (status: {status}). Please wait and try again.") + raise ValueError( + f"Video is still processing (status: {status}). Please wait and try again." + ) elif status == "FAILED": failure_reason = response_data.get("failure", "Unknown error") raise ValueError(f"Video generation failed: {failure_reason}") else: - raise ValueError("Video URL not found in response. Video may not be ready yet.") - + raise ValueError( + "Video URL not found in response. Video may not be ready yet." + ) + return video_url def transform_video_content_response( @@ -359,10 +377,10 @@ class RunwayMLVideoConfig(BaseVideoConfig): ) -> bytes: """ Transform the RunwayML video content download response (synchronous). - + RunwayML's task endpoint returns JSON with a video URL in the output field. We need to extract the URL and download the video. - + Example response: { "id":"63fd0f13-f29d-4e58-99d3-1cb9efa14a5b", @@ -373,12 +391,12 @@ class RunwayMLVideoConfig(BaseVideoConfig): """ response_data = raw_response.json() video_url = self._extract_video_url_from_response(response_data) - + # Download the video from the CloudFront URL synchronously httpx_client: HTTPHandler = _get_httpx_client() video_response = httpx_client.get(video_url) video_response.raise_for_status() - + return video_response.content async def async_transform_video_content_response( @@ -388,10 +406,10 @@ class RunwayMLVideoConfig(BaseVideoConfig): ) -> bytes: """ Transform the RunwayML video content download response (asynchronous). - + RunwayML's task endpoint returns JSON with a video URL in the output field. We need to extract the URL and download the video asynchronously. - + Example response: { "id":"63fd0f13-f29d-4e58-99d3-1cb9efa14a5b", @@ -402,14 +420,14 @@ class RunwayMLVideoConfig(BaseVideoConfig): """ response_data = raw_response.json() video_url = self._extract_video_url_from_response(response_data) - + # Download the video from the CloudFront URL asynchronously async_httpx_client: AsyncHTTPHandler = get_async_httpx_client( llm_provider=litellm.LlmProviders.RUNWAYML, ) video_response = await async_httpx_client.get(video_url) video_response.raise_for_status() - + return video_response.content def transform_video_remix_request( @@ -423,7 +441,7 @@ class RunwayMLVideoConfig(BaseVideoConfig): ) -> Tuple[str, Dict]: """ Transform the video remix request for RunwayML API. - + RunwayML doesn't have a direct remix endpoint in their current API. This would need to be implemented when/if they add this feature. """ @@ -450,7 +468,7 @@ class RunwayMLVideoConfig(BaseVideoConfig): ) -> Tuple[str, Dict]: """ Transform the video list request for RunwayML API. - + RunwayML doesn't expose a list endpoint in their public API yet. """ raise NotImplementedError("Video listing is not yet supported by RunwayML API") @@ -473,16 +491,16 @@ class RunwayMLVideoConfig(BaseVideoConfig): ) -> Tuple[str, Dict]: """ Transform the video delete request for RunwayML API. - + RunwayML uses task cancellation. """ original_video_id = extract_original_video_id(video_id) - + # Construct the URL for task cancellation url = f"{api_base}/tasks/{original_video_id}/cancel" - + data: Dict[str, Any] = {} - + return url, data def transform_video_delete_response( @@ -492,7 +510,7 @@ class RunwayMLVideoConfig(BaseVideoConfig): ) -> VideoObject: """Transform the RunwayML video delete/cancel response.""" response_data = raw_response.json() - + video_obj = VideoObject( id=response_data.get("id", ""), object="video", @@ -511,17 +529,17 @@ class RunwayMLVideoConfig(BaseVideoConfig): ) -> Tuple[str, Dict]: """ Transform the RunwayML video status retrieve request. - + RunwayML uses GET /v1/tasks/{task_id} to retrieve task status. """ original_video_id = extract_original_video_id(video_id) - + # Construct the full URL for task status retrieval url = f"{api_base}/tasks/{original_video_id}" - + # Empty dict for GET request (no body) data: Dict[str, Any] = {} - + return url, data def transform_video_status_retrieve_response( @@ -534,7 +552,7 @@ class RunwayMLVideoConfig(BaseVideoConfig): Transform the RunwayML video status retrieve response. """ response_data = raw_response.json() - + # Map RunwayML task response to VideoObject format video_data: Dict[str, Any] = { "id": response_data.get("id", ""), @@ -542,27 +560,35 @@ class RunwayMLVideoConfig(BaseVideoConfig): "status": self._map_runway_status(response_data.get("status", "pending")), "created_at": self._parse_runway_timestamp(response_data.get("createdAt")), } - + # Add optional fields if present if "output" in response_data and response_data["output"]: - video_data["output_url"] = response_data["output"][0] if isinstance(response_data["output"], list) else response_data["output"] - + video_data["output_url"] = ( + response_data["output"][0] + if isinstance(response_data["output"], list) + else response_data["output"] + ) + if "completedAt" in response_data: - video_data["completed_at"] = self._parse_runway_timestamp(response_data.get("completedAt")) - + video_data["completed_at"] = self._parse_runway_timestamp( + response_data.get("completedAt") + ) + if "progress" in response_data: video_data["progress"] = response_data["progress"] - + if "failureCode" in response_data or "failure" in response_data: video_data["error"] = { "code": response_data.get("failureCode", "unknown"), - "message": response_data.get("failure", "Video generation failed") + "message": response_data.get("failure", "Video generation failed"), } - + video_obj = VideoObject(**video_data) # type: ignore[arg-type] - + if custom_llm_provider and video_obj.id: - video_obj.id = encode_video_id_with_provider(video_obj.id, custom_llm_provider, None) + video_obj.id = encode_video_id_with_provider( + video_obj.id, custom_llm_provider, None + ) return video_obj @@ -576,4 +602,3 @@ class RunwayMLVideoConfig(BaseVideoConfig): message=error_message, headers=headers, ) - diff --git a/litellm/llms/s3_vectors/vector_stores/transformation.py b/litellm/llms/s3_vectors/vector_stores/transformation.py index df81a78289a..11836e361ef 100644 --- a/litellm/llms/s3_vectors/vector_stores/transformation.py +++ b/litellm/llms/s3_vectors/vector_stores/transformation.py @@ -82,13 +82,15 @@ class S3VectorsVectorStoreConfig(BaseVectorStoreConfig, BaseAWSLLM): # If not in that format, try to construct it from litellm_params bucket_name: str index_name: str - + if ":" in vector_store_id: bucket_name, index_name = vector_store_id.split(":", 1) else: # Try to get bucket_name from litellm_params bucket_name_from_params = litellm_params.get("vector_bucket_name") - if not bucket_name_from_params or not isinstance(bucket_name_from_params, str): + if not bucket_name_from_params or not isinstance( + bucket_name_from_params, str + ): raise ValueError( "vector_store_id must be in format 'bucket_name:index_name' for S3 Vectors, " "or vector_bucket_name must be provided in litellm_params" @@ -100,10 +102,15 @@ class S3VectorsVectorStoreConfig(BaseVectorStoreConfig, BaseAWSLLM): query = " ".join(query) # Generate embedding for the query - embedding_model = litellm_params.get("embedding_model", "text-embedding-3-small") - + embedding_model = litellm_params.get( + "embedding_model", "text-embedding-3-small" + ) + import litellm as litellm_module - embedding_response = litellm_module.embedding(model=embedding_model, input=[query]) + + embedding_response = litellm_module.embedding( + model=embedding_model, input=[query] + ) query_embedding = embedding_response.data[0]["embedding"] url = f"{api_base}/QueryVectors" @@ -112,7 +119,9 @@ class S3VectorsVectorStoreConfig(BaseVectorStoreConfig, BaseAWSLLM): "vectorBucketName": bucket_name, "indexName": index_name, "queryVector": {"float32": query_embedding}, - "topK": vector_store_search_optional_params.get("max_num_results", 5), # Default to 5 + "topK": vector_store_search_optional_params.get( + "max_num_results", 5 + ), # Default to 5 "returnDistance": True, "returnMetadata": True, } @@ -134,13 +143,15 @@ class S3VectorsVectorStoreConfig(BaseVectorStoreConfig, BaseAWSLLM): # If not in that format, try to construct it from litellm_params bucket_name: str index_name: str - + if ":" in vector_store_id: bucket_name, index_name = vector_store_id.split(":", 1) else: # Try to get bucket_name from litellm_params bucket_name_from_params = litellm_params.get("vector_bucket_name") - if not bucket_name_from_params or not isinstance(bucket_name_from_params, str): + if not bucket_name_from_params or not isinstance( + bucket_name_from_params, str + ): raise ValueError( "vector_store_id must be in format 'bucket_name:index_name' for S3 Vectors, " "or vector_bucket_name must be provided in litellm_params" @@ -152,10 +163,15 @@ class S3VectorsVectorStoreConfig(BaseVectorStoreConfig, BaseAWSLLM): query = " ".join(query) # Generate embedding for the query asynchronously - embedding_model = litellm_params.get("embedding_model", "text-embedding-3-small") - + embedding_model = litellm_params.get( + "embedding_model", "text-embedding-3-small" + ) + import litellm as litellm_module - embedding_response = await litellm_module.aembedding(model=embedding_model, input=[query]) + + embedding_response = await litellm_module.aembedding( + model=embedding_model, input=[query] + ) query_embedding = embedding_response.data[0]["embedding"] url = f"{api_base}/QueryVectors" @@ -164,7 +180,9 @@ class S3VectorsVectorStoreConfig(BaseVectorStoreConfig, BaseAWSLLM): "vectorBucketName": bucket_name, "indexName": index_name, "queryVector": {"float32": query_embedding}, - "topK": vector_store_search_optional_params.get("max_num_results", 5), # Default to 5 + "topK": vector_store_search_optional_params.get( + "max_num_results", 5 + ), # Default to 5 "returnDistance": True, "returnMetadata": True, } @@ -223,7 +241,9 @@ class S3VectorsVectorStoreConfig(BaseVectorStoreConfig, BaseAWSLLM): results.append( VectorStoreSearchResult( score=score, - content=[VectorStoreResultContent(text=source_text, type="text")], + content=[ + VectorStoreResultContent(text=source_text, type="text") + ], file_id=file_id, filename=filename, attributes=metadata, diff --git a/litellm/llms/sagemaker/completion/handler.py b/litellm/llms/sagemaker/completion/handler.py index 2a30dc5ef38..efbb218f575 100644 --- a/litellm/llms/sagemaker/completion/handler.py +++ b/litellm/llms/sagemaker/completion/handler.py @@ -583,35 +583,17 @@ class SagemakerLLM(BaseAWSLLM): ### BOTO3 INIT import boto3 - # pop aws_secret_access_key, aws_access_key_id, aws_region_name from kwargs, since completion calls fail with them - aws_secret_access_key = optional_params.pop("aws_secret_access_key", None) - aws_access_key_id = optional_params.pop("aws_access_key_id", None) - aws_region_name = optional_params.pop("aws_region_name", None) + # Use _load_credentials to support role assumption (aws_role_name, aws_session_name) + credentials, aws_region_name = self._load_credentials(optional_params) - if aws_access_key_id is not None: - # uses auth params passed to completion - # aws_access_key_id is not None, assume user is trying to auth using litellm.completion - client = boto3.client( - service_name="sagemaker-runtime", - aws_access_key_id=aws_access_key_id, - aws_secret_access_key=aws_secret_access_key, - region_name=aws_region_name, - ) - else: - # aws_access_key_id is None, assume user is trying to auth using env variables - # boto3 automaticaly reads env variables - - # we need to read region name from env - # I assume majority of users use .env for auth - region_name = ( - get_secret("AWS_REGION_NAME") - or aws_region_name # get region from config file if specified - or "us-west-2" # default to us-west-2 if region not specified - ) - client = boto3.client( - service_name="sagemaker-runtime", - region_name=region_name, - ) + # Create boto3 session with the loaded credentials + session = boto3.Session( + aws_access_key_id=credentials.access_key, + aws_secret_access_key=credentials.secret_key, + aws_session_token=credentials.token, + region_name=aws_region_name, + ) + client = session.client(service_name="sagemaker-runtime") # pop streaming if it's in the optional params as 'stream' raises an error with sagemaker inference_params = deepcopy(optional_params) @@ -628,7 +610,9 @@ class SagemakerLLM(BaseAWSLLM): #### EMBEDDING LOGIC # Transform request based on model type provider_config = SagemakerEmbeddingConfig.get_model_config(model) - request_data = provider_config.transform_embedding_request(model, input, optional_params, {}) + request_data = provider_config.transform_embedding_request( + model, input, optional_params, {} + ) data = json.dumps(request_data).encode("utf-8") ## LOGGING @@ -673,19 +657,19 @@ class SagemakerLLM(BaseAWSLLM): ) print_verbose(f"raw model_response: {response}") - + # Transform response based on model type from httpx import Response as HttpxResponse - + # Create a mock httpx Response object for the transformation mock_response = HttpxResponse( status_code=200, - content=json.dumps(response).encode('utf-8'), - headers={"content-type": "application/json"} + content=json.dumps(response).encode("utf-8"), + headers={"content-type": "application/json"}, ) - + model_response = EmbeddingResponse() - + # Use the request_data that was already transformed above return provider_config.transform_embedding_response( model=model, @@ -695,5 +679,5 @@ class SagemakerLLM(BaseAWSLLM): api_key=None, request_data=request_data, optional_params=optional_params, - litellm_params=litellm_params or {} + litellm_params=litellm_params or {}, ) diff --git a/litellm/llms/sagemaker/completion/transformation.py b/litellm/llms/sagemaker/completion/transformation.py index 42202bbf079..dd7cb603905 100644 --- a/litellm/llms/sagemaker/completion/transformation.py +++ b/litellm/llms/sagemaker/completion/transformation.py @@ -68,7 +68,15 @@ class SagemakerConfig(BaseConfig): ) def get_supported_openai_params(self, model: str) -> List: - return ["stream", "temperature", "max_tokens", "max_completion_tokens", "top_p", "stop", "n"] + return [ + "stream", + "temperature", + "max_tokens", + "max_completion_tokens", + "top_p", + "stop", + "n", + ] def map_openai_params( self, @@ -278,5 +286,3 @@ class SagemakerConfig(BaseConfig): headers = {"Content-Type": "application/json", **headers} return headers - - diff --git a/litellm/llms/sagemaker/embedding/transformation.py b/litellm/llms/sagemaker/embedding/transformation.py index 04b201380fc..04430171187 100644 --- a/litellm/llms/sagemaker/embedding/transformation.py +++ b/litellm/llms/sagemaker/embedding/transformation.py @@ -23,7 +23,7 @@ class SagemakerEmbeddingConfig(BaseEmbeddingConfig): """ SageMaker embedding configuration factory for supporting embedding parameters """ - + def __init__(self) -> None: pass @@ -31,10 +31,10 @@ class SagemakerEmbeddingConfig(BaseEmbeddingConfig): def get_model_config(cls, model: str) -> "BaseEmbeddingConfig": """ Factory method to get the appropriate embedding config based on model type - + Args: model: The model name - + Returns: Appropriate embedding config instance """ @@ -57,7 +57,6 @@ class SagemakerEmbeddingConfig(BaseEmbeddingConfig): model: str, drop_params: bool, ) -> dict: - return optional_params def get_error_class( @@ -98,8 +97,8 @@ class SagemakerEmbeddingConfig(BaseEmbeddingConfig): response_data = raw_response.json() except Exception as e: raise SagemakerError( - message=f"Failed to parse response: {str(e)}", - status_code=raw_response.status_code + message=f"Failed to parse response: {str(e)}", + status_code=raw_response.status_code, ) # Handle both raw array format (TEI) and wrapped format (standard HF) diff --git a/litellm/llms/sambanova/chat.py b/litellm/llms/sambanova/chat.py index 2218c808721..3c4003f72e9 100644 --- a/litellm/llms/sambanova/chat.py +++ b/litellm/llms/sambanova/chat.py @@ -117,10 +117,11 @@ class SambanovaConfig(OpenAIGPTConfig): ) -> Union[List[AllMessageValues], Coroutine[Any, Any, List[AllMessageValues]]]: """ Transform messages to handle content list conversion. - + SambaNova API doesn't support content as a list - only string content. This converts content lists like [{"type": "text", "text": "..."}] to strings. """ + async def _async_transform(): return handle_messages_with_content_list_to_str_conversion(messages) diff --git a/litellm/llms/sap/chat/handler.py b/litellm/llms/sap/chat/handler.py index 1390b2a4785..713143d895f 100755 --- a/litellm/llms/sap/chat/handler.py +++ b/litellm/llms/sap/chat/handler.py @@ -251,11 +251,8 @@ class AsyncSAPStreamIterator: # ------------------------------- class GenAIHubOrchestration(BaseLLMHTTPHandler): def _add_stream_param_to_request_body( - self, - data: dict, - provider_config: BaseConfig, - fake_stream: bool - ): + self, data: dict, provider_config: BaseConfig, fake_stream: bool + ): if data.get("config", {}).get("stream", None) is not None: data["config"]["stream"]["enabled"] = True else: diff --git a/litellm/llms/sap/chat/models.py b/litellm/llms/sap/chat/models.py index 1b09ce9a756..8ca2aa7a690 100644 --- a/litellm/llms/sap/chat/models.py +++ b/litellm/llms/sap/chat/models.py @@ -7,21 +7,22 @@ def validate_different_content(v: Union[str, dict, list]) -> str: if v in ((), {}, []): return "" elif isinstance(v, dict) and "text" in v: - return v['text'] + return v["text"] elif isinstance(v, list): new_v = [] for item in v: if isinstance(item, dict) and "text" in item: - if item['text']: - new_v.append(item['text']) + if item["text"]: + new_v.append(item["text"]) elif isinstance(item, str): new_v.append(item) - return '\n'.join(new_v) + return "\n".join(new_v) elif isinstance(v, str): return v raise ValueError("Content must be a string") return v + class TextContent(BaseModel): type_: Literal["text"] = Field(default="text", alias="type") text: str @@ -80,7 +81,9 @@ class SAPMessage(BaseModel): role: Literal["system", "developer"] = "system" content: str - _content_validator = field_validator("content", mode="before")(validate_different_content) + _content_validator = field_validator("content", mode="before")( + validate_different_content + ) class SAPUserMessage(BaseModel): @@ -96,8 +99,9 @@ class SAPAssistantMessage(BaseModel): refusal: str = "" tool_calls: list[MessageToolCall] = [] - _content_validator = field_validator("content", mode="before")(validate_different_content) - + _content_validator = field_validator("content", mode="before")( + validate_different_content + ) class SAPToolChatMessage(BaseModel): @@ -105,7 +109,9 @@ class SAPToolChatMessage(BaseModel): tool_call_id: str content: str - _content_validator = field_validator("content", mode="before")(validate_different_content) + _content_validator = field_validator("content", mode="before")( + validate_different_content + ) class ResponseFormat(BaseModel): diff --git a/litellm/llms/sap/chat/transformation.py b/litellm/llms/sap/chat/transformation.py index a019ba1767a..7f6bab4a1d5 100755 --- a/litellm/llms/sap/chat/transformation.py +++ b/litellm/llms/sap/chat/transformation.py @@ -1,7 +1,17 @@ """ Translate from OpenAI's `/v1/chat/completions` to SAP Generative AI Hub's Orchestration Service`v2/completion` """ -from typing import List, Optional, Union, Dict, Tuple, Any, TYPE_CHECKING, Iterator, AsyncIterator +from typing import ( + List, + Optional, + Union, + Dict, + Tuple, + Any, + TYPE_CHECKING, + Iterator, + AsyncIterator, +) from functools import cached_property import litellm import httpx @@ -29,7 +39,12 @@ from .models import ( ResponseFormat, SAPUserMessage, ) -from .handler import GenAIHubOrchestrationError, AsyncSAPStreamIterator, SAPStreamIterator +from .handler import ( + GenAIHubOrchestrationError, + AsyncSAPStreamIterator, + SAPStreamIterator, +) + def validate_dict(data: dict, model) -> dict: return model(**data).model_dump(by_alias=True) @@ -77,16 +92,15 @@ class GenAIHubOrchestrationConfig(OpenAIGPTConfig): def run_env_setup(self, service_key: Optional[str] = None) -> None: try: - self.token_creator, self._base_url, self._resource_group = get_token_creator(service_key) # type: ignore + self.token_creator, self._base_url, self._resource_group = get_token_creator(service_key) # type: ignore except ValueError as err: raise GenAIHubOrchestrationError(status_code=400, message=err.args[0]) - @property def headers(self) -> Dict[str, str]: if self.token_creator is None: self.run_env_setup() - access_token = self.token_creator() # type: ignore + access_token = self.token_creator() # type: ignore return { "Authorization": access_token, "AI-Resource-Group": self.resource_group, @@ -98,14 +112,13 @@ class GenAIHubOrchestrationConfig(OpenAIGPTConfig): def base_url(self) -> str: if self._base_url is None: self.run_env_setup() - return self._base_url # type: ignore - + return self._base_url # type: ignore @property def resource_group(self) -> str: if self._resource_group is None: self.run_env_setup() - return self._resource_group # type: ignore + return self._resource_group # type: ignore @cached_property def deployment_url(self) -> str: @@ -169,7 +182,6 @@ class GenAIHubOrchestrationConfig(OpenAIGPTConfig): params.remove("tool_choice") return params - def validate_environment( self, headers: dict, @@ -185,13 +197,13 @@ class GenAIHubOrchestrationConfig(OpenAIGPTConfig): return self.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, + self, + api_base: Optional[str], + api_key: Optional[str], + model: str, + optional_params: dict, + litellm_params: dict, + stream: Optional[bool] = None, ): api_base_ = f"{self.deployment_url}/v2/completion" return api_base_ @@ -199,7 +211,7 @@ class GenAIHubOrchestrationConfig(OpenAIGPTConfig): def transform_request( self, model: str, - messages: List[Dict[str, str]], # type: ignore + messages: List[Dict[str, str]], # type: ignore optional_params: dict, litellm_params: dict, headers: dict, @@ -240,8 +252,10 @@ class GenAIHubOrchestrationConfig(OpenAIGPTConfig): response_format = model_params.pop("response_format", {}) resp_type = response_format.get("type", None) if resp_type: - if resp_type== "json_schema": - response_format = validate_dict(response_format, ResponseFormatJSONSchema) + if resp_type == "json_schema": + response_format = validate_dict( + response_format, ResponseFormatJSONSchema + ) else: response_format = validate_dict(response_format, ResponseFormat) response_format = {"response_format": response_format} @@ -259,11 +273,7 @@ class GenAIHubOrchestrationConfig(OpenAIGPTConfig): "config": { "modules": { "prompt_templating": { - "prompt": { - "template": template, - **tools, - **response_format - }, + "prompt": {"template": template, **tools, **response_format}, "model": { "name": model, "params": model_params, @@ -278,18 +288,18 @@ class GenAIHubOrchestrationConfig(OpenAIGPTConfig): return config def transform_response( - self, - model: str, - raw_response: httpx.Response, - model_response: ModelResponse, - logging_obj: LiteLLMLoggingObj, - request_data: dict, - messages: List[AllMessageValues], - optional_params: dict, - litellm_params: dict, - encoding: Any, - api_key: Optional[str] = None, - json_mode: Optional[bool] = None, + self, + model: str, + raw_response: httpx.Response, + model_response: ModelResponse, + logging_obj: LiteLLMLoggingObj, + 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: logging_obj.post_call( input=messages, @@ -323,17 +333,17 @@ class GenAIHubOrchestrationConfig(OpenAIGPTConfig): if choice.message and choice.message.content: content = choice.message.content.strip() # Match ```json ... ``` or ``` ... ``` - match = re.match(r'^```(?:json)?\s*\n?(.*?)\n?```$', content, re.DOTALL) + match = re.match(r"^```(?:json)?\s*\n?(.*?)\n?```$", content, re.DOTALL) if match: choice.message.content = match.group(1).strip() return response def get_model_response_iterator( - self, - streaming_response: Union[Iterator[str], AsyncIterator[str], "ModelResponse"], - sync_stream: bool, - json_mode: Optional[bool] = False, + self, + streaming_response: Union[Iterator[str], AsyncIterator[str], "ModelResponse"], + sync_stream: bool, + json_mode: Optional[bool] = False, ): if sync_stream: return SAPStreamIterator(response=streaming_response) # type: ignore diff --git a/litellm/llms/sap/credentials.py b/litellm/llms/sap/credentials.py index e10bcbf7eae..aeae51bf0bb 100644 --- a/litellm/llms/sap/credentials.py +++ b/litellm/llms/sap/credentials.py @@ -180,7 +180,9 @@ def _resolve_value( return cred.default -def fetch_credentials(service_key: Optional[str] = None, profile: Optional[str] = None, **kwargs) -> Dict[str, str]: +def fetch_credentials( + service_key: Optional[str] = None, profile: Optional[str] = None, **kwargs +) -> Dict[str, str]: """ Resolution order per key: kwargs @@ -196,8 +198,11 @@ def fetch_credentials(service_key: Optional[str] = None, profile: Optional[str] if not config: # Prefer AICORE_SERVICE_KEY if present; otherwise fall back to the VCAP service. - service_like = service_key or sap_service_key or _load_json_env(SERVICE_KEY_ENV_VAR) or _get_vcap_service( - VCAP_AICORE_SERVICE_NAME + service_like = ( + service_key + or sap_service_key + or _load_json_env(SERVICE_KEY_ENV_VAR) + or _get_vcap_service(VCAP_AICORE_SERVICE_NAME) ) out: Dict[str, str] = {} @@ -241,7 +246,9 @@ def get_token_creator( """ # Resolve credentials using your helper - credentials: Dict[str, str] = fetch_credentials(service_key=service_key, profile=profile, **overrides) + credentials: Dict[str, str] = fetch_credentials( + service_key=service_key, profile=profile, **overrides + ) auth_url = credentials.get("auth_url") client_id = credentials.get("client_id") diff --git a/litellm/llms/searchapi/search/transformation.py b/litellm/llms/searchapi/search/transformation.py index f3333bb20c9..92b2814018d 100644 --- a/litellm/llms/searchapi/search/transformation.py +++ b/litellm/llms/searchapi/search/transformation.py @@ -19,6 +19,7 @@ from litellm.secret_managers.main import get_secret_str class _SearchAPIRequestRequired(TypedDict): """Required fields for SearchAPI.io request.""" + engine: str # Required - search engine (e.g., 'google') q: str # Required - search query @@ -28,6 +29,7 @@ class SearchAPIRequest(_SearchAPIRequestRequired, total=False): SearchAPI.io request format for Google Search. Based on: https://www.searchapi.io/docs/google """ + kgmid: str # Optional - Knowledge Graph identifier device: str # Optional - device type ('desktop', 'mobile', 'tablet') location: str # Optional - geographic location @@ -50,17 +52,17 @@ class SearchAPIRequest(_SearchAPIRequestRequired, total=False): class SearchAPIConfig(BaseSearchConfig): SEARCHAPI_API_BASE = "https://www.searchapi.io/api/v1/search" - + @staticmethod def ui_friendly_name() -> str: return "SearchAPI.io (Google Search)" - + def get_http_method(self) -> Literal["GET", "POST"]: """ SearchAPI.io uses GET requests for search. """ return "GET" - + def validate_environment( self, headers: Dict, @@ -72,14 +74,14 @@ class SearchAPIConfig(BaseSearchConfig): Validate environment and return headers. """ api_key = api_key or get_secret_str("SEARCHAPI_API_KEY") - + if not api_key: raise ValueError( "SEARCHAPI_API_KEY is not set. Set `SEARCHAPI_API_KEY` environment variable." ) - + headers["Content-Type"] = "application/json" - + return headers def get_complete_url( @@ -94,7 +96,9 @@ class SearchAPIConfig(BaseSearchConfig): SearchAPI.io uses GET requests and includes api_key in query params. """ - api_base = api_base or get_secret_str("SEARCHAPI_API_BASE") or self.SEARCHAPI_API_BASE + api_base = ( + api_base or get_secret_str("SEARCHAPI_API_BASE") or self.SEARCHAPI_API_BASE + ) # Build query parameters from the transformed request body if data and isinstance(data, dict) and "_searchapi_params" in data: @@ -197,7 +201,7 @@ class SearchAPIConfig(BaseSearchConfig): ) -> SearchResponse: """ Transform SearchAPI.io response to LiteLLM unified SearchResponse format. - + SearchAPI.io → LiteLLM mappings: - organic_results[].title → SearchResult.title - organic_results[].link → SearchResult.url @@ -215,7 +219,7 @@ class SearchAPIConfig(BaseSearchConfig): url = result.get("link", "") snippet = result.get("snippet", "") date = result.get("date") # SearchAPI.io provides date in some results - + search_result = SearchResult( title=title, url=url, diff --git a/litellm/llms/searxng/__init__.py b/litellm/llms/searxng/__init__.py index 91d237a8a08..f7ad1978c76 100644 --- a/litellm/llms/searxng/__init__.py +++ b/litellm/llms/searxng/__init__.py @@ -4,4 +4,3 @@ SearXNG API integration module. from litellm.llms.searxng.search.transformation import SearXNGSearchConfig __all__ = ["SearXNGSearchConfig"] - diff --git a/litellm/llms/searxng/search/__init__.py b/litellm/llms/searxng/search/__init__.py index cb6fccfa9d5..88ac5dc629b 100644 --- a/litellm/llms/searxng/search/__init__.py +++ b/litellm/llms/searxng/search/__init__.py @@ -4,4 +4,3 @@ SearXNG Search API module. from litellm.llms.searxng.search.transformation import SearXNGSearchConfig __all__ = ["SearXNGSearchConfig"] - diff --git a/litellm/llms/searxng/search/transformation.py b/litellm/llms/searxng/search/transformation.py index 00ad9d19485..bbd3b765010 100644 --- a/litellm/llms/searxng/search/transformation.py +++ b/litellm/llms/searxng/search/transformation.py @@ -18,6 +18,7 @@ from litellm.secret_managers.main import get_secret_str class _SearXNGSearchRequestRequired(TypedDict): """Required fields for SearXNG Search API request.""" + q: str # Required - search query @@ -26,6 +27,7 @@ class SearXNGSearchRequest(_SearXNGSearchRequestRequired, total=False): SearXNG Search API request format. Based on: https://docs.searxng.org/dev/search_api.html """ + categories: str # Optional - comma-separated list of categories engines: str # Optional - comma-separated list of engines language: str # Optional - language code @@ -35,17 +37,16 @@ class SearXNGSearchRequest(_SearXNGSearchRequestRequired, total=False): class SearXNGSearchConfig(BaseSearchConfig): - @staticmethod def ui_friendly_name() -> str: return "SearXNG" - + def get_http_method(self): """ SearXNG supports both GET and POST, but we'll use GET for simplicity. """ return "GET" - + def validate_environment( self, headers: Dict, @@ -74,27 +75,27 @@ class SearXNGSearchConfig(BaseSearchConfig): ) -> str: """ Get complete URL for Search endpoint with query parameters. - + SearXNG uses GET requests, so we build the full URL with query params here. The transformed request body (data) contains the parameters needed for the URL. """ from urllib.parse import urlencode - + api_base = api_base or get_secret_str("SEARXNG_API_BASE") - + if not api_base: raise ValueError( "SEARXNG_API_BASE is not set. Please set the `SEARXNG_API_BASE` environment variable " "or pass `api_base` parameter. Example: os.environ['SEARXNG_API_BASE'] = 'https://your-searxng-instance.com'" ) - + # Append "/search" to the api base if it's not already there if not api_base.endswith("/search"): if api_base.endswith("/"): api_base = f"{api_base}search" else: api_base = f"{api_base}/search" - + # Build query parameters from the transformed request body if data and isinstance(data, dict) and "_searxng_params" in data: params = data["_searxng_params"] @@ -102,7 +103,6 @@ class SearXNGSearchConfig(BaseSearchConfig): return f"{api_base}?{query_string}" return api_base - def transform_search_request( self, @@ -112,20 +112,20 @@ class SearXNGSearchConfig(BaseSearchConfig): ) -> Dict: """ Transform Search request to SearXNG API format. - + Transforms Perplexity unified spec parameters: - query → q - max_results → (handled via pageno, SearXNG returns ~20 results per page) - search_domain_filter → (not directly supported) - country → language (approximate mapping) - max_tokens_per_page → (not applicable, ignored) - + All other SearXNG-specific parameters are passed through as-is. - + Args: query: Search query (string or list of strings). SearXNG only supports single string queries. optional_params: Optional parameters for the request - + Returns: Dict with typed request data following SearXNGSearchRequest spec """ @@ -137,7 +137,7 @@ class SearXNGSearchConfig(BaseSearchConfig): "q": query, "format": "json", # Always request JSON format } - + # Transform Perplexity unified spec parameters to SearXNG format if "country" in optional_params: # Map country code to language (approximate) @@ -154,22 +154,25 @@ class SearXNGSearchConfig(BaseSearchConfig): request_data["language"] = "ja" else: request_data["language"] = country # Pass through as-is - + # Handle max_results via pagination (SearXNG returns ~20 results per page by default) # For simplicity, we'll just use page 1 and let SearXNG return its default number of results if "max_results" in optional_params: # Note: We could calculate pageno based on max_results, but for now we'll ignore this # and let SearXNG return its default results pass - + # Convert to dict before dynamic key assignments result_data = dict(request_data) - + # Pass through all other SearXNG-specific parameters as-is for param, value in optional_params.items(): - if param not in self.get_supported_perplexity_optional_params() and param not in result_data: + if ( + param not in self.get_supported_perplexity_optional_params() + and param not in result_data + ): result_data[param] = value - + # Store params in special key for GET request URL building # This will be used by get_complete_url to build the query string return {"_searxng_params": result_data} @@ -182,23 +185,23 @@ class SearXNGSearchConfig(BaseSearchConfig): ) -> SearchResponse: """ Transform SearXNG API response to LiteLLM unified SearchResponse format. - + SearXNG → LiteLLM mappings: - results[].title → SearchResult.title - results[].url → SearchResult.url - results[].content → SearchResult.snippet - results[].publishedDate OR results[].pubdate → SearchResult.date - No last_updated field in SearXNG response (set to None) - + Args: raw_response: Raw httpx response from SearXNG API logging_obj: Logging object for tracking - + Returns: SearchResponse with standardized format """ response_json = raw_response.json() - + # Transform results to SearchResult objects # Note: SearXNG doesn't natively support limiting results via API params # It returns ~20 results per page by default @@ -206,7 +209,7 @@ class SearXNGSearchConfig(BaseSearchConfig): for result in response_json.get("results", []): # Get date from either publishedDate or pubdate field date = result.get("publishedDate") or result.get("pubdate") - + search_result = SearchResult( title=result.get("title", ""), url=result.get("url", ""), @@ -215,9 +218,8 @@ class SearXNGSearchConfig(BaseSearchConfig): last_updated=None, # SearXNG doesn't provide last_updated in response ) results.append(search_result) - + return SearchResponse( results=results, object="search", ) - diff --git a/litellm/llms/serper/search/transformation.py b/litellm/llms/serper/search/transformation.py index 63526ea8aba..34e726dc77d 100644 --- a/litellm/llms/serper/search/transformation.py +++ b/litellm/llms/serper/search/transformation.py @@ -18,6 +18,7 @@ from litellm.secret_managers.main import get_secret_str class _SerperSearchRequestRequired(TypedDict): """Required fields for Serper Search API request.""" + q: str # Required - search query @@ -26,6 +27,7 @@ class SerperSearchRequest(_SerperSearchRequestRequired, total=False): Serper Search API request format. Based on: https://serper.dev """ + num: int # Optional - number of results to return, default 10 page: int # Optional - page number (default 1) gl: str # Optional - country/geolocation code (e.g., "us", "gb") @@ -37,11 +39,11 @@ class SerperSearchRequest(_SerperSearchRequestRequired, total=False): class SerperSearchConfig(BaseSearchConfig): SERPER_API_BASE = "https://google.serper.dev" - + @staticmethod def ui_friendly_name() -> str: return "Serper" - + def validate_environment( self, headers: Dict, @@ -54,7 +56,9 @@ class SerperSearchConfig(BaseSearchConfig): """ api_key = api_key or get_secret_str("SERPER_API_KEY") if not api_key: - raise ValueError("SERPER_API_KEY is not set. Set `SERPER_API_KEY` environment variable.") + raise ValueError( + "SERPER_API_KEY is not set. Set `SERPER_API_KEY` environment variable." + ) headers["X-API-KEY"] = api_key headers["Content-Type"] = "application/json" return headers @@ -71,7 +75,7 @@ class SerperSearchConfig(BaseSearchConfig): """ api_base = api_base or get_secret_str("SERPER_API_BASE") or self.SERPER_API_BASE api_base = api_base.rstrip("/") - + if not api_base.endswith("/search"): api_base = f"{api_base}/search" @@ -85,14 +89,14 @@ class SerperSearchConfig(BaseSearchConfig): ) -> Dict: """ Transform Search request to Serper API format. - + Args: query: Search query (string or list of strings). Serper only supports single string queries. optional_params: Optional parameters for the request - max_results: Maximum number of search results -> maps to `num` - search_domain_filter: List of domains -> appended as site: clauses to `q` - country: Country code filter (e.g., 'US', 'GB') -> maps to `gl` (lowercased) - + Returns: Dict with typed request data following SerperSearchRequest spec """ @@ -102,27 +106,30 @@ class SerperSearchConfig(BaseSearchConfig): request_data: SerperSearchRequest = { "q": query, } - + if "max_results" in optional_params: request_data["num"] = optional_params["max_results"] - + if "country" in optional_params: request_data["gl"] = optional_params["country"].lower() - + if "search_domain_filter" in optional_params: domains = optional_params["search_domain_filter"] if isinstance(domains, list) and len(domains) > 0: domain_clauses = " OR ".join(f"site:{d}" for d in domains) request_data["q"] = f"({request_data['q']}) ({domain_clauses})" - + # Convert to dict before dynamic key assignments result_data = dict(request_data) - + # pass through all other parameters as-is for param, value in optional_params.items(): - if param not in self.get_supported_perplexity_optional_params() and param not in result_data: + if ( + param not in self.get_supported_perplexity_optional_params() + and param not in result_data + ): result_data[param] = value - + return result_data def transform_search_response( @@ -133,22 +140,22 @@ class SerperSearchConfig(BaseSearchConfig): ) -> SearchResponse: """ Transform Serper API response to LiteLLM unified SearchResponse format. - + Serper -> LiteLLM mappings: - organic[].title -> SearchResult.title - organic[].link -> SearchResult.url - organic[].snippet -> SearchResult.snippet - organic[].date -> SearchResult.date (optional, not always present) - + Args: raw_response: Raw httpx response from Serper API logging_obj: Logging object for tracking - + Returns: SearchResponse with standardized format """ response_json = raw_response.json() - + results = [] for result in response_json.get("organic", []): search_result = SearchResult( @@ -159,9 +166,8 @@ class SerperSearchConfig(BaseSearchConfig): last_updated=None, ) results.append(search_result) - + return SearchResponse( results=results, object="search", ) - diff --git a/litellm/llms/snowflake/chat/transformation.py b/litellm/llms/snowflake/chat/transformation.py index e11cab4138d..3e590680a75 100644 --- a/litellm/llms/snowflake/chat/transformation.py +++ b/litellm/llms/snowflake/chat/transformation.py @@ -219,17 +219,32 @@ class SnowflakeConfig(SnowflakeBaseConfig, OpenAIGPTConfig): tool_choice: Tool choice in OpenAI format (str or dict) Returns: - Tool choice in Snowflake format (always an object) + Tool choice in Snowflake format (always an object, never a string) - OpenAI format (string): "auto", "required", "none" - OpenAI format (object): {"type": "function", "function": {"name": "get_weather"}} + OpenAI format (string): + "auto", "required", "none" - Snowflake format (string values become objects): {"type": "auto"} - Snowflake format (specific tool): {"type": "tool", "name": ["get_weather"]} + OpenAI format (dict): + {"type": "function", "function": {"name": "get_weather"}} + + Snowflake format: + {"type": "auto"} / {"type": "any"} / {"type": "none"} + {"type": "tool", "name": ["get_weather"]} + + Snowflake's API (like Anthropic) requires tool_choice as an object + with a "type" field, not as a bare string. """ if isinstance(tool_choice, str): - # Snowflake requires object format: {"type": "auto"} not string "auto" - return {"type": tool_choice} + # Snowflake requires object format, not string. + # Map OpenAI string values to Snowflake object format. + # "required" maps to "any" (Snowflake/Anthropic convention). + _type_map = { + "auto": "auto", + "required": "any", + "none": "none", + } + mapped_type = _type_map.get(tool_choice, tool_choice) + return {"type": mapped_type} if isinstance(tool_choice, dict): if tool_choice.get("type") == "function": diff --git a/litellm/llms/stability/image_edit/transformations.py b/litellm/llms/stability/image_edit/transformations.py index 53bdc825dd4..eb400a2526e 100644 --- a/litellm/llms/stability/image_edit/transformations.py +++ b/litellm/llms/stability/image_edit/transformations.py @@ -40,9 +40,7 @@ class StabilityImageEditConfig(BaseImageEditConfig): DEFAULT_BASE_URL: str = "https://api.stability.ai" - def get_supported_openai_params( - self, model: str - ) -> List[str]: + def get_supported_openai_params(self, model: str) -> List[str]: """ Return list of OpenAI params supported by Stability AI. @@ -52,7 +50,7 @@ class StabilityImageEditConfig(BaseImageEditConfig): "n", # Number of images (Stability always returns 1, we can loop) "size", # Maps to aspect_ratio "response_format", # b64_json or url (Stability only returns b64) - "mask" + "mask", ] def map_openai_params( @@ -188,7 +186,7 @@ class StabilityImageEditConfig(BaseImageEditConfig): data: Dict[str, Any] = { "output_format": "png", # Default to PNG } - + # Add prompt only if provided (some Stability endpoints don't require it) if prompt is not None and prompt != "": data["prompt"] = prompt @@ -241,7 +239,7 @@ class StabilityImageEditConfig(BaseImageEditConfig): "select_prompt", "control_strength", "composition_fidelity", - "change_strength" + "change_strength", ]: data[key] = value # type: ignore @@ -310,7 +308,9 @@ class StabilityImageEditConfig(BaseImageEditConfig): model_info = get_model_info(model, custom_llm_provider="stability") cost_per_image = model_info.get("output_cost_per_image", 0) if cost_per_image is not None: - model_response._hidden_params["additional_headers"]["llm_provider-x-litellm-response-cost"] = float(cost_per_image) + model_response._hidden_params["additional_headers"][ + "llm_provider-x-litellm-response-cost" + ] = float(cost_per_image) return model_response def use_multipart_form_data(self) -> bool: diff --git a/litellm/llms/stability/image_generation/transformation.py b/litellm/llms/stability/image_generation/transformation.py index d69dd399b2c..ac63548bf56 100644 --- a/litellm/llms/stability/image_generation/transformation.py +++ b/litellm/llms/stability/image_generation/transformation.py @@ -80,9 +80,9 @@ class StabilityImageGenerationConfig(BaseImageGenerationConfig): if k in supported_params: # Map size to aspect_ratio if k == "size" and v in OPENAI_SIZE_TO_STABILITY_ASPECT_RATIO: - optional_params["aspect_ratio"] = ( - OPENAI_SIZE_TO_STABILITY_ASPECT_RATIO[v] - ) + optional_params[ + "aspect_ratio" + ] = OPENAI_SIZE_TO_STABILITY_ASPECT_RATIO[v] elif k == "n": # Store n for later, but don't pass to Stability optional_params["_n"] = v @@ -132,9 +132,7 @@ class StabilityImageGenerationConfig(BaseImageGenerationConfig): Get the complete URL for the Stability AI API request. """ base_url: str = ( - api_base - or get_secret_str("STABILITY_API_BASE") - or self.DEFAULT_BASE_URL + api_base or get_secret_str("STABILITY_API_BASE") or self.DEFAULT_BASE_URL ) base_url = base_url.rstrip("/") diff --git a/litellm/llms/tavily/search/__init__.py b/litellm/llms/tavily/search/__init__.py index 4753928806b..6e3fe1163c7 100644 --- a/litellm/llms/tavily/search/__init__.py +++ b/litellm/llms/tavily/search/__init__.py @@ -4,4 +4,3 @@ Tavily Search API module. from litellm.llms.tavily.search.transformation import TavilySearchConfig __all__ = ["TavilySearchConfig"] - diff --git a/litellm/llms/tavily/search/transformation.py b/litellm/llms/tavily/search/transformation.py index 7fc33416a0b..1228433b539 100644 --- a/litellm/llms/tavily/search/transformation.py +++ b/litellm/llms/tavily/search/transformation.py @@ -18,6 +18,7 @@ from litellm.secret_managers.main import get_secret_str class _TavilySearchRequestRequired(TypedDict): """Required fields for Tavily Search API request.""" + query: str # Required - search query @@ -26,6 +27,7 @@ class TavilySearchRequest(_TavilySearchRequestRequired, total=False): Tavily Search API request format. Based on: https://docs.tavily.com/documentation/api-reference/endpoint/search """ + max_results: int # Optional - maximum number of results (0-20), default 5 include_domains: List[str] # Optional - list of domains to include (max 300) exclude_domains: List[str] # Optional - list of domains to exclude (max 150) @@ -44,11 +46,11 @@ class TavilySearchRequest(_TavilySearchRequestRequired, total=False): class TavilySearchConfig(BaseSearchConfig): TAVILY_API_BASE = "https://api.tavily.com" - + @staticmethod def ui_friendly_name() -> str: return "Tavily" - + def validate_environment( self, headers: Dict, @@ -61,7 +63,9 @@ class TavilySearchConfig(BaseSearchConfig): """ api_key = api_key or get_secret_str("TAVILY_API_KEY") if not api_key: - raise ValueError("TAVILY_API_KEY is not set. Set `TAVILY_API_KEY` environment variable.") + raise ValueError( + "TAVILY_API_KEY is not set. Set `TAVILY_API_KEY` environment variable." + ) headers["Authorization"] = f"Bearer {api_key}" headers["Content-Type"] = "application/json" return headers @@ -77,13 +81,12 @@ class TavilySearchConfig(BaseSearchConfig): Get complete URL for Search endpoint. """ api_base = api_base or get_secret_str("TAVILY_API_BASE") or self.TAVILY_API_BASE - + # Append "/search" to the api base if it's not already there if not api_base.endswith("/search"): api_base = f"{api_base}/search" return api_base - def transform_search_request( self, @@ -93,7 +96,7 @@ class TavilySearchConfig(BaseSearchConfig): ) -> Dict: """ Transform Search request to Tavily API format. - + Args: query: Search query (string or list of strings). Tavily only supports single string queries. optional_params: Optional parameters for the request @@ -111,7 +114,7 @@ class TavilySearchConfig(BaseSearchConfig): - start_date: Start date filter (YYYY-MM-DD) - end_date: End date filter (YYYY-MM-DD) - country: Country code filter (e.g., 'US', 'GB', 'DE') - + Returns: Dict with typed request data following TavilySearchRequest spec """ @@ -122,26 +125,29 @@ class TavilySearchConfig(BaseSearchConfig): request_data: TavilySearchRequest = { "query": query, } - + # Transform Perplexity unified spec parameters to Tavily format if "max_results" in optional_params: request_data["max_results"] = optional_params["max_results"] - + if "search_domain_filter" in optional_params: request_data["include_domains"] = optional_params["search_domain_filter"] - + if "country" in optional_params: # Tavily expects lowercase country names request_data["country"] = optional_params["country"].lower() - + # Convert to dict before dynamic key assignments result_data = dict(request_data) - + # pass through all other parameters as-is for param, value in optional_params.items(): - if param not in self.get_supported_perplexity_optional_params() and param not in result_data: + if ( + param not in self.get_supported_perplexity_optional_params() + and param not in result_data + ): result_data[param] = value - + return result_data def transform_search_response( @@ -152,36 +158,37 @@ class TavilySearchConfig(BaseSearchConfig): ) -> SearchResponse: """ Transform Tavily API response to LiteLLM unified SearchResponse format. - + Tavily → LiteLLM mappings: - results[].title → SearchResult.title - results[].url → SearchResult.url - results[].content → SearchResult.snippet - No date/last_updated fields in Tavily response (set to None) - + Args: raw_response: Raw httpx response from Tavily API logging_obj: Logging object for tracking - + Returns: SearchResponse with standardized format """ response_json = raw_response.json() - + # Transform results to SearchResult objects results = [] for result in response_json.get("results", []): search_result = SearchResult( title=result.get("title", ""), url=result.get("url", ""), - snippet=result.get("content", ""), # Tavily uses "content" instead of "snippet" + snippet=result.get( + "content", "" + ), # Tavily uses "content" instead of "snippet" date=None, # Tavily doesn't provide date in response last_updated=None, # Tavily doesn't provide last_updated in response ) results.append(search_result) - + return SearchResponse( results=results, object="search", ) - diff --git a/litellm/llms/v0/chat/transformation.py b/litellm/llms/v0/chat/transformation.py index 1417e5f5ae1..7b65cec9d39 100644 --- a/litellm/llms/v0/chat/transformation.py +++ b/litellm/llms/v0/chat/transformation.py @@ -13,7 +13,7 @@ class V0ChatConfig(OpenAILikeChatConfig): """ v0 is OpenAI-compatible with standard endpoints """ - + @property def custom_llm_provider(self) -> Optional[str]: return "v0" @@ -36,9 +36,9 @@ class V0ChatConfig(OpenAILikeChatConfig): Reference: https://v0.dev/docs/v0-model-api#request-body """ return [ - "messages", # Required - "model", # Required - "stream", # Optional - "tools", # Optional + "messages", # Required + "model", # Required + "stream", # Optional + "tools", # Optional "tool_choice", # Optional - ] \ No newline at end of file + ] diff --git a/litellm/llms/vercel_ai_gateway/chat/transformation.py b/litellm/llms/vercel_ai_gateway/chat/transformation.py index 13a88377489..81a1688b909 100644 --- a/litellm/llms/vercel_ai_gateway/chat/transformation.py +++ b/litellm/llms/vercel_ai_gateway/chat/transformation.py @@ -33,14 +33,13 @@ class VercelAIGatewayConfig(OpenAIGPTConfig): def _get_openai_compatible_provider_info( self, api_base: Optional[str], api_key: Optional[str] ) -> Tuple[Optional[str], Optional[str]]: - api_base = ( api_base or get_secret_str("VERCEL_AI_GATEWAY_API_BASE") or "https://ai-gateway.vercel.sh/v1" ) user_api_key = ( - api_key + api_key or get_secret_str("VERCEL_AI_GATEWAY_API_KEY") or get_secret_str("VERCEL_OIDC_TOKEN") ) @@ -60,11 +59,13 @@ class VercelAIGatewayConfig(OpenAIGPTConfig): # Vercel AI Gateway-only parameters extra_body = {} provider_options = non_default_params.pop("providerOptions", None) - + if provider_options is not None: extra_body["providerOptions"] = provider_options - - mapped_openai_params["extra_body"] = extra_body # openai client supports `extra_body` param + + mapped_openai_params[ + "extra_body" + ] = extra_body # openai client supports `extra_body` param return mapped_openai_params def transform_request( @@ -98,10 +99,10 @@ class VercelAIGatewayConfig(OpenAIGPTConfig): self, api_key: Optional[str] = None, api_base: Optional[str] = None ) -> List[str]: api_base, _ = self._get_openai_compatible_provider_info(api_base, api_key) - + if api_base is None: api_base = "https://ai-gateway.vercel.sh/v1" - + models_url = f"{api_base}/models" response = litellm.module_level_client.get(url=models_url) diff --git a/litellm/llms/vertex_ai/agent_engine/__init__.py b/litellm/llms/vertex_ai/agent_engine/__init__.py index de891f85602..a790d8b6bdf 100644 --- a/litellm/llms/vertex_ai/agent_engine/__init__.py +++ b/litellm/llms/vertex_ai/agent_engine/__init__.py @@ -10,4 +10,3 @@ from litellm.llms.vertex_ai.agent_engine.transformation import ( ) __all__ = ["VertexAgentEngineConfig", "VertexAgentEngineError"] - diff --git a/litellm/llms/vertex_ai/agent_engine/transformation.py b/litellm/llms/vertex_ai/agent_engine/transformation.py index 42032079f94..0707a7b4c26 100644 --- a/litellm/llms/vertex_ai/agent_engine/transformation.py +++ b/litellm/llms/vertex_ai/agent_engine/transformation.py @@ -120,7 +120,9 @@ class VertexAgentEngineConfig(BaseConfig, VertexBase): # Get project and location from litellm_params or environment vertex_project = self.safe_get_vertex_ai_project(litellm_params) - vertex_location = self.safe_get_vertex_ai_location(litellm_params) or "us-central1" + vertex_location = ( + self.safe_get_vertex_ai_location(litellm_params) or "us-central1" + ) # Build the full resource path if only engine_id was provided if not resource_path.startswith("projects/"): @@ -156,7 +158,9 @@ class VertexAgentEngineConfig(BaseConfig, VertexBase): project_id=vertex_project, ) - verbose_logger.debug(f"Vertex Agent Engine: Authenticated for project {project_id}") + verbose_logger.debug( + f"Vertex Agent Engine: Authenticated for project {project_id}" + ) return { "Authorization": f"Bearer {access_token}", @@ -300,7 +304,9 @@ class VertexAgentEngineConfig(BaseConfig, VertexBase): """ try: content_type = raw_response.headers.get("content-type", "").lower() - verbose_logger.debug(f"Vertex Agent Engine response Content-Type: {content_type}") + verbose_logger.debug( + f"Vertex Agent Engine response Content-Type: {content_type}" + ) # Parse the SSE response response_text = raw_response.text @@ -340,7 +346,9 @@ class VertexAgentEngineConfig(BaseConfig, VertexBase): return model_response except Exception as e: - verbose_logger.error(f"Error processing Vertex Agent Engine response: {str(e)}") + verbose_logger.error( + f"Error processing Vertex Agent Engine response: {str(e)}" + ) raise VertexAgentEngineError( message=f"Error processing response: {str(e)}", status_code=raw_response.status_code, @@ -398,7 +406,9 @@ class VertexAgentEngineConfig(BaseConfig, VertexBase): ) # Create iterator for SSE stream - completion_stream = self.get_streaming_response(model=model, raw_response=response) + completion_stream = self.get_streaming_response( + model=model, raw_response=response + ) streaming_response = CustomStreamWrapper( completion_stream=completion_stream, @@ -505,4 +515,3 @@ class VertexAgentEngineConfig(BaseConfig, VertexBase): ) -> bool: """Agent Engine always returns SSE streams, so we use real streaming.""" return False - diff --git a/litellm/llms/vertex_ai/batches/handler.py b/litellm/llms/vertex_ai/batches/handler.py index 5f1fefca963..f0b181c9a61 100644 --- a/litellm/llms/vertex_ai/batches/handler.py +++ b/litellm/llms/vertex_ai/batches/handler.py @@ -118,7 +118,8 @@ class VertexAIBatchPrediction(VertexLLM): error_body = e.response.text litellm.verbose_logger.error( "Vertex AI batch create failed: status=%s, body=%s", - e.response.status_code, error_body[:1000], + e.response.status_code, + error_body[:1000], ) raise if response.status_code != 200: @@ -202,6 +203,7 @@ class VertexAIBatchPrediction(VertexLLM): # Log the request using logging_obj if available if logging_obj is not None: from litellm.litellm_core_utils.litellm_logging import Logging + if isinstance(logging_obj, Logging): logging_obj.pre_call( input="", @@ -243,10 +245,11 @@ class VertexAIBatchPrediction(VertexLLM): client = get_async_httpx_client( llm_provider=litellm.LlmProviders.VERTEX_AI, ) - + # Log the request using logging_obj if available if logging_obj is not None: from litellm.litellm_core_utils.litellm_logging import Logging + if isinstance(logging_obj, Logging): logging_obj.pre_call( input="", @@ -264,7 +267,7 @@ class VertexAIBatchPrediction(VertexLLM): ), }, ) - + response = await client.get( url=api_base, headers=headers, diff --git a/litellm/llms/vertex_ai/common_utils.py b/litellm/llms/vertex_ai/common_utils.py index 078fce63cc1..5895a91f3aa 100644 --- a/litellm/llms/vertex_ai/common_utils.py +++ b/litellm/llms/vertex_ai/common_utils.py @@ -39,8 +39,10 @@ class VertexAIModelRoute(str, Enum): OPENAI_COMPATIBLE = "openai" AGENT_ENGINE = "agent_engine" + VERTEX_AI_MODEL_ROUTES = [f"{route.value}/" for route in VertexAIModelRoute] + def get_vertex_ai_model_route( model: str, litellm_params: Optional[dict] = None ) -> VertexAIModelRoute: @@ -66,7 +68,7 @@ def get_vertex_ai_model_route( >>> get_vertex_ai_model_route("openai/gpt-oss-120b") VertexAIModelRoute.MODEL_GARDEN - + >>> get_vertex_ai_model_route("1234567890", {"api_base": "http://10.96.32.8"}) VertexAIModelRoute.GEMINI # Numeric endpoints with api_base use HTTP path """ @@ -82,20 +84,20 @@ def get_vertex_ai_model_route( # Check for agent_engine models (Reasoning Engines) if "agent_engine/" in model: return VertexAIModelRoute.AGENT_ENGINE - + # Check if numeric endpoint ID with custom api_base (PSC endpoint) # Route to GEMINI (HTTP path) to support PSC endpoints properly if model.isdigit() and litellm_params and litellm_params.get("api_base"): return VertexAIModelRoute.GEMINI - + # Check for partner models (llama, mistral, claude, etc.) if VertexAIPartnerModels.is_vertex_partner_model(model=model): return VertexAIModelRoute.PARTNER_MODELS - + # Check for BGE models if "bge/" in model or "bge" in model.lower(): return VertexAIModelRoute.BGE - + # Check for gemma models if "gemma/" in model: return VertexAIModelRoute.GEMMA @@ -189,27 +191,27 @@ all_gemini_url_modes = Literal[ def get_vertex_base_model_name(model: str) -> str: """ Strip routing prefixes from model name for PSC/endpoint URL construction. - - Patterns like "bge/", "gemma/", "openai/" are used for internal routing but + + Patterns like "bge/", "gemma/", "openai/" are used for internal routing but should not appear in the actual endpoint URL. Routing prefixes are derived from VertexAIModelRoute enum values. - + Args: model: The model name with potential prefix (e.g., "bge/123456", "gemma/gemma-3-12b-it") - + Returns: str: The model name without routing prefix (e.g., "123456", "gemma-3-12b-it") - + Examples: >>> get_vertex_base_model_name("bge/378943383978115072") "378943383978115072" - + >>> get_vertex_base_model_name("gemma/gemma-3-12b-it") "gemma-3-12b-it" - + >>> get_vertex_base_model_name("openai/gpt-oss-120b") "gpt-oss-120b" - + >>> get_vertex_base_model_name("1234567890") "1234567890" """ @@ -218,7 +220,7 @@ def get_vertex_base_model_name(model: str) -> str: for route in VERTEX_AI_MODEL_ROUTES: if model.startswith(route): return model.replace(route, "", 1) - + return model @@ -242,16 +244,16 @@ def _get_embedding_url( ) -> Tuple[str, str]: """ Get URL for embedding models. - + Handles special patterns: - bge/endpoint_id -> strips to endpoint_id for endpoints/ routing - numeric model -> routes to endpoints/ - regular model -> routes to publishers/google/models/ - models with uses_embed_content flag -> use embedContent endpoint instead of predict - """ + """ original_model = model model = get_vertex_base_model_name(model=model) - + try: model_info = litellm.get_model_info( model=original_model, @@ -260,16 +262,16 @@ def _get_embedding_url( uses_embed_content = model_info.get("uses_embed_content", False) except Exception: uses_embed_content = False - + endpoint = "embedContent" if uses_embed_content else "predict" - + base_url = get_vertex_base_url(vertex_location) - + if model.isdigit(): url = f"{base_url}/{vertex_api_version}/projects/{vertex_project}/locations/{vertex_location}/endpoints/{model}:{endpoint}" else: url = f"{base_url}/v1/projects/{vertex_project}/locations/{vertex_location}/publishers/google/models/{model}:{endpoint}" - + return url, endpoint @@ -285,15 +287,15 @@ def _get_vertex_url( endpoint: Optional[str] = None model = litellm.VertexGeminiConfig.get_model_for_vertex_ai_url(model=model) - + if mode == "chat": ### SET RUNTIME ENDPOINT ### endpoint = "generateContent" base_url = get_vertex_base_url(vertex_location) - + if stream is True: endpoint = "streamGenerateContent" - + # if model is only numeric chars then it's a fine tuned gemini model # model = 4965075652664360960 # send to this url: url = f"{base_url}/{version}/projects/{vertex_project}/locations/{vertex_location}/endpoints/{model}:{endpoint}" @@ -303,7 +305,7 @@ def _get_vertex_url( else: # Regular model - use publishers/google/models/ path url = f"{base_url}/{vertex_api_version}/projects/{vertex_project}/locations/{vertex_location}/publishers/google/models/{model}:{endpoint}" - + if stream is True: url += "?alt=sse" elif mode == "embedding": @@ -340,10 +342,12 @@ def _get_gemini_url( from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import ( VertexGeminiConfig, ) - + _gemini_model_name = "models/{}".format(model) - api_version = "v1alpha" if VertexGeminiConfig._is_gemini_3_or_newer(model) else "v1beta" - + api_version = ( + "v1alpha" if VertexGeminiConfig._is_gemini_3_or_newer(model) else "v1beta" + ) + if mode == "chat": endpoint = "generateContent" if stream is True: @@ -352,10 +356,8 @@ def _get_gemini_url( api_version, _gemini_model_name, endpoint, gemini_api_key ) else: - url = ( - "https://generativelanguage.googleapis.com/{}/{}:{}?key={}".format( - api_version, _gemini_model_name, endpoint, gemini_api_key - ) + url = "https://generativelanguage.googleapis.com/{}/{}:{}?key={}".format( + api_version, _gemini_model_name, endpoint, gemini_api_key ) elif mode == "embedding": endpoint = "embedContent" @@ -520,29 +522,6 @@ def _build_vertex_schema(parameters: dict, add_property_ordering: bool = False): return parameters -def _build_vertex_schema_for_gemini_2(parameters: dict) -> dict: - """ - Minimal schema builder for Gemini 2.0+ tool parameters. - - Gemini 2.0+ accepts standard JSON Schema natively in tool parameters, - including lowercase types, anyOf with null, and bare {} (TYPE_UNSPECIFIED). - The only transformation needed is resolving $ref/$defs, which Gemini does - NOT support in tool parameters (returns 400). - - This avoids the harmful transforms in _build_vertex_schema that break - JsonValue/Any semantics by coercing {} to {"type": "object"}. - """ - valid_schema_fields = set(get_type_hints(Schema).keys()) - - parameters = dict(parameters) # shallow copy to avoid mutating caller's dict - defs = parameters.pop("$defs", {}) - unpack_defs(parameters, defs) - - parameters = filter_schema_fields(parameters, valid_schema_fields) - - return parameters - - def _build_json_schema(parameters: dict) -> dict: """ Build a JSON Schema for use with Gemini's responseJsonSchema parameter. @@ -740,7 +719,12 @@ def convert_anyof_null_to_nullable(schema, depth=0): def add_object_type(schema): # Gemini requires all function parameters to be type OBJECT # Handle case where schema has no properties and no type (e.g. tools with no arguments) - if "type" not in schema and "anyOf" not in schema and "oneOf" not in schema and "allOf" not in schema: + if ( + "type" not in schema + and "anyOf" not in schema + and "oneOf" not in schema + and "allOf" not in schema + ): schema["type"] = "object" properties = schema.get("properties", None) @@ -817,10 +801,19 @@ def _convert_schema_types(schema, depth=0): if "type" in schema: type_val = schema["type"] if isinstance(type_val, list) and len(type_val) > 1: - # Convert type arrays to anyOf format + # Convert type arrays to anyOf format # Fields that are specific to object/array types and should move into anyOf - type_specific_fields = {"properties", "required", "additionalProperties", "items", "minItems", "maxItems", "minProperties", "maxProperties"} - + type_specific_fields = { + "properties", + "required", + "additionalProperties", + "items", + "minItems", + "maxItems", + "minProperties", + "maxProperties", + } + any_of: List[Dict[str, Any]] = [] for t in type_val: if not isinstance(t, str): @@ -829,7 +822,7 @@ def _convert_schema_types(schema, depth=0): # Keep null entry minimal so we can strip it later. any_of.append({"type": "null"}) continue - + # For object/array types, include type-specific fields if t in ("object", "array"): item_schema = {"type": t} @@ -841,13 +834,15 @@ def _convert_schema_types(schema, depth=0): else: # For primitive types, only include the type any_of.append({"type": t}) - + # Remove type-specific fields from parent if we moved them into anyOf - has_object_or_array = any(t in ("object", "array") for t in type_val if isinstance(t, str)) + has_object_or_array = any( + t in ("object", "array") for t in type_val if isinstance(t, str) + ) if has_object_or_array: for field in type_specific_fields: schema.pop(field, None) - + schema["anyOf"] = any_of schema.pop("type") elif isinstance(type_val, list) and len(type_val) == 1: @@ -967,26 +962,6 @@ def construct_target_url( return updated_url -def is_global_only_vertex_model(model: str) -> bool: - """ - Check if a model is only available in the global region. - - Args: - model: The model name to check - - Returns: - True if the model is only available in global region, False otherwise - """ - from litellm.utils import get_supported_regions - - supported_regions = get_supported_regions( - model=model, custom_llm_provider="vertex_ai" - ) - if supported_regions is None: - return False - return "global" in supported_regions - - class VertexAIModelInfo(BaseLLMModelInfo): def get_token_counter(self) -> Optional[BaseTokenCounter]: """ @@ -1080,15 +1055,16 @@ class VertexAITokenCounter(BaseTokenCounter): vertex_project = count_tokens_params_request.get( "vertex_project" ) or count_tokens_params_request.get("vertex_ai_project") - + vertex_location = count_tokens_params_request.get( "vertex_location" ) or count_tokens_params_request.get("vertex_ai_location") # Count tokens not available on global location: https://docs.cloud.google.com/vertex-ai/generative-ai/docs/partner-models/claude/count-tokens - vertex_location = count_tokens_params_request.get( - "vertex_count_tokens_location" - ) or vertex_location + vertex_location = ( + count_tokens_params_request.get("vertex_count_tokens_location") + or vertex_location + ) vertex_credentials = count_tokens_params_request.get( "vertex_credentials" @@ -1133,4 +1109,4 @@ class VertexAITokenCounter(BaseTokenCounter): original_response=result, ) - return None \ No newline at end of file + return None diff --git a/litellm/llms/vertex_ai/context_caching/transformation.py b/litellm/llms/vertex_ai/context_caching/transformation.py index bc5c1b451f1..950edbeb478 100644 --- a/litellm/llms/vertex_ai/context_caching/transformation.py +++ b/litellm/llms/vertex_ai/context_caching/transformation.py @@ -51,37 +51,37 @@ def get_first_continuous_block_idx( def extract_ttl_from_cached_messages(messages: List[AllMessageValues]) -> Optional[str]: """ Extract TTL from cached messages. Returns the first valid TTL found. - + Args: messages: List of messages to extract TTL from - + Returns: Optional[str]: TTL string in format "3600s" or None if not found/invalid """ for message in messages: if not is_cached_message(message): continue - + content = message.get("content") if not content or isinstance(content, str): continue - + for content_item in content: # Type check to ensure content_item is a dictionary before calling .get() if not isinstance(content_item, dict): continue - + cache_control = content_item.get("cache_control") if not cache_control or not isinstance(cache_control, dict): continue - + if cache_control.get("type") != "ephemeral": continue - + ttl = cache_control.get("ttl") if ttl and _is_valid_ttl_format(ttl): return str(ttl) - + return None @@ -89,23 +89,23 @@ def _is_valid_ttl_format(ttl: str) -> bool: """ Validate TTL format. Should be a string ending with 's' for seconds. Examples: "3600s", "7200s", "1.5s" - + Args: ttl: TTL string to validate - + Returns: bool: True if valid format, False otherwise """ if not isinstance(ttl, str): return False - + # TTL should end with 's' and contain a valid number before it - pattern = r'^([0-9]*\.?[0-9]+)s$' + pattern = r"^([0-9]*\.?[0-9]+)s$" match = re.match(pattern, ttl) - + if not match: return False - + try: # Ensure the numeric part is valid and positive numeric_part = float(match.group(1)) @@ -164,7 +164,7 @@ def transform_openai_messages_to_gemini_context_caching( ) -> CachedContentRequestBody: # Extract TTL from cached messages BEFORE system message transformation ttl = extract_ttl_from_cached_messages(messages) - + supports_system_message = get_supports_system_message( model=model, custom_llm_provider=custom_llm_provider ) @@ -173,8 +173,10 @@ def transform_openai_messages_to_gemini_context_caching( supports_system_message=supports_system_message, messages=messages ) - transformed_messages = _gemini_convert_messages_with_history(messages=new_messages, model=model) - + transformed_messages = _gemini_convert_messages_with_history( + messages=new_messages, model=model + ) + model_name = "models/{}".format(model) if custom_llm_provider == "vertex_ai" or custom_llm_provider == "vertex_ai_beta": @@ -185,11 +187,11 @@ def transform_openai_messages_to_gemini_context_caching( model=model_name, displayName=cache_key, ) - + # Add TTL if present and valid if ttl: data["ttl"] = ttl - + if transformed_system_messages is not None: data["system_instruction"] = transformed_system_messages 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 4450ae58349..db6be9499a2 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 @@ -81,7 +81,6 @@ class ContextCachingEndpoints(VertexBase): else: url = f"https://{vertex_location}-aiplatform.googleapis.com/v1beta1/projects/{vertex_project}/locations/{vertex_location}/{endpoint}" - return self._check_custom_proxy( api_base=api_base, custom_llm_provider=custom_llm_provider, @@ -93,7 +92,9 @@ class ContextCachingEndpoints(VertexBase): model=None, vertex_project=vertex_project, vertex_location=vertex_location, - vertex_api_version="v1beta1" if custom_llm_provider == "vertex_ai_beta" else "v1", + vertex_api_version="v1beta1" + if custom_llm_provider == "vertex_ai_beta" + else "v1", ) def check_cache( @@ -126,7 +127,7 @@ class ContextCachingEndpoints(VertexBase): api_base=api_base, vertex_project=vertex_project, vertex_location=vertex_location, - vertex_auth_header=vertex_auth_header + vertex_auth_header=vertex_auth_header, ) page_token: Optional[str] = None @@ -199,7 +200,7 @@ class ContextCachingEndpoints(VertexBase): custom_llm_provider: Literal["vertex_ai", "vertex_ai_beta", "gemini"], vertex_project: Optional[str], vertex_location: Optional[str], - vertex_auth_header: Optional[str] + vertex_auth_header: Optional[str], ) -> Optional[str]: """ Checks if content already cached. @@ -218,7 +219,7 @@ class ContextCachingEndpoints(VertexBase): api_base=api_base, vertex_project=vertex_project, vertex_location=vertex_location, - vertex_auth_header=vertex_auth_header + vertex_auth_header=vertex_auth_header, ) page_token: Optional[str] = None @@ -340,7 +341,7 @@ class ContextCachingEndpoints(VertexBase): api_base=api_base, vertex_project=vertex_project, vertex_location=vertex_location, - vertex_auth_header=vertex_auth_header + vertex_auth_header=vertex_auth_header, ) headers = { @@ -375,7 +376,7 @@ class ContextCachingEndpoints(VertexBase): custom_llm_provider=custom_llm_provider, vertex_project=vertex_project, vertex_location=vertex_location, - vertex_auth_header=vertex_auth_header + vertex_auth_header=vertex_auth_header, ) if google_cache_name: return non_cached_messages, optional_params, google_cache_name @@ -486,7 +487,7 @@ class ContextCachingEndpoints(VertexBase): api_base=api_base, vertex_project=vertex_project, vertex_location=vertex_location, - vertex_auth_header=vertex_auth_header + vertex_auth_header=vertex_auth_header, ) headers = { @@ -518,7 +519,7 @@ class ContextCachingEndpoints(VertexBase): custom_llm_provider=custom_llm_provider, vertex_project=vertex_project, vertex_location=vertex_location, - vertex_auth_header=vertex_auth_header + vertex_auth_header=vertex_auth_header, ) if google_cache_name: @@ -574,4 +575,4 @@ class ContextCachingEndpoints(VertexBase): pass async def async_get_cache(self): - pass \ No newline at end of file + pass diff --git a/litellm/llms/vertex_ai/count_tokens/handler.py b/litellm/llms/vertex_ai/count_tokens/handler.py index d95c6801e57..9a175371a27 100644 --- a/litellm/llms/vertex_ai/count_tokens/handler.py +++ b/litellm/llms/vertex_ai/count_tokens/handler.py @@ -17,7 +17,9 @@ class VertexAITokenCounter(GoogleAIStudioTokenCounter, VertexBase): Returns a Tuple of headers and url for the Vertex AI countTokens endpoint. """ litellm_params = litellm_params or {} - vertex_credentials = self.get_vertex_ai_credentials(litellm_params=litellm_params) + vertex_credentials = self.get_vertex_ai_credentials( + litellm_params=litellm_params + ) vertex_project = self.get_vertex_ai_project(litellm_params=litellm_params) vertex_location = self.get_vertex_ai_location(litellm_params=litellm_params) should_use_v1beta1_features = self.is_using_v1beta1_features(litellm_params) @@ -43,4 +45,4 @@ class VertexAITokenCounter(GoogleAIStudioTokenCounter, VertexBase): headers = { "Authorization": f"Bearer {auth_header}", } - return headers, api_base \ No newline at end of file + return headers, api_base diff --git a/litellm/llms/vertex_ai/files/transformation.py b/litellm/llms/vertex_ai/files/transformation.py index bf3ed5e6ac9..070ec508283 100644 --- a/litellm/llms/vertex_ai/files/transformation.py +++ b/litellm/llms/vertex_ai/files/transformation.py @@ -165,7 +165,11 @@ class VertexAIFilesConfig(VertexBase, BaseFilesConfig): """ Get the complete url for the request """ - bucket_name = litellm_params.get("bucket_name") or litellm_params.get("litellm_metadata", {}).pop("gcs_bucket_name", None) 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") @@ -410,6 +414,7 @@ class VertexAIFilesConfig(VertexBase, BaseFilesConfig): url = str(raw_response.request.url) if "/b/" in url and "/o/" in url: import urllib.parse + bucket_part = url.split("/b/")[-1].split("/o/")[0] encoded_name = url.split("/o/")[-1].split("?")[0] file_id = f"gs://{bucket_part}/{urllib.parse.unquote(encoded_name)}" diff --git a/litellm/llms/vertex_ai/fine_tuning/handler.py b/litellm/llms/vertex_ai/fine_tuning/handler.py index e2cd052fffd..77891e245cd 100644 --- a/litellm/llms/vertex_ai/fine_tuning/handler.py +++ b/litellm/llms/vertex_ai/fine_tuning/handler.py @@ -65,9 +65,9 @@ class VertexFineTuningAPI(VertexLLM): ) if create_fine_tuning_job_data.validation_file: - supervised_tuning_spec["validation_dataset"] = ( - create_fine_tuning_job_data.validation_file - ) + supervised_tuning_spec[ + "validation_dataset" + ] = create_fine_tuning_job_data.validation_file _vertex_hyperparameters = ( self._transform_openai_hyperparameters_to_vertex_hyperparameters( @@ -332,7 +332,7 @@ class VertexFineTuningAPI(VertexLLM): } base_url = get_vertex_base_url(vertex_location) - + url = None if request_route == "/tuningJobs": url = f"{base_url}/v1/projects/{vertex_project}/locations/{vertex_location}/tuningJobs" @@ -349,9 +349,9 @@ class VertexFineTuningAPI(VertexLLM): elif "cachedContents" in request_route: _model = request_data.get("model") if _model is not None and "/publishers/google/models/" not in _model: - request_data["model"] = ( - f"projects/{vertex_project}/locations/{vertex_location}/publishers/google/models/{_model}" - ) + request_data[ + "model" + ] = f"projects/{vertex_project}/locations/{vertex_location}/publishers/google/models/{_model}" url = f"{base_url}/v1beta1/projects/{vertex_project}/locations/{vertex_location}{request_route}" else: diff --git a/litellm/llms/vertex_ai/gemini/transformation.py b/litellm/llms/vertex_ai/gemini/transformation.py index 48477f2f3a1..d7b96b4db7b 100644 --- a/litellm/llms/vertex_ai/gemini/transformation.py +++ b/litellm/llms/vertex_ai/gemini/transformation.py @@ -335,7 +335,9 @@ def _gemini_convert_messages_with_history( # noqa: PLR0915 image_url = img_element["image_url"]["url"] format = img_element["image_url"].get("format") detail = img_element["image_url"].get("detail") - media_resolution_enum = _convert_detail_to_media_resolution_enum(detail) + media_resolution_enum = ( + _convert_detail_to_media_resolution_enum(detail) + ) else: image_url = img_element["image_url"] _part = _process_gemini_media( @@ -384,7 +386,9 @@ def _gemini_convert_messages_with_history( # noqa: PLR0915 ) # Convert detail to media_resolution_enum - media_resolution_enum = _convert_detail_to_media_resolution_enum(detail) + media_resolution_enum = ( + _convert_detail_to_media_resolution_enum(detail) + ) try: _part = _process_gemini_media( @@ -402,10 +406,7 @@ def _gemini_convert_messages_with_history( # noqa: PLR0915 ) ) user_content.extend(_parts) - elif ( - _message_content is not None - and isinstance(_message_content, str) - ): + elif _message_content is not None and isinstance(_message_content, str): _part = PartType(text=_message_content) user_content.append(_part) @@ -473,19 +474,26 @@ def _gemini_convert_messages_with_history( # noqa: PLR0915 _parts.append(_part) assistant_content.extend(_parts) - elif ( - _message_content is not None - and isinstance(_message_content, str) - ): + elif _message_content is not None and isinstance(_message_content, str): assistant_text = _message_content # Check if message has thought_signatures in provider_specific_fields - provider_specific_fields = assistant_msg.get("provider_specific_fields") + provider_specific_fields = assistant_msg.get( + "provider_specific_fields" + ) thought_signatures = None - if provider_specific_fields and isinstance(provider_specific_fields, dict): - thought_signatures = provider_specific_fields.get("thought_signatures") - + if provider_specific_fields and isinstance( + provider_specific_fields, dict + ): + thought_signatures = provider_specific_fields.get( + "thought_signatures" + ) + # If we have thought signatures, add them to the part - if thought_signatures and isinstance(thought_signatures, list) and len(thought_signatures) > 0: + if ( + thought_signatures + and isinstance(thought_signatures, list) + and len(thought_signatures) > 0 + ): # Use the first signature for the text part (Gemini expects one signature per part) assistant_content.append(PartType(text=assistant_text, thoughtSignature=thought_signatures[0])) # type: ignore else: @@ -502,7 +510,9 @@ def _gemini_convert_messages_with_history( # noqa: PLR0915 assistant_image_url = image_url_obj.get("url") format = image_url_obj.get("format") detail = image_url_obj.get("detail") - media_resolution_enum = _convert_detail_to_media_resolution_enum(detail) + media_resolution_enum = ( + _convert_detail_to_media_resolution_enum(detail) + ) if assistant_image_url: _part = _process_gemini_media( image_url=assistant_image_url, @@ -583,13 +593,23 @@ def _gemini_convert_messages_with_history( # noqa: PLR0915 raise e +# Keys that LiteLLM consumes internally and must never be forwarded to the +_LITELLM_INTERNAL_EXTRA_BODY_KEYS: frozenset = frozenset({"cache", "tags"}) + + def _pop_and_merge_extra_body(data: RequestBody, optional_params: dict) -> None: """Pop extra_body from optional_params and shallow-merge into data, deep-merging dict values.""" extra_body: Optional[dict] = optional_params.pop("extra_body", None) if extra_body is not None: data_dict: dict = data # type: ignore[assignment] for k, v in extra_body.items(): - if k in data_dict and isinstance(data_dict[k], dict) and isinstance(v, dict): + if k in _LITELLM_INTERNAL_EXTRA_BODY_KEYS: + continue + if ( + k in data_dict + and isinstance(data_dict[k], dict) + and isinstance(v, dict) + ): data_dict[k].update(v) else: data_dict[k] = v @@ -665,7 +685,9 @@ def _transform_request_body( # noqa: PLR0915 labels = {k: v for k, v in rm.items() if isinstance(v, str)} filtered_params = { - k: v for k, v in optional_params.items() if _get_equivalent_key(k, set(config_fields)) + k: v + for k, v in optional_params.items() + if _get_equivalent_key(k, set(config_fields)) } generation_config: Optional[GenerationConfig] = GenerationConfig( @@ -682,7 +704,9 @@ def _transform_request_body( # noqa: PLR0915 max_media_resolution ) if media_resolution_value and generation_config is not None: - generation_config["mediaResolution"] = media_resolution_value["level"] + generation_config["mediaResolution"] = media_resolution_value[ + "level" + ] data = RequestBody(contents=content) if system_instructions is not None: @@ -728,9 +752,9 @@ def sync_transform_request_body( context_caching_endpoints = ContextCachingEndpoints() ( - messages, - optional_params, - cached_content, + messages, + optional_params, + cached_content, ) = context_caching_endpoints.check_and_create_cache( messages=messages, optional_params=optional_params, @@ -748,7 +772,6 @@ def sync_transform_request_body( vertex_auth_header=vertex_auth_header, ) - return _transform_request_body( messages=messages, model=model, @@ -780,9 +803,9 @@ async def async_transform_request_body( context_caching_endpoints = ContextCachingEndpoints() ( - messages, - optional_params, - cached_content, + messages, + optional_params, + cached_content, ) = await context_caching_endpoints.async_check_and_create_cache( messages=messages, optional_params=optional_params, 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 df7a4a6511d..3f1bccaccfc 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 @@ -97,7 +97,6 @@ from ..common_utils import ( VertexAIError, _build_json_schema, _build_vertex_schema, - _build_vertex_schema_for_gemini_2, supports_response_json_schema, ) from ..vertex_llm_base import VertexBase @@ -468,7 +467,7 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig): return None def _map_function( # noqa: PLR0915 - self, value: List[dict], optional_params: dict, model: str = "" + self, value: List[dict], optional_params: dict ) -> List[Tools]: """ Map OpenAI-style tools/functions to Vertex AI format. @@ -499,9 +498,9 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig): value = _remove_strict_from_schema(value) for tool in value: - openai_function_object: Optional[ChatCompletionToolParamFunctionChunk] = ( - None - ) + openai_function_object: Optional[ + ChatCompletionToolParamFunctionChunk + ] = None if "function" in tool: # tools list _openai_function_object = ChatCompletionToolParamFunctionChunk( # type: ignore **tool["function"] @@ -511,21 +510,10 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig): "parameters" in _openai_function_object and _openai_function_object["parameters"] is not None and isinstance(_openai_function_object["parameters"], dict) - ): - if supports_response_json_schema(model): - # Gemini 2.0+: minimal transform (resolve $ref only) - _openai_function_object["parameters"] = ( - _build_vertex_schema_for_gemini_2( - _openai_function_object["parameters"] - ) - ) - else: - # Gemini 1.5: full OpenAPI-style transform - _openai_function_object["parameters"] = ( - _build_vertex_schema( - _openai_function_object["parameters"] - ) - ) + ): # OPENAI accepts JSON Schema, Google accepts OpenAPI schema. + _openai_function_object["parameters"] = _build_vertex_schema( + _openai_function_object["parameters"] + ) openai_function_object = _openai_function_object @@ -644,15 +632,15 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig): _tools_list.append(search_tool) if googleSearchRetrieval is not None: retrieval_tool = Tools() - retrieval_tool[VertexToolName.GOOGLE_SEARCH_RETRIEVAL.value] = ( - googleSearchRetrieval - ) + retrieval_tool[ + VertexToolName.GOOGLE_SEARCH_RETRIEVAL.value + ] = googleSearchRetrieval _tools_list.append(retrieval_tool) if enterpriseWebSearch is not None: enterprise_tool = Tools() - enterprise_tool[VertexToolName.ENTERPRISE_WEB_SEARCH.value] = ( - enterpriseWebSearch - ) + enterprise_tool[ + VertexToolName.ENTERPRISE_WEB_SEARCH.value + ] = enterpriseWebSearch _tools_list.append(enterprise_tool) if code_execution is not None: code_tool = Tools() @@ -814,12 +802,9 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig): # Check if this is gemini-3-flash which supports MINIMAL thinking level # Covers gemini-3-flash, gemini-3-flash-preview, gemini-3.1-flash, gemini-3.1-flash-lite-preview, etc. is_gemini3flash = model and ( - "gemini-3-flash" in model.lower() - or "gemini-3.1-flash" in model.lower() - ) - is_gemini31pro = model and ( - "gemini-3.1-pro-preview" in model.lower() + "gemini-3-flash" in model.lower() or "gemini-3.1-flash" in model.lower() ) + is_gemini31pro = model and ("gemini-3.1-pro-preview" in model.lower()) if reasoning_effort == "minimal": if is_gemini3flash: return {"thinkingLevel": "minimal", "includeThoughts": True} @@ -1063,7 +1048,7 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig): ): # Pass optional_params so _map_function can add toolConfig if needed mapped_tools = self._map_function( - value=value, optional_params=optional_params, model=model + value=value, optional_params=optional_params ) optional_params = self._add_tools_to_optional_params( optional_params, mapped_tools @@ -1102,16 +1087,16 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig): param_description="thinking_budget", ) if VertexGeminiConfig._is_gemini_3_or_newer(model): - optional_params["thinkingConfig"] = ( - VertexGeminiConfig._map_reasoning_effort_to_thinking_level( - effort_value, model - ) + optional_params[ + "thinkingConfig" + ] = VertexGeminiConfig._map_reasoning_effort_to_thinking_level( + effort_value, model ) else: - optional_params["thinkingConfig"] = ( - VertexGeminiConfig._map_reasoning_effort_to_thinking_budget( - effort_value, model - ) + optional_params[ + "thinkingConfig" + ] = VertexGeminiConfig._map_reasoning_effort_to_thinking_budget( + effort_value, model ) elif param == "thinking": # Validate no conflict with thinking_level @@ -1120,11 +1105,11 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig): param_name="thinking", param_description="thinking_budget", ) - optional_params["thinkingConfig"] = ( - VertexGeminiConfig._map_thinking_param( - cast(AnthropicThinkingParam, value), - model=model, - ) + optional_params[ + "thinkingConfig" + ] = VertexGeminiConfig._map_thinking_param( + cast(AnthropicThinkingParam, value), + model=model, ) elif param == "modalities" and isinstance(value, list): response_modalities = self.map_response_modalities(value) @@ -1242,12 +1227,25 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig): "IMAGE_PROHIBITED_CONTENT": "The token generation was stopped as the response was flagged for prohibited image content.", } - _GEMINI_FINISH_REASON_KEYS = frozenset({ - "STOP", "MAX_TOKENS", "SAFETY", "RECITATION", "FINISH_REASON_UNSPECIFIED", - "MALFORMED_FUNCTION_CALL", "LANGUAGE", "OTHER", "BLOCKLIST", - "PROHIBITED_CONTENT", "SPII", "IMAGE_SAFETY", "IMAGE_PROHIBITED_CONTENT", - "TOO_MANY_TOOL_CALLS", "MALFORMED_RESPONSE", - }) + _GEMINI_FINISH_REASON_KEYS = frozenset( + { + "STOP", + "MAX_TOKENS", + "SAFETY", + "RECITATION", + "FINISH_REASON_UNSPECIFIED", + "MALFORMED_FUNCTION_CALL", + "LANGUAGE", + "OTHER", + "BLOCKLIST", + "PROHIBITED_CONTENT", + "SPII", + "IMAGE_SAFETY", + "IMAGE_PROHIBITED_CONTENT", + "TOO_MANY_TOOL_CALLS", + "MALFORMED_RESPONSE", + } + ) @staticmethod def get_finish_reason_mapping() -> Dict[str, OpenAIChatCompletionFinishReason]: @@ -1470,10 +1468,10 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig): _tool_response_chunk["provider_specific_fields"] = { # type: ignore "thought_signature": thought_signature } - _tool_response_chunk["id"] = ( - _encode_tool_call_id_with_signature( - _tool_response_chunk["id"] or "", thought_signature - ) + _tool_response_chunk[ + "id" + ] = _encode_tool_call_id_with_signature( + _tool_response_chunk["id"] or "", thought_signature ) _tools.append(_tool_response_chunk) cumulative_tool_call_idx += 1 @@ -2283,35 +2281,37 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig): ## ADD METADATA TO RESPONSE ## setattr(model_response, "vertex_ai_grounding_metadata", grounding_metadata) - model_response._hidden_params["vertex_ai_grounding_metadata"] = ( - grounding_metadata - ) + model_response._hidden_params[ + "vertex_ai_grounding_metadata" + ] = grounding_metadata setattr( model_response, "vertex_ai_url_context_metadata", url_context_metadata ) - model_response._hidden_params["vertex_ai_url_context_metadata"] = ( - url_context_metadata - ) + model_response._hidden_params[ + "vertex_ai_url_context_metadata" + ] = url_context_metadata setattr(model_response, "vertex_ai_safety_results", safety_ratings) - model_response._hidden_params["vertex_ai_safety_results"] = ( - safety_ratings # older approach - maintaining to prevent regressions - ) + model_response._hidden_params[ + "vertex_ai_safety_results" + ] = safety_ratings # older approach - maintaining to prevent regressions ## ADD CITATION METADATA ## setattr(model_response, "vertex_ai_citation_metadata", citation_metadata) - model_response._hidden_params["vertex_ai_citation_metadata"] = ( - citation_metadata # older approach - maintaining to prevent regressions - ) + model_response._hidden_params[ + "vertex_ai_citation_metadata" + ] = citation_metadata # older approach - maintaining to prevent regressions ## ADD TRAFFIC TYPE ## traffic_type = completion_response.get("usageMetadata", {}).get( "trafficType" ) if traffic_type: - model_response._hidden_params.setdefault("provider_specific_fields", {})["traffic_type"] = traffic_type + model_response._hidden_params.setdefault( + "provider_specific_fields", {} + )["traffic_type"] = traffic_type except Exception as e: raise VertexAIError( @@ -2967,7 +2967,11 @@ class ModelResponseIterator: # to correctly set finish_reason="tool_calls" per the OpenAI spec. if not self.has_seen_tool_calls: for choice in model_response.choices: - if hasattr(choice, "delta") and choice.delta and choice.delta.tool_calls: + if ( + hasattr(choice, "delta") + and choice.delta + and choice.delta.tool_calls + ): self.has_seen_tool_calls = True break @@ -2983,8 +2987,10 @@ class ModelResponseIterator: if self.has_seen_tool_calls: mapped_finish_reason = "tool_calls" else: - mapped_finish_reason = VertexGeminiConfig._check_finish_reason( - None, finish_reason_str + mapped_finish_reason = ( + VertexGeminiConfig._check_finish_reason( + None, finish_reason_str + ) ) choice = StreamingChoices( finish_reason=mapped_finish_reason, @@ -3017,7 +3023,9 @@ class ModelResponseIterator: "trafficType" ) if traffic_type: - model_response._hidden_params.setdefault("provider_specific_fields", {})["traffic_type"] = traffic_type + model_response._hidden_params.setdefault( + "provider_specific_fields", {} + )["traffic_type"] = traffic_type setattr(model_response, "usage", usage) # type: ignore diff --git a/litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_handler.py b/litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_handler.py index 68901340c7c..2371bc4865a 100644 --- a/litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_handler.py +++ b/litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_handler.py @@ -40,37 +40,37 @@ class GoogleBatchEmbeddings(VertexLLM): ) -> Dict[str, Dict[str, str]]: """ Resolve Gemini file references (files/...) to get mime_type and uri. - + Args: input: EmbeddingInput that may contain file references api_key: Gemini API key sync_handler: HTTP client - + Returns: Dict mapping file name to {mime_type, uri} """ input_list = [input] if isinstance(input, str) else input resolved_files: Dict[str, Dict[str, str]] = {} - + for element in input_list: if isinstance(element, str) and _is_file_reference(element): url = f"https://generativelanguage.googleapis.com/v1beta/{element}" headers = {"x-goog-api-key": api_key} response = sync_handler.get(url=url, headers=headers) - + if response.status_code != 200: raise Exception( f"Error fetching file {element}: {response.status_code} {response.text}" ) - + file_data = response.json() resolved_files[element] = { "mime_type": file_data.get("mimeType", ""), "uri": file_data.get("uri", element), } - + return resolved_files - + async def _async_resolve_file_references( self, input: EmbeddingInput, @@ -79,37 +79,37 @@ class GoogleBatchEmbeddings(VertexLLM): ) -> Dict[str, Dict[str, str]]: """ Async version of _resolve_file_references. - + Args: input: EmbeddingInput that may contain file references api_key: Gemini API key async_handler: Async HTTP client - + Returns: Dict mapping file name to {mime_type, uri} """ input_list = [input] if isinstance(input, str) else input resolved_files: Dict[str, Dict[str, str]] = {} - + for element in input_list: if isinstance(element, str) and _is_file_reference(element): url = f"https://generativelanguage.googleapis.com/v1beta/{element}" headers = {"x-goog-api-key": api_key} response = await async_handler.get(url=url, headers=headers) - + if response.status_code != 200: raise Exception( f"Error fetching file {element}: {response.status_code} {response.text}" ) - + file_data = response.json() resolved_files[element] = { "mime_type": file_data.get("mimeType", ""), "uri": file_data.get("uri", element), } - + return resolved_files - + def batch_embeddings( self, model: str, @@ -153,6 +153,7 @@ class GoogleBatchEmbeddings(VertexLLM): is_multimodal = _is_multimodal_input(input) use_embed_content = is_multimodal or (custom_llm_provider == "vertex_ai") + mode: Literal["embedding", "batch_embedding"] if use_embed_content: mode = "embedding" else: @@ -200,6 +201,7 @@ class GoogleBatchEmbeddings(VertexLLM): ) ### TRANSFORMATION (sync path) ### + request_data: Any if use_embed_content: resolved_files = {} if api_key: @@ -238,7 +240,7 @@ class GoogleBatchEmbeddings(VertexLLM): raise Exception(f"Error: {response.status_code} {response.text}") _json_response = response.json() - + if use_embed_content: return process_embed_content_response( input=input, @@ -327,7 +329,7 @@ class GoogleBatchEmbeddings(VertexLLM): raise Exception(f"Error: {response.status_code} {response.text}") _json_response = response.json() - + if use_embed_content: return process_embed_content_response( input=input, diff --git a/litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_transformation.py b/litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_transformation.py index 41f477d9db9..0f6d85525d9 100644 --- a/litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_transformation.py +++ b/litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_transformation.py @@ -43,13 +43,13 @@ def _is_gcs_url(s: str) -> bool: def _infer_mime_type_from_gcs_url(gcs_url: str) -> str: """ Infer MIME type from GCS URL file extension. - + Args: gcs_url: GCS URL like gs://bucket/path/to/file.png - + Returns: str: Inferred MIME type - + Raises: ValueError: If file extension is not supported """ @@ -63,12 +63,12 @@ def _infer_mime_type_from_gcs_url(gcs_url: str) -> str: ".mov": "video/quicktime", ".pdf": "application/pdf", } - + gcs_url_lower = gcs_url.lower() for ext, mime_type in extension_to_mime.items(): if gcs_url_lower.endswith(ext): return mime_type - + raise ValueError( f"Unable to infer MIME type from GCS URL: {gcs_url}. " f"Supported extensions: {', '.join(extension_to_mime.keys())}" @@ -78,49 +78,49 @@ def _infer_mime_type_from_gcs_url(gcs_url: str) -> str: def _parse_data_url(data_url: str) -> Tuple[str, str]: """ Parse a data URL to extract the media type and base64 data. - + Args: data_url: Data URL in format: data:image/jpeg;base64,/9j/4AAQ... - + Returns: tuple: (media_type, base64_data) media_type: e.g., "image/jpeg", "video/mp4", "audio/mpeg" base64_data: The base64-encoded data without the prefix - + Raises: ValueError: If data URL format is invalid or MIME type is unsupported """ if not data_url.startswith("data:"): raise ValueError(f"Invalid data URL format: {data_url[:50]}...") - + if "," not in data_url: raise ValueError(f"Invalid data URL format (missing comma): {data_url[:50]}...") - + metadata, base64_data = data_url.split(",", 1) - + metadata = metadata[5:] - + if ";" in metadata: media_type = metadata.split(";")[0] else: media_type = metadata - + if media_type not in SUPPORTED_EMBEDDING_MIME_TYPES: raise ValueError( f"Unsupported MIME type for embedding: {media_type}. " f"Supported types: {', '.join(sorted(SUPPORTED_EMBEDDING_MIME_TYPES))}" ) - + return media_type, base64_data def _is_multimodal_input(input: EmbeddingInput) -> bool: """ Check if the input contains multimodal data (data URIs, file references, or GCS URLs). - + Args: input: EmbeddingInput (str or List[str]) - + Returns: bool: True if any element is a data URI, file reference, or GCS URL """ @@ -128,7 +128,7 @@ def _is_multimodal_input(input: EmbeddingInput) -> bool: input_list = [input] else: input_list = input - + for element in input_list: if isinstance(element, str): if element.startswith("data:") and ";base64," in element: @@ -137,7 +137,7 @@ def _is_multimodal_input(input: EmbeddingInput) -> bool: return True if _is_gcs_url(element): return True - + return False @@ -148,17 +148,17 @@ def transform_openai_input_gemini_content( The content to embed. Only the parts.text fields will be counted. """ gemini_model_name = "models/{}".format(model) - + gemini_params = optional_params.copy() if "dimensions" in gemini_params: gemini_params["outputDimensionality"] = gemini_params.pop("dimensions") - + requests: List[EmbedContentRequest] = [] if isinstance(input, str): request = EmbedContentRequest( model=gemini_model_name, content=ContentType(parts=[PartType(text=input)]), - **gemini_params + **gemini_params, ) requests.append(request) else: @@ -166,7 +166,7 @@ def transform_openai_input_gemini_content( request = EmbedContentRequest( model=gemini_model_name, content=ContentType(parts=[PartType(text=i)]), - **gemini_params + **gemini_params, ) requests.append(request) @@ -181,29 +181,29 @@ def transform_openai_input_gemini_embed_content( ) -> dict: """ Transform OpenAI embedding input to Gemini embedContent format (multimodal). - + Args: input: EmbeddingInput (str or List[str]) with text, data URIs, or file references model: Model name optional_params: Additional parameters (taskType, outputDimensionality, etc.) resolved_files: Dict mapping file names (files/abc) to {mime_type, uri} - + Returns: dict: Gemini embedContent request body with content.parts """ resolved_files = resolved_files or {} - + gemini_params = optional_params.copy() if "dimensions" in gemini_params: gemini_params["outputDimensionality"] = gemini_params.pop("dimensions") - + input_list = [input] if isinstance(input, str) else input parts: List[PartType] = [] - + for element in input_list: if not isinstance(element, str): raise ValueError(f"Unsupported input type: {type(element)}") - + if element.startswith("data:") and ";base64," in element: mime_type, base64_data = _parse_data_url(element) blob: BlobType = {"mime_type": mime_type, "data": base64_data} @@ -226,12 +226,12 @@ def transform_openai_input_gemini_embed_content( parts.append(PartType(file_data=file_data_ref)) else: parts.append(PartType(text=element)) - + request_body: dict = { "content": ContentType(parts=parts), **gemini_params, } - + return request_body @@ -243,30 +243,32 @@ def process_embed_content_response( ) -> EmbeddingResponse: """ Process Gemini embedContent response (single embedding for multimodal input). - + Args: input: Original input model_response: EmbeddingResponse to populate model: Model name response_json: Raw JSON response from embedContent endpoint - + Returns: EmbeddingResponse with single embedding """ if "embedding" not in response_json: - raise ValueError(f"embedContent response missing 'embedding' field: {response_json}") - + raise ValueError( + f"embedContent response missing 'embedding' field: {response_json}" + ) + embedding_data = response_json["embedding"] - + openai_embedding = Embedding( embedding=embedding_data["values"], index=0, object="embedding", ) - + model_response.data = [openai_embedding] model_response.model = model - + if _is_multimodal_input(input): prompt_tokens = 0 else: @@ -275,7 +277,7 @@ def process_embed_content_response( model_response.usage = Usage( prompt_tokens=prompt_tokens, total_tokens=prompt_tokens ) - + return model_response diff --git a/litellm/llms/vertex_ai/image_edit/__init__.py b/litellm/llms/vertex_ai/image_edit/__init__.py index 44914e861a7..51bb1511653 100644 --- a/litellm/llms/vertex_ai/image_edit/__init__.py +++ b/litellm/llms/vertex_ai/image_edit/__init__.py @@ -1,35 +1,38 @@ from litellm.llms.base_llm.image_edit.transformation import BaseImageEditConfig -from litellm.llms.vertex_ai.common_utils import VertexAIModelRoute, get_vertex_ai_model_route +from litellm.llms.vertex_ai.common_utils import ( + VertexAIModelRoute, + get_vertex_ai_model_route, +) from .cost_calculator import cost_calculator from .vertex_gemini_transformation import VertexAIGeminiImageEditConfig from .vertex_imagen_transformation import VertexAIImagenImageEditConfig __all__ = [ - "VertexAIGeminiImageEditConfig", + "VertexAIGeminiImageEditConfig", "VertexAIImagenImageEditConfig", - "get_vertex_ai_image_edit_config", - "cost_calculator" + "get_vertex_ai_image_edit_config", + "cost_calculator", ] def get_vertex_ai_image_edit_config(model: str) -> BaseImageEditConfig: """ Get the appropriate image edit config for a Vertex AI model. - + Routes to the correct transformation class based on the model type: - Gemini models use generateContent API (VertexAIGeminiImageEditConfig) - Imagen models use predict API (VertexAIImagenImageEditConfig) - + Args: model: The model name (e.g., "gemini-2.5-flash", "imagegeneration@006") - + Returns: BaseImageEditConfig: The appropriate configuration class """ # Determine the model route model_route = get_vertex_ai_model_route(model) - + if model_route == VertexAIModelRoute.GEMINI: # Gemini models use generateContent API return VertexAIGeminiImageEditConfig() diff --git a/litellm/llms/vertex_ai/image_edit/vertex_gemini_transformation.py b/litellm/llms/vertex_ai/image_edit/vertex_gemini_transformation.py index 8fcd285824d..de7f234a861 100644 --- a/litellm/llms/vertex_ai/image_edit/vertex_gemini_transformation.py +++ b/litellm/llms/vertex_ai/image_edit/vertex_gemini_transformation.py @@ -28,9 +28,10 @@ else: class VertexAIGeminiImageEditConfig(BaseImageEditConfig, VertexLLM): """ Vertex AI Gemini Image Edit Configuration - + Uses generateContent API for Gemini models on Vertex AI """ + SUPPORTED_PARAMS: List[str] = ["size"] def __init__(self) -> None: @@ -99,17 +100,23 @@ class VertexAIGeminiImageEditConfig(BaseImageEditConfig, VertexLLM): ) -> dict: headers = headers or {} litellm_params = litellm_params or {} - + # If a custom api_base is provided, skip credential validation # This allows users to use proxies or mock endpoints without needing Vertex AI credentials _api_base = litellm_params.get("api_base") or api_base if _api_base is not None: return headers - + # First check litellm_params (where vertex_ai_project/vertex_ai_credentials are passed) # then fall back to environment variables and other sources - vertex_project = self.safe_get_vertex_ai_project(litellm_params) or self._resolve_vertex_project() - vertex_credentials = self.safe_get_vertex_ai_credentials(litellm_params) or self._resolve_vertex_credentials() + vertex_project = ( + self.safe_get_vertex_ai_project(litellm_params) + or self._resolve_vertex_project() + ) + vertex_credentials = ( + self.safe_get_vertex_ai_credentials(litellm_params) + or self._resolve_vertex_credentials() + ) access_token, _ = self._ensure_access_token( credentials=vertex_credentials, project_id=vertex_project, @@ -138,11 +145,19 @@ class VertexAIGeminiImageEditConfig(BaseImageEditConfig, VertexLLM): # First check litellm_params (where vertex_ai_project/vertex_ai_location are passed) # then fall back to environment variables and other sources - vertex_project = self.safe_get_vertex_ai_project(litellm_params) or self._resolve_vertex_project() - vertex_location = self.safe_get_vertex_ai_location(litellm_params) or self._resolve_vertex_location() + vertex_project = ( + self.safe_get_vertex_ai_project(litellm_params) + or self._resolve_vertex_project() + ) + vertex_location = ( + self.safe_get_vertex_ai_location(litellm_params) + or self._resolve_vertex_location() + ) if not vertex_project or not vertex_location: - raise ValueError("vertex_project and vertex_location are required for Vertex AI") + raise ValueError( + "vertex_project and vertex_location are required for Vertex AI" + ) base_url = get_vertex_base_url(vertex_location) @@ -167,23 +182,20 @@ class VertexAIGeminiImageEditConfig(BaseImageEditConfig, VertexLLM): parts.append({"text": prompt}) # Correct format for Vertex AI Gemini image editing - contents = { - "role": "USER", - "parts": parts - } + contents = {"role": "USER", "parts": parts} request_body: Dict[str, Any] = {"contents": contents} # Generation config with proper structure for image editing - generation_config: Dict[str, Any] = { - "response_modalities": ["IMAGE"] - } + generation_config: Dict[str, Any] = {"response_modalities": ["IMAGE"]} # Add image-specific configuration image_config: Dict[str, Any] = {} if "aspectRatio" in image_edit_optional_request_params: - image_config["aspect_ratio"] = image_edit_optional_request_params["aspectRatio"] - + image_config["aspect_ratio"] = image_edit_optional_request_params[ + "aspectRatio" + ] + if image_config: generation_config["image_config"] = image_config @@ -191,7 +203,9 @@ class VertexAIGeminiImageEditConfig(BaseImageEditConfig, VertexLLM): payload: Any = json.dumps(request_body) empty_files = cast(RequestFiles, []) - return cast(Tuple[Dict[str, Any], Optional[RequestFiles]], (payload, empty_files)) + return cast( + Tuple[Dict[str, Any], Optional[RequestFiles]], (payload, empty_files) + ) def transform_image_edit_response( self, diff --git a/litellm/llms/vertex_ai/image_edit/vertex_imagen_transformation.py b/litellm/llms/vertex_ai/image_edit/vertex_imagen_transformation.py index b58825e1faa..7979e0e7901 100644 --- a/litellm/llms/vertex_ai/image_edit/vertex_imagen_transformation.py +++ b/litellm/llms/vertex_ai/image_edit/vertex_imagen_transformation.py @@ -29,9 +29,10 @@ else: class VertexAIImagenImageEditConfig(BaseImageEditConfig, VertexLLM): """ Vertex AI Imagen Image Edit Configuration - + Uses predict API for Imagen models on Vertex AI """ + SUPPORTED_PARAMS: List[str] = ["n", "size", "mask"] def __init__(self) -> None: @@ -59,12 +60,12 @@ class VertexAIImagenImageEditConfig(BaseImageEditConfig, VertexLLM): # Map OpenAI parameters to Imagen format if "n" in filtered_params: mapped_params["sampleCount"] = filtered_params["n"] - + if "size" in filtered_params: mapped_params["aspectRatio"] = self._map_size_to_aspect_ratio( filtered_params["size"] # type: ignore[arg-type] ) - + if "mask" in filtered_params: mapped_params["mask"] = filtered_params["mask"] @@ -126,7 +127,9 @@ class VertexAIImagenImageEditConfig(BaseImageEditConfig, VertexLLM): vertex_location = self._resolve_vertex_location() if not vertex_project or not vertex_location: - raise ValueError("vertex_project and vertex_location are required for Vertex AI") + raise ValueError( + "vertex_project and vertex_location are required for Vertex AI" + ) # Use the model name as provided, handling vertex_ai prefix model_name = model @@ -151,35 +154,34 @@ class VertexAIImagenImageEditConfig(BaseImageEditConfig, VertexLLM): ) -> Tuple[Dict[str, Any], Optional[RequestFiles]]: # Prepare reference images in the correct Imagen format if image is None: - raise ValueError("Vertex AI Imagen image edit requires at least one reference image.") - reference_images = self._prepare_reference_images(image, image_edit_optional_request_params) + raise ValueError( + "Vertex AI Imagen image edit requires at least one reference image." + ) + reference_images = self._prepare_reference_images( + image, image_edit_optional_request_params + ) if not reference_images: - raise ValueError("Vertex AI Imagen image edit requires at least one reference image.") + raise ValueError( + "Vertex AI Imagen image edit requires at least one reference image." + ) if prompt is None: raise ValueError("Vertex AI Imagen image edit requires a prompt.") # Correct Imagen instances format - instances = [ - { - "prompt": prompt, - "referenceImages": reference_images - } - ] + instances = [{"prompt": prompt, "referenceImages": reference_images}] # Extract OpenAI parameters and set sensible defaults for Vertex AI-specific parameters sample_count = image_edit_optional_request_params.get("sampleCount", 1) # Use sensible defaults for Vertex AI-specific parameters (not exposed to users) edit_mode = "EDIT_MODE_INPAINT_INSERTION" # Default edit mode base_steps = 50 # Default number of steps - + # Imagen parameters with correct structure parameters = { "sampleCount": sample_count, "editMode": edit_mode, - "editConfig": { - "baseSteps": base_steps - } + "editConfig": {"baseSteps": base_steps}, } # Set default values for Vertex AI-specific parameters (not configurable by users via OpenAI API) @@ -188,12 +190,14 @@ class VertexAIImagenImageEditConfig(BaseImageEditConfig, VertexLLM): request_body: Dict[str, Any] = { "instances": instances, - "parameters": parameters + "parameters": parameters, } payload: Any = json.dumps(request_body) empty_files = cast(RequestFiles, []) - return cast(Tuple[Dict[str, Any], Optional[RequestFiles]], (payload, empty_files)) + return cast( + Tuple[Dict[str, Any], Optional[RequestFiles]], (payload, empty_files) + ) def transform_image_edit_response( self, @@ -231,7 +235,7 @@ class VertexAIImagenImageEditConfig(BaseImageEditConfig, VertexLLM): """Map OpenAI size format to Imagen aspect ratio format""" aspect_ratio_map = { "1024x1024": "1:1", - "1792x1024": "16:9", + "1792x1024": "16:9", "1024x1792": "9:16", "1280x896": "4:3", "896x1280": "3:4", @@ -239,8 +243,9 @@ class VertexAIImagenImageEditConfig(BaseImageEditConfig, VertexLLM): return aspect_ratio_map.get(size, "1:1") def _prepare_reference_images( - self, image: Union[FileTypes, List[FileTypes]], - image_edit_optional_request_params: Dict[str, Any] + self, + image: Union[FileTypes, List[FileTypes]], + image_edit_optional_request_params: Dict[str, Any], ) -> List[Dict[str, Any]]: """ Prepare reference images in the correct Imagen API format @@ -252,41 +257,37 @@ class VertexAIImagenImageEditConfig(BaseImageEditConfig, VertexLLM): images = [image] reference_images: List[Dict[str, Any]] = [] - + for idx, img in enumerate(images): if img is None: continue image_bytes = self._read_all_bytes(img) base64_data = base64.b64encode(image_bytes).decode("utf-8") - + # Create reference image structure reference_image = { "referenceType": "REFERENCE_TYPE_RAW", "referenceId": idx + 1, - "referenceImage": { - "bytesBase64Encoded": base64_data - } + "referenceImage": {"bytesBase64Encoded": base64_data}, } - + reference_images.append(reference_image) - + # Handle mask image if provided (for inpainting) mask_image = image_edit_optional_request_params.get("mask") if mask_image is not None: mask_bytes = self._read_all_bytes(mask_image) mask_base64 = base64.b64encode(mask_bytes).decode("utf-8") - + mask_reference = { "referenceType": "REFERENCE_TYPE_MASK", "referenceId": len(reference_images) + 1, - "referenceImage": { - "bytesBase64Encoded": mask_base64 - }, + "referenceImage": {"bytesBase64Encoded": mask_base64}, "maskImageConfig": { "maskMode": "MASK_MODE_USER_PROVIDED", - "dilation": 0.03 # Default dilation value (not configurable via OpenAI API) - } + "dilation": 0.03, # Default dilation value (not configurable via OpenAI API) + }, } reference_images.append(mask_reference) @@ -303,7 +304,9 @@ class VertexAIImagenImageEditConfig(BaseImageEditConfig, VertexLLM): if isinstance(image, (list, tuple)): for item in image: if item is not None: - return self._read_all_bytes(item, depth=depth + 1, max_depth=max_depth) + return self._read_all_bytes( + item, depth=depth + 1, max_depth=max_depth + ) raise ValueError("Unsupported image type for Vertex AI Imagen image edit.") if isinstance(image, dict): @@ -315,9 +318,13 @@ class VertexAIImagenImageEditConfig(BaseImageEditConfig, VertexLLM): return base64.b64decode(value) except Exception: continue - return self._read_all_bytes(value, depth=depth + 1, max_depth=max_depth) + return self._read_all_bytes( + value, depth=depth + 1, max_depth=max_depth + ) if "path" in image: - return self._read_all_bytes(image["path"], depth=depth + 1, max_depth=max_depth) + return self._read_all_bytes( + image["path"], depth=depth + 1, max_depth=max_depth + ) if isinstance(image, bytes): return image diff --git a/litellm/llms/vertex_ai/image_generation/__init__.py b/litellm/llms/vertex_ai/image_generation/__init__.py index a6f6156167a..9445660dba7 100644 --- a/litellm/llms/vertex_ai/image_generation/__init__.py +++ b/litellm/llms/vertex_ai/image_generation/__init__.py @@ -10,29 +10,29 @@ from .vertex_gemini_transformation import VertexAIGeminiImageGenerationConfig from .vertex_imagen_transformation import VertexAIImagenImageGenerationConfig __all__ = [ - "VertexAIGeminiImageGenerationConfig", + "VertexAIGeminiImageGenerationConfig", "VertexAIImagenImageGenerationConfig", - "get_vertex_ai_image_generation_config", + "get_vertex_ai_image_generation_config", ] def get_vertex_ai_image_generation_config(model: str) -> BaseImageGenerationConfig: """ Get the appropriate image generation config for a Vertex AI model. - + Routes to the correct transformation class based on the model type: - Gemini image generation models use generateContent API (VertexAIGeminiImageGenerationConfig) - Imagen models use predict API (VertexAIImagenImageGenerationConfig) - + Args: model: The model name (e.g., "gemini-2.5-flash-image", "imagegeneration@006") - + Returns: BaseImageGenerationConfig: The appropriate configuration class """ # Determine the model route model_route = get_vertex_ai_model_route(model) - + if model_route == VertexAIModelRoute.GEMINI: # Gemini models use generateContent API return VertexAIGeminiImageGenerationConfig() @@ -40,4 +40,3 @@ def get_vertex_ai_image_generation_config(model: str) -> BaseImageGenerationConf # Default to Imagen for other models (imagegeneration, etc.) # This includes NON_GEMINI models like imagegeneration@006 return VertexAIImagenImageGenerationConfig() - 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 447612877fe..98e02743bd2 100644 --- a/litellm/llms/vertex_ai/image_generation/vertex_gemini_transformation.py +++ b/litellm/llms/vertex_ai/image_generation/vertex_gemini_transformation.py @@ -29,18 +29,16 @@ else: class VertexAIGeminiImageGenerationConfig(BaseImageGenerationConfig, VertexLLM): """ Vertex AI Gemini Image Generation Configuration - + Uses generateContent API for Gemini image generation models on Vertex AI Supports models like gemini-2.5-flash-image, gemini-3-pro-image-preview, etc. """ - + def __init__(self) -> None: BaseImageGenerationConfig.__init__(self) VertexLLM.__init__(self) - - def get_supported_openai_params( - self, model: str - ) -> list: + + def get_supported_openai_params(self, model: str) -> list: """ Gemini image generation supported parameters @@ -55,7 +53,7 @@ class VertexAIGeminiImageGenerationConfig(BaseImageGenerationConfig, VertexLLM): "imageSize", "image_size", ] - + def map_openai_params( self, non_default_params: dict, @@ -65,7 +63,7 @@ class VertexAIGeminiImageGenerationConfig(BaseImageGenerationConfig, VertexLLM): ) -> dict: supported_params = self.get_supported_openai_params(model) mapped_params = {} - + for k, v in non_default_params.items(): if k not in optional_params.keys(): if k in supported_params: @@ -81,22 +79,22 @@ class VertexAIGeminiImageGenerationConfig(BaseImageGenerationConfig, VertexLLM): mapped_params["imageSize"] = v else: mapped_params[k] = v - + return mapped_params - + def _map_size_to_aspect_ratio(self, size: str) -> str: """ Map OpenAI size format to Gemini aspect ratio format """ aspect_ratio_map = { "1024x1024": "1:1", - "1792x1024": "16:9", + "1792x1024": "16:9", "1024x1792": "9:16", "1280x896": "4:3", - "896x1280": "3:4" + "896x1280": "3:4", } return aspect_ratio_map.get(size, "1:1") - + def _resolve_vertex_project(self) -> Optional[str]: return ( getattr(self, "_vertex_project", None) @@ -148,11 +146,19 @@ class VertexAIGeminiImageGenerationConfig(BaseImageGenerationConfig, VertexLLM): # First check litellm_params (where vertex_ai_project/vertex_ai_location are passed) # then fall back to environment variables and other sources - vertex_project = self.safe_get_vertex_ai_project(litellm_params) or self._resolve_vertex_project() - vertex_location = self.safe_get_vertex_ai_location(litellm_params) or self._resolve_vertex_location() + vertex_project = ( + self.safe_get_vertex_ai_project(litellm_params) + or self._resolve_vertex_project() + ) + vertex_location = ( + self.safe_get_vertex_ai_location(litellm_params) + or self._resolve_vertex_location() + ) if not vertex_project or not vertex_location: - raise ValueError("vertex_project and vertex_location are required for Vertex AI") + raise ValueError( + "vertex_project and vertex_location are required for Vertex AI" + ) base_url = get_vertex_base_url(vertex_location) @@ -169,17 +175,23 @@ class VertexAIGeminiImageGenerationConfig(BaseImageGenerationConfig, VertexLLM): api_base: Optional[str] = None, ) -> dict: headers = headers or {} - + # If a custom api_base is provided, skip credential validation # This allows users to use proxies or mock endpoints without needing Vertex AI credentials _api_base = litellm_params.get("api_base") or api_base if _api_base is not None: return headers - + # First check litellm_params (where vertex_ai_project/vertex_ai_credentials are passed) # then fall back to environment variables and other sources - vertex_project = self.safe_get_vertex_ai_project(litellm_params) or self._resolve_vertex_project() - vertex_credentials = self.safe_get_vertex_ai_credentials(litellm_params) or self._resolve_vertex_credentials() + vertex_project = ( + self.safe_get_vertex_ai_project(litellm_params) + or self._resolve_vertex_project() + ) + vertex_credentials = ( + self.safe_get_vertex_ai_credentials(litellm_params) + or self._resolve_vertex_credentials() + ) access_token, _ = self._ensure_access_token( credentials=vertex_credentials, project_id=vertex_project, @@ -197,51 +209,44 @@ class VertexAIGeminiImageGenerationConfig(BaseImageGenerationConfig, VertexLLM): ) -> dict: """ Transform the image generation request to Gemini format - + Uses generateContent API with responseModalities: ["IMAGE"] """ # Prepare messages with the prompt - contents = [ - { - "role": "user", - "parts": [{"text": prompt}] - } - ] - + contents = [{"role": "user", "parts": [{"text": prompt}]}] + # Prepare generation config - generation_config: Dict[str, Any] = { - "responseModalities": ["IMAGE"] - } - + generation_config: Dict[str, Any] = {"responseModalities": ["IMAGE"]} + # Handle image-specific config parameters image_config: Dict[str, Any] = {} - + # Map aspectRatio if "aspectRatio" in optional_params: image_config["aspectRatio"] = optional_params["aspectRatio"] elif "aspect_ratio" in optional_params: image_config["aspectRatio"] = optional_params["aspect_ratio"] - + # Map imageSize (for Gemini 3 Pro) if "imageSize" in optional_params: image_config["imageSize"] = optional_params["imageSize"] elif "image_size" in optional_params: image_config["imageSize"] = optional_params["image_size"] - + if image_config: generation_config["imageConfig"] = image_config - + # Handle candidate_count (n parameter) if "candidate_count" in optional_params: generation_config["candidateCount"] = optional_params["candidate_count"] elif "n" in optional_params: generation_config["candidateCount"] = optional_params["n"] - + request_body: Dict[str, Any] = { "contents": contents, - "generationConfig": generation_config + "generationConfig": generation_config, } - + return request_body def _transform_image_usage(self, usage: dict) -> ImageUsage: @@ -289,7 +294,7 @@ class VertexAIGeminiImageGenerationConfig(BaseImageGenerationConfig, VertexLLM): status_code=raw_response.status_code, headers=raw_response.headers, ) - + if not model_response.data: model_response.data = [] @@ -304,14 +309,19 @@ class VertexAIGeminiImageGenerationConfig(BaseImageGenerationConfig, VertexLLM): 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, - )) + 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): model_response.usage = self._transform_image_usage(usage_metadata) - - return model_response + return model_response diff --git a/litellm/llms/vertex_ai/image_generation/vertex_imagen_transformation.py b/litellm/llms/vertex_ai/image_generation/vertex_imagen_transformation.py index 6f9e3874173..1c7696d55a2 100644 --- a/litellm/llms/vertex_ai/image_generation/vertex_imagen_transformation.py +++ b/litellm/llms/vertex_ai/image_generation/vertex_imagen_transformation.py @@ -27,26 +27,23 @@ else: class VertexAIImagenImageGenerationConfig(BaseImageGenerationConfig, VertexLLM): """ Vertex AI Imagen Image Generation Configuration - + Uses predict API for Imagen models on Vertex AI Supports models like imagegeneration@006 """ - + def __init__(self) -> None: BaseImageGenerationConfig.__init__(self) VertexLLM.__init__(self) - + def get_supported_openai_params( self, model: str ) -> List[OpenAIImageGenerationOptionalParams]: """ Imagen API supported parameters """ - return [ - "n", - "size" - ] - + return ["n", "size"] + def map_openai_params( self, non_default_params: dict, @@ -56,7 +53,7 @@ class VertexAIImagenImageGenerationConfig(BaseImageGenerationConfig, VertexLLM): ) -> dict: supported_params = self.get_supported_openai_params(model) mapped_params = {} - + for k, v in non_default_params.items(): if k not in optional_params.keys(): if k in supported_params: @@ -68,22 +65,22 @@ class VertexAIImagenImageGenerationConfig(BaseImageGenerationConfig, VertexLLM): mapped_params["aspectRatio"] = self._map_size_to_aspect_ratio(v) else: mapped_params[k] = v - + return mapped_params - + def _map_size_to_aspect_ratio(self, size: str) -> str: """ Map OpenAI size format to Imagen aspect ratio format """ aspect_ratio_map = { "1024x1024": "1:1", - "1792x1024": "16:9", + "1792x1024": "16:9", "1024x1792": "9:16", "1280x896": "4:3", - "896x1280": "3:4" + "896x1280": "3:4", } return aspect_ratio_map.get(size, "1:1") - + def _resolve_vertex_project(self) -> Optional[str]: return ( getattr(self, "_vertex_project", None) @@ -135,11 +132,19 @@ class VertexAIImagenImageGenerationConfig(BaseImageGenerationConfig, VertexLLM): # First check litellm_params (where vertex_ai_project/vertex_ai_location are passed) # then fall back to environment variables and other sources - vertex_project = self.safe_get_vertex_ai_project(litellm_params) or self._resolve_vertex_project() - vertex_location = self.safe_get_vertex_ai_location(litellm_params) or self._resolve_vertex_location() + vertex_project = ( + self.safe_get_vertex_ai_project(litellm_params) + or self._resolve_vertex_project() + ) + vertex_location = ( + self.safe_get_vertex_ai_location(litellm_params) + or self._resolve_vertex_location() + ) if not vertex_project or not vertex_location: - raise ValueError("vertex_project and vertex_location are required for Vertex AI") + raise ValueError( + "vertex_project and vertex_location are required for Vertex AI" + ) base_url = get_vertex_base_url(vertex_location) @@ -156,17 +161,23 @@ class VertexAIImagenImageGenerationConfig(BaseImageGenerationConfig, VertexLLM): api_base: Optional[str] = None, ) -> dict: headers = headers or {} - + # If a custom api_base is provided, skip credential validation # This allows users to use proxies or mock endpoints without needing Vertex AI credentials _api_base = litellm_params.get("api_base") or api_base if _api_base is not None: return headers - + # First check litellm_params (where vertex_ai_project/vertex_ai_credentials are passed) # then fall back to environment variables and other sources - vertex_project = self.safe_get_vertex_ai_project(litellm_params) or self._resolve_vertex_project() - vertex_credentials = self.safe_get_vertex_ai_credentials(litellm_params) or self._resolve_vertex_credentials() + vertex_project = ( + self.safe_get_vertex_ai_project(litellm_params) + or self._resolve_vertex_project() + ) + vertex_credentials = ( + self.safe_get_vertex_ai_credentials(litellm_params) + or self._resolve_vertex_credentials() + ) access_token, _ = self._ensure_access_token( credentials=vertex_credentials, project_id=vertex_project, @@ -184,22 +195,22 @@ class VertexAIImagenImageGenerationConfig(BaseImageGenerationConfig, VertexLLM): ) -> dict: """ Transform the image generation request to Imagen format - + Uses predict API with instances and parameters """ # Default parameters default_params = { "sampleCount": 1, } - + # Merge with optional params parameters = {**default_params, **optional_params} - + request_body = { "instances": [{"prompt": prompt}], "parameters": parameters, } - + return request_body def transform_image_generation_response( @@ -226,7 +237,7 @@ class VertexAIImagenImageGenerationConfig(BaseImageGenerationConfig, VertexLLM): status_code=raw_response.status_code, headers=raw_response.headers, ) - + if not model_response.data: model_response.data = [] @@ -235,10 +246,11 @@ class VertexAIImagenImageGenerationConfig(BaseImageGenerationConfig, VertexLLM): for prediction in predictions: # Imagen returns images as bytesBase64Encoded if "bytesBase64Encoded" in prediction: - model_response.data.append(ImageObject( - b64_json=prediction["bytesBase64Encoded"], - url=None, - )) - - return model_response + model_response.data.append( + ImageObject( + b64_json=prediction["bytesBase64Encoded"], + url=None, + ) + ) + return model_response diff --git a/litellm/llms/vertex_ai/ocr/__init__.py b/litellm/llms/vertex_ai/ocr/__init__.py index fa8c85da9c5..15da24f3089 100644 --- a/litellm/llms/vertex_ai/ocr/__init__.py +++ b/litellm/llms/vertex_ai/ocr/__init__.py @@ -2,4 +2,3 @@ from .transformation import VertexAIOCRConfig __all__ = ["VertexAIOCRConfig"] - diff --git a/litellm/llms/vertex_ai/ocr/common_utils.py b/litellm/llms/vertex_ai/ocr/common_utils.py index dc2c07420bf..3e5fbe23447 100644 --- a/litellm/llms/vertex_ai/ocr/common_utils.py +++ b/litellm/llms/vertex_ai/ocr/common_utils.py @@ -14,20 +14,20 @@ if TYPE_CHECKING: def get_vertex_ai_ocr_config(model: str) -> Optional["BaseOCRConfig"]: """ Determine which Vertex AI OCR configuration to use based on the model name. - + Vertex AI supports multiple OCR services: - Vertex AI OCR: vertex_ai/ - + Args: model: The model name (e.g., "vertex_ai/ocr/") - + Returns: OCR configuration instance for the specified model - + Examples: >>> get_vertex_ai_ocr_config("vertex_ai/deepseek-ai/deepseek-ocr-maas") - + >>> get_vertex_ai_ocr_config("vertex_ai/ocr/mistral-ocr-maas") """ @@ -35,7 +35,7 @@ def get_vertex_ai_ocr_config(model: str) -> Optional["BaseOCRConfig"]: VertexAIDeepSeekOCRConfig, ) from litellm.llms.vertex_ai.ocr.transformation import VertexAIOCRConfig + if "deepseek" in model: return VertexAIDeepSeekOCRConfig() return VertexAIOCRConfig() - diff --git a/litellm/llms/vertex_ai/ocr/deepseek_transformation.py b/litellm/llms/vertex_ai/ocr/deepseek_transformation.py index b16f73af3f6..953bb51fd1c 100644 --- a/litellm/llms/vertex_ai/ocr/deepseek_transformation.py +++ b/litellm/llms/vertex_ai/ocr/deepseek_transformation.py @@ -26,7 +26,7 @@ else: class VertexAIDeepSeekOCRConfig(BaseOCRConfig): """ Vertex AI DeepSeek OCR transformation configuration. - + Vertex AI DeepSeek OCR uses the chat completion API format through the openapi endpoint. This transformation converts OCR requests to chat completion format and vice versa. """ @@ -46,16 +46,20 @@ class VertexAIDeepSeekOCRConfig(BaseOCRConfig): ) -> Dict: """ Validate environment and return headers for Vertex AI OCR. - + Vertex AI uses Bearer token authentication with access token from credentials. """ # Extract Vertex AI parameters using safe helpers from VertexBase # Use safe_get_* methods that don't mutate litellm_params dict litellm_params = litellm_params or {} - - vertex_project = VertexBase.safe_get_vertex_ai_project(litellm_params=litellm_params) - vertex_credentials = VertexBase.safe_get_vertex_ai_credentials(litellm_params=litellm_params) - + + vertex_project = VertexBase.safe_get_vertex_ai_project( + litellm_params=litellm_params + ) + vertex_credentials = VertexBase.safe_get_vertex_ai_credentials( + litellm_params=litellm_params + ) + # Get access token from Vertex credentials access_token, project_id = self.vertex_base.get_access_token( credentials=vertex_credentials, @@ -80,25 +84,29 @@ class VertexAIDeepSeekOCRConfig(BaseOCRConfig): ) -> str: """ Get complete URL for Vertex AI DeepSeek OCR endpoint. - - Vertex AI endpoint format: + + Vertex AI endpoint format: https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/endpoints/openapi/chat/completions - + Args: api_base: Vertex AI API base URL (optional) model: Model name (e.g., "deepseek-ai/deepseek-ocr-maas") optional_params: Optional parameters litellm_params: LiteLLM parameters containing vertex_project, vertex_location - + Returns: Complete URL for Vertex AI OCR endpoint """ # Extract Vertex AI parameters using safe helpers from VertexBase # Use safe_get_* methods that don't mutate litellm_params dict litellm_params = litellm_params or {} - - vertex_project = VertexBase.safe_get_vertex_ai_project(litellm_params=litellm_params) - vertex_location = VertexBase.safe_get_vertex_ai_location(litellm_params=litellm_params) - + + vertex_project = VertexBase.safe_get_vertex_ai_project( + litellm_params=litellm_params + ) + vertex_location = VertexBase.safe_get_vertex_ai_location( + litellm_params=litellm_params + ) + if vertex_project is None: raise ValueError( "Missing vertex_project - Set VERTEXAI_PROJECT environment variable or pass vertex_project parameter" @@ -113,7 +121,7 @@ class VertexAIDeepSeekOCRConfig(BaseOCRConfig): # Ensure no trailing slash api_base = api_base.rstrip("/") - + # Vertex AI DeepSeek OCR endpoint format # Format: https://{region}-aiplatform.googleapis.com/v1/projects/{project}/locations/{region}/endpoints/openapi/chat/completions return f"{api_base}/v1/projects/{vertex_project}/locations/{vertex_location}/endpoints/openapi/chat/completions" @@ -128,63 +136,56 @@ class VertexAIDeepSeekOCRConfig(BaseOCRConfig): ) -> OCRRequestData: """ Transform OCR request to chat completion format for Vertex AI DeepSeek OCR. - + Converts OCR document format to chat completion messages format: - Input: {"type": "image_url", "image_url": "gs://..."} - Output: {"model": "deepseek-ai/deepseek-ocr-maas", "messages": [{"role": "user", "content": [{"type": "image_url", "image_url": "gs://..."}]}]} - + Args: model: Model name (e.g., "deepseek-ai/deepseek-ocr-maas") document: Document dict from user (Mistral OCR format) optional_params: Already mapped optional parameters headers: Request headers **kwargs: Additional arguments - + Returns: OCRRequestData with JSON data in chat completion format """ - verbose_logger.debug("Vertex AI DeepSeek OCR transform_ocr_request (sync) called") - + verbose_logger.debug( + "Vertex AI DeepSeek OCR transform_ocr_request (sync) called" + ) + if not isinstance(document, dict): raise ValueError(f"Expected document dict, got {type(document)}") - + # Extract document type and URL doc_type = document.get("type") image_url = None document_url = None - + if doc_type == "image_url": image_url = document.get("image_url", "") elif doc_type == "document_url": document_url = document.get("document_url", "") else: - raise ValueError(f"Unsupported document type: {doc_type}. Expected 'image_url' or 'document_url'") - + raise ValueError( + f"Unsupported document type: {doc_type}. Expected 'image_url' or 'document_url'" + ) + # Build chat completion message content content_item = {} if image_url: - content_item = { - "type": "image_url", - "image_url": image_url - } + content_item = {"type": "image_url", "image_url": image_url} elif document_url: # For document URLs, we use image_url type as well (Vertex AI supports both) - content_item = { - "type": "image_url", - "image_url": document_url - } - + content_item = {"type": "image_url", "image_url": document_url} + # Build chat completion request data = { "model": "deepseek-ai/" + model, - "messages": [ - { - "role": "user", - "content": [content_item] - } - ] + "messages": [{"role": "user", "content": [content_item]}], } - + # Add optional parameters (stream, temperature, etc.) # Filter out OCR-specific params that don't apply to chat completion chat_completion_params = {} @@ -192,11 +193,13 @@ class VertexAIDeepSeekOCRConfig(BaseOCRConfig): # Include common chat completion params if key in ["stream", "temperature", "max_tokens", "top_p", "n", "stop"]: chat_completion_params[key] = value - + data.update(chat_completion_params) - - verbose_logger.debug("Vertex AI DeepSeek OCR: Transformed request to chat completion format") - + + verbose_logger.debug( + "Vertex AI DeepSeek OCR: Transformed request to chat completion format" + ) + return OCRRequestData(data=data, files=None) async def async_transform_ocr_request( @@ -209,16 +212,16 @@ class VertexAIDeepSeekOCRConfig(BaseOCRConfig): ) -> OCRRequestData: """ Transform OCR request to chat completion format for Vertex AI DeepSeek OCR (async). - + Same as sync version - no async-specific logic needed. - + Args: model: Model name document: Document dict from user optional_params: Already mapped optional parameters headers: Request headers **kwargs: Additional arguments - + Returns: OCRRequestData with JSON data in chat completion format """ @@ -239,7 +242,7 @@ class VertexAIDeepSeekOCRConfig(BaseOCRConfig): ) -> OCRResponse: """ Transform chat completion response to OCR format. - + Vertex AI DeepSeek OCR returns chat completion format: { "id": "...", @@ -252,35 +255,35 @@ class VertexAIDeepSeekOCRConfig(BaseOCRConfig): }], "usage": {...} } - + We need to extract the content and convert it to OCRResponse format. - + Args: model: Model name raw_response: Raw HTTP response from Vertex AI logging_obj: Logging object **kwargs: Additional arguments - + Returns: OCRResponse in standard format """ verbose_logger.debug("Vertex AI DeepSeek OCR transform_ocr_response called") verbose_logger.debug(f"Raw response: {raw_response.text}") - + try: response_json = raw_response.json() - + # Extract content from chat completion response choices = response_json.get("choices", []) if not choices: raise ValueError("No choices in chat completion response") - + message = choices[0].get("message", {}) content = message.get("content", "") - + if not content: raise ValueError("No content in chat completion response") - + # Try to parse content as JSON (OCR result might be JSON string) ocr_data = None try: @@ -292,28 +295,18 @@ class VertexAIDeepSeekOCRConfig(BaseOCRConfig): else: # If content is markdown text, create a single page with the markdown ocr_data = { - "pages": [ - { - "index": 0, - "markdown": content - } - ], + "pages": [{"index": 0, "markdown": content}], "model": model, - "usage_info": response_json.get("usage", {}) + "usage_info": response_json.get("usage", {}), } except json.JSONDecodeError: # If JSON parsing fails, treat content as markdown ocr_data = { - "pages": [ - { - "index": 0, - "markdown": content - } - ], + "pages": [{"index": 0, "markdown": content}], "model": model, - "usage_info": response_json.get("usage", {}) + "usage_info": response_json.get("usage", {}), } - + # Ensure we have the expected structure if "pages" not in ocr_data: # If OCR data doesn't have pages, wrap the content in a page @@ -321,20 +314,24 @@ class VertexAIDeepSeekOCRConfig(BaseOCRConfig): "pages": [ { "index": 0, - "markdown": content if isinstance(content, str) else json.dumps(content) + "markdown": content + if isinstance(content, str) + else json.dumps(content), } ], "model": ocr_data.get("model", model), - "usage_info": ocr_data.get("usage_info", response_json.get("usage", {})) + "usage_info": ocr_data.get( + "usage_info", response_json.get("usage", {}) + ), } - + # Convert usage info if present usage_info = None if "usage_info" in ocr_data: usage_dict = ocr_data["usage_info"] if isinstance(usage_dict, dict): usage_info = OCRUsageInfo(**usage_dict) - + # Build OCRResponse pages = [] for page_data in ocr_data.get("pages", []): @@ -344,14 +341,18 @@ class VertexAIDeepSeekOCRConfig(BaseOCRConfig): index=page_data.get("index", 0), markdown=page_data.get("markdown", ""), images=page_data.get("images"), - dimensions=page_data.get("dimensions") + dimensions=page_data.get("dimensions"), ) pages.append(page) - + if not pages: # Create a default page if none exist - pages = [OCRPage(index=0, markdown=content if isinstance(content, str) else "")] - + pages = [ + OCRPage( + index=0, markdown=content if isinstance(content, str) else "" + ) + ] + return OCRResponse( pages=pages, model=ocr_data.get("model", model), @@ -359,7 +360,7 @@ class VertexAIDeepSeekOCRConfig(BaseOCRConfig): usage_info=usage_info, object="ocr", ) - + except Exception as e: verbose_logger.error(f"Error parsing Vertex AI DeepSeek OCR response: {e}") raise e @@ -373,15 +374,15 @@ class VertexAIDeepSeekOCRConfig(BaseOCRConfig): ) -> OCRResponse: """ Async transform chat completion response to OCR format. - + Same as sync version - no async-specific logic needed. - + Args: model: Model name raw_response: Raw HTTP response logging_obj: Logging object **kwargs: Additional arguments - + Returns: OCRResponse in standard format """ @@ -391,4 +392,3 @@ class VertexAIDeepSeekOCRConfig(BaseOCRConfig): logging_obj=logging_obj, **kwargs, ) - diff --git a/litellm/llms/vertex_ai/ocr/transformation.py b/litellm/llms/vertex_ai/ocr/transformation.py index 849e332dae3..6fe88459ea2 100644 --- a/litellm/llms/vertex_ai/ocr/transformation.py +++ b/litellm/llms/vertex_ai/ocr/transformation.py @@ -17,12 +17,12 @@ from litellm.llms.vertex_ai.vertex_llm_base import VertexBase class VertexAIOCRConfig(MistralOCRConfig): """ Vertex AI Mistral OCR transformation configuration. - + Vertex AI uses Mistral's OCR API format through the Mistral publisher endpoint. Inherits transformation logic from MistralOCRConfig since they use the same format. - + Reference: Vertex AI Mistral OCR documentation - + Important: Vertex AI OCR only supports base64 data URIs (data:image/..., data:application/pdf;base64,...). Regular URLs are not supported. """ @@ -42,16 +42,20 @@ class VertexAIOCRConfig(MistralOCRConfig): ) -> Dict: """ Validate environment and return headers for Vertex AI OCR. - + Vertex AI uses Bearer token authentication with access token from credentials. """ # Extract Vertex AI parameters using safe helpers from VertexBase # Use safe_get_* methods that don't mutate litellm_params dict litellm_params = litellm_params or {} - - vertex_project = VertexBase.safe_get_vertex_ai_project(litellm_params=litellm_params) - vertex_credentials = VertexBase.safe_get_vertex_ai_credentials(litellm_params=litellm_params) - + + vertex_project = VertexBase.safe_get_vertex_ai_project( + litellm_params=litellm_params + ) + vertex_credentials = VertexBase.safe_get_vertex_ai_credentials( + litellm_params=litellm_params + ) + # Get access token from Vertex credentials access_token, project_id = self.vertex_base.get_access_token( credentials=vertex_credentials, @@ -76,25 +80,29 @@ class VertexAIOCRConfig(MistralOCRConfig): ) -> str: """ Get complete URL for Vertex AI OCR endpoint. - - Vertex AI endpoint format: + + Vertex AI endpoint format: https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/publishers/mistralai/ocr - + Args: api_base: Vertex AI API base URL (optional) model: Model name (not used in URL construction) optional_params: Optional parameters litellm_params: LiteLLM parameters containing vertex_project, vertex_location - + Returns: Complete URL for Vertex AI OCR endpoint """ # Extract Vertex AI parameters using safe helpers from VertexBase # Use safe_get_* methods that don't mutate litellm_params dict litellm_params = litellm_params or {} - - vertex_project = VertexBase.safe_get_vertex_ai_project(litellm_params=litellm_params) - vertex_location = VertexBase.safe_get_vertex_ai_location(litellm_params=litellm_params) - + + vertex_project = VertexBase.safe_get_vertex_ai_project( + litellm_params=litellm_params + ) + vertex_location = VertexBase.safe_get_vertex_ai_location( + litellm_params=litellm_params + ) + if vertex_project is None: raise ValueError( "Missing vertex_project - Set VERTEXAI_PROJECT environment variable or pass vertex_project parameter" @@ -109,7 +117,7 @@ class VertexAIOCRConfig(MistralOCRConfig): # Ensure no trailing slash api_base = api_base.rstrip("/") - + # Vertex AI OCR endpoint format for Mistral publisher # Format: https://{region}-aiplatform.googleapis.com/v1/projects/{project}/locations/{region}/publishers/mistralai/models/{model}:rawPredict return f"{api_base}/v1/projects/{vertex_project}/locations/{vertex_location}/publishers/mistralai/models/{model}:rawPredict" @@ -117,47 +125,55 @@ class VertexAIOCRConfig(MistralOCRConfig): def _convert_url_to_data_uri_sync(self, url: str) -> str: """ Synchronously convert a URL to a base64 data URI. - + Vertex AI OCR doesn't have internet access, so we need to fetch URLs and convert them to base64 data URIs. - + Args: url: The URL to convert - + Returns: Base64 data URI string """ - verbose_logger.debug(f"Vertex AI OCR: Converting URL to base64 data URI (sync): {url}") - + verbose_logger.debug( + f"Vertex AI OCR: Converting URL to base64 data URI (sync): {url}" + ) + # Fetch and convert to base64 data URI # convert_url_to_base64 already returns a full data URI like "data:image/jpeg;base64,..." data_uri = convert_url_to_base64(url=url) - - verbose_logger.debug(f"Vertex AI OCR: Converted URL to data URI (length: {len(data_uri)})") - + + verbose_logger.debug( + f"Vertex AI OCR: Converted URL to data URI (length: {len(data_uri)})" + ) + return data_uri async def _convert_url_to_data_uri_async(self, url: str) -> str: """ Asynchronously convert a URL to a base64 data URI. - + Vertex AI OCR doesn't have internet access, so we need to fetch URLs and convert them to base64 data URIs. - + Args: url: The URL to convert - + Returns: Base64 data URI string """ - verbose_logger.debug(f"Vertex AI OCR: Converting URL to base64 data URI (async): {url}") - + verbose_logger.debug( + f"Vertex AI OCR: Converting URL to base64 data URI (async): {url}" + ) + # Fetch and convert to base64 data URI asynchronously # async_convert_url_to_base64 already returns a full data URI like "data:image/jpeg;base64,..." data_uri = await async_convert_url_to_base64(url=url) - - verbose_logger.debug(f"Vertex AI OCR: Converted URL to data URI (length: {len(data_uri)})") - + + verbose_logger.debug( + f"Vertex AI OCR: Converted URL to data URI (length: {len(data_uri)})" + ) + return data_uri def transform_ocr_request( @@ -170,29 +186,29 @@ class VertexAIOCRConfig(MistralOCRConfig): ) -> OCRRequestData: """ Transform OCR request for Vertex AI, converting URLs to base64 data URIs (sync). - + Vertex AI OCR doesn't have internet access, so we automatically fetch any URLs and convert them to base64 data URIs synchronously. - + Args: model: Model name document: Document dict from user optional_params: Already mapped optional parameters headers: Request headers **kwargs: Additional arguments - + Returns: OCRRequestData with JSON data """ verbose_logger.debug("Vertex AI OCR transform_ocr_request (sync) called") - + if not isinstance(document, dict): raise ValueError(f"Expected document dict, got {type(document)}") - + # Check if we need to convert URL to base64 doc_type = document.get("type") transformed_document = document.copy() - + if doc_type == "document_url": document_url = document.get("document_url", "") # If it's not already a data URI, convert it @@ -211,7 +227,7 @@ class VertexAIOCRConfig(MistralOCRConfig): ) data_uri = self._convert_url_to_data_uri_sync(url=image_url) transformed_document["image_url"] = data_uri - + # Call parent's transform to build the request return super().transform_ocr_request( model=model, @@ -231,29 +247,31 @@ class VertexAIOCRConfig(MistralOCRConfig): ) -> OCRRequestData: """ Transform OCR request for Vertex AI, converting URLs to base64 data URIs (async). - + Vertex AI OCR doesn't have internet access, so we automatically fetch any URLs and convert them to base64 data URIs asynchronously. - + Args: model: Model name document: Document dict from user optional_params: Already mapped optional parameters headers: Request headers **kwargs: Additional arguments - + Returns: OCRRequestData with JSON data """ - verbose_logger.debug(f"Vertex AI OCR async_transform_ocr_request - model: {model}") - + verbose_logger.debug( + f"Vertex AI OCR async_transform_ocr_request - model: {model}" + ) + if not isinstance(document, dict): raise ValueError(f"Expected document dict, got {type(document)}") - + # Check if we need to convert URL to base64 doc_type = document.get("type") transformed_document = document.copy() - + if doc_type == "document_url": document_url = document.get("document_url", "") # If it's not already a data URI, convert it @@ -272,7 +290,7 @@ class VertexAIOCRConfig(MistralOCRConfig): ) data_uri = await self._convert_url_to_data_uri_async(url=image_url) transformed_document["image_url"] = data_uri - + # Call parent's transform to build the request return super().transform_ocr_request( model=model, @@ -281,4 +299,3 @@ class VertexAIOCRConfig(MistralOCRConfig): headers=headers, **kwargs, ) - diff --git a/litellm/llms/vertex_ai/rag_engine/__init__.py b/litellm/llms/vertex_ai/rag_engine/__init__.py index 2a88b43f5a9..79b9e2c132c 100644 --- a/litellm/llms/vertex_ai/rag_engine/__init__.py +++ b/litellm/llms/vertex_ai/rag_engine/__init__.py @@ -11,4 +11,3 @@ __all__ = [ "VertexAIRAGIngestion", "VertexAIRAGTransformation", ] - diff --git a/litellm/llms/vertex_ai/rag_engine/ingestion.py b/litellm/llms/vertex_ai/rag_engine/ingestion.py index 6b435a46bc3..2ec61667795 100644 --- a/litellm/llms/vertex_ai/rag_engine/ingestion.py +++ b/litellm/llms/vertex_ai/rag_engine/ingestion.py @@ -79,10 +79,9 @@ class VertexAIRAGIngestion(BaseRAGIngestion): ) # GCP config - self.vertex_project = ( - self.vector_store_config.get("vertex_project") - or get_secret_str("VERTEXAI_PROJECT") - ) + self.vertex_project = self.vector_store_config.get( + "vertex_project" + ) or get_secret_str("VERTEXAI_PROJECT") self.vertex_location = ( self.vector_store_config.get("vertex_location") or get_secret_str("VERTEXAI_LOCATION") @@ -91,9 +90,8 @@ class VertexAIRAGIngestion(BaseRAGIngestion): self.vertex_credentials = self.vector_store_config.get("vertex_credentials") # GCS bucket for file uploads - self.gcs_bucket = ( - self.vector_store_config.get("gcs_bucket") - or os.environ.get("GCS_BUCKET_NAME") + self.gcs_bucket = self.vector_store_config.get("gcs_bucket") or os.environ.get( + "GCS_BUCKET_NAME" ) if not self.gcs_bucket: raise ValueError( @@ -312,4 +310,3 @@ class VertexAIRAGIngestion(BaseRAGIngestion): raise RuntimeError(f"Failed to import file into RAG corpus: {e}") from e return str(self.corpus_id), gcs_uri - diff --git a/litellm/llms/vertex_ai/rag_engine/transformation.py b/litellm/llms/vertex_ai/rag_engine/transformation.py index 7e70202fb75..ed5154bbdff 100644 --- a/litellm/llms/vertex_ai/rag_engine/transformation.py +++ b/litellm/llms/vertex_ai/rag_engine/transformation.py @@ -121,9 +121,7 @@ class VertexAIRAGTransformation(VertexBase): return { "import_rag_files_config": { - "gcs_source": { - "uris": [gcs_uri] - }, + "gcs_source": {"uris": [gcs_uri]}, "rag_file_transformation_config": transformation_config, } } @@ -153,4 +151,3 @@ class VertexAIRAGTransformation(VertexBase): "Authorization": f"Bearer {access_token}", "Content-Type": "application/json", } - diff --git a/litellm/llms/vertex_ai/realtime/transformation.py b/litellm/llms/vertex_ai/realtime/transformation.py index 5eae143175b..2b4746b174e 100644 --- a/litellm/llms/vertex_ai/realtime/transformation.py +++ b/litellm/llms/vertex_ai/realtime/transformation.py @@ -35,7 +35,10 @@ class VertexAIRealtimeConfig(GeminiRealtimeConfig): # ------------------------------------------------------------------ def get_complete_url( - self, api_base: Optional[str], model: str, api_key: Optional[str] = None # noqa: ARG002 + self, + api_base: Optional[str], + model: str, + api_key: Optional[str] = None, # noqa: ARG002 ) -> str: """ Build the Vertex AI Live WSS endpoint URL. diff --git a/litellm/llms/vertex_ai/rerank/transformation.py b/litellm/llms/vertex_ai/rerank/transformation.py index 953c6c84ea8..53651839671 100644 --- a/litellm/llms/vertex_ai/rerank/transformation.py +++ b/litellm/llms/vertex_ai/rerank/transformation.py @@ -13,14 +13,18 @@ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLogging from litellm.llms.base_llm.rerank.transformation import BaseRerankConfig from litellm.llms.vertex_ai.vertex_llm_base import VertexBase from litellm.secret_managers.main import get_secret_str -from litellm.types.rerank import RerankResponse, RerankResponseMeta, RerankBilledUnits, RerankResponseResult - +from litellm.types.rerank import ( + RerankResponse, + RerankResponseMeta, + RerankBilledUnits, + RerankResponseResult, +) class VertexAIRerankConfig(BaseRerankConfig, VertexBase): """ Configuration for Vertex AI Discovery Engine Rerank API - + Reference: https://cloud.google.com/generative-ai-app-builder/docs/ranking#rank_or_rerank_a_set_of_records_according_to_a_query """ @@ -28,8 +32,8 @@ class VertexAIRerankConfig(BaseRerankConfig, VertexBase): super().__init__() def get_complete_url( - self, - api_base: Optional[str], + self, + api_base: Optional[str], model: str, optional_params: Optional[Dict] = None, ) -> str: @@ -38,11 +42,11 @@ class VertexAIRerankConfig(BaseRerankConfig, VertexBase): """ # Try to get project ID from optional_params first (e.g., vertex_project parameter) params = optional_params or {} - + # Get credentials to extract project ID if needed vertex_credentials = self.safe_get_vertex_ai_credentials(params.copy()) vertex_project = self.safe_get_vertex_ai_project(params.copy()) - + # Use _ensure_access_token to extract project_id from credentials # This is the same method used in vertex embeddings _, vertex_project = self._ensure_access_token( @@ -50,19 +54,19 @@ class VertexAIRerankConfig(BaseRerankConfig, VertexBase): project_id=vertex_project, custom_llm_provider="vertex_ai", ) - + # Fallback to environment or litellm config project_id = ( vertex_project - or get_secret_str("VERTEXAI_PROJECT") + or get_secret_str("VERTEXAI_PROJECT") or litellm.vertex_project ) - + if not project_id: raise ValueError( "Vertex AI project ID is required. Please set 'VERTEXAI_PROJECT', 'litellm.vertex_project', or pass 'vertex_project' parameter" ) - + return f"https://discoveryengine.googleapis.com/v1/projects/{project_id}/locations/global/rankingConfigs/default_ranking_config:rank" def validate_environment( @@ -79,14 +83,14 @@ class VertexAIRerankConfig(BaseRerankConfig, VertexBase): litellm_params = optional_params.copy() if optional_params else {} vertex_credentials = self.safe_get_vertex_ai_credentials(litellm_params) vertex_project = self.safe_get_vertex_ai_project(litellm_params) - + # Get access token using the base class method access_token, project_id = self._ensure_access_token( credentials=vertex_credentials, project_id=vertex_project, custom_llm_provider="vertex_ai", ) - + default_headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json", @@ -113,12 +117,12 @@ class VertexAIRerankConfig(BaseRerankConfig, VertexBase): raise ValueError("query is required for Vertex AI rerank") if "documents" not in optional_rerank_params: raise ValueError("documents is required for Vertex AI rerank") - + query = optional_rerank_params["query"] documents = optional_rerank_params["documents"] top_n = optional_rerank_params.get("top_n", None) return_documents = optional_rerank_params.get("return_documents", True) - + # Convert documents to records format records = [] for idx, document in enumerate(documents): @@ -129,26 +133,18 @@ class VertexAIRerankConfig(BaseRerankConfig, VertexBase): # Handle dict format content = document.get("text", str(document)) title = document.get("title", " ".join(content.split()[:3])) - - records.append({ - "id": str(idx), - "title": title, - "content": content - }) - - request_data = { - "model": model, - "query": query, - "records": records - } - + + records.append({"id": str(idx), "title": title, "content": content}) + + request_data = {"model": model, "query": query, "records": records} + if top_n is not None: request_data["topN"] = top_n - + # Map return_documents to ignoreRecordDetailsInResponse # When return_documents is False, we want to ignore record details (return only IDs) request_data["ignoreRecordDetailsInResponse"] = not return_documents - + return request_data def transform_rerank_response( @@ -172,54 +168,55 @@ class VertexAIRerankConfig(BaseRerankConfig, VertexBase): # Extract records from response records = raw_response_json.get("records", []) - + # Convert to Cohere format results = [] for record in records: # Handle both cases: with full details and with only IDs if "score" in record: # Full response with score and details - results.append({ - "index": int(record["id"]), - "relevance_score": record.get("score", 0.0) - }) + results.append( + { + "index": int(record["id"]), + "relevance_score": record.get("score", 0.0), + } + ) else: # Response with only IDs (when ignoreRecordDetailsInResponse=true) # We can't provide a relevance score, so we'll use a default - results.append({ - "index": int(record["id"]), - "relevance_score": 1.0 # Default score when details are ignored - }) - + results.append( + { + "index": int(record["id"]), + "relevance_score": 1.0, # Default score when details are ignored + } + ) + # Sort by relevance score (descending) results.sort(key=lambda x: x["relevance_score"], reverse=True) - - # Create response in Cohere format + + # Create response in Cohere format # Convert results to proper RerankResponseResult objects rerank_results = [] for result in results: - rerank_results.append(RerankResponseResult( - index=result["index"], - relevance_score=result["relevance_score"] - )) - + rerank_results.append( + RerankResponseResult( + index=result["index"], relevance_score=result["relevance_score"] + ) + ) + # Create meta object meta = RerankResponseMeta( - billed_units=RerankBilledUnits( - search_units=len(records) - ) + billed_units=RerankBilledUnits(search_units=len(records)) ) - + return RerankResponse( - id=f"vertex_ai_rerank_{model}", - results=rerank_results, - meta=meta + id=f"vertex_ai_rerank_{model}", results=rerank_results, meta=meta ) def get_supported_cohere_rerank_params(self, model: str) -> list: return [ "query", - "documents", + "documents", "top_n", "return_documents", ] @@ -249,4 +246,3 @@ class VertexAIRerankConfig(BaseRerankConfig, VertexBase): } result.update(non_default_params) return result - diff --git a/litellm/llms/vertex_ai/text_to_speech/transformation.py b/litellm/llms/vertex_ai/text_to_speech/transformation.py index 18ca077c4da..be7bcfcadd7 100644 --- a/litellm/llms/vertex_ai/text_to_speech/transformation.py +++ b/litellm/llms/vertex_ai/text_to_speech/transformation.py @@ -164,12 +164,14 @@ class VertexAITextToSpeechConfig(BaseTextToSpeechConfig, VertexBase): voice_str = voice.get("name") if voice else None # Store credentials in litellm_params for use in transform methods - litellm_params_dict.update({ - "vertex_credentials": vertex_credentials, - "vertex_project": vertex_project, - "vertex_location": vertex_location, - "api_base": api_base, - }) + litellm_params_dict.update( + { + "vertex_credentials": vertex_credentials, + "vertex_project": vertex_project, + "vertex_location": vertex_location, + "api_base": api_base, + } + ) # Call the text_to_speech_handler response = base_llm_http_handler.text_to_speech_handler( @@ -328,7 +330,9 @@ class VertexAITextToSpeechConfig(BaseTextToSpeechConfig, VertexBase): if not input_data: raise ValueError("Either 'text' or 'ssml' must be provided.") if "text" in input_data and "ssml" in input_data: - raise ValueError("Only one of 'text' or 'ssml' should be provided, not both.") + raise ValueError( + "Only one of 'text' or 'ssml' should be provided, not both." + ) return input_data @@ -389,9 +393,8 @@ class VertexAITextToSpeechConfig(BaseTextToSpeechConfig, VertexBase): # Check for voice dict stored in: # 1. litellm_params by dispatch method # 2. optional_params by map_openai_params - voice_dict = ( - litellm_params.get("vertex_voice_dict") - or optional_params.get("vertex_voice_dict") + voice_dict = litellm_params.get("vertex_voice_dict") or optional_params.get( + "vertex_voice_dict" ) if voice_dict is not None and isinstance(voice_dict, dict): vertex_voice = VertexTextToSpeechVoice(**voice_dict) @@ -414,12 +417,16 @@ class VertexAITextToSpeechConfig(BaseTextToSpeechConfig, VertexBase): ) # Build audio configuration - audio_encoding = optional_params.get("audioEncoding", self.DEFAULT_AUDIO_ENCODING) + audio_encoding = optional_params.get( + "audioEncoding", self.DEFAULT_AUDIO_ENCODING + ) speaking_rate = optional_params.get("speakingRate", self.DEFAULT_SPEAKING_RATE) # Check for full audioConfig in optional_params if "audioConfig" in optional_params: - vertex_audio_config = VertexTextToSpeechAudioConfig(**optional_params["audioConfig"]) + vertex_audio_config = VertexTextToSpeechAudioConfig( + **optional_params["audioConfig"] + ) else: vertex_audio_config = VertexTextToSpeechAudioConfig( audioEncoding=audio_encoding, diff --git a/litellm/llms/vertex_ai/vector_stores/rag_api/transformation.py b/litellm/llms/vertex_ai/vector_stores/rag_api/transformation.py index 1be9cd820a3..4baa5774c48 100644 --- a/litellm/llms/vertex_ai/vector_stores/rag_api/transformation.py +++ b/litellm/llms/vertex_ai/vector_stores/rag_api/transformation.py @@ -162,7 +162,6 @@ class VertexVectorStoreConfig(BaseVectorStoreConfig, VertexBase): Transform Vertex AI RAG API response to standard vector store search response """ try: - response_json = response.json() # Extract contexts from Vertex AI response - handle nested structure contexts = response_json.get("contexts", {}).get("contexts", []) diff --git a/litellm/llms/vertex_ai/vertex_ai_aws_wif.py b/litellm/llms/vertex_ai/vertex_ai_aws_wif.py index 44a0016e4ec..a03a4e37a21 100644 --- a/litellm/llms/vertex_ai/vertex_ai_aws_wif.py +++ b/litellm/llms/vertex_ai/vertex_ai_aws_wif.py @@ -18,18 +18,20 @@ GOOGLE_IMPORT_ERROR_MESSAGE = ( # AWS params recognized in WIF credential JSON for explicit auth. # These match the kwargs accepted by BaseAWSLLM.get_credentials(). -_AWS_CREDENTIAL_KEYS = frozenset({ - "aws_access_key_id", - "aws_secret_access_key", - "aws_session_token", - "aws_region_name", - "aws_session_name", - "aws_profile_name", - "aws_role_name", - "aws_web_identity_token", - "aws_sts_endpoint", - "aws_external_id", -}) +_AWS_CREDENTIAL_KEYS = frozenset( + { + "aws_access_key_id", + "aws_secret_access_key", + "aws_session_token", + "aws_region_name", + "aws_session_name", + "aws_profile_name", + "aws_role_name", + "aws_web_identity_token", + "aws_sts_endpoint", + "aws_external_id", + } +) class VertexAIAwsWifAuth: @@ -46,11 +48,7 @@ class VertexAIAwsWifAuth: Returns a dict of {param_name: value} for any recognized aws_* keys found in the JSON. Returns empty dict if none are present. """ - return { - key: json_obj[key] - for key in _AWS_CREDENTIAL_KEYS - if key in json_obj - } + return {key: json_obj[key] for key in _AWS_CREDENTIAL_KEYS if key in json_obj} @staticmethod def credentials_from_explicit_aws(json_obj, aws_params, scopes): diff --git a/litellm/llms/vertex_ai/vertex_ai_non_gemini.py b/litellm/llms/vertex_ai/vertex_ai_non_gemini.py index 54cb83bb0bc..cfbab584f6a 100644 --- a/litellm/llms/vertex_ai/vertex_ai_non_gemini.py +++ b/litellm/llms/vertex_ai/vertex_ai_non_gemini.py @@ -145,11 +145,9 @@ def completion( # noqa: PLR0915 json_obj = json.loads(vertex_credentials) - creds = ( - google.oauth2.service_account.Credentials.from_service_account_info( - json_obj, - scopes=["https://www.googleapis.com/auth/cloud-platform"], - ) + creds = google.oauth2.service_account.Credentials.from_service_account_info( + json_obj, + scopes=["https://www.googleapis.com/auth/cloud-platform"], ) else: creds, _ = google.auth.default(quota_project_id=vertex_project) 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 6bede1a2352..d3b0217d044 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 @@ -33,10 +33,12 @@ class VertexAIPartnerModelsAnthropicMessagesConfig(AnthropicMessagesConfig, Vert """ vertex_ai_project = VertexBase.safe_get_vertex_ai_project(litellm_params) vertex_ai_location = VertexBase.safe_get_vertex_ai_location(litellm_params) - + project_id: Optional[str] = None if "Authorization" not in headers: - vertex_credentials = VertexBase.safe_get_vertex_ai_credentials(litellm_params) + vertex_credentials = VertexBase.safe_get_vertex_ai_credentials( + litellm_params + ) access_token, project_id = self._ensure_access_token( credentials=vertex_credentials, @@ -62,11 +64,11 @@ class VertexAIPartnerModelsAnthropicMessagesConfig(AnthropicMessagesConfig, Vert ) headers["content-type"] = "application/json" - + # Add beta headers for Vertex AI tools = optional_params.get("tools", []) beta_values: set[str] = set() - + # Get existing beta headers if any existing_beta = headers.get("anthropic-beta") if existing_beta: @@ -79,36 +81,42 @@ class VertexAIPartnerModelsAnthropicMessagesConfig(AnthropicMessagesConfig, Vert 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) + beta_values.add( + ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value + ) # Check for web search tool for tool in tools: - if isinstance(tool, dict) and tool.get("type", "").startswith(ANTHROPIC_HOSTED_TOOLS.WEB_SEARCH.value): - beta_values.add(ANTHROPIC_BETA_HEADER_VALUES.WEB_SEARCH_2025_03_05.value) + if isinstance(tool, dict) and tool.get("type", "").startswith( + ANTHROPIC_HOSTED_TOOLS.WEB_SEARCH.value + ): + beta_values.add( + ANTHROPIC_BETA_HEADER_VALUES.WEB_SEARCH_2025_03_05.value + ) break - + # Check for tool search tools - Vertex AI uses different beta header anthropic_model_info = AnthropicModelInfo() if anthropic_model_info.is_tool_search_used(tools): beta_values.add(get_tool_search_beta_header("vertex_ai")) - + if beta_values: headers["anthropic-beta"] = ",".join(beta_values) - + return headers, api_base def get_complete_url( 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 4e2c2895f9e..504914c4796 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 @@ -107,7 +107,7 @@ class VertexAIAnthropicConfig(AnthropicConfig): # VertexAI doesn't support output_format parameter, remove it if present data.pop("output_format", None) - + # VertexAI doesn't support output_config parameter, remove it if present data.pop("output_config", None) diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/gpt_oss/transformation.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/gpt_oss/transformation.py index 86e36e802ed..47c388f0a54 100644 --- a/litellm/llms/vertex_ai/vertex_ai_partner_models/gpt_oss/transformation.py +++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/gpt_oss/transformation.py @@ -8,9 +8,10 @@ class VertexAIGPTOSSTransformation(OpenAIGPTConfig): https://console.cloud.google.com/vertex-ai/publishers/openai/model-garden/gpt-oss-120b-maas?hl=id """ + def __init__(self): super().__init__() - + def get_supported_openai_params(self, model: str) -> list: base_gpt_series_params = super().get_supported_openai_params(model=model) gpt_oss_only_params = ["reasoning_effort"] @@ -20,8 +21,16 @@ class VertexAIGPTOSSTransformation(OpenAIGPTConfig): # VertexAI - GPT-OSS does not support tool calls ######################################################### if litellm.supports_function_calling(model=model) is False: - TOOL_CALLING_PARAMS_TO_REMOVE = ["tool", "tool_choice", "function_call", "functions"] - base_gpt_series_params = [param for param in base_gpt_series_params if param not in TOOL_CALLING_PARAMS_TO_REMOVE] + TOOL_CALLING_PARAMS_TO_REMOVE = [ + "tool", + "tool_choice", + "function_call", + "functions", + ] + base_gpt_series_params = [ + param + for param in base_gpt_series_params + if param not in TOOL_CALLING_PARAMS_TO_REMOVE + ] return base_gpt_series_params - diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/llama3/transformation.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/llama3/transformation.py index 51310e4fa85..3031f159d87 100644 --- a/litellm/llms/vertex_ai/vertex_ai_partner_models/llama3/transformation.py +++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/llama3/transformation.py @@ -151,12 +151,12 @@ class VertexAILlama3StreamingHandler(OpenAIChatCompletionStreamingHandler): """ Vertex AI Llama models may not include role in streaming chunk deltas. This handler ensures the first chunk always has role="assistant". - + When Vertex AI returns a single chunk with both role and finish_reason (empty response), this handler splits it into two chunks: 1. First chunk: role="assistant", content="", finish_reason=None 2. Second chunk: role=None, content=None, finish_reason="stop" - + This matches OpenAI's streaming format where the first chunk has role and the final chunk has finish_reason but no role. """ @@ -171,7 +171,7 @@ class VertexAILlama3StreamingHandler(OpenAIChatCompletionStreamingHandler): if not self.sent_role and result.choices: delta = result.choices[0].delta finish_reason = result.choices[0].finish_reason - + # If this is both the first chunk AND the final chunk (has finish_reason), # we need to split it into two chunks to match OpenAI format if finish_reason is not None: @@ -190,7 +190,7 @@ class VertexAILlama3StreamingHandler(OpenAIChatCompletionStreamingHandler): ], ) # Modify current chunk to be the first chunk with role but no finish_reason - result.choices[0].finish_reason = None + result.choices[0].finish_reason = None # type: ignore[assignment] delta.role = "assistant" # Ensure content is empty string for first chunk, not None if delta.content is None: @@ -202,7 +202,9 @@ class VertexAILlama3StreamingHandler(OpenAIChatCompletionStreamingHandler): elif delta.role is None: delta.role = "assistant" # If the first chunk has empty content, ensure it's still emitted - if (delta.content == "" or delta.content is None) and delta.provider_specific_fields is None: + if ( + delta.content == "" or delta.content is None + ) and delta.provider_specific_fields is None: delta.provider_specific_fields = {} self.sent_role = True return result diff --git a/litellm/llms/vertex_ai/vertex_embeddings/bge.py b/litellm/llms/vertex_ai/vertex_embeddings/bge.py index 2eff0ba96db..e3f25b425ff 100644 --- a/litellm/llms/vertex_ai/vertex_embeddings/bge.py +++ b/litellm/llms/vertex_ai/vertex_embeddings/bge.py @@ -25,14 +25,14 @@ from .types import ( class VertexBGEConfig: """ Configuration and transformation logic for BGE models on Vertex AI. - + BGE (BAAI General Embedding) models use a different request format where the input field is named "prompt" instead of "content". - + Supported model patterns (after provider split in main.py): - "bge-small-en-v1.5" (model name) - "bge/204379420394258432" (endpoint ID pattern) - + Note: Model name transformation (bge/ -> numeric ID) is handled automatically in common_utils._get_vertex_url(). This class focuses on request/response format only. """ @@ -41,14 +41,14 @@ class VertexBGEConfig: def is_bge_model(model: str) -> bool: """ Check if the model is a BGE (BAAI General Embedding) model. - + After provider split in main.py, supports: - "bge-small-en-v1.5" (model name) - "bge/204379420394258432" (endpoint ID pattern) - + Args: model: The model name after provider split - + Returns: bool: True if the model is a BGE model """ @@ -62,14 +62,14 @@ class VertexBGEConfig: ) -> VertexEmbeddingRequest: """ Transforms an OpenAI request to a Vertex BGE embedding request. - + BGE models use "prompt" instead of "content" as the input field. - + Args: input: The input text(s) to embed optional_params: Optional parameters for the request model: The model name - + Returns: VertexEmbeddingRequest: The transformed request """ @@ -124,7 +124,7 @@ class VertexBGEConfig: ) -> EmbeddingResponse: """ Transforms a Vertex BGE embedding response to OpenAI format. - + BGE models return embeddings directly as arrays in predictions: { "predictions": [ @@ -132,26 +132,28 @@ class VertexBGEConfig: [0.003, 0.022, ...] ] } - + Args: response: The raw response from Vertex AI model: The model name model_response: The EmbeddingResponse object to populate - + Returns: EmbeddingResponse: The transformed response in OpenAI format - + Raises: KeyError: If response doesn't contain 'predictions' ValueError: If predictions is not a list or contains invalid data """ if "predictions" not in response: raise KeyError("Response missing 'predictions' field") - + _predictions = response["predictions"] - + if not isinstance(_predictions, list): - raise ValueError(f"Expected 'predictions' to be a list, got {type(_predictions)}") + raise ValueError( + f"Expected 'predictions' to be a list, got {type(_predictions)}" + ) embedding_response = [] # BGE models don't return token counts, so we estimate or set to 0 @@ -162,7 +164,7 @@ class VertexBGEConfig: raise ValueError( f"Expected embedding at index {idx} to be a list, got {type(embedding_values)}" ) - + embedding_response.append( { "object": "embedding", @@ -179,4 +181,3 @@ class VertexBGEConfig: ) setattr(model_response, "usage", usage) return model_response - diff --git a/litellm/llms/vertex_ai/vertex_embeddings/embedding_handler.py b/litellm/llms/vertex_ai/vertex_embeddings/embedding_handler.py index 8a03738ad78..5fffd983c24 100644 --- a/litellm/llms/vertex_ai/vertex_embeddings/embedding_handler.py +++ b/litellm/llms/vertex_ai/vertex_embeddings/embedding_handler.py @@ -74,7 +74,7 @@ class VertexEmbedding(VertexBase): ) # Extract use_psc_endpoint_format from optional_params use_psc_endpoint_format = optional_params.get("use_psc_endpoint_format", False) - + auth_header, api_base = self._get_token_and_url( model=model, gemini_api_key=gemini_api_key, @@ -90,10 +90,8 @@ class VertexEmbedding(VertexBase): use_psc_endpoint_format=use_psc_endpoint_format, ) headers = self.set_headers(auth_header=auth_header, extra_headers=extra_headers) - vertex_request: VertexEmbeddingRequest = ( - litellm.vertexAITextEmbeddingConfig.transform_openai_request_to_vertex_embedding_request( - input=input, optional_params=optional_params, model=model - ) + vertex_request: VertexEmbeddingRequest = litellm.vertexAITextEmbeddingConfig.transform_openai_request_to_vertex_embedding_request( + input=input, optional_params=optional_params, model=model ) _client_params = {} @@ -170,7 +168,7 @@ class VertexEmbedding(VertexBase): ) # Extract use_psc_endpoint_format from optional_params use_psc_endpoint_format = optional_params.get("use_psc_endpoint_format", False) - + auth_header, api_base = self._get_token_and_url( model=model, gemini_api_key=gemini_api_key, @@ -186,10 +184,8 @@ class VertexEmbedding(VertexBase): use_psc_endpoint_format=use_psc_endpoint_format, ) headers = self.set_headers(auth_header=auth_header, extra_headers=extra_headers) - vertex_request: VertexEmbeddingRequest = ( - litellm.vertexAITextEmbeddingConfig.transform_openai_request_to_vertex_embedding_request( - input=input, optional_params=optional_params, model=model - ) + vertex_request: VertexEmbeddingRequest = litellm.vertexAITextEmbeddingConfig.transform_openai_request_to_vertex_embedding_request( + input=input, optional_params=optional_params, model=model ) _async_client_params = {} diff --git a/litellm/llms/vertex_ai/vertex_embeddings/transformation.py b/litellm/llms/vertex_ai/vertex_embeddings/transformation.py index 5a3a4a7188a..132f29987af 100644 --- a/litellm/llms/vertex_ai/vertex_embeddings/transformation.py +++ b/litellm/llms/vertex_ai/vertex_embeddings/transformation.py @@ -107,6 +107,7 @@ class VertexAITextEmbeddingConfig(BaseModel): """ # Import here to avoid circular import issues with litellm.__init__ from litellm.llms.vertex_ai.vertex_embeddings.bge import VertexBGEConfig + if model.isdigit(): return self._transform_openai_request_to_fine_tuned_embedding_request( input, optional_params, model @@ -174,7 +175,10 @@ class VertexAITextEmbeddingConfig(BaseModel): **optional_params ) # Remove 'shared_session' from parameters if present - if vertex_request["parameters"] is not None and "shared_session" in vertex_request["parameters"]: + if ( + vertex_request["parameters"] is not None + and "shared_session" in vertex_request["parameters"] + ): del vertex_request["parameters"]["shared_session"] # type: ignore[typeddict-item] return vertex_request @@ -215,10 +219,10 @@ class VertexAITextEmbeddingConfig(BaseModel): return self._transform_vertex_response_to_openai_for_fine_tuned_models( response, model, model_response ) - + # Import here to avoid circular import issues with litellm.__init__ from litellm.llms.vertex_ai.vertex_embeddings.bge import VertexBGEConfig - + if VertexBGEConfig.is_bge_model(model): return VertexBGEConfig.transform_response( response=response, model=model, model_response=model_response diff --git a/litellm/llms/vertex_ai/vertex_embeddings/types.py b/litellm/llms/vertex_ai/vertex_embeddings/types.py index fa9794d79a5..317b9c4fb81 100644 --- a/litellm/llms/vertex_ai/vertex_embeddings/types.py +++ b/litellm/llms/vertex_ai/vertex_embeddings/types.py @@ -50,7 +50,11 @@ class EmbeddingParameters(TypedDict, total=False): class VertexEmbeddingRequest(TypedDict, total=False): - instances: Union[List[TextEmbeddingInput], List[TextEmbeddingBGEInput], List[TextEmbeddingFineTunedInput]] + instances: Union[ + List[TextEmbeddingInput], + List[TextEmbeddingBGEInput], + List[TextEmbeddingFineTunedInput], + ] parameters: Optional[Union[EmbeddingParameters, TextEmbeddingFineTunedParameters]] diff --git a/litellm/llms/vertex_ai/vertex_gemma_models/__init__.py b/litellm/llms/vertex_ai/vertex_gemma_models/__init__.py index d06c7a5cd7a..92106ab7c2d 100644 --- a/litellm/llms/vertex_ai/vertex_gemma_models/__init__.py +++ b/litellm/llms/vertex_ai/vertex_gemma_models/__init__.py @@ -1,2 +1 @@ """Vertex AI Gemma-AI Models Handler""" - diff --git a/litellm/llms/vertex_ai/vertex_gemma_models/main.py b/litellm/llms/vertex_ai/vertex_gemma_models/main.py index 41bd6b5431e..82cfe6de984 100644 --- a/litellm/llms/vertex_ai/vertex_gemma_models/main.py +++ b/litellm/llms/vertex_ai/vertex_gemma_models/main.py @@ -82,7 +82,6 @@ class VertexAIGemmaModels(VertexBase): message="""Upgrade vertex ai. Run `pip install "google-cloud-aiplatform>=1.38"`""", ) try: - model = get_vertex_base_model_name(model=model) vertex_httpx_logic = VertexLLM() @@ -143,4 +142,3 @@ class VertexAIGemmaModels(VertexBase): if hasattr(e, "status_code"): raise e raise VertexAIError(status_code=500, message=str(e)) - diff --git a/litellm/llms/vertex_ai/vertex_gemma_models/transformation.py b/litellm/llms/vertex_ai/vertex_gemma_models/transformation.py index 24b53f0ba4f..6c6446958bc 100644 --- a/litellm/llms/vertex_ai/vertex_gemma_models/transformation.py +++ b/litellm/llms/vertex_ai/vertex_gemma_models/transformation.py @@ -21,7 +21,7 @@ from litellm.types.utils import ModelResponse class VertexGemmaConfig(OpenAIGPTConfig): """ Configuration and transformation class for Vertex AI Gemma models - + Extends OpenAIGPTConfig to wrap/unwrap the instances/predictions format used by Vertex AI's Gemma deployment endpoint. """ @@ -48,16 +48,17 @@ class VertexGemmaConfig(OpenAIGPTConfig): ) -> Union[ModelResponse, Any]: """ Helper method to return fake stream iterator if streaming is requested. - + Args: model_response: The completed model response stream: Whether streaming was requested - + Returns: MockResponseIterator if stream=True, otherwise the model_response """ if stream: from litellm.llms.base_llm.base_model_iterator import MockResponseIterator + return MockResponseIterator(model_response=model_response) return model_response @@ -71,7 +72,7 @@ class VertexGemmaConfig(OpenAIGPTConfig): ) -> dict: """ Transform request to Vertex Gemma format. - + Uses parent class to create OpenAI-compatible request, then wraps it in the Vertex Gemma instances format. """ @@ -83,12 +84,14 @@ class VertexGemmaConfig(OpenAIGPTConfig): litellm_params=litellm_params, headers=headers, ) - + # Remove params not needed/supported by Vertex Gemma openai_request.pop("model", None) - openai_request.pop("stream", None) # Streaming not supported, will be faked client-side + openai_request.pop( + "stream", None + ) # Streaming not supported, will be faked client-side openai_request.pop("stream_options", None) # Stream options not supported - + # Wrap in Vertex Gemma format return { "instances": [ @@ -105,7 +108,7 @@ class VertexGemmaConfig(OpenAIGPTConfig): ) -> Dict[str, Any]: """ Unwrap the Vertex Gemma predictions format to OpenAI format. - + Vertex Gemma wraps the OpenAI-compatible response in a 'predictions' field. This method extracts it so the parent class can process it normally. """ @@ -114,7 +117,7 @@ class VertexGemmaConfig(OpenAIGPTConfig): status_code=422, message="Invalid response format: missing 'predictions' field", ) - + return response_json["predictions"] def completion( @@ -189,7 +192,7 @@ class VertexGemmaConfig(OpenAIGPTConfig): # Check if streaming is requested (will be faked) stream = optional_params.get("stream", False) - + # Transform the request using parent class methods request_data = self.transform_request( model=model, @@ -198,7 +201,7 @@ class VertexGemmaConfig(OpenAIGPTConfig): litellm_params=litellm_params, headers={}, ) - + # Set up headers headers = { "Authorization": f"Bearer {api_key}", @@ -231,10 +234,10 @@ class VertexGemmaConfig(OpenAIGPTConfig): ) response_json = response.json() - + # Unwrap predictions to get OpenAI-compatible response openai_response = self._unwrap_predictions_response(response_json) - + # Use litellm's standard response converter model_response = cast( ModelResponse, @@ -244,10 +247,10 @@ class VertexGemmaConfig(OpenAIGPTConfig): _response_headers={}, ), ) - + # Ensure model is set correctly model_response.model = model - + # Log the response logging_obj.post_call( input=messages, @@ -255,9 +258,11 @@ class VertexGemmaConfig(OpenAIGPTConfig): original_response=response_json, additional_args={"complete_input_dict": request_data}, ) - + # Return fake stream iterator if streaming was requested - return self._handle_fake_stream_response(model_response=model_response, stream=stream) + return self._handle_fake_stream_response( + model_response=model_response, stream=stream + ) async def _async_completion( self, @@ -280,7 +285,7 @@ class VertexGemmaConfig(OpenAIGPTConfig): # Check if streaming is requested (will be faked) stream = optional_params.get("stream", False) - + # Transform the request using parent class async methods request_data = await self.async_transform_request( model=model, @@ -289,7 +294,7 @@ class VertexGemmaConfig(OpenAIGPTConfig): litellm_params=litellm_params, headers={}, ) - + # Set up headers headers = { "Authorization": f"Bearer {api_key}", @@ -324,10 +329,10 @@ class VertexGemmaConfig(OpenAIGPTConfig): ) response_json = response.json() - + # Unwrap predictions to get OpenAI-compatible response openai_response = self._unwrap_predictions_response(response_json) - + # Use litellm's standard response converter model_response = cast( ModelResponse, @@ -337,10 +342,10 @@ class VertexGemmaConfig(OpenAIGPTConfig): _response_headers={}, ), ) - + # Ensure model is set correctly model_response.model = model - + # Log the response logging_obj.post_call( input=messages, @@ -348,7 +353,8 @@ class VertexGemmaConfig(OpenAIGPTConfig): original_response=response_json, additional_args={"complete_input_dict": request_data}, ) - - # Return fake stream iterator if streaming was requested - return self._handle_fake_stream_response(model_response=model_response, stream=stream) + # Return fake stream iterator if streaming was requested + return self._handle_fake_stream_response( + model_response=model_response, stream=stream + ) diff --git a/litellm/llms/vertex_ai/vertex_llm_base.py b/litellm/llms/vertex_ai/vertex_llm_base.py index 86e14a30df4..1a29ba82eac 100644 --- a/litellm/llms/vertex_ai/vertex_llm_base.py +++ b/litellm/llms/vertex_ai/vertex_llm_base.py @@ -21,7 +21,6 @@ from .common_utils import ( all_gemini_url_modes, get_vertex_base_model_name, get_vertex_base_url, - is_global_only_vertex_model, ) GOOGLE_IMPORT_ERROR_MESSAGE = ( @@ -49,8 +48,32 @@ class VertexBase: self.async_handler: Optional[AsyncHTTPHandler] = None def get_vertex_region(self, vertex_region: Optional[str], model: str) -> str: - if is_global_only_vertex_model(model): - return "global" + import litellm + + # Try to get supported_regions directly from model_cost + # Check both with and without vertex_ai/ prefix + model_key = ( + f"vertex_ai/{model}" if not model.startswith("vertex_ai/") else model + ) + model_info = litellm.model_cost.get(model_key, {}) + supported_regions = model_info.get("supported_regions") + + if supported_regions and len(supported_regions) > 0: + # If user didn't specify region, use the first supported region + if vertex_region is None: + return supported_regions[0] + # If user specified a region not supported by this model, override it + if vertex_region not in supported_regions: + verbose_logger.warning( + "Vertex AI model '%s' does not support region '%s' " + "(supported: %s). Routing to '%s'.", + model, + vertex_region, + supported_regions, + supported_regions[0], + ) + return supported_regions[0] + return vertex_region return vertex_region or "us-central1" def load_auth( @@ -214,7 +237,9 @@ class VertexBase: ) -> str: if api_base: return api_base - return get_vertex_base_url(vertex_location or self.get_default_vertex_location()) + return get_vertex_base_url( + vertex_location or self.get_default_vertex_location() + ) @staticmethod def create_vertex_url( diff --git a/litellm/llms/vertex_ai/videos/__init__.py b/litellm/llms/vertex_ai/videos/__init__.py index 1dcdbdf4ded..7e00770787e 100644 --- a/litellm/llms/vertex_ai/videos/__init__.py +++ b/litellm/llms/vertex_ai/videos/__init__.py @@ -7,4 +7,3 @@ This module provides support for Vertex AI's Veo video generation API. from .transformation import VertexAIVideoConfig __all__ = ["VertexAIVideoConfig"] - diff --git a/litellm/llms/vertex_ai/videos/transformation.py b/litellm/llms/vertex_ai/videos/transformation.py index 60852c1bf02..e61f2f46ec8 100644 --- a/litellm/llms/vertex_ai/videos/transformation.py +++ b/litellm/llms/vertex_ai/videos/transformation.py @@ -78,11 +78,11 @@ class VertexAIVideoConfig(BaseVideoConfig, VertexBase): def extract_model_from_operation_name(operation_name: str) -> Optional[str]: """ Extract the model name from a Vertex AI operation name. - + Args: operation_name: Operation name in format: projects/PROJECT/locations/LOCATION/publishers/google/models/MODEL/operations/OPERATION_ID - + Returns: Model name (e.g., "veo-2.0-generate-001") or None if extraction fails """ @@ -174,17 +174,23 @@ class VertexAIVideoConfig(BaseVideoConfig, VertexBase): ) -> dict: """ Validate environment and return headers for Vertex AI OCR. - + Vertex AI uses Bearer token authentication with access token from credentials. """ # Extract Vertex AI parameters using safe helpers from VertexBase # Use safe_get_* methods that don't mutate litellm_params dict # Ensure litellm_params is a dict for type checking - params_dict: Dict[str, Any] = cast(Dict[str, Any], litellm_params) if litellm_params is not None else {} - - vertex_project = VertexBase.safe_get_vertex_ai_project(litellm_params=params_dict) - vertex_credentials = VertexBase.safe_get_vertex_ai_credentials(litellm_params=params_dict) - + params_dict: Dict[str, Any] = ( + cast(Dict[str, Any], litellm_params) if litellm_params is not None else {} + ) + + vertex_project = VertexBase.safe_get_vertex_ai_project( + litellm_params=params_dict + ) + vertex_credentials = VertexBase.safe_get_vertex_ai_credentials( + litellm_params=params_dict + ) + # Get access token from Vertex credentials access_token, project_id = self.get_access_token( credentials=vertex_credentials, @@ -353,24 +359,23 @@ class VertexAIVideoConfig(BaseVideoConfig, VertexBase): else: video_id = operation_name - video_obj = VideoObject( - id=video_id, - object="video", - status="processing", - model=model + id=video_id, object="video", status="processing", model=model ) usage_data = {} if request_data: parameters = request_data.get("parameters", {}) - duration = parameters.get("durationSeconds") or DEFAULT_GOOGLE_VIDEO_DURATION_SECONDS + duration = ( + parameters.get("durationSeconds") + or DEFAULT_GOOGLE_VIDEO_DURATION_SECONDS + ) if duration is not None: try: usage_data["duration_seconds"] = float(duration) except (ValueError, TypeError): pass - + video_obj.usage = usage_data return video_obj @@ -388,7 +393,7 @@ class VertexAIVideoConfig(BaseVideoConfig, VertexBase): """ operation_name = extract_original_video_id(video_id) model = self.extract_model_from_operation_name(operation_name) - + if not model: raise ValueError( f"Invalid operation name format: {operation_name}. " @@ -500,7 +505,9 @@ class VertexAIVideoConfig(BaseVideoConfig, VertexBase): Since we need to make an HTTP call here, we'll use the same fetchPredictOperation approach as status retrieval. """ - return self.transform_video_status_retrieve_request(video_id, api_base, litellm_params, headers) + return self.transform_video_status_retrieve_request( + video_id, api_base, litellm_params, headers + ) def transform_video_content_response( self, @@ -627,4 +634,3 @@ class VertexAIVideoConfig(BaseVideoConfig, VertexBase): message=error_message, headers=headers, ) - diff --git a/litellm/llms/volcengine/chat/transformation.py b/litellm/llms/volcengine/chat/transformation.py index 6df1cd38267..7395f9ce75b 100644 --- a/litellm/llms/volcengine/chat/transformation.py +++ b/litellm/llms/volcengine/chat/transformation.py @@ -7,6 +7,7 @@ class VolcEngineChatConfig(OpenAILikeChatConfig): """ Reference: https://www.volcengine.com/docs/82379/1494384 """ + frequency_penalty: Optional[int] = None function_call: Optional[Union[str, dict]] = None functions: Optional[list] = None @@ -95,10 +96,13 @@ class VolcEngineChatConfig(OpenAILikeChatConfig): if ( thinking_value is not None and isinstance(thinking_value, dict) - and thinking_value.get("type", None) in ["enabled", "disabled", "auto"] # legal values, see docs + and thinking_value.get("type", None) + in ["enabled", "disabled", "auto"] # legal values, see docs ): # Add thinking parameter to extra_body for all legal cases - optional_params.setdefault("extra_body", {})["thinking"] = thinking_value + optional_params.setdefault("extra_body", {})[ + "thinking" + ] = thinking_value else: # Skip adding thinking parameter when it's not set or has invalid value pass diff --git a/litellm/llms/volcengine/embedding/transformation.py b/litellm/llms/volcengine/embedding/transformation.py index 20747b76725..cb497c9f155 100644 --- a/litellm/llms/volcengine/embedding/transformation.py +++ b/litellm/llms/volcengine/embedding/transformation.py @@ -59,7 +59,7 @@ class VolcEngineEmbeddingConfig(BaseEmbeddingConfig): ) -> str: """ Get the complete URL for volcengine embedding API calls. - + Args: api_base: Optional custom API base URL api_key: API key (not used for URL construction) @@ -67,7 +67,7 @@ class VolcEngineEmbeddingConfig(BaseEmbeddingConfig): optional_params: Optional parameters (not used for URL construction) litellm_params: LiteLLM parameters (not used for URL construction) stream: Stream parameter (not used for URL construction) - + Returns: Complete URL for the embedding API endpoint """ @@ -117,8 +117,6 @@ class VolcEngineEmbeddingConfig(BaseEmbeddingConfig): return optional_params - - def transform_embedding_request( self, model: str, @@ -175,7 +173,7 @@ class VolcEngineEmbeddingConfig(BaseEmbeddingConfig): # Add id if present if "id" in response_json: transformed_response["id"] = response_json["id"] - + # Create EmbeddingResponse from transformed data return EmbeddingResponse(**transformed_response) @@ -201,6 +199,7 @@ class VolcEngineEmbeddingConfig(BaseEmbeddingConfig): ) -> BaseLLMException: """Get error class for Volcengine errors""" from ..common_utils import VolcEngineError + # Convert dict to httpx.Headers if needed if isinstance(headers, dict): headers = httpx.Headers(headers) diff --git a/litellm/llms/volcengine/responses/transformation.py b/litellm/llms/volcengine/responses/transformation.py index f9ed93f680c..f6dda4dd25b 100644 --- a/litellm/llms/volcengine/responses/transformation.py +++ b/litellm/llms/volcengine/responses/transformation.py @@ -92,7 +92,9 @@ class VolcEngineResponsesAPIConfig(OpenAIResponsesAPIConfig): self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ) -> VolcEngineError: typed_headers: httpx.Headers = ( - headers if isinstance(headers, httpx.Headers) else httpx.Headers(headers or {}) + headers + if isinstance(headers, httpx.Headers) + else httpx.Headers(headers or {}) ) return VolcEngineError( status_code=status_code, @@ -193,7 +195,9 @@ class VolcEngineResponsesAPIConfig(OpenAIResponsesAPIConfig): allowed = set(self._SUPPORTED_OPTIONAL_PARAMS) sanitized_optional = { - k: v for k, v in response_api_optional_request_params.items() if k in allowed + k: v + for k, v in response_api_optional_request_params.items() + if k in allowed } # Ensure metadata never reaches provider sanitized_optional.pop("metadata", None) @@ -203,7 +207,9 @@ class VolcEngineResponsesAPIConfig(OpenAIResponsesAPIConfig): # leaking unsupported params to the provider. if isinstance(sanitized_optional.get("extra_body"), dict): filtered_body = { - k: v for k, v in sanitized_optional["extra_body"].items() if k in allowed + k: v + for k, v in sanitized_optional["extra_body"].items() + if k in allowed } if filtered_body: sanitized_optional["extra_body"] = filtered_body @@ -438,9 +444,7 @@ class VolcEngineResponsesAPIConfig(OpenAIResponsesAPIConfig): return False @staticmethod - def _fill_missing_fields( - chunk: Any, event_model: Any - ) -> Dict[str, Any]: + def _fill_missing_fields(chunk: Any, event_model: Any) -> Dict[str, Any]: """ Heuristically fill missing required fields with safe defaults based on the event model's field annotations. This keeps parsing tolerant of providers that @@ -460,7 +464,10 @@ class VolcEngineResponsesAPIConfig(OpenAIResponsesAPIConfig): continue # Explicit default or factory - if field.default is not pyd_fields.PydanticUndefined and field.default is not None: + if ( + field.default is not pyd_fields.PydanticUndefined + and field.default is not None + ): patched[name] = field.default continue if ( diff --git a/litellm/llms/voyage/rerank/transformation.py b/litellm/llms/voyage/rerank/transformation.py index a6fe38c0cdf..521dae980d5 100644 --- a/litellm/llms/voyage/rerank/transformation.py +++ b/litellm/llms/voyage/rerank/transformation.py @@ -23,7 +23,6 @@ from ..embedding.transformation import VoyageError class VoyageRerankConfig(BaseRerankConfig): - def get_supported_cohere_rerank_params(self, model: str) -> list: return ["query", "documents", "top_n", "return_documents"] @@ -137,12 +136,17 @@ class VoyageRerankConfig(BaseRerankConfig): optional_params: Optional[dict] = None, ) -> Dict: if api_key is None: - api_key = get_secret_str("VOYAGE_API_KEY") or get_secret_str("VOYAGE_AI_API_KEY") + api_key = get_secret_str("VOYAGE_API_KEY") or get_secret_str( + "VOYAGE_AI_API_KEY" + ) if api_key is None: raise ValueError( "Voyage AI API key is required. Set via `api_key` parameter or `VOYAGE_API_KEY` env var." ) - return {"Authorization": f"Bearer {api_key}", "content-type": "application/json"} + return { + "Authorization": f"Bearer {api_key}", + "content-type": "application/json", + } def calculate_rerank_cost( self, @@ -166,4 +170,6 @@ class VoyageRerankConfig(BaseRerankConfig): def get_error_class( self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ): - return VoyageError(message=error_message, status_code=status_code, headers=headers) + return VoyageError( + message=error_message, status_code=status_code, headers=headers + ) diff --git a/litellm/llms/watsonx/rerank/transformation.py b/litellm/llms/watsonx/rerank/transformation.py index 7b4c2a07c3c..4f8e196f254 100644 --- a/litellm/llms/watsonx/rerank/transformation.py +++ b/litellm/llms/watsonx/rerank/transformation.py @@ -42,7 +42,9 @@ class IBMWatsonXRerankConfig(IBMWatsonXMixin, BaseRerankConfig): params = optional_params or {} - complete_url = self._add_api_version_to_url(url=url, api_version=(params.get("api_version", None))) + complete_url = self._add_api_version_to_url( + url=url, api_version=(params.get("api_version", None)) + ) return complete_url def get_supported_cohere_rerank_params(self, model: str) -> list: @@ -76,7 +78,8 @@ class IBMWatsonXRerankConfig(IBMWatsonXMixin, BaseRerankConfig): ) zen_api_key = cast( Optional[str], - optional_params.pop("zen_api_key", None) or get_secret_str("WATSONX_ZENAPIKEY"), + optional_params.pop("zen_api_key", None) + or get_secret_str("WATSONX_ZENAPIKEY"), ) if token: headers["Authorization"] = f"Bearer {token}" @@ -115,11 +118,17 @@ class IBMWatsonXRerankConfig(IBMWatsonXMixin, BaseRerankConfig): {"text": el} if isinstance(el, str) else el for el in v ] elif k == "top_n" and v is not None: - optional_rerank_params.setdefault("parameters", {}).setdefault("return_options", {})["top_n"] = v + optional_rerank_params.setdefault("parameters", {}).setdefault( + "return_options", {} + )["top_n"] = v elif k == "return_documents" and v is not None and isinstance(v, bool): - optional_rerank_params.setdefault("parameters", {}).setdefault("return_options", {})["inputs"] = v + optional_rerank_params.setdefault("parameters", {}).setdefault( + "return_options", {} + )["inputs"] = v elif k == "max_tokens_per_doc" and v is not None: - optional_rerank_params.setdefault("parameters", {})["truncate_input_tokens"] = v + optional_rerank_params.setdefault("parameters", {})[ + "truncate_input_tokens" + ] = v # IBM watsonx.ai require one of below parameters elif k == "project_id" and v is not None: @@ -189,7 +198,11 @@ class IBMWatsonXRerankConfig(IBMWatsonXMixin, BaseRerankConfig): transformed_results.append(transformed_result) - response_id = raw_response_json.get("id") or raw_response_json.get("model_id") or str(uuid.uuid4()) + response_id = ( + raw_response_json.get("id") + or raw_response_json.get("model_id") + or str(uuid.uuid4()) + ) # Extract usage information _tokens = RerankTokens( diff --git a/litellm/llms/xai/chat/transformation.py b/litellm/llms/xai/chat/transformation.py index aa2dee354cf..bfa55105a6c 100644 --- a/litellm/llms/xai/chat/transformation.py +++ b/litellm/llms/xai/chat/transformation.py @@ -62,14 +62,13 @@ class XAIChatConfig(OpenAIGPTConfig): ######################################################### if self._supports_stop_reason(model): base_openai_params.append("stop") - ######################################################### # frequency penalty check ######################################################### if self._supports_frequency_penalty(model): base_openai_params.append("frequency_penalty") - + ######################################################### # reasoning check ######################################################### @@ -82,7 +81,7 @@ class XAIChatConfig(OpenAIGPTConfig): verbose_logger.debug(f"Error checking if model supports reasoning: {e}") return base_openai_params - + def _supports_stop_reason(self, model: str) -> bool: if "grok-3-mini" in model: return False @@ -91,7 +90,7 @@ class XAIChatConfig(OpenAIGPTConfig): elif "grok-code-fast" in model: return False return True - + def _supports_frequency_penalty(self, model: str) -> bool: """ From manual testing grok-4 does not support `frequency_penalty` @@ -162,13 +161,15 @@ class XAIChatConfig(OpenAIGPTConfig): def _fix_choice_finish_reason_for_tool_calls(choice: Choices) -> None: """ Helper to fix finish_reason for tool calls when XAI API returns empty string. - + XAI API returns empty string for finish_reason when using tools, so we need to set it to "tool_calls" when tool_calls are present. """ - if (choice.finish_reason == "" and - choice.message.tool_calls and - len(choice.message.tool_calls) > 0): + if ( + choice.finish_reason == "" + and choice.message.tool_calls + and len(choice.message.tool_calls) > 0 + ): choice.finish_reason = "tool_calls" def transform_response( @@ -187,13 +188,13 @@ class XAIChatConfig(OpenAIGPTConfig): ) -> ModelResponse: """ Transform the response from the XAI API. - + XAI API returns empty string for finish_reason when using tools, so we need to fix this after the standard OpenAI transformation. - + Also handles X.AI web search usage tracking by extracting num_sources_used. """ - + # First, let the parent class handle the standard transformation response = super().transform_response( model=model, @@ -237,12 +238,12 @@ class XAIChatConfig(OpenAIGPTConfig): response_usage = raw_response_json.get("usage", {}) if isinstance(response_usage, dict) and "num_sources_used" in response_usage: num_sources_used = response_usage.get("num_sources_used") - + # Map num_sources_used to web_search_requests for cost detection if num_sources_used is not None and num_sources_used > 0: if usage.prompt_tokens_details is None: usage.prompt_tokens_details = PromptTokensDetailsWrapper() - + usage.prompt_tokens_details.web_search_requests = int(num_sources_used) setattr(usage, "num_sources_used", int(num_sources_used)) verbose_logger.debug(f"X.AI web search sources used: {num_sources_used}") @@ -252,10 +253,10 @@ class XAIChatCompletionStreamingHandler(OpenAIChatCompletionStreamingHandler): def chunk_parser(self, chunk: dict) -> ModelResponseStream: """ Handle xAI-specific streaming behavior. - + xAI Grok sends a final chunk with empty choices array but with usage data when stream_options={"include_usage": True} is set. - + Example from xAI API: {"id":"...","object":"chat.completion.chunk","created":...,"model":"grok-4-1-fast-non-reasoning", "choices":[],"usage":{"prompt_tokens":171,"completion_tokens":2,"total_tokens":173,...}} @@ -266,5 +267,5 @@ class XAIChatCompletionStreamingHandler(OpenAIChatCompletionStreamingHandler): # xAI sends usage in a chunk with empty choices array # Add a dummy choice with empty delta to ensure proper processing chunk["choices"] = [{"index": 0, "delta": {}, "finish_reason": None}] - + return super().chunk_parser(chunk) diff --git a/litellm/llms/xai/cost_calculator.py b/litellm/llms/xai/cost_calculator.py index 91ad87e0b87..0cfcfe98415 100644 --- a/litellm/llms/xai/cost_calculator.py +++ b/litellm/llms/xai/cost_calculator.py @@ -30,22 +30,22 @@ def cost_per_token(model: str, usage: Usage) -> Tuple[float, float]: completion_tokens = int(getattr(usage, "completion_tokens", 0) or 0) reasoning_tokens = 0 if hasattr(usage, "completion_tokens_details") and usage.completion_tokens_details: - reasoning_tokens = int(getattr(usage.completion_tokens_details, "reasoning_tokens", 0) or 0) + reasoning_tokens = int( + getattr(usage.completion_tokens_details, "reasoning_tokens", 0) or 0 + ) total_completion_tokens = completion_tokens + reasoning_tokens - + modified_usage = Usage( prompt_tokens=usage.prompt_tokens, completion_tokens=total_completion_tokens, total_tokens=usage.total_tokens, prompt_tokens_details=usage.prompt_tokens_details, - completion_tokens_details=None + completion_tokens_details=None, ) - + prompt_cost, completion_cost = generic_cost_per_token( - model=model, - usage=modified_usage, - custom_llm_provider="xai" + model=model, usage=modified_usage, custom_llm_provider="xai" ) return prompt_cost, completion_cost @@ -54,30 +54,30 @@ def cost_per_token(model: str, usage: Usage) -> Tuple[float, float]: def cost_per_web_search_request(usage: "Usage", model_info: "ModelInfo") -> float: """ Calculate the cost of web search requests for X.AI models. - + X.AI Live Search costs $25 per 1,000 sources used. Each source costs $0.025. - + The number of sources is stored in prompt_tokens_details.web_search_requests by the transformation layer to be compatible with the existing detection system. """ # Cost per source used: $25 per 1,000 sources = $0.025 per source cost_per_source = 25.0 / 1000.0 # $0.025 - + num_sources_used = 0 - + if ( - hasattr(usage, "prompt_tokens_details") + hasattr(usage, "prompt_tokens_details") and usage.prompt_tokens_details is not None and hasattr(usage.prompt_tokens_details, "web_search_requests") and usage.prompt_tokens_details.web_search_requests is not None ): num_sources_used = int(usage.prompt_tokens_details.web_search_requests) - + # Fallback: try to get from num_sources_used if set directly elif hasattr(usage, "num_sources_used") and usage.num_sources_used is not None: num_sources_used = int(usage.num_sources_used) total_cost = cost_per_source * num_sources_used - + return total_cost diff --git a/litellm/llms/xai/realtime/handler.py b/litellm/llms/xai/realtime/handler.py index c79477ba1df..805cce5a264 100644 --- a/litellm/llms/xai/realtime/handler.py +++ b/litellm/llms/xai/realtime/handler.py @@ -15,19 +15,19 @@ 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. diff --git a/litellm/llms/xai/responses/transformation.py b/litellm/llms/xai/responses/transformation.py index 3c69b7d08b7..23aee3a1202 100644 --- a/litellm/llms/xai/responses/transformation.py +++ b/litellm/llms/xai/responses/transformation.py @@ -21,13 +21,13 @@ else: class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig): """ Configuration for XAI's Responses API. - + Inherits from OpenAIResponsesAPIConfig since XAI's Responses API is largely compatible with OpenAI's, with a few differences: - Does not support the 'instructions' parameter - Requires code_interpreter tools to have 'container' field removed - Recommends store=false when sending images - + Reference: https://docs.x.ai/docs/api-reference#create-new-response """ @@ -38,60 +38,64 @@ class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig): def get_supported_openai_params(self, model: str) -> list: """ Get supported parameters for XAI Responses API. - + XAI supports most OpenAI Responses API params except 'instructions'. """ supported_params = super().get_supported_openai_params(model) - + # Remove 'instructions' as it's not supported by XAI if "instructions" in supported_params: supported_params.remove("instructions") - + return supported_params - def _transform_web_search_tool(self, tool: Dict[str, Any]) -> Union[XAIWebSearchTool, Dict[str, Any]]: + def _transform_web_search_tool( + self, tool: Dict[str, Any] + ) -> Union[XAIWebSearchTool, Dict[str, Any]]: """ Transform web_search tool to XAI format. - + XAI supports web_search with specific filters: - allowed_domains (max 5) - excluded_domains (max 5) - enable_image_understanding - + XAI does NOT support search_context_size (OpenAI-specific). """ xai_tool: Dict[str, Any] = {"type": "web_search"} - + # Remove search_context_size if present (not supported by XAI) if "search_context_size" in tool: verbose_logger.info( "XAI does not support 'search_context_size' parameter. Removing it from web_search tool." ) - + # Handle filters (XAI-specific structure) filters = {} if "allowed_domains" in tool: allowed_domains = tool["allowed_domains"] filters["allowed_domains"] = allowed_domains - + if "excluded_domains" in tool: excluded_domains = tool["excluded_domains"] filters["excluded_domains"] = excluded_domains - + # Add filters if any were specified if filters: xai_tool["filters"] = filters - + # Handle enable_image_understanding (top-level in XAI format) if "enable_image_understanding" in tool: xai_tool["enable_image_understanding"] = tool["enable_image_understanding"] - + return xai_tool - - def _transform_x_search_tool(self, tool: Dict[str, Any]) -> Union[XAIXSearchTool, Dict[str, Any]]: + + def _transform_x_search_tool( + self, tool: Dict[str, Any] + ) -> Union[XAIXSearchTool, Dict[str, Any]]: """ Transform x_search tool to XAI format. - + XAI supports x_search with specific parameters: - allowed_x_handles (max 10) - excluded_x_handles (max 10) @@ -101,31 +105,31 @@ class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig): - enable_video_understanding """ xai_tool: Dict[str, Any] = {"type": "x_search"} - + # Handle allowed_x_handles if "allowed_x_handles" in tool: allowed_handles = tool["allowed_x_handles"] xai_tool["allowed_x_handles"] = allowed_handles - + # Handle excluded_x_handles if "excluded_x_handles" in tool: excluded_handles = tool["excluded_x_handles"] xai_tool["excluded_x_handles"] = excluded_handles - + # Handle date range if "from_date" in tool: xai_tool["from_date"] = tool["from_date"] - + if "to_date" in tool: xai_tool["to_date"] = tool["to_date"] - + # Handle media understanding flags if "enable_image_understanding" in tool: xai_tool["enable_image_understanding"] = tool["enable_image_understanding"] - + if "enable_video_understanding" in tool: xai_tool["enable_video_understanding"] = tool["enable_video_understanding"] - + return xai_tool def map_openai_params( @@ -136,7 +140,7 @@ class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig): ) -> Dict: """ Map parameters for XAI Responses API. - + Handles XAI-specific transformations: 1. Drops 'instructions' parameter (not supported) 2. Transforms code_interpreter tools to remove 'container' field @@ -145,61 +149,61 @@ class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig): 5. Sets store=false when images are detected (recommended by XAI) """ params = dict(response_api_optional_params) - + # Drop instructions parameter (not supported by XAI) if "instructions" in params: verbose_logger.debug( "XAI Responses API does not support 'instructions' parameter. Dropping it." ) params.pop("instructions") - + if "metadata" in params: verbose_logger.debug( "XAI Responses API does not support 'metadata' parameter. Dropping it." ) params.pop("metadata") - + # Transform tools if "tools" in params and params["tools"]: tools_list = params["tools"] # Ensure tools is a list for iteration if not isinstance(tools_list, list): tools_list = [tools_list] - + transformed_tools: List[Any] = [] for tool in tools_list: if isinstance(tool, dict): tool_type = tool.get("type") - + if tool_type == "code_interpreter": # XAI supports code_interpreter but doesn't use the container field verbose_logger.debug( "XAI: Transforming code_interpreter tool, removing container field" ) transformed_tools.append({"type": "code_interpreter"}) - + elif tool_type == "web_search": # Transform web_search to XAI format verbose_logger.debug( "XAI: Transforming web_search tool to XAI format" ) transformed_tools.append(self._transform_web_search_tool(tool)) - + elif tool_type == "x_search": # Transform x_search to XAI format verbose_logger.debug( "XAI: Transforming x_search tool to XAI format" ) transformed_tools.append(self._transform_x_search_tool(tool)) - + else: # Keep other tools as-is transformed_tools.append(tool) else: transformed_tools.append(tool) - + params["tools"] = transformed_tools - + return params def validate_environment( @@ -207,21 +211,19 @@ class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig): ) -> dict: """ Validate environment and set up headers for XAI API. - + Uses XAI_API_KEY from environment or litellm_params. """ litellm_params = litellm_params or GenericLiteLLMParams() api_key = ( - litellm_params.api_key - or litellm.api_key - or get_secret_str("XAI_API_KEY") + litellm_params.api_key or litellm.api_key or get_secret_str("XAI_API_KEY") ) - + if not api_key: raise ValueError( "XAI API key is required. Set XAI_API_KEY environment variable or pass api_key parameter." ) - + headers.update( { "Authorization": f"Bearer {api_key}", @@ -236,7 +238,7 @@ class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig): ) -> str: """ Get the complete URL for XAI Responses API endpoint. - + Returns: str: The full URL for the XAI /responses endpoint """ @@ -246,13 +248,12 @@ class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig): or get_secret_str("XAI_API_BASE") or XAI_API_BASE ) - + # Remove trailing slashes api_base = api_base.rstrip("/") - + return f"{api_base}/responses" def supports_native_websocket(self) -> bool: """XAI does not support native WebSocket for Responses API""" return False - diff --git a/litellm/llms/zai/chat/transformation.py b/litellm/llms/zai/chat/transformation.py index fb1d67df357..c932dcd2e03 100644 --- a/litellm/llms/zai/chat/transformation.py +++ b/litellm/llms/zai/chat/transformation.py @@ -48,7 +48,9 @@ class ZAIChatConfig(OpenAIGPTConfig): import litellm try: - if litellm.supports_reasoning(model=model, custom_llm_provider=self.custom_llm_provider): + if litellm.supports_reasoning( + model=model, custom_llm_provider=self.custom_llm_provider + ): base_params.append("thinking") except Exception: pass diff --git a/litellm/main.py b/litellm/main.py index 4e4ce976ac4..722b4a7aaec 100644 --- a/litellm/main.py +++ b/litellm/main.py @@ -99,6 +99,7 @@ from litellm.llms.base_llm.base_model_iterator import ( from litellm.llms.bedrock.common_utils import BedrockModelInfo from litellm.llms.cohere.common_utils import CohereModelInfo from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler +from litellm.llms.openai.chat.gpt_5_transformation import OpenAIGPT5Config from litellm.llms.openai_like.json_loader import JSONProviderRegistry from litellm.llms.vertex_ai.common_utils import ( VertexAIModelRoute, @@ -934,6 +935,8 @@ def responses_api_bridge_check( model: str, custom_llm_provider: str, web_search_options: Optional[OpenAIWebSearchOptions] = None, + tools: Optional[List[Any]] = None, + reasoning_effort: Optional[Any] = None, ) -> Tuple[dict, str]: model_info: Dict[str, Any] = {} try: @@ -951,6 +954,17 @@ def responses_api_bridge_check( if web_search_options is not None and custom_llm_provider == "xai": model_info["mode"] = "responses" model = model.replace("responses/", "") + + # OpenAI gpt-5.4+ chat-completions calls with both tools + reasoning_effort + # must be bridged to Responses API. + if ( + custom_llm_provider == "openai" + and OpenAIGPT5Config.is_model_gpt_5_4_plus_model(model) + and tools + and reasoning_effort is not None + ): + model_info["mode"] = "responses" + model = model.replace("responses/", "") except Exception as e: verbose_logger.debug("Error getting model info: {}".format(e)) @@ -1596,11 +1610,17 @@ def completion( # type: ignore # noqa: PLR0915 model=model, custom_llm_provider=custom_llm_provider, web_search_options=web_search_options, + tools=tools, + reasoning_effort=reasoning_effort, ) if model_info.get("mode") == "responses": from litellm.completion_extras import responses_api_bridge + if isinstance(reasoning_effort, dict) and "summary" in reasoning_effort: + optional_params = dict(optional_params) + optional_params["reasoning_effort"] = reasoning_effort + return responses_api_bridge.completion( model=model, messages=messages, @@ -2244,7 +2264,9 @@ def completion( # type: ignore # noqa: PLR0915 client=client, ) elif custom_llm_provider == "bedrock_mantle": - api_base = api_base or litellm.api_base or get_secret("BEDROCK_MANTLE_API_BASE") + api_base = ( + api_base or litellm.api_base or get_secret("BEDROCK_MANTLE_API_BASE") + ) api_key = api_key or litellm.api_key or get_secret("BEDROCK_MANTLE_API_KEY") headers = headers or litellm.headers config = litellm.BedrockMantleChatConfig.get_config() @@ -2272,14 +2294,16 @@ def completion( # type: ignore # noqa: PLR0915 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, - ) + ( + 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 @@ -3751,9 +3775,9 @@ def completion( # type: ignore # noqa: PLR0915 "aws_region_name" not in optional_params or optional_params["aws_region_name"] is None ): - optional_params["aws_region_name"] = ( - aws_bedrock_client.meta.region_name - ) + optional_params[ + "aws_region_name" + ] = aws_bedrock_client.meta.region_name bedrock_route = BedrockModelInfo.get_bedrock_route(model) if bedrock_route == "converse": @@ -5193,7 +5217,9 @@ def embedding( # noqa: PLR0915 ) try: - model_info = get_model_info(model=model, custom_llm_provider="vertex_ai") + model_info = get_model_info( + model=model, custom_llm_provider="vertex_ai" + ) uses_embed_content = model_info.get("uses_embed_content", False) except Exception: uses_embed_content = False @@ -6154,9 +6180,9 @@ def adapter_completion( new_kwargs = translation_obj.translate_completion_input_params(kwargs=kwargs) response: Union[ModelResponse, CustomStreamWrapper] = completion(**new_kwargs) # type: ignore - translated_response: Optional[Union[BaseModel, AdapterCompletionStreamWrapper]] = ( - None - ) + translated_response: Optional[ + Union[BaseModel, AdapterCompletionStreamWrapper] + ] = None if isinstance(response, ModelResponse): translated_response = translation_obj.translate_completion_output_params( response=response @@ -6336,7 +6362,9 @@ async def atranscription(*args, **kwargs) -> TranscriptionResponse: if existing_duration is None: calculated_duration = calculate_request_duration(file) if calculated_duration is not None: - response._hidden_params["audio_transcription_duration"] = calculated_duration + response._hidden_params[ + "audio_transcription_duration" + ] = calculated_duration return response except Exception as e: @@ -6559,7 +6587,9 @@ def transcription( if existing_duration is None: calculated_duration = calculate_request_duration(file) if calculated_duration is not None: - response._hidden_params["audio_transcription_duration"] = calculated_duration + response._hidden_params[ + "audio_transcription_duration" + ] = calculated_duration if response is None: raise ValueError("Unmapped provider passed in. Unable to get the response.") @@ -6863,9 +6893,9 @@ def speech( # noqa: PLR0915 ElevenLabsTextToSpeechConfig.ELEVENLABS_QUERY_PARAMS_KEY ] = query_params - litellm_params_dict[ElevenLabsTextToSpeechConfig.ELEVENLABS_VOICE_ID_KEY] = ( - voice_id - ) + litellm_params_dict[ + ElevenLabsTextToSpeechConfig.ELEVENLABS_VOICE_ID_KEY + ] = voice_id if api_base is not None: litellm_params_dict["api_base"] = api_base @@ -7444,9 +7474,9 @@ def stream_chunk_builder( # noqa: PLR0915 ] if len(content_chunks) > 0: - response["choices"][0]["message"]["content"] = ( - processor.get_combined_content(content_chunks) - ) + response["choices"][0]["message"][ + "content" + ] = processor.get_combined_content(content_chunks) thinking_blocks = [ chunk @@ -7457,9 +7487,9 @@ def stream_chunk_builder( # noqa: PLR0915 ] if len(thinking_blocks) > 0: - response["choices"][0]["message"]["thinking_blocks"] = ( - processor.get_combined_thinking_content(thinking_blocks) - ) + response["choices"][0]["message"][ + "thinking_blocks" + ] = processor.get_combined_thinking_content(thinking_blocks) reasoning_chunks = [ chunk @@ -7470,9 +7500,9 @@ def stream_chunk_builder( # noqa: PLR0915 ] if len(reasoning_chunks) > 0: - response["choices"][0]["message"]["reasoning_content"] = ( - processor.get_combined_reasoning_content(reasoning_chunks) - ) + response["choices"][0]["message"][ + "reasoning_content" + ] = processor.get_combined_reasoning_content(reasoning_chunks) annotation_chunks = [ chunk @@ -7626,12 +7656,15 @@ async def acount_tokens( from litellm.utils import ProviderConfigManager # Determine provider from model string - resolved_model, custom_llm_provider, dynamic_api_key, dynamic_api_base = ( - get_llm_provider( - model=model, - api_base=api_base, - api_key=api_key, - ) + ( + resolved_model, + custom_llm_provider, + dynamic_api_key, + dynamic_api_base, + ) = get_llm_provider( + model=model, + api_base=api_base, + api_key=api_key, ) # Use dynamic key/base if not explicitly provided @@ -7687,7 +7720,7 @@ async def acount_tokens( local_count = litellm.token_counter( model=model, messages=fallback_messages, - tools=tools, + tools=tools, # type: ignore[arg-type] ) return TokenCountResponse( diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json index 16a9e52825e..9b1d81fee40 100644 --- a/litellm/model_prices_and_context_window_backup.json +++ b/litellm/model_prices_and_context_window_backup.json @@ -7997,6 +7997,80 @@ "supports_response_schema": true, "supports_tool_choice": true }, + "black_forest_labs/flux-kontext-pro": { + "litellm_provider": "black_forest_labs", + "mode": "image_edit", + "output_cost_per_image": 0.04, + "source": "https://bfl.ai/pricing", + "supported_endpoints": [ + "/v1/images/edits", + "/v1/images/generations" + ] + }, + "black_forest_labs/flux-kontext-max": { + "litellm_provider": "black_forest_labs", + "mode": "image_edit", + "output_cost_per_image": 0.08, + "source": "https://bfl.ai/pricing", + "supported_endpoints": [ + "/v1/images/edits", + "/v1/images/generations" + ] + }, + "black_forest_labs/flux-pro-1.0-fill": { + "litellm_provider": "black_forest_labs", + "mode": "image_edit", + "output_cost_per_image": 0.05, + "source": "https://bfl.ai/pricing", + "supported_endpoints": [ + "/v1/images/edits" + ] + }, + "black_forest_labs/flux-pro-1.0-expand": { + "litellm_provider": "black_forest_labs", + "mode": "image_edit", + "output_cost_per_image": 0.05, + "source": "https://bfl.ai/pricing", + "supported_endpoints": [ + "/v1/images/edits" + ] + }, + "black_forest_labs/flux-pro-1.1": { + "litellm_provider": "black_forest_labs", + "mode": "image_generation", + "output_cost_per_image": 0.04, + "source": "https://bfl.ai/pricing", + "supported_endpoints": [ + "/v1/images/generations" + ] + }, + "black_forest_labs/flux-pro-1.1-ultra": { + "litellm_provider": "black_forest_labs", + "mode": "image_generation", + "output_cost_per_image": 0.06, + "source": "https://bfl.ai/pricing", + "supported_endpoints": [ + "/v1/images/generations" + ] + }, + "black_forest_labs/flux-dev": { + "litellm_provider": "black_forest_labs", + "mode": "image_generation", + "output_cost_per_image": 0.025, + "source": "https://bfl.ai/pricing", + "supported_endpoints": [ + "/v1/images/generations" + ] + }, + "black_forest_labs/flux-pro": { + "litellm_provider": "black_forest_labs", + "mode": "image_generation", + "output_cost_per_image": 0.05, + "source": "https://bfl.ai/pricing", + "supported_endpoints": [ + "/v1/images/generations" + ] + }, "cerebras/llama-3.3-70b": { "input_cost_per_token": 8.5e-07, "litellm_provider": "cerebras", @@ -14442,7 +14516,7 @@ "input_cost_per_audio_per_second": 0.00016, "input_cost_per_image": 0.00012, "input_cost_per_token": 2e-07, - "input_cost_per_video_per_second": 0.0237, + "input_cost_per_video_per_second": 0.00079, "litellm_provider": "vertex_ai-embedding-models", "max_input_tokens": 8192, "max_tokens": 8192, @@ -14452,6 +14526,34 @@ "source": "https://cloud.google.com/vertex-ai/generative-ai/pricing", "uses_embed_content": true }, + "vertex_ai/gemini-embedding-2-preview": { + "input_cost_per_audio_per_second": 0.00016, + "input_cost_per_image": 0.00012, + "input_cost_per_token": 2e-07, + "input_cost_per_video_per_second": 0.00079, + "litellm_provider": "vertex_ai", + "max_input_tokens": 8192, + "max_tokens": 8192, + "mode": "embedding", + "output_cost_per_token": 0, + "output_vector_size": 3072, + "source": "https://cloud.google.com/vertex-ai/generative-ai/pricing", + "supports_multimodal": true, + "uses_embed_content": true + }, + "gemini-flash-experimental": { + "input_cost_per_character": 0, + "input_cost_per_token": 0, + "litellm_provider": "vertex_ai-language-models", + "max_input_tokens": 1000000, + "max_output_tokens": 8192, + "max_tokens": 8192, + "mode": "embedding", + "output_cost_per_token": 0, + "output_vector_size": 3072, + "source": "https://cloud.google.com/vertex-ai/generative-ai/pricing", + "uses_embed_content": true + }, "vertex_ai/gemini-embedding-2-preview": { "input_cost_per_token": 1.5e-07, "litellm_provider": "vertex_ai", @@ -14477,7 +14579,25 @@ "tpm": 10000000 }, "gemini/gemini-embedding-2-preview": { - "input_cost_per_token": 1.5e-07, + "input_cost_per_audio_per_second": 0.00016, + "input_cost_per_image": 0.00012, + "input_cost_per_token": 2e-07, + "input_cost_per_video_per_second": 0.00079, + "litellm_provider": "gemini", + "max_input_tokens": 8192, + "max_tokens": 8192, + "mode": "embedding", + "output_cost_per_token": 0, + "output_vector_size": 3072, + "rpm": 10000, + "source": "https://ai.google.dev/gemini-api/docs/pricing", + "supports_multimodal": true, + "tpm": 10000000 + }, + "gemini/gemini-1.5-flash": { + "deprecation_date": "2025-09-29", + "input_cost_per_token": 7.5e-08, + "input_cost_per_token_above_128k_tokens": 1.5e-07, "litellm_provider": "gemini", "max_input_tokens": 8192, "max_tokens": 8192, @@ -30801,6 +30921,9 @@ "mode": "chat", "output_cost_per_token": 2.2e-06, "source": "https://cloud.google.com/vertex-ai/generative-ai/pricing#partner-models", + "supported_regions": [ + "global" + ], "supports_function_calling": true, "supports_reasoning": true, "supports_tool_choice": true @@ -30815,6 +30938,7 @@ "mode": "chat", "output_cost_per_token": 3.2e-06, "source": "https://cloud.google.com/vertex-ai/generative-ai/pricing#glm-models", + "supported_regions": ["global"], "supports_function_calling": true, "supports_prompt_caching": true, "supports_reasoning": true, diff --git a/litellm/ocr/__init__.py b/litellm/ocr/__init__.py index 53f455619d7..a20b0ef6cad 100644 --- a/litellm/ocr/__init__.py +++ b/litellm/ocr/__init__.py @@ -2,4 +2,3 @@ from .main import aocr, ocr __all__ = ["ocr", "aocr"] - diff --git a/litellm/passthrough/main.py b/litellm/passthrough/main.py index e76a222b2ed..edee50bdfc4 100644 --- a/litellm/passthrough/main.py +++ b/litellm/passthrough/main.py @@ -113,7 +113,7 @@ async def allm_passthrough_route( # Only call raise_for_status if it's a Response object (not a generator) if isinstance(response, httpx.Response): response.raise_for_status() - + return response else: # This shouldn't happen when allm_passthrough_route=True, but handle it for type safety @@ -216,11 +216,11 @@ def llm_passthrough_route( ) litellm_params_dict = get_litellm_params(**kwargs) - + # Add model_id to litellm_params if present in kwargs (for Bedrock Application Inference Profiles) if "model_id" in kwargs: litellm_params_dict["model_id"] = kwargs["model_id"] - + litellm_logging_obj.update_environment_variables( model=model, litellm_params=litellm_params_dict, @@ -363,7 +363,7 @@ async def _async_passthrough_request( """ # client.client.send returns a coroutine for async clients response_result = client.client.send(request=request, stream=is_streaming_request) - + # Check if it's a coroutine and await it if asyncio.iscoroutine(response_result): if is_streaming_request: @@ -416,7 +416,6 @@ async def _async_streaming( raw_bytes: List[bytes] = [] async for chunk in iter_response.aiter_bytes(): # type: ignore - raw_bytes.append(chunk) yield chunk diff --git a/litellm/passthrough/utils.py b/litellm/passthrough/utils.py index fe1ecad96c2..ef4357d1ca2 100644 --- a/litellm/passthrough/utils.py +++ b/litellm/passthrough/utils.py @@ -11,7 +11,7 @@ class BasePassthroughUtils: def get_merged_query_parameters( existing_url: httpx.URL, request_query_params: Mapping[str, Union[str, list]], - default_query_params: Optional[Dict[str, Union[str, list]]] = None + default_query_params: Optional[Dict[str, Union[str, list]]] = None, ) -> Dict[str, Union[str, List[str]]]: # Get the existing query params from the target URL existing_query_string = existing_url.query.decode("utf-8") @@ -65,6 +65,7 @@ class BasePassthroughUtils: return headers + class CommonUtils: @staticmethod def encode_bedrock_runtime_modelid_arn(endpoint: str) -> str: @@ -77,37 +78,36 @@ class CommonUtils: arn:aws:bedrock:ap-southeast-1:123456789012:application-inference-profile%2Fabdefg12334 so that it is treated as one part of the path. Otherwise, the encoded endpoint will return 500 error when passed to Bedrock endpoint. - + See the apis in https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Amazon_Bedrock_Runtime.html for more details on the regex patterns of modelId which we use in the regex logic below. - + Args: endpoint (str): The original endpoint string which may contain ARNs that contain slashes. - + Returns: str: The endpoint with properly encoded ARN slashes """ import re # Early exit: if no ARN detected, return unchanged - if 'arn:aws:' not in endpoint: + if "arn:aws:" not in endpoint: return endpoint # Handle all patterns in one go - more efficient and cleaner patterns = [ # Custom model with 2 slashes (order matters - do this first) - (r'(custom-model)/([a-z0-9.-]+)/([a-z0-9]+)', r'\1%2F\2%2F\3'), - + (r"(custom-model)/([a-z0-9.-]+)/([a-z0-9]+)", r"\1%2F\2%2F\3"), # All other resource types with 1 slash - (r'(:application-inference-profile)/', r'\1%2F'), - (r'(:inference-profile)/', r'\1%2F'), - (r'(:foundation-model)/', r'\1%2F'), - (r'(:imported-model)/', r'\1%2F'), - (r'(:provisioned-model)/', r'\1%2F'), - (r'(:prompt)/', r'\1%2F'), - (r'(:endpoint)/', r'\1%2F'), - (r'(:prompt-router)/', r'\1%2F'), - (r'(:default-prompt-router)/', r'\1%2F'), + (r"(:application-inference-profile)/", r"\1%2F"), + (r"(:inference-profile)/", r"\1%2F"), + (r"(:foundation-model)/", r"\1%2F"), + (r"(:imported-model)/", r"\1%2F"), + (r"(:provisioned-model)/", r"\1%2F"), + (r"(:prompt)/", r"\1%2F"), + (r"(:endpoint)/", r"\1%2F"), + (r"(:prompt-router)/", r"\1%2F"), + (r"(:default-prompt-router)/", r"\1%2F"), ] for pattern, replacement in patterns: @@ -116,4 +116,4 @@ class CommonUtils: endpoint = re.sub(pattern, replacement, endpoint) break # Exit after first match since each ARN has only one resource type - return endpoint \ No newline at end of file + return endpoint 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 c670146be35..357d21eb09a 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 @@ -388,7 +388,6 @@ class MCPRequestHandler: ) ) - # If end_user has explicit MCP server permissions, apply intersection if len(allowed_mcp_servers_for_end_user) > 0: verbose_logger.debug( @@ -547,16 +546,16 @@ class MCPRequestHandler: agent_obj_perm = await MCPRequestHandler._get_agent_object_permission( user_api_key_auth ) - agent_tools = await MCPRequestHandler._get_agent_tool_permissions_for_server( - server_id=server_id, - user_api_key_auth=user_api_key_auth, - agent_object_permission=agent_obj_perm, + agent_tools = ( + await MCPRequestHandler._get_agent_tool_permissions_for_server( + server_id=server_id, + user_api_key_auth=user_api_key_auth, + agent_object_permission=agent_obj_perm, + ) ) if agent_tools is not None: if allowed_tools is not None: - allowed_tools = list( - set(allowed_tools) & set(agent_tools) - ) + allowed_tools = list(set(allowed_tools) & set(agent_tools)) else: allowed_tools = agent_tools return allowed_tools @@ -621,13 +620,18 @@ class MCPRequestHandler: key_object_permission = MCPRequestHandler._get_key_object_permission( user_api_key_auth ) - if key_object_permission is None and user_api_key_auth and user_api_key_auth.object_permission_id: + if ( + key_object_permission is None + and user_api_key_auth + and user_api_key_auth.object_permission_id + ): from litellm.proxy.auth.auth_checks import get_object_permission from litellm.proxy.proxy_server import ( prisma_client, proxy_logging_obj, user_api_key_cache, ) + if prisma_client is not None: key_object_permission = await get_object_permission( object_permission_id=user_api_key_auth.object_permission_id, @@ -725,7 +729,6 @@ class MCPRequestHandler: return [] if prisma_client is None: - verbose_logger.debug("prisma_client is None") return [] @@ -740,7 +743,6 @@ class MCPRequestHandler: route="/mcp", ) - if end_user_obj is None or end_user_obj.object_permission is None: return [] @@ -796,9 +798,7 @@ class MCPRequestHandler: return agent_row.object_permission except Exception as e: - verbose_logger.warning( - f"Failed to get agent object permission: {str(e)}" - ) + verbose_logger.warning(f"Failed to get agent object permission: {str(e)}") return None @staticmethod @@ -877,9 +877,7 @@ class MCPRequestHandler: if obj_perm is None: return None - mcp_tool_permissions = getattr( - obj_perm, "mcp_tool_permissions", None - ) + mcp_tool_permissions = getattr(obj_perm, "mcp_tool_permissions", None) if not mcp_tool_permissions: return None if isinstance(mcp_tool_permissions, dict): diff --git a/litellm/proxy/_experimental/mcp_server/byok_oauth_endpoints.py b/litellm/proxy/_experimental/mcp_server/byok_oauth_endpoints.py index db18885721a..48884d82274 100644 --- a/litellm/proxy/_experimental/mcp_server/byok_oauth_endpoints.py +++ b/litellm/proxy/_experimental/mcp_server/byok_oauth_endpoints.py @@ -653,7 +653,9 @@ async def byok_authorize_post( # Reject new codes if the store is at capacity (prevents memory exhaustion # from a burst of abandoned OAuth flows). if len(_byok_auth_codes) >= _AUTH_CODES_MAX_SIZE: - raise HTTPException(status_code=503, detail="Too many pending authorization flows") + raise HTTPException( + status_code=503, detail="Too many pending authorization flows" + ) if code_challenge_method != "S256": raise HTTPException( @@ -745,6 +747,7 @@ async def byok_token( from litellm.proxy._experimental.mcp_server.server import ( _invalidate_byok_cred_cache, ) + _invalidate_byok_cred_cache(user_id, server_id) except Exception as exc: verbose_proxy_logger.error( diff --git a/litellm/proxy/_experimental/mcp_server/db.py b/litellm/proxy/_experimental/mcp_server/db.py index 477229dc700..fbef33c32ed 100644 --- a/litellm/proxy/_experimental/mcp_server/db.py +++ b/litellm/proxy/_experimental/mcp_server/db.py @@ -68,9 +68,13 @@ def _prepare_mcp_server_data( # Handle tool name override serialization if data.tool_name_to_display_name is not None: - data_dict["tool_name_to_display_name"] = safe_dumps(data.tool_name_to_display_name) + data_dict["tool_name_to_display_name"] = safe_dumps( + data.tool_name_to_display_name + ) if data.tool_name_to_description is not None: - data_dict["tool_name_to_description"] = safe_dumps(data.tool_name_to_description) + data_dict["tool_name_to_description"] = safe_dumps( + data.tool_name_to_description + ) # mcp_access_groups is already List[str], no serialization needed @@ -138,9 +142,9 @@ def decrypt_credentials( "aws_session_token", ] for field in secret_fields: - value = credentials.get(field) - if value is not None: - credentials[field] = decrypt_value_helper( + value = credentials.get(field) # type: ignore[literal-required] + if value is not None and isinstance(value, str): + credentials[field] = decrypt_value_helper( # type: ignore[literal-required] value=value, key=field, exception_type="debug", @@ -405,7 +409,9 @@ async def update_mcp_server( # Pre-fetch existing record once if we need it for auth_type or credential logic existing = None - has_credentials = "credentials" in data_dict and data_dict["credentials"] is not None + has_credentials = ( + "credentials" in data_dict and data_dict["credentials"] is not None + ) if data.auth_type or has_credentials: existing = await prisma_client.db.litellm_mcpservertable.find_unique( where={"server_id": data.server_id} @@ -628,6 +634,24 @@ async def store_user_oauth_credential( ) +def is_oauth_credential_expired(cred: Dict[str, Any]) -> bool: + """Return True if the OAuth2 credential's access_token has expired. + + Checks the ``expires_at`` ISO-format string stored in the credential payload. + Returns False when ``expires_at`` is absent or unparseable (treat as non-expired). + """ + expires_at = cred.get("expires_at") + if not expires_at: + return False + try: + exp_dt = datetime.fromisoformat(expires_at) + if exp_dt.tzinfo is None: + exp_dt = exp_dt.replace(tzinfo=timezone.utc) + return datetime.now(timezone.utc) > exp_dt + except (ValueError, TypeError): + return False + + async def get_user_oauth_credential( prisma_client: PrismaClient, user_id: str, @@ -728,7 +752,9 @@ async def get_mcp_submissions( ) items = [LiteLLM_MCPServerTable(**r.model_dump()) for r in rows] - pending = sum(1 for i in items if i.approval_status == MCPApprovalStatus.pending_review) + pending = sum( + 1 for i in items if i.approval_status == MCPApprovalStatus.pending_review + ) active = sum(1 for i in items if i.approval_status == MCPApprovalStatus.active) rejected = sum(1 for i in items if i.approval_status == MCPApprovalStatus.rejected) diff --git a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py index ad1dadb1222..af3a715051b 100644 --- a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py +++ b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py @@ -141,9 +141,7 @@ def _resolve_oauth2_server_for_root_endpoints( ) registry = global_mcp_server_manager.get_filtered_registry(client_ip=client_ip) - oauth2_servers = [ - s for s in registry.values() if s.auth_type == MCPAuth.oauth2 - ] + oauth2_servers = [s for s in registry.values() if s.auth_type == MCPAuth.oauth2] if len(oauth2_servers) == 1: return oauth2_servers[0] return None @@ -197,9 +195,7 @@ async def authorize_with_server( parsed_auth_url = urlparse(mcp_server.authorization_url) existing_params = dict(parse_qsl(parsed_auth_url.query)) existing_params.update(params) - final_url = urlunparse( - parsed_auth_url._replace(query=urlencode(existing_params)) - ) + final_url = urlunparse(parsed_auth_url._replace(query=urlencode(existing_params))) return RedirectResponse(final_url) @@ -333,7 +329,9 @@ async def authorize( lookup_name: Optional[str] = mcp_server_name or client_id 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) + global_mcp_server_manager.get_mcp_server_by_name( + lookup_name, client_ip=client_ip + ) if lookup_name else None ) @@ -513,16 +511,18 @@ def _build_oauth_protected_resource_response( ) ], "resource": resource_url, - "scopes_supported": mcp_server.scopes if mcp_server and mcp_server.scopes else [], + "scopes_supported": mcp_server.scopes + if mcp_server and mcp_server.scopes + else [], } # Standard MCP pattern: /.well-known/oauth-protected-resource/mcp/{server_name} # This is the pattern expected by standard MCP clients (mcp-inspector, VSCode Copilot) -@router.get(f"/.well-known/oauth-protected-resource{'' if get_server_root_path() == '/' else get_server_root_path()}/mcp/{{mcp_server_name}}") -async def oauth_protected_resource_mcp_standard( - request: Request, mcp_server_name: str -): +@router.get( + f"/.well-known/oauth-protected-resource{'' if get_server_root_path() == '/' else get_server_root_path()}/mcp/{{mcp_server_name}}" +) +async def oauth_protected_resource_mcp_standard(request: Request, mcp_server_name: str): """ OAuth protected resource discovery endpoint using standard MCP URL pattern. @@ -541,7 +541,9 @@ async def oauth_protected_resource_mcp_standard( # LiteLLM legacy pattern: /.well-known/oauth-protected-resource/{server_name}/mcp # Kept for backward compatibility with existing deployments -@router.get(f"/.well-known/oauth-protected-resource{'' if get_server_root_path() == '/' else get_server_root_path()}/{{mcp_server_name}}/mcp") +@router.get( + f"/.well-known/oauth-protected-resource{'' if get_server_root_path() == '/' else get_server_root_path()}/{{mcp_server_name}}/mcp" +) @router.get("/.well-known/oauth-protected-resource") async def oauth_protected_resource_mcp( request: Request, mcp_server_name: Optional[str] = None @@ -561,6 +563,7 @@ async def oauth_protected_resource_mcp( use_standard_pattern=False, ) + """ https://datatracker.ietf.org/doc/html/rfc8414#section-3.1 RFC 8414: Path-aware OAuth discovery @@ -620,17 +623,23 @@ def _build_oauth_authorization_server_response( "authorization_endpoint": authorization_endpoint, "token_endpoint": token_endpoint, "response_types_supported": ["code"], - "scopes_supported": mcp_server.scopes if mcp_server and mcp_server.scopes else [], + "scopes_supported": mcp_server.scopes + if mcp_server and mcp_server.scopes + else [], "grant_types_supported": ["authorization_code", "refresh_token"], "code_challenge_methods_supported": ["S256"], "token_endpoint_auth_methods_supported": ["client_secret_post"], # Claude expects a registration endpoint, even if we just fake it - "registration_endpoint": f"{request_base_url}/{mcp_server_name}/register" if mcp_server_name else f"{request_base_url}/register", + "registration_endpoint": f"{request_base_url}/{mcp_server_name}/register" + if mcp_server_name + else f"{request_base_url}/register", } # Standard MCP pattern: /.well-known/oauth-authorization-server/mcp/{server_name} -@router.get(f"/.well-known/oauth-authorization-server{'' if get_server_root_path() == '/' else get_server_root_path()}/mcp/{{mcp_server_name}}") +@router.get( + f"/.well-known/oauth-authorization-server{'' if get_server_root_path() == '/' else get_server_root_path()}/mcp/{{mcp_server_name}}" +) async def oauth_authorization_server_mcp_standard( request: Request, mcp_server_name: str ): @@ -647,7 +656,9 @@ async def oauth_authorization_server_mcp_standard( # LiteLLM legacy pattern and root endpoint -@router.get(f"/.well-known/oauth-authorization-server{'' if get_server_root_path() == '/' else get_server_root_path()}/{{mcp_server_name}}") +@router.get( + f"/.well-known/oauth-authorization-server{'' if get_server_root_path() == '/' else get_server_root_path()}/{{mcp_server_name}}" +) @router.get("/.well-known/oauth-authorization-server") async def oauth_authorization_server_mcp( request: Request, mcp_server_name: Optional[str] = None @@ -671,9 +682,7 @@ async def openid_configuration(request: Request): # Additional legacy pattern support @router.get("/.well-known/oauth-authorization-server/{mcp_server_name}/mcp") -async def oauth_authorization_server_legacy( - request: Request, mcp_server_name: str -): +async def oauth_authorization_server_legacy(request: Request, mcp_server_name: str): """ OAuth authorization server discovery for legacy /{server_name}/mcp pattern. """ @@ -710,9 +719,7 @@ async def register_client(request: Request, mcp_server_name: Optional[str] = Non client_name=data.get("client_name", ""), grant_types=data.get("grant_types", []), response_types=data.get("response_types", []), - token_endpoint_auth_method=data.get( - "token_endpoint_auth_method", "" - ), + token_endpoint_auth_method=data.get("token_endpoint_auth_method", ""), fallback_client_id=resolved.server_name or resolved.name, ) return dummy_return diff --git a/litellm/proxy/_experimental/mcp_server/mcp_debug.py b/litellm/proxy/_experimental/mcp_server/mcp_debug.py index 46741a9df98..254f208e231 100644 --- a/litellm/proxy/_experimental/mcp_server/mcp_debug.py +++ b/litellm/proxy/_experimental/mcp_server/mcp_debug.py @@ -254,9 +254,7 @@ class MCPDebug: return debug @staticmethod - def wrap_send_with_debug_headers( - send: Send, debug_headers: Dict[str, str] - ) -> Send: + def wrap_send_with_debug_headers(send: Send, debug_headers: Dict[str, str]) -> Send: """ Return a new ASGI ``send`` callable that injects *debug_headers* into the ``http.response.start`` message. @@ -315,9 +313,7 @@ class MCPDebug: break scope_headers = MCPRequestHandler._safe_get_headers_from_scope(scope) - litellm_key = MCPRequestHandler.get_litellm_api_key_from_headers( - scope_headers - ) + litellm_key = MCPRequestHandler.get_litellm_api_key_from_headers(scope_headers) return MCPDebug.build_debug_headers( inbound_headers=raw_headers, diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py index b10bfde4915..43fe54fdfb7 100644 --- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py +++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py @@ -501,12 +501,12 @@ class MCPServerManager: ) # 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( @@ -970,7 +970,9 @@ class MCPServerManager: # Handle stdio transport if transport == MCPTransport.stdio: - resolved_env = stdio_env if stdio_env is not None else dict(server.env or {}) + resolved_env = ( + stdio_env if stdio_env is not None else dict(server.env or {}) + ) # Ensure npm-based STDIO MCP servers have a writable cache dir. # In containers the default (~/.npm or /app/.npm) may not exist @@ -2355,7 +2357,9 @@ class MCPServerManager: prisma_client = get_prisma_client_or_throw( "Database not connected. Connect a database to your proxy" ) - db_mcp_servers = await get_all_mcp_servers(prisma_client, approval_status="active") + db_mcp_servers = await get_all_mcp_servers( + prisma_client, approval_status="active" + ) verbose_logger.info(f"Found {len(db_mcp_servers)} MCP servers in database") previous_registry = self.registry diff --git a/litellm/proxy/_experimental/mcp_server/oauth2_token_cache.py b/litellm/proxy/_experimental/mcp_server/oauth2_token_cache.py index 0de381ee1df..84a2e94467b 100644 --- a/litellm/proxy/_experimental/mcp_server/oauth2_token_cache.py +++ b/litellm/proxy/_experimental/mcp_server/oauth2_token_cache.py @@ -124,11 +124,18 @@ class MCPOAuth2TokenCache(InMemoryCache): # Safely parse expires_in — providers may return null or non-numeric values raw_expires_in = body.get("expires_in") try: - expires_in = int(raw_expires_in) if raw_expires_in is not None else MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL + expires_in = ( + int(raw_expires_in) + if raw_expires_in is not None + else MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL + ) except (TypeError, ValueError): expires_in = MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL - ttl = max(expires_in - MCP_OAUTH2_TOKEN_EXPIRY_BUFFER_SECONDS, MCP_OAUTH2_TOKEN_CACHE_MIN_TTL) + ttl = max( + expires_in - MCP_OAUTH2_TOKEN_EXPIRY_BUFFER_SECONDS, + MCP_OAUTH2_TOKEN_CACHE_MIN_TTL, + ) verbose_logger.info( "Fetched OAuth2 token for MCP server %s (expires in %ds)", diff --git a/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py b/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py index 5f6cb87b26b..4b4818892bb 100644 --- a/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py +++ b/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py @@ -71,6 +71,7 @@ def load_openapi_spec(filepath: str) -> Dict[str, Any]: raise return asyncio.run(load_openapi_spec_async(filepath)) + async def load_openapi_spec_async(filepath: str) -> Dict[str, Any]: if filepath.startswith("http://") or filepath.startswith("https://"): client = get_async_httpx_client(llm_provider=httpxSpecialProvider.MCP) @@ -92,26 +93,55 @@ def get_base_url(spec: Dict[str, Any], spec_path: Optional[str] = None) -> str: """Extract base URL from OpenAPI spec.""" # OpenAPI 3.x if "servers" in spec and spec["servers"]: - return spec["servers"][0]["url"] + server_url = spec["servers"][0]["url"] + + # If the server URL is relative (starts with /), derive base from spec_path + if server_url.startswith("/") and spec_path: + if spec_path.startswith("http://") or spec_path.startswith("https://"): + # Extract base URL from spec_path (e.g., https://petstore3.swagger.io/api/v3/openapi.json) + # Combine domain with the relative server URL + from urllib.parse import urlparse + + parsed = urlparse(spec_path) + base_domain = f"{parsed.scheme}://{parsed.netloc}" + full_base_url = base_domain + server_url + verbose_logger.info( + f"OpenAPI spec has relative server URL '{server_url}'. " + f"Deriving base from spec_path: {full_base_url}" + ) + return full_base_url + + return server_url # OpenAPI 2.x (Swagger) elif "host" in spec: scheme = spec.get("schemes", ["https"])[0] base_path = spec.get("basePath", "") return f"{scheme}://{spec['host']}{base_path}" - + # Fallback: derive base URL from spec_path if it's a URL - if spec_path and (spec_path.startswith("http://") or spec_path.startswith("https://")): - for suffix in ["/openapi.json", "/openapi.yaml", "/swagger.json", "/swagger.yaml"]: + if spec_path and ( + spec_path.startswith("http://") or spec_path.startswith("https://") + ): + for suffix in [ + "/openapi.json", + "/openapi.yaml", + "/swagger.json", + "/swagger.yaml", + ]: if spec_path.endswith(suffix): - base_url = spec_path[:-len(suffix)] - verbose_logger.info(f"No server info in OpenAPI spec. Using derived base URL: {base_url}") + base_url = spec_path[: -len(suffix)] + verbose_logger.info( + f"No server info in OpenAPI spec. Using derived base URL: {base_url}" + ) return base_url - + if spec_path.split("/")[-1].endswith((".json", ".yaml", ".yml")): base_url = "/".join(spec_path.split("/")[:-1]) - verbose_logger.info(f"No server info in OpenAPI spec. Using derived base URL: {base_url}") + verbose_logger.info( + f"No server info in OpenAPI spec. Using derived base URL: {base_url}" + ) return base_url - + return "" @@ -165,7 +195,9 @@ def resolve_operation_params( path_level = _resolve_param_list(path_item.get("parameters", []), component_params) op_level = _resolve_param_list(operation.get("parameters", []), component_params) op_keys = {(p["name"], p.get("in")) for p in op_level} - merged = [p for p in path_level if (p["name"], p.get("in")) not in op_keys] + op_level + merged = [ + p for p in path_level if (p["name"], p.get("in")) not in op_keys + ] + op_level result = dict(operation) result["parameters"] = merged return result @@ -350,7 +382,9 @@ def create_tool_function( url, params=params, json=json_body, headers=effective_headers ) elif original_method == "delete": - response = await client.delete(url, params=params, headers=effective_headers) + response = await client.delete( + url, params=params, headers=effective_headers + ) elif original_method == "patch": response = await client.patch( url, params=params, json=json_body, headers=effective_headers diff --git a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py b/litellm/proxy/_experimental/mcp_server/rest_endpoints.py index 6082e9bd606..307caa2fbc8 100644 --- a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py +++ b/litellm/proxy/_experimental/mcp_server/rest_endpoints.py @@ -1,6 +1,6 @@ import importlib from datetime import datetime -from typing import Any, Awaitable, Callable, Dict, List, Optional, Union +from typing import Any, Awaitable, Callable, Dict, List, Literal, Optional, Set, Union from fastapi import APIRouter, Depends, HTTPException, Query, Request @@ -69,6 +69,136 @@ if MCP_AVAILABLE: return server_auth return mcp_auth_header + def _get_oauth2_server_ids(allowed_server_ids: List[str]) -> Set[str]: + """Return the subset of *allowed_server_ids* whose servers use OAuth2 auth. + + Used as a cheap pre-flight check to skip bulk credential fetching when no + OAuth2 servers are involved in the current request. + """ + return { + sid + for sid in allowed_server_ids + if getattr( + global_mcp_server_manager.get_mcp_server_by_id(sid), "auth_type", None + ) + == MCPAuth.oauth2 + } + + async def _get_user_oauth_extra_headers( + server, + user_api_key_dict: UserAPIKeyAuth, + prefetched_creds: Optional[Dict[str, Dict[str, Any]]] = None, + ) -> Optional[Dict[str, str]]: + """ + For OAuth2 servers, look up the user's stored access token and return it + as extra_headers {"Authorization": "Bearer "} so that it reaches + the MCP server the same way the admin "Add MCP / Authorize and Fetch" flow does. + Returns None for non-OAuth2 servers or when no credential is stored. + + Args: + prefetched_creds: Optional dict keyed by server_id with credential payloads. + When provided, avoids a per-server DB round-trip. + """ + if getattr(server, "auth_type", None) != MCPAuth.oauth2: + return None + user_id = getattr(user_api_key_dict, "user_id", None) + server_id = getattr(server, "server_id", None) + if not user_id or not server_id: + return None + try: + from litellm.proxy._experimental.mcp_server.db import ( + get_user_oauth_credential, + is_oauth_credential_expired, + ) + + if prefetched_creds is not None: + cred = prefetched_creds.get(server_id) + else: + from litellm.proxy.utils import get_prisma_client_or_throw + + prisma_client = get_prisma_client_or_throw( + "Database not connected. Connect a database to use OAuth2 MCP tools." + ) + cred = await get_user_oauth_credential( + prisma_client, user_id, server_id + ) + if cred and cred.get("access_token"): + if is_oauth_credential_expired(cred): + verbose_logger.debug( + f"_get_user_oauth_extra_headers: token expired for " + f"user={user_id} server={server_id}" + ) + return None + return {"Authorization": f"Bearer {cred['access_token']}"} + except Exception as e: + verbose_logger.warning( + f"_get_user_oauth_extra_headers: failed to retrieve credential for " + f"user={user_id} server={server_id}: {e}" + ) + return None + + async def _prefetch_user_oauth_creds( + user_api_key_dict: UserAPIKeyAuth, + ) -> Dict[str, Dict[str, Any]]: + """Fetch all OAuth2 credentials for the user in a single DB query. + + Returns a dict keyed by server_id. Used to avoid N+1 DB queries when + iterating over multiple OAuth2 MCP servers. + """ + user_id = getattr(user_api_key_dict, "user_id", None) + if not user_id: + return {} + try: + from litellm.proxy._experimental.mcp_server.db import ( + list_user_oauth_credentials, + ) + from litellm.proxy.utils import get_prisma_client_or_throw + + prisma_client = get_prisma_client_or_throw( + "Database not connected. Connect a database to use OAuth2 MCP tools." + ) + creds = await list_user_oauth_credentials(prisma_client, user_id) + return {c["server_id"]: c for c in creds if "server_id" in c} + except Exception as e: + verbose_logger.warning( + f"_prefetch_user_oauth_creds: failed to prefetch for user={user_id}: {e}" + ) + return {} + + async def _get_bulk_user_oauth_headers( + user_api_key_dict: UserAPIKeyAuth, + ) -> Dict[str, Dict[str, str]]: + """ + Fetch ALL OAuth2 credentials for the current user in a single DB query and + return a mapping of server_id → {"Authorization": "Bearer "}. + + This is the batch alternative to calling _get_user_oauth_extra_headers + per-server inside a loop (N+1 DB queries). + """ + user_id = getattr(user_api_key_dict, "user_id", None) + if not user_id: + return {} + try: + from litellm.proxy._experimental.mcp_server.db import ( + list_user_oauth_credentials, + ) + from litellm.proxy.utils import get_prisma_client_or_throw + + prisma_client = get_prisma_client_or_throw( + "Database not connected. Connect a database to use OAuth2 MCP tools." + ) + creds = await list_user_oauth_credentials(prisma_client, user_id) + return { + c["server_id"]: {"Authorization": f"Bearer {c['access_token']}"} + for c in creds + if c.get("access_token") and c.get("server_id") + } + except Exception: + verbose_logger.debug( + "Failed to bulk-fetch OAuth credentials", exc_info=True + ) + return {} + def _create_tool_response_objects(tools, server_mcp_info): """Helper function to create tool response objects.""" return [ @@ -162,11 +292,13 @@ if MCP_AVAILABLE: server_auth_header, raw_headers: Optional[Dict[str, str]] = None, user_api_key_auth: Optional[UserAPIKeyAuth] = None, + extra_headers: Optional[Dict[str, str]] = None, ): """Helper function to get tools for a single server.""" tools = await global_mcp_server_manager._get_tools_from_server( server=server, mcp_auth_header=server_auth_header, + extra_headers=extra_headers, add_prefix=False, raw_headers=raw_headers, ) @@ -228,7 +360,189 @@ if MCP_AVAILABLE: allowed_mcp_servers.append(server) return allowed_mcp_servers + async def _list_tools_for_single_server( + server_id: str, + allowed_server_ids: List[str], + rest_client_ip: Optional[str], + mcp_server_auth_headers: dict, + mcp_auth_header: Optional[str], + raw_headers_from_request: dict, + user_api_key_dict: "UserAPIKeyAuth", + ) -> dict: + """ + Resolve and fetch tools for a single specified MCP server. + + Returns the full REST response dict (tools / error / message). + Raises HTTPException on access / IP-filter errors. + """ + # Resolve a server name to its UUID if needed + _name_resolved = None + if server_id not in allowed_server_ids: + _name_resolved = global_mcp_server_manager.get_mcp_server_by_name( + server_id + ) + if _name_resolved is not None and _name_resolved.server_id in set( + allowed_server_ids + ): + server_id = _name_resolved.server_id + + if server_id not in allowed_server_ids: + _server = ( + global_mcp_server_manager.get_mcp_server_by_id(server_id) + or _name_resolved + ) + if ( + _server is not None + and rest_client_ip is not None + and not global_mcp_server_manager._is_server_accessible_from_ip( + _server, rest_client_ip + ) + ): + raise HTTPException( + status_code=403, + detail={ + "error": "ip_filtering", + "message": ( + f"MCP server '{server_id}' is not accessible from your IP address " + f"({rest_client_ip}). This server is restricted to internal " + "networks only. To make it externally accessible, set " + "'available_on_public_internet: true' in the server configuration." + ), + }, + ) + raise HTTPException( + status_code=403, + detail={ + "error": "access_denied", + "message": f"The key is not allowed to access server {server_id}", + }, + ) + + server = global_mcp_server_manager.get_mcp_server_by_id(server_id) + if server is None: + return { + "tools": [], + "error": "server_not_found", + "message": f"Server with id {server_id} not found", + } + + server_auth_header = _get_server_auth_header( + server, mcp_server_auth_headers, mcp_auth_header + ) + user_oauth_extra_headers = await _get_user_oauth_extra_headers( + server, user_api_key_dict + ) + + try: + tools = await _get_tools_for_single_server( + server, + server_auth_header, + raw_headers_from_request, + user_api_key_dict, + extra_headers=user_oauth_extra_headers, + ) + except Exception as e: + verbose_logger.exception( + f"Error getting tools from {server.name}: {e}" + ) + return { + "tools": [], + "error": "server_error", + "message": f"Failed to get tools from server {server.name}: {str(e)}", + } + + return { + "tools": tools, + "error": None, + "message": "Successfully retrieved tools", + } + ######################################################## + + async def _list_tools_for_single_server( + server_id: str, + allowed_server_ids: List[str], + rest_client_ip: Optional[str], + mcp_server_auth_headers: dict, + mcp_auth_header: Optional[str], + raw_headers_from_request: dict, + user_api_key_dict: UserAPIKeyAuth, + ) -> dict: + """Handle tool listing for a single server_id request.""" + # Resolve a server name to its UUID if needed + _name_resolved = None + if server_id not in allowed_server_ids: + _name_resolved = global_mcp_server_manager.get_mcp_server_by_name(server_id) + if _name_resolved is not None and _name_resolved.server_id in set(allowed_server_ids): + server_id = _name_resolved.server_id + + if server_id not in allowed_server_ids: + _server = ( + global_mcp_server_manager.get_mcp_server_by_id(server_id) + or _name_resolved + ) + if ( + _server is not None + and rest_client_ip is not None + and not global_mcp_server_manager._is_server_accessible_from_ip( + _server, rest_client_ip + ) + ): + raise HTTPException( + status_code=403, + detail={ + "error": "ip_filtering", + "message": ( + f"MCP server '{server_id}' is not accessible from your IP address " + f"({rest_client_ip}). This server is restricted to internal " + "networks only. To make it externally accessible, set " + "'available_on_public_internet: true' in the server configuration." + ), + }, + ) + raise HTTPException( + status_code=403, + detail={ + "error": "access_denied", + "message": f"The key is not allowed to access server {server_id}", + }, + ) + server = global_mcp_server_manager.get_mcp_server_by_id(server_id) + if server is None: + return { + "tools": [], + "error": "server_not_found", + "message": f"Server with id {server_id} not found", + } + + server_auth_header = _get_server_auth_header( + server, mcp_server_auth_headers, mcp_auth_header + ) + user_oauth_extra_headers = await _get_user_oauth_extra_headers(server, user_api_key_dict) + + try: + list_tools_result = await _get_tools_for_single_server( + server, + server_auth_header, + raw_headers_from_request, + user_api_key_dict, + extra_headers=user_oauth_extra_headers, + ) + except Exception as e: + verbose_logger.exception( + f"Error getting tools from {server.name}: {e}" + ) + return { + "tools": [], + "error": "server_error", + "message": f"Failed to get tools from server {server.name}: {str(e)}", + } + return { + "tools": list_tools_result, + "error": None, + "message": "Successfully retrieved tools", + } + @router.get("/tools/list", dependencies=[Depends(user_api_key_auth)]) async def list_tool_rest_api( request: Request, @@ -283,10 +597,11 @@ if MCP_AVAILABLE: ) allowed_server_ids_set.update(servers) - allowed_server_ids, _ip_blocked_count = ( - global_mcp_server_manager.filter_server_ids_by_ip_with_info( - list(allowed_server_ids_set), _rest_client_ip - ) + ( + allowed_server_ids, + _ip_blocked_count, + ) = global_mcp_server_manager.filter_server_ids_by_ip_with_info( + list(allowed_server_ids_set), _rest_client_ip ) list_tools_result = [] @@ -294,62 +609,15 @@ if MCP_AVAILABLE: # If server_id is specified, only query that specific server if server_id: - if server_id not in allowed_server_ids: - _server = global_mcp_server_manager.get_mcp_server_by_id(server_id) - if ( - _server is not None - and _rest_client_ip is not None - and not global_mcp_server_manager._is_server_accessible_from_ip( - _server, _rest_client_ip - ) - ): - raise HTTPException( - status_code=403, - detail={ - "error": "ip_filtering", - "message": ( - f"MCP server '{server_id}' is not accessible from your IP address " - f"({_rest_client_ip}). This server is restricted to internal " - "networks only. To make it externally accessible, set " - "'available_on_public_internet: true' in the server configuration." - ), - }, - ) - raise HTTPException( - status_code=403, - detail={ - "error": "access_denied", - "message": f"The key is not allowed to access server {server_id}", - }, - ) - server = global_mcp_server_manager.get_mcp_server_by_id(server_id) - if server is None: - return { - "tools": [], - "error": "server_not_found", - "message": f"Server with id {server_id} not found", - } - - server_auth_header = _get_server_auth_header( - server, mcp_server_auth_headers, mcp_auth_header + return await _list_tools_for_single_server( + server_id=server_id, + allowed_server_ids=allowed_server_ids, + rest_client_ip=_rest_client_ip, + mcp_server_auth_headers=mcp_server_auth_headers, + mcp_auth_header=mcp_auth_header, + raw_headers_from_request=raw_headers_from_request, + user_api_key_dict=user_api_key_dict, ) - - try: - list_tools_result = await _get_tools_for_single_server( - server, - server_auth_header, - raw_headers_from_request, - user_api_key_dict, - ) - except Exception as e: - verbose_logger.exception( - f"Error getting tools from {server.name}: {e}" - ) - return { - "tools": [], - "error": "server_error", - "message": f"Failed to get tools from server {server.name}: {str(e)}", - } else: if not allowed_server_ids: if _ip_blocked_count > 0: @@ -373,6 +641,14 @@ if MCP_AVAILABLE: }, ) + # Pre-fetch OAuth credentials only when at least one allowed server uses OAuth2, + # to avoid an unnecessary DB round-trip on requests with no OAuth2 MCP servers. + prefetched_oauth_creds = ( + await _prefetch_user_oauth_creds(user_api_key_dict) + if _get_oauth2_server_ids(allowed_server_ids) + else {} + ) + # Query all servers the user has access to errors = [] for allowed_server_id in allowed_server_ids: @@ -385,6 +661,11 @@ if MCP_AVAILABLE: server_auth_header = _get_server_auth_header( server, mcp_server_auth_headers, mcp_auth_header ) + user_oauth_extra_headers = await _get_user_oauth_extra_headers( + server, + user_api_key_dict, + prefetched_creds=prefetched_oauth_creds, + ) try: tools_result = await _get_tools_for_single_server( @@ -392,6 +673,7 @@ if MCP_AVAILABLE: server_auth_header, raw_headers_from_request, user_api_key_dict, + extra_headers=user_oauth_extra_headers, ) list_tools_result.extend(tools_result) except Exception as e: @@ -474,21 +756,24 @@ if MCP_AVAILABLE: tool_arguments = data.get("arguments") 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, - ) + ( + 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, ) # 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) - ) + ( + mcp_auth_header, + mcp_server_auth_headers, + raw_headers_from_request, + ) = _extract_mcp_headers_from_request(request, MCPRequestHandler) if mcp_auth_header: data["mcp_auth_header"] = mcp_auth_header if mcp_server_auth_headers: @@ -505,6 +790,16 @@ if MCP_AVAILABLE: request, user_api_key_dict, server_id ) + # Look up per-user OAuth headers for this server (mirrors list_tool_rest_api). + user_oauth_extra_headers: Optional[Dict[str, str]] = None + target_server = next( + (s for s in allowed_mcp_servers if s.server_id == server_id), None + ) + if target_server is not None: + user_oauth_extra_headers = await _get_user_oauth_extra_headers( + target_server, user_api_key_dict + ) + # Call execute_mcp_tool directly (permission checks already done) result = await execute_mcp_tool( name=tool_name, @@ -514,7 +809,7 @@ if MCP_AVAILABLE: user_api_key_auth=data.get("user_api_key_auth"), mcp_auth_header=data.get("mcp_auth_header"), mcp_server_auth_headers=data.get("mcp_server_auth_headers"), - oauth2_headers=data.get("oauth2_headers"), + oauth2_headers=user_oauth_extra_headers or data.get("oauth2_headers"), raw_headers=data.get("raw_headers"), litellm_logging_obj=data.get("litellm_logging_obj"), ) @@ -577,7 +872,9 @@ if MCP_AVAILABLE: client_id: Optional[str] = creds.get("client_id") client_secret: Optional[str] = creds.get("client_secret") scopes_raw = creds.get("scopes") - scopes: Optional[List[str]] = scopes_raw if isinstance(scopes_raw, list) else None + scopes: Optional[List[str]] = ( + scopes_raw if isinstance(scopes_raw, list) else None + ) return client_id, client_secret, scopes async def _execute_with_mcp_client( @@ -608,6 +905,12 @@ if MCP_AVAILABLE: try: client_id, client_secret, scopes = _extract_credentials(request) + _oauth2_flow: Optional[Literal["client_credentials", "authorization_code"]] = ( + "client_credentials" + if client_id and client_secret and request.token_url + else None + ) + server_model = MCPServer( server_id=request.server_id or "", name=request.alias or request.server_name or "", @@ -625,6 +928,7 @@ if MCP_AVAILABLE: scopes=scopes, authorization_url=request.authorization_url, registration_url=request.registration_url, + oauth2_flow=_oauth2_flow, ) stdio_env = global_mcp_server_manager._build_stdio_env( @@ -680,7 +984,9 @@ if MCP_AVAILABLE: if operation is None: continue - resolved_op = resolve_operation_params(operation, path_item, components) + resolved_op = resolve_operation_params( + operation, path_item, components + ) op_id = operation.get("operationId", f"{method}_{path}") summary = operation.get("summary", "") @@ -689,7 +995,9 @@ if MCP_AVAILABLE: tools.append( { "name": op_id, - "description": description or summary or f"{method.upper()} {path}", + "description": description + or summary + or f"{method.upper()} {path}", "inputSchema": input_schema, } ) diff --git a/litellm/proxy/_experimental/mcp_server/semantic_tool_filter.py b/litellm/proxy/_experimental/mcp_server/semantic_tool_filter.py index e5cb6a0098d..0bafd7da265 100644 --- a/litellm/proxy/_experimental/mcp_server/semantic_tool_filter.py +++ b/litellm/proxy/_experimental/mcp_server/semantic_tool_filter.py @@ -60,10 +60,14 @@ class SemanticMCPToolFilter: all_tools = [] for server_id, server in registry.items(): try: - tools = await global_mcp_server_manager.get_tools_for_server(server_id) + 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}") + verbose_logger.warning( + f"Failed to fetch tools from server {server_id}: {e}" + ) continue if not all_tools: @@ -71,7 +75,9 @@ class SemanticMCPToolFilter: self.tool_router = None return - verbose_logger.info(f"Fetched {len(all_tools)} tools from {len(registry)} MCP servers") + verbose_logger.info( + f"Fetched {len(all_tools)} tools from {len(registry)} MCP servers" + ) self._build_router(all_tools) except Exception as e: @@ -83,7 +89,7 @@ class SemanticMCPToolFilter: """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", "") @@ -92,7 +98,7 @@ class SemanticMCPToolFilter: # 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: @@ -136,9 +142,7 @@ class SemanticMCPToolFilter: auto_sync="local", ) - verbose_logger.info( - f"Built semantic router with {len(routes)} tools" - ) + 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}") @@ -165,16 +169,18 @@ class SemanticMCPToolFilter: # 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?") + verbose_logger.warning( + "Router not initialized - was build_router_from_mcp_registry() called on startup?" + ) return available_tools # Run semantic filtering @@ -182,10 +188,10 @@ class SemanticMCPToolFilter: 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: @@ -196,15 +202,15 @@ class SemanticMCPToolFilter: """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( @@ -217,7 +223,7 @@ class SemanticMCPToolFilter: 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] diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.py index 99f6a5234a1..cd06de2a2df 100644 --- a/litellm/proxy/_experimental/mcp_server/server.py +++ b/litellm/proxy/_experimental/mcp_server/server.py @@ -81,6 +81,7 @@ def _write_byok_cred_cache( _byok_cred_cache.clear() _byok_cred_cache[(user_id, server_id)] = (credential, time.monotonic()) + # Check if MCP is available # "mcp" requires python 3.10 or higher, but several litellm users use python 3.8 # We're making this conditional import to avoid breaking users who use python 3.8. @@ -182,7 +183,7 @@ if MCP_AVAILABLE: session_manager = StreamableHTTPSessionManager( app=server, event_store=None, - json_response=False, # enables SSE streaming + json_response=False, # enables SSE streaming stateless=True, ) @@ -341,9 +342,9 @@ if MCP_AVAILABLE: host_progress_callback = None try: host_ctx = server.request_context - if host_ctx and hasattr(host_ctx, 'meta') and host_ctx.meta: - host_token = getattr(host_ctx.meta, 'progressToken', None) - if host_token and hasattr(host_ctx, 'session') and host_ctx.session: + if host_ctx and hasattr(host_ctx, "meta") and host_ctx.meta: + 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): @@ -352,14 +353,20 @@ if MCP_AVAILABLE: await host_session.send_progress_notification( progress_token=host_token, progress=progress, - total=total + total=total, + ) + verbose_logger.debug( + f"Forwarded progress {progress}/{total} to Host" ) - 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}") + 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]}...") + verbose_logger.debug( + f"Host progressToken captured: {host_token[:8]}..." + ) except Exception as e: verbose_logger.warning(f"Could not capture host progress context: {e}") try: @@ -711,6 +718,7 @@ if MCP_AVAILABLE: Checks both the full tool name and unprefixed version (without server prefix). This allows users to configure simple tool names regardless of prefixing. + Comparison is case-insensitive to handle OpenAPI operationIds that may be in camelCase. Args: tool_name: The tool name to check (may be prefixed like "server-tool_name") @@ -723,13 +731,15 @@ if MCP_AVAILABLE: split_server_prefix_from_name, ) - # Check if the full name is in the list - if tool_name in filter_list: + # Normalize filter list to lowercase for case-insensitive comparison + filter_list_lower = [f.lower() for f in filter_list] + + if tool_name.lower() in filter_list_lower: return True - # Check if the unprefixed name is in the list + # Check if the unprefixed name is in the list (case-insensitive) unprefixed_name, _ = split_server_prefix_from_name(tool_name) - return unprefixed_name in filter_list + return unprefixed_name.lower() in filter_list_lower def filter_tools_by_allowed_tools( tools: List[MCPTool], @@ -831,18 +841,18 @@ if MCP_AVAILABLE: ) 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, _ip_blocked = ( - global_mcp_server_manager.filter_server_ids_by_ip_with_info( - allowed_mcp_server_ids, client_ip - ) + ( + allowed_mcp_server_ids, + _ip_blocked, + ) = global_mcp_server_manager.filter_server_ids_by_ip_with_info( + 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, + client_ip, + allowed_mcp_server_ids, ) if _ip_blocked > 0: verbose_logger.debug( @@ -867,10 +877,91 @@ if MCP_AVAILABLE: mcp_servers=mcp_servers, allowed_mcp_servers=allowed_mcp_servers, ) - return allowed_mcp_servers + async def _get_user_oauth_extra_headers_from_db( + server: MCPServer, + user_api_key_auth: Optional[UserAPIKeyAuth], + prefetched_creds: Optional[Dict[str, Dict[str, Any]]] = None, + ) -> Optional[Dict[str, str]]: + """Look up stored OAuth2 token for (user, server) from DB and return as extra_headers dict. + + Args: + prefetched_creds: Optional dict keyed by server_id with credential payloads. + When provided, avoids a per-server DB round-trip. + """ + if server.auth_type != MCPAuth.oauth2: + return None + if user_api_key_auth is None: + return None + user_id = getattr(user_api_key_auth, "user_id", None) + server_id = getattr(server, "server_id", None) + if not user_id or not server_id: + return None + try: + from litellm.proxy._experimental.mcp_server.db import ( # noqa: PLC0415 + get_user_oauth_credential, + is_oauth_credential_expired, + ) + + if prefetched_creds is not None: + cred = prefetched_creds.get(server_id) + else: + from litellm.proxy.utils import ( # noqa: PLC0415 + get_prisma_client_or_throw, + ) + + prisma_client = get_prisma_client_or_throw( + "Database not connected. Connect a database to use OAuth2 MCP tools." + ) + cred = await get_user_oauth_credential( + prisma_client, user_id, server_id + ) + if cred and cred.get("access_token"): + if is_oauth_credential_expired(cred): + verbose_logger.debug( + f"_get_user_oauth_extra_headers_from_db: token expired for " + f"user={user_id} server={server_id}" + ) + return None + return {"Authorization": f"Bearer {cred['access_token']}"} + except Exception as e: + verbose_logger.warning( + f"_get_user_oauth_extra_headers_from_db: failed to retrieve credential for " + f"user={user_id} server={server_id}: {e}" + ) + return None + + async def _prefetch_oauth_creds_for_user( + user_api_key_auth: Optional[UserAPIKeyAuth], + ) -> Dict[str, Dict[str, Any]]: + """Fetch all OAuth2 credentials for the user in one DB query. + + Returns a dict keyed by server_id to avoid N+1 queries in asyncio.gather loops. + """ + user_id = ( + getattr(user_api_key_auth, "user_id", None) if user_api_key_auth else None + ) + if not user_id: + return {} + try: + from litellm.proxy._experimental.mcp_server.db import ( # noqa: PLC0415 + list_user_oauth_credentials, + ) + from litellm.proxy.utils import get_prisma_client_or_throw # noqa: PLC0415 + + prisma_client = get_prisma_client_or_throw( + "Database not connected. Connect a database to use OAuth2 MCP tools." + ) + creds = await list_user_oauth_credentials(prisma_client, user_id) + return {c["server_id"]: c for c in creds if "server_id" in c} + except Exception as e: + verbose_logger.warning( + f"_prefetch_oauth_creds_for_user: failed to prefetch for user={user_id}: {e}" + ) + return {} + def _prepare_mcp_server_headers( server: MCPServer, mcp_server_auth_headers: Optional[Dict[str, Dict[str, str]]], @@ -980,7 +1071,6 @@ if MCP_AVAILABLE: # Attach user identifiers using the standard helper if user_api_key_auth is not None: - LiteLLMProxyRequestSetup.add_user_api_key_auth_to_request_metadata( data=list_tools_request_data, user_api_key_dict=user_api_key_auth, @@ -1015,6 +1105,18 @@ if MCP_AVAILABLE: mcp_servers=mcp_servers, ) + # Pre-fetch OAuth credentials only when at least one server uses OAuth2, + # to avoid an unnecessary DB round-trip on requests with no OAuth2 MCP servers. + _has_oauth2_server = any( + getattr(s, "auth_type", None) == MCPAuth.oauth2 + for s in allowed_mcp_servers + ) + _prefetched_oauth_creds = ( + await _prefetch_oauth_creds_for_user(user_api_key_auth) + if _has_oauth2_server + else {} + ) + async def _fetch_and_filter_server_tools( server: MCPServer, ) -> List[MCPTool]: @@ -1030,6 +1132,14 @@ if MCP_AVAILABLE: raw_headers=raw_headers, ) + # If no OAuth2 token came from request headers, fall back to pre-fetched creds + if extra_headers is None and server.auth_type == MCPAuth.oauth2: + extra_headers = await _get_user_oauth_extra_headers_from_db( + server, + user_api_key_auth, + prefetched_creds=_prefetched_oauth_creds, + ) + try: tools = await global_mcp_server_manager._get_tools_from_server( server=server, @@ -1157,7 +1267,6 @@ if MCP_AVAILABLE: mcp_servers=mcp_servers, ) - # Get prompts from each allowed server all_prompts = [] for server in allowed_mcp_servers: @@ -1216,7 +1325,6 @@ if MCP_AVAILABLE: mcp_servers=mcp_servers, ) - all_resources: List[Resource] = [] for server in allowed_mcp_servers: if server is None: @@ -1272,7 +1380,6 @@ if MCP_AVAILABLE: mcp_servers=mcp_servers, ) - all_resource_templates: List[ResourceTemplate] = [] for server in allowed_mcp_servers: if server is None: @@ -1770,7 +1877,9 @@ if MCP_AVAILABLE: # configured auth_type so the generator doesn't need to know the prefix. auth_header_value: Optional[str] = None if mcp_auth_header: - server_auth_type = getattr(mcp_server, "auth_type", None) if mcp_server else None + server_auth_type = ( + getattr(mcp_server, "auth_type", None) if mcp_server else None + ) if server_auth_type == MCPAuth.api_key: auth_header_value = f"ApiKey {mcp_auth_header}" elif server_auth_type == MCPAuth.basic: @@ -1806,12 +1915,8 @@ if MCP_AVAILABLE: # Deprecated: Local MCP Server Tool ######################################################### else: - local_content = await _handle_local_mcp_tool( - original_tool_name, arguments - ) - response = CallToolResult( - content=cast(Any, local_content), isError=False - ) + local_content = await _handle_local_mcp_tool(original_tool_name, arguments) + response = CallToolResult(content=cast(Any, local_content), isError=False) return response @@ -1932,7 +2037,6 @@ if MCP_AVAILABLE: detail="User not allowed to get this prompt.", ) - # Extract server name from prefixed prompt name original_prompt_name, server_name = split_server_prefix_from_name(name) diff --git a/litellm/proxy/_experimental/out/404/index.html b/litellm/proxy/_experimental/out/404.html similarity index 96% rename from litellm/proxy/_experimental/out/404/index.html rename to litellm/proxy/_experimental/out/404.html index 583173ce407..9ae6eece580 100644 --- a/litellm/proxy/_experimental/out/404/index.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.__PAGE__.txt b/litellm/proxy/_experimental/out/__next.__PAGE__.txt index eea5a9b8f3c..9953e63348a 100644 --- a/litellm/proxy/_experimental/out/__next.__PAGE__.txt +++ b/litellm/proxy/_experimental/out/__next.__PAGE__.txt @@ -1,30 +1,27 @@ 1:"$Sreact.fragment" 2:I[347257,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"ClientPageRoot"] -3:I[952683,["/litellm-asset-prefix/_next/static/chunks/a7f104aa2cc7f3f0.js","/litellm-asset-prefix/_next/static/chunks/e8ed72789c2b42ff.js","/litellm-asset-prefix/_next/static/chunks/bb64f18ed439db51.js","/litellm-asset-prefix/_next/static/chunks/9de031ba49f226b2.js","/litellm-asset-prefix/_next/static/chunks/30539b80ac15aad2.js","/litellm-asset-prefix/_next/static/chunks/142704439974f6b3.js","/litellm-asset-prefix/_next/static/chunks/f0a13680e53afb88.js","/litellm-asset-prefix/_next/static/chunks/1fe0596a309ad6cf.js","/litellm-asset-prefix/_next/static/chunks/5f9c3b92a016f382.js","/litellm-asset-prefix/_next/static/chunks/403c4d96324c23a6.js","/litellm-asset-prefix/_next/static/chunks/edc62b8625528255.js","/litellm-asset-prefix/_next/static/chunks/e34ebe113303fbb2.js","/litellm-asset-prefix/_next/static/chunks/2d471965761a22ff.js","/litellm-asset-prefix/_next/static/chunks/e8718f949e42598e.js","/litellm-asset-prefix/_next/static/chunks/3b30ab8eaa03bc21.js","/litellm-asset-prefix/_next/static/chunks/0bd654557fbb50e9.js","/litellm-asset-prefix/_next/static/chunks/124fefccff39e221.js","/litellm-asset-prefix/_next/static/chunks/bb0a6e4a3a18721a.js","/litellm-asset-prefix/_next/static/chunks/d0d828f9a0668699.js","/litellm-asset-prefix/_next/static/chunks/4d3d997560b322ca.js","/litellm-asset-prefix/_next/static/chunks/4e4d0f466b5c1780.js","/litellm-asset-prefix/_next/static/chunks/88c74f8b4b20d25a.js","/litellm-asset-prefix/_next/static/chunks/821f45f615724874.js","/litellm-asset-prefix/_next/static/chunks/2971c4658f1bcd7d.js","/litellm-asset-prefix/_next/static/chunks/134f728fa7099e3e.js","/litellm-asset-prefix/_next/static/chunks/9b539d4d807cee27.js","/litellm-asset-prefix/_next/static/chunks/fc83f709354547bd.js","/litellm-asset-prefix/_next/static/chunks/853e5f250e7a0af5.js","/litellm-asset-prefix/_next/static/chunks/348b31083769a7c4.js","/litellm-asset-prefix/_next/static/chunks/37c03dc421ba81f8.js","/litellm-asset-prefix/_next/static/chunks/c81bdad246412686.js","/litellm-asset-prefix/_next/static/chunks/496b84010c33cf69.js","/litellm-asset-prefix/_next/static/chunks/b6cdb9a433f054f3.js","/litellm-asset-prefix/_next/static/chunks/fcdf7322b0aa3e2e.js","/litellm-asset-prefix/_next/static/chunks/6146a0436556bd42.js","/litellm-asset-prefix/_next/static/chunks/4980372eaa37b78b.js","/litellm-asset-prefix/_next/static/chunks/90f0529c4408147d.js","/litellm-asset-prefix/_next/static/chunks/a85adee4198d5478.js","/litellm-asset-prefix/_next/static/chunks/0a65da2cd24e2ab6.js","/litellm-asset-prefix/_next/static/chunks/8604d59a86c051be.js","/litellm-asset-prefix/_next/static/chunks/d3ac82723ec9e30d.js","/litellm-asset-prefix/_next/static/chunks/664bbc28119f9cc1.js","/litellm-asset-prefix/_next/static/chunks/d64d74932cb225a3.js","/litellm-asset-prefix/_next/static/chunks/0adb91ab5f3140d5.js","/litellm-asset-prefix/_next/static/chunks/5c6d02376dbf0f55.js","/litellm-asset-prefix/_next/static/chunks/85238af541b170ca.js","/litellm-asset-prefix/_next/static/chunks/06ebe9b0e9cdf241.js","/litellm-asset-prefix/_next/static/chunks/6c4c97f1ea6e7d77.js","/litellm-asset-prefix/_next/static/chunks/9d6e5aad99b19216.js","/litellm-asset-prefix/_next/static/chunks/99cf9cf99df5ccfc.js","/litellm-asset-prefix/_next/static/chunks/fba776c260ae166c.js","/litellm-asset-prefix/_next/static/chunks/b13b0ddeb85b5333.js","/litellm-asset-prefix/_next/static/chunks/54e29148cb2f2582.js","/litellm-asset-prefix/_next/static/chunks/7e417dd24c8becd0.js","/litellm-asset-prefix/_next/static/chunks/09058c1c88c095d7.js"],"default"] -1a:I[897367,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"OutletBoundary"] -1b:"$Sreact.suspense" +3:I[952683,["/litellm-asset-prefix/_next/static/chunks/a7f104aa2cc7f3f0.js","/litellm-asset-prefix/_next/static/chunks/e8ed72789c2b42ff.js","/litellm-asset-prefix/_next/static/chunks/e627c7aa5ead52b3.js","/litellm-asset-prefix/_next/static/chunks/142704439974f6b3.js","/litellm-asset-prefix/_next/static/chunks/30539b80ac15aad2.js","/litellm-asset-prefix/_next/static/chunks/7d82a1cebfdb679c.js","/litellm-asset-prefix/_next/static/chunks/2d471965761a22ff.js","/litellm-asset-prefix/_next/static/chunks/1fe0596a309ad6cf.js","/litellm-asset-prefix/_next/static/chunks/7b788dd93ad868b3.js","/litellm-asset-prefix/_next/static/chunks/c847ecdf8c790b0b.js","/litellm-asset-prefix/_next/static/chunks/403c4d96324c23a6.js","/litellm-asset-prefix/_next/static/chunks/88c74f8b4b20d25a.js","/litellm-asset-prefix/_next/static/chunks/d64d74932cb225a3.js","/litellm-asset-prefix/_next/static/chunks/8c13023d89b01566.js","/litellm-asset-prefix/_next/static/chunks/3b30ab8eaa03bc21.js","/litellm-asset-prefix/_next/static/chunks/74ce31aa0fb2adc9.js","/litellm-asset-prefix/_next/static/chunks/cdf98a03da656604.js","/litellm-asset-prefix/_next/static/chunks/cac89fc12fb6ef7e.js","/litellm-asset-prefix/_next/static/chunks/d0d828f9a0668699.js","/litellm-asset-prefix/_next/static/chunks/1a04d31843c96649.js","/litellm-asset-prefix/_next/static/chunks/ed90bf177ad61e18.js","/litellm-asset-prefix/_next/static/chunks/2971c4658f1bcd7d.js","/litellm-asset-prefix/_next/static/chunks/6c4c97f1ea6e7d77.js","/litellm-asset-prefix/_next/static/chunks/9d6e5aad99b19216.js","/litellm-asset-prefix/_next/static/chunks/134f728fa7099e3e.js","/litellm-asset-prefix/_next/static/chunks/acbeac1b0fde1fdf.js","/litellm-asset-prefix/_next/static/chunks/fa6fc6b79591df63.js","/litellm-asset-prefix/_next/static/chunks/7e417dd24c8becd0.js","/litellm-asset-prefix/_next/static/chunks/348b31083769a7c4.js","/litellm-asset-prefix/_next/static/chunks/a85adee4198d5478.js","/litellm-asset-prefix/_next/static/chunks/c8eee6971ca36303.js","/litellm-asset-prefix/_next/static/chunks/0adb91ab5f3140d5.js","/litellm-asset-prefix/_next/static/chunks/b6cdb9a433f054f3.js","/litellm-asset-prefix/_next/static/chunks/22970a12064ba16b.js","/litellm-asset-prefix/_next/static/chunks/aae16a3ce4812424.js","/litellm-asset-prefix/_next/static/chunks/4980372eaa37b78b.js","/litellm-asset-prefix/_next/static/chunks/d069df5baead6d90.js","/litellm-asset-prefix/_next/static/chunks/69365f493e1655a4.js","/litellm-asset-prefix/_next/static/chunks/0a65da2cd24e2ab6.js","/litellm-asset-prefix/_next/static/chunks/fc4d54eb6afe7984.js","/litellm-asset-prefix/_next/static/chunks/e99f98e7f34532c9.js","/litellm-asset-prefix/_next/static/chunks/496b84010c33cf69.js","/litellm-asset-prefix/_next/static/chunks/06ebe9b0e9cdf241.js","/litellm-asset-prefix/_next/static/chunks/df6546cd8a44d3b3.js","/litellm-asset-prefix/_next/static/chunks/d3ac82723ec9e30d.js","/litellm-asset-prefix/_next/static/chunks/99cf9cf99df5ccfc.js","/litellm-asset-prefix/_next/static/chunks/07fd9d7c5c879cb6.js","/litellm-asset-prefix/_next/static/chunks/8dda507c226082ca.js","/litellm-asset-prefix/_next/static/chunks/54e29148cb2f2582.js","/litellm-asset-prefix/_next/static/chunks/3675074b1d85e268.js","/litellm-asset-prefix/_next/static/chunks/fcdf7322b0aa3e2e.js","/litellm-asset-prefix/_next/static/chunks/bd94e2fe34d8a187.js"],"default"] +17:I[897367,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"OutletBoundary"] +18:"$Sreact.suspense" :HL["/litellm-asset-prefix/_next/static/chunks/3f3fa56b5786d58c.css","style"] -0:{"buildId":"WhBGJTAPhDM3j-59ST728","rsc":["$","$1","c",{"children":[["$","$L2",null,{"Component":"$3","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@4","$@5"]}}],[["$","link","0",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/3f3fa56b5786d58c.css","precedence":"next"}],["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/bb64f18ed439db51.js","async":true}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/9de031ba49f226b2.js","async":true}],["$","script","script-2",{"src":"/litellm-asset-prefix/_next/static/chunks/30539b80ac15aad2.js","async":true}],["$","script","script-3",{"src":"/litellm-asset-prefix/_next/static/chunks/142704439974f6b3.js","async":true}],["$","script","script-4",{"src":"/litellm-asset-prefix/_next/static/chunks/f0a13680e53afb88.js","async":true}],["$","script","script-5",{"src":"/litellm-asset-prefix/_next/static/chunks/1fe0596a309ad6cf.js","async":true}],["$","script","script-6",{"src":"/litellm-asset-prefix/_next/static/chunks/5f9c3b92a016f382.js","async":true}],["$","script","script-7",{"src":"/litellm-asset-prefix/_next/static/chunks/403c4d96324c23a6.js","async":true}],["$","script","script-8",{"src":"/litellm-asset-prefix/_next/static/chunks/edc62b8625528255.js","async":true}],["$","script","script-9",{"src":"/litellm-asset-prefix/_next/static/chunks/e34ebe113303fbb2.js","async":true}],["$","script","script-10",{"src":"/litellm-asset-prefix/_next/static/chunks/2d471965761a22ff.js","async":true}],["$","script","script-11",{"src":"/litellm-asset-prefix/_next/static/chunks/e8718f949e42598e.js","async":true}],["$","script","script-12",{"src":"/litellm-asset-prefix/_next/static/chunks/3b30ab8eaa03bc21.js","async":true}],["$","script","script-13",{"src":"/litellm-asset-prefix/_next/static/chunks/0bd654557fbb50e9.js","async":true}],["$","script","script-14",{"src":"/litellm-asset-prefix/_next/static/chunks/124fefccff39e221.js","async":true}],["$","script","script-15",{"src":"/litellm-asset-prefix/_next/static/chunks/bb0a6e4a3a18721a.js","async":true}],["$","script","script-16",{"src":"/litellm-asset-prefix/_next/static/chunks/d0d828f9a0668699.js","async":true}],["$","script","script-17",{"src":"/litellm-asset-prefix/_next/static/chunks/4d3d997560b322ca.js","async":true}],["$","script","script-18",{"src":"/litellm-asset-prefix/_next/static/chunks/4e4d0f466b5c1780.js","async":true}],["$","script","script-19",{"src":"/litellm-asset-prefix/_next/static/chunks/88c74f8b4b20d25a.js","async":true}],["$","script","script-20",{"src":"/litellm-asset-prefix/_next/static/chunks/821f45f615724874.js","async":true}],["$","script","script-21",{"src":"/litellm-asset-prefix/_next/static/chunks/2971c4658f1bcd7d.js","async":true}],["$","script","script-22",{"src":"/litellm-asset-prefix/_next/static/chunks/134f728fa7099e3e.js","async":true}],["$","script","script-23",{"src":"/litellm-asset-prefix/_next/static/chunks/9b539d4d807cee27.js","async":true}],["$","script","script-24",{"src":"/litellm-asset-prefix/_next/static/chunks/fc83f709354547bd.js","async":true}],["$","script","script-25",{"src":"/litellm-asset-prefix/_next/static/chunks/853e5f250e7a0af5.js","async":true}],["$","script","script-26",{"src":"/litellm-asset-prefix/_next/static/chunks/348b31083769a7c4.js","async":true}],["$","script","script-27",{"src":"/litellm-asset-prefix/_next/static/chunks/37c03dc421ba81f8.js","async":true}],["$","script","script-28",{"src":"/litellm-asset-prefix/_next/static/chunks/c81bdad246412686.js","async":true}],["$","script","script-29",{"src":"/litellm-asset-prefix/_next/static/chunks/496b84010c33cf69.js","async":true}],["$","script","script-30",{"src":"/litellm-asset-prefix/_next/static/chunks/b6cdb9a433f054f3.js","async":true}],["$","script","script-31",{"src":"/litellm-asset-prefix/_next/static/chunks/fcdf7322b0aa3e2e.js","async":true}],["$","script","script-32",{"src":"/litellm-asset-prefix/_next/static/chunks/6146a0436556bd42.js","async":true}],["$","script","script-33",{"src":"/litellm-asset-prefix/_next/static/chunks/4980372eaa37b78b.js","async":true}],"$L6","$L7","$L8","$L9","$La","$Lb","$Lc","$Ld","$Le","$Lf","$L10","$L11","$L12","$L13","$L14","$L15","$L16","$L17","$L18"],"$L19"]}],"loading":null,"isPartial":false} +0:{"buildId":"Kalni9LnFJDBB7xvqCPNe","rsc":["$","$1","c",{"children":[["$","$L2",null,{"Component":"$3","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@4","$@5"]}}],[["$","link","0",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/3f3fa56b5786d58c.css","precedence":"next"}],["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/e627c7aa5ead52b3.js","async":true}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/142704439974f6b3.js","async":true}],["$","script","script-2",{"src":"/litellm-asset-prefix/_next/static/chunks/30539b80ac15aad2.js","async":true}],["$","script","script-3",{"src":"/litellm-asset-prefix/_next/static/chunks/7d82a1cebfdb679c.js","async":true}],["$","script","script-4",{"src":"/litellm-asset-prefix/_next/static/chunks/2d471965761a22ff.js","async":true}],["$","script","script-5",{"src":"/litellm-asset-prefix/_next/static/chunks/1fe0596a309ad6cf.js","async":true}],["$","script","script-6",{"src":"/litellm-asset-prefix/_next/static/chunks/7b788dd93ad868b3.js","async":true}],["$","script","script-7",{"src":"/litellm-asset-prefix/_next/static/chunks/c847ecdf8c790b0b.js","async":true}],["$","script","script-8",{"src":"/litellm-asset-prefix/_next/static/chunks/403c4d96324c23a6.js","async":true}],["$","script","script-9",{"src":"/litellm-asset-prefix/_next/static/chunks/88c74f8b4b20d25a.js","async":true}],["$","script","script-10",{"src":"/litellm-asset-prefix/_next/static/chunks/d64d74932cb225a3.js","async":true}],["$","script","script-11",{"src":"/litellm-asset-prefix/_next/static/chunks/8c13023d89b01566.js","async":true}],["$","script","script-12",{"src":"/litellm-asset-prefix/_next/static/chunks/3b30ab8eaa03bc21.js","async":true}],["$","script","script-13",{"src":"/litellm-asset-prefix/_next/static/chunks/74ce31aa0fb2adc9.js","async":true}],["$","script","script-14",{"src":"/litellm-asset-prefix/_next/static/chunks/cdf98a03da656604.js","async":true}],["$","script","script-15",{"src":"/litellm-asset-prefix/_next/static/chunks/cac89fc12fb6ef7e.js","async":true}],["$","script","script-16",{"src":"/litellm-asset-prefix/_next/static/chunks/d0d828f9a0668699.js","async":true}],["$","script","script-17",{"src":"/litellm-asset-prefix/_next/static/chunks/1a04d31843c96649.js","async":true}],["$","script","script-18",{"src":"/litellm-asset-prefix/_next/static/chunks/ed90bf177ad61e18.js","async":true}],["$","script","script-19",{"src":"/litellm-asset-prefix/_next/static/chunks/2971c4658f1bcd7d.js","async":true}],["$","script","script-20",{"src":"/litellm-asset-prefix/_next/static/chunks/6c4c97f1ea6e7d77.js","async":true}],["$","script","script-21",{"src":"/litellm-asset-prefix/_next/static/chunks/9d6e5aad99b19216.js","async":true}],["$","script","script-22",{"src":"/litellm-asset-prefix/_next/static/chunks/134f728fa7099e3e.js","async":true}],["$","script","script-23",{"src":"/litellm-asset-prefix/_next/static/chunks/acbeac1b0fde1fdf.js","async":true}],["$","script","script-24",{"src":"/litellm-asset-prefix/_next/static/chunks/fa6fc6b79591df63.js","async":true}],["$","script","script-25",{"src":"/litellm-asset-prefix/_next/static/chunks/7e417dd24c8becd0.js","async":true}],["$","script","script-26",{"src":"/litellm-asset-prefix/_next/static/chunks/348b31083769a7c4.js","async":true}],["$","script","script-27",{"src":"/litellm-asset-prefix/_next/static/chunks/a85adee4198d5478.js","async":true}],["$","script","script-28",{"src":"/litellm-asset-prefix/_next/static/chunks/c8eee6971ca36303.js","async":true}],["$","script","script-29",{"src":"/litellm-asset-prefix/_next/static/chunks/0adb91ab5f3140d5.js","async":true}],["$","script","script-30",{"src":"/litellm-asset-prefix/_next/static/chunks/b6cdb9a433f054f3.js","async":true}],["$","script","script-31",{"src":"/litellm-asset-prefix/_next/static/chunks/22970a12064ba16b.js","async":true}],["$","script","script-32",{"src":"/litellm-asset-prefix/_next/static/chunks/aae16a3ce4812424.js","async":true}],["$","script","script-33",{"src":"/litellm-asset-prefix/_next/static/chunks/4980372eaa37b78b.js","async":true}],"$L6","$L7","$L8","$L9","$La","$Lb","$Lc","$Ld","$Le","$Lf","$L10","$L11","$L12","$L13","$L14","$L15"],"$L16"]}],"loading":null,"isPartial":false} 4:{} 5:"$0:rsc:props:children:0:props:serverProvidedParams:params" -6:["$","script","script-34",{"src":"/litellm-asset-prefix/_next/static/chunks/90f0529c4408147d.js","async":true}] -7:["$","script","script-35",{"src":"/litellm-asset-prefix/_next/static/chunks/a85adee4198d5478.js","async":true}] +6:["$","script","script-34",{"src":"/litellm-asset-prefix/_next/static/chunks/d069df5baead6d90.js","async":true}] +7:["$","script","script-35",{"src":"/litellm-asset-prefix/_next/static/chunks/69365f493e1655a4.js","async":true}] 8:["$","script","script-36",{"src":"/litellm-asset-prefix/_next/static/chunks/0a65da2cd24e2ab6.js","async":true}] -9:["$","script","script-37",{"src":"/litellm-asset-prefix/_next/static/chunks/8604d59a86c051be.js","async":true}] -a:["$","script","script-38",{"src":"/litellm-asset-prefix/_next/static/chunks/d3ac82723ec9e30d.js","async":true}] -b:["$","script","script-39",{"src":"/litellm-asset-prefix/_next/static/chunks/664bbc28119f9cc1.js","async":true}] -c:["$","script","script-40",{"src":"/litellm-asset-prefix/_next/static/chunks/d64d74932cb225a3.js","async":true}] -d:["$","script","script-41",{"src":"/litellm-asset-prefix/_next/static/chunks/0adb91ab5f3140d5.js","async":true}] -e:["$","script","script-42",{"src":"/litellm-asset-prefix/_next/static/chunks/5c6d02376dbf0f55.js","async":true}] -f:["$","script","script-43",{"src":"/litellm-asset-prefix/_next/static/chunks/85238af541b170ca.js","async":true}] -10:["$","script","script-44",{"src":"/litellm-asset-prefix/_next/static/chunks/06ebe9b0e9cdf241.js","async":true}] -11:["$","script","script-45",{"src":"/litellm-asset-prefix/_next/static/chunks/6c4c97f1ea6e7d77.js","async":true}] -12:["$","script","script-46",{"src":"/litellm-asset-prefix/_next/static/chunks/9d6e5aad99b19216.js","async":true}] -13:["$","script","script-47",{"src":"/litellm-asset-prefix/_next/static/chunks/99cf9cf99df5ccfc.js","async":true}] -14:["$","script","script-48",{"src":"/litellm-asset-prefix/_next/static/chunks/fba776c260ae166c.js","async":true}] -15:["$","script","script-49",{"src":"/litellm-asset-prefix/_next/static/chunks/b13b0ddeb85b5333.js","async":true}] -16:["$","script","script-50",{"src":"/litellm-asset-prefix/_next/static/chunks/54e29148cb2f2582.js","async":true}] -17:["$","script","script-51",{"src":"/litellm-asset-prefix/_next/static/chunks/7e417dd24c8becd0.js","async":true}] -18:["$","script","script-52",{"src":"/litellm-asset-prefix/_next/static/chunks/09058c1c88c095d7.js","async":true}] -19:["$","$L1a",null,{"children":["$","$1b",null,{"name":"Next.MetadataOutlet","children":"$@1c"}]}] -1c:null +9:["$","script","script-37",{"src":"/litellm-asset-prefix/_next/static/chunks/fc4d54eb6afe7984.js","async":true}] +a:["$","script","script-38",{"src":"/litellm-asset-prefix/_next/static/chunks/e99f98e7f34532c9.js","async":true}] +b:["$","script","script-39",{"src":"/litellm-asset-prefix/_next/static/chunks/496b84010c33cf69.js","async":true}] +c:["$","script","script-40",{"src":"/litellm-asset-prefix/_next/static/chunks/06ebe9b0e9cdf241.js","async":true}] +d:["$","script","script-41",{"src":"/litellm-asset-prefix/_next/static/chunks/df6546cd8a44d3b3.js","async":true}] +e:["$","script","script-42",{"src":"/litellm-asset-prefix/_next/static/chunks/d3ac82723ec9e30d.js","async":true}] +f:["$","script","script-43",{"src":"/litellm-asset-prefix/_next/static/chunks/99cf9cf99df5ccfc.js","async":true}] +10:["$","script","script-44",{"src":"/litellm-asset-prefix/_next/static/chunks/07fd9d7c5c879cb6.js","async":true}] +11:["$","script","script-45",{"src":"/litellm-asset-prefix/_next/static/chunks/8dda507c226082ca.js","async":true}] +12:["$","script","script-46",{"src":"/litellm-asset-prefix/_next/static/chunks/54e29148cb2f2582.js","async":true}] +13:["$","script","script-47",{"src":"/litellm-asset-prefix/_next/static/chunks/3675074b1d85e268.js","async":true}] +14:["$","script","script-48",{"src":"/litellm-asset-prefix/_next/static/chunks/fcdf7322b0aa3e2e.js","async":true}] +15:["$","script","script-49",{"src":"/litellm-asset-prefix/_next/static/chunks/bd94e2fe34d8a187.js","async":true}] +16:["$","$L17",null,{"children":["$","$18",null,{"name":"Next.MetadataOutlet","children":"$@19"}]}] +19:null diff --git a/litellm/proxy/_experimental/out/__next._full.txt b/litellm/proxy/_experimental/out/__next._full.txt index 9134672e6da..62ed8a5f0b1 100644 --- a/litellm/proxy/_experimental/out/__next._full.txt +++ b/litellm/proxy/_experimental/out/__next._full.txt @@ -4,59 +4,56 @@ 4:I[339756,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"default"] 5:I[837457,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"default"] 6:I[347257,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"ClientPageRoot"] -7:I[952683,["/litellm-asset-prefix/_next/static/chunks/a7f104aa2cc7f3f0.js","/litellm-asset-prefix/_next/static/chunks/e8ed72789c2b42ff.js","/litellm-asset-prefix/_next/static/chunks/bb64f18ed439db51.js","/litellm-asset-prefix/_next/static/chunks/9de031ba49f226b2.js","/litellm-asset-prefix/_next/static/chunks/30539b80ac15aad2.js","/litellm-asset-prefix/_next/static/chunks/142704439974f6b3.js","/litellm-asset-prefix/_next/static/chunks/f0a13680e53afb88.js","/litellm-asset-prefix/_next/static/chunks/1fe0596a309ad6cf.js","/litellm-asset-prefix/_next/static/chunks/5f9c3b92a016f382.js","/litellm-asset-prefix/_next/static/chunks/403c4d96324c23a6.js","/litellm-asset-prefix/_next/static/chunks/edc62b8625528255.js","/litellm-asset-prefix/_next/static/chunks/e34ebe113303fbb2.js","/litellm-asset-prefix/_next/static/chunks/2d471965761a22ff.js","/litellm-asset-prefix/_next/static/chunks/e8718f949e42598e.js","/litellm-asset-prefix/_next/static/chunks/3b30ab8eaa03bc21.js","/litellm-asset-prefix/_next/static/chunks/0bd654557fbb50e9.js","/litellm-asset-prefix/_next/static/chunks/124fefccff39e221.js","/litellm-asset-prefix/_next/static/chunks/bb0a6e4a3a18721a.js","/litellm-asset-prefix/_next/static/chunks/d0d828f9a0668699.js","/litellm-asset-prefix/_next/static/chunks/4d3d997560b322ca.js","/litellm-asset-prefix/_next/static/chunks/4e4d0f466b5c1780.js","/litellm-asset-prefix/_next/static/chunks/88c74f8b4b20d25a.js","/litellm-asset-prefix/_next/static/chunks/821f45f615724874.js","/litellm-asset-prefix/_next/static/chunks/2971c4658f1bcd7d.js","/litellm-asset-prefix/_next/static/chunks/134f728fa7099e3e.js","/litellm-asset-prefix/_next/static/chunks/9b539d4d807cee27.js","/litellm-asset-prefix/_next/static/chunks/fc83f709354547bd.js","/litellm-asset-prefix/_next/static/chunks/853e5f250e7a0af5.js","/litellm-asset-prefix/_next/static/chunks/348b31083769a7c4.js","/litellm-asset-prefix/_next/static/chunks/37c03dc421ba81f8.js","/litellm-asset-prefix/_next/static/chunks/c81bdad246412686.js","/litellm-asset-prefix/_next/static/chunks/496b84010c33cf69.js","/litellm-asset-prefix/_next/static/chunks/b6cdb9a433f054f3.js","/litellm-asset-prefix/_next/static/chunks/fcdf7322b0aa3e2e.js","/litellm-asset-prefix/_next/static/chunks/6146a0436556bd42.js","/litellm-asset-prefix/_next/static/chunks/4980372eaa37b78b.js","/litellm-asset-prefix/_next/static/chunks/90f0529c4408147d.js","/litellm-asset-prefix/_next/static/chunks/a85adee4198d5478.js","/litellm-asset-prefix/_next/static/chunks/0a65da2cd24e2ab6.js","/litellm-asset-prefix/_next/static/chunks/8604d59a86c051be.js","/litellm-asset-prefix/_next/static/chunks/d3ac82723ec9e30d.js","/litellm-asset-prefix/_next/static/chunks/664bbc28119f9cc1.js","/litellm-asset-prefix/_next/static/chunks/d64d74932cb225a3.js","/litellm-asset-prefix/_next/static/chunks/0adb91ab5f3140d5.js","/litellm-asset-prefix/_next/static/chunks/5c6d02376dbf0f55.js","/litellm-asset-prefix/_next/static/chunks/85238af541b170ca.js","/litellm-asset-prefix/_next/static/chunks/06ebe9b0e9cdf241.js","/litellm-asset-prefix/_next/static/chunks/6c4c97f1ea6e7d77.js","/litellm-asset-prefix/_next/static/chunks/9d6e5aad99b19216.js","/litellm-asset-prefix/_next/static/chunks/99cf9cf99df5ccfc.js","/litellm-asset-prefix/_next/static/chunks/fba776c260ae166c.js","/litellm-asset-prefix/_next/static/chunks/b13b0ddeb85b5333.js","/litellm-asset-prefix/_next/static/chunks/54e29148cb2f2582.js","/litellm-asset-prefix/_next/static/chunks/7e417dd24c8becd0.js","/litellm-asset-prefix/_next/static/chunks/09058c1c88c095d7.js"],"default"] -31:I[168027,[],"default"] +7:I[952683,["/litellm-asset-prefix/_next/static/chunks/a7f104aa2cc7f3f0.js","/litellm-asset-prefix/_next/static/chunks/e8ed72789c2b42ff.js","/litellm-asset-prefix/_next/static/chunks/e627c7aa5ead52b3.js","/litellm-asset-prefix/_next/static/chunks/142704439974f6b3.js","/litellm-asset-prefix/_next/static/chunks/30539b80ac15aad2.js","/litellm-asset-prefix/_next/static/chunks/7d82a1cebfdb679c.js","/litellm-asset-prefix/_next/static/chunks/2d471965761a22ff.js","/litellm-asset-prefix/_next/static/chunks/1fe0596a309ad6cf.js","/litellm-asset-prefix/_next/static/chunks/7b788dd93ad868b3.js","/litellm-asset-prefix/_next/static/chunks/c847ecdf8c790b0b.js","/litellm-asset-prefix/_next/static/chunks/403c4d96324c23a6.js","/litellm-asset-prefix/_next/static/chunks/88c74f8b4b20d25a.js","/litellm-asset-prefix/_next/static/chunks/d64d74932cb225a3.js","/litellm-asset-prefix/_next/static/chunks/8c13023d89b01566.js","/litellm-asset-prefix/_next/static/chunks/3b30ab8eaa03bc21.js","/litellm-asset-prefix/_next/static/chunks/74ce31aa0fb2adc9.js","/litellm-asset-prefix/_next/static/chunks/cdf98a03da656604.js","/litellm-asset-prefix/_next/static/chunks/cac89fc12fb6ef7e.js","/litellm-asset-prefix/_next/static/chunks/d0d828f9a0668699.js","/litellm-asset-prefix/_next/static/chunks/1a04d31843c96649.js","/litellm-asset-prefix/_next/static/chunks/ed90bf177ad61e18.js","/litellm-asset-prefix/_next/static/chunks/2971c4658f1bcd7d.js","/litellm-asset-prefix/_next/static/chunks/6c4c97f1ea6e7d77.js","/litellm-asset-prefix/_next/static/chunks/9d6e5aad99b19216.js","/litellm-asset-prefix/_next/static/chunks/134f728fa7099e3e.js","/litellm-asset-prefix/_next/static/chunks/acbeac1b0fde1fdf.js","/litellm-asset-prefix/_next/static/chunks/fa6fc6b79591df63.js","/litellm-asset-prefix/_next/static/chunks/7e417dd24c8becd0.js","/litellm-asset-prefix/_next/static/chunks/348b31083769a7c4.js","/litellm-asset-prefix/_next/static/chunks/a85adee4198d5478.js","/litellm-asset-prefix/_next/static/chunks/c8eee6971ca36303.js","/litellm-asset-prefix/_next/static/chunks/0adb91ab5f3140d5.js","/litellm-asset-prefix/_next/static/chunks/b6cdb9a433f054f3.js","/litellm-asset-prefix/_next/static/chunks/22970a12064ba16b.js","/litellm-asset-prefix/_next/static/chunks/aae16a3ce4812424.js","/litellm-asset-prefix/_next/static/chunks/4980372eaa37b78b.js","/litellm-asset-prefix/_next/static/chunks/d069df5baead6d90.js","/litellm-asset-prefix/_next/static/chunks/69365f493e1655a4.js","/litellm-asset-prefix/_next/static/chunks/0a65da2cd24e2ab6.js","/litellm-asset-prefix/_next/static/chunks/fc4d54eb6afe7984.js","/litellm-asset-prefix/_next/static/chunks/e99f98e7f34532c9.js","/litellm-asset-prefix/_next/static/chunks/496b84010c33cf69.js","/litellm-asset-prefix/_next/static/chunks/06ebe9b0e9cdf241.js","/litellm-asset-prefix/_next/static/chunks/df6546cd8a44d3b3.js","/litellm-asset-prefix/_next/static/chunks/d3ac82723ec9e30d.js","/litellm-asset-prefix/_next/static/chunks/99cf9cf99df5ccfc.js","/litellm-asset-prefix/_next/static/chunks/07fd9d7c5c879cb6.js","/litellm-asset-prefix/_next/static/chunks/8dda507c226082ca.js","/litellm-asset-prefix/_next/static/chunks/54e29148cb2f2582.js","/litellm-asset-prefix/_next/static/chunks/3675074b1d85e268.js","/litellm-asset-prefix/_next/static/chunks/fcdf7322b0aa3e2e.js","/litellm-asset-prefix/_next/static/chunks/bd94e2fe34d8a187.js"],"default"] +2e:I[168027,[],"default"] :HL["/litellm-asset-prefix/_next/static/chunks/4e20891f2fd03463.css","style"] -:HL["/litellm-asset-prefix/_next/static/chunks/7936c9bd377ea4bf.css","style"] +:HL["/litellm-asset-prefix/_next/static/chunks/8dc3b559a2e76f88.css","style"] :HL["/litellm-asset-prefix/_next/static/media/83afe278b6a6bb3c-s.p.3a6ba036.woff2","font",{"crossOrigin":"","type":"font/woff2"}] :HL["/litellm-asset-prefix/_next/static/chunks/3f3fa56b5786d58c.css","style"] -0:{"P":null,"b":"WhBGJTAPhDM3j-59ST728","c":["",""],"q":"","i":false,"f":[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/4e20891f2fd03463.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/7936c9bd377ea4bf.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/a7f104aa2cc7f3f0.js","async":true,"nonce":"$undefined"}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/e8ed72789c2b42ff.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"inter_5972bc34-module__OU16Qa__className","children":["$","$L2",null,{"children":["$","$L3",null,{"children":["$","$L4",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]}]}]}]]}],{"children":[["$","$1","c",{"children":[["$","$L6",null,{"Component":"$7","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@8","$@9"]}}],[["$","link","0",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/3f3fa56b5786d58c.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/bb64f18ed439db51.js","async":true,"nonce":"$undefined"}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/9de031ba49f226b2.js","async":true,"nonce":"$undefined"}],["$","script","script-2",{"src":"/litellm-asset-prefix/_next/static/chunks/30539b80ac15aad2.js","async":true,"nonce":"$undefined"}],["$","script","script-3",{"src":"/litellm-asset-prefix/_next/static/chunks/142704439974f6b3.js","async":true,"nonce":"$undefined"}],["$","script","script-4",{"src":"/litellm-asset-prefix/_next/static/chunks/f0a13680e53afb88.js","async":true,"nonce":"$undefined"}],["$","script","script-5",{"src":"/litellm-asset-prefix/_next/static/chunks/1fe0596a309ad6cf.js","async":true,"nonce":"$undefined"}],["$","script","script-6",{"src":"/litellm-asset-prefix/_next/static/chunks/5f9c3b92a016f382.js","async":true,"nonce":"$undefined"}],["$","script","script-7",{"src":"/litellm-asset-prefix/_next/static/chunks/403c4d96324c23a6.js","async":true,"nonce":"$undefined"}],["$","script","script-8",{"src":"/litellm-asset-prefix/_next/static/chunks/edc62b8625528255.js","async":true,"nonce":"$undefined"}],["$","script","script-9",{"src":"/litellm-asset-prefix/_next/static/chunks/e34ebe113303fbb2.js","async":true,"nonce":"$undefined"}],["$","script","script-10",{"src":"/litellm-asset-prefix/_next/static/chunks/2d471965761a22ff.js","async":true,"nonce":"$undefined"}],["$","script","script-11",{"src":"/litellm-asset-prefix/_next/static/chunks/e8718f949e42598e.js","async":true,"nonce":"$undefined"}],["$","script","script-12",{"src":"/litellm-asset-prefix/_next/static/chunks/3b30ab8eaa03bc21.js","async":true,"nonce":"$undefined"}],["$","script","script-13",{"src":"/litellm-asset-prefix/_next/static/chunks/0bd654557fbb50e9.js","async":true,"nonce":"$undefined"}],["$","script","script-14",{"src":"/litellm-asset-prefix/_next/static/chunks/124fefccff39e221.js","async":true,"nonce":"$undefined"}],["$","script","script-15",{"src":"/litellm-asset-prefix/_next/static/chunks/bb0a6e4a3a18721a.js","async":true,"nonce":"$undefined"}],"$La","$Lb","$Lc","$Ld","$Le","$Lf","$L10","$L11","$L12","$L13","$L14","$L15","$L16","$L17","$L18","$L19","$L1a","$L1b","$L1c","$L1d","$L1e","$L1f","$L20","$L21","$L22","$L23","$L24","$L25","$L26","$L27","$L28","$L29","$L2a","$L2b","$L2c","$L2d","$L2e"],"$L2f"]}],{},null,false,false]},null,false,false],"$L30",false]],"m":"$undefined","G":["$31",[]],"S":true} -32:I[897367,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"OutletBoundary"] -33:"$Sreact.suspense" -35:I[897367,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"ViewportBoundary"] -37:I[897367,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"MetadataBoundary"] +0:{"P":null,"b":"Kalni9LnFJDBB7xvqCPNe","c":["",""],"q":"","i":false,"f":[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/4e20891f2fd03463.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/8dc3b559a2e76f88.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/a7f104aa2cc7f3f0.js","async":true,"nonce":"$undefined"}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/e8ed72789c2b42ff.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"inter_5972bc34-module__OU16Qa__className","children":["$","$L2",null,{"children":["$","$L3",null,{"children":["$","$L4",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]}]}]}]]}],{"children":[["$","$1","c",{"children":[["$","$L6",null,{"Component":"$7","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@8","$@9"]}}],[["$","link","0",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/3f3fa56b5786d58c.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/e627c7aa5ead52b3.js","async":true,"nonce":"$undefined"}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/142704439974f6b3.js","async":true,"nonce":"$undefined"}],["$","script","script-2",{"src":"/litellm-asset-prefix/_next/static/chunks/30539b80ac15aad2.js","async":true,"nonce":"$undefined"}],["$","script","script-3",{"src":"/litellm-asset-prefix/_next/static/chunks/7d82a1cebfdb679c.js","async":true,"nonce":"$undefined"}],["$","script","script-4",{"src":"/litellm-asset-prefix/_next/static/chunks/2d471965761a22ff.js","async":true,"nonce":"$undefined"}],["$","script","script-5",{"src":"/litellm-asset-prefix/_next/static/chunks/1fe0596a309ad6cf.js","async":true,"nonce":"$undefined"}],["$","script","script-6",{"src":"/litellm-asset-prefix/_next/static/chunks/7b788dd93ad868b3.js","async":true,"nonce":"$undefined"}],["$","script","script-7",{"src":"/litellm-asset-prefix/_next/static/chunks/c847ecdf8c790b0b.js","async":true,"nonce":"$undefined"}],["$","script","script-8",{"src":"/litellm-asset-prefix/_next/static/chunks/403c4d96324c23a6.js","async":true,"nonce":"$undefined"}],["$","script","script-9",{"src":"/litellm-asset-prefix/_next/static/chunks/88c74f8b4b20d25a.js","async":true,"nonce":"$undefined"}],["$","script","script-10",{"src":"/litellm-asset-prefix/_next/static/chunks/d64d74932cb225a3.js","async":true,"nonce":"$undefined"}],["$","script","script-11",{"src":"/litellm-asset-prefix/_next/static/chunks/8c13023d89b01566.js","async":true,"nonce":"$undefined"}],["$","script","script-12",{"src":"/litellm-asset-prefix/_next/static/chunks/3b30ab8eaa03bc21.js","async":true,"nonce":"$undefined"}],["$","script","script-13",{"src":"/litellm-asset-prefix/_next/static/chunks/74ce31aa0fb2adc9.js","async":true,"nonce":"$undefined"}],["$","script","script-14",{"src":"/litellm-asset-prefix/_next/static/chunks/cdf98a03da656604.js","async":true,"nonce":"$undefined"}],["$","script","script-15",{"src":"/litellm-asset-prefix/_next/static/chunks/cac89fc12fb6ef7e.js","async":true,"nonce":"$undefined"}],"$La","$Lb","$Lc","$Ld","$Le","$Lf","$L10","$L11","$L12","$L13","$L14","$L15","$L16","$L17","$L18","$L19","$L1a","$L1b","$L1c","$L1d","$L1e","$L1f","$L20","$L21","$L22","$L23","$L24","$L25","$L26","$L27","$L28","$L29","$L2a","$L2b"],"$L2c"]}],{},null,false,false]},null,false,false],"$L2d",false]],"m":"$undefined","G":["$2e",[]],"S":true} +2f:I[897367,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"OutletBoundary"] +30:"$Sreact.suspense" +32:I[897367,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"ViewportBoundary"] +34:I[897367,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"MetadataBoundary"] a:["$","script","script-16",{"src":"/litellm-asset-prefix/_next/static/chunks/d0d828f9a0668699.js","async":true,"nonce":"$undefined"}] -b:["$","script","script-17",{"src":"/litellm-asset-prefix/_next/static/chunks/4d3d997560b322ca.js","async":true,"nonce":"$undefined"}] -c:["$","script","script-18",{"src":"/litellm-asset-prefix/_next/static/chunks/4e4d0f466b5c1780.js","async":true,"nonce":"$undefined"}] -d:["$","script","script-19",{"src":"/litellm-asset-prefix/_next/static/chunks/88c74f8b4b20d25a.js","async":true,"nonce":"$undefined"}] -e:["$","script","script-20",{"src":"/litellm-asset-prefix/_next/static/chunks/821f45f615724874.js","async":true,"nonce":"$undefined"}] -f:["$","script","script-21",{"src":"/litellm-asset-prefix/_next/static/chunks/2971c4658f1bcd7d.js","async":true,"nonce":"$undefined"}] +b:["$","script","script-17",{"src":"/litellm-asset-prefix/_next/static/chunks/1a04d31843c96649.js","async":true,"nonce":"$undefined"}] +c:["$","script","script-18",{"src":"/litellm-asset-prefix/_next/static/chunks/ed90bf177ad61e18.js","async":true,"nonce":"$undefined"}] +d:["$","script","script-19",{"src":"/litellm-asset-prefix/_next/static/chunks/2971c4658f1bcd7d.js","async":true,"nonce":"$undefined"}] +e:["$","script","script-20",{"src":"/litellm-asset-prefix/_next/static/chunks/6c4c97f1ea6e7d77.js","async":true,"nonce":"$undefined"}] +f:["$","script","script-21",{"src":"/litellm-asset-prefix/_next/static/chunks/9d6e5aad99b19216.js","async":true,"nonce":"$undefined"}] 10:["$","script","script-22",{"src":"/litellm-asset-prefix/_next/static/chunks/134f728fa7099e3e.js","async":true,"nonce":"$undefined"}] -11:["$","script","script-23",{"src":"/litellm-asset-prefix/_next/static/chunks/9b539d4d807cee27.js","async":true,"nonce":"$undefined"}] -12:["$","script","script-24",{"src":"/litellm-asset-prefix/_next/static/chunks/fc83f709354547bd.js","async":true,"nonce":"$undefined"}] -13:["$","script","script-25",{"src":"/litellm-asset-prefix/_next/static/chunks/853e5f250e7a0af5.js","async":true,"nonce":"$undefined"}] +11:["$","script","script-23",{"src":"/litellm-asset-prefix/_next/static/chunks/acbeac1b0fde1fdf.js","async":true,"nonce":"$undefined"}] +12:["$","script","script-24",{"src":"/litellm-asset-prefix/_next/static/chunks/fa6fc6b79591df63.js","async":true,"nonce":"$undefined"}] +13:["$","script","script-25",{"src":"/litellm-asset-prefix/_next/static/chunks/7e417dd24c8becd0.js","async":true,"nonce":"$undefined"}] 14:["$","script","script-26",{"src":"/litellm-asset-prefix/_next/static/chunks/348b31083769a7c4.js","async":true,"nonce":"$undefined"}] -15:["$","script","script-27",{"src":"/litellm-asset-prefix/_next/static/chunks/37c03dc421ba81f8.js","async":true,"nonce":"$undefined"}] -16:["$","script","script-28",{"src":"/litellm-asset-prefix/_next/static/chunks/c81bdad246412686.js","async":true,"nonce":"$undefined"}] -17:["$","script","script-29",{"src":"/litellm-asset-prefix/_next/static/chunks/496b84010c33cf69.js","async":true,"nonce":"$undefined"}] +15:["$","script","script-27",{"src":"/litellm-asset-prefix/_next/static/chunks/a85adee4198d5478.js","async":true,"nonce":"$undefined"}] +16:["$","script","script-28",{"src":"/litellm-asset-prefix/_next/static/chunks/c8eee6971ca36303.js","async":true,"nonce":"$undefined"}] +17:["$","script","script-29",{"src":"/litellm-asset-prefix/_next/static/chunks/0adb91ab5f3140d5.js","async":true,"nonce":"$undefined"}] 18:["$","script","script-30",{"src":"/litellm-asset-prefix/_next/static/chunks/b6cdb9a433f054f3.js","async":true,"nonce":"$undefined"}] -19:["$","script","script-31",{"src":"/litellm-asset-prefix/_next/static/chunks/fcdf7322b0aa3e2e.js","async":true,"nonce":"$undefined"}] -1a:["$","script","script-32",{"src":"/litellm-asset-prefix/_next/static/chunks/6146a0436556bd42.js","async":true,"nonce":"$undefined"}] +19:["$","script","script-31",{"src":"/litellm-asset-prefix/_next/static/chunks/22970a12064ba16b.js","async":true,"nonce":"$undefined"}] +1a:["$","script","script-32",{"src":"/litellm-asset-prefix/_next/static/chunks/aae16a3ce4812424.js","async":true,"nonce":"$undefined"}] 1b:["$","script","script-33",{"src":"/litellm-asset-prefix/_next/static/chunks/4980372eaa37b78b.js","async":true,"nonce":"$undefined"}] -1c:["$","script","script-34",{"src":"/litellm-asset-prefix/_next/static/chunks/90f0529c4408147d.js","async":true,"nonce":"$undefined"}] -1d:["$","script","script-35",{"src":"/litellm-asset-prefix/_next/static/chunks/a85adee4198d5478.js","async":true,"nonce":"$undefined"}] +1c:["$","script","script-34",{"src":"/litellm-asset-prefix/_next/static/chunks/d069df5baead6d90.js","async":true,"nonce":"$undefined"}] +1d:["$","script","script-35",{"src":"/litellm-asset-prefix/_next/static/chunks/69365f493e1655a4.js","async":true,"nonce":"$undefined"}] 1e:["$","script","script-36",{"src":"/litellm-asset-prefix/_next/static/chunks/0a65da2cd24e2ab6.js","async":true,"nonce":"$undefined"}] -1f:["$","script","script-37",{"src":"/litellm-asset-prefix/_next/static/chunks/8604d59a86c051be.js","async":true,"nonce":"$undefined"}] -20:["$","script","script-38",{"src":"/litellm-asset-prefix/_next/static/chunks/d3ac82723ec9e30d.js","async":true,"nonce":"$undefined"}] -21:["$","script","script-39",{"src":"/litellm-asset-prefix/_next/static/chunks/664bbc28119f9cc1.js","async":true,"nonce":"$undefined"}] -22:["$","script","script-40",{"src":"/litellm-asset-prefix/_next/static/chunks/d64d74932cb225a3.js","async":true,"nonce":"$undefined"}] -23:["$","script","script-41",{"src":"/litellm-asset-prefix/_next/static/chunks/0adb91ab5f3140d5.js","async":true,"nonce":"$undefined"}] -24:["$","script","script-42",{"src":"/litellm-asset-prefix/_next/static/chunks/5c6d02376dbf0f55.js","async":true,"nonce":"$undefined"}] -25:["$","script","script-43",{"src":"/litellm-asset-prefix/_next/static/chunks/85238af541b170ca.js","async":true,"nonce":"$undefined"}] -26:["$","script","script-44",{"src":"/litellm-asset-prefix/_next/static/chunks/06ebe9b0e9cdf241.js","async":true,"nonce":"$undefined"}] -27:["$","script","script-45",{"src":"/litellm-asset-prefix/_next/static/chunks/6c4c97f1ea6e7d77.js","async":true,"nonce":"$undefined"}] -28:["$","script","script-46",{"src":"/litellm-asset-prefix/_next/static/chunks/9d6e5aad99b19216.js","async":true,"nonce":"$undefined"}] -29:["$","script","script-47",{"src":"/litellm-asset-prefix/_next/static/chunks/99cf9cf99df5ccfc.js","async":true,"nonce":"$undefined"}] -2a:["$","script","script-48",{"src":"/litellm-asset-prefix/_next/static/chunks/fba776c260ae166c.js","async":true,"nonce":"$undefined"}] -2b:["$","script","script-49",{"src":"/litellm-asset-prefix/_next/static/chunks/b13b0ddeb85b5333.js","async":true,"nonce":"$undefined"}] -2c:["$","script","script-50",{"src":"/litellm-asset-prefix/_next/static/chunks/54e29148cb2f2582.js","async":true,"nonce":"$undefined"}] -2d:["$","script","script-51",{"src":"/litellm-asset-prefix/_next/static/chunks/7e417dd24c8becd0.js","async":true,"nonce":"$undefined"}] -2e:["$","script","script-52",{"src":"/litellm-asset-prefix/_next/static/chunks/09058c1c88c095d7.js","async":true,"nonce":"$undefined"}] -2f:["$","$L32",null,{"children":["$","$33",null,{"name":"Next.MetadataOutlet","children":"$@34"}]}] -30:["$","$1","h",{"children":[null,["$","$L35",null,{"children":"$L36"}],["$","div",null,{"hidden":true,"children":["$","$L37",null,{"children":["$","$33",null,{"name":"Next.Metadata","children":"$L38"}]}]}],["$","meta",null,{"name":"next-size-adjust","content":""}]]}] +1f:["$","script","script-37",{"src":"/litellm-asset-prefix/_next/static/chunks/fc4d54eb6afe7984.js","async":true,"nonce":"$undefined"}] +20:["$","script","script-38",{"src":"/litellm-asset-prefix/_next/static/chunks/e99f98e7f34532c9.js","async":true,"nonce":"$undefined"}] +21:["$","script","script-39",{"src":"/litellm-asset-prefix/_next/static/chunks/496b84010c33cf69.js","async":true,"nonce":"$undefined"}] +22:["$","script","script-40",{"src":"/litellm-asset-prefix/_next/static/chunks/06ebe9b0e9cdf241.js","async":true,"nonce":"$undefined"}] +23:["$","script","script-41",{"src":"/litellm-asset-prefix/_next/static/chunks/df6546cd8a44d3b3.js","async":true,"nonce":"$undefined"}] +24:["$","script","script-42",{"src":"/litellm-asset-prefix/_next/static/chunks/d3ac82723ec9e30d.js","async":true,"nonce":"$undefined"}] +25:["$","script","script-43",{"src":"/litellm-asset-prefix/_next/static/chunks/99cf9cf99df5ccfc.js","async":true,"nonce":"$undefined"}] +26:["$","script","script-44",{"src":"/litellm-asset-prefix/_next/static/chunks/07fd9d7c5c879cb6.js","async":true,"nonce":"$undefined"}] +27:["$","script","script-45",{"src":"/litellm-asset-prefix/_next/static/chunks/8dda507c226082ca.js","async":true,"nonce":"$undefined"}] +28:["$","script","script-46",{"src":"/litellm-asset-prefix/_next/static/chunks/54e29148cb2f2582.js","async":true,"nonce":"$undefined"}] +29:["$","script","script-47",{"src":"/litellm-asset-prefix/_next/static/chunks/3675074b1d85e268.js","async":true,"nonce":"$undefined"}] +2a:["$","script","script-48",{"src":"/litellm-asset-prefix/_next/static/chunks/fcdf7322b0aa3e2e.js","async":true,"nonce":"$undefined"}] +2b:["$","script","script-49",{"src":"/litellm-asset-prefix/_next/static/chunks/bd94e2fe34d8a187.js","async":true,"nonce":"$undefined"}] +2c:["$","$L2f",null,{"children":["$","$30",null,{"name":"Next.MetadataOutlet","children":"$@31"}]}] +2d:["$","$1","h",{"children":[null,["$","$L32",null,{"children":"$L33"}],["$","div",null,{"hidden":true,"children":["$","$L34",null,{"children":["$","$30",null,{"name":"Next.Metadata","children":"$L35"}]}]}],["$","meta",null,{"name":"next-size-adjust","content":""}]]}] 8:{} 9:"$0:f:0:1:1:children:0:props:children:0:props:serverProvidedParams:params" -36:[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]] -39:I[27201,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"IconMark"] -34:null -38:[["$","title","0",{"children":"LiteLLM Dashboard"}],["$","meta","1",{"name":"description","content":"LiteLLM Proxy Admin UI"}],["$","link","2",{"rel":"icon","href":"/favicon.ico?favicon.1d32c690.ico","sizes":"48x48","type":"image/x-icon"}],["$","link","3",{"rel":"icon","href":"./favicon.ico"}],["$","$L39","4",{}]] +33:[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]] +36:I[27201,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"IconMark"] +31:null +35:[["$","title","0",{"children":"LiteLLM Dashboard"}],["$","meta","1",{"name":"description","content":"LiteLLM Proxy Admin UI"}],["$","link","2",{"rel":"icon","href":"/favicon.ico?favicon.1d32c690.ico","sizes":"48x48","type":"image/x-icon"}],["$","link","3",{"rel":"icon","href":"./favicon.ico"}],["$","$L36","4",{}]] diff --git a/litellm/proxy/_experimental/out/__next._head.txt b/litellm/proxy/_experimental/out/__next._head.txt index b8902a5de43..594e8f57492 100644 --- a/litellm/proxy/_experimental/out/__next._head.txt +++ b/litellm/proxy/_experimental/out/__next._head.txt @@ -3,4 +3,4 @@ 3:I[897367,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"MetadataBoundary"] 4:"$Sreact.suspense" 5:I[27201,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"IconMark"] -0:{"buildId":"WhBGJTAPhDM3j-59ST728","rsc":["$","$1","h",{"children":[null,["$","$L2",null,{"children":[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]}],["$","div",null,{"hidden":true,"children":["$","$L3",null,{"children":["$","$4",null,{"name":"Next.Metadata","children":[["$","title","0",{"children":"LiteLLM Dashboard"}],["$","meta","1",{"name":"description","content":"LiteLLM Proxy Admin UI"}],["$","link","2",{"rel":"icon","href":"/favicon.ico?favicon.1d32c690.ico","sizes":"48x48","type":"image/x-icon"}],["$","link","3",{"rel":"icon","href":"./favicon.ico"}],["$","$L5","4",{}]]}]}]}],["$","meta",null,{"name":"next-size-adjust","content":""}]]}],"loading":null,"isPartial":false} +0:{"buildId":"Kalni9LnFJDBB7xvqCPNe","rsc":["$","$1","h",{"children":[null,["$","$L2",null,{"children":[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]}],["$","div",null,{"hidden":true,"children":["$","$L3",null,{"children":["$","$4",null,{"name":"Next.Metadata","children":[["$","title","0",{"children":"LiteLLM Dashboard"}],["$","meta","1",{"name":"description","content":"LiteLLM Proxy Admin UI"}],["$","link","2",{"rel":"icon","href":"/favicon.ico?favicon.1d32c690.ico","sizes":"48x48","type":"image/x-icon"}],["$","link","3",{"rel":"icon","href":"./favicon.ico"}],["$","$L5","4",{}]]}]}]}],["$","meta",null,{"name":"next-size-adjust","content":""}]]}],"loading":null,"isPartial":false} diff --git a/litellm/proxy/_experimental/out/__next._index.txt b/litellm/proxy/_experimental/out/__next._index.txt index 5425415e444..5b96902d9c5 100644 --- a/litellm/proxy/_experimental/out/__next._index.txt +++ b/litellm/proxy/_experimental/out/__next._index.txt @@ -4,5 +4,5 @@ 4:I[339756,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"default"] 5:I[837457,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"default"] :HL["/litellm-asset-prefix/_next/static/chunks/4e20891f2fd03463.css","style"] -:HL["/litellm-asset-prefix/_next/static/chunks/7936c9bd377ea4bf.css","style"] -0:{"buildId":"WhBGJTAPhDM3j-59ST728","rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/4e20891f2fd03463.css","precedence":"next"}],["$","link","1",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/7936c9bd377ea4bf.css","precedence":"next"}],["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/a7f104aa2cc7f3f0.js","async":true}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/e8ed72789c2b42ff.js","async":true}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"inter_5972bc34-module__OU16Qa__className","children":["$","$L2",null,{"children":["$","$L3",null,{"children":["$","$L4",null,{"parallelRouterKey":"children","template":["$","$L5",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]}]}]}]}]]}],"loading":null,"isPartial":false} +:HL["/litellm-asset-prefix/_next/static/chunks/8dc3b559a2e76f88.css","style"] +0:{"buildId":"Kalni9LnFJDBB7xvqCPNe","rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/4e20891f2fd03463.css","precedence":"next"}],["$","link","1",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/8dc3b559a2e76f88.css","precedence":"next"}],["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/a7f104aa2cc7f3f0.js","async":true}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/e8ed72789c2b42ff.js","async":true}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"inter_5972bc34-module__OU16Qa__className","children":["$","$L2",null,{"children":["$","$L3",null,{"children":["$","$L4",null,{"parallelRouterKey":"children","template":["$","$L5",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]}]}]}]}]]}],"loading":null,"isPartial":false} diff --git a/litellm/proxy/_experimental/out/__next._tree.txt b/litellm/proxy/_experimental/out/__next._tree.txt index 7de1b14486f..90402dd4bff 100644 --- a/litellm/proxy/_experimental/out/__next._tree.txt +++ b/litellm/proxy/_experimental/out/__next._tree.txt @@ -1,5 +1,5 @@ :HL["/litellm-asset-prefix/_next/static/chunks/4e20891f2fd03463.css","style"] -:HL["/litellm-asset-prefix/_next/static/chunks/7936c9bd377ea4bf.css","style"] +:HL["/litellm-asset-prefix/_next/static/chunks/8dc3b559a2e76f88.css","style"] :HL["/litellm-asset-prefix/_next/static/media/83afe278b6a6bb3c-s.p.3a6ba036.woff2","font",{"crossOrigin":"","type":"font/woff2"}] :HL["/litellm-asset-prefix/_next/static/chunks/3f3fa56b5786d58c.css","style"] -0:{"buildId":"WhBGJTAPhDM3j-59ST728","tree":{"name":"","paramType":null,"paramKey":"","hasRuntimePrefetch":false,"slots":{"children":{"name":"__PAGE__","paramType":null,"paramKey":"__PAGE__","hasRuntimePrefetch":false,"slots":null,"isRootLayout":false}},"isRootLayout":true},"staleTime":300} +0:{"buildId":"Kalni9LnFJDBB7xvqCPNe","tree":{"name":"","paramType":null,"paramKey":"","hasRuntimePrefetch":false,"slots":{"children":{"name":"__PAGE__","paramType":null,"paramKey":"__PAGE__","hasRuntimePrefetch":false,"slots":null,"isRootLayout":false}},"isRootLayout":true},"staleTime":300} diff --git a/litellm/proxy/_experimental/out/_next/static/WhBGJTAPhDM3j-59ST728/_buildManifest.js b/litellm/proxy/_experimental/out/_next/static/Kalni9LnFJDBB7xvqCPNe/_buildManifest.js similarity index 100% rename from litellm/proxy/_experimental/out/_next/static/WhBGJTAPhDM3j-59ST728/_buildManifest.js rename to litellm/proxy/_experimental/out/_next/static/Kalni9LnFJDBB7xvqCPNe/_buildManifest.js diff --git a/litellm/proxy/_experimental/out/_next/static/WhBGJTAPhDM3j-59ST728/_clientMiddlewareManifest.json b/litellm/proxy/_experimental/out/_next/static/Kalni9LnFJDBB7xvqCPNe/_clientMiddlewareManifest.json similarity index 100% rename from litellm/proxy/_experimental/out/_next/static/WhBGJTAPhDM3j-59ST728/_clientMiddlewareManifest.json rename to litellm/proxy/_experimental/out/_next/static/Kalni9LnFJDBB7xvqCPNe/_clientMiddlewareManifest.json diff --git a/litellm/proxy/_experimental/out/_next/static/WhBGJTAPhDM3j-59ST728/_ssgManifest.js b/litellm/proxy/_experimental/out/_next/static/Kalni9LnFJDBB7xvqCPNe/_ssgManifest.js similarity index 100% rename from litellm/proxy/_experimental/out/_next/static/WhBGJTAPhDM3j-59ST728/_ssgManifest.js rename to litellm/proxy/_experimental/out/_next/static/Kalni9LnFJDBB7xvqCPNe/_ssgManifest.js diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/0184f3b07b67e571.js b/litellm/proxy/_experimental/out/_next/static/chunks/0184f3b07b67e571.js deleted file mode 100644 index aebaaa0e0ff..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/0184f3b07b67e571.js +++ /dev/null @@ -1 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,621482,e=>{"use strict";var t=e.i(869230),s=e.i(992571),a=class extends t.QueryObserver{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){super.setOptions({...e,behavior:(0,s.infiniteQueryBehavior)()})}getOptimisticResult(e){return e.behavior=(0,s.infiniteQueryBehavior)(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:a}=e,i=super.createResult(e,t),{isFetching:l,isRefetching:r,isError:n,isRefetchError:o}=i,c=a.fetchMeta?.fetchMore?.direction,d=n&&"forward"===c,u=l&&"forward"===c,h=n&&"backward"===c,g=l&&"backward"===c;return{...i,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:(0,s.hasNextPage)(t,a.data),hasPreviousPage:(0,s.hasPreviousPage)(t,a.data),isFetchNextPageError:d,isFetchingNextPage:u,isFetchPreviousPageError:h,isFetchingPreviousPage:g,isRefetchError:o&&!d&&!h,isRefetching:r&&!u&&!g}}},i=e.i(469637);function l(e,t){return(0,i.useBaseQuery)(e,a,t)}e.s(["useInfiniteQuery",()=>l],621482)},214541,e=>{"use strict";var t=e.i(271645),s=e.i(135214),a=e.i(270345);e.s(["default",0,()=>{let[e,i]=(0,t.useState)([]),{accessToken:l,userId:r,userRole:n}=(0,s.default)();return(0,t.useEffect)(()=>{(async()=>{i(await (0,a.fetchTeams)(l,r,n,null))})()},[l,r,n]),{teams:e,setTeams:i}}])},439189,435684,96226,497245,e=>{"use strict";function t(e){let t=Object.prototype.toString.call(e);return e instanceof Date||"object"==typeof e&&"[object Date]"===t?new e.constructor(+e):new Date("number"==typeof e||"[object Number]"===t||"string"==typeof e||"[object String]"===t?e:NaN)}function s(e,t){return e instanceof Date?new e.constructor(t):new Date(t)}function a(e,a){let i=t(e);return isNaN(a)?s(e,NaN):(a&&i.setDate(i.getDate()+a),i)}function i(e,a){let i=t(e);if(isNaN(a))return s(e,NaN);if(!a)return i;let l=i.getDate(),r=s(e,i.getTime());return(r.setMonth(i.getMonth()+a+1,0),l>=r.getDate())?r:(i.setFullYear(r.getFullYear(),r.getMonth(),l),i)}e.s(["toDate",()=>t],435684),e.s(["constructFrom",()=>s],96226),e.s(["addDays",()=>a],439189),e.s(["addMonths",()=>i],497245)},891547,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(199133),i=e.i(764205);e.s(["default",0,({onChange:e,value:l,className:r,accessToken:n,disabled:o})=>{let[c,d]=(0,s.useState)([]),[u,h]=(0,s.useState)(!1);return(0,s.useEffect)(()=>{(async()=>{if(n){h(!0);try{let e=await (0,i.getGuardrailsList)(n);console.log("Guardrails response:",e),e.guardrails&&(console.log("Guardrails data:",e.guardrails),d(e.guardrails))}catch(e){console.error("Error fetching guardrails:",e)}finally{h(!1)}}})()},[n]),(0,t.jsx)("div",{children:(0,t.jsx)(a.Select,{mode:"multiple",disabled:o,placeholder:o?"Setting guardrails is a premium feature.":"Select guardrails",onChange:t=>{console.log("Selected guardrails:",t),e(t)},value:l,loading:u,className:r,allowClear:!0,options:c.map(e=>(console.log("Mapping guardrail:",e),{label:`${e.guardrail_name}`,value:e.guardrail_name})),optionFilterProp:"label",showSearch:!0,style:{width:"100%"}})})}])},921511,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(199133),i=e.i(764205);function l(e){return e.filter(e=>(e.version_status??"draft")!=="draft").map(e=>{var t;let s=e.version_number??1,a=e.version_status??"draft";return{label:`${e.policy_name} — v${s} (${a})${e.description?` — ${e.description}`:""}`,value:"production"===a?e.policy_name:e.policy_id?(t=e.policy_id,`policy_${t}`):e.policy_name}})}e.s(["default",0,({onChange:e,value:r,className:n,accessToken:o,disabled:c,onPoliciesLoaded:d})=>{let[u,h]=(0,s.useState)([]),[g,m]=(0,s.useState)(!1);return(0,s.useEffect)(()=>{(async()=>{if(o){m(!0);try{let e=await (0,i.getPoliciesList)(o);e.policies&&(h(e.policies),d?.(e.policies))}catch(e){console.error("Error fetching policies:",e)}finally{m(!1)}}})()},[o,d]),(0,t.jsx)("div",{children:(0,t.jsx)(a.Select,{mode:"multiple",disabled:c,placeholder:c?"Setting policies is a premium feature.":"Select policies (production or published versions)",onChange:t=>{e(t)},value:r,loading:g,className:n,allowClear:!0,options:l(u),optionFilterProp:"label",showSearch:!0,style:{width:"100%"}})})},"getPolicyOptionEntries",()=>l])},637235,e=>{"use strict";e.i(247167);var t=e.i(931067),s=e.i(271645);let 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 372z"}},{tag:"path",attrs:{d:"M686.7 638.6L544.1 535.5V288c0-4.4-3.6-8-8-8H488c-4.4 0-8 3.6-8 8v275.4c0 2.6 1.2 5 3.3 6.5l165.4 120.6c3.6 2.6 8.6 1.8 11.2-1.7l28.6-39c2.6-3.7 1.8-8.7-1.8-11.2z"}}]},name:"clock-circle",theme:"outlined"};var i=e.i(9583),l=s.forwardRef(function(e,l){return s.createElement(i.default,(0,t.default)({},e,{ref:l,icon:a}))});e.s(["ClockCircleOutlined",0,l],637235)},646563,e=>{"use strict";var t=e.i(959013);e.s(["PlusOutlined",()=>t.default])},447566,e=>{"use strict";e.i(247167);var t=e.i(931067),s=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M872 474H286.9l350.2-304c5.6-4.9 2.2-14-5.2-14h-88.5c-3.9 0-7.6 1.4-10.5 3.9L155 487.8a31.96 31.96 0 000 48.3L535.1 866c1.5 1.3 3.3 2 5.2 2h91.5c7.4 0 10.8-9.2 5.2-14L286.9 550H872c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8z"}}]},name:"arrow-left",theme:"outlined"};var i=e.i(9583),l=s.forwardRef(function(e,l){return s.createElement(i.default,(0,t.default)({},e,{ref:l,icon:a}))});e.s(["ArrowLeftOutlined",0,l],447566)},954616,e=>{"use strict";var t=e.i(271645),s=e.i(114272),a=e.i(540143),i=e.i(915823),l=e.i(619273),r=class extends i.Subscribable{#e;#t=void 0;#s;#a;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),(0,l.shallowEqualObjects)(this.options,t)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#s,observer:this}),t?.mutationKey&&this.options.mutationKey&&(0,l.hashKey)(t.mutationKey)!==(0,l.hashKey)(this.options.mutationKey)?this.reset():this.#s?.state.status==="pending"&&this.#s.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#s?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#l(e)}getCurrentResult(){return this.#t}reset(){this.#s?.removeObserver(this),this.#s=void 0,this.#i(),this.#l()}mutate(e,t){return this.#a=t,this.#s?.removeObserver(this),this.#s=this.#e.getMutationCache().build(this.#e,this.options),this.#s.addObserver(this),this.#s.execute(e)}#i(){let e=this.#s?.state??(0,s.getDefaultState)();this.#t={...e,isPending:"pending"===e.status,isSuccess:"success"===e.status,isError:"error"===e.status,isIdle:"idle"===e.status,mutate:this.mutate,reset:this.reset}}#l(e){a.notifyManager.batch(()=>{if(this.#a&&this.hasListeners()){let t=this.#t.variables,s=this.#t.context,a={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#a.onSuccess?.(e.data,t,s,a)}catch(e){Promise.reject(e)}try{this.#a.onSettled?.(e.data,null,t,s,a)}catch(e){Promise.reject(e)}}else if(e?.type==="error"){try{this.#a.onError?.(e.error,t,s,a)}catch(e){Promise.reject(e)}try{this.#a.onSettled?.(void 0,e.error,t,s,a)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},n=e.i(912598);function o(e,s){let i=(0,n.useQueryClient)(s),[o]=t.useState(()=>new r(i,e));t.useEffect(()=>{o.setOptions(e)},[o,e]);let c=t.useSyncExternalStore(t.useCallback(e=>o.subscribe(a.notifyManager.batchCalls(e)),[o]),()=>o.getCurrentResult(),()=>o.getCurrentResult()),d=t.useCallback((e,t)=>{o.mutate(e,t).catch(l.noop)},[o]);if(c.error&&(0,l.shouldThrowError)(o.options.throwOnError,[c.error]))throw c.error;return{...c,mutate:d,mutateAsync:c.mutate}}e.s(["useMutation",()=>o],954616)},525720,e=>{"use strict";e.i(247167);var t=e.i(271645),s=e.i(343794),a=e.i(529681),i=e.i(908286),l=e.i(242064),r=e.i(246422),n=e.i(838378);let o=["wrap","nowrap","wrap-reverse"],c=["flex-start","flex-end","start","end","center","space-between","space-around","space-evenly","stretch","normal","left","right"],d=["center","start","end","flex-start","flex-end","self-start","self-end","baseline","normal","stretch"],u=function(e,t){let a,i,l;return(0,s.default)(Object.assign(Object.assign(Object.assign({},(a=!0===t.wrap?"wrap":t.wrap,{[`${e}-wrap-${a}`]:a&&o.includes(a)})),(i={},d.forEach(s=>{i[`${e}-align-${s}`]=t.align===s}),i[`${e}-align-stretch`]=!t.align&&!!t.vertical,i)),(l={},c.forEach(s=>{l[`${e}-justify-${s}`]=t.justify===s}),l)))},h=(0,r.genStyleHooks)("Flex",e=>{let{paddingXS:t,padding:s,paddingLG:a}=e,i=(0,n.mergeToken)(e,{flexGapSM:t,flexGap:s,flexGapLG:a});return[(e=>{let{componentCls:t}=e;return{[t]:{display:"flex",margin:0,padding:0,"&-vertical":{flexDirection:"column"},"&-rtl":{direction:"rtl"},"&:empty":{display:"none"}}}})(i),(e=>{let{componentCls:t}=e;return{[t]:{"&-gap-small":{gap:e.flexGapSM},"&-gap-middle":{gap:e.flexGap},"&-gap-large":{gap:e.flexGapLG}}}})(i),(e=>{let{componentCls:t}=e,s={};return o.forEach(e=>{s[`${t}-wrap-${e}`]={flexWrap:e}}),s})(i),(e=>{let{componentCls:t}=e,s={};return d.forEach(e=>{s[`${t}-align-${e}`]={alignItems:e}}),s})(i),(e=>{let{componentCls:t}=e,s={};return c.forEach(e=>{s[`${t}-justify-${e}`]={justifyContent:e}}),s})(i)]},()=>({}),{resetStyle:!1});var g=function(e,t){var s={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(s[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,a=Object.getOwnPropertySymbols(e);it.indexOf(a[i])&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(s[a[i]]=e[a[i]]);return s};let m=t.default.forwardRef((e,r)=>{let{prefixCls:n,rootClassName:o,className:c,style:d,flex:m,gap:f,vertical:p=!1,component:x="div",children:y}=e,w=g(e,["prefixCls","rootClassName","className","style","flex","gap","vertical","component","children"]),{flex:b,direction:v,getPrefixCls:S}=t.default.useContext(l.ConfigContext),j=S("flex",n),[_,N,C]=h(j),k=null!=p?p:null==b?void 0:b.vertical,O=(0,s.default)(c,o,null==b?void 0:b.className,j,N,C,u(j,e),{[`${j}-rtl`]:"rtl"===v,[`${j}-gap-${f}`]:(0,i.isPresetSize)(f),[`${j}-vertical`]:k}),z=Object.assign(Object.assign({},null==b?void 0:b.style),d);return m&&(z.flex=m),f&&!(0,i.isPresetSize)(f)&&(z.gap=f),_(t.default.createElement(x,Object.assign({ref:r,className:O,style:z},(0,a.default)(w,["justify","wrap","align"])),y))});e.s(["Flex",0,m],525720)},633627,e=>{"use strict";var t=e.i(764205);let s=(e,t,s,a)=>{for(let i of e){let e=i?.key_alias;e&&"string"==typeof e&&t.add(e.trim());let l=i?.organization_id??i?.org_id;l&&"string"==typeof l&&s.add(l.trim());let r=i?.user_id;if(r&&"string"==typeof r){let e=i?.user?.user_email||r;a.set(r,e)}}},a=async(e,a)=>{if(!e||!a)return{keyAliases:[],organizationIds:[],userIds:[]};try{let i=new Set,l=new Set,r=new Map,n=await (0,t.keyListCall)(e,null,a,null,null,null,1,100,null,null,"user",null),o=n?.keys||[],c=n?.total_pages??1;s(o,i,l,r);let d=Math.min(c,10)-1;if(d>0){let n=Array.from({length:d},(s,i)=>(0,t.keyListCall)(e,null,a,null,null,null,i+2,100,null,null,"user",null));for(let e of(await Promise.allSettled(n)))"fulfilled"===e.status&&s(e.value?.keys||[],i,l,r)}return{keyAliases:Array.from(i).sort(),organizationIds:Array.from(l).sort(),userIds:Array.from(r.entries()).map(([e,t])=>({id:e,email:t}))}}catch(e){return console.error("Error fetching team filter options:",e),{keyAliases:[],organizationIds:[],userIds:[]}}},i=async(e,s)=>{if(!e)return[];try{let a=[],i=1,l=!0;for(;l;){let r=await (0,t.teamListCall)(e,s||null,null);a=[...a,...r],i{if(!e)return[];try{let s=[],a=1,i=!0;for(;i;){let l=await (0,t.organizationListCall)(e);s=[...s,...l],a{"use strict";var t=e.i(843476),s=e.i(271645);let a=s.forwardRef(function(e,t){return s.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:t},e),s.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",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"}))});var i=e.i(464571),l=e.i(311451),r=e.i(199133),n=e.i(374009);e.s(["default",0,({options:e,onApplyFilters:o,onResetFilters:c,initialValues:d={},buttonLabel:u="Filters"})=>{let[h,g]=(0,s.useState)(!1),[m,f]=(0,s.useState)(d),[p,x]=(0,s.useState)({}),[y,w]=(0,s.useState)({}),[b,v]=(0,s.useState)({}),[S,j]=(0,s.useState)({}),_=(0,s.useCallback)((0,n.default)(async(e,t)=>{if(t.isSearchable&&t.searchFn){w(e=>({...e,[t.name]:!0}));try{let s=await t.searchFn(e);x(e=>({...e,[t.name]:s}))}catch(e){console.error("Error searching:",e),x(e=>({...e,[t.name]:[]}))}finally{w(e=>({...e,[t.name]:!1}))}}},300),[]),N=(0,s.useCallback)(async e=>{if(e.isSearchable&&e.searchFn&&!S[e.name]){w(t=>({...t,[e.name]:!0})),j(t=>({...t,[e.name]:!0}));try{let t=await e.searchFn("");x(s=>({...s,[e.name]:t}))}catch(t){console.error("Error loading initial options:",t),x(t=>({...t,[e.name]:[]}))}finally{w(t=>({...t,[e.name]:!1}))}}},[S]);(0,s.useEffect)(()=>{h&&e.forEach(e=>{e.isSearchable&&!S[e.name]&&N(e)})},[h,e,N,S]);let C=(e,t)=>{let s={...m,[e]:t};f(s),o(s)};return(0,t.jsxs)("div",{className:"w-full",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 mb-6",children:[(0,t.jsx)(i.Button,{icon:(0,t.jsx)(a,{className:"h-4 w-4"}),onClick:()=>g(!h),className:"flex items-center gap-2",children:u}),(0,t.jsx)(i.Button,{onClick:()=>{let t={};e.forEach(e=>{t[e.name]=""}),f(t),c()},children:"Reset Filters"})]}),h&&(0,t.jsx)("div",{className:"grid grid-cols-3 gap-x-6 gap-y-4 mb-6",children:["Team ID","Status","Organization ID","Key Alias","User ID","End User","Error Code","Error Message","Key Hash","Model"].map(s=>{let a,i=e.find(e=>e.label===s||e.name===s);return i?(0,t.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,t.jsx)("label",{className:"text-sm text-gray-600",children:i.label||i.name}),i.isSearchable?(0,t.jsx)(r.Select,{showSearch:!0,className:"w-full",placeholder:`Search ${i.label||i.name}...`,value:m[i.name]||void 0,onChange:e=>C(i.name,e),onOpenChange:e=>{e&&i.isSearchable&&!S[i.name]&&N(i)},onSearch:e=>{v(t=>({...t,[i.name]:e})),i.searchFn&&_(e,i)},filterOption:!1,loading:y[i.name],options:p[i.name]||[],allowClear:!0,notFoundContent:y[i.name]?"Loading...":"No results found"}):i.options?(0,t.jsx)(r.Select,{className:"w-full",placeholder:`Select ${i.label||i.name}...`,value:m[i.name]||void 0,onChange:e=>C(i.name,e),allowClear:!0,children:i.options.map(e=>(0,t.jsx)(r.Select.Option,{value:e.value,children:e.label},e.value))}):i.customComponent?(a=i.customComponent,(0,t.jsx)(a,{value:m[i.name]||void 0,onChange:e=>C(i.name,e??""),placeholder:`Select ${i.label||i.name}...`})):(0,t.jsx)(l.Input,{className:"w-full",placeholder:`Enter ${i.label||i.name}...`,value:m[i.name]||"",onChange:e=>C(i.name,e.target.value),allowClear:!0})]},i.name):null})})]})}],969550)},584578,e=>{"use strict";var t=e.i(764205);let s=async(e,s,a,i,l)=>{let r;r="Admin"!=a&&"Admin Viewer"!=a?await (0,t.teamListCall)(e,i?.organization_id||null,s):await (0,t.teamListCall)(e,i?.organization_id||null),console.log(`givenTeams: ${r}`),l(r)};e.s(["fetchTeams",0,s])},566606,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(618566),i=e.i(947293),l=e.i(764205),r=e.i(954616),n=e.i(266027),o=e.i(612256);let c=(0,e.i(243652).createQueryKeys)("onboarding");var d=e.i(482725),u=e.i(56456);function h(){return(0,t.jsx)("div",{className:"mx-auto w-full max-w-md mt-10 flex justify-center",children:(0,t.jsx)(d.Spin,{indicator:(0,t.jsx)(u.LoadingOutlined,{spin:!0}),size:"large"})})}var g=e.i(560445),m=e.i(464571);function f(){return(0,t.jsxs)("div",{className:"mx-auto w-full max-w-md mt-10",children:[(0,t.jsx)(g.Alert,{type:"error",message:"Failed to load invitation",description:"The invitation link may be invalid or expired.",showIcon:!0}),(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(m.Button,{href:"/ui/login",children:"Back to Login"})})]})}var p=e.i(175712),x=e.i(808613),y=e.i(311451),w=e.i(898586);function b({variant:e,userEmail:a,isPending:i,claimError:l,onSubmit:r}){let[n]=x.Form.useForm();return s.default.useEffect(()=>{a&&n.setFieldValue("user_email",a)},[a,n]),(0,t.jsx)("div",{className:"mx-auto w-full max-w-md mt-10",children:(0,t.jsxs)(p.Card,{children:[(0,t.jsx)(w.Typography.Title,{level:5,className:"text-center mb-5",children:"🚅 LiteLLM"}),(0,t.jsx)(w.Typography.Title,{level:3,children:"reset_password"===e?"Reset Password":"Sign Up"}),(0,t.jsx)(w.Typography.Text,{children:"reset_password"===e?"Reset your password to access Admin UI.":"Claim your user account to login to Admin UI."}),"signup"===e&&(0,t.jsx)(g.Alert,{className:"mt-4",type:"info",message:"SSO",description:(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[(0,t.jsx)("span",{children:"SSO is under the Enterprise Tier."}),(0,t.jsx)(m.Button,{type:"primary",size:"small",href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:"Get Free Trial"})]}),showIcon:!0}),(0,t.jsxs)(x.Form,{className:"mt-10 mb-5",layout:"vertical",form:n,onFinish:e=>r({password:e.password}),children:[(0,t.jsx)(x.Form.Item,{label:"Email Address",name:"user_email",children:(0,t.jsx)(y.Input,{type:"email",disabled:!0})}),(0,t.jsx)(x.Form.Item,{label:"Password",name:"password",rules:[{required:!0,message:"password required to sign up"}],help:"reset_password"===e?"Enter your new password":"Create a password for your account",children:(0,t.jsx)(y.Input.Password,{})}),l&&(0,t.jsx)(g.Alert,{type:"error",message:l,showIcon:!0,className:"mb-4"}),(0,t.jsx)("div",{className:"mt-10",children:(0,t.jsx)(m.Button,{htmlType:"submit",loading:i,children:"reset_password"===e?"Reset Password":"Sign Up"})})]})]})})}function v({variant:e}){let d=(0,a.useSearchParams)().get("invitation_id"),[u,g]=s.default.useState(null),{data:m,isLoading:p,isError:x}=(e=>{let{isLoading:t}=(0,o.useUIConfig)();return(0,n.useQuery)({queryKey:c.detail(e??""),queryFn:async()=>{if(!e)throw Error("inviteId is required");return(0,l.getOnboardingCredentials)(e)},enabled:!!e&&!t})})(d),{mutate:y,isPending:w}=(0,r.useMutation)({mutationFn:async({accessToken:e,inviteId:t,userId:s,password:a})=>await (0,l.claimOnboardingToken)(e,t,s,a)}),v=m?.token?(0,i.jwtDecode)(m.token):null,S=v?.user_email??"",j=v?.user_id??null,_=v?.key??null,N=m?.token??null;return p?(0,t.jsx)(h,{}):x?(0,t.jsx)(f,{}):(0,t.jsx)(b,{variant:e,userEmail:S,isPending:w,claimError:u,onSubmit:e=>{_&&N&&j&&d&&(g(null),y({accessToken:_,inviteId:d,userId:j,password:e.password},{onSuccess:()=>{document.cookie=`token=${N}; path=/; SameSite=Lax`;let e=(0,l.getProxyBaseUrl)();window.location.href=e?`${e}/ui/?login=success`:"/ui/?login=success"},onError:e=>{g(e.message||"Failed to submit. Please try again.")}}))}})}function S(){let e=(0,a.useSearchParams)().get("action");return(0,t.jsx)(v,{variant:"reset_password"===e?"reset_password":"signup"})}function j(){return(0,t.jsx)(s.Suspense,{fallback:(0,t.jsx)("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:(0,t.jsx)(S,{})})}e.s(["default",()=>j],566606)},152473,e=>{"use strict";var t=e.i(271645);let s={enabled:!0,leading:!1,trailing:!0,wait:0,onExecute:()=>{}};class a{constructor(e,t){this.fn=e,this._canLeadingExecute=!0,this._isPending=!1,this._executionCount=0,this._options={...s,...t}}setOptions(e){return this._options={...this._options,...e},this._options.enabled||(this._isPending=!1),this._options}getOptions(){return this._options}maybeExecute(...e){this._options.leading&&this._canLeadingExecute&&(this.executeFunction(...e),this._canLeadingExecute=!1),(this._options.leading||this._options.trailing)&&(this._isPending=!0),this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=setTimeout(()=>{this._canLeadingExecute=!0,this._isPending=!1,this._options.trailing&&this.executeFunction(...e)},this._options.wait)}executeFunction(...e){this._options.enabled&&(this.fn(...e),this._executionCount++,this._options.onExecute(this))}cancel(){this._timeoutId&&(clearTimeout(this._timeoutId),this._canLeadingExecute=!0,this._isPending=!1)}getExecutionCount(){return this._executionCount}getIsPending(){return this._options.enabled&&this._isPending}}function i(e,s){let[i,l]=(0,t.useState)(e),r=function(e,s){let[i]=(0,t.useState)(()=>{var t;return Object.getOwnPropertyNames(Object.getPrototypeOf(t=new a(e,s))).filter(e=>"function"==typeof t[e]).reduce((e,s)=>{let a=t[s];return"function"==typeof a&&(e[s]=a.bind(t)),e},{})});return i.setOptions(s),i}(l,s);return[i,r.maybeExecute,r]}e.s(["useDebouncedState",()=>i],152473)},700514,e=>{"use strict";var t=e.i(271645);e.s(["defaultPageSize",0,25,"useBaseUrl",0,()=>{let[e,s]=(0,t.useState)("http://localhost:4000");return(0,t.useEffect)(()=>{{let{protocol:e,host:t}=window.location;s(`${e}//${t}`)}},[]),e}])},50882,e=>{"use strict";var t=e.i(843476),s=e.i(621482),a=e.i(243652),i=e.i(764205),l=e.i(135214);let r=(0,a.createQueryKeys)("infiniteKeyAliases");var n=e.i(56456),o=e.i(152473),c=e.i(199133),d=e.i(271645);e.s(["PaginatedKeyAliasSelect",0,({value:e,onChange:a,placeholder:u="Select a key alias",style:h,pageSize:g=50,allowClear:m=!0,disabled:f=!1})=>{let[p,x]=(0,d.useState)(""),[y,w]=(0,o.useDebouncedState)("",{wait:300}),{data:b,fetchNextPage:v,hasNextPage:S,isFetchingNextPage:j,isLoading:_}=((e=50,t)=>{let{accessToken:a}=(0,l.default)();return(0,s.useInfiniteQuery)({queryKey:r.list({filters:{size:e,...t&&{search:t}}}),queryFn:async({pageParam:s})=>await (0,i.keyAliasesCall)(a,s,e,t),initialPageParam:1,getNextPageParam:e=>{if(e.current_page{if(!b?.pages)return[];let e=new Set,t=[];for(let s of b.pages)for(let a of s.aliases)!a||e.has(a)||(e.add(a),t.push({label:a,value:a}));return t},[b]);return(0,t.jsx)(c.Select,{value:e||void 0,onChange:e=>{a?.(e??"")},placeholder:u,style:{width:"100%",...h},allowClear:m,disabled:f,showSearch:!0,filterOption:!1,onSearch:e=>{x(e),w(e)},searchValue:p,onPopupScroll:e=>{let t=e.currentTarget;(t.scrollTop+t.clientHeight)/t.scrollHeight>=.8&&S&&!j&&v()},loading:_,notFoundContent:_?(0,t.jsx)(n.LoadingOutlined,{spin:!0}):"No key aliases found",options:N,popupRender:e=>(0,t.jsxs)(t.Fragment,{children:[e,j&&(0,t.jsx)("div",{style:{textAlign:"center",padding:8},children:(0,t.jsx)(n.LoadingOutlined,{spin:!0})})]})})}],50882)},693569,e=>{"use strict";var t=e.i(843476),s=e.i(268004),a=e.i(309426),i=e.i(350967),l=e.i(898586),r=e.i(947293),n=e.i(618566),o=e.i(271645),c=e.i(566606),d=e.i(584578),u=e.i(764205),h=e.i(702597),g=e.i(207082),m=e.i(500330),f=e.i(871943),p=e.i(502547),x=e.i(360820),y=e.i(94629),w=e.i(152990),b=e.i(682830),v=e.i(389083),S=e.i(994388),j=e.i(752978),_=e.i(269200),N=e.i(942232),C=e.i(977572),k=e.i(427612),O=e.i(64848),z=e.i(496020),P=e.i(599724),I=e.i(827252),D=e.i(282786),E=e.i(981339),T=e.i(592968),M=e.i(355619),R=e.i(633627),A=e.i(374009),$=e.i(700514),L=e.i(135214),K=e.i(50882),U=e.i(969550),F=e.i(20147);function B({teams:e,organizations:s,onSortChange:a,currentSort:i}){let[l,r]=(0,o.useState)(null),[n,c]=o.default.useState(()=>i?[{id:i.sortBy,desc:"desc"===i.sortOrder}]:[{id:"created_at",desc:!0}]),[d,h]=o.default.useState({pageIndex:0,pageSize:50}),B=n.length>0?n[0].id:null,V=n.length>0?n[0].desc?"desc":"asc":null,{data:H,isPending:G,isFetching:W,refetch:J}=(0,g.useKeys)(d.pageIndex+1,d.pageSize,{sortBy:B||void 0,sortOrder:V||void 0}),[q,Q]=(0,o.useState)({}),{filters:Y,filteredKeys:Z,filteredTotalCount:X,allTeams:ee,allOrganizations:et,handleFilterChange:es,handleFilterReset:ea}=function({keys:e,teams:t,organizations:s}){let a={"Team ID":"","Organization ID":"","Key Alias":"","User ID":"","Sort By":"created_at","Sort Order":"desc"},{accessToken:i}=(0,L.default)(),[l,r]=(0,o.useState)(a),[n,c]=(0,o.useState)(t||[]),[d,h]=(0,o.useState)(s||[]),[g,m]=(0,o.useState)(e),[f,p]=(0,o.useState)(null),x=(0,o.useRef)(0),y=(0,o.useCallback)((0,A.default)(async e=>{if(!i)return;let t=Date.now();x.current=t;try{let s=await (0,u.keyListCall)(i,e["Organization ID"]||null,e["Team ID"]||null,e["Key Alias"]||null,e["User ID"]||null,e["Key Hash"]||null,1,$.defaultPageSize,e["Sort By"]||null,e["Sort Order"]||null);t===x.current&&s&&(m(s.keys),p(s.total_count??null),console.log("called from debouncedSearch filters:",JSON.stringify(e)),console.log("called from debouncedSearch data:",JSON.stringify(s)))}catch(e){console.error("Error searching users:",e)}},300),[i]);return(0,o.useEffect)(()=>{if(!e)return void m([]);let t=[...e];l["Team ID"]&&(t=t.filter(e=>e.team_id===l["Team ID"])),l["Organization ID"]&&(t=t.filter(e=>(e.organization_id??e.org_id)===l["Organization ID"])),m(t)},[e,l]),(0,o.useEffect)(()=>{let e=async()=>{let e=await (0,R.fetchAllTeams)(i);e.length>0&&c(e);let t=await (0,R.fetchAllOrganizations)(i);t.length>0&&h(t)};i&&e()},[i]),(0,o.useEffect)(()=>{t&&t.length>0&&c(e=>e.length{s&&s.length>0&&h(e=>e.length{r({"Team ID":e["Team ID"]||"","Organization ID":e["Organization ID"]||"","Key Alias":e["Key Alias"]||"","User ID":e["User ID"]||"","Sort By":e["Sort By"]||"created_at","Sort Order":e["Sort Order"]||"desc"}),t||y({...l,...e})},handleFilterReset:()=>{r(a),p(null),y(a)}}}({keys:H?.keys||[],teams:e,organizations:s}),ei=X??H?.total_count??0;(0,o.useEffect)(()=>{if(J){let e=()=>{J()};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}},[J]);let el=(0,o.useMemo)(()=>[{id:"expander",header:()=>null,size:40,enableSorting:!1,cell:({row:e})=>e.getCanExpand()?(0,t.jsx)("button",{onClick:e.getToggleExpandedHandler(),style:{cursor:"pointer"},children:e.getIsExpanded()?"▼":"▶"}):null},{id:"token",accessorKey:"token",header:"Key ID",size:100,enableSorting:!0,cell:e=>{let s=e.getValue(),a=e.cell.column.getSize();return(0,t.jsx)(T.Tooltip,{title:s,children:(0,t.jsx)(S.Button,{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 block",style:{maxWidth:a,overflow:"hidden"},onClick:()=>r(e.row.original),children:s??"-"})})}},{id:"key_alias",accessorKey:"key_alias",header:"Key Alias",size:150,enableSorting:!0,cell:e=>{let s=e.getValue(),a=e.cell.column.getSize();return(0,t.jsx)(T.Tooltip,{title:s,children:(0,t.jsx)("span",{className:"font-mono text-xs truncate block",style:{maxWidth:a,overflow:"hidden"},children:s??"-"})})}},{id:"key_name",accessorKey:"key_name",header:"Secret Key",size:120,enableSorting:!1,cell:e=>(0,t.jsx)("span",{className:"font-mono text-xs",children:e.getValue()})},{id:"team_alias",accessorKey:"team_id",header:"Team Alias",size:120,enableSorting:!1,cell:({row:t,getValue:s})=>{let a=s(),i=e?.find(e=>e.team_id===a);return i?.team_alias||"Unknown"}},{id:"team_id",accessorKey:"team_id",header:"Team ID",size:80,enableSorting:!1,cell:e=>{let s=e.getValue(),a=e.cell.column.getSize();return(0,t.jsx)(T.Tooltip,{title:s,children:(0,t.jsx)("span",{className:"font-mono text-xs truncate block",style:{maxWidth:a,overflow:"hidden"},children:s??"-"})})}},{id:"organization_id",accessorKey:"org_id",header:"Organization ID",size:140,enableSorting:!1,cell:e=>e.getValue()?e.renderValue():"-"},{id:"user_email",accessorKey:"user",header:"User Email",size:160,enableSorting:!1,cell:e=>{let s=e.getValue(),a=s?.user_email,i=e.cell.column.getSize();return(0,t.jsx)(T.Tooltip,{title:a,children:(0,t.jsx)("span",{className:"font-mono text-xs truncate block",style:{maxWidth:i,overflow:"hidden"},children:a??"-"})})}},{id:"user_id",accessorKey:"user_id",header:"User ID",size:70,enableSorting:!1,cell:e=>{let s=e.getValue(),a="default_user_id"===s?"Default Proxy Admin":s,i=e.cell.column.getSize();return(0,t.jsx)(T.Tooltip,{title:a,children:(0,t.jsx)("span",{className:"font-mono text-xs truncate block",style:{maxWidth:i,overflow:"hidden"},children:a??"-"})})}},{id:"created_at",accessorKey:"created_at",header:"Created At",size:120,enableSorting:!0,cell:e=>{let t=e.getValue();return t?new Date(t).toLocaleDateString():"-"}},{id:"created_by",accessorKey:"created_by",header:"Created By",size:70,enableSorting:!1,cell:e=>{let s=e.getValue(),a="default_user_id"===s?"Default Proxy Admin":s,i=e.cell.column.getSize();return(0,t.jsx)(T.Tooltip,{title:a,children:(0,t.jsx)("span",{className:"font-mono text-xs truncate block",style:{maxWidth:i,overflow:"hidden"},children:a??"-"})})}},{id:"updated_at",accessorKey:"updated_at",header:"Updated At",size:120,enableSorting:!0,cell:e=>{let t=e.getValue();return t?new Date(t).toLocaleDateString():"Never"}},{id:"last_active",accessorKey:"last_active",header:()=>(0,t.jsxs)("span",{className:"flex items-center gap-1",children:["Last Active",(0,t.jsx)(D.Popover,{content:"This is a new field and is not backfilled. Only new key usage will update this value.",trigger:"hover",children:(0,t.jsx)(I.InfoCircleOutlined,{className:"text-gray-400 text-xs cursor-help"})})]}),size:130,enableSorting:!1,cell:e=>{let s=e.getValue();if(!s)return"Unknown";let a=new Date(s);return(0,t.jsx)(T.Tooltip,{title:a.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"long"}),children:(0,t.jsx)("span",{children:a.toLocaleDateString()})})}},{id:"expires",accessorKey:"expires",header:"Expires",size:120,enableSorting:!1,cell:e=>{let t=e.getValue();return t?new Date(t).toLocaleDateString():"Never"}},{id:"spend",accessorKey:"spend",header:"Spend (USD)",size:100,enableSorting:!0,cell:e=>(0,m.formatNumberWithCommas)(e.getValue(),4)},{id:"max_budget",accessorKey:"max_budget",header:"Budget (USD)",size:110,enableSorting:!0,cell:e=>{let t=e.getValue();return null===t?"Unlimited":`$${(0,m.formatNumberWithCommas)(t)}`}},{id:"budget_reset_at",accessorKey:"budget_reset_at",header:"Budget Reset",size:130,enableSorting:!1,cell:e=>{let t=e.getValue();return t?new Date(t).toLocaleString():"Never"}},{id:"models",accessorKey:"models",header:"Models",size:200,enableSorting:!1,cell:e=>{let s=e.getValue();return(0,t.jsx)("div",{className:"flex flex-col py-2",children:Array.isArray(s)?(0,t.jsx)("div",{className:"flex flex-col",children:0===s.length?(0,t.jsx)(v.Badge,{size:"xs",className:"mb-1",color:"red",children:(0,t.jsx)(P.Text,{children:"All Proxy Models"})}):(0,t.jsx)(t.Fragment,{children:(0,t.jsxs)("div",{className:"flex items-start",children:[s.length>3&&(0,t.jsx)("div",{children:(0,t.jsx)(j.Icon,{icon:q[e.row.id]?f.ChevronDownIcon:p.ChevronRightIcon,className:"cursor-pointer",size:"xs",onClick:()=>{Q(t=>({...t,[e.row.id]:!t[e.row.id]}))}})}),(0,t.jsxs)("div",{className:"flex flex-wrap gap-1",children:[s.slice(0,3).map((e,s)=>"all-proxy-models"===e?(0,t.jsx)(v.Badge,{size:"xs",color:"red",children:(0,t.jsx)(P.Text,{children:"All Proxy Models"})},s):(0,t.jsx)(v.Badge,{size:"xs",color:"blue",children:(0,t.jsx)(P.Text,{children:e.length>30?`${(0,M.getModelDisplayName)(e).slice(0,30)}...`:(0,M.getModelDisplayName)(e)})},s)),s.length>3&&!q[e.row.id]&&(0,t.jsx)(v.Badge,{size:"xs",color:"gray",className:"cursor-pointer",children:(0,t.jsxs)(P.Text,{children:["+",s.length-3," ",s.length-3==1?"more model":"more models"]})}),q[e.row.id]&&(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:s.slice(3).map((e,s)=>"all-proxy-models"===e?(0,t.jsx)(v.Badge,{size:"xs",color:"red",children:(0,t.jsx)(P.Text,{children:"All Proxy Models"})},s+3):(0,t.jsx)(v.Badge,{size:"xs",color:"blue",children:(0,t.jsx)(P.Text,{children:e.length>30?`${(0,M.getModelDisplayName)(e).slice(0,30)}...`:(0,M.getModelDisplayName)(e)})},s+3))})]})]})})}):null})}},{id:"rate_limits",header:"Rate Limits",size:140,enableSorting:!1,cell:({row:e})=>{let s=e.original;return(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{children:["TPM: ",null!==s.tpm_limit?s.tpm_limit:"Unlimited"]}),(0,t.jsxs)("div",{children:["RPM: ",null!==s.rpm_limit?s.rpm_limit:"Unlimited"]})]})}}],[]),er=[{name:"Team ID",label:"Team ID",isSearchable:!0,searchFn:async e=>ee&&0!==ee.length?ee.filter(t=>t.team_id.toLowerCase().includes(e.toLowerCase())||t.team_alias&&t.team_alias.toLowerCase().includes(e.toLowerCase())).map(e=>({label:`${e.team_alias||e.team_id} (${e.team_id})`,value:e.team_id})):[]},{name:"Organization ID",label:"Organization ID",isSearchable:!0,searchFn:async e=>et&&0!==et.length?et.filter(t=>t.organization_id?.toLowerCase().includes(e.toLowerCase())??!1).filter(e=>null!==e.organization_id&&void 0!==e.organization_id).map(e=>({label:`${e.organization_id||"Unknown"} (${e.organization_id})`,value:e.organization_id})):[]},{name:"Key Alias",label:"Key Alias",customComponent:K.PaginatedKeyAliasSelect},{name:"User ID",label:"User ID",isSearchable:!1},{name:"Key Hash",label:"Key Hash",isSearchable:!1}];console.log(`keys: ${JSON.stringify(H)}`);let en=(0,w.useReactTable)({data:Z,columns:el.filter(e=>"expander"!==e.id),columnResizeMode:"onChange",columnResizeDirection:"ltr",state:{sorting:n,pagination:d},onSortingChange:e=>{let t="function"==typeof e?e(n):e;if(console.log(`newSorting: ${JSON.stringify(t)}`),c(t),t&&t.length>0){let e=t[0],s=e.id,i=e.desc?"desc":"asc";console.log(`sortBy: ${s}, sortOrder: ${i}`),es({...Y,"Sort By":s,"Sort Order":i},!0),a?.(s,i)}},onPaginationChange:h,getCoreRowModel:(0,b.getCoreRowModel)(),getSortedRowModel:(0,b.getSortedRowModel)(),getPaginationRowModel:(0,b.getPaginationRowModel)(),enableSorting:!0,manualSorting:!1,manualPagination:!0,pageCount:Math.ceil(ei/d.pageSize)});o.default.useEffect(()=>{i&&c([{id:i.sortBy,desc:"desc"===i.sortOrder}])},[i]);let{pageIndex:eo,pageSize:ec}=en.getState().pagination,ed=Math.min((eo+1)*ec,ei),eu=`${eo*ec+1} - ${ed}`;return(0,t.jsx)("div",{className:"w-full h-full overflow-hidden",children:l?(0,t.jsx)(F.default,{keyId:l.token,onClose:()=>r(null),keyData:l,teams:ee,onDelete:J}):(0,t.jsxs)("div",{className:"border-b py-4 flex-1 overflow-hidden",children:[(0,t.jsx)("div",{className:"w-full mb-6",children:(0,t.jsx)(U.default,{options:er,onApplyFilters:es,initialValues:Y,onResetFilters:ea})}),(0,t.jsxs)("div",{className:"flex items-center justify-between w-full mb-4",children:[G||W?(0,t.jsx)(E.Skeleton.Node,{active:!0,style:{width:200,height:20}}):(0,t.jsxs)("span",{className:"inline-flex text-sm text-gray-700",children:["Showing ",eu," of ",ei," results"]}),(0,t.jsxs)("div",{className:"inline-flex items-center gap-2",children:[G||W?(0,t.jsx)(E.Skeleton.Node,{active:!0,style:{width:74,height:20}}):(0,t.jsxs)("span",{className:"text-sm text-gray-700",children:["Page ",eo+1," of ",en.getPageCount()]}),G||W?(0,t.jsx)(E.Skeleton.Button,{active:!0,size:"small",style:{width:84,height:30}}):(0,t.jsx)("button",{onClick:()=>en.previousPage(),disabled:G||W||!en.getCanPreviousPage(),className:"px-3 py-1 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Previous"}),G||W?(0,t.jsx)(E.Skeleton.Button,{active:!0,size:"small",style:{width:58,height:30}}):(0,t.jsx)("button",{onClick:()=>en.nextPage(),disabled:G||W||!en.getCanNextPage(),className:"px-3 py-1 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Next"})]})]}),(0,t.jsx)("div",{className:"h-[75vh] 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)(_.Table,{className:"[&_td]:py-0.5 [&_th]:py-1",style:{width:en.getCenterTotalSize()},children:[(0,t.jsx)(k.TableHead,{children:en.getHeaderGroups().map(e=>(0,t.jsx)(z.TableRow,{children:e.headers.map(e=>(0,t.jsx)(O.TableHeaderCell,{"data-header-id":e.id,className:`py-1 h-8 relative hover:bg-gray-50 ${"actions"===e.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]":""}`,style:{width:e.getSize(),position:"relative",cursor:e.column.getCanSort()?"pointer":"default"},onMouseEnter:()=>{let t=document.querySelector(`[data-header-id="${e.id}"] .resizer`);t&&(t.style.opacity="0.5")},onMouseLeave:()=>{let t=document.querySelector(`[data-header-id="${e.id}"] .resizer`);t&&!e.column.getIsResizing()&&(t.style.opacity="0")},onClick:e.column.getCanSort()?e.column.getToggleSortingHandler():void 0,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,w.flexRender)(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)(x.ChevronUpIcon,{className:"h-4 w-4 text-blue-500"}),desc:(0,t.jsx)(f.ChevronDownIcon,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,t.jsx)(y.SwitchVerticalIcon,{className:"h-4 w-4 text-gray-400"})}),(0,t.jsx)("div",{onDoubleClick:()=>e.column.resetSize(),onMouseDown:e.getResizeHandler(),onTouchStart:e.getResizeHandler(),className:`resizer ${en.options.columnResizeDirection} ${e.column.getIsResizing()?"isResizing":""}`,style:{position:"absolute",right:0,top:0,height:"100%",width:"5px",background:e.column.getIsResizing()?"#3b82f6":"transparent",cursor:"col-resize",userSelect:"none",touchAction:"none",opacity:+!!e.column.getIsResizing()}})]})},e.id))},e.id))}),(0,t.jsx)(N.TableBody,{children:G||W?(0,t.jsx)(z.TableRow,{children:(0,t.jsx)(C.TableCell,{colSpan:el.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:"🚅 Loading keys..."})})})}):Z.length>0?en.getRowModel().rows.map(e=>(0,t.jsx)(z.TableRow,{className:"h-8",children:e.getVisibleCells().map(e=>(0,t.jsx)(C.TableCell,{style:{width:e.column.getSize(),maxWidth:"8-x",whiteSpace:"pre-wrap",overflow:"hidden"},className:`py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap ${"models"===e.column.id&&Array.isArray(e.getValue())&&e.getValue().length>3?"px-0":""}`,children:(0,w.flexRender)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,t.jsx)(z.TableRow,{children:(0,t.jsx)(C.TableCell,{colSpan:el.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:"No keys found"})})})})})]})})})})]})})}e.s(["default",0,({userID:e,userRole:g,teams:m,keys:f,setUserRole:p,userEmail:x,setUserEmail:y,setTeams:w,setKeys:b,premiumUser:v,organizations:S,addKey:j,createClicked:_,autoOpenCreate:N,prefillData:C})=>{let k,[O,z]=(0,o.useState)(null),[P,I]=(0,o.useState)(null),D=(0,n.useSearchParams)(),E=(console.log("COOKIES",document.cookie),(k=document.cookie.split("; ").find(e=>e.startsWith("token=")))?k.split("=")[1]:null),T=D.get("invitation_id"),[M,R]=(0,o.useState)(null),[A,$]=(0,o.useState)(null),[L,K]=(0,o.useState)([]),[U,F]=(0,o.useState)(null),[V,H]=(0,o.useState)(null);if((0,o.useEffect)(()=>{let e=()=>{sessionStorage.clear()};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[]),(0,o.useEffect)(()=>{if(E){let e=(0,r.jwtDecode)(E);if(e){if(console.log("Decoded token:",e),console.log("Decoded key:",e.key),R(e.key),e.user_role){let t=function(e){if(!e)return"Undefined Role";switch(console.log(`Received user role: ${e}`),e.toLowerCase()){case"app_owner":case"demo_app_owner":return"App Owner";case"app_admin":case"proxy_admin":return"Admin";case"proxy_admin_viewer":return"Admin Viewer";case"app_user":return"App User";case"internal_user":return"Internal User";case"internal_user_viewer":return"Internal Viewer";default:return"Unknown Role"}}(e.user_role);console.log("Decoded user_role:",t),p(t)}else console.log("User role not defined");e.user_email?y(e.user_email):console.log(`User Email is not set ${e}`)}}if(e&&M&&g&&!f&&!O){let t=sessionStorage.getItem("userModels"+e);t?K(JSON.parse(t)):(console.log(`currentOrg: ${JSON.stringify(P)}`),(async()=>{try{let t=await (0,u.getProxyUISettings)(M);F(t);let s=await (0,u.userInfoCall)(M,e,g,!1,null,null);z(s.user_info),console.log(`userSpendData: ${JSON.stringify(O)}`),s?.teams[0].keys?b(s.keys.concat(s.teams.filter(t=>"Admin"===g||t.user_id===e).flatMap(e=>e.keys))):b(s.keys),sessionStorage.setItem("userData"+e,JSON.stringify(s.keys)),sessionStorage.setItem("userSpendData"+e,JSON.stringify(s.user_info));let a=(await (0,u.modelAvailableCall)(M,e,g)).data.map(e=>e.id);console.log("available_model_names:",a),K(a),console.log("userModels:",L),sessionStorage.setItem("userModels"+e,JSON.stringify(a))}catch(e){console.error("There was an error fetching the data",e),e.message.includes("Invalid proxy server token passed")&&G()}})(),(0,d.fetchTeams)(M,e,g,P,w))}},[e,E,M,f,g]),(0,o.useEffect)(()=>{M&&(async()=>{try{let e=await (0,u.keyInfoCall)(M,[M]);console.log("keyInfo: ",e)}catch(e){e.message.includes("Invalid proxy server token passed")&&G()}})()},[M]),(0,o.useEffect)(()=>{console.log(`currentOrg: ${JSON.stringify(P)}, accessToken: ${M}, userID: ${e}, userRole: ${g}`),M&&(console.log("fetching teams"),(0,d.fetchTeams)(M,e,g,P,w))},[P]),(0,o.useEffect)(()=>{if(null!==f&&null!=V&&null!==V.team_id){let e=0;for(let t of(console.log(`keys: ${JSON.stringify(f)}`),f))V.hasOwnProperty("team_id")&&null!==t.team_id&&t.team_id===V.team_id&&(e+=t.spend);console.log(`sum: ${e}`),$(e)}else if(null!==f){let e=0;for(let t of f)e+=t.spend;$(e)}},[V]),null!=T)return(0,t.jsx)(c.default,{});function G(){(0,s.clearTokenCookies)();let e=(0,u.getProxyBaseUrl)();console.log("proxyBaseUrl:",e);let t=e?`${e}/sso/key/generate`:"/sso/key/generate";return console.log("Full URL:",t),window.location.href=t,null}if(null==E)return console.log("All cookies before redirect:",document.cookie),G(),null;try{let e=(0,r.jwtDecode)(E);console.log("Decoded token:",e);let t=e.exp,s=Math.floor(Date.now()/1e3);if(t&&s>=t)return console.log("Token expired, redirecting to login"),G(),null}catch(e){return console.error("Error decoding token:",e),(0,s.clearTokenCookies)(),G(),null}if(null==M)return null;if(null==e)return(0,t.jsx)("h1",{children:"User ID is not set"});if(null==g&&p("App Owner"),g&&"Admin Viewer"==g){let{Title:e,Paragraph:s}=l.Typography;return(0,t.jsxs)("div",{children:[(0,t.jsx)(e,{level:1,children:"Access Denied"}),(0,t.jsx)(s,{children:"Ask your proxy admin for access to create keys"})]})}return console.log("inside user dashboard, selected team",V),console.log("All cookies after redirect:",document.cookie),(0,t.jsx)("div",{className:"w-full mx-4 h-[75vh]",children:(0,t.jsx)(i.Grid,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:(0,t.jsxs)(a.Col,{numColSpan:1,className:"flex flex-col gap-2",children:[(0,t.jsx)(h.default,{team:V,teams:m,data:f,addKey:j,autoOpenCreate:N,prefillData:C},V?V.team_id:null),(0,t.jsx)(B,{teams:m,organizations:S})]})})})}],693569)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/02765645e0bbd8f7.js b/litellm/proxy/_experimental/out/_next/static/chunks/02765645e0bbd8f7.js deleted file mode 100644 index a7da1a2598a..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/02765645e0bbd8f7.js +++ /dev/null @@ -1,29 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,822315,(e,t,n)=>{e.e,t.exports=function(){"use strict";var e="millisecond",t="second",n="minute",r="hour",i="week",o="month",l="quarter",s="year",a="date",c="Invalid Date",d=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,u=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,f=function(e,t,n){var r=String(e);return!r||r.length>=t?e:""+Array(t+1-r.length).join(n)+e},p="en",h={};h[p]={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(e){var t=["th","st","nd","rd"],n=e%100;return"["+e+(t[(n-20)%10]||t[n]||t[0])+"]"}};var g="$isDayjsObject",x=function(e){return e instanceof v||!(!e||!e[g])},m=function e(t,n,r){var i;if(!t)return p;if("string"==typeof t){var o=t.toLowerCase();h[o]&&(i=o),n&&(h[o]=n,i=o);var l=t.split("-");if(!i&&l.length>1)return e(l[0])}else{var s=t.name;h[s]=t,i=s}return!r&&i&&(p=i),i||!r&&p},y=function(e,t){if(x(e))return e.clone();var n="object"==typeof t?t:{};return n.date=e,n.args=arguments,new v(n)},b={s:f,z:function(e){var t=-e.utcOffset(),n=Math.abs(t);return(t<=0?"+":"-")+f(Math.floor(n/60),2,"0")+":"+f(n%60,2,"0")},m:function e(t,n){if(t.date(){"use strict";var t=e.i(843476),n=e.i(271645),r=e.i(135214);e.i(247167);var i=e.i(592968),o=e.i(981339),l=e.i(282786),s=e.i(998573),a=e.i(313603),c=e.i(646563),d=e.i(751904),u=e.i(44121),f=e.i(186515),p=e.i(928685),h=e.i(264843),g=e.i(477189),x=e.i(447566),m=e.i(755151),y=e.i(492030),b=e.i(918789);function v(e,t){let n=String(e);if("string"!=typeof t)throw TypeError("Expected character");let r=0,i=n.indexOf(t);for(;-1!==i;)r++,i=n.indexOf(t,i+t.length);return r}var k=e.i(420061),S=e.i(997803),j=e.i(733644),w=e.i(457579);let C="phrasing",z=["autolink","link","image","label"];function M(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function O(e){this.config.enter.autolinkProtocol.call(this,e)}function D(e){this.config.exit.autolinkProtocol.call(this,e)}function $(e){this.config.exit.data.call(this,e);let t=this.stack[this.stack.length-1];(0,k.ok)("link"===t.type),t.url="http://"+this.sliceSerialize(e)}function E(e){this.config.exit.autolinkEmail.call(this,e)}function L(e){this.exit(e)}function T(e){!function(e,t,n){let r=(0,w.convert)((n||{}).ignore||[]),i=function(e){let t=[];if(!Array.isArray(e))throw TypeError("Expected find and replace tuple or list of tuples");let n=!e[0]||Array.isArray(e[0])?e:[e],r=-1;for(;++r0?{type:"text",value:o}:void 0),!1===o?r.lastIndex=n+1:(s!==n&&d.push({type:"text",value:e.value.slice(s,n)}),Array.isArray(o)?d.push(...o):o&&d.push(o),s=n+u[0].length,c=!0),!r.global)break;u=r.exec(e.value)}return c?(s?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(")"),i=v(e,"("),o=v(e,")");for(;-1!==r&&i>o;)e+=n.slice(0,r+1),r=(n=n.slice(r+1)).indexOf(")"),o++;return[e,n]}(n+r);if(!s[0])return!1;let a={type:"link",title:null,url:l+t+s[0],children:[{type:"text",value:t+s[0]}]};return s[1]?[a,{type:"text",value:s[1]}]:a}function I(e,t,n,r){return!(!R(r,!0)||/[-\d_]$/.test(n))&&{type:"link",title:null,url:"mailto:"+t+"@"+n,children:[{type:"text",value:t+"@"+n}]}}function R(e,t){let n=e.input.charCodeAt(e.index-1);return(0===e.index||(0,S.unicodeWhitespace)(n)||(0,S.unicodePunctuation)(n))&&(!t||47!==n)}var F=e.i(431745);function W(){this.buffer()}function _(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function P(){this.buffer()}function H(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function B(e){let t=this.resume(),n=this.stack[this.stack.length-1];(0,k.ok)("footnoteReference"===n.type),n.identifier=(0,F.normalizeIdentifier)(this.sliceSerialize(e)).toLowerCase(),n.label=t}function N(e){this.exit(e)}function U(e){let t=this.resume(),n=this.stack[this.stack.length-1];(0,k.ok)("footnoteDefinition"===n.type),n.identifier=(0,F.normalizeIdentifier)(this.sliceSerialize(e)).toLowerCase(),n.label=t}function Y(e){this.exit(e)}function q(e,t,n,r){let i=n.createTracker(r),o=i.move("[^"),l=n.enter("footnoteReference"),s=n.enter("reference");return o+=i.move(n.safe(n.associationId(e),{after:"]",before:o})),s(),l(),o+=i.move("]")}function J(e,t,n){return 0===t?e:V(e,t,n)}function V(e,t,n){return(n?"":" ")+e}q.peek=function(){return"["};let K=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];function G(e){this.enter({type:"delete",children:[]},e)}function Z(e){this.exit(e)}function Q(e,t,n,r){let i=n.createTracker(r),o=n.enter("strikethrough"),l=i.move("~~");return l+=n.containerPhrasing(e,{...i.current(),before:l,after:"~"}),l+=i.move("~~"),o(),l}function X(e){return e.length}function ee(e){let t="string"==typeof e?e.codePointAt(0):0;return 67===t||99===t?99:76===t||108===t?108:114*(82===t||114===t)}Q.peek=function(){return"~"};var et=e.i(682523);e.i(784801);e.i(900065);function en(e,t,n){let r=e.value||"",i="`",o=-1;for(;RegExp("(^|[^`])"+i+"([^`]|$)").test(r);)i+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=" "+r+" ");++o-1?t.start:1)+(!1===n.options.incrementListMarker?0:t.children.indexOf(e))+o);let l=o.length+1;("tab"===i||"mixed"===i&&(t&&"list"===t.type&&t.spread||e.spread))&&(l=4*Math.ceil(l/4));let s=n.createTracker(r);s.move(o+" ".repeat(l-o.length)),s.shift(l);let a=n.enter("listItem"),c=n.indentLines(n.containerFlow(e,s.current()),function(e,t,n){return t?(n?"":" ".repeat(l))+e:(n?o:o+" ".repeat(l-o.length))+e});return a(),c};function ei(e){let t=e._align;(0,k.ok)(t,"expected `_align` on table"),this.enter({type:"table",align:t.map(function(e){return"none"===e?null:e}),children:[]},e),this.data.inTable=!0}function eo(e){this.exit(e),this.data.inTable=void 0}function el(e){this.enter({type:"tableRow",children:[]},e)}function es(e){this.exit(e)}function ea(e){this.enter({type:"tableCell",children:[]},e)}function ec(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,ed));let n=this.stack[this.stack.length-1];(0,k.ok)("inlineCode"===n.type),n.value=t,this.exit(e)}function ed(e,t){return"|"===t?t:e}function eu(e){let t=this.stack[this.stack.length-2];(0,k.ok)("listItem"===t.type),t.checked="taskListCheckValueChecked"===e.type}function ef(e){let t=this.stack[this.stack.length-2];if(t&&"listItem"===t.type&&"boolean"==typeof t.checked){let e=this.stack[this.stack.length-1];(0,k.ok)("paragraph"===e.type);let n=e.children[0];if(n&&"text"===n.type){let r,i=t.children,o=-1;for(;++o0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}ej[43]=eS,ej[45]=eS,ej[46]=eS,ej[95]=eS,ej[72]=[eS,ek],ej[104]=[eS,ek],ej[87]=[eS,ev],ej[119]=[eS,ev];var e$=e.i(653161),eE=e.i(204108);let eL={tokenize:function(e,t,n){let r=this;return(0,eE.factorySpace)(e,function(e){let i=r.events[r.events.length-1];return i&&"gfmFootnoteDefinitionIndent"===i[1].type&&4===i[2].sliceSerialize(i[1],!0).length?t(e):n(e)},"gfmFootnoteDefinitionIndent",5)},partial:!0};function eT(e,t,n){let r,i=this,o=i.events.length,l=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);for(;o--;){let e=i.events[o][1];if("labelImage"===e.type){r=e;break}if("gfmFootnoteCall"===e.type||"labelLink"===e.type||"label"===e.type||"image"===e.type||"link"===e.type)break}return function(o){if(!r||!r._balanced)return n(o);let s=(0,F.normalizeIdentifier)(i.sliceSerialize({start:r.end,end:i.now()}));return 94===s.codePointAt(0)&&l.includes(s.slice(1))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(o),e.exit("gfmFootnoteCallLabelMarker"),t(o)):n(o)}}function eA(e,t){let n=e.length;for(;n--;)if("labelImage"===e[n][1].type&&"enter"===e[n][0]){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";let r={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;let o={type:"gfmFootnoteCallString",start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},l={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},s=[e[n+1],e[n+2],["enter",r,t],e[n+3],e[n+4],["enter",i,t],["exit",i,t],["enter",o,t],["enter",l,t],["exit",l,t],["exit",o,t],e[e.length-2],e[e.length-1],["exit",r,t]];return e.splice(n,e.length-n+1,...s),e}function eI(e,t,n){let r,i=this,o=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]),l=0;return function(t){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(t),e.exit("gfmFootnoteCallLabelMarker"),s};function s(t){return 94!==t?n(t):(e.enter("gfmFootnoteCallMarker"),e.consume(t),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",a)}function a(s){if(l>999||93===s&&!r||null===s||91===s||(0,S.markdownLineEndingOrSpace)(s))return n(s);if(93===s){e.exit("chunkString");let r=e.exit("gfmFootnoteCallString");return o.includes((0,F.normalizeIdentifier)(i.sliceSerialize(r)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(s),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(s)}return(0,S.markdownLineEndingOrSpace)(s)||(r=!0),l++,e.consume(s),92===s?c:a}function c(t){return 91===t||92===t||93===t?(e.consume(t),l++,a):a(t)}}function eR(e,t,n){let r,i,o=this,l=o.parser.gfmFootnotes||(o.parser.gfmFootnotes=[]),s=0;return function(t){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(t),e.exit("gfmFootnoteDefinitionLabelMarker"),a};function a(t){return 94===t?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(t),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",c):n(t)}function c(t){if(s>999||93===t&&!i||null===t||91===t||(0,S.markdownLineEndingOrSpace)(t))return n(t);if(93===t){e.exit("chunkString");let n=e.exit("gfmFootnoteDefinitionLabelString");return r=(0,F.normalizeIdentifier)(o.sliceSerialize(n)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(t),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),u}return(0,S.markdownLineEndingOrSpace)(t)||(i=!0),s++,e.consume(t),92===t?d:c}function d(t){return 91===t||92===t||93===t?(e.consume(t),s++,c):c(t)}function u(t){return 58===t?(e.enter("definitionMarker"),e.consume(t),e.exit("definitionMarker"),l.includes(r)||l.push(r),(0,eE.factorySpace)(e,f,"gfmFootnoteDefinitionWhitespace")):n(t)}function f(e){return t(e)}}function eF(e,t,n){return e.check(e$.blankLine,t,e.attempt(eL,t,n))}function eW(e){e.exit("gfmFootnoteDefinition")}var e_=e.i(938402),eP=e.i(810291);class eH{constructor(){this.map=[]}add(e,t,n){!function(e,t,n,r){let i=0;if(0!==n||0!==r.length){for(;i0;)t-=1,n.push(e.slice(this.map[t][0]+this.map[t][1]),this.map[t][2]),e.length=this.map[t][0];n.push(e.slice()),e.length=0;let r=n.pop();for(;r;){for(let t of r)e.push(t);r=n.pop()}this.map.length=0}}function eB(e,t,n){let r,i=this,o=0,l=0;return function(e){let t=i.events.length-1;for(;t>-1;){let e=i.events[t][1].type;if("lineEnding"===e||"linePrefix"===e)t--;else break}let r=t>-1?i.events[t][1].type:null,o="tableHead"===r||"tableRow"===r?y:s;return o===y&&i.parser.lazy[i.now().line]?n(e):o(e)};function s(t){var n;return e.enter("tableHead"),e.enter("tableRow"),124===(n=t)||(r=!0,l+=1),a(n)}function a(t){return null===t?n(t):(0,S.markdownLineEnding)(t)?l>1?(l=0,i.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),u):n(t):(0,S.markdownSpace)(t)?(0,eE.factorySpace)(e,a,"whitespace")(t):(l+=1,r&&(r=!1,o+=1),124===t)?(e.enter("tableCellDivider"),e.consume(t),e.exit("tableCellDivider"),r=!0,a):(e.enter("data"),c(t))}function c(t){return null===t||124===t||(0,S.markdownLineEndingOrSpace)(t)?(e.exit("data"),a(t)):(e.consume(t),92===t?d:c)}function d(t){return 92===t||124===t?(e.consume(t),c):c(t)}function u(t){return(i.interrupt=!1,i.parser.lazy[i.now().line])?n(t):(e.enter("tableDelimiterRow"),r=!1,(0,S.markdownSpace)(t))?(0,eE.factorySpace)(e,f,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(t):f(t)}function f(t){return 45===t||58===t?h(t):124===t?(r=!0,e.enter("tableCellDivider"),e.consume(t),e.exit("tableCellDivider"),p):n(t)}function p(t){return(0,S.markdownSpace)(t)?(0,eE.factorySpace)(e,h,"whitespace")(t):h(t)}function h(t){return 58===t?(l+=1,r=!0,e.enter("tableDelimiterMarker"),e.consume(t),e.exit("tableDelimiterMarker"),g):45===t?(l+=1,g(t)):null===t||(0,S.markdownLineEnding)(t)?m(t):n(t)}function g(t){return 45===t?(e.enter("tableDelimiterFiller"),function t(n){return 45===n?(e.consume(n),t):58===n?(r=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(n),e.exit("tableDelimiterMarker"),x):(e.exit("tableDelimiterFiller"),x(n))}(t)):n(t)}function x(t){return(0,S.markdownSpace)(t)?(0,eE.factorySpace)(e,m,"whitespace")(t):m(t)}function m(i){if(124===i)return f(i);if(null===i||(0,S.markdownLineEnding)(i))return r&&o===l?(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(i)):n(i);return n(i)}function y(t){return e.enter("tableRow"),b(t)}function b(n){return 124===n?(e.enter("tableCellDivider"),e.consume(n),e.exit("tableCellDivider"),b):null===n||(0,S.markdownLineEnding)(n)?(e.exit("tableRow"),t(n)):(0,S.markdownSpace)(n)?(0,eE.factorySpace)(e,b,"whitespace")(n):(e.enter("data"),v(n))}function v(t){return null===t||124===t||(0,S.markdownLineEndingOrSpace)(t)?(e.exit("data"),b(t)):(e.consume(t),92===t?k:v)}function k(t){return 92===t||124===t?(e.consume(t),v):v(t)}}function eN(e,t){let n,r,i,o=-1,l=!0,s=0,a=[0,0,0,0],c=[0,0,0,0],d=!1,u=0,f=new eH;for(;++on[2]+1){let t=n[2]+1,r=n[3]-n[2]-1;e.add(t,r,[])}}e.add(n[3]+1,0,[["exit",l,t]])}return void 0!==i&&(o.end=Object.assign({},eq(t.events,i)),e.add(i,0,[["exit",o,t]]),o=void 0),o}function eY(e,t,n,r,i){let o=[],l=eq(t.events,n);i&&(i.end=Object.assign({},l),o.push(["exit",i,t])),r.end=Object.assign({},l),o.push(["exit",r,t]),e.add(n+1,0,o)}function eq(e,t){let n=e[t],r="enter"===n[0]?"start":"end";return n[1][r]}let eJ={name:"tasklistCheck",tokenize:function(e,t,n){let r=this;return function(t){return null===r.previous&&r._gfmTasklistFirstContentOfListItem?(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(t),e.exit("taskListCheckMarker"),i):n(t)};function i(t){return(0,S.markdownLineEndingOrSpace)(t)?(e.enter("taskListCheckValueUnchecked"),e.consume(t),e.exit("taskListCheckValueUnchecked"),o):88===t||120===t?(e.enter("taskListCheckValueChecked"),e.consume(t),e.exit("taskListCheckValueChecked"),o):n(t)}function o(t){return 93===t?(e.enter("taskListCheckMarker"),e.consume(t),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),l):n(t)}function l(r){return(0,S.markdownLineEnding)(r)?t(r):(0,S.markdownSpace)(r)?e.check({tokenize:eV},t,n)(r):n(r)}}};function eV(e,t,n){return(0,eE.factorySpace)(e,function(e){return null===e?n(e):t(e)},"whitespace")}let eK={};function eG(e){var t;let n,r,i,o=e||eK,l=this.data(),s=l.micromarkExtensions||(l.micromarkExtensions=[]),a=l.fromMarkdownExtensions||(l.fromMarkdownExtensions=[]),c=l.toMarkdownExtensions||(l.toMarkdownExtensions=[]);s.push((t=o,(0,eh.combineExtensions)([{text:ej},{document:{91:{name:"gfmFootnoteDefinition",tokenize:eR,continuation:{tokenize:eF},exit:eW}},text:{91:{name:"gfmFootnoteCall",tokenize:eI},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:eT,resolveTo:eA}}},(n=(t||{}).singleTilde,r={name:"strikethrough",tokenize:function(e,t,r){let i=this.previous,o=this.events,l=0;return function(s){return 126===i&&"characterEscape"!==o[o.length-1][1].type?r(s):(e.enter("strikethroughSequenceTemporary"),function o(s){let a=(0,et.classifyCharacter)(i);if(126===s)return l>1?r(s):(e.consume(s),l++,o);if(l<2&&!n)return r(s);let c=e.exit("strikethroughSequenceTemporary"),d=(0,et.classifyCharacter)(s);return c._open=!d||2===d&&!!a,c._close=!a||2===a&&!!d,t(s)}(s))}},resolveAll:function(e,t){let n=-1;for(;++n0&&(o.shift(4),l+=o.move((i?"\n":" ")+n.indentLines(n.containerFlow(e,o.current()),i?V:J))),s(),l},footnoteReference:q},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]}),{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:K}],handlers:{delete:Q}},function(e){let t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,i=t.stringLength,o=n?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:"\n",inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:function(e,t,n){let r=en(e,t,n);return n.stack.includes("tableCell")&&(r=r.replace(/\|/g,"\\$&")),r},table:function(e,t,n,r){return s(function(e,t,n){let r=e.children,i=-1,o=[],l=t.enter("table");for(;++ic&&(c=e[d].length);++oa[o])&&(a[o]=e)}t.push(l)}l[d]=t,s[d]=r}let f=-1;if("object"==typeof r&&"length"in r)for(;++fa[f]&&(a[f]=i),h[f]=i),p[f]=l}l.splice(1,0,p),s.splice(1,0,h),d=-1;let g=[];for(;++dt.updatedAt-e.updatedAt).slice(0,100)}var e0=e.i(464571),e1=e.i(311451),e2=e.i(212931),e4=e.i(883552),e5=e.i(343794),e6=e.i(430073),e3=e.i(611935),e8=e.i(908206),e7=e.i(242064),e9=e.i(321883),te=e.i(517455),tt=e.i(150073);let tn=n.createContext({});e.i(296059);var tr=e.i(915654),ti=e.i(183293),to=e.i(246422),tl=e.i(838378);let ts=(0,to.genStyleHooks)("Avatar",e=>{let{colorTextLightSolid:t,colorTextPlaceholder:n}=e,r=(0,tl.mergeToken)(e,{avatarBg:n,avatarColor:t});return[(e=>{let{antCls:t,componentCls:n,iconCls:r,avatarBg:i,avatarColor:o,containerSize:l,containerSizeLG:s,containerSizeSM:a,textFontSize:c,textFontSizeLG:d,textFontSizeSM:u,iconFontSize:f,iconFontSizeLG:p,iconFontSizeSM:h,borderRadius:g,borderRadiusLG:x,borderRadiusSM:m,lineWidth:y,lineType:b}=e,v=(e,t,i,o)=>({width:e,height:e,borderRadius:"50%",fontSize:t,[`&${n}-square`]:{borderRadius:o},[`&${n}-icon`]:{fontSize:i,[`> ${r}`]:{margin:0}}});return{[n]:Object.assign(Object.assign(Object.assign(Object.assign({},(0,ti.resetComponent)(e)),{position:"relative",display:"inline-flex",justifyContent:"center",alignItems:"center",overflow:"hidden",color:o,whiteSpace:"nowrap",textAlign:"center",verticalAlign:"middle",background:i,border:`${(0,tr.unit)(y)} ${b} transparent`,"&-image":{background:"transparent"},[`${t}-image-img`]:{display:"block"}}),v(l,c,f,g)),{"&-lg":Object.assign({},v(s,d,p,x)),"&-sm":Object.assign({},v(a,u,h,m)),"> img":{display:"block",width:"100%",height:"100%",objectFit:"cover"}})}})(r),(e=>{let{componentCls:t,groupBorderColor:n,groupOverlapping:r,groupSpace:i}=e;return{[`${t}-group`]:{display:"inline-flex",[t]:{borderColor:n},"> *:not(:first-child)":{marginInlineStart:r}},[`${t}-group-popover`]:{[`${t} + ${t}`]:{marginInlineStart:i}}}})(r)]},e=>{let{controlHeight:t,controlHeightLG:n,controlHeightSM:r,fontSize:i,fontSizeLG:o,fontSizeXL:l,fontSizeHeading3:s,marginXS:a,marginXXS:c,colorBorderBg:d}=e;return{containerSize:t,containerSizeLG:n,containerSizeSM:r,textFontSize:i,textFontSizeLG:i,textFontSizeSM:i,iconFontSize:Math.round((o+l)/2),iconFontSizeLG:s,iconFontSizeSM:i,groupSpace:c,groupOverlapping:-a,groupBorderColor:d}});var ta=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,r=Object.getOwnPropertySymbols(e);it.indexOf(r[i])&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n};let tc=n.forwardRef((e,t)=>{let r,{prefixCls:i,shape:o,size:l,src:s,srcSet:a,icon:c,className:d,rootClassName:u,style:f,alt:p,draggable:h,children:g,crossOrigin:x,gap:m=4,onError:y}=e,b=ta(e,["prefixCls","shape","size","src","srcSet","icon","className","rootClassName","style","alt","draggable","children","crossOrigin","gap","onError"]),[v,k]=n.useState(1),[S,j]=n.useState(!1),[w,C]=n.useState(!0),z=n.useRef(null),M=n.useRef(null),O=(0,e3.composeRef)(t,z),{getPrefixCls:D,avatar:$}=n.useContext(e7.ConfigContext),E=n.useContext(tn),L=()=>{if(!M.current||!z.current)return;let e=M.current.offsetWidth,t=z.current.offsetWidth;0!==e&&0!==t&&2*m{j(!0)},[]),n.useEffect(()=>{C(!0),k(1)},[s]),n.useEffect(L,[m]);let T=(0,te.default)(e=>{var t,n;return null!=(n=null!=(t=null!=l?l:null==E?void 0:E.size)?t:e)?n:"default"}),A=Object.keys("object"==typeof T&&T||{}).some(e=>["xs","sm","md","lg","xl","xxl"].includes(e)),I=(0,tt.default)(A),R=n.useMemo(()=>{if("object"!=typeof T)return{};let e=T[e8.responsiveArray.find(e=>I[e])];return e?{width:e,height:e,fontSize:e&&(c||g)?e/2:18}:{}},[I,T,c,g]),F=D("avatar",i),W=(0,e9.default)(F),[_,P,H]=ts(F,W),B=(0,e5.default)({[`${F}-lg`]:"large"===T,[`${F}-sm`]:"small"===T}),N=n.isValidElement(s),U=o||(null==E?void 0:E.shape)||"circle",Y=(0,e5.default)(F,B,null==$?void 0:$.className,`${F}-${U}`,{[`${F}-image`]:N||s&&w,[`${F}-icon`]:!!c},H,W,d,u,P),q="number"==typeof T?{width:T,height:T,fontSize:c?T/2:18}:{};if("string"==typeof s&&w)r=n.createElement("img",{src:s,draggable:h,srcSet:a,onError:()=>{!1!==(null==y?void 0:y())&&C(!1)},alt:p,crossOrigin:x});else if(N)r=s;else if(c)r=c;else if(S||1!==v){let e=`scale(${v})`;r=n.createElement(e6.default,{onResize:L},n.createElement("span",{className:`${F}-string`,ref:M,style:{msTransform:e,WebkitTransform:e,transform:e}},g))}else r=n.createElement("span",{className:`${F}-string`,style:{opacity:0},ref:M},g);return _(n.createElement("span",Object.assign({},b,{style:Object.assign(Object.assign(Object.assign(Object.assign({},q),R),null==$?void 0:$.style),f),className:Y,ref:O}),r))});var td=e.i(876556),tu=e.i(763731),tf=e.i(829672);let tp=e=>{let{size:t,shape:r}=n.useContext(tn),i=n.useMemo(()=>({size:e.size||t,shape:e.shape||r}),[e.size,e.shape,t,r]);return n.createElement(tn.Provider,{value:i},e.children)};tc.Group=e=>{var t,r,i,o;let{getPrefixCls:l,direction:s}=n.useContext(e7.ConfigContext),{prefixCls:a,className:c,rootClassName:d,style:u,maxCount:f,maxStyle:p,size:h,shape:g,maxPopoverPlacement:x,maxPopoverTrigger:m,children:y,max:b}=e,v=l("avatar",a),k=`${v}-group`,S=(0,e9.default)(v),[j,w,C]=ts(v,S),z=(0,e5.default)(k,{[`${k}-rtl`]:"rtl"===s},C,S,c,d,w),M=(0,td.default)(y).map((e,t)=>(0,tu.cloneElement)(e,{key:`avatar-key-${t}`})),O=(null==b?void 0:b.count)||f,D=M.length;if(O&&O{let t=(0,tm.default)(),n=(0,tm.default)(e);return n.isSame(t,"day")?"Today":n.isSame(t.subtract(1,"day"),"day")?"Yesterday":n.isAfter(t.subtract(7,"day"))?"Last 7 Days":"Older"},tv=["Today","Yesterday","Last 7 Days","Older"],tk=({conv:e,isActive:r,onSelect:o,onDelete:l,onRename:s})=>{let[a,c]=(0,n.useState)(!1),[u,f]=(0,n.useState)(e.title),p=(0,n.useRef)(null);(0,n.useEffect)(()=>{a&&p.current&&(p.current.focus(),p.current.select())},[a]);let h=()=>{let t=u.trim();t&&t!==e.title&&s(e.id,t),c(!1)},g=e.title.length>40?e.title.slice(0,40)+"…":e.title;return(0,t.jsx)("div",{onClick:()=>!a&&o(e.id),className:"conversation-row group",style:{display:"flex",alignItems:"center",padding:"6px 8px",borderRadius:6,cursor:a?"default":"pointer",backgroundColor:r?"#e6f4ff":"transparent",transition:"background-color 0.15s",minHeight:34,position:"relative"},onMouseEnter:e=>{r||(e.currentTarget.style.backgroundColor="#f5f5f5")},onMouseLeave:e=>{r||(e.currentTarget.style.backgroundColor="transparent")},children:a?(0,t.jsx)(e1.Input,{ref:e=>{p.current=e?.input??null},size:"small",value:u,onChange:e=>f(e.target.value),onKeyDown:t=>{"Enter"===t.key?(t.preventDefault(),h()):"Escape"===t.key&&(t.preventDefault(),f(e.title),c(!1))},onBlur:h,onClick:e=>e.stopPropagation(),style:{flex:1,fontSize:13}}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(ty,{style:{flex:1,fontSize:13,color:r?"#1677ff":"#333",overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",fontWeight:r?500:400},title:e.title,children:g}),(0,t.jsxs)("div",{className:"conversation-actions",style:{display:"flex",gap:2,opacity:0,transition:"opacity 0.15s",flexShrink:0},onClick:e=>e.stopPropagation(),children:[(0,t.jsx)(i.Tooltip,{title:"Rename",children:(0,t.jsx)(e0.Button,{type:"text",size:"small",icon:(0,t.jsx)(d.EditOutlined,{style:{fontSize:12}}),onClick:t=>{t.stopPropagation(),f(e.title),c(!0)},style:{width:22,height:22,padding:0,minWidth:22}})}),(0,t.jsx)(e4.Popconfirm,{title:"Delete this conversation?",onConfirm:()=>l(e.id),okText:"Delete",cancelText:"Cancel",okButtonProps:{danger:!0},children:(0,t.jsx)(i.Tooltip,{title:"Delete",children:(0,t.jsx)(e0.Button,{type:"text",size:"small",danger:!0,icon:(0,t.jsx)(tg.DeleteOutlined,{style:{fontSize:12}}),style:{width:22,height:22,padding:0,minWidth:22}})})})]})]})})},tS=({open:e,conversations:r,onSelect:i,onClose:o})=>{let[l,s]=(0,n.useState)("");(0,n.useEffect)(()=>{e||s("")},[e]);let a=l.trim()?r.filter(e=>e.title.toLowerCase().includes(l.trim().toLowerCase())):r;return(0,t.jsxs)(e2.Modal,{open:e,onCancel:o,footer:null,title:null,width:480,styles:{body:{padding:"16px 16px 8px"}},children:[(0,t.jsx)(e1.Input,{autoFocus:!0,prefix:(0,t.jsx)(p.SearchOutlined,{style:{color:"#bbb"}}),placeholder:"Search conversations…",value:l,onChange:e=>s(e.target.value),style:{marginBottom:12},allowClear:!0}),(0,t.jsx)("div",{style:{maxHeight:320,overflowY:"auto"},children:0===a.length?(0,t.jsx)("div",{style:{textAlign:"center",padding:"24px 0",color:"#999"},children:"No conversations found"}):a.map(e=>{let n=e.title.length>55?e.title.slice(0,55)+"…":e.title;return(0,t.jsxs)("div",{onClick:()=>{i(e.id),o()},style:{display:"flex",alignItems:"center",gap:8,padding:"8px 10px",borderRadius:6,cursor:"pointer",transition:"background-color 0.1s"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor="#f0f5ff"},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="transparent"},children:[(0,t.jsx)(h.MessageOutlined,{style:{color:"#999",flexShrink:0}}),(0,t.jsx)(ty,{style:{fontSize:13},children:n}),(0,t.jsx)(ty,{type:"secondary",style:{fontSize:11,marginLeft:"auto",flexShrink:0},children:(0,tm.default)(e.updatedAt).format("MMM D")})]},e.id)})})]})},tj=({conversations:e,activeConversationId:r,onSelect:o,onDelete:l,onNewChat:s,onRename:a})=>{let[d,u]=(0,n.useState)(!1),f=(0,n.useCallback)(e=>{"k"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),u(e=>!e))},[]);(0,n.useEffect)(()=>(document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)),[f]);let p=(e=>{let t=new Map;for(let n of e){let e=tb(n.updatedAt);t.has(e)||t.set(e,[]),t.get(e).push(n)}return tv.filter(e=>t.has(e)).map(e=>({group:e,items:t.get(e)}))})(e);return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("style",{children:` - .conversation-row:hover .conversation-actions { - opacity: 1 !important; - } - `}),(0,t.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",width:"100%",overflow:"hidden"},children:[(0,t.jsx)("div",{style:{padding:"12px 10px 8px"},children:(0,t.jsx)(i.Tooltip,{title:"Chats are saved locally in this browser. All requests are logged in Spend → Logs.",placement:"right",children:(0,t.jsx)(e0.Button,{type:"primary",icon:(0,t.jsx)(c.PlusOutlined,{}),onClick:s,style:{width:"100%"},children:"New Chat"})})}),(0,t.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"0 6px"},children:0===p.length?(0,t.jsxs)("div",{style:{textAlign:"center",color:"#bbb",fontSize:12,marginTop:32,padding:"0 12px"},children:["No conversations yet.",(0,t.jsx)("br",{}),"Start a new chat above."]}):p.map(({group:e,items:n})=>(0,t.jsxs)("div",{style:{marginBottom:8},children:[(0,t.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"#999",textTransform:"uppercase",letterSpacing:"0.04em",padding:"8px 8px 4px"},children:e}),n.map(e=>(0,t.jsx)(tk,{conv:e,isActive:e.id===r,onSelect:o,onDelete:l,onRename:a},e.id))]},e))}),(0,t.jsxs)("div",{style:{padding:"10px 12px",borderTop:"1px solid #f0f0f0",display:"flex",alignItems:"center",gap:8},children:[(0,t.jsx)(tc,{size:28,icon:(0,t.jsx)(tx.UserOutlined,{}),style:{backgroundColor:"#e0e7ff",color:"#4f46e5",flexShrink:0}}),(0,t.jsx)(ty,{style:{fontSize:13,color:"#555",overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"},children:"My Account"})]})]}),(0,t.jsx)(tS,{open:d,conversations:e,onSelect:o,onClose:()=>u(!1)})]})};var tw=e.i(366308),tC=e.i(166406),tz=e.i(362024),tM=e.i(650056),tO=e.i(219470),tD=e.i(966988);let{Panel:t$}=tz.Collapse,tE=/token|key|secret|password|auth/i;function tL(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0");return`${n}:${r}`}function tT({node:e,className:n,children:r,...i}){let o=/language-(\w+)/.exec(n||"");return o?(0,t.jsx)(tM.Prism,{style:tO.coy,language:o[1],PreTag:"div",className:"rounded-md my-2",...i,children:String(r).replace(/\n$/,"")}):(0,t.jsx)("code",{className:`${n??""} px-1.5 py-0.5 rounded bg-gray-100 text-sm font-mono`,...i,children:r})}function tA({message:e,onEdit:r,isStreaming:o}){let[l,s]=(0,n.useState)(!1),[a,c]=(0,n.useState)(!1),[u,f]=(0,n.useState)(e.content),p=(0,n.useRef)(null);(0,n.useEffect)(()=>{a&&p.current&&(p.current.focus(),p.current.selectionStart=p.current.value.length)},[a]),(0,n.useEffect)(()=>{let e=p.current;e&&(e.style.height="auto",e.style.height=`${e.scrollHeight}px`)},[u,a]);let h=()=>{let t=u.trim();t&&t!==e.content&&r&&r(e.id,t),c(!1)};return a?(0,t.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end"},children:(0,t.jsxs)("div",{style:{width:"72%",background:"#fff",border:"1.5px solid #1677ff",borderRadius:12,overflow:"hidden",boxShadow:"0 0 0 3px rgba(22,119,255,0.1)"},children:[(0,t.jsx)("textarea",{ref:p,value:u,onChange:e=>f(e.target.value),onKeyDown:t=>{"Enter"!==t.key||t.shiftKey||(t.preventDefault(),h()),"Escape"===t.key&&(f(e.content),c(!1))},style:{width:"100%",padding:"10px 14px",border:"none",outline:"none",resize:"none",fontSize:14,lineHeight:"1.6",color:"#111827",fontFamily:"inherit",background:"transparent",boxSizing:"border-box",minHeight:40}}),(0,t.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,padding:"6px 10px 8px",borderTop:"1px solid #f0f0f0"},children:[(0,t.jsx)("button",{onClick:()=>{f(e.content),c(!1)},style:{padding:"4px 12px",borderRadius:6,border:"1px solid #d1d5db",background:"#fff",color:"#374151",fontSize:13,cursor:"pointer"},children:"Cancel"}),(0,t.jsx)("button",{onClick:h,disabled:!u.trim(),style:{padding:"4px 12px",borderRadius:6,border:"none",background:u.trim()?"#1677ff":"#f3f4f6",color:u.trim()?"#fff":"#9ca3af",fontSize:13,fontWeight:500,cursor:u.trim()?"pointer":"not-allowed"},children:"Save & Send"})]})]})}):(0,t.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",width:"100%"},onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),children:[(0,t.jsxs)("div",{style:{display:"flex",alignItems:"flex-end",gap:6,maxWidth:"72%"},children:[l&&!o&&r&&(0,t.jsx)(i.Tooltip,{title:"Edit message",children:(0,t.jsx)("button",{onClick:()=>{f(e.content),c(!0)},style:{background:"none",border:"none",cursor:"pointer",padding:"4px 6px",borderRadius:5,color:"#9ca3af",fontSize:13,flexShrink:0,display:"flex",alignItems:"center",transition:"color 0.15s"},onMouseEnter:e=>{e.currentTarget.style.color="#6b7280"},onMouseLeave:e=>{e.currentTarget.style.color="#9ca3af"},children:(0,t.jsx)(d.EditOutlined,{})})}),(0,t.jsx)("div",{style:{backgroundColor:"#f0f2f5",borderRadius:16,padding:"10px 14px",fontSize:14,lineHeight:"1.6",whiteSpace:"pre-wrap",wordBreak:"break-word",color:"#111827"},children:e.content})]}),(0,t.jsx)("span",{style:{fontSize:11,color:"#9ca3af",marginTop:4},children:tL(e.timestamp)})]})}function tI({message:e,isLastMessage:r,isStreaming:i,isTypingIndicator:o}){let l=(0,n.useRef)(0),s=(0,n.useRef)(i);(0,n.useEffect)(()=>{s.current&&!i&&(l.current+=1),s.current=i},[i]);let a=r&&i&&!e.reasoningContent,c=!!e.reasoningContent||a;if(o)return(0,t.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start"},children:(0,t.jsx)("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"10px 4px"},children:(0,t.jsx)(tW,{})})});let d=e.content,u=!1;return d.endsWith("[stopped]")&&(d=d.slice(0,-9),u=!0),(0,t.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",maxWidth:"80%"},children:[c&&(a?(0,t.jsx)(tF,{}):(0,t.jsx)(tD.default,{reasoningContent:e.reasoningContent},l.current)),(0,t.jsxs)("div",{style:{fontSize:14,lineHeight:"1.7",color:"#111827",wordBreak:"break-word"},children:[(0,t.jsx)(b.default,{remarkPlugins:[eG],components:{code:tT},children:d}),u&&(0,t.jsx)("span",{style:{color:"#9ca3af",fontStyle:"italic"},children:" [stopped]"})]}),(0,t.jsx)(tR,{text:d})]})}function tR({text:e}){let[r,o]=(0,n.useState)(!1);return(0,t.jsx)("div",{style:{display:"flex",alignItems:"center",gap:4,marginTop:6},children:(0,t.jsx)(i.Tooltip,{title:r?"Copied!":"Copy",children:(0,t.jsx)("button",{onClick:()=>{navigator.clipboard.writeText(e).then(()=>{o(!0),setTimeout(()=>o(!1),2e3)}).catch(()=>{})},style:{background:"none",border:"none",cursor:"pointer",padding:"4px 6px",borderRadius:5,color:r?"#52c41a":"#9ca3af",fontSize:13,display:"flex",alignItems:"center",gap:4,transition:"color 0.15s"},onMouseEnter:e=>{r||(e.currentTarget.style.color="#6b7280")},onMouseLeave:e=>{r||(e.currentTarget.style.color="#9ca3af")},children:r?(0,t.jsx)(y.CheckOutlined,{}):(0,t.jsx)(tC.CopyOutlined,{})})})})}function tF(){return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("style",{children:` - @keyframes thinking-pulse { - 0%, 100% { opacity: 0.4; } - 50% { opacity: 1; } - } - .chat-thinking-text { - animation: thinking-pulse 1.4s ease-in-out infinite; - } - `}),(0,t.jsx)("div",{style:{display:"inline-flex",alignItems:"center",gap:6,padding:"4px 10px",marginBottom:8,backgroundColor:"#f9fafb",border:"1px solid #e5e7eb",borderRadius:8,fontSize:12,color:"#6b7280"},children:(0,t.jsx)("span",{className:"chat-thinking-text",children:"Thinking..."})})]})}function tW(){return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("style",{children:` - @keyframes chat-typing-bounce { - 0%, 60%, 100% { transform: translateY(0); opacity: 0.4; } - 30% { transform: translateY(-4px); opacity: 1; } - } - .chat-dot { - width: 7px; - height: 7px; - border-radius: 50%; - background-color: #9ca3af; - animation: chat-typing-bounce 1.2s ease-in-out infinite; - } - .chat-dot:nth-child(2) { animation-delay: 0.2s; } - .chat-dot:nth-child(3) { animation-delay: 0.4s; } - `}),(0,t.jsx)("div",{className:"chat-dot"}),(0,t.jsx)("div",{className:"chat-dot"}),(0,t.jsx)("div",{className:"chat-dot"})]})}function t_({message:e}){let n=e.toolArgs?function e(t){let n={};for(let[r,i]of Object.entries(t))tE.test(r)?n[r]="[redacted]":Array.isArray(i)?n[r]=i.map(t=>null===t||"object"!=typeof t||Array.isArray(t)?t:e(t)):null!==i&&"object"==typeof i?n[r]=e(i):n[r]=i;return n}(e.toolArgs):void 0;return(0,t.jsxs)("div",{style:{maxWidth:"80%"},children:[(0,t.jsx)(tz.Collapse,{size:"small",style:{backgroundColor:"#fafafa",border:"1px solid #e5e7eb",borderRadius:8},children:(0,t.jsxs)(t$,{header:(0,t.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,fontSize:13},children:[(0,t.jsx)(tw.ToolOutlined,{style:{color:"#6b7280"}}),(0,t.jsx)("span",{style:{color:"#374151",fontWeight:500},children:e.toolName??"Tool call"})]}),children:[void 0!==n&&(0,t.jsxs)("div",{style:{marginBottom:12*!!e.toolResult},children:[(0,t.jsx)("div",{style:{fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em",color:"#9ca3af",marginBottom:4},children:"Arguments"}),(0,t.jsx)("pre",{style:{margin:0,padding:"8px 10px",backgroundColor:"#f3f4f6",borderRadius:6,fontSize:12,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Monaco, Consolas, "Liberation Mono", "Courier New", monospace',whiteSpace:"pre-wrap",wordBreak:"break-word",color:"#374151"},children:JSON.stringify(n,null,2)})]}),e.toolResult&&(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{style:{fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em",color:"#9ca3af",marginBottom:4},children:"Result"}),(0,t.jsx)("div",{style:{fontSize:13,color:"#374151",whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Monaco, Consolas, "Liberation Mono", "Courier New", monospace'},children:e.toolResult})]})]},"tool")}),(0,t.jsx)("div",{style:{fontSize:11,color:"#9ca3af",marginTop:4},children:tL(e.timestamp)})]})}let tP=({messages:e,isStreaming:n,onEditMessage:r})=>{let i=e.length-1,o=e[i]??null,l=n&&null!==o&&"assistant"===o.role&&""===o.content;return(0,t.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:e.map((e,o)=>{let s=o===i;return"user"===e.role?(0,t.jsx)(tA,{message:e,onEdit:r,isStreaming:n},e.id):"tool"===e.role?(0,t.jsx)(t_,{message:e},e.id):(0,t.jsx)(tI,{message:e,isLastMessage:s,isStreaming:n,isTypingIndicator:s&&l},e.id)})})};var tH=e.i(790848),tB=e.i(482725),tN=e.i(764205);let tU=({accessToken:e,selectedServers:r,onChange:i})=>{let[o,l]=(0,n.useState)([]),[a,c]=(0,n.useState)(!0),[d,u]=(0,n.useState)(new Set);(0,n.useEffect)(()=>{let t=!1;return(async()=>{c(!0);try{let n=await (0,tN.fetchMCPServers)(e);if(t)return;let r=Array.isArray(n)?n:n?.data??[];l(r)}catch{t||l([])}finally{t||c(!1)}})(),()=>{t=!0}},[e]);let f=async(t,n)=>{if(!n)return void i(r.filter(e=>e!==t));u(e=>new Set(e).add(t));try{let n=await (0,tN.listMCPTools)(e,t);if(n?.error)return void s.message.warning(`Could not load tools for ${t} — it will be excluded from this message.`);i([...r,t])}catch{s.message.warning(`Could not load tools for ${t} — it will be excluded from this message.`)}finally{u(e=>{let n=new Set(e);return n.delete(t),n})}};return(0,t.jsx)("div",{style:{maxWidth:320,maxHeight:400,overflowY:"auto",padding:"8px 0"},children:a?(0,t.jsx)("div",{style:{display:"flex",justifyContent:"center",padding:"24px 0"},children:(0,t.jsx)(tB.Spin,{})}):0===o.length?(0,t.jsx)("div",{style:{padding:"16px 12px",color:"#8c8c8c",fontSize:13,textAlign:"center"},children:"No MCP servers configured"}):o.map(e=>{let n=e.server_name??e.alias??e.server_id,i=r.includes(n),o=d.has(n);return(0,t.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",padding:"8px 12px",gap:12},children:[(0,t.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,t.jsx)("div",{style:{fontWeight:500,fontSize:13,color:"#1f1f1f",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:n}),e.description&&(0,t.jsx)("div",{style:{fontSize:12,color:"#8c8c8c",marginTop:2,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:e.description})]}),(0,t.jsx)(tH.Switch,{size:"small",checked:i,loading:o,onChange:e=>f(n,e)})]},e.server_id)})})};var tY=e.i(240647);let tq=["#1677ff","#52c41a","#fa8c16","#eb2f96","#722ed1","#13c2c2","#fa541c","#2f54eb","#a0d911","#faad14"];function tJ(e){let t=0;for(let n=0;n{let[o,l]=(0,n.useState)([]),[a,c]=(0,n.useState)(!0),[d,u]=(0,n.useState)(""),[f,h]=(0,n.useState)("all"),[g,m]=(0,n.useState)(new Set),[y,b]=(0,n.useState)(null);(0,n.useEffect)(()=>{let t=!1;return c(!0),(0,tN.fetchMCPServers)(e).then(e=>{t||l(Array.isArray(e)?e:e?.data??[])}).catch(()=>{t||l([])}).finally(()=>{t||c(!1)}),()=>{t=!0}},[e]);let v=async(t,n)=>{if(!n)return void i(r.filter(e=>e!==t));m(e=>new Set(e).add(t));try{let n=await (0,tN.listMCPTools)(e,t);if(n?.error)return void s.message.warning(`Could not load tools for ${t}`);i([...r,t])}catch{s.message.warning(`Could not load tools for ${t}`)}finally{m(e=>{let n=new Set(e);return n.delete(t),n})}},k=e=>e.server_name??e.alias??e.server_id,S=o.filter(e=>{let t=k(e),n=!d.trim()||t.toLowerCase().includes(d.toLowerCase())||(e.description??"").toLowerCase().includes(d.toLowerCase()),i="all"===f||r.includes(t);return n&&i}),j=o.filter(e=>r.includes(k(e))).length;if(y){let e=k(y),n=r.includes(e),i=g.has(e),o=tJ(e);return(0,t.jsxs)("div",{style:{width:"100%"},children:[(0,t.jsxs)("button",{onClick:()=>b(null),style:{display:"flex",alignItems:"center",gap:6,background:"none",border:"none",cursor:"pointer",color:"#6b7280",fontSize:13,padding:"0 0 20px 0"},children:[(0,t.jsx)(x.ArrowLeftOutlined,{style:{fontSize:12}}),"Back"]}),(0,t.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:20,marginBottom:28},children:[(0,t.jsx)("div",{style:{width:64,height:64,borderRadius:16,background:o,display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:28,flexShrink:0},children:e.charAt(0).toUpperCase()}),(0,t.jsxs)("div",{style:{flex:1},children:[(0,t.jsx)("h2",{style:{margin:"0 0 4px",fontSize:22,fontWeight:700,color:"#111827"},children:e}),(0,t.jsx)("p",{style:{margin:0,fontSize:14,color:"#6b7280"},children:y.description??"MCP server"})]}),(0,t.jsx)(e0.Button,{type:n?"default":"primary",loading:i,onClick:()=>v(e,!n),style:{borderRadius:8,fontWeight:600,height:38,minWidth:110},children:n?"Disconnect":"Connect"})]}),(0,t.jsx)("h3",{style:{margin:"0 0 12px",fontSize:15,fontWeight:600,color:"#111827"},children:"Information"}),(0,t.jsx)("div",{style:{border:"1px solid #e5e7eb",borderRadius:10,overflow:"hidden"},children:[["Server ID",y.server_id],["Transport",y.mcp_info?.server_url?"HTTP":"stdio"],["Status",n?"Connected":"Not connected"]].filter(([,e])=>e).map(([e,n],r,i)=>(0,t.jsxs)("div",{style:{display:"flex",padding:"12px 16px",borderBottom:ru(e.target.value),allowClear:!0,style:{width:220,borderRadius:8,fontSize:13},size:"middle"})]}),(0,t.jsx)("div",{style:{display:"flex",borderBottom:"1px solid #e5e7eb",marginBottom:16},children:["all","connected"].map(e=>(0,t.jsx)("button",{onClick:()=>h(e),style:{padding:"8px 16px",border:"none",borderBottom:f===e?"2px solid #1677ff":"2px solid transparent",cursor:"pointer",fontSize:13,fontWeight:f===e?600:400,background:"transparent",color:f===e?"#1677ff":"#6b7280",marginBottom:-1},children:"all"===e?"All":`Connected${j>0?` (${j})`:""}`},e))}),a?(0,t.jsx)("div",{style:{display:"flex",justifyContent:"center",padding:"48px 0"},children:(0,t.jsx)(tB.Spin,{})}):0===S.length?(0,t.jsx)("div",{style:{textAlign:"center",color:"#9ca3af",fontSize:13,padding:"48px 12px"},children:0===o.length?"No MCP servers configured. Add servers in Tools → MCP Servers.":"connected"===f?"No servers connected yet.":"No servers match your search."}):(0,t.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(2, minmax(0, 1fr))",gap:0,border:"1px solid #e5e7eb",borderRadius:10,overflow:"hidden"},children:S.map((e,n)=>{let i=k(e),o=r.includes(i),l=tJ(i);return(0,t.jsxs)("div",{onClick:()=>b(e),style:{display:"flex",alignItems:"center",gap:12,padding:"14px 16px",background:"#fff",borderRight:n%2==0?"1px solid #f3f4f6":"none",borderBottom:Math.floor(n/2){e.currentTarget.style.background="#fafafa"},onMouseLeave:e=>{e.currentTarget.style.background="#fff"},children:[(0,t.jsx)("div",{style:{width:38,height:38,borderRadius:10,background:l,display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:700,fontSize:16,flexShrink:0},children:i.charAt(0).toUpperCase()}),(0,t.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,t.jsx)("div",{style:{fontSize:14,fontWeight:500,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),(0,t.jsx)("div",{style:{fontSize:12,color:"#9ca3af",marginTop:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.description??"MCP server"})]}),o&&(0,t.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:"#1677ff",flexShrink:0}}),(0,t.jsx)(tY.RightOutlined,{style:{fontSize:11,color:"#d1d5db",flexShrink:0}})]},e.server_id)})})]})};var tK=e.i(689020),tG=e.i(254530),tZ=e.i(612256),tQ=e.i(916925);let tX=["Write","Learn","Code","Brainstorm"],t0="litellm_chat_selected_models";function t1(){let e=new Date().getHours();return e>=5&&e<12?"Good morning":e>=12&&e<17?"Good afternoon":"Good evening"}function t2(e,t){return t?`${e}/ui/chat?id=${t}`:`${e}/ui/chat`}function t4(e){if(!e)return"";let t=e.toLowerCase(),n=t.indexOf("/");return n>0?t.slice(0,n):t.includes("claude")?"anthropic":t.includes("gemini")?"gemini":t.includes("gpt")||t.includes("chatgpt")||/^o[0-9]/.test(t)?"openai":t.includes("mistral")||t.includes("codestral")?"mistral":t.includes("llama")?"meta_llama":t.includes("deepseek")?"deepseek":t.includes("grok")?"xai":t.includes("command")?"cohere":t.includes("nova")||t.includes("titan")?"bedrock":""}async function t5(e,t,n,r,i,o,l){try{await (0,tG.makeOpenAIChatCompletionRequest)(t,t=>o(e,t),e,n,void 0,i,void 0,void 0,void 0,void 0,void 0,void 0,void 0,r.length>0?r:void 0)}catch(t){if(!(t instanceof Error&&"AbortError"===t.name)){let n=t instanceof Error?t.message:String(t);o(e,` - -_Error: ${n}_`)}}finally{l(e)}}let t6=({accessToken:e,userRole:r,userId:v,userEmail:k})=>{let S,j=(0,eZ.useRouter)(),w=(0,eZ.useSearchParams)().get("id"),{data:C}=(0,tZ.useUIConfig)(),z=C?.server_root_path&&"/"!==C.server_root_path?C.server_root_path.replace(/\/+$/,""):"",M=`${(0,tN.getProxyBaseUrl)()}/get_image`,[O,D]=(0,n.useState)([]),[$,E]=(0,n.useState)([]),[L,T]=(0,n.useState)(!0),[A,I]=(0,n.useState)(!1),[R,F]=(0,n.useState)(""),[W,_]=(0,n.useState)([]),[P,H]=(0,n.useState)(!1),[B,N]=(0,n.useState)(""),[U,Y]=(0,n.useState)(!1),[q,J]=(0,n.useState)(!1),[V,K]=(0,n.useState)("chats"),[G,Z]=(0,n.useState)(!1),[Q,X]=(0,n.useState)([]),[ee,et]=(0,n.useState)(new Set),en=(0,n.useRef)({}),er=(0,n.useRef)(null),ei=(0,n.useRef)(null),eo=(0,n.useRef)(null),[el,es]=(0,n.useState)(!1),ea=(0,n.useRef)(null),{conversations:ec,activeConversation:ed,storageUnavailable:eu,staleId:ef,createConversation:ep,appendMessage:eh,updateLastAssistantMessage:eg,truncateAfterMessage:ex,deleteConversation:em,renameConversation:ey}=function(e){let[t,r]=(0,n.useState)([]),[i,o]=(0,n.useState)(!1),[l,s]=(0,n.useState)(!1),[a,c]=(0,n.useState)(e),d=(0,n.useRef)(!1),u=(0,n.useRef)(!1);(0,n.useEffect)(()=>{c(e),s(!1)},[e]),(0,n.useEffect)(()=>{let{conversations:t,storageUnavailable:n}=function(){try{let e=localStorage.getItem(eQ);if(!e)return{conversations:[],storageUnavailable:!1};return{conversations:JSON.parse(e),storageUnavailable:!1}}catch{return{conversations:[],storageUnavailable:!0}}}();d.current=n,r(t),o(n),u.current=!0,null!==e&&(t.some(t=>t.id===e)||s(!0))},[]),(0,n.useEffect)(()=>{!u.current||d.current||!function(e){try{return localStorage.setItem(eQ,JSON.stringify(e)),!0}catch{return!1}}(t)&&(d.current=!0,o(!0))},[t]);let f=(0,n.useCallback)(e=>{let t=crypto.randomUUID(),n=Date.now(),i={id:t,title:"New conversation",model:e,messages:[],mcpServerNames:[],createdAt:n,updatedAt:n};return r(e=>eX([i,...e])),c(t),t},[]),p=(0,n.useCallback)((e,t)=>{let n={...t,id:crypto.randomUUID(),timestamp:Date.now()};r(t=>eX(t.map(t=>{let r;if(t.id!==e)return t;let i=[...t.messages,n],o=t.title;return"New conversation"===o&&"user"===n.role&&0===t.messages.filter(e=>"user"===e.role).length&&(o=(r=n.content.trim()).length<=40?r:r.slice(0,40)+"…"),{...t,title:o,messages:i,updatedAt:Date.now()}})))},[]),h=(0,n.useCallback)((e,t)=>{r(n=>eX(n.map(n=>{if(n.id!==e)return n;let r=[...n.messages],i=r.reduceRight((e,t,n)=>-1!==e?e:"assistant"===t.role?n:-1,-1);return -1===i?n:(r[i]={...r[i],...t},{...n,messages:r,updatedAt:Date.now()})})))},[]),g=(0,n.useCallback)((e,t)=>{r(n=>eX(n.map(n=>{if(n.id!==e)return n;let r=n.messages.findIndex(e=>e.id===t);return -1===r?n:{...n,messages:n.messages.slice(0,r),updatedAt:Date.now()}})))},[]),x=(0,n.useCallback)(e=>{r(t=>eX(t.filter(t=>t.id!==e))),a===e&&c(null)},[a]),m=(0,n.useCallback)((e,t)=>{r(n=>eX(n.map(n=>n.id===e?{...n,title:t,updatedAt:Date.now()}:n)))},[]),y=(0,n.useCallback)(e=>{c(e),s(!1)},[]),b=null!==a?t.find(e=>e.id===a)??null:null;return{conversations:t,activeConversation:b,storageUnavailable:i,staleId:l,createConversation:f,appendMessage:p,updateLastAssistantMessage:h,truncateAfterMessage:g,deleteConversation:x,renameConversation:m,setActiveConversationId:y}}(w);(0,n.useEffect)(()=>{e&&(T(!0),(0,tK.fetchAvailableModels)(e).then(e=>{let t=(e||[]).map(e=>e.model_group??"").filter(Boolean);E(t);try{let e=localStorage.getItem(t0);if(e){let n=JSON.parse(e);if(Array.isArray(n)){let e=n.filter(e=>t.includes(e));if(e.length>0)return void D(e)}}}catch{}t.length>0&&(D([t[0]]),localStorage.setItem(t0,JSON.stringify([t[0]])))}).catch(()=>s.message.error("Could not load models")).finally(()=>T(!1)))},[e]),(0,n.useEffect)(()=>{ef&&j.replace(t2(z))},[ef,j]);let eb=(0,n.useCallback)(e=>{D(t=>{let n;if(t.includes(e))n=t.filter(t=>t!==e);else{if(t.length>=3)return t;n=[...t,e]}return localStorage.setItem(t0,JSON.stringify(n)),n})},[]),ev=O.length>1,ek=P||ee.size>0,eS=(0,n.useCallback)(async(t,n)=>{let r=t.trim();if(!r||0===O.length||P)return;let i=O[0];N("");let o=w;o||(o=ep(i),j.push(t2(z,o))),eh(o,{role:"user",content:r}),eh(o,{role:"assistant",content:""}),H(!0),er.current=new AbortController;let l=[...n??(ed?.messages??[]).filter(e=>"user"===e.role||"assistant"===e.role).map(e=>({role:e.role,content:e.content})),{role:"user",content:r}],s="",a="";try{await (0,tG.makeOpenAIChatCompletionRequest)(l,e=>{s+=e,eg(o,{content:s})},i,e,void 0,er.current.signal,e=>{a+=e,eg(o,{reasoningContent:a})},void 0,void 0,void 0,void 0,void 0,void 0,W.length>0?W:void 0)}catch(e){e instanceof Error&&"AbortError"===e.name?eg(o,{content:s+" [stopped]"}):eg(o,{content:"[Something went wrong. The partial response has been saved.]"})}finally{H(!1),er.current=null}},[w,ed,O,W,e,ep,eh,eg,j,P]),ej=(0,n.useCallback)((t,n)=>{let r=t.trim();if(!r||0===O.length||ek)return;N("");let i={userMessage:r,responses:{}},o=n.length;X(e=>[...e,i]),et(new Set(O));let l={};O.forEach(e=>{l[e]=new AbortController}),en.current=l,Promise.allSettled(O.map(t=>{let i=[];for(let e of n)i.push({role:"user",content:e.userMessage}),i.push({role:"assistant",content:e.responses[t]??""});return i.push({role:"user",content:r}),t5(t,i,e,W,l[t].signal,(e,t)=>X(n=>{let r=[...n],i={...r[o]};return i.responses={...i.responses,[e]:(i.responses[e]??"")+t},r[o]=i,r}),e=>et(t=>{let n=new Set(t);return n.delete(e),n}))}))},[O,e,W,ek]),ew=(0,n.useCallback)(()=>{er.current?.abort(),Object.values(en.current).forEach(e=>e.abort()),en.current={}},[]),eC=(0,n.useCallback)((e,t)=>{if(!w||P)return;let n=ed?.messages??[],r=n.findIndex(t=>t.id===e),i=(-1===r?n:n.slice(0,r)).filter(e=>"user"===e.role||"assistant"===e.role).map(e=>({role:e.role,content:e.content}));ex(w,e),eS(t,i)},[w,P,ed,ex,eS]),ez=(0,n.useCallback)(e=>{ev?ej(e,Q):eS(e)},[ev,eS,ej,Q]),eM=e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),ez(B))};(0,n.useEffect)(()=>{let e=ei.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,180)}px`)},[B]),(0,n.useEffect)(()=>{let e=eo.current;if(!e)return;let t=()=>{es(e.scrollHeight-e.scrollTop-e.clientHeight>120),null!==ea.current&&(ea.current=e.scrollTop)};return e.addEventListener("scroll",t,{passive:!0}),()=>e.removeEventListener("scroll",t)},[ed]),(0,n.useEffect)(()=>{let e=eo.current;P?ea.current=e?.scrollTop??0:ea.current=null},[P]),(0,n.useLayoutEffect)(()=>{if(null===ea.current)return;let e=eo.current;e&&(e.scrollTop=ea.current)});let eO=(0,n.useRef)(0);(0,n.useLayoutEffect)(()=>{let e=ed?.messages?.length??0,t=eO.current;if(eO.current=e,e>t){let e=eo.current;e&&(e.scrollTop=e.scrollHeight)}},[ed?.messages]);let eD=ev?0===Q.length:!ed||0===ed.messages.length,e$=k?.split("@")[0]??v??"",eE=e$?`${t1()}, ${e$}`:t1(),eL=(S="ui/".replace(/^\/+|\/+$/g,""))?`${z}/${S}/`:`${z}/`,eT=(R?$.filter(e=>e.toLowerCase().includes(R.toLowerCase())):$).sort((e,t)=>{let n=O.includes(e),r=O.includes(t);return n&&!r?-1:!n&&r?1:0}),eA=(0,t.jsxs)("div",{style:{width:280,maxHeight:400,display:"flex",flexDirection:"column"},children:[(0,t.jsx)("div",{style:{padding:"8px 8px 4px"},children:(0,t.jsx)("input",{autoFocus:!0,value:R,onChange:e=>F(e.target.value),placeholder:"Search models...",style:{width:"100%",padding:"6px 10px",border:"1px solid #d1d5db",borderRadius:6,fontSize:13,outline:"none",boxSizing:"border-box"}})}),O.length>=3&&(0,t.jsxs)("div",{style:{padding:"4px 12px",fontSize:12,color:"#6b7280"},children:["Max ",3," models selected — deselect one to change."]}),(0,t.jsx)("div",{style:{flex:1,overflowY:"auto"},children:eT.map(e=>{let n=O.includes(e),r=!n&&O.length>=3,i=t4(e),{logo:o}=i?(0,tQ.getProviderLogoAndName)(i):{logo:""};return(0,t.jsxs)("button",{disabled:r,onClick:()=>eb(e),style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"#eff6ff":"transparent",border:"none",cursor:r?"not-allowed":"pointer",textAlign:"left",opacity:r?.45:1,borderRadius:4},children:[(0,t.jsx)("span",{style:{width:16,height:16,borderRadius:3,border:`1.5px solid ${n?"#1677ff":"#d1d5db"}`,background:n?"#1677ff":"#fff",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,transition:"all 0.1s"},children:n&&(0,t.jsx)(y.CheckOutlined,{style:{fontSize:10,color:"#fff"}})}),o?(0,t.jsx)("img",{src:o,alt:"",style:{width:16,height:16,objectFit:"contain",flexShrink:0},onError:e=>{e.currentTarget.style.display="none"}}):(0,t.jsx)("span",{style:{width:16,flexShrink:0}}),(0,t.jsx)("span",{style:{fontSize:13,color:"#111827",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})]},e)})})]}),eI=(e,n,r,o=!1,l)=>(0,t.jsx)(i.Tooltip,{title:q?n:void 0,placement:"right",children:(0,t.jsxs)("button",{onClick:r,style:{display:"flex",alignItems:"center",gap:10,padding:"8px 10px",width:"100%",borderRadius:7,border:"none",cursor:"pointer",background:o?"#e8f4ff":"transparent",color:o?"#1677ff":"#374151",textAlign:"left",fontSize:14,justifyContent:q?"center":"flex-start",transition:"background 0.12s"},onMouseEnter:e=>{o||(e.currentTarget.style.background="#f5f5f5")},onMouseLeave:e=>{e.currentTarget.style.background=o?"#e8f4ff":"transparent"},children:[(0,t.jsx)("span",{style:{fontSize:16,flexShrink:0},children:e}),!q&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{style:{flex:1},children:n}),l&&(0,t.jsx)("span",{style:{fontSize:11,color:"#9ca3af"},children:l})]})]})},n),eR=L?(0,t.jsx)(o.Skeleton.Input,{active:!0,style:{width:160,height:28}}):(0,t.jsx)(l.Popover,{open:A,onOpenChange:e=>{I(e),e||F("")},content:eA,trigger:"click",placement:"bottomLeft",children:(0,t.jsxs)("button",{style:{display:"flex",alignItems:"center",gap:6,padding:"5px 10px",borderRadius:7,border:"1px solid transparent",cursor:"pointer",background:"transparent",color:"#111827",fontSize:14,fontWeight:500,maxWidth:480,overflow:"hidden"},onMouseEnter:e=>{e.currentTarget.style.background="#f5f5f5"},onMouseLeave:e=>{e.currentTarget.style.background="transparent"},children:[0===O.length?(0,t.jsx)("span",{style:{color:"#9ca3af"},children:"Select model"}):1===O.length?(0,t.jsxs)(t.Fragment,{children:[(()=>{let e=t4(O[0]),{logo:n}=e?(0,tQ.getProviderLogoAndName)(e):{logo:""};return n?(0,t.jsx)("img",{src:n,alt:"",style:{width:18,height:18,objectFit:"contain",flexShrink:0},onError:e=>{e.currentTarget.style.display="none"}}):null})(),(0,t.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:240},children:O[0]})]}):(0,t.jsx)("div",{style:{display:"flex",alignItems:"center",gap:4,flexWrap:"nowrap",overflow:"hidden"},children:O.map(e=>{let n=t4(e),{logo:r}=n?(0,tQ.getProviderLogoAndName)(n):{logo:""};return(0,t.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 8px",background:"#f0f4ff",borderRadius:10,fontSize:12,color:"#1677ff",fontWeight:500,flexShrink:0},children:[r&&(0,t.jsx)("img",{src:r,alt:"",style:{width:13,height:13,objectFit:"contain"},onError:e=>{e.currentTarget.style.display="none"}}),(0,t.jsx)("span",{style:{maxWidth:120,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})]},e)})}),(0,t.jsx)(m.DownOutlined,{style:{fontSize:10,color:"#9ca3af",flexShrink:0,marginLeft:2}})]})}),eF=n=>(0,t.jsxs)("div",{style:{background:"#fff",borderRadius:12,border:"1px solid #e5e7eb",boxShadow:"0 1px 6px rgba(0,0,0,0.06)",overflow:"hidden"},children:[(0,t.jsx)("textarea",{ref:ei,value:B,onChange:e=>N(e.target.value),onKeyDown:eM,placeholder:n?"Send a message...":"How can I help you today?",style:{width:"100%",minHeight:n?52:80,padding:n?"16px 20px 8px":"20px 20px 8px",border:"none",outline:"none",resize:"none",fontSize:15,color:"#111827",background:"transparent",fontFamily:"inherit",boxSizing:"border-box"}}),(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:n?"4px 12px 10px":"8px 12px 12px",borderTop:"1px solid #f3f4f6"},children:[(0,t.jsx)(l.Popover,{open:U,onOpenChange:Y,content:(0,t.jsx)(tU,{accessToken:e,selectedServers:W,onChange:_}),trigger:"click",placement:"topLeft",children:(0,t.jsxs)("button",{style:{background:"none",border:"1px solid #d1d5db",borderRadius:6,padding:"5px 10px",cursor:"pointer",fontSize:14,color:"#6b7280",display:"flex",alignItems:"center",gap:4},children:[(0,t.jsx)(c.PlusOutlined,{}),W.length>0&&(0,t.jsx)("span",{style:{fontSize:12,color:"#1677ff",fontWeight:500},children:W.length})]})}),(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[!ev&&(0,t.jsx)("span",{style:{fontSize:12,color:"#9ca3af",maxWidth:160,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n?W.length>0?`${W.length} tool${W.length>1?"s":""} connected`:"":O[0]||"No model"}),ek?(0,t.jsx)("button",{onClick:ew,style:{background:"none",border:"1.5px solid #d1d5db",borderRadius:"50%",width:32,height:32,cursor:"pointer",color:"#374151",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,transition:"border-color 0.15s"},onMouseEnter:e=>{e.currentTarget.style.borderColor="#9ca3af"},onMouseLeave:e=>{e.currentTarget.style.borderColor="#d1d5db"},children:(0,t.jsx)("div",{style:{width:10,height:10,background:"#374151",borderRadius:2}})}):(0,t.jsx)("button",{onClick:()=>ez(B),disabled:!B.trim()||L||0===O.length,style:{background:B.trim()&&O.length>0?"#1677ff":"#f3f4f6",border:"none",borderRadius:7,padding:"7px 16px",cursor:B.trim()&&O.length>0?"pointer":"not-allowed",color:B.trim()&&O.length>0?"#fff":"#9ca3af",fontSize:14,fontWeight:500,transition:"background 0.15s"},children:"Send"})]})]})]});return(0,t.jsxs)("div",{style:{display:"flex",height:"100vh",width:"100vw",background:"#ffffff",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",overflow:"hidden"},children:[(0,t.jsxs)("div",{style:{width:q?56:260,flexShrink:0,background:"#f9fafb",borderRight:"1px solid #e5e7eb",display:"flex",flexDirection:"column",overflow:"hidden",transition:"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)"},children:[(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"12px 10px",justifyContent:q?"center":"space-between",flexShrink:0},children:[!q&&(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,t.jsx)("img",{src:M,alt:"LiteLLM",style:{height:28,maxWidth:120,objectFit:"contain",flexShrink:0}}),(0,t.jsx)("span",{style:{fontWeight:700,fontSize:15,color:"#111827",letterSpacing:"-0.01em"},children:"LiteLLM"})]}),(0,t.jsx)(i.Tooltip,{title:q?"Expand sidebar":"Collapse sidebar",placement:"right",children:(0,t.jsx)("button",{onClick:()=>J(e=>!e),style:{background:"none",border:"none",cursor:"pointer",padding:6,borderRadius:7,color:"#6b7280",fontSize:16,display:"flex",alignItems:"center"},children:q?(0,t.jsx)(f.MenuUnfoldOutlined,{}):(0,t.jsx)(u.MenuFoldOutlined,{})})})]}),(0,t.jsxs)("div",{style:{padding:"0 8px 4px",flexShrink:0},children:[eI((0,t.jsx)(d.EditOutlined,{}),"New chat",()=>j.push(t2(z))),eI((0,t.jsx)(p.SearchOutlined,{}),"Search chats",()=>K("chats"))]}),(0,t.jsx)("div",{style:{height:1,background:"#e5e7eb",margin:"4px 8px",flexShrink:0}}),(0,t.jsxs)("div",{style:{padding:"4px 8px",flexShrink:0},children:[eI((0,t.jsx)(h.MessageOutlined,{}),"Chats",()=>K("chats"),"chats"===V),eI((0,t.jsx)(g.AppstoreOutlined,{}),"Apps",()=>K("apps"),"apps"===V),(0,t.jsx)(i.Tooltip,{title:q?"Back to Developer Console UI":void 0,placement:"right",children:(0,t.jsxs)("a",{href:eL,style:{display:"flex",alignItems:"center",gap:10,padding:"8px 10px",width:"100%",borderRadius:7,color:"#6b7280",textDecoration:"none",fontSize:14,justifyContent:q?"center":"flex-start",boxSizing:"border-box"},onMouseEnter:e=>{e.currentTarget.style.background="#f5f5f5"},onMouseLeave:e=>{e.currentTarget.style.background="transparent"},children:[(0,t.jsx)(x.ArrowLeftOutlined,{style:{fontSize:16,flexShrink:0}}),!q&&(0,t.jsx)("span",{children:"Back to Developer Console UI"})]})})]}),(0,t.jsx)("div",{style:{height:1,background:"#e5e7eb",margin:"4px 8px",flexShrink:0}}),!q&&"chats"===V&&(0,t.jsx)("div",{style:{flex:1,overflow:"hidden",display:"flex",flexDirection:"column"},children:(0,t.jsx)(tj,{conversations:ec,activeConversationId:w,onSelect:e=>j.push(t2(z,e)),onDelete:em,onNewChat:()=>j.push(t2(z)),onRename:ey})})]}),(0,t.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:[(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 16px",flexShrink:0,borderBottom:"1px solid #f0f0f0",background:"#fff",height:48},children:[(0,t.jsx)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:eR}),(0,t.jsx)("div",{style:{display:"flex",alignItems:"center",gap:4,flexShrink:0},children:(0,t.jsx)(i.Tooltip,{title:"Settings",children:(0,t.jsx)("button",{style:{background:"none",border:"none",cursor:"pointer",padding:7,borderRadius:7,color:"#6b7280",fontSize:16,display:"flex",alignItems:"center"},children:(0,t.jsx)(a.SettingOutlined,{})})})})]}),eu&&!G&&(0,t.jsxs)("div",{style:{background:"#fffbe6",borderBottom:"1px solid #ffe58f",padding:"6px 20px",fontSize:13,color:"#874d00",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[(0,t.jsx)("span",{children:"Chat history won't be saved in this browser session."}),(0,t.jsx)("button",{onClick:()=>Z(!0),style:{background:"none",border:"none",cursor:"pointer",fontSize:16,color:"#874d00"},children:"×"})]}),(0,t.jsx)("div",{style:{flex:1,minHeight:0,overflow:"hidden",display:"flex",flexDirection:"column",background:"#fff"},children:"apps"===V?(0,t.jsx)("div",{style:{flex:1,minHeight:0,overflow:"auto",maxWidth:800,margin:"0 auto",width:"100%",padding:"32px 24px"},children:(0,t.jsx)(tV,{accessToken:e,selectedServers:W,onChange:_})}):eD?(0,t.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"0 24px 80px"},children:[(0,t.jsx)("h1",{style:{margin:"0 0 32px",fontSize:28,fontWeight:600,color:"#111827",fontFamily:"inherit",letterSpacing:"-0.01em",textAlign:"center"},children:ev?`Compare ${O.length} models`:eE}),ev&&(0,t.jsx)("p",{style:{margin:"-16px 0 24px",fontSize:14,color:"#6b7280",textAlign:"center"},children:"Send a message to see responses side-by-side"}),(0,t.jsx)("div",{style:{width:"100%",maxWidth:680},children:eF(!1)}),!ev&&(0,t.jsx)("div",{style:{display:"flex",gap:8,marginTop:14,flexWrap:"wrap",justifyContent:"center"},children:tX.map(e=>(0,t.jsx)("button",{onClick:()=>N(e+": "),style:{background:"#f9fafb",border:"1px solid #e5e7eb",borderRadius:20,padding:"7px 16px",fontSize:14,color:"#374151",cursor:"pointer"},onMouseEnter:e=>{e.currentTarget.style.background="#f3f4f6"},onMouseLeave:e=>{e.currentTarget.style.background="#f9fafb"},children:e},e))})]}):(0,t.jsxs)("div",{style:{flex:1,minHeight:0,display:"flex",flexDirection:"column",maxWidth:ev?O.length>=3?1200:960:760,margin:"0 auto",width:"100%",padding:"0 24px",position:"relative"},children:[(0,t.jsx)("div",{ref:eo,style:{flex:1,minHeight:0,overflow:"auto",paddingTop:24,overflowAnchor:"none"},children:ev?(0,t.jsx)("div",{style:{paddingBottom:8},children:Q.map((e,n)=>{let r=n===Q.length-1;return(0,t.jsxs)("div",{style:{marginBottom:32},children:[(0,t.jsx)("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:20},children:(0,t.jsx)("div",{style:{background:"#f3f4f6",borderRadius:16,padding:"10px 16px",maxWidth:"75%",fontSize:14,color:"#111827",lineHeight:1.5},children:e.userMessage})}),(0,t.jsx)("div",{style:{display:"flex",gap:14,alignItems:"flex-start"},children:O.map((i,o)=>{let l=t4(i),{logo:s}=l?(0,tQ.getProviderLogoAndName)(l):{logo:""},a=e.responses[i]??"",c=r&&ee.has(i);return(0,t.jsxs)("div",{style:{flex:1,border:"1px solid #e5e7eb",borderRadius:12,overflow:"hidden",minWidth:0},children:[0===n&&(0,t.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid #f0f0f0",display:"flex",alignItems:"center",gap:8,background:"#fafafa"},children:[s?(0,t.jsx)("img",{src:s,alt:"",style:{width:18,height:18,objectFit:"contain",flexShrink:0},onError:e=>{e.currentTarget.style.display="none"}}):(0,t.jsx)("div",{style:{width:18,height:18,borderRadius:"50%",background:"#e5e7eb",flexShrink:0}}),(0,t.jsxs)("span",{style:{fontWeight:600,fontSize:12,color:"#374151"},children:["Response ",o+1]}),(0,t.jsx)("span",{style:{fontSize:11,color:"#9ca3af",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:i})]}),(0,t.jsxs)("div",{style:{padding:"14px 16px",minHeight:60,position:"relative"},children:[c&&(0,t.jsx)("span",{style:{position:"absolute",top:10,right:12,fontSize:9,color:"#1677ff"},children:"●"}),a?(0,t.jsx)(b.default,{remarkPlugins:[eG],components:{p:({children:e})=>(0,t.jsx)("p",{style:{margin:"0 0 10px",lineHeight:1.6,fontSize:14,color:"#111827"},children:e}),code:({className:e,children:n})=>/language-(\w+)/.exec(e||"")?(0,t.jsx)("pre",{style:{background:"#f8f9fa",padding:"10px 12px",borderRadius:6,overflow:"auto",fontSize:13,margin:"8px 0"},children:(0,t.jsx)("code",{children:n})}):(0,t.jsx)("code",{style:{background:"#f3f4f6",padding:"2px 5px",borderRadius:3,fontSize:13},children:n})},children:a}):c?(0,t.jsx)("span",{style:{color:"#9ca3af",fontSize:14},children:"Generating…"}):(0,t.jsx)("span",{style:{color:"#9ca3af",fontSize:14},children:"—"})]})]},i)})})]},n)})}):(0,t.jsx)(tP,{messages:ed.messages,isStreaming:P,onEditMessage:eC})}),el&&(0,t.jsx)("button",{onClick:()=>{let e=eo.current;e&&(e.scrollTo({top:e.scrollHeight,behavior:"smooth"}),null!==ea.current&&(ea.current=e.scrollHeight))},style:{position:"absolute",bottom:100,left:"50%",transform:"translateX(-50%)",width:34,height:34,borderRadius:"50%",background:"rgba(255,255,255,0.75)",backdropFilter:"blur(6px)",WebkitBackdropFilter:"blur(6px)",border:"1px solid rgba(0,0,0,0.1)",boxShadow:"0 1px 4px rgba(0,0,0,0.08)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",zIndex:10,transition:"background 0.15s"},onMouseEnter:e=>{e.currentTarget.style.background="rgba(255,255,255,0.95)"},onMouseLeave:e=>{e.currentTarget.style.background="rgba(255,255,255,0.75)"},"aria-label":"Scroll to bottom",children:(0,t.jsx)(m.DownOutlined,{style:{fontSize:12}})}),(0,t.jsx)("div",{style:{padding:"12px 0 24px"},children:eF(!0)})]})})]})]})},t3=()=>{let{accessToken:e,userRole:n,userId:i,userEmail:o}=(0,r.default)();return(0,t.jsx)(t6,{accessToken:e??"",userRole:n??"",userId:i??"",userEmail:o??""})};e.s(["default",0,()=>(0,t.jsx)(n.Suspense,{children:(0,t.jsx)(t3,{})})],321443)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/0289c4377358ae4f.js b/litellm/proxy/_experimental/out/_next/static/chunks/0289c4377358ae4f.js deleted file mode 100644 index 3dee581d934..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/0289c4377358ae4f.js +++ /dev/null @@ -1 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,11751,e=>{"use strict";function t(e){return""===e?null:e}e.s(["mapEmptyStringToNull",()=>t])},643449,e=>{"use strict";var t=e.i(843476),a=e.i(599724),s=e.i(389083),l=e.i(810757),r=e.i(477386),i=e.i(557662);e.s(["default",0,function({loggingConfigs:e=[],disabledCallbacks:n=[],variant:o="card",className:d=""}){let c=(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(l.CogIcon,{className:"h-4 w-4 text-blue-600"}),(0,t.jsx)(a.Text,{className:"font-semibold text-gray-900",children:"Logging Integrations"}),(0,t.jsx)(s.Badge,{color:"blue",size:"xs",children:e.length})]}),e.length>0?(0,t.jsx)("div",{className:"space-y-3",children:e.map((e,r)=>{var n;let o=(n=e.callback_name,Object.entries(i.callback_map).find(([e,t])=>t===n)?.[0]||n),d=i.callbackInfo[o]?.logo;return(0,t.jsxs)("div",{className:"flex items-center justify-between p-3 rounded-lg bg-blue-50 border border-blue-200",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[d?(0,t.jsx)("img",{src:d,alt:o,className:"w-5 h-5 object-contain"}):(0,t.jsx)(l.CogIcon,{className:"h-5 w-5 text-gray-400"}),(0,t.jsxs)("div",{children:[(0,t.jsx)(a.Text,{className:"font-medium text-blue-800",children:o}),(0,t.jsxs)(a.Text,{className:"text-xs text-blue-600",children:[Object.keys(e.callback_vars).length," parameters configured"]})]})]}),(0,t.jsx)(s.Badge,{color:(e=>{switch(e){case"success":return"green";case"failure":return"red";case"success_and_failure":return"blue";default:return"gray"}})(e.callback_type),size:"sm",children:(e=>{switch(e){case"success":return"Success Only";case"failure":return"Failure Only";case"success_and_failure":return"Success & Failure";default:return e}})(e.callback_type)})]},r)})}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 border border-gray-200",children:[(0,t.jsx)(l.CogIcon,{className:"h-4 w-4 text-gray-400"}),(0,t.jsx)(a.Text,{className:"text-gray-500 text-sm",children:"No logging integrations configured"})]})]}),(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(r.BanIcon,{className:"h-4 w-4 text-red-600"}),(0,t.jsx)(a.Text,{className:"font-semibold text-gray-900",children:"Disabled Callbacks"}),(0,t.jsx)(s.Badge,{color:"red",size:"xs",children:n.length})]}),n.length>0?(0,t.jsx)("div",{className:"space-y-3",children:n.map((e,l)=>{let n=i.reverse_callback_map[e]||e,o=i.callbackInfo[n]?.logo;return(0,t.jsxs)("div",{className:"flex items-center justify-between p-3 rounded-lg bg-red-50 border border-red-200",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[o?(0,t.jsx)("img",{src:o,alt:n,className:"w-5 h-5 object-contain"}):(0,t.jsx)(r.BanIcon,{className:"h-5 w-5 text-gray-400"}),(0,t.jsxs)("div",{children:[(0,t.jsx)(a.Text,{className:"font-medium text-red-800",children:n}),(0,t.jsx)(a.Text,{className:"text-xs text-red-600",children:"Disabled for this key"})]})]}),(0,t.jsx)(s.Badge,{color:"red",size:"sm",children:"Disabled"})]},l)})}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 border border-gray-200",children:[(0,t.jsx)(r.BanIcon,{className:"h-4 w-4 text-gray-400"}),(0,t.jsx)(a.Text,{className:"text-gray-500 text-sm",children:"No callbacks disabled"})]})]})]});return"card"===o?(0,t.jsxs)("div",{className:`bg-white border border-gray-200 rounded-lg p-6 ${d}`,children:[(0,t.jsx)("div",{className:"flex items-center gap-2 mb-6",children:(0,t.jsxs)("div",{children:[(0,t.jsx)(a.Text,{className:"font-semibold text-gray-900",children:"Logging Settings"}),(0,t.jsx)(a.Text,{className:"text-xs text-gray-500",children:"Active logging integrations and disabled callbacks for this key"})]})}),c]}):(0,t.jsxs)("div",{className:`${d}`,children:[(0,t.jsx)(a.Text,{className:"font-medium text-gray-900 mb-3",children:"Logging Settings"}),c]})}])},183588,e=>{"use strict";var t=e.i(843476),a=e.i(266484);e.s(["default",0,({value:e,onChange:s,disabledCallbacks:l=[],onDisabledCallbacksChange:r})=>(0,t.jsx)(a.default,{value:e,onChange:s,disabledCallbacks:l,onDisabledCallbacksChange:r})])},772345,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M168 504.2c1-43.7 10-86.1 26.9-126 17.3-41 42.1-77.7 73.7-109.4S337 212.3 378 195c42.4-17.9 87.4-27 133.9-27s91.5 9.1 133.8 27A341.5 341.5 0 01755 268.8c9.9 9.9 19.2 20.4 27.8 31.4l-60.2 47a8 8 0 003 14.1l175.7 43c5 1.2 9.9-2.6 9.9-7.7l.8-180.9c0-6.7-7.7-10.5-12.9-6.3l-56.4 44.1C765.8 155.1 646.2 92 511.8 92 282.7 92 96.3 275.6 92 503.8a8 8 0 008 8.2h60c4.4 0 7.9-3.5 8-7.8zm756 7.8h-60c-4.4 0-7.9 3.5-8 7.8-1 43.7-10 86.1-26.9 126-17.3 41-42.1 77.8-73.7 109.4A342.45 342.45 0 01512.1 856a342.24 342.24 0 01-243.2-100.8c-9.9-9.9-19.2-20.4-27.8-31.4l60.2-47a8 8 0 00-3-14.1l-175.7-43c-5-1.2-9.9 2.6-9.9 7.7l-.7 181c0 6.7 7.7 10.5 12.9 6.3l56.4-44.1C258.2 868.9 377.8 932 512.2 932c229.2 0 415.5-183.7 419.8-411.8a8 8 0 00-8-8.2z"}}]},name:"sync",theme:"outlined"};var l=e.i(9583),r=a.forwardRef(function(e,r){return a.createElement(l.default,(0,t.default)({},e,{ref:r,icon:s}))});e.s(["SyncOutlined",0,r],772345)},72713,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M880 184H712v-64c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v64H384v-64c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v64H144c-17.7 0-32 14.3-32 32v664c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V216c0-17.7-14.3-32-32-32zm-40 656H184V460h656v380zM184 392V256h128v48c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8v-48h256v48c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8v-48h128v136H184z"}}]},name:"calendar",theme:"outlined"};var l=e.i(9583),r=a.forwardRef(function(e,r){return a.createElement(l.default,(0,t.default)({},e,{ref:r,icon:s}))});e.s(["CalendarOutlined",0,r],72713)},962944,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M848 359.3H627.7L825.8 109c4.1-5.3.4-13-6.3-13H436c-2.8 0-5.5 1.5-6.9 4L170 547.5c-3.1 5.3.7 12 6.9 12h174.4l-89.4 357.6c-1.9 7.8 7.5 13.3 13.3 7.7L853.5 373c5.2-4.9 1.7-13.7-5.5-13.7zM378.2 732.5l60.3-241H281.1l189.6-327.4h224.6L487 427.4h211L378.2 732.5z"}}]},name:"thunderbolt",theme:"outlined"};var l=e.i(9583),r=a.forwardRef(function(e,r){return a.createElement(l.default,(0,t.default)({},e,{ref:r,icon:s}))});e.s(["ThunderboltOutlined",0,r],962944)},784647,304911,505022,721929,e=>{"use strict";var t=e.i(843476),a=e.i(464571),s=e.i(898586),l=e.i(592968),r=e.i(770914),i=e.i(312361),n=e.i(525720),o=e.i(447566),d=e.i(772345),c=e.i(955135),m=e.i(646563),u=e.i(771674),x=e.i(948401),p=e.i(72713),g=e.i(637235),h=e.i(962944);e.i(247167);var j=e.i(931067),_=e.i(271645);let y={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M866.9 169.9L527.1 54.1C523 52.7 517.5 52 512 52s-11 .7-15.1 2.1L157.1 169.9c-8.3 2.8-15.1 12.4-15.1 21.2v482.4c0 8.8 5.7 20.4 12.6 25.9L499.3 968c3.5 2.7 8 4.1 12.6 4.1s9.2-1.4 12.6-4.1l344.7-268.6c6.9-5.4 12.6-17 12.6-25.9V191.1c.2-8.8-6.6-18.3-14.9-21.2zM810 654.3L512 886.5 214 654.3V226.7l298-101.6 298 101.6v427.6zm-405.8-201c-3-4.1-7.8-6.6-13-6.6H336c-6.5 0-10.3 7.4-6.5 12.7l126.4 174a16.1 16.1 0 0026 0l212.6-292.7c3.8-5.3 0-12.7-6.5-12.7h-55.2c-5.1 0-10 2.5-13 6.6L468.9 542.4l-64.7-89.1z"}}]},name:"safety-certificate",theme:"outlined"};var b=e.i(9583),f=_.forwardRef(function(e,t){return _.createElement(b.default,(0,j.default)({},e,{ref:t,icon:y}))});let v={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M668.6 320c0-4.4-3.6-8-8-8h-54.5c-3 0-5.8 1.7-7.1 4.4l-84.7 168.8H511l-84.7-168.8a8 8 0 00-7.1-4.4h-55.7c-1.3 0-2.6.3-3.8 1-3.9 2.1-5.3 7-3.2 10.8l103.9 191.6h-57c-4.4 0-8 3.6-8 8v27.1c0 4.4 3.6 8 8 8h76v39h-76c-4.4 0-8 3.6-8 8v27.1c0 4.4 3.6 8 8 8h76V704c0 4.4 3.6 8 8 8h49.9c4.4 0 8-3.6 8-8v-63.5h76.3c4.4 0 8-3.6 8-8v-27.1c0-4.4-3.6-8-8-8h-76.3v-39h76.3c4.4 0 8-3.6 8-8v-27.1c0-4.4-3.6-8-8-8H564l103.7-191.6c.5-1.1.9-2.4.9-3.7zM157.9 504.2a352.7 352.7 0 01103.5-242.4c32.5-32.5 70.3-58.1 112.4-75.9 43.6-18.4 89.9-27.8 137.6-27.8 47.8 0 94.1 9.3 137.6 27.8 42.1 17.8 79.9 43.4 112.4 75.9 10 10 19.3 20.5 27.9 31.4l-50 39.1a8 8 0 003 14.1l156.8 38.3c5 1.2 9.9-2.6 9.9-7.7l.8-161.5c0-6.7-7.7-10.5-12.9-6.3l-47.8 37.4C770.7 146.3 648.6 82 511.5 82 277 82 86.3 270.1 82 503.8a8 8 0 008 8.2h60c4.3 0 7.8-3.5 7.9-7.8zM934 512h-60c-4.3 0-7.9 3.5-8 7.8a352.7 352.7 0 01-103.5 242.4 352.57 352.57 0 01-112.4 75.9c-43.6 18.4-89.9 27.8-137.6 27.8s-94.1-9.3-137.6-27.8a352.57 352.57 0 01-112.4-75.9c-10-10-19.3-20.5-27.9-31.4l49.9-39.1a8 8 0 00-3-14.1l-156.8-38.3c-5-1.2-9.9 2.6-9.9 7.7l-.8 161.7c0 6.7 7.7 10.5 12.9 6.3l47.8-37.4C253.3 877.7 375.4 942 512.5 942 747 942 937.7 753.9 942 520.2a8 8 0 00-8-8.2z"}}]},name:"transaction",theme:"outlined"};var N=_.forwardRef(function(e,t){return _.createElement(b.default,(0,j.default)({},e,{ref:t,icon:v}))}),k=e.i(262218);let{Text:T}=s.Typography;function w({userId:e}){return"default_user_id"===e?(0,t.jsx)(k.Tag,{color:"blue",children:"Default Proxy Admin"}):(0,t.jsx)(T,{children:e})}e.s(["default",()=>w],304911);let{Text:S}=s.Typography;function I({label:e,value:a,icon:s,truncate:l=!1,copyable:i=!1,defaultUserIdCheck:n=!1}){let o=!a,d=n&&"default_user_id"===a,c=d?(0,t.jsx)(w,{userId:a}):(0,t.jsx)(S,{strong:!0,copyable:!!(i&&!o&&!d)&&{tooltips:[`Copy ${e}`,"Copied!"]},ellipsis:l,style:l?{maxWidth:160,display:"block"}:void 0,children:o?"-":a});return(0,t.jsxs)("div",{children:[(0,t.jsxs)(r.Space,{size:4,children:[(0,t.jsx)(S,{type:"secondary",children:s}),(0,t.jsx)(S,{type:"secondary",style:{fontSize:12,textTransform:"uppercase",letterSpacing:"0.05em"},children:e})]}),(0,t.jsx)("div",{children:c})]})}let{Title:C,Text:A}=s.Typography;function F({data:e,onBack:s,onCreateNew:j,onRegenerate:_,onDelete:y,onResetSpend:b,canModifyKey:v=!0,backButtonText:k="Back to Keys",regenerateDisabled:T=!1,regenerateTooltip:w}){return(0,t.jsxs)("div",{children:[j&&(0,t.jsx)("div",{style:{marginBottom:16},children:(0,t.jsx)(a.Button,{type:"primary",icon:(0,t.jsx)(m.PlusOutlined,{}),onClick:j,children:"Create New Key"})}),(0,t.jsx)("div",{style:{marginBottom:16},children:(0,t.jsx)(a.Button,{type:"text",icon:(0,t.jsx)(o.ArrowLeftOutlined,{}),onClick:s,children:k})}),(0,t.jsxs)(n.Flex,{justify:"space-between",align:"start",style:{marginBottom:20},children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(C,{level:3,copyable:{tooltips:["Copy Key Alias","Copied!"]},style:{margin:0},children:e.keyName}),(0,t.jsxs)(A,{type:"secondary",copyable:{text:e.keyId,tooltips:["Copy Key ID","Copied!"]},children:["Key ID: ",e.keyId]})]}),v&&(0,t.jsxs)(r.Space,{children:[(0,t.jsx)(l.Tooltip,{title:w||"",children:(0,t.jsx)("span",{children:(0,t.jsx)(a.Button,{icon:(0,t.jsx)(d.SyncOutlined,{}),onClick:_,disabled:T,children:"Regenerate Key"})})}),b&&(0,t.jsx)(a.Button,{danger:!0,icon:(0,t.jsx)(N,{}),onClick:b,children:"Reset Spend"}),(0,t.jsx)(a.Button,{danger:!0,icon:(0,t.jsx)(c.DeleteOutlined,{}),onClick:y,children:"Delete Key"})]})]}),(0,t.jsxs)(n.Flex,{align:"stretch",gap:40,style:{marginBottom:40},children:[(0,t.jsxs)(r.Space,{direction:"vertical",size:16,children:[(0,t.jsx)(I,{label:"User Email",value:e.userEmail,icon:(0,t.jsx)(x.MailOutlined,{})}),(0,t.jsx)(I,{label:"User ID",value:e.userId,icon:(0,t.jsx)(u.UserOutlined,{}),truncate:!0,copyable:!0,defaultUserIdCheck:!0})]}),(0,t.jsx)(i.Divider,{type:"vertical",style:{height:"auto"}}),(0,t.jsxs)(r.Space,{direction:"vertical",size:16,children:[(0,t.jsx)(I,{label:"Created At",value:e.createdAt,icon:(0,t.jsx)(p.CalendarOutlined,{})}),(0,t.jsx)(I,{label:"Created By",value:e.createdBy,icon:(0,t.jsx)(f,{}),truncate:!0,copyable:!0,defaultUserIdCheck:!0})]}),(0,t.jsx)(i.Divider,{type:"vertical",style:{height:"auto"}}),(0,t.jsxs)(r.Space,{direction:"vertical",size:16,children:[(0,t.jsx)(I,{label:"Last Updated",value:e.lastUpdated,icon:(0,t.jsx)(g.ClockCircleOutlined,{})}),(0,t.jsx)(I,{label:"Last Active",value:e.lastActive,icon:(0,t.jsx)(h.ThunderboltOutlined,{})})]})]})]})}e.s(["KeyInfoHeader",()=>F],784647);var L=e.i(599724),M=e.i(389083),R=e.i(278587);let D=_.forwardRef(function(e,t){return _.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:t},e),_.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"}))});e.s(["default",0,({autoRotate:e=!1,rotationInterval:a,lastRotationAt:s,keyRotationAt:l,nextRotationAt:r,variant:i="card",className:n=""})=>{let o=e=>{let t=new Date(e),a=t.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"}),s=t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0});return`${a} at ${s}`},d=(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsx)("div",{className:"space-y-3",children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(R.RefreshIcon,{className:"h-4 w-4 text-blue-600"}),(0,t.jsx)(L.Text,{className:"font-semibold text-gray-900",children:"Auto-Rotation"}),(0,t.jsx)(M.Badge,{color:e?"green":"gray",size:"xs",children:e?"Enabled":"Disabled"}),e&&a&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(L.Text,{className:"text-gray-400",children:"•"}),(0,t.jsxs)(L.Text,{className:"text-sm text-gray-600",children:["Every ",a]})]})]})}),(e||s||l||r)&&(0,t.jsxs)("div",{className:"space-y-3",children:[s&&(0,t.jsxs)("div",{className:"flex items-center gap-2 p-3 bg-gray-50 border border-gray-200 rounded-md",children:[(0,t.jsx)(D,{className:"w-4 h-4 text-gray-500"}),(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsx)(L.Text,{className:"font-medium text-gray-700",children:"Last Rotation"}),(0,t.jsx)(L.Text,{className:"text-sm text-gray-600",children:o(s)})]})]}),(l||r)&&(0,t.jsxs)("div",{className:"flex items-center gap-2 p-3 bg-gray-50 border border-gray-200 rounded-md",children:[(0,t.jsx)(D,{className:"w-4 h-4 text-gray-500"}),(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsx)(L.Text,{className:"font-medium text-gray-700",children:"Next Scheduled Rotation"}),(0,t.jsx)(L.Text,{className:"text-sm text-gray-600",children:o(r||l||"")})]})]}),e&&!s&&!l&&!r&&(0,t.jsxs)("div",{className:"flex items-center gap-2 p-3 bg-gray-50 border border-gray-100 rounded-md",children:[(0,t.jsx)(D,{className:"w-4 h-4 text-gray-500"}),(0,t.jsx)(L.Text,{className:"text-gray-600",children:"No rotation history available"})]})]}),!e&&!s&&!l&&!r&&(0,t.jsxs)("div",{className:"flex items-center gap-2 p-3 bg-gray-50 border border-gray-100 rounded-md",children:[(0,t.jsx)(R.RefreshIcon,{className:"w-4 h-4 text-gray-400"}),(0,t.jsx)(L.Text,{className:"text-gray-600",children:"Auto-rotation is not enabled for this key"})]})]});return"card"===i?(0,t.jsxs)("div",{className:`bg-white border border-gray-200 rounded-lg p-6 ${n}`,children:[(0,t.jsx)("div",{className:"flex items-center gap-2 mb-6",children:(0,t.jsxs)("div",{children:[(0,t.jsx)(L.Text,{className:"font-semibold text-gray-900",children:"Auto-Rotation"}),(0,t.jsx)(L.Text,{className:"text-xs text-gray-500",children:"Automatic key rotation settings and status for this key"})]})}),d]}):(0,t.jsxs)("div",{className:`${n}`,children:[(0,t.jsx)(L.Text,{className:"font-medium text-gray-900 mb-3",children:"Auto-Rotation"}),d]})}],505022);let B=["logging"];e.s(["extractLoggingSettings",0,e=>e&&"object"==typeof e&&Array.isArray(e.logging)?e.logging:[],"formatMetadataForDisplay",0,(e,t=2)=>JSON.stringify(e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([e])=>!B.includes(e))):{},null,t),"stripTagsFromMetadata",0,e=>{if(!e||"object"!=typeof e)return e;let{tags:t,...a}=e;return a}],721929)},65932,690284,e=>{"use strict";var t=e.i(954616),a=e.i(912598),s=e.i(764205),l=e.i(135214),r=e.i(207082);let i=async(e,t)=>{let a=(0,s.getProxyBaseUrl)(),l=`${a?`${a}/key/${t}/reset_spend`:`/key/${t}/reset_spend`}`,r=await fetch(l,{method:"POST",headers:{[(0,s.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({reset_to:0})});if(!r.ok){let e=await r.json(),t=(0,s.deriveErrorMessage)(e);throw(0,s.handleError)(t),Error(t)}return r.json()};e.s(["useResetKeySpend",0,()=>{let{accessToken:e}=(0,l.default)(),s=(0,a.useQueryClient)();return(0,t.useMutation)({mutationFn:async t=>{if(!e)throw Error("Access token is required");return i(e,t)},onSuccess:()=>{s.invalidateQueries({queryKey:r.keyKeys.all})}})}],65932);var n=e.i(843476),o=e.i(994388),d=e.i(309426),c=e.i(350967),m=e.i(599724),u=e.i(779241),x=e.i(629569),p=e.i(808613),g=e.i(28651),h=e.i(212931),j=e.i(439189),_=e.i(497245),y=e.i(96226),b=e.i(435684);function f(e,t){let{years:a=0,months:s=0,weeks:l=0,days:r=0,hours:i=0,minutes:n=0,seconds:o=0}=t,d=(0,b.toDate)(e),c=s||a?(0,_.addMonths)(d,s+12*a):d,m=r||l?(0,j.addDays)(c,r+7*l):c;return(0,y.constructFrom)(e,m.getTime()+1e3*(o+60*(n+60*i)))}var v=e.i(271645),N=e.i(237016),k=e.i(727749);function T({selectedToken:e,visible:t,onClose:a,onKeyUpdate:r}){let{accessToken:i}=(0,l.default)(),[j]=p.Form.useForm(),[_,y]=(0,v.useState)(null),[b,T]=(0,v.useState)(null),[w,S]=(0,v.useState)(null),[I,C]=(0,v.useState)(!1),[A,F]=(0,v.useState)(!1),[L,M]=(0,v.useState)(null);(0,v.useEffect)(()=>{t&&e&&i&&(j.setFieldsValue({key_alias:e.key_alias,max_budget:e.max_budget,tpm_limit:e.tpm_limit,rpm_limit:e.rpm_limit,duration:e.duration||"",grace_period:""}),M(i),F(e.key_name===i))},[t,e,j,i]),(0,v.useEffect)(()=>{t||(y(null),C(!1),F(!1),M(null),j.resetFields())},[t,j]);let R=e=>{if(!e)return null;try{let t,a=new Date;if(e.endsWith("s"))t=f(a,{seconds:parseInt(e)});else if(e.endsWith("h"))t=f(a,{hours:parseInt(e)});else if(e.endsWith("d"))t=f(a,{days:parseInt(e)});else throw Error("Invalid duration format");return t.toLocaleString()}catch(e){return null}};(0,v.useEffect)(()=>{b?.duration?S(R(b.duration)):S(null)},[b?.duration]);let D=async()=>{if(e&&L){C(!0);try{let t=await j.validateFields(),a=await (0,s.regenerateKeyCall)(L,e.token||e.token_id,t);y(a.key),k.default.success("Virtual Key regenerated successfully"),console.log("Full regenerate response:",a);let l={token:a.token||a.key_id||e.token,key_name:a.key,max_budget:t.max_budget,tpm_limit:t.tpm_limit,rpm_limit:t.rpm_limit,expires:t.duration?R(t.duration):e.expires,...a};console.log("Updated key data with new token:",l),r&&r(l),C(!1)}catch(e){console.error("Error regenerating key:",e),k.default.fromBackend(e),C(!1)}}},B=()=>{y(null),C(!1),F(!1),M(null),j.resetFields(),a()};return(0,n.jsx)(h.Modal,{title:"Regenerate Virtual Key",open:t,onCancel:B,footer:_?[(0,n.jsx)(o.Button,{onClick:B,children:"Close"},"close")]:[(0,n.jsx)(o.Button,{onClick:B,className:"mr-2",children:"Cancel"},"cancel"),(0,n.jsx)(o.Button,{onClick:D,disabled:I,children:I?"Regenerating...":"Regenerate"},"regenerate")],children:_?(0,n.jsxs)(c.Grid,{numItems:1,className:"gap-2 w-full",children:[(0,n.jsx)(x.Title,{children:"Regenerated Key"}),(0,n.jsx)(d.Col,{numColSpan:1,children:(0,n.jsxs)("p",{children:["Please replace your old key with the new key generated. For security reasons,"," ",(0,n.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,n.jsxs)(d.Col,{numColSpan:1,children:[(0,n.jsx)(m.Text,{className:"mt-3",children:"Key Alias:"}),(0,n.jsx)("div",{className:"bg-gray-100 p-2 rounded mb-2",children:(0,n.jsx)("pre",{className:"break-words whitespace-normal",children:e?.key_alias||"No alias set"})}),(0,n.jsx)(m.Text,{className:"mt-3",children:"New Virtual Key:"}),(0,n.jsx)("div",{className:"bg-gray-100 p-2 rounded mb-2",children:(0,n.jsx)("pre",{className:"break-words whitespace-normal",children:_})}),(0,n.jsx)(N.CopyToClipboard,{text:_,onCopy:()=>k.default.success("Virtual Key copied to clipboard"),children:(0,n.jsx)(o.Button,{className:"mt-3",children:"Copy Virtual Key"})})]})]}):(0,n.jsxs)(p.Form,{form:j,layout:"vertical",onValuesChange:e=>{"duration"in e&&T(t=>({...t,duration:e.duration}))},children:[(0,n.jsx)(p.Form.Item,{name:"key_alias",label:"Key Alias",children:(0,n.jsx)(u.TextInput,{disabled:!0})}),(0,n.jsx)(p.Form.Item,{name:"max_budget",label:"Max Budget (USD)",children:(0,n.jsx)(g.InputNumber,{step:.01,precision:2,style:{width:"100%"}})}),(0,n.jsx)(p.Form.Item,{name:"tpm_limit",label:"TPM Limit",children:(0,n.jsx)(g.InputNumber,{style:{width:"100%"}})}),(0,n.jsx)(p.Form.Item,{name:"rpm_limit",label:"RPM Limit",children:(0,n.jsx)(g.InputNumber,{style:{width:"100%"}})}),(0,n.jsx)(p.Form.Item,{name:"duration",label:"Expire Key (eg: 30s, 30h, 30d)",className:"mt-8",children:(0,n.jsx)(u.TextInput,{placeholder:""})}),(0,n.jsxs)("div",{className:"mt-2 text-sm text-gray-500",children:["Current expiry: ",e?.expires?new Date(e.expires).toLocaleString():"Never"]}),w&&(0,n.jsxs)("div",{className:"mt-2 text-sm text-green-600",children:["New expiry: ",w]}),(0,n.jsx)(p.Form.Item,{name:"grace_period",label:"Grace Period (eg: 24h, 2d)",tooltip:"Keep the old key valid for this duration after rotation. Both keys work during this period for seamless cutover. Empty = immediate revoke.",className:"mt-8",rules:[{pattern:/^(\d+(s|m|h|d|w|mo))?$/,message:"Must be a duration like 30s, 30m, 24h, 2d, 1w, or 1mo"}],children:(0,n.jsx)(u.TextInput,{placeholder:"e.g. 24h, 2d (empty = immediate revoke)"})}),(0,n.jsx)("div",{className:"mt-2 text-sm text-gray-500",children:"Recommended: 24h to 72h for production keys to allow seamless client migration."})]})})}e.s(["RegenerateKeyModal",()=>T],690284)},20147,e=>{"use strict";var t=e.i(843476),a=e.i(135214),s=e.i(510674),l=e.i(292639),r=e.i(214541),i=e.i(500330),n=e.i(11751),o=e.i(530212),d=e.i(389083),c=e.i(994388),m=e.i(304967),u=e.i(350967),x=e.i(197647),p=e.i(653824),g=e.i(881073),h=e.i(404206),j=e.i(723731),_=e.i(599724),y=e.i(629569),b=e.i(808613),f=e.i(212931),v=e.i(262218),N=e.i(784647),k=e.i(271645),T=e.i(708347),w=e.i(557662),S=e.i(505022),I=e.i(127952),C=e.i(721929),A=e.i(643449),F=e.i(727749),L=e.i(764205),M=e.i(65932),R=e.i(384767),D=e.i(690284),B=e.i(190702),E=e.i(891547),P=e.i(921511),O=e.i(827252),K=e.i(779241),U=e.i(311451),V=e.i(199133),$=e.i(790848),z=e.i(592968),G=e.i(552130),W=e.i(9314),H=e.i(392110),q=e.i(844565),J=e.i(939510),Q=e.i(75921),Y=e.i(390605),X=e.i(702597),Z=e.i(435451),ee=e.i(183588),et=e.i(916940);function ea({keyData:e,onCancel:a,onSubmit:r,teams:i,accessToken:n,userID:o,userRole:d,premiumUser:m=!1}){let u=m||null!=d&&T.rolesWithWriteAccess.includes(d),[x]=b.Form.useForm(),[p,g]=(0,k.useState)([]),[h,j]=(0,k.useState)({}),_=i?.find(t=>t.team_id===e.team_id),[y,f]=(0,k.useState)([]),[v,N]=(0,k.useState)(Array.isArray(e.metadata?.litellm_disabled_callbacks)?(0,w.mapInternalToDisplayNames)(e.metadata.litellm_disabled_callbacks):[]),[S,I]=(0,k.useState)(e.auto_rotate||!1),[A,M]=(0,k.useState)(e.rotation_interval||""),[R,D]=(0,k.useState)(!e.expires),[B,ea]=(0,k.useState)(!1),{data:es}=(0,s.useProjects)(),{data:el}=(0,l.useUISettings)(),er=!!el?.values?.enable_projects_ui,ei=!!e.project_id,en=(()=>{if(!e.project_id)return null;let t=es?.find(t=>t.project_id===e.project_id);return t?.project_alias?`${t.project_alias} (${e.project_id})`:e.project_id})();(0,k.useEffect)(()=>{let t=async()=>{if(o&&d&&n)try{if(null===e.team_id){let e=(await (0,L.modelAvailableCall)(n,o,d)).data.map(e=>e.id);f(e)}else if(_?.team_id){let e=await (0,X.fetchTeamModels)(o,d,n,_.team_id);f(Array.from(new Set([..._.models,...e])))}}catch(e){console.error("Error fetching models:",e)}};(async()=>{if(n)try{let e=await (0,L.getPromptsList)(n);g(e.prompts.map(e=>e.prompt_id))}catch(e){console.error("Failed to fetch prompts:",e)}})(),t()},[o,d,n,_,e.team_id]),(0,k.useEffect)(()=>{x.setFieldValue("disabled_callbacks",v)},[x,v]);let eo=e=>e&&({"24h":"daily","7d":"weekly","30d":"monthly"})[e]||null,ed={...e,token:e.token||e.token_id,budget_duration:eo(e.budget_duration),metadata:(0,C.formatMetadataForDisplay)((0,C.stripTagsFromMetadata)(e.metadata)),guardrails:e.metadata?.guardrails,disable_global_guardrails:e.metadata?.disable_global_guardrails||!1,prompts:e.metadata?.prompts,tags:e.metadata?.tags,vector_stores:e.object_permission?.vector_stores||[],mcp_servers_and_groups:{servers:e.object_permission?.mcp_servers||[],accessGroups:e.object_permission?.mcp_access_groups||[]},mcp_tool_permissions:e.object_permission?.mcp_tool_permissions||{},agents_and_groups:{agents:e.object_permission?.agents||[],accessGroups:e.object_permission?.agent_access_groups||[]},logging_settings:(0,C.extractLoggingSettings)(e.metadata),disabled_callbacks:Array.isArray(e.metadata?.litellm_disabled_callbacks)?(0,w.mapInternalToDisplayNames)(e.metadata.litellm_disabled_callbacks):[],access_group_ids:e.access_group_ids||[],auto_rotate:e.auto_rotate||!1,...e.rotation_interval&&{rotation_interval:e.rotation_interval},allowed_routes:Array.isArray(e.allowed_routes)&&e.allowed_routes.length>0?e.allowed_routes.join(", "):""};(0,k.useEffect)(()=>{x.setFieldsValue({...e,token:e.token||e.token_id,budget_duration:eo(e.budget_duration),metadata:(0,C.formatMetadataForDisplay)((0,C.stripTagsFromMetadata)(e.metadata)),guardrails:e.metadata?.guardrails,disable_global_guardrails:e.metadata?.disable_global_guardrails||!1,prompts:e.metadata?.prompts,tags:e.metadata?.tags,vector_stores:e.object_permission?.vector_stores||[],mcp_servers_and_groups:{servers:e.object_permission?.mcp_servers||[],accessGroups:e.object_permission?.mcp_access_groups||[]},mcp_tool_permissions:e.object_permission?.mcp_tool_permissions||{},logging_settings:(0,C.extractLoggingSettings)(e.metadata),disabled_callbacks:Array.isArray(e.metadata?.litellm_disabled_callbacks)?(0,w.mapInternalToDisplayNames)(e.metadata.litellm_disabled_callbacks):[],access_group_ids:e.access_group_ids||[],auto_rotate:e.auto_rotate||!1,...e.rotation_interval&&{rotation_interval:e.rotation_interval},allowed_routes:Array.isArray(e.allowed_routes)&&e.allowed_routes.length>0?e.allowed_routes.join(", "):""})},[e,x]),(0,k.useEffect)(()=>{x.setFieldValue("auto_rotate",S)},[S,x]),(0,k.useEffect)(()=>{A&&x.setFieldValue("rotation_interval",A)},[A,x]),(0,k.useEffect)(()=>{(async()=>{if(n)try{let e=await (0,L.tagListCall)(n);j(e)}catch(e){F.default.fromBackend("Error fetching tags: "+e)}})()},[n]);let ec=async e=>{try{if(ea(!0),"string"==typeof e.allowed_routes){let t=e.allowed_routes.trim();""===t?e.allowed_routes=[]:e.allowed_routes=t.split(",").map(e=>e.trim()).filter(e=>e.length>0)}R&&(e.duration=null),await r(e)}finally{ea(!1)}};return(0,t.jsxs)(b.Form,{form:x,onFinish:ec,initialValues:ed,layout:"vertical",children:[(0,t.jsx)(b.Form.Item,{label:"Key Alias",name:"key_alias",children:(0,t.jsx)(K.TextInput,{})}),(0,t.jsx)(b.Form.Item,{label:"Models",name:"models",children:(0,t.jsx)(b.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.allowed_routes!==t.allowed_routes||e.models!==t.models,children:({getFieldValue:e,setFieldValue:a})=>{let s=e("allowed_routes")||"",l="string"==typeof s&&""!==s.trim()?s.split(",").map(e=>e.trim()).filter(e=>e.length>0):[],r=l.includes("management_routes")||l.includes("info_routes"),i=e("models")||[];return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(V.Select,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},disabled:r,value:r?[]:i,onChange:e=>a("models",e),children:[y.length>0&&(0,t.jsx)(V.Select.Option,{value:"all-team-models",children:"All Team Models"}),y.map(e=>(0,t.jsx)(V.Select.Option,{value:e,children:e},e))]}),r&&(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Models field is disabled for this key type"})]})}})}),(0,t.jsx)(b.Form.Item,{label:"Key Type",children:(0,t.jsx)(b.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.allowed_routes!==t.allowed_routes,children:({getFieldValue:e,setFieldValue:a})=>{var s;let l=e("allowed_routes")||"",r=(s="string"==typeof l&&""!==l.trim()?l.split(",").map(e=>e.trim()).filter(e=>e.length>0):[])&&0!==s.length?s.includes("llm_api_routes")?"llm_api":s.includes("management_routes")?"management":s.includes("info_routes")?"read_only":"default":"default";return(0,t.jsxs)(V.Select,{placeholder:"Select key type",style:{width:"100%"},optionLabelProp:"label",value:r,onChange:e=>{switch(e){case"default":a("allowed_routes","");break;case"llm_api":a("allowed_routes","llm_api_routes");break;case"management":a("allowed_routes","management_routes"),a("models",[])}},children:[(0,t.jsx)(V.Select.Option,{value:"default",label:"Default",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Default"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call AI APIs + Management routes"})]})}),(0,t.jsx)(V.Select.Option,{value:"llm_api",label:"AI APIs",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"AI APIs"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call only AI API routes (chat/completions, embeddings, etc.)"})]})}),(0,t.jsx)(V.Select.Option,{value:"management",label:"Management",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Management"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call only management routes (user/team/key management)"})]})})]})}})}),(0,t.jsx)(b.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Routes"," ",(0,t.jsx)(z.Tooltip,{title:"List of allowed routes for the key (comma-separated). Can be specific routes (e.g., '/chat/completions') or route patterns (e.g., 'llm_api_routes', 'management_routes', '/keys/*'). Leave empty to allow all routes.",children:(0,t.jsx)(O.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_routes",children:(0,t.jsx)(U.Input,{placeholder:"Enter allowed routes (comma-separated). Special values: llm_api_routes, management_routes. Examples: llm_api_routes, /chat/completions, /keys/*. Leave empty to allow all routes"})}),(0,t.jsx)(b.Form.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,t.jsx)(Z.default,{step:.01,style:{width:"100%"},placeholder:"Enter a numerical value"})}),(0,t.jsx)(b.Form.Item,{label:"Reset Budget",name:"budget_duration",children:(0,t.jsxs)(V.Select,{placeholder:"n/a",children:[(0,t.jsx)(V.Select.Option,{value:"daily",children:"Daily"}),(0,t.jsx)(V.Select.Option,{value:"weekly",children:"Weekly"}),(0,t.jsx)(V.Select.Option,{value:"monthly",children:"Monthly"})]})}),(0,t.jsx)(b.Form.Item,{label:"TPM Limit",name:"tpm_limit",children:(0,t.jsx)(Z.default,{min:0})}),(0,t.jsx)(J.default,{type:"tpm",name:"tpm_limit_type",showDetailedDescriptions:!1}),(0,t.jsx)(b.Form.Item,{label:"RPM Limit",name:"rpm_limit",children:(0,t.jsx)(Z.default,{min:0})}),(0,t.jsx)(J.default,{type:"rpm",name:"rpm_limit_type",showDetailedDescriptions:!1}),(0,t.jsx)(b.Form.Item,{label:"Max Parallel Requests",name:"max_parallel_requests",children:(0,t.jsx)(Z.default,{min:0})}),(0,t.jsx)(b.Form.Item,{label:"Model TPM Limit",name:"model_tpm_limit",children:(0,t.jsx)(U.Input.TextArea,{rows:4,placeholder:'{"gpt-4": 100, "claude-v1": 200}'})}),(0,t.jsx)(b.Form.Item,{label:"Model RPM Limit",name:"model_rpm_limit",children:(0,t.jsx)(U.Input.TextArea,{rows:4,placeholder:'{"gpt-4": 100, "claude-v1": 200}'})}),(0,t.jsx)(b.Form.Item,{label:"Guardrails",name:"guardrails",children:n&&(0,t.jsx)(E.default,{onChange:e=>{x.setFieldValue("guardrails",e)},accessToken:n,disabled:!u})}),(0,t.jsx)(b.Form.Item,{label:(0,t.jsxs)("span",{children:["Disable Global Guardrails"," ",(0,t.jsx)(z.Tooltip,{title:"When enabled, this key will bypass any guardrails configured to run on every request (global guardrails)",children:(0,t.jsx)(O.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"disable_global_guardrails",valuePropName:"checked",children:(0,t.jsx)($.Switch,{disabled:!u,checkedChildren:"Yes",unCheckedChildren:"No"})}),(0,t.jsx)(b.Form.Item,{label:(0,t.jsxs)("span",{children:["Policies"," ",(0,t.jsx)(z.Tooltip,{title:"Apply policies to this key to control guardrails and other settings",children:(0,t.jsx)(O.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"policies",children:n&&(0,t.jsx)(P.default,{onChange:e=>{x.setFieldValue("policies",e)},accessToken:n,disabled:!m})}),(0,t.jsx)(b.Form.Item,{label:"Tags",name:"tags",children:(0,t.jsx)(V.Select,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter tags",options:Object.values(h).map(e=>({value:e.name,label:e.name,title:e.description||e.name}))})}),(0,t.jsx)(b.Form.Item,{label:"Prompts",name:"prompts",children:(0,t.jsx)(z.Tooltip,{title:m?"":"Setting prompts by key is a premium feature",placement:"top",children:(0,t.jsx)(V.Select,{mode:"tags",style:{width:"100%"},disabled:!m,placeholder:m?Array.isArray(e.metadata?.prompts)&&e.metadata.prompts.length>0?`Current: ${e.metadata.prompts.join(", ")}`:"Select or enter prompts":"Premium feature - Upgrade to set prompts by key",options:p.map(e=>({value:e,label:e}))})})}),(0,t.jsx)(b.Form.Item,{label:(0,t.jsxs)("span",{children:["Access Groups"," ",(0,t.jsx)(z.Tooltip,{title:"Assign access groups to this key. Access groups control which models, MCP servers, and agents this key can use",children:(0,t.jsx)(O.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"access_group_ids",children:(0,t.jsx)(W.default,{placeholder:"Select access groups (optional)"})}),(0,t.jsx)(b.Form.Item,{label:"Allowed Pass Through Routes",name:"allowed_passthrough_routes",children:(0,t.jsx)(z.Tooltip,{title:m?"":"Setting allowed pass through routes by key is a premium feature",placement:"top",children:(0,t.jsx)(q.default,{onChange:e=>x.setFieldValue("allowed_passthrough_routes",e),value:x.getFieldValue("allowed_passthrough_routes"),accessToken:n||"",placeholder:m?Array.isArray(e.metadata?.allowed_passthrough_routes)&&e.metadata.allowed_passthrough_routes.length>0?`Current: ${e.metadata.allowed_passthrough_routes.join(", ")}`:"Select or enter allowed pass through routes":"Premium feature - Upgrade to set allowed pass through routes by key",disabled:!m})})}),(0,t.jsx)(b.Form.Item,{label:"Vector Stores",name:"vector_stores",children:(0,t.jsx)(et.default,{onChange:e=>x.setFieldValue("vector_stores",e),value:x.getFieldValue("vector_stores"),accessToken:n||"",placeholder:"Select vector stores"})}),(0,t.jsx)(b.Form.Item,{label:"MCP Servers / Access Groups",name:"mcp_servers_and_groups",children:(0,t.jsx)(Q.default,{onChange:e=>x.setFieldValue("mcp_servers_and_groups",e),value:x.getFieldValue("mcp_servers_and_groups"),accessToken:n||"",placeholder:"Select MCP servers or access groups (optional)"})}),(0,t.jsx)(b.Form.Item,{name:"mcp_tool_permissions",initialValue:{},hidden:!0,children:(0,t.jsx)(U.Input,{type:"hidden"})}),(0,t.jsx)(b.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.mcp_servers_and_groups!==t.mcp_servers_and_groups||e.mcp_tool_permissions!==t.mcp_tool_permissions,children:()=>(0,t.jsx)("div",{className:"mb-6",children:(0,t.jsx)(Y.default,{accessToken:n||"",selectedServers:x.getFieldValue("mcp_servers_and_groups")?.servers||[],toolPermissions:x.getFieldValue("mcp_tool_permissions")||{},onChange:e=>x.setFieldsValue({mcp_tool_permissions:e})})})}),(0,t.jsx)(b.Form.Item,{label:"Agents / Access Groups",name:"agents_and_groups",children:(0,t.jsx)(G.default,{onChange:e=>x.setFieldValue("agents_and_groups",e),value:x.getFieldValue("agents_and_groups"),accessToken:n||"",placeholder:"Select agents or access groups (optional)"})}),(0,t.jsx)(b.Form.Item,{label:"Team ID",name:"team_id",help:er&&ei?"Team is locked because this key belongs to a project":void 0,children:(0,t.jsx)(V.Select,{placeholder:"Select team",showSearch:!0,disabled:er&&ei,style:{width:"100%"},filterOption:(e,t)=>{let a=i?.find(e=>e.team_id===t?.value);return!!a&&(a.team_alias?.toLowerCase().includes(e.toLowerCase())??!1)},children:i?.map(e=>(0,t.jsx)(V.Select.Option,{value:e.team_id,children:`${e.team_alias} (${e.team_id})`},e.team_id))})}),er&&ei&&(0,t.jsx)(b.Form.Item,{label:"Project",children:(0,t.jsx)(U.Input,{value:en??"",disabled:!0})}),(0,t.jsx)(b.Form.Item,{label:"Logging Settings",name:"logging_settings",children:(0,t.jsx)(ee.default,{value:x.getFieldValue("logging_settings"),onChange:e=>x.setFieldValue("logging_settings",e),disabledCallbacks:v,onDisabledCallbacksChange:e=>{N((0,w.mapInternalToDisplayNames)(e)),x.setFieldValue("disabled_callbacks",e)}})}),(0,t.jsx)(b.Form.Item,{label:"Metadata",name:"metadata",children:(0,t.jsx)(U.Input.TextArea,{rows:10})}),(0,t.jsxs)("div",{className:"mb-4",children:[(0,t.jsx)(H.default,{form:x,autoRotationEnabled:S,onAutoRotationChange:I,rotationInterval:A,onRotationIntervalChange:M,neverExpire:R,onNeverExpireChange:D}),(0,t.jsx)(b.Form.Item,{name:"duration",hidden:!0,initialValue:"",children:(0,t.jsx)(U.Input,{})})]}),(0,t.jsx)(b.Form.Item,{name:"token",hidden:!0,children:(0,t.jsx)(U.Input,{})}),(0,t.jsx)(b.Form.Item,{name:"disabled_callbacks",hidden:!0,children:(0,t.jsx)(U.Input,{})}),(0,t.jsx)(b.Form.Item,{name:"auto_rotate",hidden:!0,children:(0,t.jsx)(U.Input,{})}),(0,t.jsx)(b.Form.Item,{name:"rotation_interval",hidden:!0,children:(0,t.jsx)(U.Input,{})}),(0,t.jsx)("div",{className:"sticky z-10 bg-white p-4 border-t border-gray-200 bottom-[-1.5rem] inset-x-[-1.5rem]",children:(0,t.jsxs)("div",{className:"flex justify-end items-center gap-2",children:[(0,t.jsx)(c.Button,{variant:"secondary",onClick:a,disabled:B,children:"Cancel"}),(0,t.jsx)(c.Button,{type:"submit",loading:B,children:"Save Changes"})]})})]})}function es({onClose:e,keyData:E,teams:P,onKeyDataUpdate:O,onDelete:K,backButtonText:U="Back to Keys"}){let V,{accessToken:$,userId:z,userRole:G,premiumUser:W}=(0,a.default)(),H=W||null!=G&&T.rolesWithWriteAccess.includes(G),{teams:q}=(0,r.default)(),{data:J}=(0,s.useProjects)(),{data:Q}=(0,l.useUISettings)(),Y=!!Q?.values?.enable_projects_ui,[X,Z]=(0,k.useState)(!1),[ee]=b.Form.useForm(),[et,es]=(0,k.useState)(!1),[el,er]=(0,k.useState)(!1),[ei,en]=(0,k.useState)(""),[eo,ed]=(0,k.useState)(!1),[ec,em]=(0,k.useState)(!1),{mutate:eu,isPending:ex}=(0,M.useResetKeySpend)(),[ep,eg]=(0,k.useState)(E),[eh,ej]=(0,k.useState)(null),[e_,ey]=(0,k.useState)(!1),[eb,ef]=(0,k.useState)({}),[ev,eN]=(0,k.useState)(!1);if((0,k.useEffect)(()=>{E&&eg(E)},[E]),(0,k.useEffect)(()=>{(async()=>{let e=ep?.metadata?.policies;if(!$||!e||!Array.isArray(e)||0===e.length)return;eN(!0);let t={};try{await Promise.all(e.map(async e=>{try{let a=await (0,L.getPolicyInfoWithGuardrails)($,e);t[e]=a.resolved_guardrails||[]}catch(a){console.error(`Failed to fetch guardrails for policy ${e}:`,a),t[e]=[]}})),ef(t)}catch(e){console.error("Failed to fetch policy guardrails:",e)}finally{eN(!1)}})()},[$,ep?.metadata?.policies]),(0,k.useEffect)(()=>{if(e_){let e=setTimeout(()=>{ey(!1)},5e3);return()=>clearTimeout(e)}},[e_]),!ep)return(0,t.jsxs)("div",{className:"p-4",children:[(0,t.jsx)(c.Button,{icon:o.ArrowLeftIcon,variant:"light",onClick:e,className:"mb-4",children:U}),(0,t.jsx)(_.Text,{children:"Key not found"})]});let ek=async e=>{try{if(!$)return;let t=e.token;if(e.key=t,H||(delete e.guardrails,delete e.prompts),e.max_budget=(0,n.mapEmptyStringToNull)(e.max_budget),void 0!==e.vector_stores&&(e.object_permission={...ep.object_permission,vector_stores:e.vector_stores||[]},delete e.vector_stores),void 0!==e.mcp_servers_and_groups){let{servers:t,accessGroups:a}=e.mcp_servers_and_groups||{servers:[],accessGroups:[]};e.object_permission={...ep.object_permission,mcp_servers:t||[],mcp_access_groups:a||[]},delete e.mcp_servers_and_groups}if(void 0!==e.mcp_tool_permissions){let t=e.mcp_tool_permissions||{};Object.keys(t).length>0&&(e.object_permission={...e.object_permission,mcp_tool_permissions:t}),delete e.mcp_tool_permissions}if(void 0!==e.agents_and_groups){let{agents:t,accessGroups:a}=e.agents_and_groups||{agents:[],accessGroups:[]};e.object_permission={...e.object_permission,agents:t||[],agent_access_groups:a||[]},delete e.agents_and_groups}if(e.max_budget=(0,n.mapEmptyStringToNull)(e.max_budget),e.tpm_limit=(0,n.mapEmptyStringToNull)(e.tpm_limit),e.rpm_limit=(0,n.mapEmptyStringToNull)(e.rpm_limit),e.max_parallel_requests=(0,n.mapEmptyStringToNull)(e.max_parallel_requests),e.metadata&&"string"==typeof e.metadata)try{let t=JSON.parse(e.metadata);"tags"in t&&delete t.tags,e.metadata={...t,...Array.isArray(e.tags)&&e.tags.length>0?{tags:e.tags}:{},...e.guardrails?.length>0?{guardrails:e.guardrails}:{},...Array.isArray(e.logging_settings)&&e.logging_settings.length>0?{logging:e.logging_settings}:{},...e.disabled_callbacks?.length>0?{litellm_disabled_callbacks:(0,w.mapDisplayToInternalNames)(e.disabled_callbacks)}:{}}}catch(e){console.error("Error parsing metadata JSON:",e),F.default.error("Invalid metadata JSON");return}else{let{tags:t,...a}=e.metadata||{};e.metadata={...a,...Array.isArray(e.tags)&&e.tags.length>0?{tags:e.tags}:{},...e.guardrails?.length>0?{guardrails:e.guardrails}:{},...Array.isArray(e.logging_settings)&&e.logging_settings.length>0?{logging:e.logging_settings}:{},...e.disabled_callbacks?.length>0?{litellm_disabled_callbacks:(0,w.mapDisplayToInternalNames)(e.disabled_callbacks)}:{}}}"tags"in e&&delete e.tags,delete e.logging_settings,e.budget_duration&&(e.budget_duration=({daily:"24h",weekly:"7d",monthly:"30d"})[e.budget_duration]);let a=await (0,L.keyUpdateCall)($,e);eg(e=>e?{...e,...a}:void 0),O&&O(a),F.default.success("Key updated successfully"),Z(!1)}catch(e){F.default.fromBackend((0,B.parseErrorMessage)(e)),console.error("Error updating key:",e)}},eT=async()=>{try{if(er(!0),!$)return;await (0,L.keyDeleteCall)($,ep.token||ep.token_id),F.default.success("Key deleted successfully"),K&&K(),e()}catch(e){console.error("Error deleting the key:",e),F.default.fromBackend(e)}finally{er(!1),es(!1),en("")}},ew=e=>{let t=new Date(e),a=t.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"}),s=t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0});return`${a} at ${s}`},eS=(0,T.isProxyAdminRole)(G||"")||q&&(0,T.isUserTeamAdminForSingleTeam)(q?.filter(e=>e.team_id===ep.team_id)[0]?.members_with_roles,z||"")||z===ep.user_id&&"Internal Viewer"!==G,eI=(0,T.isProxyAdminRole)(G||"")||q&&(0,T.isUserTeamAdminForSingleTeam)(q?.filter(e=>e.team_id===ep.team_id)[0]?.members_with_roles,z||"");return(0,t.jsxs)("div",{className:"w-full h-screen p-4",children:[(0,t.jsx)(N.KeyInfoHeader,{data:{keyName:ep.key_alias||"Virtual Key",keyId:ep.token_id||ep.token,userId:ep.user_id||"",userEmail:ep.user_email||"",createdBy:ep.user_email||ep.user_id||"",createdAt:ep.created_at?ew(ep.created_at):"",lastUpdated:ep.updated_at?ew(ep.updated_at):"",lastActive:ep.last_active?ew(ep.last_active):"Never"},onBack:e,onRegenerate:()=>ed(!0),onDelete:()=>es(!0),onResetSpend:eI?()=>em(!0):void 0,canModifyKey:eS,backButtonText:U,regenerateDisabled:!W,regenerateTooltip:W?void 0:"This is a LiteLLM Enterprise feature, and requires a valid key to use."}),(0,t.jsx)(D.RegenerateKeyModal,{selectedToken:ep,visible:eo,onClose:()=>ed(!1),onKeyUpdate:e=>{eg(t=>{if(t)return{...t,...e,created_at:new Date().toLocaleString()}}),ej(new Date),ey(!0),O&&O({...e,created_at:new Date().toLocaleString()})}}),(0,t.jsx)(I.default,{isOpen:et,title:"Delete Key",alertMessage:"This action is irreversible and will immediately revoke access for any applications using this key.",message:"Are you sure you want to delete this Virtual Key?",resourceInformationTitle:"Key Information",resourceInformation:[{label:"Key Alias",value:ep?.key_alias||"-"},{label:"Key ID",value:ep?.token_id||ep?.token||"-",code:!0},{label:"Team ID",value:ep?.team_id||"-",code:!0},{label:"Spend",value:ep?.spend?`$${(0,i.formatNumberWithCommas)(ep.spend,4)}`:"$0.0000"}],onCancel:()=>{es(!1),en("")},onOk:eT,confirmLoading:el,requiredConfirmation:ep?.key_alias}),(0,t.jsxs)(f.Modal,{title:"Reset Key Spend",open:ec,onOk:()=>{eu(ep.token||ep.token_id,{onSuccess:()=>{eg(e=>e?{...e,spend:0}:void 0),O&&O({spend:0}),F.default.success("Key spend reset to $0"),em(!1)},onError:e=>{F.default.fromBackend((0,B.parseErrorMessage)(e)),console.error("Error resetting key spend:",e)}})},onCancel:()=>em(!1),okText:"Reset",okButtonProps:{danger:!0},confirmLoading:ex,children:[(0,t.jsxs)("p",{children:["Reset spend for ",(0,t.jsx)("strong",{children:ep?.key_alias||ep?.token_id||"this key"})," to"," ",(0,t.jsx)("strong",{children:"$0"}),"?"]}),(0,t.jsxs)("p",{style:{color:"#666",fontSize:"0.875rem",marginTop:8},children:["Current spend: ",(0,t.jsxs)("strong",{children:["$",(0,i.formatNumberWithCommas)(ep.spend,4)]}),". Spend history is preserved in logs. This resets the current period spend counter, the same as an automatic budget reset."]})]}),(0,t.jsxs)(p.TabGroup,{children:[(0,t.jsxs)(g.TabList,{className:"mb-4",children:[(0,t.jsx)(x.Tab,{children:"Overview"}),(0,t.jsx)(x.Tab,{children:"Settings"})]}),(0,t.jsxs)(j.TabPanels,{children:[(0,t.jsx)(h.TabPanel,{children:(0,t.jsxs)(u.Grid,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,t.jsxs)(m.Card,{children:[(0,t.jsx)(_.Text,{children:"Spend"}),(0,t.jsxs)("div",{className:"mt-2",children:[(0,t.jsxs)(y.Title,{children:["$",(0,i.formatNumberWithCommas)(ep.spend,4)]}),(0,t.jsxs)(_.Text,{children:["of"," ",null!==ep.max_budget?`$${(0,i.formatNumberWithCommas)(ep.max_budget)}`:"Unlimited"]})]})]}),(0,t.jsxs)(m.Card,{children:[(0,t.jsx)(_.Text,{children:"Rate Limits"}),(0,t.jsxs)("div",{className:"mt-2",children:[(0,t.jsxs)(_.Text,{children:["TPM: ",null!==ep.tpm_limit?ep.tpm_limit:"Unlimited"]}),(0,t.jsxs)(_.Text,{children:["RPM: ",null!==ep.rpm_limit?ep.rpm_limit:"Unlimited"]})]})]}),(0,t.jsxs)(m.Card,{children:[(0,t.jsx)(_.Text,{children:"Models"}),(0,t.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:ep.models&&ep.models.length>0?ep.models.map((e,a)=>(0,t.jsx)(d.Badge,{color:"red",children:e},a)):(0,t.jsx)(_.Text,{children:"No models specified"})})]}),(0,t.jsx)(m.Card,{children:(0,t.jsx)(R.default,{objectPermission:ep.object_permission,variant:"inline",accessToken:$})}),(0,t.jsxs)(m.Card,{children:[(0,t.jsx)(_.Text,{className:"font-medium mb-3",children:"Guardrails"}),Array.isArray(ep.metadata?.guardrails)&&ep.metadata.guardrails.length>0?(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:ep.metadata.guardrails.map((e,a)=>(0,t.jsx)(d.Badge,{color:"blue",children:e},a))}):(0,t.jsx)(_.Text,{className:"text-gray-500",children:"No guardrails configured"}),"boolean"==typeof ep.metadata?.disable_global_guardrails&&!0===ep.metadata.disable_global_guardrails&&(0,t.jsx)("div",{className:"mt-3 pt-3 border-t border-gray-200",children:(0,t.jsx)(d.Badge,{color:"yellow",children:"Global Guardrails Disabled"})})]}),(0,t.jsxs)(m.Card,{children:[(0,t.jsx)(_.Text,{className:"font-medium mb-3",children:"Policies"}),Array.isArray(ep.metadata?.policies)&&ep.metadata.policies.length>0?(0,t.jsx)("div",{className:"space-y-4",children:ep.metadata.policies.map((e,a)=>(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(d.Badge,{color:"purple",children:e}),ev&&(0,t.jsx)(_.Text,{className:"text-xs text-gray-400",children:"Loading guardrails..."})]}),!ev&&eb[e]&&eb[e].length>0&&(0,t.jsxs)("div",{className:"ml-4 pl-3 border-l-2 border-gray-200",children:[(0,t.jsx)(_.Text,{className:"text-xs text-gray-500 mb-1",children:"Resolved Guardrails:"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:eb[e].map((e,a)=>(0,t.jsx)(d.Badge,{color:"blue",size:"xs",children:e},a))})]})]},a))}):(0,t.jsx)(_.Text,{className:"text-gray-500",children:"No policies configured"})]}),(0,t.jsx)(A.default,{loggingConfigs:(0,C.extractLoggingSettings)(ep.metadata),disabledCallbacks:Array.isArray(ep.metadata?.litellm_disabled_callbacks)?(0,w.mapInternalToDisplayNames)(ep.metadata.litellm_disabled_callbacks):[],variant:"card"}),(0,t.jsx)(S.default,{autoRotate:ep.auto_rotate,rotationInterval:ep.rotation_interval,lastRotationAt:ep.last_rotation_at,keyRotationAt:ep.key_rotation_at,nextRotationAt:ep.next_rotation_at,variant:"card"})]})}),(0,t.jsx)(h.TabPanel,{children:(0,t.jsxs)(m.Card,{className:"overflow-y-auto max-h-[65vh]",children:[(0,t.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,t.jsx)(y.Title,{children:"Key Settings"}),!X&&eS&&(0,t.jsx)(c.Button,{onClick:()=>Z(!0),children:"Edit Settings"})]}),X?(0,t.jsx)(ea,{keyData:ep,onCancel:()=>Z(!1),onSubmit:ek,teams:P,accessToken:$,userID:z,userRole:G,premiumUser:W}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Key ID"}),(0,t.jsx)(_.Text,{className:"font-mono",children:ep.token_id||ep.token})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Key Alias"}),(0,t.jsx)(_.Text,{children:ep.key_alias||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Secret Key"}),(0,t.jsx)(_.Text,{className:"font-mono",children:ep.key_name})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Team ID"}),(0,t.jsx)(_.Text,{children:ep.team_id||"Not Set"})]}),Y&&(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Project"}),(0,t.jsx)(_.Text,{children:ep.project_id?(V=J?.find(e=>e.project_id===ep.project_id),V?.project_alias?`${V.project_alias} (${ep.project_id})`:ep.project_id):"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Organization"}),(0,t.jsx)(_.Text,{children:(ep.organization_id??ep.org_id)||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Created"}),(0,t.jsx)(_.Text,{children:ew(ep.created_at)})]}),eh&&(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Last Regenerated"}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(_.Text,{children:ew(eh)}),(0,t.jsx)(d.Badge,{color:"green",size:"xs",children:"Recent"})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Expires"}),(0,t.jsx)(_.Text,{children:ep.expires?ew(ep.expires):"Never"})]}),(0,t.jsx)(S.default,{autoRotate:ep.auto_rotate,rotationInterval:ep.rotation_interval,lastRotationAt:ep.last_rotation_at,keyRotationAt:ep.key_rotation_at,nextRotationAt:ep.next_rotation_at,variant:"inline",className:"pt-4 border-t border-gray-200"}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Spend"}),(0,t.jsxs)(_.Text,{children:["$",(0,i.formatNumberWithCommas)(ep.spend,4)," USD"]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Budget"}),(0,t.jsx)(_.Text,{children:null!==ep.max_budget?`$${(0,i.formatNumberWithCommas)(ep.max_budget,2)}`:"Unlimited"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Tags"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:Array.isArray(ep.metadata?.tags)&&ep.metadata.tags.length>0?ep.metadata.tags.map((e,a)=>(0,t.jsx)("span",{className:"px-2 mr-2 py-1 bg-blue-100 rounded text-xs",children:e},a)):"No tags specified"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Prompts"}),(0,t.jsx)(_.Text,{children:Array.isArray(ep.metadata?.prompts)&&ep.metadata.prompts.length>0?ep.metadata.prompts.map((e,a)=>(0,t.jsx)("span",{className:"px-2 mr-2 py-1 bg-blue-100 rounded text-xs",children:e},a)):"No prompts specified"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Allowed Routes"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:Array.isArray(ep.allowed_routes)&&ep.allowed_routes.length>0?ep.allowed_routes.map((e,a)=>(0,t.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:e},a)):(0,t.jsx)(v.Tag,{color:"green",children:"All routes allowed"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Allowed Pass Through Routes"}),(0,t.jsx)(_.Text,{children:Array.isArray(ep.metadata?.allowed_passthrough_routes)&&ep.metadata.allowed_passthrough_routes.length>0?ep.metadata.allowed_passthrough_routes.map((e,a)=>(0,t.jsx)("span",{className:"px-2 mr-2 py-1 bg-blue-100 rounded text-xs",children:e},a)):"No pass through routes specified"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Disable Global Guardrails"}),(0,t.jsx)(_.Text,{children:ep.metadata?.disable_global_guardrails===!0?(0,t.jsx)(d.Badge,{color:"yellow",children:"Enabled - Global guardrails bypassed"}):(0,t.jsx)(d.Badge,{color:"green",children:"Disabled - Global guardrails active"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Models"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:ep.models&&ep.models.length>0?ep.models.map((e,a)=>(0,t.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:e},a)):(0,t.jsx)(_.Text,{children:"No models specified"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Rate Limits"}),(0,t.jsxs)(_.Text,{children:["TPM: ",null!==ep.tpm_limit?ep.tpm_limit:"Unlimited"]}),(0,t.jsxs)(_.Text,{children:["RPM: ",null!==ep.rpm_limit?ep.rpm_limit:"Unlimited"]}),(0,t.jsxs)(_.Text,{children:["Max Parallel Requests:"," ",null!==ep.max_parallel_requests?ep.max_parallel_requests:"Unlimited"]}),(0,t.jsxs)(_.Text,{children:["Model TPM Limits:"," ",ep.metadata?.model_tpm_limit?JSON.stringify(ep.metadata.model_tpm_limit):"Unlimited"]}),(0,t.jsxs)(_.Text,{children:["Model RPM Limits:"," ",ep.metadata?.model_rpm_limit?JSON.stringify(ep.metadata.model_rpm_limit):"Unlimited"]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Metadata"}),(0,t.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:(0,C.formatMetadataForDisplay)((0,C.stripTagsFromMetadata)(ep.metadata))})]}),(0,t.jsx)(R.default,{objectPermission:ep.object_permission,variant:"inline",className:"pt-4 border-t border-gray-200",accessToken:$}),(0,t.jsx)(A.default,{loggingConfigs:(0,C.extractLoggingSettings)(ep.metadata),disabledCallbacks:Array.isArray(ep.metadata?.litellm_disabled_callbacks)?(0,w.mapInternalToDisplayNames)(ep.metadata.litellm_disabled_callbacks):[],variant:"inline",className:"pt-4 border-t border-gray-200"})]})]})})]})]})]})}e.s(["default",()=>es],20147)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/e8718f949e42598e.js b/litellm/proxy/_experimental/out/_next/static/chunks/07fd9d7c5c879cb6.js similarity index 54% rename from litellm/proxy/_experimental/out/_next/static/chunks/e8718f949e42598e.js rename to litellm/proxy/_experimental/out/_next/static/chunks/07fd9d7c5c879cb6.js index 7daf47e9cfd..77423d00781 100644 --- a/litellm/proxy/_experimental/out/_next/static/chunks/e8718f949e42598e.js +++ b/litellm/proxy/_experimental/out/_next/static/chunks/07fd9d7c5c879cb6.js @@ -1 +1 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,757440,e=>{"use strict";var t=e.i(290571),s=e.i(271645);let r=e=>{var r=(0,t.__rest)(e,[]);return s.default.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"},r),s.default.createElement("path",{d:"M11.9999 13.1714L16.9497 8.22168L18.3639 9.63589L11.9999 15.9999L5.63599 9.63589L7.0502 8.22168L11.9999 13.1714Z"}))};e.s(["default",()=>r])},446428,854056,e=>{"use strict";let t;var s=e.i(290571),r=e.i(271645);let l=e=>{var t=(0,s.__rest)(e,[]);return r.default.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"},t),r.default.createElement("path",{d:"M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 10.5858L9.17157 7.75736L7.75736 9.17157L10.5858 12L7.75736 14.8284L9.17157 16.2426L12 13.4142L14.8284 16.2426L16.2426 14.8284L13.4142 12L16.2426 9.17157L14.8284 7.75736L12 10.5858Z"}))};e.s(["default",()=>l],446428);var a=e.i(746725),n=e.i(914189),i=e.i(553521),o=e.i(835696),d=e.i(941444),c=e.i(178677),u=e.i(294316),m=e.i(83733),h=e.i(233137),x=e.i(732607),g=e.i(397701),f=e.i(700020);function p(e){var t;return!!(e.enter||e.enterFrom||e.enterTo||e.leave||e.leaveFrom||e.leaveTo)||(null!=(t=e.as)?t:N)!==r.Fragment||1===r.default.Children.count(e.children)}let j=(0,r.createContext)(null);j.displayName="TransitionContext";var b=((t=b||{}).Visible="visible",t.Hidden="hidden",t);let v=(0,r.createContext)(null);function y(e){return"children"in e?y(e.children):e.current.filter(({el:e})=>null!==e.current).filter(({state:e})=>"visible"===e).length>0}function _(e,t){let s=(0,d.useLatestValue)(e),l=(0,r.useRef)([]),o=(0,i.useIsMounted)(),c=(0,a.useDisposables)(),u=(0,n.useEvent)((e,t=f.RenderStrategy.Hidden)=>{let r=l.current.findIndex(({el:t})=>t===e);-1!==r&&((0,g.match)(t,{[f.RenderStrategy.Unmount](){l.current.splice(r,1)},[f.RenderStrategy.Hidden](){l.current[r].state="hidden"}}),c.microTask(()=>{var e;!y(l)&&o.current&&(null==(e=s.current)||e.call(s))}))}),m=(0,n.useEvent)(e=>{let t=l.current.find(({el:t})=>t===e);return t?"visible"!==t.state&&(t.state="visible"):l.current.push({el:e,state:"visible"}),()=>u(e,f.RenderStrategy.Unmount)}),h=(0,r.useRef)([]),x=(0,r.useRef)(Promise.resolve()),p=(0,r.useRef)({enter:[],leave:[]}),j=(0,n.useEvent)((e,s,r)=>{h.current.splice(0),t&&(t.chains.current[s]=t.chains.current[s].filter(([t])=>t!==e)),null==t||t.chains.current[s].push([e,new Promise(e=>{h.current.push(e)})]),null==t||t.chains.current[s].push([e,new Promise(e=>{Promise.all(p.current[s].map(([e,t])=>t)).then(()=>e())})]),"enter"===s?x.current=x.current.then(()=>null==t?void 0:t.wait.current).then(()=>r(s)):r(s)}),b=(0,n.useEvent)((e,t,s)=>{Promise.all(p.current[t].splice(0).map(([e,t])=>t)).then(()=>{var e;null==(e=h.current.shift())||e()}).then(()=>s(t))});return(0,r.useMemo)(()=>({children:l,register:m,unregister:u,onStart:j,onStop:b,wait:x,chains:p}),[m,u,l,j,b,p,x])}v.displayName="NestingContext";let N=r.Fragment,S=f.RenderFeatures.RenderStrategy,w=(0,f.forwardRefWithAs)(function(e,t){let{show:s,appear:l=!1,unmount:a=!0,...i}=e,d=(0,r.useRef)(null),m=p(e),x=(0,u.useSyncRefs)(...m?[d,t]:null===t?[]:[t]);(0,c.useServerHandoffComplete)();let g=(0,h.useOpenClosed)();if(void 0===s&&null!==g&&(s=(g&h.State.Open)===h.State.Open),void 0===s)throw Error("A is used but it is missing a `show={true | false}` prop.");let[b,N]=(0,r.useState)(s?"visible":"hidden"),w=_(()=>{s||N("hidden")}),[T,k]=(0,r.useState)(!0),I=(0,r.useRef)([s]);(0,o.useIsoMorphicEffect)(()=>{!1!==T&&I.current[I.current.length-1]!==s&&(I.current.push(s),k(!1))},[I,s]);let E=(0,r.useMemo)(()=>({show:s,appear:l,initial:T}),[s,l,T]);(0,o.useIsoMorphicEffect)(()=>{s?N("visible"):y(w)||null===d.current||N("hidden")},[s,w]);let U={unmount:a},B=(0,n.useEvent)(()=>{var t;T&&k(!1),null==(t=e.beforeEnter)||t.call(e)}),R=(0,n.useEvent)(()=>{var t;T&&k(!1),null==(t=e.beforeLeave)||t.call(e)}),F=(0,f.useRender)();return r.default.createElement(v.Provider,{value:w},r.default.createElement(j.Provider,{value:E},F({ourProps:{...U,as:r.Fragment,children:r.default.createElement(C,{ref:x,...U,...i,beforeEnter:B,beforeLeave:R})},theirProps:{},defaultTag:r.Fragment,features:S,visible:"visible"===b,name:"Transition"})))}),C=(0,f.forwardRefWithAs)(function(e,t){var s,l;let{transition:a=!0,beforeEnter:i,afterEnter:d,beforeLeave:b,afterLeave:w,enter:C,enterFrom:T,enterTo:k,entered:I,leave:E,leaveFrom:U,leaveTo:B,...R}=e,[F,M]=(0,r.useState)(null),D=(0,r.useRef)(null),L=p(e),A=(0,u.useSyncRefs)(...L?[D,t,M]:null===t?[]:[t]),O=null==(s=R.unmount)||s?f.RenderStrategy.Unmount:f.RenderStrategy.Hidden,{show:P,appear:z,initial:V}=function(){let e=(0,r.useContext)(j);if(null===e)throw Error("A is used but it is missing a parent or .");return e}(),[$,K]=(0,r.useState)(P?"visible":"hidden"),q=function(){let e=(0,r.useContext)(v);if(null===e)throw Error("A is used but it is missing a parent or .");return e}(),{register:H,unregister:W}=q;(0,o.useIsoMorphicEffect)(()=>H(D),[H,D]),(0,o.useIsoMorphicEffect)(()=>{if(O===f.RenderStrategy.Hidden&&D.current)return P&&"visible"!==$?void K("visible"):(0,g.match)($,{hidden:()=>W(D),visible:()=>H(D)})},[$,D,H,W,P,O]);let G=(0,c.useServerHandoffComplete)();(0,o.useIsoMorphicEffect)(()=>{if(L&&G&&"visible"===$&&null===D.current)throw Error("Did you forget to passthrough the `ref` to the actual DOM node?")},[D,$,G,L]);let J=V&&!z,Q=z&&P&&V,Z=(0,r.useRef)(!1),Y=_(()=>{Z.current||(K("hidden"),W(D))},q),X=(0,n.useEvent)(e=>{Z.current=!0,Y.onStart(D,e?"enter":"leave",e=>{"enter"===e?null==i||i():"leave"===e&&(null==b||b())})}),ee=(0,n.useEvent)(e=>{let t=e?"enter":"leave";Z.current=!1,Y.onStop(D,t,e=>{"enter"===e?null==d||d():"leave"===e&&(null==w||w())}),"leave"!==t||y(Y)||(K("hidden"),W(D))});(0,r.useEffect)(()=>{L&&a||(X(P),ee(P))},[P,L,a]);let et=!(!a||!L||!G||J),[,es]=(0,m.useTransition)(et,F,P,{start:X,end:ee}),er=(0,f.compact)({ref:A,className:(null==(l=(0,x.classNames)(R.className,Q&&C,Q&&T,es.enter&&C,es.enter&&es.closed&&T,es.enter&&!es.closed&&k,es.leave&&E,es.leave&&!es.closed&&U,es.leave&&es.closed&&B,!es.transition&&P&&I))?void 0:l.trim())||void 0,...(0,m.transitionDataAttributes)(es)}),el=0;"visible"===$&&(el|=h.State.Open),"hidden"===$&&(el|=h.State.Closed),es.enter&&(el|=h.State.Opening),es.leave&&(el|=h.State.Closing);let ea=(0,f.useRender)();return r.default.createElement(v.Provider,{value:Y},r.default.createElement(h.OpenClosedProvider,{value:el},ea({ourProps:er,theirProps:R,defaultTag:N,features:S,visible:"visible"===$,name:"Transition.Child"})))}),T=(0,f.forwardRefWithAs)(function(e,t){let s=null!==(0,r.useContext)(j),l=null!==(0,h.useOpenClosed)();return r.default.createElement(r.default.Fragment,null,!s&&l?r.default.createElement(w,{ref:t,...e}):r.default.createElement(C,{ref:t,...e}))}),k=Object.assign(w,{Child:T,Root:w});e.s(["Transition",()=>k],854056)},206929,e=>{"use strict";var t=e.i(290571),s=e.i(757440),r=e.i(271645),l=e.i(446428),a=e.i(444755),n=e.i(673706),i=e.i(103471),o=e.i(495470),d=e.i(854056),c=e.i(888288);let u=(0,n.makeClassName)("Select"),m=r.default.forwardRef((e,n)=>{let{defaultValue:m="",value:h,onValueChange:x,placeholder:g="Select...",disabled:f=!1,icon:p,enableClear:j=!1,required:b,children:v,name:y,error:_=!1,errorMessage:N,className:S,id:w}=e,C=(0,t.__rest)(e,["defaultValue","value","onValueChange","placeholder","disabled","icon","enableClear","required","children","name","error","errorMessage","className","id"]),T=(0,r.useRef)(null),k=r.Children.toArray(v),[I,E]=(0,c.default)(m,h),U=(0,r.useMemo)(()=>{let e=r.default.Children.toArray(v).filter(r.isValidElement);return(0,i.constructValueToNameMapping)(e)},[v]);return r.default.createElement("div",{className:(0,a.tremorTwMerge)("w-full min-w-[10rem] text-tremor-default",S)},r.default.createElement("div",{className:"relative"},r.default.createElement("select",{title:"select-hidden",required:b,className:(0,a.tremorTwMerge)("h-full w-full absolute left-0 top-0 -z-10 opacity-0"),value:I,onChange:e=>{e.preventDefault()},name:y,disabled:f,id:w,onFocus:()=>{let e=T.current;e&&e.focus()}},r.default.createElement("option",{className:"hidden",value:"",disabled:!0,hidden:!0},g),k.map(e=>{let t=e.props.value,s=e.props.children;return r.default.createElement("option",{className:"hidden",key:t,value:t},s)})),r.default.createElement(o.Listbox,Object.assign({as:"div",ref:n,defaultValue:I,value:I,onChange:e=>{null==x||x(e),E(e)},disabled:f,id:w},C),({value:e})=>{var t;return r.default.createElement(r.default.Fragment,null,r.default.createElement(o.ListboxButton,{ref:T,className:(0,a.tremorTwMerge)("w-full outline-none text-left whitespace-nowrap truncate rounded-tremor-default focus:ring-2 transition duration-100 border pr-8 py-2","border-tremor-border shadow-tremor-input focus:border-tremor-brand-subtle focus:ring-tremor-brand-muted","dark:border-dark-tremor-border dark:shadow-dark-tremor-input dark:focus:border-dark-tremor-brand-subtle dark:focus:ring-dark-tremor-brand-muted",p?"pl-10":"pl-3",(0,i.getSelectButtonColors)((0,i.hasValue)(e),f,_))},p&&r.default.createElement("span",{className:(0,a.tremorTwMerge)("absolute inset-y-0 left-0 flex items-center ml-px pl-2.5")},r.default.createElement(p,{className:(0,a.tremorTwMerge)(u("Icon"),"flex-none h-5 w-5","text-tremor-content-subtle","dark:text-dark-tremor-content-subtle")})),r.default.createElement("span",{className:"w-[90%] block truncate"},e&&null!=(t=U.get(e))?t:g),r.default.createElement("span",{className:(0,a.tremorTwMerge)("absolute inset-y-0 right-0 flex items-center mr-3")},r.default.createElement(s.default,{className:(0,a.tremorTwMerge)(u("arrowDownIcon"),"flex-none h-5 w-5","text-tremor-content-subtle","dark:text-dark-tremor-content-subtle")}))),j&&I?r.default.createElement("button",{type:"button",className:(0,a.tremorTwMerge)("absolute inset-y-0 right-0 flex items-center mr-8"),onClick:e=>{e.preventDefault(),E(""),null==x||x("")}},r.default.createElement(l.default,{className:(0,a.tremorTwMerge)(u("clearIcon"),"flex-none h-4 w-4","text-tremor-content-subtle","dark:text-dark-tremor-content-subtle")})):null,r.default.createElement(d.Transition,{enter:"transition ease duration-100 transform",enterFrom:"opacity-0 -translate-y-4",enterTo:"opacity-100 translate-y-0",leave:"transition ease duration-100 transform",leaveFrom:"opacity-100 translate-y-0",leaveTo:"opacity-0 -translate-y-4"},r.default.createElement(o.ListboxOptions,{anchor:"bottom start",className:(0,a.tremorTwMerge)("z-10 w-[var(--button-width)] divide-y overflow-y-auto outline-none rounded-tremor-default max-h-[228px] border [--anchor-gap:4px]","bg-tremor-background border-tremor-border divide-tremor-border shadow-tremor-dropdown","dark:bg-dark-tremor-background dark:border-dark-tremor-border dark:divide-dark-tremor-border dark:shadow-dark-tremor-dropdown")},v)))})),_&&N?r.default.createElement("p",{className:(0,a.tremorTwMerge)("errorMessage","text-sm text-rose-500 mt-1")},N):null)});m.displayName="Select",e.s(["Select",()=>m],206929)},502275,e=>{"use strict";var t=e.i(271645);let s=t.forwardRef(function(e,s){return t.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:s},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"}))});e.s(["InformationCircleIcon",0,s],502275)},78085,e=>{"use strict";var t=e.i(290571),s=e.i(103471),r=e.i(888288),l=e.i(271645),a=e.i(444755),n=e.i(673706);let i=(0,n.makeClassName)("Textarea"),o=l.default.forwardRef((e,o)=>{let{value:d,defaultValue:c="",placeholder:u="Type...",error:m=!1,errorMessage:h,disabled:x=!1,className:g,onChange:f,onValueChange:p,autoHeight:j=!1}=e,b=(0,t.__rest)(e,["value","defaultValue","placeholder","error","errorMessage","disabled","className","onChange","onValueChange","autoHeight"]),[v,y]=(0,r.default)(c,d),_=(0,l.useRef)(null),N=(0,s.hasValue)(v);return(0,l.useEffect)(()=>{let e=_.current;if(j&&e){e.style.height="60px";let t=e.scrollHeight;e.style.height=t+"px"}},[j,_,v]),l.default.createElement(l.default.Fragment,null,l.default.createElement("textarea",Object.assign({ref:(0,n.mergeRefs)([_,o]),value:v,placeholder:u,disabled:x,className:(0,a.tremorTwMerge)(i("Textarea"),"w-full flex items-center outline-none rounded-tremor-default px-3 py-2 text-tremor-default focus:ring-2 transition duration-100 border","shadow-tremor-input focus:border-tremor-brand-subtle focus:ring-tremor-brand-muted","dark:shadow-dark-tremor-input focus:dark:border-dark-tremor-brand-subtle focus:dark:ring-dark-tremor-brand-muted",(0,s.getSelectButtonColors)(N,x,m),x?"placeholder:text-tremor-content-subtle dark:placeholder:text-dark-tremor-content-subtle":"placeholder:text-tremor-content dark:placeholder:text-dark-tremor-content",g),"data-testid":"text-area",onChange:e=>{null==f||f(e),y(e.target.value),null==p||p(e.target.value)}},b)),m&&h?l.default.createElement("p",{className:(0,a.tremorTwMerge)(i("errorMessage"),"text-sm text-red-500 mt-1")},h):null)});o.displayName="Textarea",e.s(["Textarea",()=>o],78085)},910119,e=>{"use strict";var t=e.i(843476),s=e.i(197647),r=e.i(653824),l=e.i(881073),a=e.i(404206),n=e.i(723731),i=e.i(271645),o=e.i(994388),d=e.i(212931),c=e.i(898586),u=e.i(312361),m=e.i(998573),h=e.i(291542),x=e.i(199133),g=e.i(28651),f=e.i(175712),p=e.i(770914),j=e.i(536916),b=e.i(764205),v=e.i(827252),y=e.i(35983),_=e.i(779241),N=e.i(78085),S=e.i(808613),w=e.i(592968),C=e.i(708347),T=e.i(860585),k=e.i(355619),I=e.i(435451);function E({userData:e,onCancel:s,onSubmit:r,teams:l,accessToken:a,userID:n,userRole:d,userModels:c,possibleUIRoles:u,isBulkEdit:m=!1}){let[h]=S.Form.useForm(),[g,f]=(0,i.useState)(!1);return i.default.useEffect(()=>{let t=e.user_info?.max_budget,s=null==t;f(s),h.setFieldsValue({user_id:e.user_id,user_email:e.user_info?.user_email,user_alias:e.user_info?.user_alias,user_role:e.user_info?.user_role,models:e.user_info?.models||[],max_budget:s?"":t,budget_duration:e.user_info?.budget_duration,metadata:e.user_info?.metadata?JSON.stringify(e.user_info.metadata,null,2):void 0})},[e,h]),(0,t.jsxs)(S.Form,{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}(g||""===e.max_budget||void 0===e.max_budget)&&(e.max_budget=null),r(e)},layout:"vertical",children:[!m&&(0,t.jsx)(S.Form.Item,{label:"User ID",name:"user_id",children:(0,t.jsx)(_.TextInput,{disabled:!0})}),!m&&(0,t.jsx)(S.Form.Item,{label:"Email",name:"user_email",children:(0,t.jsx)(_.TextInput,{})}),(0,t.jsx)(S.Form.Item,{label:"User Alias",name:"user_alias",children:(0,t.jsx)(_.TextInput,{})}),(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{children:["Global Proxy Role"," ",(0,t.jsx)(w.Tooltip,{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)(v.InfoCircleOutlined,{})})]}),name:"user_role",children:(0,t.jsx)(x.Select,{children:u&&Object.entries(u).map(([e,{ui_label:s,description:r}])=>(0,t.jsx)(y.SelectItem,{value:e,title:s,children:(0,t.jsxs)("div",{className:"flex",children:[s," ",(0,t.jsx)("p",{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:r})]})},e))})}),(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{children:["Personal Models"," ",(0,t.jsx)(w.Tooltip,{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)(v.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"models",children:(0,t.jsxs)(x.Select,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},disabled:!C.all_admin_roles.includes(d||""),children:[(0,t.jsx)(x.Select.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),(0,t.jsx)(x.Select.Option,{value:"no-default-models",children:"No Default Models"},"no-default-models"),c.map(e=>(0,t.jsx)(x.Select.Option,{value:e,children:(0,k.getModelDisplayName)(e)},e))]})}),(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[(0,t.jsx)("span",{children:"Max Budget (USD)"}),(0,t.jsx)(j.Checkbox,{checked:g,onChange:e=>{let t=e.target.checked;f(t),t&&h.setFieldsValue({max_budget:""})},children:"Unlimited Budget"})]}),name:"max_budget",rules:[{validator:(e,t)=>g||""!==t&&null!=t?Promise.resolve():Promise.reject(Error("Please enter a budget or select Unlimited Budget"))}],children:(0,t.jsx)(I.default,{step:.01,precision:2,style:{width:"100%"},disabled:g})}),(0,t.jsx)(S.Form.Item,{label:"Reset Budget",name:"budget_duration",children:(0,t.jsx)(T.default,{})}),(0,t.jsx)(S.Form.Item,{label:"Metadata",name:"metadata",children:(0,t.jsx)(N.Textarea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,t.jsxs)("div",{className:"flex justify-end space-x-2",children:[(0,t.jsx)(o.Button,{variant:"secondary",type:"button",onClick:s,children:"Cancel"}),(0,t.jsx)(o.Button,{type:"submit",children:"Save Changes"})]})]})}var U=e.i(727749);let{Text:B,Title:R}=c.Typography,F=({open:e,onCancel:s,selectedUsers:r,possibleUIRoles:l,accessToken:a,onSuccess:n,teams:o,userRole:c,userModels:v,allowAllUsers:y=!1})=>{let[_,N]=(0,i.useState)(!1),[S,w]=(0,i.useState)([]),[C,T]=(0,i.useState)(null),[k,I]=(0,i.useState)(!1),[F,M]=(0,i.useState)(!1),D=()=>{w([]),T(null),I(!1),M(!1),s()},L=i.default.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:o||[]}),[o,e]),A=async e=>{if(console.log("formValues",e),!a)return void U.default.fromBackend("Access token not found");N(!0);try{let t=r.map(e=>e.user_id),l={};e.user_role&&""!==e.user_role&&(l.user_role=e.user_role),null!==e.max_budget&&void 0!==e.max_budget&&(l.max_budget=e.max_budget),e.models&&e.models.length>0&&(l.models=e.models),e.budget_duration&&""!==e.budget_duration&&(l.budget_duration=e.budget_duration),e.metadata&&Object.keys(e.metadata).length>0&&(l.metadata=e.metadata);let i=Object.keys(l).length>0,o=k&&S.length>0;if(!i&&!o)return void U.default.fromBackend("Please modify at least one field or select teams to add users to");let d=[];if(i)if(F){let e=await (0,b.userBulkUpdateUserCall)(a,l,void 0,!0);d.push(`Updated all users (${e.total_requested} total)`)}else await (0,b.userBulkUpdateUserCall)(a,l,t),d.push(`Updated ${t.length} user(s)`);if(o){let e=[];for(let t of S)try{let s=null;s=F?null:r.map(e=>({user_id:e.user_id,role:"user",user_email:e.user_email||null}));let l=await (0,b.teamBulkMemberAddCall)(a,t,s||null,C||void 0,F);console.log("result",l),e.push({teamId:t,success:!0,successfulAdditions:l.successful_additions,failedAdditions:l.failed_additions})}catch(s){console.error(`Failed to add users to team ${t}:`,s),e.push({teamId:t,success:!1,error:s})}let t=e.filter(e=>e.success),s=e.filter(e=>!e.success);if(t.length>0){let e=t.reduce((e,t)=>e+t.successfulAdditions,0);d.push(`Added users to ${t.length} team(s) (${e} total additions)`)}s.length>0&&m.message.warning(`Failed to add users to ${s.length} team(s)`)}d.length>0&&U.default.success(d.join(". ")),w([]),T(null),I(!1),M(!1),n(),s()}catch(e){console.error("Bulk operation failed:",e),U.default.fromBackend("Failed to perform bulk operations")}finally{N(!1)}};return(0,t.jsxs)(d.Modal,{open:e,onCancel:D,footer:null,title:F?"Bulk Edit All Users":`Bulk Edit ${r.length} User(s)`,width:800,children:[y&&(0,t.jsxs)("div",{className:"mb-4",children:[(0,t.jsx)(j.Checkbox,{checked:F,onChange:e=>M(e.target.checked),children:(0,t.jsx)(B,{strong:!0,children:"Update ALL users in the system"})}),F&&(0,t.jsx)("div",{style:{marginTop:8},children:(0,t.jsx)(B,{type:"warning",style:{fontSize:"12px"},children:"⚠️ This will apply changes to ALL users in the system, not just the selected ones."})})]}),!F&&(0,t.jsxs)("div",{className:"mb-4",children:[(0,t.jsxs)(R,{level:5,children:["Selected Users (",r.length,"):"]}),(0,t.jsx)(h.Table,{size:"small",bordered:!0,dataSource:r,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)(B,{strong:!0,style:{fontSize:"12px"},children:e.length>20?`${e.slice(0,20)}...`:e})},{title:"Email",dataIndex:"user_email",key:"user_email",width:"25%",render:e=>(0,t.jsx)(B,{type:"secondary",style:{fontSize:"12px"},children:e||"No email"})},{title:"Current Role",dataIndex:"user_role",key:"user_role",width:"25%",render:e=>(0,t.jsx)(B,{style:{fontSize:"12px"},children:l?.[e]?.ui_label||e})},{title:"Budget",dataIndex:"max_budget",key:"max_budget",width:"20%",render:e=>(0,t.jsx)(B,{style:{fontSize:"12px"},children:null!==e?`$${e}`:"Unlimited"})}]})]}),(0,t.jsx)(u.Divider,{}),(0,t.jsx)("div",{className:"mb-4",children:(0,t.jsxs)(B,{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)(f.Card,{title:"Team Management",size:"small",className:"mb-4",style:{backgroundColor:"#fafafa"},children:(0,t.jsxs)(p.Space,{direction:"vertical",style:{width:"100%"},children:[(0,t.jsx)(j.Checkbox,{checked:k,onChange:e=>I(e.target.checked),children:"Add selected users to teams"}),k&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(B,{strong:!0,children:"Select Teams:"}),(0,t.jsx)(x.Select,{mode:"multiple",placeholder:"Select teams to add users to",value:S,onChange:w,style:{width:"100%",marginTop:8},options:o?.map(e=>({label:e.team_alias||e.team_id,value:e.team_id}))||[]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(B,{strong:!0,children:"Team Budget (Optional):"}),(0,t.jsx)(g.InputNumber,{placeholder:"Max budget per user in team",value:C,onChange:e=>T(e),style:{width:"100%",marginTop:8},min:0,step:.01,precision:2}),(0,t.jsx)(B,{type:"secondary",style:{fontSize:"12px"},children:"Leave empty for unlimited budget within team limits"})]}),(0,t.jsx)(B,{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)(E,{userData:L,onCancel:D,onSubmit:A,teams:o,accessToken:a,userID:"bulk_edit",userRole:c,userModels:v,possibleUIRoles:l,isBulkEdit:!0}),_&&(0,t.jsx)("div",{style:{textAlign:"center",marginTop:"10px"},children:(0,t.jsxs)(B,{children:["Updating ",F?"all users":r.length," user(s)..."]})})]})};var M=e.i(371455),D=e.i(464571);let L=({visible:e,possibleUIRoles:s,onCancel:r,user:l,onSubmit:a})=>{let[n,o]=(0,i.useState)(l),[c]=S.Form.useForm();(0,i.useEffect)(()=>{c.resetFields()},[l]);let u=async()=>{c.resetFields(),r()},m=async e=>{a(e),c.resetFields(),r()};return l?(0,t.jsx)(d.Modal,{open:e,onCancel:u,footer:null,title:"Edit User "+l.user_id,width:1e3,children:(0,t.jsx)(S.Form,{form:c,onFinish:m,initialValues:l,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(S.Form.Item,{className:"mt-8",label:"User Email",tooltip:"Email of the User",name:"user_email",children:(0,t.jsx)(_.TextInput,{})}),(0,t.jsx)(S.Form.Item,{label:"user_id",name:"user_id",hidden:!0,children:(0,t.jsx)(_.TextInput,{})}),(0,t.jsx)(S.Form.Item,{label:"User Role",name:"user_role",children:(0,t.jsx)(x.Select,{children:s&&Object.entries(s).map(([e,{ui_label:s,description:r}])=>(0,t.jsx)(y.SelectItem,{value:e,title:s,children:(0,t.jsxs)("div",{className:"flex",children:[s," ",(0,t.jsx)("p",{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:r})]})},e))})}),(0,t.jsx)(S.Form.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)(g.InputNumber,{min:0,step:.01})}),(0,t.jsx)(S.Form.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)(I.default,{min:0,step:.01})}),(0,t.jsx)(S.Form.Item,{label:"Reset Budget",name:"budget_duration",children:(0,t.jsx)(T.default,{})}),(0,t.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,t.jsx)(D.Button,{htmlType:"submit",children:"Save"})}),(0,t.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,t.jsx)(D.Button,{htmlType:"submit",children:"Save"})})]})})}):null};var A=e.i(172372),O=e.i(500330),P=e.i(152473),z=e.i(266027),V=e.i(912598),$=e.i(127952),K=e.i(304967),q=e.i(629569),H=e.i(599724),W=e.i(114600),G=e.i(482725),J=e.i(790848),Q=e.i(646563),Z=e.i(955135);let Y=({accessToken:e,possibleUIRoles:s,userID:r,userRole:l})=>{let[a,n]=(0,i.useState)(!0),[d,u]=(0,i.useState)(null),[m,h]=(0,i.useState)(!1),[f,p]=(0,i.useState)({}),[j,v]=(0,i.useState)(!1),[y,N]=(0,i.useState)([]),{Paragraph:S}=c.Typography,{Option:w}=x.Select;(0,i.useEffect)(()=>{(async()=>{if(!e)return n(!1);try{let t=await (0,b.getInternalUserSettings)(e);if(u(t),p(t.values||{}),e)try{let t=await (0,b.modelAvailableCall)(e,r,l);if(t&&t.data){let e=t.data.map(e=>e.id);N(e)}}catch(e){console.error("Error fetching available models:",e)}}catch(e){console.error("Error fetching SSO settings:",e),U.default.fromBackend("Failed to fetch SSO settings")}finally{n(!1)}})()},[e]);let C=async()=>{if(e){v(!0);try{let t=Object.entries(f).reduce((e,[t,s])=>(e[t]=""===s?null:s,e),{}),s=await (0,b.updateInternalUserSettings)(e,t);u({...d,values:s.settings}),h(!1)}catch(e){console.error("Error updating SSO settings:",e),U.default.fromBackend("Failed to update settings: "+e)}finally{v(!1)}}},I=(e,t)=>{p(s=>({...s,[e]:t}))},E=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"}):[];return a?(0,t.jsx)("div",{className:"flex justify-center items-center h-64",children:(0,t.jsx)(G.Spin,{size:"large"})}):d?(0,t.jsxs)(K.Card,{children:[(0,t.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,t.jsx)(q.Title,{children:"Default User Settings"}),!a&&d&&(m?(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(o.Button,{variant:"secondary",onClick:()=>{h(!1),p(d.values||{})},disabled:j,children:"Cancel"}),(0,t.jsx)(o.Button,{onClick:C,loading:j,children:"Save Changes"})]}):(0,t.jsx)(o.Button,{onClick:()=>h(!0),children:"Edit Settings"}))]}),d?.field_schema?.description&&(0,t.jsx)(S,{className:"mb-4",children:d.field_schema.description}),(0,t.jsx)(W.Divider,{}),(0,t.jsx)("div",{className:"mt-4 space-y-4",children:(()=>{let{values:e,field_schema:r}=d;return r&&r.properties?Object.entries(r.properties).map(([r,l])=>{let a=e[r],n=r.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)(H.Text,{className:"font-medium text-lg",children:n}),(0,t.jsx)(S,{className:"text-sm text-gray-500 mt-1",children:l.description||"No description available"}),m?(0,t.jsx)("div",{className:"mt-2",children:((e,r,l)=>{let a=r.type;if("teams"===e){let s,r;return(0,t.jsx)("div",{className:"mt-2",children:(s=E(f[e]||[]),r=(e,t,r)=>{let l=[...s];l[e]={...l[e],[t]:r},I("teams",l)},(0,t.jsxs)("div",{className:"space-y-3",children:[s.map((e,l)=>(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)(H.Text,{className:"font-medium",children:["Team ",l+1]}),(0,t.jsx)(o.Button,{size:"sm",variant:"secondary",icon:Z.DeleteOutlined,onClick:()=>{I("teams",s.filter((e,t)=>t!==l))},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)(H.Text,{className:"text-sm font-medium mb-1",children:"Team ID"}),(0,t.jsx)(_.TextInput,{value:e.team_id,onChange:e=>r(l,"team_id",e.target.value),placeholder:"Enter team ID"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"text-sm font-medium mb-1",children:"Max Budget in Team"}),(0,t.jsx)(g.InputNumber,{style:{width:"100%"},value:e.max_budget_in_team,onChange:e=>r(l,"max_budget_in_team",e),placeholder:"Optional",min:0,step:.01,precision:2})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"text-sm font-medium mb-1",children:"User Role"}),(0,t.jsxs)(x.Select,{style:{width:"100%"},value:e.user_role,onChange:e=>r(l,"user_role",e),children:[(0,t.jsx)(w,{value:"user",children:"User"}),(0,t.jsx)(w,{value:"admin",children:"Admin"})]})]})]})]},l)),(0,t.jsx)(o.Button,{variant:"secondary",icon:Q.PlusOutlined,onClick:()=>{I("teams",[...s,{team_id:"",user_role:"user"}])},className:"w-full",children:"Add Team"})]}))})}if("user_role"===e&&s)return(0,t.jsx)(x.Select,{style:{width:"100%"},value:f[e]||"",onChange:t=>I(e,t),className:"mt-2",children:Object.entries(s).filter(([e])=>e.includes("internal_user")).map(([e,{ui_label:s,description:r}])=>(0,t.jsx)(w,{value:e,children:(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)("span",{children:s}),(0,t.jsx)("span",{className:"ml-2 text-xs text-gray-500",children:r})]})},e))});if("budget_duration"===e)return(0,t.jsx)(T.default,{value:f[e]||null,onChange:t=>I(e,t),className:"mt-2"});if("boolean"===a)return(0,t.jsx)("div",{className:"mt-2",children:(0,t.jsx)(J.Switch,{checked:!!f[e],onChange:t=>I(e,t)})});if("array"===a&&r.items?.enum)return(0,t.jsx)(x.Select,{mode:"multiple",style:{width:"100%"},value:f[e]||[],onChange:t=>I(e,t),className:"mt-2",children:r.items.enum.map(e=>(0,t.jsx)(w,{value:e,children:e},e))});else if("models"===e)return(0,t.jsxs)(x.Select,{mode:"multiple",style:{width:"100%"},value:f[e]||[],onChange:t=>I(e,t),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"),y.map(e=>(0,t.jsx)(w,{value:e,children:(0,k.getModelDisplayName)(e)},e))]});else if("string"===a&&r.enum)return(0,t.jsx)(x.Select,{style:{width:"100%"},value:f[e]||"",onChange:t=>I(e,t),className:"mt-2",children:r.enum.map(e=>(0,t.jsx)(w,{value:e,children:e},e))});else return(0,t.jsx)(_.TextInput,{value:void 0!==f[e]?String(f[e]):"",onChange:t=>I(e,t.target.value),placeholder:r.description||"",className:"mt-2"})})(r,l,0)}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:((e,r)=>{if(null==r)return(0,t.jsx)("span",{className:"text-gray-400",children:"Not set"});if("teams"===e&&Array.isArray(r)){if(0===r.length)return(0,t.jsx)("span",{className:"text-gray-400",children:"No teams assigned"});let e=E(r);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?`$${(0,O.formatNumberWithCommas)(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&&s&&s[r]){let{ui_label:e,description:l}=s[r];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})]})}if("budget_duration"===e)return(0,t.jsx)("span",{children:(0,T.getBudgetDurationLabel)(r)});if("boolean"==typeof r)return(0,t.jsx)("span",{children:r?"Enabled":"Disabled"});if("models"===e&&Array.isArray(r))return 0===r.length?(0,t.jsx)("span",{className:"text-gray-400",children:"None"}):(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:r.map((e,s)=>(0,t.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:(0,k.getModelDisplayName)(e)},s))});if("object"==typeof r)return Array.isArray(r)?0===r.length?(0,t.jsx)("span",{className:"text-gray-400",children:"None"}):(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:r.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(r,null,2)});return(0,t.jsx)("span",{children:String(r)})})(r,a)})]},r)}):(0,t.jsx)(H.Text,{children:"No schema information available"})})()})]}):(0,t.jsx)(K.Card,{children:(0,t.jsx)(H.Text,{children:"No settings available or you do not have permission to view them."})})};var X=e.i(389083),ee=e.i(350967),et=e.i(752978),es=e.i(591935),er=e.i(68155),el=e.i(502275),ea=e.i(278587);let en=(e,s,r,l,a,n)=>{let i=[{header:"User ID",accessorKey:"user_id",enableSorting:!0,cell:({row:e})=>(0,t.jsx)(w.Tooltip,{title:e.original.user_id,children:(0,t.jsx)("span",{className:"text-xs",children:e.original.user_id?`${e.original.user_id.slice(0,7)}...`:"-"})})},{header:"Email",accessorKey:"user_email",enableSorting:!0,cell:({row:e})=>(0,t.jsx)("span",{className:"text-xs",children:e.original.user_email||"-"})},{header:"Global Proxy Role",accessorKey:"user_role",enableSorting:!0,cell:({row:s})=>(0,t.jsx)("span",{className:"text-xs",children:e?.[s.original.user_role]?.ui_label||"-"})},{header:"User Alias",accessorKey:"user_alias",enableSorting:!1,cell:({row:e})=>(0,t.jsx)("span",{className:"text-xs",children:e.original.user_alias||"-"})},{header:"Spend (USD)",accessorKey:"spend",enableSorting:!0,cell:({row:e})=>(0,t.jsx)("span",{className:"text-xs",children:e.original.spend?(0,O.formatNumberWithCommas)(e.original.spend,4):"-"})},{header:"Budget (USD)",accessorKey:"max_budget",enableSorting:!1,cell:({row:e})=>(0,t.jsx)("span",{className:"text-xs",children:null!==e.original.max_budget?e.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)(w.Tooltip,{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)(el.InformationCircleIcon,{className:"w-4 h-4"})})]}),accessorKey:"sso_user_id",enableSorting:!1,cell:({row:e})=>(0,t.jsx)("span",{className:"text-xs",children:null!==e.original.sso_user_id?e.original.sso_user_id:"-"})},{header:"Virtual Keys",accessorKey:"key_count",enableSorting:!1,cell:({row:e})=>(0,t.jsx)(ee.Grid,{numItems:2,children:e.original.key_count>0?(0,t.jsxs)(X.Badge,{size:"xs",color:"indigo",children:[e.original.key_count," ",1===e.original.key_count?"Key":"Keys"]}):(0,t.jsx)(X.Badge,{size:"xs",color:"gray",children:"No Keys"})})},{header:"Created At",accessorKey:"created_at",enableSorting:!0,cell:({row:e})=>(0,t.jsx)("span",{className:"text-xs",children:e.original.created_at?new Date(e.original.created_at).toLocaleDateString():"-"})},{header:"Updated At",accessorKey:"updated_at",enableSorting:!1,cell:({row:e})=>(0,t.jsx)("span",{className:"text-xs",children:e.original.updated_at?new Date(e.original.updated_at).toLocaleDateString():"-"})},{id:"actions",header:"Actions",enableSorting:!1,cell:({row:e})=>(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(w.Tooltip,{title:"Edit user details",children:(0,t.jsx)(et.Icon,{icon:es.PencilAltIcon,size:"sm",onClick:()=>a(e.original.user_id,!0),className:"cursor-pointer hover:text-blue-600"})}),(0,t.jsx)(w.Tooltip,{title:"Delete user",children:(0,t.jsx)(et.Icon,{icon:er.TrashIcon,size:"sm",onClick:()=>r(e.original),className:"cursor-pointer hover:text-red-600"})}),(0,t.jsx)(w.Tooltip,{title:"Reset Password",children:(0,t.jsx)(et.Icon,{icon:ea.RefreshIcon,size:"sm",onClick:()=>l(e.original.user_id),className:"cursor-pointer hover:text-green-600"})})]})}];if(n){let{onSelectUser:e,onSelectAll:s,isUserSelected:r,isAllSelected:l,isIndeterminate:a}=n;return[{id:"select",enableSorting:!1,header:()=>(0,t.jsx)(j.Checkbox,{indeterminate:a,checked:l,onChange:e=>s(e.target.checked),onClick:e=>e.stopPropagation()}),cell:({row:s})=>(0,t.jsx)(j.Checkbox,{checked:r(s.original),onChange:t=>e(s.original,t.target.checked),onClick:e=>e.stopPropagation()})},...i]}return i};var ei=e.i(152990),eo=e.i(682830),ed=e.i(269200),ec=e.i(427612),eu=e.i(64848),em=e.i(942232),eh=e.i(496020),ex=e.i(977572),eg=e.i(206929),ef=e.i(94629),ep=e.i(360820),ej=e.i(871943),eb=e.i(981339),ev=e.i(530212),ey=e.i(118366),e_=e.i(678784);function eN({userId:e,onClose:d,accessToken:c,userRole:u,onDelete:m,possibleUIRoles:h,initialTab:x=0,startInEditMode:g=!1}){let[f,p]=(0,i.useState)(null),[j,v]=(0,i.useState)(!1),[y,_]=(0,i.useState)(!1),[N,S]=(0,i.useState)(!0),[w,k]=(0,i.useState)(g),[I,B]=(0,i.useState)([]),[R,F]=(0,i.useState)(!1),[M,L]=(0,i.useState)(null),[P,z]=(0,i.useState)(null),[V,W]=(0,i.useState)(x),[G,J]=(0,i.useState)({}),[Q,Z]=(0,i.useState)(!1);i.default.useEffect(()=>{z((0,b.getProxyBaseUrl)())},[]),i.default.useEffect(()=>{console.log(`userId: ${e}, userRole: ${u}, accessToken: ${c}`),(async()=>{try{if(!c)return;let t=await (0,b.userInfoCall)(c,e,u||"",!1,null,null,!0);p(t);let s=(await (0,b.modelAvailableCall)(c,e,u||"")).data.map(e=>e.id);B(s)}catch(e){console.error("Error fetching user data:",e),U.default.fromBackend("Failed to fetch user data")}finally{S(!1)}})()},[c,e,u]);let Y=async()=>{if(!c)return void U.default.fromBackend("Access token not found");try{U.default.success("Generating password reset link...");let t=await (0,b.invitationCreateCall)(c,e);L(t),F(!0)}catch(e){U.default.fromBackend("Failed to generate password reset link")}},et=async()=>{try{if(!c)return;_(!0),await (0,b.userDeleteCall)(c,[e]),U.default.success("User deleted successfully"),m&&m(),d()}catch(e){console.error("Error deleting user:",e),U.default.fromBackend("Failed to delete user")}finally{v(!1),_(!1)}},es=async e=>{try{if(!c||!f)return;await (0,b.userUpdateUserCall)(c,e,null),p({...f,user_info:{...f.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.default.success("User updated successfully"),k(!1)}catch(e){console.error("Error updating user:",e),U.default.fromBackend("Failed to update user")}};if(N)return(0,t.jsxs)("div",{className:"p-4",children:[(0,t.jsx)(o.Button,{icon:ev.ArrowLeftIcon,variant:"light",onClick:d,className:"mb-4",children:"Back to Users"}),(0,t.jsx)(H.Text,{children:"Loading user data..."})]});if(!f)return(0,t.jsxs)("div",{className:"p-4",children:[(0,t.jsx)(o.Button,{icon:ev.ArrowLeftIcon,variant:"light",onClick:d,className:"mb-4",children:"Back to Users"}),(0,t.jsx)(H.Text,{children:"User not found"})]});let el=async(e,t)=>{await (0,O.copyToClipboard)(e)&&(J(e=>({...e,[t]:!0})),setTimeout(()=>{J(e=>({...e,[t]:!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)(o.Button,{icon:ev.ArrowLeftIcon,variant:"light",onClick:d,className:"mb-4",children:"Back to Users"}),(0,t.jsx)(q.Title,{children:f.user_info?.user_email||"User"}),(0,t.jsxs)("div",{className:"flex items-center cursor-pointer",children:[(0,t.jsx)(H.Text,{className:"text-gray-500 font-mono",children:f.user_id}),(0,t.jsx)(D.Button,{type:"text",size:"small",icon:G["user-id"]?(0,t.jsx)(e_.CheckIcon,{size:12}):(0,t.jsx)(ey.CopyIcon,{size:12}),onClick:()=>el(f.user_id,"user-id"),className:`left-2 z-10 transition-all duration-200 ${G["user-id"]?"text-green-600 bg-green-50 border-green-200":"text-gray-500 hover:text-gray-700 hover:bg-gray-100"}`})]})]}),u&&C.rolesWithWriteAccess.includes(u)&&(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)(o.Button,{icon:ea.RefreshIcon,variant:"secondary",onClick:Y,className:"flex items-center",children:"Reset Password"}),(0,t.jsx)(o.Button,{icon:er.TrashIcon,variant:"secondary",onClick:()=>v(!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)($.default,{isOpen:j,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:f.user_info?.user_email},{label:"User ID",value:f.user_id,code:!0},{label:"Global Proxy Role",value:f.user_info?.user_role&&h?.[f.user_info.user_role]?.ui_label||f.user_info?.user_role||"-"},{label:"Total Spend (USD)",value:f.user_info?.spend!==null&&f.user_info?.spend!==void 0?f.user_info.spend.toFixed(2):void 0}],onCancel:()=>{v(!1)},onOk:et,confirmLoading:y}),(0,t.jsxs)(r.TabGroup,{defaultIndex:V,onIndexChange:W,children:[(0,t.jsxs)(l.TabList,{className:"mb-4",children:[(0,t.jsx)(s.Tab,{children:"Overview"}),(0,t.jsx)(s.Tab,{children:"Details"})]}),(0,t.jsxs)(n.TabPanels,{children:[(0,t.jsx)(a.TabPanel,{children:(0,t.jsxs)(ee.Grid,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,t.jsxs)(K.Card,{children:[(0,t.jsx)(H.Text,{children:"Spend"}),(0,t.jsxs)("div",{className:"mt-2",children:[(0,t.jsxs)(q.Title,{children:["$",(0,O.formatNumberWithCommas)(f.user_info?.spend||0,4)]}),(0,t.jsxs)(H.Text,{children:["of"," ",f.user_info?.max_budget!==null?`$${(0,O.formatNumberWithCommas)(f.user_info.max_budget,4)}`:"Unlimited"]})]})]}),(0,t.jsxs)(K.Card,{children:[(0,t.jsx)(H.Text,{children:"Teams"}),(0,t.jsx)("div",{className:"mt-2",children:f.teams?.length&&f.teams?.length>0?(0,t.jsxs)("div",{className:"flex flex-wrap gap-2",children:[f.teams?.slice(0,Q?f.teams.length:20).map((e,s)=>(0,t.jsx)(X.Badge,{color:"blue",title:e.team_alias,children:e.team_alias},s)),!Q&&f.teams?.length>20&&(0,t.jsxs)(X.Badge,{color:"gray",className:"cursor-pointer hover:bg-gray-200 transition-colors",onClick:()=>Z(!0),children:["+",f.teams.length-20," more"]}),Q&&f.teams?.length>20&&(0,t.jsx)(X.Badge,{color:"gray",className:"cursor-pointer hover:bg-gray-200 transition-colors",onClick:()=>Z(!1),children:"Show Less"})]}):(0,t.jsx)(H.Text,{children:"No teams"})})]}),(0,t.jsxs)(K.Card,{children:[(0,t.jsx)(H.Text,{children:"Virtual Keys"}),(0,t.jsx)("div",{className:"mt-2",children:(0,t.jsxs)(H.Text,{children:[f.keys?.length||0," ",f.keys?.length===1?"Key":"Keys"]})})]}),(0,t.jsxs)(K.Card,{children:[(0,t.jsx)(H.Text,{children:"Personal Models"}),(0,t.jsx)("div",{className:"mt-2",children:f.user_info?.models?.length&&f.user_info?.models?.length>0?f.user_info?.models?.map((e,s)=>(0,t.jsx)(H.Text,{children:e},s)):(0,t.jsx)(H.Text,{children:"All proxy models"})})]})]})}),(0,t.jsx)(a.TabPanel,{children:(0,t.jsxs)(K.Card,{children:[(0,t.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,t.jsx)(q.Title,{children:"User Settings"}),!w&&u&&C.rolesWithWriteAccess.includes(u)&&(0,t.jsx)(o.Button,{onClick:()=>k(!0),children:"Edit Settings"})]}),w&&f?(0,t.jsx)(E,{userData:f,onCancel:()=>k(!1),onSubmit:es,teams:f.teams,accessToken:c,userID:e,userRole:u,userModels:I,possibleUIRoles:h}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"font-medium",children:"User ID"}),(0,t.jsxs)("div",{className:"flex items-center cursor-pointer",children:[(0,t.jsx)(H.Text,{className:"font-mono",children:f.user_id}),(0,t.jsx)(D.Button,{type:"text",size:"small",icon:G["user-id"]?(0,t.jsx)(e_.CheckIcon,{size:12}):(0,t.jsx)(ey.CopyIcon,{size:12}),onClick:()=>el(f.user_id,"user-id"),className:`left-2 z-10 transition-all duration-200 ${G["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)(H.Text,{className:"font-medium",children:"Email"}),(0,t.jsx)(H.Text,{children:f.user_info?.user_email||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"font-medium",children:"User Alias"}),(0,t.jsx)(H.Text,{children:f.user_info?.user_alias||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"font-medium",children:"Global Proxy Role"}),(0,t.jsx)(H.Text,{children:f.user_info?.user_role||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"font-medium",children:"Created"}),(0,t.jsx)(H.Text,{children:f.user_info?.created_at?new Date(f.user_info.created_at).toLocaleString():"Unknown"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"font-medium",children:"Last Updated"}),(0,t.jsx)(H.Text,{children:f.user_info?.updated_at?new Date(f.user_info.updated_at).toLocaleString():"Unknown"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"font-medium",children:"Teams"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:f.teams?.length&&f.teams?.length>0?(0,t.jsxs)(t.Fragment,{children:[f.teams?.slice(0,Q?f.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)),!Q&&f.teams?.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:()=>Z(!0),children:["+",f.teams.length-20," more"]}),Q&&f.teams?.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:()=>Z(!1),children:"Show Less"})]}):(0,t.jsx)(H.Text,{children:"No teams"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"font-medium",children:"Personal Models"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:f.user_info?.models?.length&&f.user_info?.models?.length>0?f.user_info?.models?.map((e,s)=>(0,t.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:e},s)):(0,t.jsx)(H.Text,{children:"All proxy models"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"font-medium",children:"Virtual Keys"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:f.keys?.length&&f.keys?.length>0?f.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)(H.Text,{children:"No Virtual Keys"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"font-medium",children:"Max Budget"}),(0,t.jsx)(H.Text,{children:f.user_info?.max_budget!==null&&f.user_info?.max_budget!==void 0?`$${(0,O.formatNumberWithCommas)(f.user_info.max_budget,4)}`:"Unlimited"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"font-medium",children:"Budget Reset"}),(0,t.jsx)(H.Text,{children:(0,T.getBudgetDurationLabel)(f.user_info?.budget_duration??null)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{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(f.user_info?.metadata||{},null,2)})]})]})]})})]})]}),(0,t.jsx)(A.default,{isInvitationLinkModalVisible:R,setIsInvitationLinkModalVisible:F,baseUrl:P||"",invitationLinkData:M,modalType:"resetPassword"})]})}var eS=e.i(655913),ew=e.i(38419),eC=e.i(78334),eT=e.i(555436),ek=e.i(284614);let eI=(0,e.i(475254).default)("circle-user-round",[["path",{d:"M18 20a6 6 0 0 0-12 0",key:"1qehca"}],["circle",{cx:"12",cy:"10",r:"4",key:"1h16sb"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);function eE({data:e=[],columns:s,isLoading:r=!1,onSortChange:l,currentSort:a,accessToken:n,userRole:o,possibleUIRoles:d,handleEdit:c,handleDelete:u,handleResetPassword:m,selectedUsers:h=[],onSelectionChange:x,enableSelection:g=!1,filters:f,updateFilters:p,initialFilters:j,teams:b,userListResponse:v,currentPage:_,handlePageChange:N}){let[S,w]=i.default.useState([{id:a?.sortBy||"created_at",desc:a?.sortOrder==="desc"}]),[C,T]=i.default.useState(null),[k,I]=i.default.useState(!1),[E,U]=i.default.useState(!1),B=(e,t=!1)=>{T(e),I(t)},R=(e,t)=>{x&&(t?x([...h,e]):x(h.filter(t=>t.user_id!==e.user_id)))},F=t=>{x&&(t?x(e):x([]))},M=e=>h.some(t=>t.user_id===e.user_id),D=e.length>0&&h.length===e.length,L=h.length>0&&h.lengthd?en(d,c,u,m,B,g?{selectedUsers:h,onSelectUser:R,onSelectAll:F,isUserSelected:M,isAllSelected:D,isIndeterminate:L}:void 0):s,[d,c,u,m,B,s,g,h,D,L]),O=(0,ei.useReactTable)({data:e,columns:A,state:{sorting:S},onSortingChange:e=>{let t="function"==typeof e?e(S):e;if(w(t),t&&Array.isArray(t)&&t.length>0&&t[0]){let e=t[0];if(e.id){let t=e.id,s=e.desc?"desc":"asc";l?.(t,s)}}else l?.("created_at","desc")},getCoreRowModel:(0,eo.getCoreRowModel)(),manualSorting:!0,enableSorting:!0});return(i.default.useEffect(()=>{a&&w([{id:a.sortBy,desc:"desc"===a.sortOrder}])},[a]),C)?(0,t.jsx)(eN,{userId:C,onClose:()=>{T(null),I(!1)},accessToken:n,userRole:o,possibleUIRoles:d,initialTab:+!!k,startInEditMode:k}):(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)(eS.FilterInput,{placeholder:"Search by email...",value:f.email,onChange:e=>p({email:e}),icon:eT.Search}),(0,t.jsx)(ew.FiltersButton,{onClick:()=>U(!E),active:E,hasActiveFilters:!!(f.user_id||f.user_role||f.team)}),(0,t.jsx)(eC.ResetFiltersButton,{onClick:()=>{p(j)}})]}),E&&(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-3 mt-3",children:[(0,t.jsx)(eS.FilterInput,{placeholder:"Filter by User ID",value:f.user_id,onChange:e=>p({user_id:e}),icon:ek.User}),(0,t.jsx)(eS.FilterInput,{placeholder:"Filter by SSO ID",value:f.sso_user_id,onChange:e=>p({sso_user_id:e}),icon:eI}),(0,t.jsx)("div",{className:"w-64",children:(0,t.jsx)(eg.Select,{value:f.user_role,onValueChange:e=>p({user_role:e}),placeholder:"Select Role",children:d&&Object.entries(d).map(([e,s])=>(0,t.jsx)(y.SelectItem,{value:e,children:s.ui_label},e))})}),(0,t.jsx)("div",{className:"w-64",children:(0,t.jsx)(eg.Select,{value:f.team,onValueChange:e=>p({team:e}),placeholder:"Select Team",children:b?.map(e=>(0,t.jsx)(y.SelectItem,{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:[r?(0,t.jsx)(eb.Skeleton.Input,{active:!0,style:{width:192,height:20}}):(0,t.jsxs)("span",{className:"text-sm text-gray-700",children:["Showing"," ",v&&v.users&&v.users.length>0?(v.page-1)*v.page_size+1:0," ","-"," ",v&&v.users?Math.min(v.page*v.page_size,v.total):0," ","of ",v?v.total:0," results"]}),(0,t.jsx)("div",{className:"flex space-x-2",children:r?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(eb.Skeleton.Button,{active:!0,size:"small",style:{width:80,height:30}}),(0,t.jsx)(eb.Skeleton.Button,{active:!0,size:"small",style:{width:60,height:30}})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("button",{onClick:()=>N(_-1),disabled:1===_,className:`px-3 py-1 text-sm border rounded-md ${1===_?"bg-gray-100 text-gray-400 cursor-not-allowed":"hover:bg-gray-50"}`,children:"Previous"}),(0,t.jsx)("button",{onClick:()=>N(_+1),disabled:!v||_>=v.total_pages,className:`px-3 py-1 text-sm border rounded-md ${!v||_>=v.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)(ed.Table,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,t.jsx)(ec.TableHead,{children:O.getHeaderGroups().map(e=>(0,t.jsx)(eh.TableRow,{children:e.headers.map(e=>(0,t.jsx)(eu.TableHeaderCell,{className:`py-1 h-8 ${"actions"===e.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]":""} ${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,ei.flexRender)(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)(ep.ChevronUpIcon,{className:"h-4 w-4 text-blue-500"}),desc:(0,t.jsx)(ej.ChevronDownIcon,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,t.jsx)(ef.SwitchVerticalIcon,{className:"h-4 w-4 text-gray-400"})})]})},e.id))},e.id))}),(0,t.jsx)(em.TableBody,{children:r?(0,t.jsx)(eh.TableRow,{children:(0,t.jsx)(ex.TableCell,{colSpan:A.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:"🚅 Loading users..."})})})}):e.length>0?O.getRowModel().rows.map(e=>(0,t.jsx)(eh.TableRow,{className:"h-8",children:e.getVisibleCells().map(e=>(0,t.jsx)(ex.TableCell,{className:`py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap ${"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&&B(e.getValue(),!1)},style:{cursor:"user_id"===e.column.id?"pointer":"default",color:"user_id"===e.column.id?"#3b82f6":"inherit"},children:(0,ei.flexRender)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,t.jsx)(eh.TableRow,{children:(0,t.jsx)(ex.TableCell,{colSpan:A.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:eU,Title:eB}=c.Typography,eR={email:"",user_id:"",user_role:"",sso_user_id:"",team:"",model:"",min_spend:null,max_spend:null,sort_by:"created_at",sort_order:"desc"};e.s(["default",0,({accessToken:e,token:d,userRole:c,userID:u,teams:m})=>{let h=(0,V.useQueryClient)(),[x,g]=(0,i.useState)(1),[f,p]=(0,i.useState)(!1),[j,v]=(0,i.useState)(null),[y,_]=(0,i.useState)(!1),[N,S]=(0,i.useState)(!1),[w,T]=(0,i.useState)(null),[k,I]=(0,i.useState)("users"),[E,B]=(0,i.useState)(eR),[R,D,K]=(0,P.useDebouncedState)(E,{wait:300}),[q,H]=(0,i.useState)(!1),[W,G]=(0,i.useState)(null),[J,Q]=(0,i.useState)(null),[Z,X]=(0,i.useState)([]),[ee,et]=(0,i.useState)(!1),[es,er]=(0,i.useState)(!1),[el,ea]=(0,i.useState)([]),ei=e=>{T(e),_(!0)};(0,i.useEffect)(()=>()=>{K.cancel()},[K]),(0,i.useEffect)(()=>{Q((0,b.getProxyBaseUrl)())},[]),(0,i.useEffect)(()=>{(async()=>{try{if(!u||!c||!e)return;let t=(await (0,b.modelAvailableCall)(e,u,c)).data.map(e=>e.id);console.log("available_model_names:",t),ea(t)}catch(e){console.error("Error fetching user models:",e)}})()},[e,u,c]);let eo=e=>{B(t=>{let s={...t,...e};return D(s),s})},ed=async t=>{if(!e)return void U.default.fromBackend("Access token not found");try{U.default.success("Generating password reset link...");let s=await (0,b.invitationCreateCall)(e,t);G(s),H(!0)}catch(e){U.default.fromBackend("Failed to generate password reset link")}},ec=async()=>{if(w&&e)try{S(!0),await (0,b.userDeleteCall)(e,[w.user_id]),h.setQueriesData({queryKey:["userList"]},e=>{if(void 0===e)return e;let t=e.users.filter(e=>e.user_id!==w.user_id);return{...e,users:t}}),U.default.success("User deleted successfully")}catch(e){console.error("Error deleting user:",e),U.default.fromBackend("Failed to delete user")}finally{_(!1),T(null),S(!1)}},eu=async()=>{v(null),p(!1)},em=async t=>{if(console.log("inside handleEditSubmit:",t),e&&d&&c&&u){try{let s=await (0,b.userUpdateUserCall)(e,t,null);h.setQueriesData({queryKey:["userList"]},e=>{if(void 0===e)return e;let t=e.users.map(e=>e.user_id===s.data.user_id?(0,O.updateExistingKeys)(e,s.data):e);return{...e,users:t}}),U.default.success(`User ${t.user_id} updated successfully`)}catch(e){console.error("There was an error updating the user",e)}v(null),p(!1)}},eh=async e=>{g(e)},ex=(0,z.useQuery)({queryKey:["userList",{debouncedFilter:R,currentPage:x}],queryFn:async()=>{if(!e)throw Error("Access token required");return await (0,b.userListCall)(e,R.user_id?[R.user_id]:null,x,25,R.email||null,R.user_role||null,R.team||null,R.sso_user_id||null,R.sort_by,R.sort_order)},enabled:!!(e&&d&&c&&u),placeholderData:e=>e}),eg=ex.data,ef=(0,z.useQuery)({queryKey:["userRoles"],initialData:()=>({}),queryFn:async()=>{if(!e)throw Error("Access token required");return await (0,b.getPossibleUserRoles)(e)},enabled:!!(e&&d&&c&&u)}).data,ep=en(ef,e=>{v(e),p(!0)},ei,ed,()=>{});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:ex.isLoading?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(eb.Skeleton.Button,{active:!0,size:"default",shape:"default",style:{width:110,height:36}}),(0,t.jsx)(eb.Skeleton.Button,{active:!0,size:"default",shape:"default",style:{width:145,height:36}}),(0,t.jsx)(eb.Skeleton.Button,{active:!0,size:"default",shape:"default",style:{width:110,height:36}})]}):u&&e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(M.CreateUserButton,{userID:u,accessToken:e,teams:m,possibleUIRoles:ef}),(0,t.jsx)(o.Button,{onClick:()=>{er(!es),X([])},variant:es?"primary":"secondary",className:"flex items-center",children:es?"Cancel Selection":"Select Users"}),es&&(0,t.jsxs)(o.Button,{onClick:()=>{0===Z.length?U.default.fromBackend("Please select users to edit"):et(!0)},disabled:0===Z.length,className:"flex items-center",children:["Bulk Edit (",Z.length," selected)"]})]}):null})}),(0,t.jsxs)(r.TabGroup,{defaultIndex:0,onIndexChange:e=>I(0===e?"users":"settings"),children:[(0,t.jsxs)(l.TabList,{className:"mb-4",children:[(0,t.jsx)(s.Tab,{children:"Users"}),(0,t.jsx)(s.Tab,{children:"Default User Settings"})]}),(0,t.jsxs)(n.TabPanels,{children:[(0,t.jsx)(a.TabPanel,{children:(0,t.jsx)(eE,{data:ex.data?.users||[],columns:ep,isLoading:ex.isLoading,accessToken:e,userRole:c,onSortChange:(e,t)=>{eo({sort_by:e,sort_order:t})},currentSort:{sortBy:E.sort_by,sortOrder:E.sort_order},possibleUIRoles:ef,handleEdit:e=>{v(e),p(!0)},handleDelete:ei,handleResetPassword:ed,enableSelection:es,selectedUsers:Z,onSelectionChange:e=>{X(e)},filters:E,updateFilters:eo,initialFilters:eR,teams:m,userListResponse:eg,currentPage:x,handlePageChange:eh})}),(0,t.jsx)(a.TabPanel,{children:u&&c&&e?(0,t.jsx)(Y,{accessToken:e,possibleUIRoles:ef,userID:u,userRole:c}):(0,t.jsx)("div",{className:"flex justify-center items-center h-64",children:(0,t.jsx)(eb.Skeleton,{active:!0,paragraph:{rows:4}})})})]})]}),(0,t.jsx)(L,{visible:f,possibleUIRoles:ef,onCancel:eu,user:j,onSubmit:em}),(0,t.jsx)($.default,{isOpen:y,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:w?.user_email},{label:"User ID",value:w?.user_id,code:!0},{label:"Global Proxy Role",value:w&&ef?.[w.user_role]?.ui_label||w?.user_role||"-"},{label:"Total Spend (USD)",value:w?.spend?.toFixed(2)}],onCancel:()=>{_(!1),T(null)},onOk:ec,confirmLoading:N}),(0,t.jsx)(A.default,{isInvitationLinkModalVisible:q,setIsInvitationLinkModalVisible:H,baseUrl:J||"",invitationLinkData:W,modalType:"resetPassword"}),(0,t.jsx)(F,{open:ee,onCancel:()=>et(!1),selectedUsers:Z,possibleUIRoles:ef,accessToken:e,onSuccess:()=>{h.invalidateQueries({queryKey:["userList"]}),X([]),er(!1)},teams:m,userRole:c,userModels:el,allowAllUsers:!!c&&(0,C.isAdminRole)(c)})]})}],910119)}]); \ No newline at end of file +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,757440,e=>{"use strict";var t=e.i(290571),s=e.i(271645);let r=e=>{var r=(0,t.__rest)(e,[]);return s.default.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"},r),s.default.createElement("path",{d:"M11.9999 13.1714L16.9497 8.22168L18.3639 9.63589L11.9999 15.9999L5.63599 9.63589L7.0502 8.22168L11.9999 13.1714Z"}))};e.s(["default",()=>r])},446428,854056,e=>{"use strict";let t;var s=e.i(290571),r=e.i(271645);let l=e=>{var t=(0,s.__rest)(e,[]);return r.default.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"},t),r.default.createElement("path",{d:"M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 10.5858L9.17157 7.75736L7.75736 9.17157L10.5858 12L7.75736 14.8284L9.17157 16.2426L12 13.4142L14.8284 16.2426L16.2426 14.8284L13.4142 12L16.2426 9.17157L14.8284 7.75736L12 10.5858Z"}))};e.s(["default",()=>l],446428);var a=e.i(746725),n=e.i(914189),i=e.i(553521),o=e.i(835696),d=e.i(941444),c=e.i(178677),u=e.i(294316),m=e.i(83733),h=e.i(233137),x=e.i(732607),g=e.i(397701),f=e.i(700020);function p(e){var t;return!!(e.enter||e.enterFrom||e.enterTo||e.leave||e.leaveFrom||e.leaveTo)||(null!=(t=e.as)?t:N)!==r.Fragment||1===r.default.Children.count(e.children)}let b=(0,r.createContext)(null);b.displayName="TransitionContext";var j=((t=j||{}).Visible="visible",t.Hidden="hidden",t);let y=(0,r.createContext)(null);function v(e){return"children"in e?v(e.children):e.current.filter(({el:e})=>null!==e.current).filter(({state:e})=>"visible"===e).length>0}function _(e,t){let s=(0,d.useLatestValue)(e),l=(0,r.useRef)([]),o=(0,i.useIsMounted)(),c=(0,a.useDisposables)(),u=(0,n.useEvent)((e,t=f.RenderStrategy.Hidden)=>{let r=l.current.findIndex(({el:t})=>t===e);-1!==r&&((0,g.match)(t,{[f.RenderStrategy.Unmount](){l.current.splice(r,1)},[f.RenderStrategy.Hidden](){l.current[r].state="hidden"}}),c.microTask(()=>{var e;!v(l)&&o.current&&(null==(e=s.current)||e.call(s))}))}),m=(0,n.useEvent)(e=>{let t=l.current.find(({el:t})=>t===e);return t?"visible"!==t.state&&(t.state="visible"):l.current.push({el:e,state:"visible"}),()=>u(e,f.RenderStrategy.Unmount)}),h=(0,r.useRef)([]),x=(0,r.useRef)(Promise.resolve()),p=(0,r.useRef)({enter:[],leave:[]}),b=(0,n.useEvent)((e,s,r)=>{h.current.splice(0),t&&(t.chains.current[s]=t.chains.current[s].filter(([t])=>t!==e)),null==t||t.chains.current[s].push([e,new Promise(e=>{h.current.push(e)})]),null==t||t.chains.current[s].push([e,new Promise(e=>{Promise.all(p.current[s].map(([e,t])=>t)).then(()=>e())})]),"enter"===s?x.current=x.current.then(()=>null==t?void 0:t.wait.current).then(()=>r(s)):r(s)}),j=(0,n.useEvent)((e,t,s)=>{Promise.all(p.current[t].splice(0).map(([e,t])=>t)).then(()=>{var e;null==(e=h.current.shift())||e()}).then(()=>s(t))});return(0,r.useMemo)(()=>({children:l,register:m,unregister:u,onStart:b,onStop:j,wait:x,chains:p}),[m,u,l,b,j,p,x])}y.displayName="NestingContext";let N=r.Fragment,S=f.RenderFeatures.RenderStrategy,w=(0,f.forwardRefWithAs)(function(e,t){let{show:s,appear:l=!1,unmount:a=!0,...i}=e,d=(0,r.useRef)(null),m=p(e),x=(0,u.useSyncRefs)(...m?[d,t]:null===t?[]:[t]);(0,c.useServerHandoffComplete)();let g=(0,h.useOpenClosed)();if(void 0===s&&null!==g&&(s=(g&h.State.Open)===h.State.Open),void 0===s)throw Error("A is used but it is missing a `show={true | false}` prop.");let[j,N]=(0,r.useState)(s?"visible":"hidden"),w=_(()=>{s||N("hidden")}),[T,k]=(0,r.useState)(!0),I=(0,r.useRef)([s]);(0,o.useIsoMorphicEffect)(()=>{!1!==T&&I.current[I.current.length-1]!==s&&(I.current.push(s),k(!1))},[I,s]);let E=(0,r.useMemo)(()=>({show:s,appear:l,initial:T}),[s,l,T]);(0,o.useIsoMorphicEffect)(()=>{s?N("visible"):v(w)||null===d.current||N("hidden")},[s,w]);let U={unmount:a},R=(0,n.useEvent)(()=>{var t;T&&k(!1),null==(t=e.beforeEnter)||t.call(e)}),B=(0,n.useEvent)(()=>{var t;T&&k(!1),null==(t=e.beforeLeave)||t.call(e)}),F=(0,f.useRender)();return r.default.createElement(y.Provider,{value:w},r.default.createElement(b.Provider,{value:E},F({ourProps:{...U,as:r.Fragment,children:r.default.createElement(C,{ref:x,...U,...i,beforeEnter:R,beforeLeave:B})},theirProps:{},defaultTag:r.Fragment,features:S,visible:"visible"===j,name:"Transition"})))}),C=(0,f.forwardRefWithAs)(function(e,t){var s,l;let{transition:a=!0,beforeEnter:i,afterEnter:d,beforeLeave:j,afterLeave:w,enter:C,enterFrom:T,enterTo:k,entered:I,leave:E,leaveFrom:U,leaveTo:R,...B}=e,[F,M]=(0,r.useState)(null),L=(0,r.useRef)(null),D=p(e),A=(0,u.useSyncRefs)(...D?[L,t,M]:null===t?[]:[t]),O=null==(s=B.unmount)||s?f.RenderStrategy.Unmount:f.RenderStrategy.Hidden,{show:P,appear:z,initial:V}=function(){let e=(0,r.useContext)(b);if(null===e)throw Error("A is used but it is missing a parent or .");return e}(),[$,K]=(0,r.useState)(P?"visible":"hidden"),q=function(){let e=(0,r.useContext)(y);if(null===e)throw Error("A is used but it is missing a parent or .");return e}(),{register:H,unregister:W}=q;(0,o.useIsoMorphicEffect)(()=>H(L),[H,L]),(0,o.useIsoMorphicEffect)(()=>{if(O===f.RenderStrategy.Hidden&&L.current)return P&&"visible"!==$?void K("visible"):(0,g.match)($,{hidden:()=>W(L),visible:()=>H(L)})},[$,L,H,W,P,O]);let G=(0,c.useServerHandoffComplete)();(0,o.useIsoMorphicEffect)(()=>{if(D&&G&&"visible"===$&&null===L.current)throw Error("Did you forget to passthrough the `ref` to the actual DOM node?")},[L,$,G,D]);let J=V&&!z,Q=z&&P&&V,Z=(0,r.useRef)(!1),Y=_(()=>{Z.current||(K("hidden"),W(L))},q),X=(0,n.useEvent)(e=>{Z.current=!0,Y.onStart(L,e?"enter":"leave",e=>{"enter"===e?null==i||i():"leave"===e&&(null==j||j())})}),ee=(0,n.useEvent)(e=>{let t=e?"enter":"leave";Z.current=!1,Y.onStop(L,t,e=>{"enter"===e?null==d||d():"leave"===e&&(null==w||w())}),"leave"!==t||v(Y)||(K("hidden"),W(L))});(0,r.useEffect)(()=>{D&&a||(X(P),ee(P))},[P,D,a]);let et=!(!a||!D||!G||J),[,es]=(0,m.useTransition)(et,F,P,{start:X,end:ee}),er=(0,f.compact)({ref:A,className:(null==(l=(0,x.classNames)(B.className,Q&&C,Q&&T,es.enter&&C,es.enter&&es.closed&&T,es.enter&&!es.closed&&k,es.leave&&E,es.leave&&!es.closed&&U,es.leave&&es.closed&&R,!es.transition&&P&&I))?void 0:l.trim())||void 0,...(0,m.transitionDataAttributes)(es)}),el=0;"visible"===$&&(el|=h.State.Open),"hidden"===$&&(el|=h.State.Closed),es.enter&&(el|=h.State.Opening),es.leave&&(el|=h.State.Closing);let ea=(0,f.useRender)();return r.default.createElement(y.Provider,{value:Y},r.default.createElement(h.OpenClosedProvider,{value:el},ea({ourProps:er,theirProps:B,defaultTag:N,features:S,visible:"visible"===$,name:"Transition.Child"})))}),T=(0,f.forwardRefWithAs)(function(e,t){let s=null!==(0,r.useContext)(b),l=null!==(0,h.useOpenClosed)();return r.default.createElement(r.default.Fragment,null,!s&&l?r.default.createElement(w,{ref:t,...e}):r.default.createElement(C,{ref:t,...e}))}),k=Object.assign(w,{Child:T,Root:w});e.s(["Transition",()=>k],854056)},206929,e=>{"use strict";var t=e.i(290571),s=e.i(757440),r=e.i(271645),l=e.i(446428),a=e.i(444755),n=e.i(673706),i=e.i(103471),o=e.i(495470),d=e.i(854056),c=e.i(888288);let u=(0,n.makeClassName)("Select"),m=r.default.forwardRef((e,n)=>{let{defaultValue:m="",value:h,onValueChange:x,placeholder:g="Select...",disabled:f=!1,icon:p,enableClear:b=!1,required:j,children:y,name:v,error:_=!1,errorMessage:N,className:S,id:w}=e,C=(0,t.__rest)(e,["defaultValue","value","onValueChange","placeholder","disabled","icon","enableClear","required","children","name","error","errorMessage","className","id"]),T=(0,r.useRef)(null),k=r.Children.toArray(y),[I,E]=(0,c.default)(m,h),U=(0,r.useMemo)(()=>{let e=r.default.Children.toArray(y).filter(r.isValidElement);return(0,i.constructValueToNameMapping)(e)},[y]);return r.default.createElement("div",{className:(0,a.tremorTwMerge)("w-full min-w-[10rem] text-tremor-default",S)},r.default.createElement("div",{className:"relative"},r.default.createElement("select",{title:"select-hidden",required:j,className:(0,a.tremorTwMerge)("h-full w-full absolute left-0 top-0 -z-10 opacity-0"),value:I,onChange:e=>{e.preventDefault()},name:v,disabled:f,id:w,onFocus:()=>{let e=T.current;e&&e.focus()}},r.default.createElement("option",{className:"hidden",value:"",disabled:!0,hidden:!0},g),k.map(e=>{let t=e.props.value,s=e.props.children;return r.default.createElement("option",{className:"hidden",key:t,value:t},s)})),r.default.createElement(o.Listbox,Object.assign({as:"div",ref:n,defaultValue:I,value:I,onChange:e=>{null==x||x(e),E(e)},disabled:f,id:w},C),({value:e})=>{var t;return r.default.createElement(r.default.Fragment,null,r.default.createElement(o.ListboxButton,{ref:T,className:(0,a.tremorTwMerge)("w-full outline-none text-left whitespace-nowrap truncate rounded-tremor-default focus:ring-2 transition duration-100 border pr-8 py-2","border-tremor-border shadow-tremor-input focus:border-tremor-brand-subtle focus:ring-tremor-brand-muted","dark:border-dark-tremor-border dark:shadow-dark-tremor-input dark:focus:border-dark-tremor-brand-subtle dark:focus:ring-dark-tremor-brand-muted",p?"pl-10":"pl-3",(0,i.getSelectButtonColors)((0,i.hasValue)(e),f,_))},p&&r.default.createElement("span",{className:(0,a.tremorTwMerge)("absolute inset-y-0 left-0 flex items-center ml-px pl-2.5")},r.default.createElement(p,{className:(0,a.tremorTwMerge)(u("Icon"),"flex-none h-5 w-5","text-tremor-content-subtle","dark:text-dark-tremor-content-subtle")})),r.default.createElement("span",{className:"w-[90%] block truncate"},e&&null!=(t=U.get(e))?t:g),r.default.createElement("span",{className:(0,a.tremorTwMerge)("absolute inset-y-0 right-0 flex items-center mr-3")},r.default.createElement(s.default,{className:(0,a.tremorTwMerge)(u("arrowDownIcon"),"flex-none h-5 w-5","text-tremor-content-subtle","dark:text-dark-tremor-content-subtle")}))),b&&I?r.default.createElement("button",{type:"button",className:(0,a.tremorTwMerge)("absolute inset-y-0 right-0 flex items-center mr-8"),onClick:e=>{e.preventDefault(),E(""),null==x||x("")}},r.default.createElement(l.default,{className:(0,a.tremorTwMerge)(u("clearIcon"),"flex-none h-4 w-4","text-tremor-content-subtle","dark:text-dark-tremor-content-subtle")})):null,r.default.createElement(d.Transition,{enter:"transition ease duration-100 transform",enterFrom:"opacity-0 -translate-y-4",enterTo:"opacity-100 translate-y-0",leave:"transition ease duration-100 transform",leaveFrom:"opacity-100 translate-y-0",leaveTo:"opacity-0 -translate-y-4"},r.default.createElement(o.ListboxOptions,{anchor:"bottom start",className:(0,a.tremorTwMerge)("z-10 w-[var(--button-width)] divide-y overflow-y-auto outline-none rounded-tremor-default max-h-[228px] border [--anchor-gap:4px]","bg-tremor-background border-tremor-border divide-tremor-border shadow-tremor-dropdown","dark:bg-dark-tremor-background dark:border-dark-tremor-border dark:divide-dark-tremor-border dark:shadow-dark-tremor-dropdown")},y)))})),_&&N?r.default.createElement("p",{className:(0,a.tremorTwMerge)("errorMessage","text-sm text-rose-500 mt-1")},N):null)});m.displayName="Select",e.s(["Select",()=>m],206929)},502275,e=>{"use strict";var t=e.i(271645);let s=t.forwardRef(function(e,s){return t.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:s},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"}))});e.s(["InformationCircleIcon",0,s],502275)},78085,e=>{"use strict";var t=e.i(290571),s=e.i(103471),r=e.i(888288),l=e.i(271645),a=e.i(444755),n=e.i(673706);let i=(0,n.makeClassName)("Textarea"),o=l.default.forwardRef((e,o)=>{let{value:d,defaultValue:c="",placeholder:u="Type...",error:m=!1,errorMessage:h,disabled:x=!1,className:g,onChange:f,onValueChange:p,autoHeight:b=!1}=e,j=(0,t.__rest)(e,["value","defaultValue","placeholder","error","errorMessage","disabled","className","onChange","onValueChange","autoHeight"]),[y,v]=(0,r.default)(c,d),_=(0,l.useRef)(null),N=(0,s.hasValue)(y);return(0,l.useEffect)(()=>{let e=_.current;if(b&&e){e.style.height="60px";let t=e.scrollHeight;e.style.height=t+"px"}},[b,_,y]),l.default.createElement(l.default.Fragment,null,l.default.createElement("textarea",Object.assign({ref:(0,n.mergeRefs)([_,o]),value:y,placeholder:u,disabled:x,className:(0,a.tremorTwMerge)(i("Textarea"),"w-full flex items-center outline-none rounded-tremor-default px-3 py-2 text-tremor-default focus:ring-2 transition duration-100 border","shadow-tremor-input focus:border-tremor-brand-subtle focus:ring-tremor-brand-muted","dark:shadow-dark-tremor-input focus:dark:border-dark-tremor-brand-subtle focus:dark:ring-dark-tremor-brand-muted",(0,s.getSelectButtonColors)(N,x,m),x?"placeholder:text-tremor-content-subtle dark:placeholder:text-dark-tremor-content-subtle":"placeholder:text-tremor-content dark:placeholder:text-dark-tremor-content",g),"data-testid":"text-area",onChange:e=>{null==f||f(e),v(e.target.value),null==p||p(e.target.value)}},j)),m&&h?l.default.createElement("p",{className:(0,a.tremorTwMerge)(i("errorMessage"),"text-sm text-red-500 mt-1")},h):null)});o.displayName="Textarea",e.s(["Textarea",()=>o],78085)},910119,e=>{"use strict";var t=e.i(843476),s=e.i(197647),r=e.i(653824),l=e.i(881073),a=e.i(404206),n=e.i(723731),i=e.i(271645),o=e.i(464571),d=e.i(212931),c=e.i(898586),u=e.i(312361),m=e.i(998573),h=e.i(291542),x=e.i(199133),g=e.i(28651),f=e.i(175712),p=e.i(770914),b=e.i(536916),j=e.i(764205),y=e.i(827252),v=e.i(994388),_=e.i(35983),N=e.i(779241),S=e.i(78085),w=e.i(808613),C=e.i(592968),T=e.i(708347),k=e.i(860585),I=e.i(355619),E=e.i(435451);function U({userData:e,onCancel:s,onSubmit:r,teams:l,accessToken:a,userID:n,userRole:o,userModels:d,possibleUIRoles:c,isBulkEdit:u=!1}){let[m]=w.Form.useForm(),[h,g]=(0,i.useState)(!1);return i.default.useEffect(()=>{let t=e.user_info?.max_budget,s=null==t;g(s),m.setFieldsValue({user_id:e.user_id,user_email:e.user_info?.user_email,user_alias:e.user_info?.user_alias,user_role:e.user_info?.user_role,models:e.user_info?.models||[],max_budget:s?"":t,budget_duration:e.user_info?.budget_duration,metadata:e.user_info?.metadata?JSON.stringify(e.user_info.metadata,null,2):void 0})},[e,m]),(0,t.jsxs)(w.Form,{form:m,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}(h||""===e.max_budget||void 0===e.max_budget)&&(e.max_budget=null),r(e)},layout:"vertical",children:[!u&&(0,t.jsx)(w.Form.Item,{label:"User ID",name:"user_id",children:(0,t.jsx)(N.TextInput,{disabled:!0})}),!u&&(0,t.jsx)(w.Form.Item,{label:"Email",name:"user_email",children:(0,t.jsx)(N.TextInput,{})}),(0,t.jsx)(w.Form.Item,{label:"User Alias",name:"user_alias",children:(0,t.jsx)(N.TextInput,{})}),(0,t.jsx)(w.Form.Item,{label:(0,t.jsxs)("span",{children:["Global Proxy Role"," ",(0,t.jsx)(C.Tooltip,{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)(y.InfoCircleOutlined,{})})]}),name:"user_role",children:(0,t.jsx)(x.Select,{children:c&&Object.entries(c).map(([e,{ui_label:s,description:r}])=>(0,t.jsx)(_.SelectItem,{value:e,title:s,children:(0,t.jsxs)("div",{className:"flex",children:[s," ",(0,t.jsx)("p",{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:r})]})},e))})}),(0,t.jsx)(w.Form.Item,{label:(0,t.jsxs)("span",{children:["Personal Models"," ",(0,t.jsx)(C.Tooltip,{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)(y.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"models",children:(0,t.jsxs)(x.Select,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},disabled:!T.all_admin_roles.includes(o||""),children:[(0,t.jsx)(x.Select.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),(0,t.jsx)(x.Select.Option,{value:"no-default-models",children:"No Default Models"},"no-default-models"),d.map(e=>(0,t.jsx)(x.Select.Option,{value:e,children:(0,I.getModelDisplayName)(e)},e))]})}),(0,t.jsx)(w.Form.Item,{label:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[(0,t.jsx)("span",{children:"Max Budget (USD)"}),(0,t.jsx)(b.Checkbox,{checked:h,onChange:e=>{let t=e.target.checked;g(t),t&&m.setFieldsValue({max_budget:""})},children:"Unlimited Budget"})]}),name:"max_budget",rules:[{validator:(e,t)=>h||""!==t&&null!=t?Promise.resolve():Promise.reject(Error("Please enter a budget or select Unlimited Budget"))}],children:(0,t.jsx)(E.default,{step:.01,precision:2,style:{width:"100%"},disabled:h})}),(0,t.jsx)(w.Form.Item,{label:"Reset Budget",name:"budget_duration",children:(0,t.jsx)(k.default,{})}),(0,t.jsx)(w.Form.Item,{label:"Metadata",name:"metadata",children:(0,t.jsx)(S.Textarea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,t.jsxs)("div",{className:"flex justify-end space-x-2",children:[(0,t.jsx)(v.Button,{variant:"secondary",type:"button",onClick:s,children:"Cancel"}),(0,t.jsx)(v.Button,{type:"submit",children:"Save Changes"})]})]})}var R=e.i(727749);let{Text:B,Title:F}=c.Typography,M=({open:e,onCancel:s,selectedUsers:r,possibleUIRoles:l,accessToken:a,onSuccess:n,teams:o,userRole:c,userModels:y,allowAllUsers:v=!1})=>{let[_,N]=(0,i.useState)(!1),[S,w]=(0,i.useState)([]),[C,T]=(0,i.useState)(null),[k,I]=(0,i.useState)(!1),[E,M]=(0,i.useState)(!1),L=()=>{w([]),T(null),I(!1),M(!1),s()},D=i.default.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:o||[]}),[o,e]),A=async e=>{if(console.log("formValues",e),!a)return void R.default.fromBackend("Access token not found");N(!0);try{let t=r.map(e=>e.user_id),l={};e.user_role&&""!==e.user_role&&(l.user_role=e.user_role),null!==e.max_budget&&void 0!==e.max_budget&&(l.max_budget=e.max_budget),e.models&&e.models.length>0&&(l.models=e.models),e.budget_duration&&""!==e.budget_duration&&(l.budget_duration=e.budget_duration),e.metadata&&Object.keys(e.metadata).length>0&&(l.metadata=e.metadata);let i=Object.keys(l).length>0,o=k&&S.length>0;if(!i&&!o)return void R.default.fromBackend("Please modify at least one field or select teams to add users to");let d=[];if(i)if(E){let e=await (0,j.userBulkUpdateUserCall)(a,l,void 0,!0);d.push(`Updated all users (${e.total_requested} total)`)}else await (0,j.userBulkUpdateUserCall)(a,l,t),d.push(`Updated ${t.length} user(s)`);if(o){let e=[];for(let t of S)try{let s=null;s=E?null:r.map(e=>({user_id:e.user_id,role:"user",user_email:e.user_email||null}));let l=await (0,j.teamBulkMemberAddCall)(a,t,s||null,C||void 0,E);console.log("result",l),e.push({teamId:t,success:!0,successfulAdditions:l.successful_additions,failedAdditions:l.failed_additions})}catch(s){console.error(`Failed to add users to team ${t}:`,s),e.push({teamId:t,success:!1,error:s})}let t=e.filter(e=>e.success),s=e.filter(e=>!e.success);if(t.length>0){let e=t.reduce((e,t)=>e+t.successfulAdditions,0);d.push(`Added users to ${t.length} team(s) (${e} total additions)`)}s.length>0&&m.message.warning(`Failed to add users to ${s.length} team(s)`)}d.length>0&&R.default.success(d.join(". ")),w([]),T(null),I(!1),M(!1),n(),s()}catch(e){console.error("Bulk operation failed:",e),R.default.fromBackend("Failed to perform bulk operations")}finally{N(!1)}};return(0,t.jsxs)(d.Modal,{open:e,onCancel:L,footer:null,title:E?"Bulk Edit All Users":`Bulk Edit ${r.length} User(s)`,width:800,children:[v&&(0,t.jsxs)("div",{className:"mb-4",children:[(0,t.jsx)(b.Checkbox,{checked:E,onChange:e=>M(e.target.checked),children:(0,t.jsx)(B,{strong:!0,children:"Update ALL users in the system"})}),E&&(0,t.jsx)("div",{style:{marginTop:8},children:(0,t.jsx)(B,{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)(F,{level:5,children:["Selected Users (",r.length,"):"]}),(0,t.jsx)(h.Table,{size:"small",bordered:!0,dataSource:r,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)(B,{strong:!0,style:{fontSize:"12px"},children:e.length>20?`${e.slice(0,20)}...`:e})},{title:"Email",dataIndex:"user_email",key:"user_email",width:"25%",render:e=>(0,t.jsx)(B,{type:"secondary",style:{fontSize:"12px"},children:e||"No email"})},{title:"Current Role",dataIndex:"user_role",key:"user_role",width:"25%",render:e=>(0,t.jsx)(B,{style:{fontSize:"12px"},children:l?.[e]?.ui_label||e})},{title:"Budget",dataIndex:"max_budget",key:"max_budget",width:"20%",render:e=>(0,t.jsx)(B,{style:{fontSize:"12px"},children:null!==e?`$${e}`:"Unlimited"})}]})]}),(0,t.jsx)(u.Divider,{}),(0,t.jsx)("div",{className:"mb-4",children:(0,t.jsxs)(B,{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)(f.Card,{title:"Team Management",size:"small",className:"mb-4",style:{backgroundColor:"#fafafa"},children:(0,t.jsxs)(p.Space,{direction:"vertical",style:{width:"100%"},children:[(0,t.jsx)(b.Checkbox,{checked:k,onChange:e=>I(e.target.checked),children:"Add selected users to teams"}),k&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(B,{strong:!0,children:"Select Teams:"}),(0,t.jsx)(x.Select,{mode:"multiple",placeholder:"Select teams to add users to",value:S,onChange:w,style:{width:"100%",marginTop:8},options:o?.map(e=>({label:e.team_alias||e.team_id,value:e.team_id}))||[]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(B,{strong:!0,children:"Team Budget (Optional):"}),(0,t.jsx)(g.InputNumber,{placeholder:"Max budget per user in team",value:C,onChange:e=>T(e),style:{width:"100%",marginTop:8},min:0,step:.01,precision:2}),(0,t.jsx)(B,{type:"secondary",style:{fontSize:"12px"},children:"Leave empty for unlimited budget within team limits"})]}),(0,t.jsx)(B,{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)(U,{userData:D,onCancel:L,onSubmit:A,teams:o,accessToken:a,userID:"bulk_edit",userRole:c,userModels:y,possibleUIRoles:l,isBulkEdit:!0}),_&&(0,t.jsx)("div",{style:{textAlign:"center",marginTop:"10px"},children:(0,t.jsxs)(B,{children:["Updating ",E?"all users":r.length," user(s)..."]})})]})};var L=e.i(371455);let D=({visible:e,possibleUIRoles:s,onCancel:r,user:l,onSubmit:a})=>{let[n,c]=(0,i.useState)(l),[u]=w.Form.useForm();(0,i.useEffect)(()=>{u.resetFields()},[l]);let m=async()=>{u.resetFields(),r()},h=async e=>{a(e),u.resetFields(),r()};return l?(0,t.jsx)(d.Modal,{open:e,onCancel:m,footer:null,title:"Edit User "+l.user_id,width:1e3,children:(0,t.jsx)(w.Form,{form:u,onFinish:h,initialValues:l,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(w.Form.Item,{className:"mt-8",label:"User Email",tooltip:"Email of the User",name:"user_email",children:(0,t.jsx)(N.TextInput,{})}),(0,t.jsx)(w.Form.Item,{label:"user_id",name:"user_id",hidden:!0,children:(0,t.jsx)(N.TextInput,{})}),(0,t.jsx)(w.Form.Item,{label:"User Role",name:"user_role",children:(0,t.jsx)(x.Select,{children:s&&Object.entries(s).map(([e,{ui_label:s,description:r}])=>(0,t.jsx)(_.SelectItem,{value:e,title:s,children:(0,t.jsxs)("div",{className:"flex",children:[s," ",(0,t.jsx)("p",{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:r})]})},e))})}),(0,t.jsx)(w.Form.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)(g.InputNumber,{min:0,step:.01})}),(0,t.jsx)(w.Form.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)(E.default,{min:0,step:.01})}),(0,t.jsx)(w.Form.Item,{label:"Reset Budget",name:"budget_duration",children:(0,t.jsx)(k.default,{})}),(0,t.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,t.jsx)(o.Button,{htmlType:"submit",children:"Save"})}),(0,t.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,t.jsx)(o.Button,{htmlType:"submit",children:"Save"})})]})})}):null};var A=e.i(172372),O=e.i(500330),P=e.i(152473),z=e.i(266027),V=e.i(912598),$=e.i(127952),K=e.i(304967),q=e.i(629569),H=e.i(599724),W=e.i(114600),G=e.i(482725),J=e.i(790848),Q=e.i(646563),Z=e.i(955135);let Y=({accessToken:e,possibleUIRoles:s,userID:r,userRole:l})=>{let[a,n]=(0,i.useState)(!0),[o,d]=(0,i.useState)(null),[u,m]=(0,i.useState)(!1),[h,f]=(0,i.useState)({}),[p,b]=(0,i.useState)(!1),[y,_]=(0,i.useState)([]),{Paragraph:S}=c.Typography,{Option:w}=x.Select;(0,i.useEffect)(()=>{(async()=>{if(!e)return n(!1);try{let t=await (0,j.getInternalUserSettings)(e);if(d(t),f(t.values||{}),e)try{let t=await (0,j.modelAvailableCall)(e,r,l);if(t&&t.data){let e=t.data.map(e=>e.id);_(e)}}catch(e){console.error("Error fetching available models:",e)}}catch(e){console.error("Error fetching SSO settings:",e),R.default.fromBackend("Failed to fetch SSO settings")}finally{n(!1)}})()},[e]);let C=async()=>{if(e){b(!0);try{let t=Object.entries(h).reduce((e,[t,s])=>(e[t]=""===s?null:s,e),{}),s=await (0,j.updateInternalUserSettings)(e,t);d({...o,values:s.settings}),m(!1)}catch(e){console.error("Error updating SSO settings:",e),R.default.fromBackend("Failed to update settings: "+e)}finally{b(!1)}}},T=(e,t)=>{f(s=>({...s,[e]:t}))},E=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"}):[];return a?(0,t.jsx)("div",{className:"flex justify-center items-center h-64",children:(0,t.jsx)(G.Spin,{size:"large"})}):o?(0,t.jsxs)(K.Card,{children:[(0,t.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,t.jsx)(q.Title,{children:"Default User Settings"}),!a&&o&&(u?(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(v.Button,{variant:"secondary",onClick:()=>{m(!1),f(o.values||{})},disabled:p,children:"Cancel"}),(0,t.jsx)(v.Button,{onClick:C,loading:p,children:"Save Changes"})]}):(0,t.jsx)(v.Button,{onClick:()=>m(!0),children:"Edit Settings"}))]}),o?.field_schema?.description&&(0,t.jsx)(S,{className:"mb-4",children:o.field_schema.description}),(0,t.jsx)(W.Divider,{}),(0,t.jsx)("div",{className:"mt-4 space-y-4",children:(()=>{let{values:e,field_schema:r}=o;return r&&r.properties?Object.entries(r.properties).map(([r,l])=>{let a=e[r],n=r.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)(H.Text,{className:"font-medium text-lg",children:n}),(0,t.jsx)(S,{className:"text-sm text-gray-500 mt-1",children:l.description||"No description available"}),u?(0,t.jsx)("div",{className:"mt-2",children:((e,r,l)=>{let a=r.type;if("teams"===e){let s,r;return(0,t.jsx)("div",{className:"mt-2",children:(s=E(h[e]||[]),r=(e,t,r)=>{let l=[...s];l[e]={...l[e],[t]:r},T("teams",l)},(0,t.jsxs)("div",{className:"space-y-3",children:[s.map((e,l)=>(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)(H.Text,{className:"font-medium",children:["Team ",l+1]}),(0,t.jsx)(v.Button,{size:"sm",variant:"secondary",icon:Z.DeleteOutlined,onClick:()=>{T("teams",s.filter((e,t)=>t!==l))},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)(H.Text,{className:"text-sm font-medium mb-1",children:"Team ID"}),(0,t.jsx)(N.TextInput,{value:e.team_id,onChange:e=>r(l,"team_id",e.target.value),placeholder:"Enter team ID"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"text-sm font-medium mb-1",children:"Max Budget in Team"}),(0,t.jsx)(g.InputNumber,{style:{width:"100%"},value:e.max_budget_in_team,onChange:e=>r(l,"max_budget_in_team",e),placeholder:"Optional",min:0,step:.01,precision:2})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"text-sm font-medium mb-1",children:"User Role"}),(0,t.jsxs)(x.Select,{style:{width:"100%"},value:e.user_role,onChange:e=>r(l,"user_role",e),children:[(0,t.jsx)(w,{value:"user",children:"User"}),(0,t.jsx)(w,{value:"admin",children:"Admin"})]})]})]})]},l)),(0,t.jsx)(v.Button,{variant:"secondary",icon:Q.PlusOutlined,onClick:()=>{T("teams",[...s,{team_id:"",user_role:"user"}])},className:"w-full",children:"Add Team"})]}))})}if("user_role"===e&&s)return(0,t.jsx)(x.Select,{style:{width:"100%"},value:h[e]||"",onChange:t=>T(e,t),className:"mt-2",children:Object.entries(s).filter(([e])=>e.includes("internal_user")).map(([e,{ui_label:s,description:r}])=>(0,t.jsx)(w,{value:e,children:(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)("span",{children:s}),(0,t.jsx)("span",{className:"ml-2 text-xs text-gray-500",children:r})]})},e))});if("budget_duration"===e)return(0,t.jsx)(k.default,{value:h[e]||null,onChange:t=>T(e,t),className:"mt-2"});if("boolean"===a)return(0,t.jsx)("div",{className:"mt-2",children:(0,t.jsx)(J.Switch,{checked:!!h[e],onChange:t=>T(e,t)})});if("array"===a&&r.items?.enum)return(0,t.jsx)(x.Select,{mode:"multiple",style:{width:"100%"},value:h[e]||[],onChange:t=>T(e,t),className:"mt-2",children:r.items.enum.map(e=>(0,t.jsx)(w,{value:e,children:e},e))});else if("models"===e)return(0,t.jsxs)(x.Select,{mode:"multiple",style:{width:"100%"},value:h[e]||[],onChange:t=>T(e,t),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"),y.map(e=>(0,t.jsx)(w,{value:e,children:(0,I.getModelDisplayName)(e)},e))]});else if("string"===a&&r.enum)return(0,t.jsx)(x.Select,{style:{width:"100%"},value:h[e]||"",onChange:t=>T(e,t),className:"mt-2",children:r.enum.map(e=>(0,t.jsx)(w,{value:e,children:e},e))});else return(0,t.jsx)(N.TextInput,{value:void 0!==h[e]?String(h[e]):"",onChange:t=>T(e,t.target.value),placeholder:r.description||"",className:"mt-2"})})(r,l,0)}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:((e,r)=>{if(null==r)return(0,t.jsx)("span",{className:"text-gray-400",children:"Not set"});if("teams"===e&&Array.isArray(r)){if(0===r.length)return(0,t.jsx)("span",{className:"text-gray-400",children:"No teams assigned"});let e=E(r);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?`$${(0,O.formatNumberWithCommas)(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&&s&&s[r]){let{ui_label:e,description:l}=s[r];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})]})}if("budget_duration"===e)return(0,t.jsx)("span",{children:(0,k.getBudgetDurationLabel)(r)});if("boolean"==typeof r)return(0,t.jsx)("span",{children:r?"Enabled":"Disabled"});if("models"===e&&Array.isArray(r))return 0===r.length?(0,t.jsx)("span",{className:"text-gray-400",children:"None"}):(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:r.map((e,s)=>(0,t.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:(0,I.getModelDisplayName)(e)},s))});if("object"==typeof r)return Array.isArray(r)?0===r.length?(0,t.jsx)("span",{className:"text-gray-400",children:"None"}):(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:r.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(r,null,2)});return(0,t.jsx)("span",{children:String(r)})})(r,a)})]},r)}):(0,t.jsx)(H.Text,{children:"No schema information available"})})()})]}):(0,t.jsx)(K.Card,{children:(0,t.jsx)(H.Text,{children:"No settings available or you do not have permission to view them."})})};var X=e.i(389083),ee=e.i(350967),et=e.i(752978),es=e.i(591935),er=e.i(68155),el=e.i(502275),ea=e.i(278587);let en=(e,s,r,l,a,n)=>{let i=[{header:"User ID",accessorKey:"user_id",enableSorting:!0,cell:({row:e})=>(0,t.jsx)(C.Tooltip,{title:e.original.user_id,children:(0,t.jsx)("span",{className:"text-xs",children:e.original.user_id?`${e.original.user_id.slice(0,7)}...`:"-"})})},{header:"Email",accessorKey:"user_email",enableSorting:!0,cell:({row:e})=>(0,t.jsx)("span",{className:"text-xs",children:e.original.user_email||"-"})},{header:"Global Proxy Role",accessorKey:"user_role",enableSorting:!0,cell:({row:s})=>(0,t.jsx)("span",{className:"text-xs",children:e?.[s.original.user_role]?.ui_label||"-"})},{header:"User Alias",accessorKey:"user_alias",enableSorting:!1,cell:({row:e})=>(0,t.jsx)("span",{className:"text-xs",children:e.original.user_alias||"-"})},{header:"Spend (USD)",accessorKey:"spend",enableSorting:!0,cell:({row:e})=>(0,t.jsx)("span",{className:"text-xs",children:e.original.spend?(0,O.formatNumberWithCommas)(e.original.spend,4):"-"})},{header:"Budget (USD)",accessorKey:"max_budget",enableSorting:!1,cell:({row:e})=>(0,t.jsx)("span",{className:"text-xs",children:null!==e.original.max_budget?e.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)(C.Tooltip,{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)(el.InformationCircleIcon,{className:"w-4 h-4"})})]}),accessorKey:"sso_user_id",enableSorting:!1,cell:({row:e})=>(0,t.jsx)("span",{className:"text-xs",children:null!==e.original.sso_user_id?e.original.sso_user_id:"-"})},{header:"Virtual Keys",accessorKey:"key_count",enableSorting:!1,cell:({row:e})=>(0,t.jsx)(ee.Grid,{numItems:2,children:e.original.key_count>0?(0,t.jsxs)(X.Badge,{size:"xs",color:"indigo",children:[e.original.key_count," ",1===e.original.key_count?"Key":"Keys"]}):(0,t.jsx)(X.Badge,{size:"xs",color:"gray",children:"No Keys"})})},{header:"Created At",accessorKey:"created_at",enableSorting:!0,cell:({row:e})=>(0,t.jsx)("span",{className:"text-xs",children:e.original.created_at?new Date(e.original.created_at).toLocaleDateString():"-"})},{header:"Updated At",accessorKey:"updated_at",enableSorting:!1,cell:({row:e})=>(0,t.jsx)("span",{className:"text-xs",children:e.original.updated_at?new Date(e.original.updated_at).toLocaleDateString():"-"})},{id:"actions",header:"Actions",enableSorting:!1,cell:({row:e})=>(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(C.Tooltip,{title:"Edit user details",children:(0,t.jsx)(et.Icon,{icon:es.PencilAltIcon,size:"sm",onClick:()=>a(e.original.user_id,!0),className:"cursor-pointer hover:text-blue-600"})}),(0,t.jsx)(C.Tooltip,{title:"Delete user",children:(0,t.jsx)(et.Icon,{icon:er.TrashIcon,size:"sm",onClick:()=>r(e.original),className:"cursor-pointer hover:text-red-600"})}),(0,t.jsx)(C.Tooltip,{title:"Reset Password",children:(0,t.jsx)(et.Icon,{icon:ea.RefreshIcon,size:"sm",onClick:()=>l(e.original.user_id),className:"cursor-pointer hover:text-green-600"})})]})}];if(n){let{onSelectUser:e,onSelectAll:s,isUserSelected:r,isAllSelected:l,isIndeterminate:a}=n;return[{id:"select",enableSorting:!1,header:()=>(0,t.jsx)(b.Checkbox,{indeterminate:a,checked:l,onChange:e=>s(e.target.checked),onClick:e=>e.stopPropagation()}),cell:({row:s})=>(0,t.jsx)(b.Checkbox,{checked:r(s.original),onChange:t=>e(s.original,t.target.checked),onClick:e=>e.stopPropagation()})},...i]}return i};var ei=e.i(152990),eo=e.i(682830),ed=e.i(269200),ec=e.i(427612),eu=e.i(64848),em=e.i(942232),eh=e.i(496020),ex=e.i(977572),eg=e.i(206929),ef=e.i(94629),ep=e.i(360820),eb=e.i(871943),ej=e.i(981339),ey=e.i(530212),ev=e.i(118366),e_=e.i(678784);function eN({userId:e,onClose:d,accessToken:c,userRole:u,onDelete:m,possibleUIRoles:h,initialTab:x=0,startInEditMode:g=!1}){let[f,p]=(0,i.useState)(null),[b,y]=(0,i.useState)(!1),[_,N]=(0,i.useState)(!1),[S,w]=(0,i.useState)(!0),[C,I]=(0,i.useState)(g),[E,B]=(0,i.useState)([]),[F,M]=(0,i.useState)(!1),[L,D]=(0,i.useState)(null),[P,z]=(0,i.useState)(null),[V,W]=(0,i.useState)(x),[G,J]=(0,i.useState)({}),[Q,Z]=(0,i.useState)(!1);i.default.useEffect(()=>{z((0,j.getProxyBaseUrl)())},[]),i.default.useEffect(()=>{console.log(`userId: ${e}, userRole: ${u}, accessToken: ${c}`),(async()=>{try{if(!c)return;let t=await (0,j.userInfoCall)(c,e,u||"",!1,null,null,!0);p(t);let s=(await (0,j.modelAvailableCall)(c,e,u||"")).data.map(e=>e.id);B(s)}catch(e){console.error("Error fetching user data:",e),R.default.fromBackend("Failed to fetch user data")}finally{w(!1)}})()},[c,e,u]);let Y=async()=>{if(!c)return void R.default.fromBackend("Access token not found");try{R.default.success("Generating password reset link...");let t=await (0,j.invitationCreateCall)(c,e);D(t),M(!0)}catch(e){R.default.fromBackend("Failed to generate password reset link")}},et=async()=>{try{if(!c)return;N(!0),await (0,j.userDeleteCall)(c,[e]),R.default.success("User deleted successfully"),m&&m(),d()}catch(e){console.error("Error deleting user:",e),R.default.fromBackend("Failed to delete user")}finally{y(!1),N(!1)}},es=async e=>{try{if(!c||!f)return;await (0,j.userUpdateUserCall)(c,e,null),p({...f,user_info:{...f.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}}),R.default.success("User updated successfully"),I(!1)}catch(e){console.error("Error updating user:",e),R.default.fromBackend("Failed to update user")}};if(S)return(0,t.jsxs)("div",{className:"p-4",children:[(0,t.jsx)(v.Button,{icon:ey.ArrowLeftIcon,variant:"light",onClick:d,className:"mb-4",children:"Back to Users"}),(0,t.jsx)(H.Text,{children:"Loading user data..."})]});if(!f)return(0,t.jsxs)("div",{className:"p-4",children:[(0,t.jsx)(v.Button,{icon:ey.ArrowLeftIcon,variant:"light",onClick:d,className:"mb-4",children:"Back to Users"}),(0,t.jsx)(H.Text,{children:"User not found"})]});let el=async(e,t)=>{await (0,O.copyToClipboard)(e)&&(J(e=>({...e,[t]:!0})),setTimeout(()=>{J(e=>({...e,[t]:!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)(v.Button,{icon:ey.ArrowLeftIcon,variant:"light",onClick:d,className:"mb-4",children:"Back to Users"}),(0,t.jsx)(q.Title,{children:f.user_info?.user_email||"User"}),(0,t.jsxs)("div",{className:"flex items-center cursor-pointer",children:[(0,t.jsx)(H.Text,{className:"text-gray-500 font-mono",children:f.user_id}),(0,t.jsx)(o.Button,{type:"text",size:"small",icon:G["user-id"]?(0,t.jsx)(e_.CheckIcon,{size:12}):(0,t.jsx)(ev.CopyIcon,{size:12}),onClick:()=>el(f.user_id,"user-id"),className:`left-2 z-10 transition-all duration-200 ${G["user-id"]?"text-green-600 bg-green-50 border-green-200":"text-gray-500 hover:text-gray-700 hover:bg-gray-100"}`})]})]}),u&&T.rolesWithWriteAccess.includes(u)&&(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)(v.Button,{icon:ea.RefreshIcon,variant:"secondary",onClick:Y,className:"flex items-center",children:"Reset Password"}),(0,t.jsx)(v.Button,{icon:er.TrashIcon,variant:"secondary",onClick:()=>y(!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)($.default,{isOpen:b,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:f.user_info?.user_email},{label:"User ID",value:f.user_id,code:!0},{label:"Global Proxy Role",value:f.user_info?.user_role&&h?.[f.user_info.user_role]?.ui_label||f.user_info?.user_role||"-"},{label:"Total Spend (USD)",value:f.user_info?.spend!==null&&f.user_info?.spend!==void 0?f.user_info.spend.toFixed(2):void 0}],onCancel:()=>{y(!1)},onOk:et,confirmLoading:_}),(0,t.jsxs)(r.TabGroup,{defaultIndex:V,onIndexChange:W,children:[(0,t.jsxs)(l.TabList,{className:"mb-4",children:[(0,t.jsx)(s.Tab,{children:"Overview"}),(0,t.jsx)(s.Tab,{children:"Details"})]}),(0,t.jsxs)(n.TabPanels,{children:[(0,t.jsx)(a.TabPanel,{children:(0,t.jsxs)(ee.Grid,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,t.jsxs)(K.Card,{children:[(0,t.jsx)(H.Text,{children:"Spend"}),(0,t.jsxs)("div",{className:"mt-2",children:[(0,t.jsxs)(q.Title,{children:["$",(0,O.formatNumberWithCommas)(f.user_info?.spend||0,4)]}),(0,t.jsxs)(H.Text,{children:["of"," ",f.user_info?.max_budget!==null?`$${(0,O.formatNumberWithCommas)(f.user_info.max_budget,4)}`:"Unlimited"]})]})]}),(0,t.jsxs)(K.Card,{children:[(0,t.jsx)(H.Text,{children:"Teams"}),(0,t.jsx)("div",{className:"mt-2",children:f.teams?.length&&f.teams?.length>0?(0,t.jsxs)("div",{className:"flex flex-wrap gap-2",children:[f.teams?.slice(0,Q?f.teams.length:20).map((e,s)=>(0,t.jsx)(X.Badge,{color:"blue",title:e.team_alias,children:e.team_alias},s)),!Q&&f.teams?.length>20&&(0,t.jsxs)(X.Badge,{color:"gray",className:"cursor-pointer hover:bg-gray-200 transition-colors",onClick:()=>Z(!0),children:["+",f.teams.length-20," more"]}),Q&&f.teams?.length>20&&(0,t.jsx)(X.Badge,{color:"gray",className:"cursor-pointer hover:bg-gray-200 transition-colors",onClick:()=>Z(!1),children:"Show Less"})]}):(0,t.jsx)(H.Text,{children:"No teams"})})]}),(0,t.jsxs)(K.Card,{children:[(0,t.jsx)(H.Text,{children:"Virtual Keys"}),(0,t.jsx)("div",{className:"mt-2",children:(0,t.jsxs)(H.Text,{children:[f.keys?.length||0," ",f.keys?.length===1?"Key":"Keys"]})})]}),(0,t.jsxs)(K.Card,{children:[(0,t.jsx)(H.Text,{children:"Personal Models"}),(0,t.jsx)("div",{className:"mt-2",children:f.user_info?.models?.length&&f.user_info?.models?.length>0?f.user_info?.models?.map((e,s)=>(0,t.jsx)(H.Text,{children:e},s)):(0,t.jsx)(H.Text,{children:"All proxy models"})})]})]})}),(0,t.jsx)(a.TabPanel,{children:(0,t.jsxs)(K.Card,{children:[(0,t.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,t.jsx)(q.Title,{children:"User Settings"}),!C&&u&&T.rolesWithWriteAccess.includes(u)&&(0,t.jsx)(v.Button,{onClick:()=>I(!0),children:"Edit Settings"})]}),C&&f?(0,t.jsx)(U,{userData:f,onCancel:()=>I(!1),onSubmit:es,teams:f.teams,accessToken:c,userID:e,userRole:u,userModels:E,possibleUIRoles:h}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"font-medium",children:"User ID"}),(0,t.jsxs)("div",{className:"flex items-center cursor-pointer",children:[(0,t.jsx)(H.Text,{className:"font-mono",children:f.user_id}),(0,t.jsx)(o.Button,{type:"text",size:"small",icon:G["user-id"]?(0,t.jsx)(e_.CheckIcon,{size:12}):(0,t.jsx)(ev.CopyIcon,{size:12}),onClick:()=>el(f.user_id,"user-id"),className:`left-2 z-10 transition-all duration-200 ${G["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)(H.Text,{className:"font-medium",children:"Email"}),(0,t.jsx)(H.Text,{children:f.user_info?.user_email||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"font-medium",children:"User Alias"}),(0,t.jsx)(H.Text,{children:f.user_info?.user_alias||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"font-medium",children:"Global Proxy Role"}),(0,t.jsx)(H.Text,{children:f.user_info?.user_role||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"font-medium",children:"Created"}),(0,t.jsx)(H.Text,{children:f.user_info?.created_at?new Date(f.user_info.created_at).toLocaleString():"Unknown"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"font-medium",children:"Last Updated"}),(0,t.jsx)(H.Text,{children:f.user_info?.updated_at?new Date(f.user_info.updated_at).toLocaleString():"Unknown"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"font-medium",children:"Teams"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:f.teams?.length&&f.teams?.length>0?(0,t.jsxs)(t.Fragment,{children:[f.teams?.slice(0,Q?f.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)),!Q&&f.teams?.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:()=>Z(!0),children:["+",f.teams.length-20," more"]}),Q&&f.teams?.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:()=>Z(!1),children:"Show Less"})]}):(0,t.jsx)(H.Text,{children:"No teams"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"font-medium",children:"Personal Models"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:f.user_info?.models?.length&&f.user_info?.models?.length>0?f.user_info?.models?.map((e,s)=>(0,t.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:e},s)):(0,t.jsx)(H.Text,{children:"All proxy models"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"font-medium",children:"Virtual Keys"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:f.keys?.length&&f.keys?.length>0?f.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)(H.Text,{children:"No Virtual Keys"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"font-medium",children:"Max Budget"}),(0,t.jsx)(H.Text,{children:f.user_info?.max_budget!==null&&f.user_info?.max_budget!==void 0?`$${(0,O.formatNumberWithCommas)(f.user_info.max_budget,4)}`:"Unlimited"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{className:"font-medium",children:"Budget Reset"}),(0,t.jsx)(H.Text,{children:(0,k.getBudgetDurationLabel)(f.user_info?.budget_duration??null)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(H.Text,{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(f.user_info?.metadata||{},null,2)})]})]})]})})]})]}),(0,t.jsx)(A.default,{isInvitationLinkModalVisible:F,setIsInvitationLinkModalVisible:M,baseUrl:P||"",invitationLinkData:L,modalType:"resetPassword"})]})}var eS=e.i(655913),ew=e.i(38419),eC=e.i(78334),eT=e.i(555436),ek=e.i(284614);let eI=(0,e.i(475254).default)("circle-user-round",[["path",{d:"M18 20a6 6 0 0 0-12 0",key:"1qehca"}],["circle",{cx:"12",cy:"10",r:"4",key:"1h16sb"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);function eE({data:e=[],columns:s,isLoading:r=!1,onSortChange:l,currentSort:a,accessToken:n,userRole:o,possibleUIRoles:d,handleEdit:c,handleDelete:u,handleResetPassword:m,selectedUsers:h=[],onSelectionChange:x,enableSelection:g=!1,filters:f,updateFilters:p,initialFilters:b,teams:j,userListResponse:y,currentPage:v,handlePageChange:N}){let[S,w]=i.default.useState([{id:a?.sortBy||"created_at",desc:a?.sortOrder==="desc"}]),[C,T]=i.default.useState(null),[k,I]=i.default.useState(!1),[E,U]=i.default.useState(!1),R=(e,t=!1)=>{T(e),I(t)},B=(e,t)=>{x&&(t?x([...h,e]):x(h.filter(t=>t.user_id!==e.user_id)))},F=t=>{x&&(t?x(e):x([]))},M=e=>h.some(t=>t.user_id===e.user_id),L=e.length>0&&h.length===e.length,D=h.length>0&&h.lengthd?en(d,c,u,m,R,g?{selectedUsers:h,onSelectUser:B,onSelectAll:F,isUserSelected:M,isAllSelected:L,isIndeterminate:D}:void 0):s,[d,c,u,m,R,s,g,h,L,D]),O=(0,ei.useReactTable)({data:e,columns:A,state:{sorting:S},onSortingChange:e=>{let t="function"==typeof e?e(S):e;if(w(t),t&&Array.isArray(t)&&t.length>0&&t[0]){let e=t[0];if(e.id){let t=e.id,s=e.desc?"desc":"asc";l?.(t,s)}}else l?.("created_at","desc")},getCoreRowModel:(0,eo.getCoreRowModel)(),manualSorting:!0,enableSorting:!0});return(i.default.useEffect(()=>{a&&w([{id:a.sortBy,desc:"desc"===a.sortOrder}])},[a]),C)?(0,t.jsx)(eN,{userId:C,onClose:()=>{T(null),I(!1)},accessToken:n,userRole:o,possibleUIRoles:d,initialTab:+!!k,startInEditMode:k}):(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)(eS.FilterInput,{placeholder:"Search by email...",value:f.email,onChange:e=>p({email:e}),icon:eT.Search}),(0,t.jsx)(ew.FiltersButton,{onClick:()=>U(!E),active:E,hasActiveFilters:!!(f.user_id||f.user_role||f.team)}),(0,t.jsx)(eC.ResetFiltersButton,{onClick:()=>{p(b)}})]}),E&&(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-3 mt-3",children:[(0,t.jsx)(eS.FilterInput,{placeholder:"Filter by User ID",value:f.user_id,onChange:e=>p({user_id:e}),icon:ek.User}),(0,t.jsx)(eS.FilterInput,{placeholder:"Filter by SSO ID",value:f.sso_user_id,onChange:e=>p({sso_user_id:e}),icon:eI}),(0,t.jsx)("div",{className:"w-64",children:(0,t.jsx)(eg.Select,{value:f.user_role,onValueChange:e=>p({user_role:e}),placeholder:"Select Role",children:d&&Object.entries(d).map(([e,s])=>(0,t.jsx)(_.SelectItem,{value:e,children:s.ui_label},e))})}),(0,t.jsx)("div",{className:"w-64",children:(0,t.jsx)(eg.Select,{value:f.team,onValueChange:e=>p({team:e}),placeholder:"Select Team",children:j?.map(e=>(0,t.jsx)(_.SelectItem,{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:[r?(0,t.jsx)(ej.Skeleton.Input,{active:!0,style:{width:192,height:20}}):(0,t.jsxs)("span",{className:"text-sm text-gray-700",children:["Showing"," ",y&&y.users&&y.users.length>0?(y.page-1)*y.page_size+1:0," ","-"," ",y&&y.users?Math.min(y.page*y.page_size,y.total):0," ","of ",y?y.total:0," results"]}),(0,t.jsx)("div",{className:"flex space-x-2",children:r?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(ej.Skeleton.Button,{active:!0,size:"small",style:{width:80,height:30}}),(0,t.jsx)(ej.Skeleton.Button,{active:!0,size:"small",style:{width:60,height:30}})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("button",{onClick:()=>N(v-1),disabled:1===v,className:`px-3 py-1 text-sm border rounded-md ${1===v?"bg-gray-100 text-gray-400 cursor-not-allowed":"hover:bg-gray-50"}`,children:"Previous"}),(0,t.jsx)("button",{onClick:()=>N(v+1),disabled:!y||v>=y.total_pages,className:`px-3 py-1 text-sm border rounded-md ${!y||v>=y.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)(ed.Table,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,t.jsx)(ec.TableHead,{children:O.getHeaderGroups().map(e=>(0,t.jsx)(eh.TableRow,{children:e.headers.map(e=>(0,t.jsx)(eu.TableHeaderCell,{className:`py-1 h-8 ${"actions"===e.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]":""} ${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,ei.flexRender)(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)(ep.ChevronUpIcon,{className:"h-4 w-4 text-blue-500"}),desc:(0,t.jsx)(eb.ChevronDownIcon,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,t.jsx)(ef.SwitchVerticalIcon,{className:"h-4 w-4 text-gray-400"})})]})},e.id))},e.id))}),(0,t.jsx)(em.TableBody,{children:r?(0,t.jsx)(eh.TableRow,{children:(0,t.jsx)(ex.TableCell,{colSpan:A.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:"🚅 Loading users..."})})})}):e.length>0?O.getRowModel().rows.map(e=>(0,t.jsx)(eh.TableRow,{className:"h-8",children:e.getVisibleCells().map(e=>(0,t.jsx)(ex.TableCell,{className:`py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap ${"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&&R(e.getValue(),!1)},style:{cursor:"user_id"===e.column.id?"pointer":"default",color:"user_id"===e.column.id?"#3b82f6":"inherit"},children:(0,ei.flexRender)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,t.jsx)(eh.TableRow,{children:(0,t.jsx)(ex.TableCell,{colSpan:A.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:eU,Title:eR}=c.Typography,eB={email:"",user_id:"",user_role:"",sso_user_id:"",team:"",model:"",min_spend:null,max_spend:null,sort_by:"created_at",sort_order:"desc"};e.s(["default",0,({accessToken:e,token:d,userRole:c,userID:u,teams:m,orgAdminOrgIds:h})=>{let x=!!c&&(0,T.isProxyAdminRole)(c),g=(0,V.useQueryClient)(),[f,p]=(0,i.useState)(1),[b,y]=(0,i.useState)(!1),[v,_]=(0,i.useState)(null),[N,S]=(0,i.useState)(!1),[w,C]=(0,i.useState)(!1),[k,I]=(0,i.useState)(null),[E,U]=(0,i.useState)("users"),[B,F]=(0,i.useState)(eB),[K,q,H]=(0,P.useDebouncedState)(B,{wait:300}),[W,G]=(0,i.useState)(!1),[J,Q]=(0,i.useState)(null),[Z,X]=(0,i.useState)(null),[ee,et]=(0,i.useState)([]),[es,er]=(0,i.useState)(!1),[el,ea]=(0,i.useState)(!1),[ei,eo]=(0,i.useState)([]),ed=e=>{I(e),S(!0)};(0,i.useEffect)(()=>()=>{H.cancel()},[H]),(0,i.useEffect)(()=>{X((0,j.getProxyBaseUrl)())},[]),(0,i.useEffect)(()=>{(async()=>{try{if(!u||!c||!e)return;let t=(await (0,j.modelAvailableCall)(e,u,c)).data.map(e=>e.id);console.log("available_model_names:",t),eo(t)}catch(e){console.error("Error fetching user models:",e)}})()},[e,u,c]);let ec=e=>{F(t=>{let s={...t,...e};return q(s),s})},eu=(e,t)=>{ec({sort_by:e,sort_order:t})},em=async t=>{if(!e)return void R.default.fromBackend("Access token not found");try{R.default.success("Generating password reset link...");let s=await (0,j.invitationCreateCall)(e,t);Q(s),G(!0)}catch(e){R.default.fromBackend("Failed to generate password reset link")}},eh=async()=>{if(k&&e)try{C(!0),await (0,j.userDeleteCall)(e,[k.user_id]),g.setQueriesData({queryKey:["userList"]},e=>{if(void 0===e)return e;let t=e.users.filter(e=>e.user_id!==k.user_id);return{...e,users:t}}),R.default.success("User deleted successfully")}catch(e){console.error("Error deleting user:",e),R.default.fromBackend("Failed to delete user")}finally{S(!1),I(null),C(!1)}},ex=async()=>{_(null),y(!1)},eg=async t=>{if(console.log("inside handleEditSubmit:",t),e&&d&&c&&u){try{let s=await (0,j.userUpdateUserCall)(e,t,null);g.setQueriesData({queryKey:["userList"]},e=>{if(void 0===e)return e;let t=e.users.map(e=>e.user_id===s.data.user_id?(0,O.updateExistingKeys)(e,s.data):e);return{...e,users:t}}),R.default.success(`User ${t.user_id} updated successfully`)}catch(e){console.error("There was an error updating the user",e)}_(null),y(!1)}},ef=async e=>{p(e)},ep=e=>{et(e)},eb=(0,z.useQuery)({queryKey:["userList",{debouncedFilter:K,currentPage:f,orgAdminOrgIds:h}],queryFn:async()=>{if(!e)throw Error("Access token required");return await (0,j.userListCall)(e,K.user_id?[K.user_id]:null,f,25,K.email||null,K.user_role||null,K.team||null,K.sso_user_id||null,K.sort_by,K.sort_order,h?h.map(e=>e.organization_id):null)},enabled:!!(e&&d&&c&&u),placeholderData:e=>e}),ey=eb.data,ev=(0,z.useQuery)({queryKey:["userRoles"],initialData:()=>({}),queryFn:async()=>{if(!e)throw Error("Access token required");return await (0,j.getPossibleUserRoles)(e)},enabled:!!(e&&d&&c&&u)}).data,e_=en(ev,e=>{_(e),y(!0)},ed,em,()=>{});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:eb.isLoading?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(ej.Skeleton.Button,{active:!0,size:"default",shape:"default",style:{width:110,height:36}}),(0,t.jsx)(ej.Skeleton.Button,{active:!0,size:"default",shape:"default",style:{width:145,height:36}}),(0,t.jsx)(ej.Skeleton.Button,{active:!0,size:"default",shape:"default",style:{width:110,height:36}})]}):u&&e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(L.CreateUserButton,{userID:u,accessToken:e,teams:m,possibleUIRoles:ev}),x&&(0,t.jsx)(o.Button,{onClick:()=>{ea(!el),et([])},type:el?"primary":"default",className:"flex items-center",children:el?"Cancel Selection":"Select Users"}),x&&el&&(0,t.jsxs)(o.Button,{type:"primary",onClick:()=>{0===ee.length?R.default.fromBackend("Please select users to edit"):er(!0)},disabled:0===ee.length,className:"flex items-center",children:["Bulk Edit (",ee.length," selected)"]})]}):null})}),x?(0,t.jsxs)(r.TabGroup,{defaultIndex:0,onIndexChange:e=>U(0===e?"users":"settings"),children:[(0,t.jsxs)(l.TabList,{className:"mb-4",children:[(0,t.jsx)(s.Tab,{children:"Users"}),(0,t.jsx)(s.Tab,{children:"Default User Settings"})]}),(0,t.jsxs)(n.TabPanels,{children:[(0,t.jsx)(a.TabPanel,{children:(0,t.jsx)(eE,{data:eb.data?.users||[],columns:e_,isLoading:eb.isLoading,accessToken:e,userRole:c,onSortChange:eu,currentSort:{sortBy:B.sort_by,sortOrder:B.sort_order},possibleUIRoles:ev,handleEdit:e=>{_(e),y(!0)},handleDelete:ed,handleResetPassword:em,enableSelection:el,selectedUsers:ee,onSelectionChange:ep,filters:B,updateFilters:ec,initialFilters:eB,teams:m,userListResponse:ey,currentPage:f,handlePageChange:ef})}),(0,t.jsx)(a.TabPanel,{children:u&&c&&e?(0,t.jsx)(Y,{accessToken:e,possibleUIRoles:ev,userID:u,userRole:c}):(0,t.jsx)("div",{className:"flex justify-center items-center h-64",children:(0,t.jsx)(ej.Skeleton,{active:!0,paragraph:{rows:4}})})})]})]}):(0,t.jsx)(eE,{data:eb.data?.users||[],columns:e_,isLoading:eb.isLoading,accessToken:e,userRole:c,onSortChange:eu,currentSort:{sortBy:B.sort_by,sortOrder:B.sort_order},possibleUIRoles:ev,handleEdit:e=>{_(e),y(!0)},handleDelete:ed,handleResetPassword:em,enableSelection:!1,selectedUsers:[],onSelectionChange:ep,filters:B,updateFilters:ec,initialFilters:eB,teams:m,userListResponse:ey,currentPage:f,handlePageChange:ef}),(0,t.jsx)(D,{visible:b,possibleUIRoles:ev,onCancel:ex,user:v,onSubmit:eg}),(0,t.jsx)($.default,{isOpen:N,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:k?.user_email},{label:"User ID",value:k?.user_id,code:!0},{label:"Global Proxy Role",value:k&&ev?.[k.user_role]?.ui_label||k?.user_role||"-"},{label:"Total Spend (USD)",value:k?.spend?.toFixed(2)}],onCancel:()=>{S(!1),I(null)},onOk:eh,confirmLoading:w}),(0,t.jsx)(A.default,{isInvitationLinkModalVisible:W,setIsInvitationLinkModalVisible:G,baseUrl:Z||"",invitationLinkData:J,modalType:"resetPassword"}),(0,t.jsx)(M,{open:es,onCancel:()=>er(!1),selectedUsers:ee,possibleUIRoles:ev,accessToken:e,onSuccess:()=>{g.invalidateQueries({queryKey:["userList"]}),et([]),ea(!1)},teams:m,userRole:c,userModels:ei,allowAllUsers:!!c&&(0,T.isAdminRole)(c)})]})}],910119)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/0a55aff89c1ec2e4.js b/litellm/proxy/_experimental/out/_next/static/chunks/0a55aff89c1ec2e4.js deleted file mode 100644 index cbd60e721c7..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/0a55aff89c1ec2e4.js +++ /dev/null @@ -1,420 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,190272,785913,e=>{"use strict";var t,i,o=((t={}).AUDIO_SPEECH="audio_speech",t.AUDIO_TRANSCRIPTION="audio_transcription",t.IMAGE_GENERATION="image_generation",t.VIDEO_GENERATION="video_generation",t.CHAT="chat",t.RESPONSES="responses",t.IMAGE_EDITS="image_edits",t.ANTHROPIC_MESSAGES="anthropic_messages",t.EMBEDDING="embedding",t),r=((i={}).IMAGE="image",i.VIDEO="video",i.CHAT="chat",i.RESPONSES="responses",i.IMAGE_EDITS="image_edits",i.ANTHROPIC_MESSAGES="anthropic_messages",i.EMBEDDINGS="embeddings",i.SPEECH="speech",i.TRANSCRIPTION="transcription",i.A2A_AGENTS="a2a_agents",i.MCP="mcp",i.REALTIME="realtime",i);let a={image_generation:"image",video_generation:"video",chat:"chat",responses:"responses",image_edits:"image_edits",anthropic_messages:"anthropic_messages",audio_speech:"speech",audio_transcription:"transcription",embedding:"embeddings"};e.s(["EndpointType",()=>r,"getEndpointType",0,e=>{if(console.log("getEndpointType:",e),Object.values(o).includes(e)){let t=a[e];return console.log("endpointType:",t),t}return"chat"}],785913),e.s(["generateCodeSnippet",0,e=>{let t,{apiKeySource:i,accessToken:o,apiKey:a,inputMessage:n,chatHistory:s,selectedTags:l,selectedVectorStores:c,selectedGuardrails:d,selectedPolicies:u,selectedMCPServers:p,mcpServers:m,mcpServerToolRestrictions:g,selectedVoice:f,endpointType:h,selectedModel:_,selectedSdk:v,proxySettings:b}=e,x="session"===i?o:a,y=window.location.origin,w=b?.LITELLM_UI_API_DOC_BASE_URL;w&&w.trim()?y=w:b?.PROXY_BASE_URL&&(y=b.PROXY_BASE_URL);let S=n||"Your prompt here",j=S.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n"),k=s.filter(e=>!e.isImage).map(({role:e,content:t})=>({role:e,content:t})),C={};l.length>0&&(C.tags=l),c.length>0&&(C.vector_stores=c),d.length>0&&(C.guardrails=d),u.length>0&&(C.policies=u);let O=_||"your-model-name",N="azure"===v?`import openai - -client = openai.AzureOpenAI( - api_key="${x||"YOUR_LITELLM_API_KEY"}", - azure_endpoint="${y}", - api_version="2024-02-01" -)`:`import openai - -client = openai.OpenAI( - api_key="${x||"YOUR_LITELLM_API_KEY"}", - base_url="${y}" -)`;switch(h){case r.CHAT:{let e=Object.keys(C).length>0,i="";if(e){let e=JSON.stringify({metadata:C},null,2).split("\n").map(e=>" ".repeat(4)+e).join("\n").trim();i=`, - extra_body=${e}`}let o=k.length>0?k:[{role:"user",content:S}];t=` -import base64 - -# Helper function to encode images to base64 -def encode_image(image_path): - with open(image_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode('utf-8') - -# Example with text only -response = client.chat.completions.create( - model="${O}", - messages=${JSON.stringify(o,null,4)}${i} -) - -print(response) - -# Example with image or PDF (uncomment and provide file path to use) -# base64_file = encode_image("path/to/your/file.jpg") # or .pdf -# response_with_file = client.chat.completions.create( -# model="${O}", -# messages=[ -# { -# "role": "user", -# "content": [ -# { -# "type": "text", -# "text": "${j}" -# }, -# { -# "type": "image_url", -# "image_url": { -# "url": f"data:image/jpeg;base64,{base64_file}" # or data:application/pdf;base64,{base64_file} -# } -# } -# ] -# } -# ]${i} -# ) -# print(response_with_file) -`;break}case r.RESPONSES:{let e=Object.keys(C).length>0,i="";if(e){let e=JSON.stringify({metadata:C},null,2).split("\n").map(e=>" ".repeat(4)+e).join("\n").trim();i=`, - extra_body=${e}`}let o=k.length>0?k:[{role:"user",content:S}];t=` -import base64 - -# Helper function to encode images to base64 -def encode_image(image_path): - with open(image_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode('utf-8') - -# Example with text only -response = client.responses.create( - model="${O}", - input=${JSON.stringify(o,null,4)}${i} -) - -print(response.output_text) - -# Example with image or PDF (uncomment and provide file path to use) -# base64_file = encode_image("path/to/your/file.jpg") # or .pdf -# response_with_file = client.responses.create( -# model="${O}", -# input=[ -# { -# "role": "user", -# "content": [ -# {"type": "input_text", "text": "${j}"}, -# { -# "type": "input_image", -# "image_url": f"data:image/jpeg;base64,{base64_file}", # or data:application/pdf;base64,{base64_file} -# }, -# ], -# } -# ]${i} -# ) -# print(response_with_file.output_text) -`;break}case r.IMAGE:t="azure"===v?` -# NOTE: The Azure SDK does not have a direct equivalent to the multi-modal 'responses.create' method shown for OpenAI. -# This snippet uses 'client.images.generate' and will create a new image based on your prompt. -# It does not use the uploaded image, as 'client.images.generate' does not support image inputs in this context. -import os -import requests -import json -import time -from PIL import Image - -result = client.images.generate( - model="${O}", - prompt="${n}", - n=1 -) - -json_response = json.loads(result.model_dump_json()) - -# Set the directory for the stored image -image_dir = os.path.join(os.curdir, 'images') - -# If the directory doesn't exist, create it -if not os.path.isdir(image_dir): - os.mkdir(image_dir) - -# Initialize the image path -image_filename = f"generated_image_{int(time.time())}.png" -image_path = os.path.join(image_dir, image_filename) - -try: - # Retrieve the generated image - if json_response.get("data") && len(json_response["data"]) > 0 && json_response["data"][0].get("url"): - image_url = json_response["data"][0]["url"] - generated_image = requests.get(image_url).content - with open(image_path, "wb") as image_file: - image_file.write(generated_image) - - print(f"Image saved to {image_path}") - # Display the image - image = Image.open(image_path) - image.show() - else: - print("Could not find image URL in response.") - print("Full response:", json_response) -except Exception as e: - print(f"An error occurred: {e}") - print("Full response:", json_response) -`:` -import base64 -import os -import time -import json -from PIL import Image -import requests - -# Helper function to encode images to base64 -def encode_image(image_path): - with open(image_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode('utf-8') - -# Helper function to create a file (simplified for this example) -def create_file(image_path): - # In a real implementation, this would upload the file to OpenAI - # For this example, we'll just return a placeholder ID - return f"file_{os.path.basename(image_path).replace('.', '_')}" - -# The prompt entered by the user -prompt = "${j}" - -# Encode images to base64 -base64_image1 = encode_image("body-lotion.png") -base64_image2 = encode_image("soap.png") - -# Create file IDs -file_id1 = create_file("body-lotion.png") -file_id2 = create_file("incense-kit.png") - -response = client.responses.create( - model="${O}", - input=[ - { - "role": "user", - "content": [ - {"type": "input_text", "text": prompt}, - { - "type": "input_image", - "image_url": f"data:image/jpeg;base64,{base64_image1}", - }, - { - "type": "input_image", - "image_url": f"data:image/jpeg;base64,{base64_image2}", - }, - { - "type": "input_image", - "file_id": file_id1, - }, - { - "type": "input_image", - "file_id": file_id2, - } - ], - } - ], - tools=[{"type": "image_generation"}], -) - -# Process the response -image_generation_calls = [ - output - for output in response.output - if output.type == "image_generation_call" -] - -image_data = [output.result for output in image_generation_calls] - -if image_data: - image_base64 = image_data[0] - image_filename = f"edited_image_{int(time.time())}.png" - with open(image_filename, "wb") as f: - f.write(base64.b64decode(image_base64)) - print(f"Image saved to {image_filename}") -else: - # If no image is generated, there might be a text response with an explanation - text_response = [output.text for output in response.output if hasattr(output, 'text')] - if text_response: - print("No image generated. Model response:") - print("\\n".join(text_response)) - else: - print("No image data found in response.") - print("Full response for debugging:") - print(response) -`;break;case r.IMAGE_EDITS:t="azure"===v?` -import base64 -import os -import time -import json -from PIL import Image -import requests - -# Helper function to encode images to base64 -def encode_image(image_path): - with open(image_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode('utf-8') - -# The prompt entered by the user -prompt = "${j}" - -# Encode images to base64 -base64_image1 = encode_image("body-lotion.png") -base64_image2 = encode_image("soap.png") - -# Create file IDs -file_id1 = create_file("body-lotion.png") -file_id2 = create_file("incense-kit.png") - -response = client.responses.create( - model="${O}", - input=[ - { - "role": "user", - "content": [ - {"type": "input_text", "text": prompt}, - { - "type": "input_image", - "image_url": f"data:image/jpeg;base64,{base64_image1}", - }, - { - "type": "input_image", - "image_url": f"data:image/jpeg;base64,{base64_image2}", - }, - { - "type": "input_image", - "file_id": file_id1, - }, - { - "type": "input_image", - "file_id": file_id2, - } - ], - } - ], - tools=[{"type": "image_generation"}], -) - -# Process the response -image_generation_calls = [ - output - for output in response.output - if output.type == "image_generation_call" -] - -image_data = [output.result for output in image_generation_calls] - -if image_data: - image_base64 = image_data[0] - image_filename = f"edited_image_{int(time.time())}.png" - with open(image_filename, "wb") as f: - f.write(base64.b64decode(image_base64)) - print(f"Image saved to {image_filename}") -else: - # If no image is generated, there might be a text response with an explanation - text_response = [output.text for output in response.output if hasattr(output, 'text')] - if text_response: - print("No image generated. Model response:") - print("\\n".join(text_response)) - else: - print("No image data found in response.") - print("Full response for debugging:") - print(response) -`:` -import base64 -import os -import time - -# Helper function to encode images to base64 -def encode_image(image_path): - with open(image_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode('utf-8') - -# Helper function to create a file (simplified for this example) -def create_file(image_path): - # In a real implementation, this would upload the file to OpenAI - # For this example, we'll just return a placeholder ID - return f"file_{os.path.basename(image_path).replace('.', '_')}" - -# The prompt entered by the user -prompt = "${j}" - -# Encode images to base64 -base64_image1 = encode_image("body-lotion.png") -base64_image2 = encode_image("soap.png") - -# Create file IDs -file_id1 = create_file("body-lotion.png") -file_id2 = create_file("incense-kit.png") - -response = client.responses.create( - model="${O}", - input=[ - { - "role": "user", - "content": [ - {"type": "input_text", "text": prompt}, - { - "type": "input_image", - "image_url": f"data:image/jpeg;base64,{base64_image1}", - }, - { - "type": "input_image", - "image_url": f"data:image/jpeg;base64,{base64_image2}", - }, - { - "type": "input_image", - "file_id": file_id1, - }, - { - "type": "input_image", - "file_id": file_id2, - } - ], - } - ], - tools=[{"type": "image_generation"}], -) - -# Process the response -image_generation_calls = [ - output - for output in response.output - if output.type == "image_generation_call" -] - -image_data = [output.result for output in image_generation_calls] - -if image_data: - image_base64 = image_data[0] - image_filename = f"edited_image_{int(time.time())}.png" - with open(image_filename, "wb") as f: - f.write(base64.b64decode(image_base64)) - print(f"Image saved to {image_filename}") -else: - # If no image is generated, there might be a text response with an explanation - text_response = [output.text for output in response.output if hasattr(output, 'text')] - if text_response: - print("No image generated. Model response:") - print("\\n".join(text_response)) - else: - print("No image data found in response.") - print("Full response for debugging:") - print(response) -`;break;case r.EMBEDDINGS:t=` -response = client.embeddings.create( - input="${n||"Your string here"}", - model="${O}", - encoding_format="base64" # or "float" -) - -print(response.data[0].embedding) -`;break;case r.TRANSCRIPTION:t=` -# Open the audio file -audio_file = open("path/to/your/audio/file.mp3", "rb") - -# Make the transcription request -response = client.audio.transcriptions.create( - model="${O}", - file=audio_file${n?`, - prompt="${n.replace(/"/g,'\\"')}"`:""} -) - -print(response.text) -`;break;case r.SPEECH:t=` -# Make the text-to-speech request -response = client.audio.speech.create( - model="${O}", - input="${n||"Your text to convert to speech here"}", - voice="${f}" # Options: alloy, ash, ballad, coral, echo, fable, nova, onyx, sage, shimmer -) - -# Save the audio to a file -output_filename = "output_speech.mp3" -response.stream_to_file(output_filename) -print(f"Audio saved to {output_filename}") - -# Optional: Customize response format and speed -# response = client.audio.speech.create( -# model="${O}", -# input="${n||"Your text to convert to speech here"}", -# voice="alloy", -# response_format="mp3", # Options: mp3, opus, aac, flac, wav, pcm -# speed=1.0 # Range: 0.25 to 4.0 -# ) -# response.stream_to_file("output_speech.mp3") -`;break;default:t="\n# Code generation for this endpoint is not implemented yet."}return`${N} -${t}`}],190272)},516015,(e,t,i)=>{},898547,(e,t,i)=>{var o=e.i(247167);e.r(516015);var r=e.r(271645),a=r&&"object"==typeof r&&"default"in r?r:{default:r},n=void 0!==o.default&&o.default.env&&!0,s=function(e){return"[object String]"===Object.prototype.toString.call(e)},l=function(){function e(e){var t=void 0===e?{}:e,i=t.name,o=void 0===i?"stylesheet":i,r=t.optimizeForSpeed,a=void 0===r?n:r;c(s(o),"`name` must be a string"),this._name=o,this._deletedRulePlaceholder="#"+o+"-deleted-rule____{}",c("boolean"==typeof a,"`optimizeForSpeed` must be a boolean"),this._optimizeForSpeed=a,this._serverSheet=void 0,this._tags=[],this._injected=!1,this._rulesCount=0;var l="u">typeof window&&document.querySelector('meta[property="csp-nonce"]');this._nonce=l?l.getAttribute("content"):null}var t,i=e.prototype;return i.setOptimizeForSpeed=function(e){c("boolean"==typeof e,"`setOptimizeForSpeed` accepts a boolean"),c(0===this._rulesCount,"optimizeForSpeed cannot be when rules have already been inserted"),this.flush(),this._optimizeForSpeed=e,this.inject()},i.isOptimizeForSpeed=function(){return this._optimizeForSpeed},i.inject=function(){var e=this;if(c(!this._injected,"sheet already injected"),this._injected=!0,"u">typeof window&&this._optimizeForSpeed){this._tags[0]=this.makeStyleTag(this._name),this._optimizeForSpeed="insertRule"in this.getSheet(),this._optimizeForSpeed||(n||console.warn("StyleSheet: optimizeForSpeed mode not supported falling back to standard mode."),this.flush(),this._injected=!0);return}this._serverSheet={cssRules:[],insertRule:function(t,i){return"number"==typeof i?e._serverSheet.cssRules[i]={cssText:t}:e._serverSheet.cssRules.push({cssText:t}),i},deleteRule:function(t){e._serverSheet.cssRules[t]=null}}},i.getSheetForTag=function(e){if(e.sheet)return e.sheet;for(var t=0;ttypeof window?this.getSheet():this._serverSheet;if(t.trim()||(t=this._deletedRulePlaceholder),!i.cssRules[e])return e;i.deleteRule(e);try{i.insertRule(t,e)}catch(o){n||console.warn("StyleSheet: illegal rule: \n\n"+t+"\n\nSee https://stackoverflow.com/q/20007992 for more info"),i.insertRule(this._deletedRulePlaceholder,e)}}else{var o=this._tags[e];c(o,"old rule at index `"+e+"` not found"),o.textContent=t}return e},i.deleteRule=function(e){if("u"typeof window?(this._tags.forEach(function(e){return e&&e.parentNode.removeChild(e)}),this._tags=[]):this._serverSheet.cssRules=[]},i.cssRules=function(){var e=this;return"u">>0},u={};function p(e,t){if(!t)return"jsx-"+e;var i=String(t),o=e+i;return u[o]||(u[o]="jsx-"+d(e+"-"+i)),u[o]}function m(e,t){"u"typeof window&&!this._fromServer&&(this._fromServer=this.selectFromServer(),this._instancesCounts=Object.keys(this._fromServer).reduce(function(e,t){return e[t]=0,e},{}));var i=this.getIdAndRules(e),o=i.styleId,r=i.rules;if(o in this._instancesCounts){this._instancesCounts[o]+=1;return}var a=r.map(function(e){return t._sheet.insertRule(e)}).filter(function(e){return -1!==e});this._indices[o]=a,this._instancesCounts[o]=1},t.remove=function(e){var t=this,i=this.getIdAndRules(e).styleId;if(function(e,t){if(!e)throw Error("StyleSheetRegistry: "+t+".")}(i in this._instancesCounts,"styleId: `"+i+"` not found"),this._instancesCounts[i]-=1,this._instancesCounts[i]<1){var o=this._fromServer&&this._fromServer[i];o?(o.parentNode.removeChild(o),delete this._fromServer[i]):(this._indices[i].forEach(function(e){return t._sheet.deleteRule(e)}),delete this._indices[i]),delete this._instancesCounts[i]}},t.update=function(e,t){this.add(t),this.remove(e)},t.flush=function(){this._sheet.flush(),this._sheet.inject(),this._fromServer=void 0,this._indices={},this._instancesCounts={}},t.cssRules=function(){var e=this,t=this._fromServer?Object.keys(this._fromServer).map(function(t){return[t,e._fromServer[t]]}):[],i=this._sheet.cssRules();return t.concat(Object.keys(this._indices).map(function(t){return[t,e._indices[t].map(function(e){return i[e].cssText}).join(e._optimizeForSpeed?"":"\n")]}).filter(function(e){return!!e[1]}))},t.styles=function(e){var t,i;return t=this.cssRules(),void 0===(i=e)&&(i={}),t.map(function(e){var t=e[0],o=e[1];return a.default.createElement("style",{id:"__"+t,key:"__"+t,nonce:i.nonce?i.nonce:void 0,dangerouslySetInnerHTML:{__html:o}})})},t.getIdAndRules=function(e){var t=e.children,i=e.dynamic,o=e.id;if(i){var r=p(o,i);return{styleId:r,rules:Array.isArray(t)?t.map(function(e){return m(r,e)}):[m(r,t)]}}return{styleId:p(o),rules:Array.isArray(t)?t:[t]}},t.selectFromServer=function(){return Array.prototype.slice.call(document.querySelectorAll('[id^="__jsx-"]')).reduce(function(e,t){return e[t.id.slice(2)]=t,e},{})},e}(),f=r.createContext(null);function h(){return new g}function _(){return r.useContext(f)}f.displayName="StyleSheetContext";var v=a.default.useInsertionEffect||a.default.useLayoutEffect,b="u">typeof window?h():void 0;function x(e){var t=b||_();return t&&("u"{t.exports=e.r(898547).style},132104,e=>{"use strict";e.i(247167);var t=e.i(931067),i=e.i(271645);let o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M868 545.5L536.1 163a31.96 31.96 0 00-48.3 0L156 545.5a7.97 7.97 0 006 13.2h81c4.6 0 9-2 12.1-5.5L474 300.9V864c0 4.4 3.6 8 8 8h60c4.4 0 8-3.6 8-8V300.9l218.9 252.3c3 3.5 7.4 5.5 12.1 5.5h81c6.8 0 10.5-8 6-13.2z"}}]},name:"arrow-up",theme:"outlined"};var r=e.i(9583),a=i.forwardRef(function(e,a){return i.createElement(r.default,(0,t.default)({},e,{ref:a,icon:o}))});e.s(["ArrowUpOutlined",0,a],132104)},447593,989022,e=>{"use strict";e.i(247167);var t=e.i(931067),i=e.i(271645),o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"defs",attrs:{},children:[{tag:"style",attrs:{}}]},{tag:"path",attrs:{d:"M899.1 869.6l-53-305.6H864c14.4 0 26-11.6 26-26V346c0-14.4-11.6-26-26-26H618V138c0-14.4-11.6-26-26-26H432c-14.4 0-26 11.6-26 26v182H160c-14.4 0-26 11.6-26 26v192c0 14.4 11.6 26 26 26h17.9l-53 305.6a25.95 25.95 0 0025.6 30.4h723c1.5 0 3-.1 4.4-.4a25.88 25.88 0 0021.2-30zM204 390h272V182h72v208h272v104H204V390zm468 440V674c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v156H416V674c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v156H202.8l45.1-260H776l45.1 260H672z"}}]},name:"clear",theme:"outlined"},r=e.i(9583),a=i.forwardRef(function(e,a){return i.createElement(r.default,(0,t.default)({},e,{ref:a,icon:o}))});e.s(["ClearOutlined",0,a],447593);var n=e.i(843476),s=e.i(592968),l=e.i(637235);let c={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M872 394c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8H708V152c0-4.4-3.6-8-8-8h-64c-4.4 0-8 3.6-8 8v166H400V152c0-4.4-3.6-8-8-8h-64c-4.4 0-8 3.6-8 8v166H152c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h168v236H152c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h168v166c0 4.4 3.6 8 8 8h64c4.4 0 8-3.6 8-8V706h228v166c0 4.4 3.6 8 8 8h64c4.4 0 8-3.6 8-8V706h164c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8H708V394h164zM628 630H400V394h228v236z"}}]},name:"number",theme:"outlined"};var d=i.forwardRef(function(e,o){return i.createElement(r.default,(0,t.default)({},e,{ref:o,icon:c}))});let u={icon:{tag:"svg",attrs:{"fill-rule":"evenodd",viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M880 912H144c-17.7 0-32-14.3-32-32V144c0-17.7 14.3-32 32-32h360c4.4 0 8 3.6 8 8v56c0 4.4-3.6 8-8 8H184v656h656V520c0-4.4 3.6-8 8-8h56c4.4 0 8 3.6 8 8v360c0 17.7-14.3 32-32 32zM653.3 424.6l52.2 52.2a8.01 8.01 0 01-4.7 13.6l-179.4 21c-5.1.6-9.5-3.7-8.9-8.9l21-179.4c.8-6.6 8.9-9.4 13.6-4.7l52.4 52.4 256.2-256.2c3.1-3.1 8.2-3.1 11.3 0l42.4 42.4c3.1 3.1 3.1 8.2 0 11.3L653.3 424.6z"}}]},name:"import",theme:"outlined"};var p=i.forwardRef(function(e,o){return i.createElement(r.default,(0,t.default)({},e,{ref:o,icon:u}))}),m=e.i(872934),g=e.i(812618),f=e.i(366308),h=e.i(458505);e.s(["default",0,({timeToFirstToken:e,totalLatency:t,usage:i,toolName:o})=>e||t||i?(0,n.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!==e&&(0,n.jsx)(s.Tooltip,{title:"Time to first token",children:(0,n.jsxs)("div",{className:"flex items-center",children:[(0,n.jsx)(l.ClockCircleOutlined,{className:"mr-1"}),(0,n.jsxs)("span",{children:["TTFT: ",(e/1e3).toFixed(2),"s"]})]})}),void 0!==t&&(0,n.jsx)(s.Tooltip,{title:"Total latency",children:(0,n.jsxs)("div",{className:"flex items-center",children:[(0,n.jsx)(l.ClockCircleOutlined,{className:"mr-1"}),(0,n.jsxs)("span",{children:["Total Latency: ",(t/1e3).toFixed(2),"s"]})]})}),i?.promptTokens!==void 0&&(0,n.jsx)(s.Tooltip,{title:"Prompt tokens",children:(0,n.jsxs)("div",{className:"flex items-center",children:[(0,n.jsx)(p,{className:"mr-1"}),(0,n.jsxs)("span",{children:["In: ",i.promptTokens]})]})}),i?.completionTokens!==void 0&&(0,n.jsx)(s.Tooltip,{title:"Completion tokens",children:(0,n.jsxs)("div",{className:"flex items-center",children:[(0,n.jsx)(m.ExportOutlined,{className:"mr-1"}),(0,n.jsxs)("span",{children:["Out: ",i.completionTokens]})]})}),i?.reasoningTokens!==void 0&&(0,n.jsx)(s.Tooltip,{title:"Reasoning tokens",children:(0,n.jsxs)("div",{className:"flex items-center",children:[(0,n.jsx)(g.BulbOutlined,{className:"mr-1"}),(0,n.jsxs)("span",{children:["Reasoning: ",i.reasoningTokens]})]})}),i?.totalTokens!==void 0&&(0,n.jsx)(s.Tooltip,{title:"Total tokens",children:(0,n.jsxs)("div",{className:"flex items-center",children:[(0,n.jsx)(d,{className:"mr-1"}),(0,n.jsxs)("span",{children:["Total: ",i.totalTokens]})]})}),i?.cost!==void 0&&(0,n.jsx)(s.Tooltip,{title:"Cost",children:(0,n.jsxs)("div",{className:"flex items-center",children:[(0,n.jsx)(h.DollarOutlined,{className:"mr-1"}),(0,n.jsxs)("span",{children:["$",i.cost.toFixed(6)]})]})}),o&&(0,n.jsx)(s.Tooltip,{title:"Tool used",children:(0,n.jsxs)("div",{className:"flex items-center",children:[(0,n.jsx)(f.ToolOutlined,{className:"mr-1"}),(0,n.jsxs)("span",{children:["Tool: ",o]})]})})]}):null],989022)},254530,e=>{"use strict";var t=e.i(356449),i=e.i(764205);async function o(e,o,r,a,n,s,l,c,d,u,p,m,g,f,h,_,v,b,x,y,w,S,j,k){console.log=function(){},console.log("isLocal:",!1);let C=y||(0,i.getProxyBaseUrl)(),O={};n&&n.length>0&&(O["x-litellm-tags"]=n.join(","));let N=new t.default.OpenAI({apiKey:a,baseURL:C,dangerouslyAllowBrowser:!0,defaultHeaders:O});try{let t,i=Date.now(),a=!1,n={},y=!1,C=[];for await(let x of(f&&f.length>0&&(f.includes("__all__")?C.push({type:"mcp",server_label:"litellm",server_url:"litellm_proxy/mcp",require_approval:"never"}):f.forEach(e=>{let t=w?.find(t=>t.server_id===e),i=t?.alias||t?.server_name||e,o=S?.[e]||[];C.push({type:"mcp",server_label:"litellm",server_url:`litellm_proxy/mcp/${i}`,require_approval:"never",...o.length>0?{allowed_tools:o}:{}})})),await N.chat.completions.create({model:r,stream:!0,stream_options:{include_usage:!0},litellm_trace_id:u,messages:e,...p?{vector_store_ids:p}:{},...m?{guardrails:m}:{},...g?{policies:g}:{},...C.length>0?{tools:C,tool_choice:"auto"}:{},...void 0!==v?{temperature:v}:{},...void 0!==b?{max_tokens:b}:{},...k?{mock_testing_fallbacks:!0}:{}},{signal:s}))){console.log("Stream chunk:",x);let e=x.choices[0]?.delta;if(console.log("Delta content:",x.choices[0]?.delta?.content),console.log("Delta reasoning content:",e?.reasoning_content),!a&&(x.choices[0]?.delta?.content||e&&e.reasoning_content)&&(a=!0,t=Date.now()-i,console.log("First token received! Time:",t,"ms"),c?(console.log("Calling onTimingData with:",t),c(t)):console.log("onTimingData callback is not defined!")),x.choices[0]?.delta?.content){let e=x.choices[0].delta.content;o(e,x.model)}if(e&&e.image&&h&&(console.log("Image generated:",e.image),h(e.image.url,x.model)),e&&e.reasoning_content){let t=e.reasoning_content;l&&l(t)}if(e&&e.provider_specific_fields?.search_results&&_&&(console.log("Search results found:",e.provider_specific_fields.search_results),_(e.provider_specific_fields.search_results)),e&&e.provider_specific_fields){let t=e.provider_specific_fields;if(t.mcp_list_tools&&!n.mcp_list_tools&&(n.mcp_list_tools=t.mcp_list_tools,j&&!y)){y=!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=>({name:e.function?.name||e.name||"",description:e.function?.description||e.description||"",input_schema:e.function?.parameters||e.input_schema||{}}))},timestamp:Date.now()};j(e),console.log("MCP list_tools event sent:",e)}t.mcp_tool_calls&&(n.mcp_tool_calls=t.mcp_tool_calls),t.mcp_call_results&&(n.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(x.usage&&d){console.log("Usage data found:",x.usage);let e={completionTokens:x.usage.completion_tokens,promptTokens:x.usage.prompt_tokens,totalTokens:x.usage.total_tokens};x.usage.completion_tokens_details?.reasoning_tokens&&(e.reasoningTokens=x.usage.completion_tokens_details.reasoning_tokens),void 0!==x.usage.cost&&null!==x.usage.cost&&(e.cost=parseFloat(x.usage.cost)),d(e)}}j&&(n.mcp_tool_calls||n.mcp_call_results)&&n.mcp_tool_calls&&n.mcp_tool_calls.length>0&&n.mcp_tool_calls.forEach((e,t)=>{let i=e.function?.name||e.name||"",o=e.function?.arguments||e.arguments||"{}",r=n.mcp_call_results?.find(t=>t.tool_call_id===e.id||t.tool_call_id===e.call_id)||n.mcp_call_results?.[t],a={type:"response.output_item.done",item:{type:"mcp_call",name:i,arguments:"string"==typeof o?o:JSON.stringify(o),output:r?.result?"string"==typeof r.result?r.result:JSON.stringify(r.result):void 0},item_id:e.id||e.call_id,timestamp:Date.now()};j(a),console.log("MCP call event sent:",a)});let O=Date.now();x&&x(O-i)}catch(e){throw s?.aborted&&console.log("Chat completion request was cancelled"),e}}e.s(["makeOpenAIChatCompletionRequest",()=>o])},966988,e=>{"use strict";var t=e.i(843476),i=e.i(271645),o=e.i(464571),r=e.i(918789),a=e.i(650056),n=e.i(219470),s=e.i(755151),l=e.i(240647),c=e.i(812618);e.s(["default",0,({reasoningContent:e})=>{let[d,u]=(0,i.useState)(!0);return e?(0,t.jsxs)("div",{className:"reasoning-content mt-1 mb-2",children:[(0,t.jsxs)(o.Button,{type:"text",className:"flex items-center text-xs text-gray-500 hover:text-gray-700",onClick:()=>u(!d),icon:(0,t.jsx)(c.BulbOutlined,{}),children:[d?"Hide reasoning":"Show reasoning",d?(0,t.jsx)(s.DownOutlined,{className:"ml-1"}):(0,t.jsx)(l.RightOutlined,{className:"ml-1"})]}),d&&(0,t.jsx)("div",{className:"mt-2 p-3 bg-gray-50 border border-gray-200 rounded-md text-sm text-gray-700",children:(0,t.jsx)(r.default,{components:{code({node:e,inline:i,className:o,children:r,...s}){let l=/language-(\w+)/.exec(o||"");return!i&&l?(0,t.jsx)(a.Prism,{style:n.coy,language:l[1],PreTag:"div",className:"rounded-md my-2",...s,children:String(r).replace(/\n$/,"")}):(0,t.jsx)("code",{className:`${o} px-1.5 py-0.5 rounded bg-gray-100 text-sm font-mono`,...s,children:r})}},children:e})})]}):null}])},362024,e=>{"use strict";var t=e.i(988122);e.s(["Collapse",()=>t.default])},166406,e=>{"use strict";var t=e.i(190144);e.s(["CopyOutlined",()=>t.default])},240647,e=>{"use strict";var t=e.i(286612);e.s(["RightOutlined",()=>t.default])},829672,836938,310730,e=>{"use strict";e.i(247167);var t=e.i(271645),i=e.i(343794),o=e.i(914949),r=e.i(404948);let a=e=>e?"function"==typeof e?e():e:null;e.s(["getRenderPropValue",0,a],836938);var n=e.i(613541),s=e.i(763731),l=e.i(242064),c=e.i(491816);e.i(793154);var d=e.i(880476),u=e.i(183293),p=e.i(717356),m=e.i(320560),g=e.i(307358),f=e.i(246422),h=e.i(838378),_=e.i(617933);let v=(0,f.genStyleHooks)("Popover",e=>{let{colorBgElevated:t,colorText:i}=e,o=(0,h.mergeToken)(e,{popoverBg:t,popoverColor:i});return[(e=>{let{componentCls:t,popoverColor:i,titleMinWidth:o,fontWeightStrong:r,innerPadding:a,boxShadowSecondary:n,colorTextHeading:s,borderRadiusLG:l,zIndexPopup:c,titleMarginBottom:d,colorBgElevated:p,popoverBg:g,titleBorderBottom:f,innerContentPadding:h,titlePadding:_}=e;return[{[t]:Object.assign(Object.assign({},(0,u.resetComponent)(e)),{position:"absolute",top:0,left:{_skip_check_:!0,value:0},zIndex:c,fontWeight:"normal",whiteSpace:"normal",textAlign:"start",cursor:"auto",userSelect:"text","--valid-offset-x":"var(--arrow-offset-horizontal, var(--arrow-x))",transformOrigin:"var(--valid-offset-x, 50%) var(--arrow-y, 50%)","--antd-arrow-background-color":p,width:"max-content",maxWidth:"100vw","&-rtl":{direction:"rtl"},"&-hidden":{display:"none"},[`${t}-content`]:{position:"relative"},[`${t}-inner`]:{backgroundColor:g,backgroundClip:"padding-box",borderRadius:l,boxShadow:n,padding:a},[`${t}-title`]:{minWidth:o,marginBottom:d,color:s,fontWeight:r,borderBottom:f,padding:_},[`${t}-inner-content`]:{color:i,padding:h}})},(0,m.default)(e,"var(--antd-arrow-background-color)"),{[`${t}-pure`]:{position:"relative",maxWidth:"none",margin:e.sizePopupArrow,display:"inline-block",[`${t}-content`]:{display:"inline-block"}}}]})(o),(e=>{let{componentCls:t}=e;return{[t]:_.PresetColors.map(i=>{let o=e[`${i}6`];return{[`&${t}-${i}`]:{"--antd-arrow-background-color":o,[`${t}-inner`]:{backgroundColor:o},[`${t}-arrow`]:{background:"transparent"}}}})}})(o),(0,p.initZoomMotion)(o,"zoom-big")]},e=>{let{lineWidth:t,controlHeight:i,fontHeight:o,padding:r,wireframe:a,zIndexPopupBase:n,borderRadiusLG:s,marginXS:l,lineType:c,colorSplit:d,paddingSM:u}=e,p=i-o;return Object.assign(Object.assign(Object.assign({titleMinWidth:177,zIndexPopup:n+30},(0,g.getArrowToken)(e)),(0,m.getArrowOffsetToken)({contentRadius:s,limitVerticalRadius:!0})),{innerPadding:12*!a,titleMarginBottom:a?0:l,titlePadding:a?`${p/2}px ${r}px ${p/2-t}px`:0,titleBorderBottom:a?`${t}px ${c} ${d}`:"none",innerContentPadding:a?`${u}px ${r}px`:0})},{resetStyle:!1,deprecatedTokens:[["width","titleMinWidth"],["minWidth","titleMinWidth"]]});var b=function(e,t){var i={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&0>t.indexOf(o)&&(i[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,o=Object.getOwnPropertySymbols(e);rt.indexOf(o[r])&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(i[o[r]]=e[o[r]]);return i};let x=({title:e,content:i,prefixCls:o})=>e||i?t.createElement(t.Fragment,null,e&&t.createElement("div",{className:`${o}-title`},e),i&&t.createElement("div",{className:`${o}-inner-content`},i)):null,y=e=>{let{hashId:o,prefixCls:r,className:n,style:s,placement:l="top",title:c,content:u,children:p}=e,m=a(c),g=a(u),f=(0,i.default)(o,r,`${r}-pure`,`${r}-placement-${l}`,n);return t.createElement("div",{className:f,style:s},t.createElement("div",{className:`${r}-arrow`}),t.createElement(d.Popup,Object.assign({},e,{className:o,prefixCls:r}),p||t.createElement(x,{prefixCls:r,title:m,content:g})))},w=e=>{let{prefixCls:o,className:r}=e,a=b(e,["prefixCls","className"]),{getPrefixCls:n}=t.useContext(l.ConfigContext),s=n("popover",o),[c,d,u]=v(s);return c(t.createElement(y,Object.assign({},a,{prefixCls:s,hashId:d,className:(0,i.default)(r,u)})))};e.s(["Overlay",0,x,"default",0,w],310730);var S=function(e,t){var i={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&0>t.indexOf(o)&&(i[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,o=Object.getOwnPropertySymbols(e);rt.indexOf(o[r])&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(i[o[r]]=e[o[r]]);return i};let j=t.forwardRef((e,d)=>{var u,p;let{prefixCls:m,title:g,content:f,overlayClassName:h,placement:_="top",trigger:b="hover",children:y,mouseEnterDelay:w=.1,mouseLeaveDelay:j=.1,onOpenChange:k,overlayStyle:C={},styles:O,classNames:N}=e,z=S(e,["prefixCls","title","content","overlayClassName","placement","trigger","children","mouseEnterDelay","mouseLeaveDelay","onOpenChange","overlayStyle","styles","classNames"]),{getPrefixCls:E,className:T,style:R,classNames:I,styles:M}=(0,l.useComponentConfig)("popover"),A=E("popover",m),[$,L,P]=v(A),H=E(),B=(0,i.default)(h,L,P,T,I.root,null==N?void 0:N.root),F=(0,i.default)(I.body,null==N?void 0:N.body),[V,D]=(0,o.default)(!1,{value:null!=(u=e.open)?u:e.visible,defaultValue:null!=(p=e.defaultOpen)?p:e.defaultVisible}),W=(e,t)=>{D(e,!0),null==k||k(e,t)},U=a(g),q=a(f);return $(t.createElement(c.default,Object.assign({placement:_,trigger:b,mouseEnterDelay:w,mouseLeaveDelay:j},z,{prefixCls:A,classNames:{root:B,body:F},styles:{root:Object.assign(Object.assign(Object.assign(Object.assign({},M.root),R),C),null==O?void 0:O.root),body:Object.assign(Object.assign({},M.body),null==O?void 0:O.body)},ref:d,open:V,onOpenChange:e=>{W(e)},overlay:U||q?t.createElement(x,{prefixCls:A,title:U,content:q}):null,transitionName:(0,n.getTransitionName)(H,"zoom-big",z.transitionName),"data-popover-inject":!0}),(0,s.cloneElement)(y,{onKeyDown:e=>{var i,o;(0,t.isValidElement)(y)&&(null==(o=null==y?void 0:(i=y.props).onKeyDown)||o.call(i,e)),e.keyCode===r.default.ESC&&W(!1,e)}})))});j._InternalPanelDoNotUseOrYouWillBeFired=w,e.s(["default",0,j],829672)},282786,e=>{"use strict";var t=e.i(829672);e.s(["Popover",()=>t.default])},219470,812618,e=>{"use strict";e.s(["coy",0,{'code[class*="language-"]':{color:"black",background:"none",fontFamily:"Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace",fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",maxHeight:"inherit",height:"inherit",padding:"0 1em",display:"block",overflow:"auto"},'pre[class*="language-"]':{color:"black",background:"none",fontFamily:"Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace",fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",position:"relative",margin:".5em 0",overflow:"visible",padding:"1px",backgroundColor:"#fdfdfd",WebkitBoxSizing:"border-box",MozBoxSizing:"border-box",boxSizing:"border-box",marginBottom:"1em"},'pre[class*="language-"] > code':{position:"relative",zIndex:"1",borderLeft:"10px solid #358ccb",boxShadow:"-1px 0px 0px 0px #358ccb, 0px 0px 0px 1px #dfdfdf",backgroundColor:"#fdfdfd",backgroundImage:"linear-gradient(transparent 50%, rgba(69, 142, 209, 0.04) 50%)",backgroundSize:"3em 3em",backgroundOrigin:"content-box",backgroundAttachment:"local"},':not(pre) > code[class*="language-"]':{backgroundColor:"#fdfdfd",WebkitBoxSizing:"border-box",MozBoxSizing:"border-box",boxSizing:"border-box",marginBottom:"1em",position:"relative",padding:".2em",borderRadius:"0.3em",color:"#c92c2c",border:"1px solid rgba(0, 0, 0, 0.1)",display:"inline",whiteSpace:"normal"},'pre[class*="language-"]:before':{content:"''",display:"block",position:"absolute",bottom:"0.75em",left:"0.18em",width:"40%",height:"20%",maxHeight:"13em",boxShadow:"0px 13px 8px #979797",WebkitTransform:"rotate(-2deg)",MozTransform:"rotate(-2deg)",msTransform:"rotate(-2deg)",OTransform:"rotate(-2deg)",transform:"rotate(-2deg)"},'pre[class*="language-"]:after':{content:"''",display:"block",position:"absolute",bottom:"0.75em",left:"auto",width:"40%",height:"20%",maxHeight:"13em",boxShadow:"0px 13px 8px #979797",WebkitTransform:"rotate(2deg)",MozTransform:"rotate(2deg)",msTransform:"rotate(2deg)",OTransform:"rotate(2deg)",transform:"rotate(2deg)",right:"0.75em"},comment:{color:"#7D8B99"},"block-comment":{color:"#7D8B99"},prolog:{color:"#7D8B99"},doctype:{color:"#7D8B99"},cdata:{color:"#7D8B99"},punctuation:{color:"#5F6364"},property:{color:"#c92c2c"},tag:{color:"#c92c2c"},boolean:{color:"#c92c2c"},number:{color:"#c92c2c"},"function-name":{color:"#c92c2c"},constant:{color:"#c92c2c"},symbol:{color:"#c92c2c"},deleted:{color:"#c92c2c"},selector:{color:"#2f9c0a"},"attr-name":{color:"#2f9c0a"},string:{color:"#2f9c0a"},char:{color:"#2f9c0a"},function:{color:"#2f9c0a"},builtin:{color:"#2f9c0a"},inserted:{color:"#2f9c0a"},operator:{color:"#a67f59",background:"rgba(255, 255, 255, 0.5)"},entity:{color:"#a67f59",background:"rgba(255, 255, 255, 0.5)",cursor:"help"},url:{color:"#a67f59",background:"rgba(255, 255, 255, 0.5)"},variable:{color:"#a67f59",background:"rgba(255, 255, 255, 0.5)"},atrule:{color:"#1990b8"},"attr-value":{color:"#1990b8"},keyword:{color:"#1990b8"},"class-name":{color:"#1990b8"},regex:{color:"#e90"},important:{color:"#e90",fontWeight:"normal"},".language-css .token.string":{color:"#a67f59",background:"rgba(255, 255, 255, 0.5)"},".style .token.string":{color:"#a67f59",background:"rgba(255, 255, 255, 0.5)"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},namespace:{Opacity:".7"},'pre[class*="language-"].line-numbers.line-numbers':{paddingLeft:"0"},'pre[class*="language-"].line-numbers.line-numbers code':{paddingLeft:"3.8em"},'pre[class*="language-"].line-numbers.line-numbers .line-numbers-rows':{left:"0"},'pre[class*="language-"][data-line]':{paddingTop:"0",paddingBottom:"0",paddingLeft:"0"},"pre[data-line] code":{position:"relative",paddingLeft:"4em"},"pre .line-highlight":{marginTop:"0"}}],219470),e.i(247167);var t=e.i(931067),i=e.i(271645);let o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M632 888H392c-4.4 0-8 3.6-8 8v32c0 17.7 14.3 32 32 32h192c17.7 0 32-14.3 32-32v-32c0-4.4-3.6-8-8-8zM512 64c-181.1 0-328 146.9-328 328 0 121.4 66 227.4 164 284.1V792c0 17.7 14.3 32 32 32h264c17.7 0 32-14.3 32-32V676.1c98-56.7 164-162.7 164-284.1 0-181.1-146.9-328-328-328zm127.9 549.8L604 634.6V752H420V634.6l-35.9-20.8C305.4 568.3 256 484.5 256 392c0-141.4 114.6-256 256-256s256 114.6 256 256c0 92.5-49.4 176.3-128.1 221.8z"}}]},name:"bulb",theme:"outlined"};var r=e.i(9583),a=i.forwardRef(function(e,a){return i.createElement(r.default,(0,t.default)({},e,{ref:a,icon:o}))});e.s(["BulbOutlined",0,a],812618)},84899,e=>{"use strict";e.i(247167);var t=e.i(931067),i=e.i(271645),o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"defs",attrs:{},children:[{tag:"style",attrs:{}}]},{tag:"path",attrs:{d:"M931.4 498.9L94.9 79.5c-3.4-1.7-7.3-2.1-11-1.2a15.99 15.99 0 00-11.7 19.3l86.2 352.2c1.3 5.3 5.2 9.6 10.4 11.3l147.7 50.7-147.6 50.7c-5.2 1.8-9.1 6-10.3 11.3L72.2 926.5c-.9 3.7-.5 7.6 1.2 10.9 3.9 7.9 13.5 11.1 21.5 7.2l836.5-417c3.1-1.5 5.6-4.1 7.2-7.1 3.9-8 .7-17.6-7.2-21.6zM170.8 826.3l50.3-205.6 295.2-101.3c2.3-.8 4.2-2.6 5-5 1.4-4.2-.8-8.7-5-10.2L221.1 403 171 198.2l628 314.9-628.2 313.2z"}}]},name:"send",theme:"outlined"},r=e.i(9583),a=i.forwardRef(function(e,a){return i.createElement(r.default,(0,t.default)({},e,{ref:a,icon:o}))});e.s(["SendOutlined",0,a],84899)},872934,e=>{"use strict";e.i(247167);var t=e.i(931067),i=e.i(271645);let o={icon:{tag:"svg",attrs:{"fill-rule":"evenodd",viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M880 912H144c-17.7 0-32-14.3-32-32V144c0-17.7 14.3-32 32-32h360c4.4 0 8 3.6 8 8v56c0 4.4-3.6 8-8 8H184v656h656V520c0-4.4 3.6-8 8-8h56c4.4 0 8 3.6 8 8v360c0 17.7-14.3 32-32 32zM770.87 199.13l-52.2-52.2a8.01 8.01 0 014.7-13.6l179.4-21c5.1-.6 9.5 3.7 8.9 8.9l-21 179.4c-.8 6.6-8.9 9.4-13.6 4.7l-52.4-52.4-256.2 256.2a8.03 8.03 0 01-11.3 0l-42.4-42.4a8.03 8.03 0 010-11.3l256.1-256.3z"}}]},name:"export",theme:"outlined"};var r=e.i(9583),a=i.forwardRef(function(e,a){return i.createElement(r.default,(0,t.default)({},e,{ref:a,icon:o}))});e.s(["ExportOutlined",0,a],872934)},518617,e=>{"use strict";e.i(247167);var t=e.i(931067),i=e.i(271645);let o={icon:{tag:"svg",attrs:{"fill-rule":"evenodd",viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M512 64c247.4 0 448 200.6 448 448S759.4 960 512 960 64 759.4 64 512 264.6 64 512 64zm0 76c-205.4 0-372 166.6-372 372s166.6 372 372 372 372-166.6 372-372-166.6-372-372-372zm128.01 198.83c.03 0 .05.01.09.06l45.02 45.01a.2.2 0 01.05.09.12.12 0 010 .07c0 .02-.01.04-.05.08L557.25 512l127.87 127.86a.27.27 0 01.05.06v.02a.12.12 0 010 .07c0 .03-.01.05-.05.09l-45.02 45.02a.2.2 0 01-.09.05.12.12 0 01-.07 0c-.02 0-.04-.01-.08-.05L512 557.25 384.14 685.12c-.04.04-.06.05-.08.05a.12.12 0 01-.07 0c-.03 0-.05-.01-.09-.05l-45.02-45.02a.2.2 0 01-.05-.09.12.12 0 010-.07c0-.02.01-.04.06-.08L466.75 512 338.88 384.14a.27.27 0 01-.05-.06l-.01-.02a.12.12 0 010-.07c0-.03.01-.05.05-.09l45.02-45.02a.2.2 0 01.09-.05.12.12 0 01.07 0c.02 0 .04.01.08.06L512 466.75l127.86-127.86c.04-.05.06-.06.08-.06a.12.12 0 01.07 0z"}}]},name:"close-circle",theme:"outlined"};var r=e.i(9583),a=i.forwardRef(function(e,a){return i.createElement(r.default,(0,t.default)({},e,{ref:a,icon:o}))});e.s(["CloseCircleOutlined",0,a],518617)},891547,e=>{"use strict";var t=e.i(843476),i=e.i(271645),o=e.i(199133),r=e.i(764205);e.s(["default",0,({onChange:e,value:a,className:n,accessToken:s,disabled:l})=>{let[c,d]=(0,i.useState)([]),[u,p]=(0,i.useState)(!1);return(0,i.useEffect)(()=>{(async()=>{if(s){p(!0);try{let e=await (0,r.getGuardrailsList)(s);console.log("Guardrails response:",e),e.guardrails&&(console.log("Guardrails data:",e.guardrails),d(e.guardrails))}catch(e){console.error("Error fetching guardrails:",e)}finally{p(!1)}}})()},[s]),(0,t.jsx)("div",{children:(0,t.jsx)(o.Select,{mode:"multiple",disabled:l,placeholder:l?"Setting guardrails is a premium feature.":"Select guardrails",onChange:t=>{console.log("Selected guardrails:",t),e(t)},value:a,loading:u,className:n,allowClear:!0,options:c.map(e=>(console.log("Mapping guardrail:",e),{label:`${e.guardrail_name}`,value:e.guardrail_name})),optionFilterProp:"label",showSearch:!0,style:{width:"100%"}})})}])},921511,e=>{"use strict";var t=e.i(843476),i=e.i(271645),o=e.i(199133),r=e.i(764205);function a(e){return e.filter(e=>(e.version_status??"draft")!=="draft").map(e=>{var t;let i=e.version_number??1,o=e.version_status??"draft";return{label:`${e.policy_name} — v${i} (${o})${e.description?` — ${e.description}`:""}`,value:"production"===o?e.policy_name:e.policy_id?(t=e.policy_id,`policy_${t}`):e.policy_name}})}e.s(["default",0,({onChange:e,value:n,className:s,accessToken:l,disabled:c,onPoliciesLoaded:d})=>{let[u,p]=(0,i.useState)([]),[m,g]=(0,i.useState)(!1);return(0,i.useEffect)(()=>{(async()=>{if(l){g(!0);try{let e=await (0,r.getPoliciesList)(l);e.policies&&(p(e.policies),d?.(e.policies))}catch(e){console.error("Error fetching policies:",e)}finally{g(!1)}}})()},[l,d]),(0,t.jsx)("div",{children:(0,t.jsx)(o.Select,{mode:"multiple",disabled:c,placeholder:c?"Setting policies is a premium feature.":"Select policies (production or published versions)",onChange:t=>{e(t)},value:n,loading:m,className:s,allowClear:!0,options:a(u),optionFilterProp:"label",showSearch:!0,style:{width:"100%"}})})},"getPolicyOptionEntries",()=>a])},916940,e=>{"use strict";var t=e.i(843476),i=e.i(271645),o=e.i(199133),r=e.i(764205);e.s(["default",0,({onChange:e,value:a,className:n,accessToken:s,placeholder:l="Select vector stores",disabled:c=!1})=>{let[d,u]=(0,i.useState)([]),[p,m]=(0,i.useState)(!1);return(0,i.useEffect)(()=>{(async()=>{if(s){m(!0);try{let e=await (0,r.vectorStoreListCall)(s);e.data&&u(e.data)}catch(e){console.error("Error fetching vector stores:",e)}finally{m(!1)}}})()},[s]),(0,t.jsx)("div",{children:(0,t.jsx)(o.Select,{mode:"multiple",placeholder:l,onChange:e,value:a,loading:p,className:n,allowClear:!0,options:d.map(e=>({label:`${e.vector_store_name||e.vector_store_id} (${e.vector_store_id})`,value:e.vector_store_id,title:e.vector_store_description||e.vector_store_id})),optionFilterProp:"label",showSearch:!0,style:{width:"100%"},disabled:c})})}])},689020,e=>{"use strict";var t=e.i(764205);let i=async e=>{try{let i=await (0,t.modelHubCall)(e);if(console.log("model_info:",i),i?.data.length>0){let e=i.data.map(e=>({model_group:e.model_group,mode:e?.mode}));return e.sort((e,t)=>e.model_group.localeCompare(t.model_group)),e}return[]}catch(e){throw console.error("Error fetching model info:",e),e}};e.s(["fetchAvailableModels",0,i])},983561,e=>{"use strict";e.i(247167);var t=e.i(931067),i=e.i(271645);let o={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"};var r=e.i(9583),a=i.forwardRef(function(e,a){return i.createElement(r.default,(0,t.default)({},e,{ref:a,icon:o}))});e.s(["RobotOutlined",0,a],983561)},737434,e=>{"use strict";var t=e.i(184163);e.s(["DownloadOutlined",()=>t.default])},447566,e=>{"use strict";e.i(247167);var t=e.i(931067),i=e.i(271645);let o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M872 474H286.9l350.2-304c5.6-4.9 2.2-14-5.2-14h-88.5c-3.9 0-7.6 1.4-10.5 3.9L155 487.8a31.96 31.96 0 000 48.3L535.1 866c1.5 1.3 3.3 2 5.2 2h91.5c7.4 0 10.8-9.2 5.2-14L286.9 550H872c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8z"}}]},name:"arrow-left",theme:"outlined"};var r=e.i(9583),a=i.forwardRef(function(e,a){return i.createElement(r.default,(0,t.default)({},e,{ref:a,icon:o}))});e.s(["ArrowLeftOutlined",0,a],447566)},637235,e=>{"use strict";e.i(247167);var t=e.i(931067),i=e.i(271645);let o={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 372z"}},{tag:"path",attrs:{d:"M686.7 638.6L544.1 535.5V288c0-4.4-3.6-8-8-8H488c-4.4 0-8 3.6-8 8v275.4c0 2.6 1.2 5 3.3 6.5l165.4 120.6c3.6 2.6 8.6 1.8 11.2-1.7l28.6-39c2.6-3.7 1.8-8.7-1.8-11.2z"}}]},name:"clock-circle",theme:"outlined"};var r=e.i(9583),a=i.forwardRef(function(e,a){return i.createElement(r.default,(0,t.default)({},e,{ref:a,icon:o}))});e.s(["ClockCircleOutlined",0,a],637235)},782273,793916,e=>{"use strict";e.i(247167);var t=e.i(931067),i=e.i(271645);let o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M625.9 115c-5.9 0-11.9 1.6-17.4 5.3L254 352H90c-8.8 0-16 7.2-16 16v288c0 8.8 7.2 16 16 16h164l354.5 231.7c5.5 3.6 11.6 5.3 17.4 5.3 16.7 0 32.1-13.3 32.1-32.1V147.1c0-18.8-15.4-32.1-32.1-32.1zM586 803L293.4 611.7l-18-11.7H146V424h129.4l17.9-11.7L586 221v582zm348-327H806c-8.8 0-16 7.2-16 16v40c0 8.8 7.2 16 16 16h128c8.8 0 16-7.2 16-16v-40c0-8.8-7.2-16-16-16zm-41.9 261.8l-110.3-63.7a15.9 15.9 0 00-21.7 5.9l-19.9 34.5c-4.4 7.6-1.8 17.4 5.8 21.8L856.3 800a15.9 15.9 0 0021.7-5.9l19.9-34.5c4.4-7.6 1.7-17.4-5.8-21.8zM760 344a15.9 15.9 0 0021.7 5.9L892 286.2c7.6-4.4 10.2-14.2 5.8-21.8L878 230a15.9 15.9 0 00-21.7-5.9L746 287.8a15.99 15.99 0 00-5.8 21.8L760 344z"}}]},name:"sound",theme:"outlined"};var r=e.i(9583),a=i.forwardRef(function(e,a){return i.createElement(r.default,(0,t.default)({},e,{ref:a,icon:o}))});e.s(["SoundOutlined",0,a],782273);let n={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M842 454c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8 0 140.3-113.7 254-254 254S258 594.3 258 454c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8 0 168.7 126.6 307.9 290 327.6V884H326.7c-13.7 0-24.7 14.3-24.7 32v36c0 4.4 2.8 8 6.2 8h407.6c3.4 0 6.2-3.6 6.2-8v-36c0-17.7-11-32-24.7-32H548V782.1c165.3-18 294-158 294-328.1zM512 624c93.9 0 170-75.2 170-168V232c0-92.8-76.1-168-170-168s-170 75.2-170 168v224c0 92.8 76.1 168 170 168zm-94-392c0-50.6 41.9-92 94-92s94 41.4 94 92v224c0 50.6-41.9 92-94 92s-94-41.4-94-92V232z"}}]},name:"audio",theme:"outlined"};var s=i.forwardRef(function(e,o){return i.createElement(r.default,(0,t.default)({},e,{ref:o,icon:n}))});e.s(["AudioOutlined",0,s],793916)},149192,e=>{"use strict";var t=e.i(864517);e.s(["CloseOutlined",()=>t.default])},492030,e=>{"use strict";var t=e.i(121229);e.s(["CheckOutlined",()=>t.default])},596239,e=>{"use strict";e.i(247167);var t=e.i(931067),i=e.i(271645);let o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M574 665.4a8.03 8.03 0 00-11.3 0L446.5 781.6c-53.8 53.8-144.6 59.5-204 0-59.5-59.5-53.8-150.2 0-204l116.2-116.2c3.1-3.1 3.1-8.2 0-11.3l-39.8-39.8a8.03 8.03 0 00-11.3 0L191.4 526.5c-84.6 84.6-84.6 221.5 0 306s221.5 84.6 306 0l116.2-116.2c3.1-3.1 3.1-8.2 0-11.3L574 665.4zm258.6-474c-84.6-84.6-221.5-84.6-306 0L410.3 307.6a8.03 8.03 0 000 11.3l39.7 39.7c3.1 3.1 8.2 3.1 11.3 0l116.2-116.2c53.8-53.8 144.6-59.5 204 0 59.5 59.5 53.8 150.2 0 204L665.3 562.6a8.03 8.03 0 000 11.3l39.8 39.8c3.1 3.1 8.2 3.1 11.3 0l116.2-116.2c84.5-84.6 84.5-221.5 0-306.1zM610.1 372.3a8.03 8.03 0 00-11.3 0L372.3 598.7a8.03 8.03 0 000 11.3l39.6 39.6c3.1 3.1 8.2 3.1 11.3 0l226.4-226.4c3.1-3.1 3.1-8.2 0-11.3l-39.5-39.6z"}}]},name:"link",theme:"outlined"};var r=e.i(9583),a=i.forwardRef(function(e,a){return i.createElement(r.default,(0,t.default)({},e,{ref:a,icon:o}))});e.s(["LinkOutlined",0,a],596239)},458505,e=>{"use strict";e.i(247167);var t=e.i(931067),i=e.i(271645);let o={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"};var r=e.i(9583),a=i.forwardRef(function(e,a){return i.createElement(r.default,(0,t.default)({},e,{ref:a,icon:o}))});e.s(["DollarOutlined",0,a],458505)},245704,e=>{"use strict";e.i(247167);var t=e.i(931067),i=e.i(271645);let o={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"};var r=e.i(9583),a=i.forwardRef(function(e,a){return i.createElement(r.default,(0,t.default)({},e,{ref:a,icon:o}))});e.s(["CheckCircleOutlined",0,a],245704)},245094,e=>{"use strict";e.i(247167);var t=e.i(931067),i=e.i(271645);let o={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M516 673c0 4.4 3.4 8 7.5 8h185c4.1 0 7.5-3.6 7.5-8v-48c0-4.4-3.4-8-7.5-8h-185c-4.1 0-7.5 3.6-7.5 8v48zm-194.9 6.1l192-161c3.8-3.2 3.8-9.1 0-12.3l-192-160.9A7.95 7.95 0 00308 351v62.7c0 2.4 1 4.6 2.9 6.1L420.7 512l-109.8 92.2a8.1 8.1 0 00-2.9 6.1V673c0 6.8 7.9 10.5 13.1 6.1zM880 112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32zm-40 728H184V184h656v656z"}}]},name:"code",theme:"outlined"};var r=e.i(9583),a=i.forwardRef(function(e,a){return i.createElement(r.default,(0,t.default)({},e,{ref:a,icon:o}))});e.s(["CodeOutlined",0,a],245094)},611052,e=>{"use strict";var t=e.i(843476),i=e.i(271645),o=e.i(212931),r=e.i(311451),a=e.i(790848),n=e.i(998573),s=e.i(438957);e.i(247167);var l=e.i(931067);let c={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M832 464h-68V240c0-70.7-57.3-128-128-128H388c-70.7 0-128 57.3-128 128v224h-68c-17.7 0-32 14.3-32 32v384c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V496c0-17.7-14.3-32-32-32zM332 240c0-30.9 25.1-56 56-56h248c30.9 0 56 25.1 56 56v224H332V240zm460 600H232V536h560v304zM484 701v53c0 4.4 3.6 8 8 8h40c4.4 0 8-3.6 8-8v-53a48.01 48.01 0 10-56 0z"}}]},name:"lock",theme:"outlined"};var d=e.i(9583),u=i.forwardRef(function(e,t){return i.createElement(d.default,(0,l.default)({},e,{ref:t,icon:c}))}),p=e.i(492030),m=e.i(266537),g=e.i(447566),f=e.i(149192),h=e.i(596239);e.s(["ByokCredentialModal",0,({server:e,open:l,onClose:c,onSuccess:d,accessToken:_})=>{let[v,b]=(0,i.useState)(1),[x,y]=(0,i.useState)(""),[w,S]=(0,i.useState)(!0),[j,k]=(0,i.useState)(!1),C=e.alias||e.server_name||"Service",O=C.charAt(0).toUpperCase(),N=()=>{b(1),y(""),S(!0),k(!1),c()},z=async()=>{if(!x.trim())return void n.message.error("Please enter your API key");k(!0);try{let t=await fetch(`/v1/mcp/server/${e.server_id}/user-credential`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${_}`},body:JSON.stringify({credential:x.trim(),save:w})});if(!t.ok){let e=await t.json();throw Error(e?.detail?.error||"Failed to save credential")}n.message.success(`Connected to ${C}`),d(e.server_id),N()}catch(e){n.message.error(e.message||"Failed to connect")}finally{k(!1)}};return(0,t.jsx)(o.Modal,{open:l,onCancel:N,footer:null,width:480,closeIcon:null,className:"byok-modal",children:(0,t.jsxs)("div",{className:"relative p-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-6",children:[2===v?(0,t.jsxs)("button",{onClick:()=>b(1),className:"flex items-center gap-1 text-gray-500 hover:text-gray-800 text-sm",children:[(0,t.jsx)(g.ArrowLeftOutlined,{})," Back"]}):(0,t.jsx)("div",{}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,t.jsx)("div",{className:`w-2 h-2 rounded-full ${1===v?"bg-blue-500":"bg-gray-300"}`}),(0,t.jsx)("div",{className:`w-2 h-2 rounded-full ${2===v?"bg-blue-500":"bg-gray-300"}`})]}),(0,t.jsx)("button",{onClick:N,className:"text-gray-400 hover:text-gray-600",children:(0,t.jsx)(f.CloseOutlined,{})})]}),1===v?(0,t.jsxs)("div",{className:"text-center",children:[(0,t.jsxs)("div",{className:"flex items-center justify-center gap-3 mb-6",children:[(0,t.jsx)("div",{className:"w-14 h-14 rounded-xl bg-gradient-to-br from-teal-400 to-cyan-600 flex items-center justify-center text-white font-bold text-xl shadow",children:"L"}),(0,t.jsx)(m.ArrowRightOutlined,{className:"text-gray-400 text-lg"}),(0,t.jsx)("div",{className:"w-14 h-14 rounded-xl bg-gradient-to-br from-blue-600 to-indigo-800 flex items-center justify-center text-white font-bold text-xl shadow",children:O})]}),(0,t.jsxs)("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:["Connect ",C]}),(0,t.jsxs)("p",{className:"text-gray-500 mb-6",children:["LiteLLM needs access to ",C," to complete your request."]}),(0,t.jsx)("div",{className:"bg-gray-50 rounded-xl p-4 text-left mb-4",children:(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)("div",{className:"mt-0.5",children:(0,t.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",className:"text-gray-500",children:[(0,t.jsx)("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",stroke:"currentColor",strokeWidth:"2"}),(0,t.jsx)("path",{d:"M8 4v16M16 4v16",stroke:"currentColor",strokeWidth:"2"})]})}),(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{className:"font-semibold text-gray-800 mb-1",children:"How it works"}),(0,t.jsxs)("p",{className:"text-gray-500 text-sm",children:["LiteLLM acts as a secure bridge. Your requests are routed through our MCP client directly to"," ",C,"'s API."]})]})]})}),e.byok_description&&e.byok_description.length>0&&(0,t.jsxs)("div",{className:"bg-gray-50 rounded-xl p-4 text-left mb-6",children:[(0,t.jsxs)("p",{className:"text-xs font-semibold text-gray-500 uppercase tracking-widest mb-3 flex items-center gap-2",children:[(0,t.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",className:"text-green-500",children:[(0,t.jsx)("path",{d:"M12 2L12 22M2 12L22 12",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"}),(0,t.jsx)("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2"})]}),"Requested Access"]}),(0,t.jsx)("ul",{className:"space-y-2",children:e.byok_description.map((e,i)=>(0,t.jsxs)("li",{className:"flex items-center gap-2 text-sm text-gray-700",children:[(0,t.jsx)(p.CheckOutlined,{className:"text-green-500 flex-shrink-0"}),e]},i))})]}),(0,t.jsxs)("button",{onClick:()=>b(2),className:"w-full bg-gray-900 hover:bg-gray-700 text-white font-medium py-3 px-6 rounded-xl flex items-center justify-center gap-2 transition-colors",children:["Continue to Authentication ",(0,t.jsx)(m.ArrowRightOutlined,{})]}),(0,t.jsx)("button",{onClick:N,className:"mt-3 w-full text-gray-400 hover:text-gray-600 text-sm py-2",children:"Cancel"})]}):(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"w-12 h-12 rounded-full bg-blue-50 flex items-center justify-center mb-4",children:(0,t.jsx)(s.KeyOutlined,{className:"text-blue-400 text-xl"})}),(0,t.jsx)("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Provide API Key"}),(0,t.jsxs)("p",{className:"text-gray-500 mb-6",children:["Enter your ",C," API key to authorize this connection."]}),(0,t.jsxs)("div",{className:"mb-4",children:[(0,t.jsxs)("label",{className:"block text-sm font-semibold text-gray-800 mb-2",children:[C," API Key"]}),(0,t.jsx)(r.Input.Password,{placeholder:"Enter your API key",value:x,onChange:e=>y(e.target.value),size:"large",className:"rounded-lg"}),e.byok_api_key_help_url&&(0,t.jsxs)("a",{href:e.byok_api_key_help_url,target:"_blank",rel:"noopener noreferrer",className:"text-blue-500 hover:text-blue-700 text-sm mt-2 flex items-center gap-1",children:["Where do I find my API key? ",(0,t.jsx)(h.LinkOutlined,{})]})]}),(0,t.jsxs)("div",{className:"bg-gray-50 rounded-xl p-4 flex items-center justify-between mb-4",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",className:"text-gray-500",children:(0,t.jsx)("path",{d:"M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z",fill:"currentColor"})}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-800",children:"Save key for future use"})]}),(0,t.jsx)(a.Switch,{checked:w,onChange:S})]}),(0,t.jsxs)("div",{className:"bg-blue-50 rounded-xl p-4 flex items-start gap-3 mb-6",children:[(0,t.jsx)(u,{className:"text-blue-400 mt-0.5 flex-shrink-0"}),(0,t.jsx)("p",{className:"text-sm text-blue-700",children:"Your key is stored securely and transmitted over HTTPS. It is never shared with third parties."})]}),(0,t.jsxs)("button",{onClick:z,disabled:j,className:"w-full bg-blue-500 hover:bg-blue-600 disabled:opacity-60 text-white font-medium py-3 px-6 rounded-xl flex items-center justify-center gap-2 transition-colors",children:[(0,t.jsx)(u,{})," Connect & Authorize"]})]})]})})}],611052)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/0b06d056425a991f.js b/litellm/proxy/_experimental/out/_next/static/chunks/0b06d056425a991f.js new file mode 100644 index 00000000000..c05203719b5 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/0b06d056425a991f.js @@ -0,0 +1,7 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,270345,e=>{"use strict";var t=e.i(764205);let r=async(e,r,a,l)=>"Admin"!=a&&"Admin Viewer"!=a?await (0,t.teamListCall)(e,l?.organization_id||null,r):await (0,t.teamListCall)(e,l?.organization_id||null);e.s(["fetchTeams",0,r])},519756,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={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"};var l=e.i(9583),n=r.forwardRef(function(e,n){return r.createElement(l.default,(0,t.default)({},e,{ref:n,icon:a}))});e.s(["UploadOutlined",0,n],519756)},981339,e=>{"use strict";var t=e.i(185793);e.s(["Skeleton",()=>t.default])},500330,e=>{"use strict";var t=e.i(727749);function r(e,t){let r=structuredClone(e);for(let[e,a]of Object.entries(t))e in r&&(r[e]=a);return r}let a=(e,t=0,r=!1,a=!0)=>{if(null==e||!Number.isFinite(e)||0===e&&!a)return"-";let l={minimumFractionDigits:t,maximumFractionDigits:t};if(!r)return e.toLocaleString("en-US",l);let n=e<0?"-":"",s=Math.abs(e),o=s,i="";return s>=1e6?(o=s/1e6,i="M"):s>=1e3&&(o=s/1e3,i="K"),`${n}${o.toLocaleString("en-US",l)}${i}`},l=async(e,r="Copied to clipboard")=>{if(!e)return!1;if(!navigator||!navigator.clipboard||!navigator.clipboard.writeText)return n(e,r);try{return await navigator.clipboard.writeText(e),t.default.success(r),!0}catch(t){return console.error("Clipboard API failed: ",t),n(e,r)}},n=(e,r)=>{try{let a=document.createElement("textarea");a.value=e,a.style.position="fixed",a.style.left="-999999px",a.style.top="-999999px",a.setAttribute("readonly",""),document.body.appendChild(a),a.focus(),a.select();let l=document.execCommand("copy");if(document.body.removeChild(a),l)return t.default.success(r),!0;throw Error("execCommand failed")}catch(e){return t.default.fromBackend("Failed to copy to clipboard"),console.error("Failed to copy: ",e),!1}};e.s(["copyToClipboard",0,l,"formatNumberWithCommas",0,a,"getSpendString",0,(e,t=6)=>{if(null==e||!Number.isFinite(e)||0===e)return"-";let r=a(e,t,!1,!1);if(0===Number(r.replace(/,/g,""))){let e=(1/10**t).toFixed(t);return`< $${e}`}return`$${r}`},"updateExistingKeys",()=>r])},743151,(e,t,r)=>{"use strict";function a(e){return(a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}Object.defineProperty(r,"__esModule",{value:!0}),r.CopyToClipboard=void 0;var l=o(e.r(271645)),n=o(e.r(844343)),s=["text","onCopy","options","children"];function o(e){return e&&e.__esModule?e:{default:e}}function i(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,a)}return r}function c(e){for(var t=1;t=0||(l[r]=e[r]);return l}(e,t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(l[r]=e[r])}return l}(e,s),a=l.default.Children.only(t);return l.default.cloneElement(a,c(c({},r),{},{onClick:this.onClick}))}}],function(e,t){for(var r=0;r{"use strict";var a=e.r(743151).CopyToClipboard;a.CopyToClipboard=a,t.exports=a},109799,e=>{"use strict";var t=e.i(135214),r=e.i(764205),a=e.i(266027),l=e.i(912598);let n=(0,e.i(243652).createQueryKeys)("organizations");e.s(["useOrganization",0,e=>{let s=(0,l.useQueryClient)(),{accessToken:o}=(0,t.default)();return(0,a.useQuery)({queryKey:n.detail(e),enabled:!!(o&&e),queryFn:async()=>{if(!o||!e)throw Error("Missing auth or teamId");return(0,r.organizationInfoCall)(o,e)},initialData:()=>{if(!e)return;let t=s.getQueryData(n.list({}));return t?.find(t=>t.organization_id===e)}})},"useOrganizations",0,()=>{let{accessToken:e,userId:l,userRole:s}=(0,t.default)();return(0,a.useQuery)({queryKey:n.list({}),queryFn:async()=>await (0,r.organizationListCall)(e),enabled:!!(e&&l&&s)})}])},309426,e=>{"use strict";var t=e.i(290571),r=e.i(444755),a=e.i(673706),l=e.i(271645),n=e.i(46757);let s=(0,a.makeClassName)("Col"),o=l.default.forwardRef((e,a)=>{let o,i,c,d,{numColSpan:u=1,numColSpanSm:m,numColSpanMd:g,numColSpanLg:f,children:p,className:h}=e,x=(0,t.__rest)(e,["numColSpan","numColSpanSm","numColSpanMd","numColSpanLg","children","className"]),b=(e,t)=>e&&Object.keys(t).includes(String(e))?t[e]:"";return l.default.createElement("div",Object.assign({ref:a,className:(0,r.tremorTwMerge)(s("root"),(o=b(u,n.colSpan),i=b(m,n.colSpanSm),c=b(g,n.colSpanMd),d=b(f,n.colSpanLg),(0,r.tremorTwMerge)(o,i,c,d)),h)},x),p)});o.displayName="Col",e.s(["Col",()=>o],309426)},988297,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 4v16m8-8H4"}))});e.s(["PlusIcon",0,r],988297)},797672,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"}))});e.s(["PencilIcon",0,r],797672)},992619,e=>{"use strict";var t=e.i(843476),r=e.i(271645),a=e.i(779241),l=e.i(599724),n=e.i(199133),s=e.i(983561),o=e.i(689020);e.s(["default",0,({accessToken:e,value:i,placeholder:c="Select a Model",onChange:d,disabled:u=!1,style:m,className:g,showLabel:f=!0,labelText:p="Select Model"})=>{let[h,x]=(0,r.useState)(i),[b,y]=(0,r.useState)(!1),[v,w]=(0,r.useState)([]),k=(0,r.useRef)(null);return(0,r.useEffect)(()=>{x(i)},[i]),(0,r.useEffect)(()=>{e&&(async()=>{try{let t=await (0,o.fetchAvailableModels)(e);console.log("Fetched models for selector:",t),t.length>0&&w(t)}catch(e){console.error("Error fetching model info:",e)}})()},[e]),(0,t.jsxs)("div",{children:[f&&(0,t.jsxs)(l.Text,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,t.jsx)(s.RobotOutlined,{className:"mr-2"})," ",p]}),(0,t.jsx)(n.Select,{value:h,placeholder:c,onChange:e=>{"custom"===e?(y(!0),x(void 0)):(y(!1),x(e),d&&d(e))},options:[...Array.from(new Set(v.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%",...m},showSearch:!0,className:`rounded-md ${g||""}`,disabled:u}),b&&(0,t.jsx)(a.TextInput,{className:"mt-2",placeholder:"Enter custom model name",onValueChange:e=>{k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{x(e),d&&d(e)},500)},disabled:u})]})}])},409797,e=>{"use strict";var t=e.i(631171);e.s(["ChevronDownIcon",()=>t.default])},91739,e=>{"use strict";var t=e.i(544195);e.s(["Radio",()=>t.default])},500727,696609,531516,e=>{"use strict";var t=e.i(266027),r=e.i(243652),a=e.i(764205),l=e.i(135214);let n=(0,r.createQueryKeys)("mcpServers");e.s(["useMCPServers",0,e=>{let{accessToken:r}=(0,l.default)();return(0,t.useQuery)({queryKey:n.list(e?{filters:{teamId:e}}:void 0),queryFn:async()=>await (0,a.fetchMCPServers)(r,e),enabled:!!r})}],500727);var s=e.i(843476),o=e.i(271645),i=e.i(536916),c=e.i(599724),d=e.i(409797),u=e.i(246349),u=u;let m=/\b(delete|remove|destroy|purge|drop|erase|unlink)\b/i,g=/\b(create|add|insert|new|post|submit|register|make|generate|write|upload)\b/i,f=/\b(update|edit|modify|change|patch|put|set|rename|move|transform)\b/i,p=/\b(get|read|list|fetch|search|find|query|retrieve|show|view|check|describe|info)\b/i;function h(e,t=""){let r=e.toLowerCase();if(p.test(r))return"read";if(m.test(r))return"delete";if(f.test(r))return"update";if(g.test(r))return"create";if(t){let e=t.toLowerCase();if(p.test(e))return"read";if(m.test(e))return"delete";if(f.test(e))return"update";if(g.test(e))return"create"}return"unknown"}function x(e){let t={read:[],create:[],update:[],delete:[],unknown:[]};for(let r of e)t[h(r.name,r.description)].push(r);return t}let b={read:{label:"Read",description:"Safe operations — fetch, list, search. No side effects.",risk:"low"},create:{label:"Create",description:"Add new resources — insert, upload, register.",risk:"medium"},update:{label:"Update",description:"Modify existing resources — edit, patch, rename.",risk:"medium"},delete:{label:"Delete",description:"Destructive operations — remove, purge, destroy.",risk:"high"},unknown:{label:"Other",description:"Operations that could not be automatically classified.",risk:"unknown"}};e.s(["CRUD_GROUP_META",0,b,"classifyToolOp",()=>h,"groupToolsByCrud",()=>x],696609);let y=["read","create","update","delete","unknown"],v={low:"bg-green-100 text-green-800",medium:"bg-yellow-100 text-yellow-800",high:"bg-red-100 text-red-800 font-semibold",unknown:"bg-gray-100 text-gray-700"},w={read:"border-green-200",create:"border-blue-200",update:"border-yellow-200",delete:"border-red-300",unknown:"border-gray-200"},k={read:"bg-green-50",create:"bg-blue-50",update:"bg-yellow-50",delete:"bg-red-50",unknown:"bg-gray-50"};e.s(["default",0,({tools:e,value:t,onChange:r,readOnly:a=!1,searchFilter:l=""})=>{let[n,m]=(0,o.useState)({read:!1,create:!1,update:!1,delete:!1,unknown:!0}),g=(0,o.useMemo)(()=>x(e),[e]),f=(0,o.useMemo)(()=>new Set(void 0===t?e.map(e=>e.name):t),[t,e]),p=e=>{if(a)return;let t=new Set(f);t.has(e)?t.delete(e):t.add(e),r(Array.from(t))};return 0===e.length?null:(0,s.jsx)("div",{className:"space-y-3",children:y.map(e=>{let t,o=g[e];if(0===o.length)return null;if(l){let e=l.toLowerCase();if(!o.some(t=>t.name.toLowerCase().includes(e)||(t.description??"").toLowerCase().includes(e)))return null}let h=b[e],x=(t=g[e]).length>0&&t.every(e=>f.has(e.name)),y=(e=>{let t=g[e];if(0===t.length)return!1;let r=t.filter(e=>f.has(e.name)).length;return r>0&&r{m(t=>({...t,[e]:!t[e]}))},children:[C?(0,s.jsx)(u.default,{className:"w-4 h-4 text-gray-500 flex-shrink-0"}):(0,s.jsx)(d.ChevronDownIcon,{className:"w-4 h-4 text-gray-500 flex-shrink-0"}),(0,s.jsx)("span",{className:"font-semibold text-gray-900 text-sm",children:h.label}),(0,s.jsx)("span",{className:`text-xs px-2 py-0.5 rounded-full ${v[h.risk]}`,children:"high"===h.risk?"High Risk":"medium"===h.risk?"Medium Risk":"low"===h.risk?"Safe":"Unclassified"}),(0,s.jsxs)("span",{className:"text-xs text-gray-500 ml-1",children:[o.filter(e=>f.has(e.name)).length,"/",o.length," allowed"]})]}),!a&&(0,s.jsxs)("div",{className:"flex items-center gap-2 ml-4",children:[(0,s.jsx)(c.Text,{className:"text-xs text-gray-500",children:x?"All on":y?"Partial":"All off"}),(0,s.jsx)(i.Checkbox,{checked:x,indeterminate:y,onChange:t=>((e,t)=>{if(a)return;let l=new Set(f);for(let r of g[e])t?l.add(r.name):l.delete(r.name);r(Array.from(l))})(e,t.target.checked),onClick:e=>e.stopPropagation()})]})]}),!C&&(0,s.jsx)("div",{className:"px-4 pt-2 pb-1 text-xs text-gray-500 bg-white border-b border-gray-100",children:h.description}),!C&&(0,s.jsx)("div",{className:"bg-white divide-y divide-gray-50",children:o.filter(e=>!l||e.name.toLowerCase().includes(l.toLowerCase())||(e.description??"").toLowerCase().includes(l.toLowerCase())).map(e=>{let t,r=(t=e.name,f.has(t));return(0,s.jsxs)("div",{className:`flex items-start gap-3 px-4 py-2.5 transition-colors hover:bg-gray-50 ${!a?"cursor-pointer":""} ${r?"":"opacity-60"}`,onClick:()=>p(e.name),children:[(0,s.jsx)(i.Checkbox,{checked:r,onChange:()=>p(e.name),disabled:a,onClick:e=>e.stopPropagation()}),(0,s.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,s.jsx)(c.Text,{className:"font-medium text-gray-900 text-sm",children:e.name}),e.description&&(0,s.jsx)(c.Text,{className:"text-xs text-gray-500 mt-0.5 leading-snug",children:e.description})]}),(0,s.jsx)("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${r?"bg-green-100 text-green-700":"bg-gray-100 text-gray-500"}`,children:r?"on":"off"})]},e.name)})})]},e)})})}],531516)},361653,e=>{"use strict";let t=(0,e.i(475254).default)("circle-alert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);e.s(["default",()=>t])},603908,e=>{"use strict";let t=(0,e.i(475254).default)("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);e.s(["default",()=>t])},841947,e=>{"use strict";let t=(0,e.i(475254).default)("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);e.s(["default",()=>t])},793130,e=>{"use strict";var t=e.i(290571),r=e.i(429427),a=e.i(371330),l=e.i(271645),n=e.i(394487),s=e.i(503269),o=e.i(214520),i=e.i(746725),c=e.i(914189),d=e.i(144279),u=e.i(294316),m=e.i(601893),g=e.i(140721),f=e.i(942803),p=e.i(233538),h=e.i(694421),x=e.i(700020),b=e.i(35889),y=e.i(998348),v=e.i(722678);let w=(0,l.createContext)(null);w.displayName="GroupContext";let k=l.Fragment,C=Object.assign((0,x.forwardRefWithAs)(function(e,t){var k;let C=(0,l.useId)(),j=(0,f.useProvidedId)(),N=(0,m.useDisabled)(),{id:S=j||`headlessui-switch-${C}`,disabled:M=N||!1,checked:T,defaultChecked:O,onChange:E,name:P,value:$,form:_,autoFocus:R=!1,...L}=e,z=(0,l.useContext)(w),[B,D]=(0,l.useState)(null),F=(0,l.useRef)(null),I=(0,u.useSyncRefs)(F,t,null===z?null:z.setSwitch,D),A=(0,o.useDefaultValue)(O),[H,q]=(0,s.useControllable)(T,E,null!=A&&A),V=(0,i.useDisposables)(),[G,K]=(0,l.useState)(!1),X=(0,c.useEvent)(()=>{K(!0),null==q||q(!H),V.nextFrame(()=>{K(!1)})}),W=(0,c.useEvent)(e=>{if((0,p.isDisabledReactIssue7711)(e.currentTarget))return e.preventDefault();e.preventDefault(),X()}),U=(0,c.useEvent)(e=>{e.key===y.Keys.Space?(e.preventDefault(),X()):e.key===y.Keys.Enter&&(0,h.attemptSubmit)(e.currentTarget)}),Y=(0,c.useEvent)(e=>e.preventDefault()),Q=(0,v.useLabelledBy)(),J=(0,b.useDescribedBy)(),{isFocusVisible:Z,focusProps:ee}=(0,r.useFocusRing)({autoFocus:R}),{isHovered:et,hoverProps:er}=(0,a.useHover)({isDisabled:M}),{pressed:ea,pressProps:el}=(0,n.useActivePress)({disabled:M}),en=(0,l.useMemo)(()=>({checked:H,disabled:M,hover:et,focus:Z,active:ea,autofocus:R,changing:G}),[H,et,Z,ea,M,G,R]),es=(0,x.mergeProps)({id:S,ref:I,role:"switch",type:(0,d.useResolveButtonType)(e,B),tabIndex:-1===e.tabIndex?0:null!=(k=e.tabIndex)?k:0,"aria-checked":H,"aria-labelledby":Q,"aria-describedby":J,disabled:M||void 0,autoFocus:R,onClick:W,onKeyUp:U,onKeyPress:Y},ee,er,el),eo=(0,l.useCallback)(()=>{if(void 0!==A)return null==q?void 0:q(A)},[q,A]),ei=(0,x.useRender)();return l.default.createElement(l.default.Fragment,null,null!=P&&l.default.createElement(g.FormFields,{disabled:M,data:{[P]:$||"on"},overrides:{type:"checkbox",checked:H},form:_,onReset:eo}),ei({ourProps:es,theirProps:L,slot:en,defaultTag:"button",name:"Switch"}))}),{Group:function(e){var t;let[r,a]=(0,l.useState)(null),[n,s]=(0,v.useLabels)(),[o,i]=(0,b.useDescriptions)(),c=(0,l.useMemo)(()=>({switch:r,setSwitch:a}),[r,a]),d=(0,x.useRender)();return l.default.createElement(i,{name:"Switch.Description",value:o},l.default.createElement(s,{name:"Switch.Label",value:n,props:{htmlFor:null==(t=c.switch)?void 0:t.id,onClick(e){r&&(e.currentTarget instanceof HTMLLabelElement&&e.preventDefault(),r.click(),r.focus({preventScroll:!0}))}}},l.default.createElement(w.Provider,{value:c},d({ourProps:{},theirProps:e,slot:{},defaultTag:k,name:"Switch.Group"}))))},Label:v.Label,Description:b.Description});var j=e.i(888288),N=e.i(95779),S=e.i(444755),M=e.i(673706),T=e.i(829087);let O=(0,M.makeClassName)("Switch"),E=l.default.forwardRef((e,r)=>{let{checked:a,defaultChecked:n=!1,onChange:s,color:o,name:i,error:c,errorMessage:d,disabled:u,required:m,tooltip:g,id:f}=e,p=(0,t.__rest)(e,["checked","defaultChecked","onChange","color","name","error","errorMessage","disabled","required","tooltip","id"]),h={bgColor:o?(0,M.getColorClassNames)(o,N.colorPalette.background).bgColor:"bg-tremor-brand dark:bg-dark-tremor-brand",ringColor:o?(0,M.getColorClassNames)(o,N.colorPalette.ring).ringColor:"ring-tremor-brand-muted dark:ring-dark-tremor-brand-muted"},[x,b]=(0,j.default)(n,a),[y,v]=(0,l.useState)(!1),{tooltipProps:w,getReferenceProps:k}=(0,T.useTooltip)(300);return l.default.createElement("div",{className:"flex flex-row items-center justify-start"},l.default.createElement(T.default,Object.assign({text:g},w)),l.default.createElement("div",Object.assign({ref:(0,M.mergeRefs)([r,w.refs.setReference]),className:(0,S.tremorTwMerge)(O("root"),"flex flex-row relative h-5")},p,k),l.default.createElement("input",{type:"checkbox",className:(0,S.tremorTwMerge)(O("input"),"absolute w-5 h-5 cursor-pointer left-0 top-0 opacity-0"),name:i,required:m,checked:x,onChange:e=>{e.preventDefault()}}),l.default.createElement(C,{checked:x,onChange:e=>{b(e),null==s||s(e)},disabled:u,className:(0,S.tremorTwMerge)(O("switch"),"w-10 h-5 group relative inline-flex shrink-0 cursor-pointer items-center justify-center rounded-tremor-full","focus:outline-none",u?"cursor-not-allowed":""),onFocus:()=>v(!0),onBlur:()=>v(!1),id:f},l.default.createElement("span",{className:(0,S.tremorTwMerge)(O("sr-only"),"sr-only")},"Switch ",x?"on":"off"),l.default.createElement("span",{"aria-hidden":"true",className:(0,S.tremorTwMerge)(O("background"),x?h.bgColor:"bg-tremor-border dark:bg-dark-tremor-border","pointer-events-none absolute mx-auto h-3 w-9 rounded-tremor-full transition-colors duration-100 ease-in-out")}),l.default.createElement("span",{"aria-hidden":"true",className:(0,S.tremorTwMerge)(O("round"),x?(0,S.tremorTwMerge)(h.bgColor,"translate-x-5 border-tremor-background dark:border-dark-tremor-background"):"translate-x-0 bg-tremor-border dark:bg-dark-tremor-border border-tremor-background dark:border-dark-tremor-background","pointer-events-none absolute left-0 inline-block h-5 w-5 transform rounded-tremor-full border-2 shadow-tremor-input duration-100 ease-in-out transition",y?(0,S.tremorTwMerge)("ring-2",h.ringColor):"")}))),c&&d?l.default.createElement("p",{className:(0,S.tremorTwMerge)(O("errorMessage"),"text-sm text-red-500 mt-1 ")},d):null)});E.displayName="Switch",e.s(["Switch",()=>E],793130)},158392,419470,e=>{"use strict";var t=e.i(843476),r=e.i(779241);let a={ttl:3600,lowest_latency_buffer:0},l=({routingStrategyArgs:e})=>{let 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,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"max-w-3xl",children:[(0,t.jsx)("h3",{className:"text-sm font-medium text-gray-900",children:"Latency-Based Configuration"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Fine-tune latency-based routing behavior"})]}),(0,t.jsx)("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2 xl:grid-cols-3",children:Object.entries(e||a).map(([e,a])=>(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsxs)("label",{className:"block",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:e.replace(/_/g," ")}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-2",children:l[e]||""}),(0,t.jsx)(r.TextInput,{name:e,defaultValue:"object"==typeof a?JSON.stringify(a,null,2):a?.toString(),className:"font-mono text-sm w-full"})]})},e))})]}),(0,t.jsx)("div",{className:"border-t border-gray-200"})]})},n=({routerSettings:e,routerFieldsMetadata:a})=>(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"max-w-3xl",children:[(0,t.jsx)("h3",{className:"text-sm font-medium text-gray-900",children:"Reliability & Retries"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Configure retry logic and failure handling"})]}),(0,t.jsx)("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2 xl:grid-cols-3",children:Object.entries(e).filter(([e,t])=>"fallbacks"!=e&&"context_window_fallbacks"!=e&&"routing_strategy_args"!=e&&"routing_strategy"!=e&&"enable_tag_filtering"!=e).map(([e,l])=>(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsxs)("label",{className:"block",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:a[e]?.ui_field_name||e}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-2",children:a[e]?.field_description||""}),(0,t.jsx)(r.TextInput,{name:e,defaultValue:null==l||"null"===l?"":"object"==typeof l?JSON.stringify(l,null,2):l?.toString()||"",placeholder:"—",className:"font-mono text-sm w-full"})]})},e))})]});var s=e.i(199133);let o=({selectedStrategy:e,availableStrategies:r,routingStrategyDescriptions:a,routerFieldsMetadata:l,onStrategyChange:n})=>(0,t.jsxs)("div",{className:"space-y-2 max-w-3xl",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:l.routing_strategy?.ui_field_name||"Routing Strategy"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-2",children:l.routing_strategy?.field_description||""})]}),(0,t.jsx)("div",{className:"routing-strategy-select max-w-3xl",children:(0,t.jsx)(s.Select,{value:e,onChange:n,style:{width:"100%"},size:"large",children:r.map(e=>(0,t.jsx)(s.Select.Option,{value:e,label:e,children:(0,t.jsxs)("div",{className:"flex flex-col gap-0.5 py-1",children:[(0,t.jsx)("span",{className:"font-mono text-sm font-medium",children:e}),a[e]&&(0,t.jsx)("span",{className:"text-xs text-gray-500 font-normal",children:a[e]})]})},e))})})]});var i=e.i(793130);let c=({enabled:e,routerFieldsMetadata:r,onToggle:a})=>(0,t.jsx)("div",{className:"space-y-3 max-w-3xl",children:(0,t.jsxs)("div",{className:"flex items-start justify-between",children:[(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsx)("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:r.enable_tag_filtering?.ui_field_name||"Enable Tag Filtering"}),(0,t.jsxs)("p",{className:"text-xs text-gray-500 mt-0.5",children:[r.enable_tag_filtering?.field_description||"",r.enable_tag_filtering?.link&&(0,t.jsxs)(t.Fragment,{children:[" ",(0,t.jsx)("a",{href:r.enable_tag_filtering.link,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"Learn more"})]})]})]}),(0,t.jsx)(i.Switch,{checked:e,onChange:a,className:"ml-4"})]})});e.s(["default",0,({value:e,onChange:r,routerFieldsMetadata:a,availableRoutingStrategies:s,routingStrategyDescriptions:i})=>(0,t.jsxs)("div",{className:"w-full space-y-8 py-2",children:[(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"max-w-3xl",children:[(0,t.jsx)("h3",{className:"text-sm font-medium text-gray-900",children:"Routing Settings"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Configure how requests are routed to deployments"})]}),s.length>0&&(0,t.jsx)(o,{selectedStrategy:e.selectedStrategy||e.routerSettings.routing_strategy||null,availableStrategies:s,routingStrategyDescriptions:i,routerFieldsMetadata:a,onStrategyChange:t=>{r({...e,selectedStrategy:t})}}),(0,t.jsx)(c,{enabled:e.enableTagFiltering,routerFieldsMetadata:a,onToggle:t=>{r({...e,enableTagFiltering:t})}})]}),(0,t.jsx)("div",{className:"border-t border-gray-200"}),"latency-based-routing"===e.selectedStrategy&&(0,t.jsx)(l,{routingStrategyArgs:e.routerSettings.routing_strategy_args}),(0,t.jsx)(n,{routerSettings:e.routerSettings,routerFieldsMetadata:a})]})],158392);var d=e.i(994388),u=e.i(998573),m=e.i(653496),g=e.i(107233),f=e.i(271645),p=e.i(592968),h=e.i(361653),h=h;let x=(0,e.i(475254).default)("arrow-down",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);var b=e.i(37727);function y({group:e,onChange:r,availableModels:a,maxFallbacks:l}){let n=a.filter(t=>t!==e.primaryModel),o=e.fallbackModels.length{let a=[...e.fallbackModels];a.includes(t)&&(a=a.filter(e=>e!==t)),r({...e,primaryModel:t,fallbackModels:a})},showSearch:!0,filterOption:(e,t)=>(t?.label??"").toLowerCase().includes(e.toLowerCase()),options:a.map(e=>({label:e,value:e}))}),!e.primaryModel&&(0,t.jsxs)("div",{className:"mt-2 flex items-center gap-2 text-amber-600 text-xs bg-amber-50 p-2 rounded",children:[(0,t.jsx)(h.default,{className:"w-4 h-4"}),(0,t.jsx)("span",{children:"Select a model to begin configuring fallbacks"})]})]}),(0,t.jsx)("div",{className:"flex items-center justify-center -my-4 z-10",children:(0,t.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,t.jsx)(x,{className:"w-4 h-4"}),"IF FAILS, TRY..."]})}),(0,t.jsxs)("div",{className:`transition-opacity duration-300 ${!e.primaryModel?"opacity-50 pointer-events-none":"opacity-100"}`,children:[(0,t.jsxs)("label",{className:"block text-sm font-semibold text-gray-700 mb-2",children:["Fallback Chain ",(0,t.jsx)("span",{className:"text-red-500",children:"*"}),(0,t.jsxs)("span",{className:"text-xs text-gray-500 font-normal ml-2",children:["(Max ",l," fallbacks at a time)"]})]}),(0,t.jsxs)("div",{className:"bg-gray-50 rounded-xl p-4 border border-gray-200",children:[(0,t.jsxs)("div",{className:"mb-4",children:[(0,t.jsx)(s.Select,{mode:"multiple",className:"w-full",size:"large",placeholder:o?"Select fallback models to add...":`Maximum ${l} fallbacks reached`,value:e.fallbackModels,onChange:t=>{let a=t.slice(0,l);r({...e,fallbackModels:a})},disabled:!e.primaryModel,options:n.map(e=>({label:e,value:e})),optionRender:(r,a)=>{let l=e.fallbackModels.includes(r.value),n=l?e.fallbackModels.indexOf(r.value)+1:null;return(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[l&&null!==n&&(0,t.jsx)("span",{className:"flex items-center justify-center w-5 h-5 rounded bg-indigo-100 text-indigo-600 text-xs font-bold",children:n}),(0,t.jsx)("span",{children:r.label})]})},maxTagCount:"responsive",maxTagPlaceholder:e=>(0,t.jsx)(p.Tooltip,{styles:{root:{pointerEvents:"none"}},title:e.map(({value:e})=>e).join(", "),children:(0,t.jsxs)("span",{children:["+",e.length," more"]})}),showSearch:!0,filterOption:(e,t)=>(t?.label??"").toLowerCase().includes(e.toLowerCase())}),(0,t.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. (${e.fallbackModels.length}/${l} used)`:`Maximum ${l} fallbacks reached. Remove some to add more.`})]}),(0,t.jsx)("div",{className:"space-y-2 min-h-[100px]",children:0===e.fallbackModels.length?(0,t.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,t.jsx)("span",{className:"text-sm",children:"No fallback models selected"}),(0,t.jsx)("span",{className:"text-xs mt-1",children:"Add models from the dropdown above"})]}):e.fallbackModels.map((a,l)=>(0,t.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,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.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,t.jsx)("span",{className:"text-xs font-bold",children:l+1})}),(0,t.jsx)("div",{children:(0,t.jsx)("span",{className:"font-medium text-gray-800",children:a})})]}),(0,t.jsx)("button",{type:"button",onClick:()=>{let t;return t=e.fallbackModels.filter((e,t)=>t!==l),void r({...e,fallbackModels:t})},className:"opacity-0 group-hover:opacity-100 transition-opacity text-gray-400 hover:text-red-500 p-1",children:(0,t.jsx)(b.X,{className:"w-4 h-4"})})]},`${a}-${l}`))})]})]})]})}function v({groups:e,onGroupsChange:r,availableModels:a,maxFallbacks:l=10,maxGroups:n=5}){let[s,o]=(0,f.useState)(e.length>0?e[0].id:"1");(0,f.useEffect)(()=>{e.length>0?e.some(e=>e.id===s)||o(e[0].id):o("1")},[e]);let i=()=>{if(e.length>=n)return;let t=Date.now().toString();r([...e,{id:t,primaryModel:null,fallbackModels:[]}]),o(t)},c=t=>{r(e.map(e=>e.id===t.id?t:e))},p=e.map((r,n)=>{let s=r.primaryModel?r.primaryModel:`Group ${n+1}`;return{key:r.id,label:s,closable:e.length>1,children:(0,t.jsx)(y,{group:r,onChange:c,availableModels:a,maxFallbacks:l})}});return 0===e.length?(0,t.jsxs)("div",{className:"text-center py-12 bg-gray-50 rounded-lg border border-dashed border-gray-300",children:[(0,t.jsx)("p",{className:"text-gray-500 mb-4",children:"No fallback groups configured"}),(0,t.jsx)(d.Button,{variant:"primary",onClick:i,icon:()=>(0,t.jsx)(g.Plus,{className:"w-4 h-4"}),children:"Create First Group"})]}):(0,t.jsx)(m.Tabs,{type:"editable-card",activeKey:s,onChange:o,onEdit:(t,a)=>{"add"===a?i():"remove"===a&&e.length>1&&(t=>{if(1===e.length)return u.message.warning("At least one group is required");let a=e.filter(e=>e.id!==t);r(a),s===t&&a.length>0&&o(a[a.length-1].id)})(t)},items:p,className:"fallback-tabs",tabBarStyle:{marginBottom:0},hideAdd:e.length>=n})}e.s(["FallbackSelectionForm",()=>v],419470)},653496,e=>{"use strict";var t=e.i(721369);e.s(["Tabs",()=>t.default])},599724,936325,e=>{"use strict";var t=e.i(95779),r=e.i(444755),a=e.i(673706),l=e.i(271645);let n=l.default.forwardRef((e,n)=>{let{color:s,className:o,children:i}=e;return l.default.createElement("p",{ref:n,className:(0,r.tremorTwMerge)("text-tremor-default",s?(0,a.getColorClassNames)(s,t.colorPalette.text).textColor:(0,r.tremorTwMerge)("text-tremor-content","dark:text-dark-tremor-content"),o)},i)});n.displayName="Text",e.s(["default",()=>n],936325),e.s(["Text",()=>n],599724)},304967,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(480731),l=e.i(95779),n=e.i(444755),s=e.i(673706);let o=(0,s.makeClassName)("Card"),i=r.default.forwardRef((e,i)=>{let{decoration:c="",decorationColor:d,children:u,className:m}=e,g=(0,t.__rest)(e,["decoration","decorationColor","children","className"]);return r.default.createElement("div",Object.assign({ref:i,className:(0,n.tremorTwMerge)(o("root"),"relative w-full text-left ring-1 rounded-tremor-default p-6","bg-tremor-background ring-tremor-ring shadow-tremor-card","dark:bg-dark-tremor-background dark:ring-dark-tremor-ring dark:shadow-dark-tremor-card",d?(0,s.getColorClassNames)(d,l.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",(e=>{if(!e)return"";switch(e){case a.HorizontalPositions.Left:return"border-l-4";case a.VerticalPositions.Top:return"border-t-4";case a.HorizontalPositions.Right:return"border-r-4";case a.VerticalPositions.Bottom:return"border-b-4";default:return""}})(c),m)},g),u)});i.displayName="Card",e.s(["Card",()=>i],304967)},994388,e=>{"use strict";var t=e.i(290571),r=e.i(829087),a=e.i(271645);let l=["preEnter","entering","entered","preExit","exiting","exited","unmounted"],n=e=>({_s:e,status:l[e],isEnter:e<3,isMounted:6!==e,isResolved:2===e||e>4}),s=e=>e?6:5,o=(e,t,r,a,l)=>{clearTimeout(a.current);let s=n(e);t(s),r.current=s,l&&l({current:s})};var i=e.i(480731),c=e.i(444755),d=e.i(673706);let u=e=>{var r=(0,t.__rest)(e,[]);return a.default.createElement("svg",Object.assign({},r,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"}),a.default.createElement("path",{fill:"none",d:"M0 0h24v24H0z"}),a.default.createElement("path",{d:"M18.364 5.636L16.95 7.05A7 7 0 1 0 19 12h2a9 9 0 1 1-2.636-6.364z"}))};var m=e.i(95779);let g={xs:{height:"h-4",width:"w-4"},sm:{height:"h-5",width:"w-5"},md:{height:"h-5",width:"w-5"},lg:{height:"h-6",width:"w-6"},xl:{height:"h-6",width:"w-6"}},f=(e,t)=>{switch(e){case"primary":return{textColor:t?(0,d.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",hoverTextColor:t?(0,d.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",bgColor:t?(0,d.getColorClassNames)(t,m.colorPalette.background).bgColor:"bg-tremor-brand dark:bg-dark-tremor-brand",hoverBgColor:t?(0,d.getColorClassNames)(t,m.colorPalette.darkBackground).hoverBgColor:"hover:bg-tremor-brand-emphasis dark:hover:bg-dark-tremor-brand-emphasis",borderColor:t?(0,d.getColorClassNames)(t,m.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",hoverBorderColor:t?(0,d.getColorClassNames)(t,m.colorPalette.darkBorder).hoverBorderColor:"hover:border-tremor-brand-emphasis dark:hover:border-dark-tremor-brand-emphasis"};case"secondary":return{textColor:t?(0,d.getColorClassNames)(t,m.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,d.getColorClassNames)(t,m.colorPalette.text).textColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,d.getColorClassNames)("transparent").bgColor,hoverBgColor:t?(0,c.tremorTwMerge)((0,d.getColorClassNames)(t,m.colorPalette.background).hoverBgColor,"hover:bg-opacity-20 dark:hover:bg-opacity-20"):"hover:bg-tremor-brand-faint dark:hover:bg-dark-tremor-brand-faint",borderColor:t?(0,d.getColorClassNames)(t,m.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand"};case"light":return{textColor:t?(0,d.getColorClassNames)(t,m.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,d.getColorClassNames)(t,m.colorPalette.darkText).hoverTextColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,d.getColorClassNames)("transparent").bgColor,borderColor:"",hoverBorderColor:""}}},p=(0,d.makeClassName)("Button"),h=({loading:e,iconSize:t,iconPosition:r,Icon:l,needMargin:n,transitionStatus:s})=>{let o=n?r===i.HorizontalPositions.Left?(0,c.tremorTwMerge)("-ml-1","mr-1.5"):(0,c.tremorTwMerge)("-mr-1","ml-1.5"):"",d=(0,c.tremorTwMerge)("w-0 h-0"),m={default:d,entering:d,entered:t,exiting:t,exited:d};return e?a.default.createElement(u,{className:(0,c.tremorTwMerge)(p("icon"),"animate-spin shrink-0",o,m.default,m[s]),style:{transition:"width 150ms"}}):a.default.createElement(l,{className:(0,c.tremorTwMerge)(p("icon"),"shrink-0",t,o)})},x=a.default.forwardRef((e,l)=>{let{icon:u,iconPosition:m=i.HorizontalPositions.Left,size:x=i.Sizes.SM,color:b,variant:y="primary",disabled:v,loading:w=!1,loadingText:k,children:C,tooltip:j,className:N}=e,S=(0,t.__rest)(e,["icon","iconPosition","size","color","variant","disabled","loading","loadingText","children","tooltip","className"]),M=w||v,T=void 0!==u||w,O=w&&k,E=!(!C&&!O),P=(0,c.tremorTwMerge)(g[x].height,g[x].width),$="light"!==y?(0,c.tremorTwMerge)("rounded-tremor-default border","shadow-tremor-input","dark:shadow-dark-tremor-input"):"",_=f(y,b),R=("light"!==y?{xs:{paddingX:"px-2.5",paddingY:"py-1.5",fontSize:"text-xs"},sm:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-sm"},md:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-md"},lg:{paddingX:"px-4",paddingY:"py-2.5",fontSize:"text-lg"},xl:{paddingX:"px-4",paddingY:"py-3",fontSize:"text-xl"}}:{xs:{paddingX:"",paddingY:"",fontSize:"text-xs"},sm:{paddingX:"",paddingY:"",fontSize:"text-sm"},md:{paddingX:"",paddingY:"",fontSize:"text-md"},lg:{paddingX:"",paddingY:"",fontSize:"text-lg"},xl:{paddingX:"",paddingY:"",fontSize:"text-xl"}})[x],{tooltipProps:L,getReferenceProps:z}=(0,r.useTooltip)(300),[B,D]=(({enter:e=!0,exit:t=!0,preEnter:r,preExit:l,timeout:i,initialEntered:c,mountOnEnter:d,unmountOnExit:u,onStateChange:m}={})=>{let[g,f]=(0,a.useState)(()=>n(c?2:s(d))),p=(0,a.useRef)(g),h=(0,a.useRef)(0),[x,b]="object"==typeof i?[i.enter,i.exit]:[i,i],y=(0,a.useCallback)(()=>{let e=((e,t)=>{switch(e){case 1:case 0:return 2;case 4:case 3:return s(t)}})(p.current._s,u);e&&o(e,f,p,h,m)},[m,u]);return[g,(0,a.useCallback)(a=>{let n=e=>{switch(o(e,f,p,h,m),e){case 1:x>=0&&(h.current=((...e)=>setTimeout(...e))(y,x));break;case 4:b>=0&&(h.current=((...e)=>setTimeout(...e))(y,b));break;case 0:case 3:h.current=((...e)=>setTimeout(...e))(()=>{isNaN(document.body.offsetTop)||n(e+1)},0)}},i=p.current.isEnter;"boolean"!=typeof a&&(a=!i),a?i||n(e?+!r:2):i&&n(t?l?3:4:s(u))},[y,m,e,t,r,l,x,b,u]),y]})({timeout:50});return(0,a.useEffect)(()=>{D(w)},[w]),a.default.createElement("button",Object.assign({ref:(0,d.mergeRefs)([l,L.refs.setReference]),className:(0,c.tremorTwMerge)(p("root"),"shrink-0 inline-flex justify-center items-center group font-medium outline-none",$,R.paddingX,R.paddingY,R.fontSize,_.textColor,_.bgColor,_.borderColor,_.hoverBorderColor,M?"opacity-50 cursor-not-allowed":(0,c.tremorTwMerge)(f(y,b).hoverTextColor,f(y,b).hoverBgColor,f(y,b).hoverBorderColor),N),disabled:M},z,S),a.default.createElement(r.default,Object.assign({text:j},L)),T&&m!==i.HorizontalPositions.Right?a.default.createElement(h,{loading:w,iconSize:P,iconPosition:m,Icon:u,transitionStatus:B.status,needMargin:E}):null,O||C?a.default.createElement("span",{className:(0,c.tremorTwMerge)(p("text"),"text-tremor-default whitespace-nowrap")},O?k:C):null,T&&m===i.HorizontalPositions.Right?a.default.createElement(h,{loading:w,iconSize:P,iconPosition:m,Icon:u,transitionStatus:B.status,needMargin:E}):null)});x.displayName="Button",e.s(["Button",()=>x],994388)},629569,e=>{"use strict";var t=e.i(290571),r=e.i(95779),a=e.i(444755),l=e.i(673706),n=e.i(271645);let s=n.default.forwardRef((e,s)=>{let{color:o,children:i,className:c}=e,d=(0,t.__rest)(e,["color","children","className"]);return n.default.createElement("p",Object.assign({ref:s,className:(0,a.tremorTwMerge)("font-medium text-tremor-title",o?(0,l.getColorClassNames)(o,r.colorPalette.darkText).textColor:"text-tremor-content-strong dark:text-dark-tremor-content-strong",c)},d),i)});s.displayName="Title",e.s(["Title",()=>s],629569)},91874,e=>{"use strict";var t=e.i(931067),r=e.i(209428),a=e.i(211577),l=e.i(392221),n=e.i(703923),s=e.i(343794),o=e.i(914949),i=e.i(271645),c=["prefixCls","className","style","checked","disabled","defaultChecked","type","title","onChange"],d=(0,i.forwardRef)(function(e,d){var u=e.prefixCls,m=void 0===u?"rc-checkbox":u,g=e.className,f=e.style,p=e.checked,h=e.disabled,x=e.defaultChecked,b=e.type,y=void 0===b?"checkbox":b,v=e.title,w=e.onChange,k=(0,n.default)(e,c),C=(0,i.useRef)(null),j=(0,i.useRef)(null),N=(0,o.default)(void 0!==x&&x,{value:p}),S=(0,l.default)(N,2),M=S[0],T=S[1];(0,i.useImperativeHandle)(d,function(){return{focus:function(e){var t;null==(t=C.current)||t.focus(e)},blur:function(){var e;null==(e=C.current)||e.blur()},input:C.current,nativeElement:j.current}});var O=(0,s.default)(m,g,(0,a.default)((0,a.default)({},"".concat(m,"-checked"),M),"".concat(m,"-disabled"),h));return i.createElement("span",{className:O,title:v,style:f,ref:j},i.createElement("input",(0,t.default)({},k,{className:"".concat(m,"-input"),ref:C,onChange:function(t){h||("checked"in e||T(t.target.checked),null==w||w({target:(0,r.default)((0,r.default)({},e),{},{type:y,checked:t.target.checked}),stopPropagation:function(){t.stopPropagation()},preventDefault:function(){t.preventDefault()},nativeEvent:t.nativeEvent}))},disabled:h,checked:!!M,type:y})),i.createElement("span",{className:"".concat(m,"-inner")}))});e.s(["default",0,d])},421512,236836,e=>{"use strict";let t=e.i(271645).default.createContext(null);e.s(["default",0,t],421512),e.i(296059);var r=e.i(915654),a=e.i(183293),l=e.i(246422),n=e.i(838378);function s(e,t){return(e=>{let{checkboxCls:t}=e,l=`${t}-wrapper`;return[{[`${t}-group`]:Object.assign(Object.assign({},(0,a.resetComponent)(e)),{display:"inline-flex",flexWrap:"wrap",columnGap:e.marginXS,[`> ${e.antCls}-row`]:{flex:1}}),[l]:Object.assign(Object.assign({},(0,a.resetComponent)(e)),{display:"inline-flex",alignItems:"baseline",cursor:"pointer","&:after":{display:"inline-block",width:0,overflow:"hidden",content:"'\\a0'"},[`& + ${l}`]:{marginInlineStart:0},[`&${l}-in-form-item`]:{'input[type="checkbox"]':{width:14,height:14}}}),[t]:Object.assign(Object.assign({},(0,a.resetComponent)(e)),{position:"relative",whiteSpace:"nowrap",lineHeight:1,cursor:"pointer",borderRadius:e.borderRadiusSM,alignSelf:"center",[`${t}-input`]:{position:"absolute",inset:0,zIndex:1,cursor:"pointer",opacity:0,margin:0,[`&:focus-visible + ${t}-inner`]:(0,a.genFocusOutline)(e)},[`${t}-inner`]:{boxSizing:"border-box",display:"block",width:e.checkboxSize,height:e.checkboxSize,direction:"ltr",backgroundColor:e.colorBgContainer,border:`${(0,r.unit)(e.lineWidth)} ${e.lineType} ${e.colorBorder}`,borderRadius:e.borderRadiusSM,borderCollapse:"separate",transition:`all ${e.motionDurationSlow}`,"&:after":{boxSizing:"border-box",position:"absolute",top:"50%",insetInlineStart:"25%",display:"table",width:e.calc(e.checkboxSize).div(14).mul(5).equal(),height:e.calc(e.checkboxSize).div(14).mul(8).equal(),border:`${(0,r.unit)(e.lineWidthBold)} solid ${e.colorWhite}`,borderTop:0,borderInlineStart:0,transform:"rotate(45deg) scale(0) translate(-50%,-50%)",opacity:0,content:'""',transition:`all ${e.motionDurationFast} ${e.motionEaseInBack}, opacity ${e.motionDurationFast}`}},"& + span":{paddingInlineStart:e.paddingXS,paddingInlineEnd:e.paddingXS}})},{[` + ${l}:not(${l}-disabled), + ${t}:not(${t}-disabled) + `]:{[`&:hover ${t}-inner`]:{borderColor:e.colorPrimary}},[`${l}:not(${l}-disabled)`]:{[`&:hover ${t}-checked:not(${t}-disabled) ${t}-inner`]:{backgroundColor:e.colorPrimaryHover,borderColor:"transparent"},[`&:hover ${t}-checked:not(${t}-disabled):after`]:{borderColor:e.colorPrimaryHover}}},{[`${t}-checked`]:{[`${t}-inner`]:{backgroundColor:e.colorPrimary,borderColor:e.colorPrimary,"&:after":{opacity:1,transform:"rotate(45deg) scale(1) translate(-50%,-50%)",transition:`all ${e.motionDurationMid} ${e.motionEaseOutBack} ${e.motionDurationFast}`}}},[` + ${l}-checked:not(${l}-disabled), + ${t}-checked:not(${t}-disabled) + `]:{[`&:hover ${t}-inner`]:{backgroundColor:e.colorPrimaryHover,borderColor:"transparent"}}},{[t]:{"&-indeterminate":{"&":{[`${t}-inner`]:{backgroundColor:`${e.colorBgContainer}`,borderColor:`${e.colorBorder}`,"&:after":{top:"50%",insetInlineStart:"50%",width:e.calc(e.fontSizeLG).div(2).equal(),height:e.calc(e.fontSizeLG).div(2).equal(),backgroundColor:e.colorPrimary,border:0,transform:"translate(-50%, -50%) scale(1)",opacity:1,content:'""'}},[`&:hover ${t}-inner`]:{backgroundColor:`${e.colorBgContainer}`,borderColor:`${e.colorPrimary}`}}}}},{[`${l}-disabled`]:{cursor:"not-allowed"},[`${t}-disabled`]:{[`&, ${t}-input`]:{cursor:"not-allowed",pointerEvents:"none"},[`${t}-inner`]:{background:e.colorBgContainerDisabled,borderColor:e.colorBorder,"&:after":{borderColor:e.colorTextDisabled}},"&:after":{display:"none"},"& + span":{color:e.colorTextDisabled},[`&${t}-indeterminate ${t}-inner::after`]:{background:e.colorTextDisabled}}}]})((0,n.mergeToken)(t,{checkboxCls:`.${e}`,checkboxSize:t.controlInteractiveSize}))}let o=(0,l.genStyleHooks)("Checkbox",(e,{prefixCls:t})=>[s(t,e)]);e.s(["default",0,o,"getStyle",()=>s],236836)},681216,e=>{"use strict";var t=e.i(271645),r=e.i(963188);function a(e){let a=t.default.useRef(null),l=()=>{r.default.cancel(a.current),a.current=null};return[()=>{l(),a.current=(0,r.default)(()=>{a.current=null})},t=>{a.current&&(t.stopPropagation(),l()),null==e||e(t)}]}e.s(["default",()=>a])},374276,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),a=e.i(91874),l=e.i(611935),n=e.i(121872),s=e.i(26905),o=e.i(242064),i=e.i(937328),c=e.i(321883),d=e.i(62139),u=e.i(421512),m=e.i(236836),g=e.i(681216),f=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var l=0,a=Object.getOwnPropertySymbols(e);lt.indexOf(a[l])&&Object.prototype.propertyIsEnumerable.call(e,a[l])&&(r[a[l]]=e[a[l]]);return r};let p=t.forwardRef((e,p)=>{var h;let{prefixCls:x,className:b,rootClassName:y,children:v,indeterminate:w=!1,style:k,onMouseEnter:C,onMouseLeave:j,skipGroup:N=!1,disabled:S}=e,M=f(e,["prefixCls","className","rootClassName","children","indeterminate","style","onMouseEnter","onMouseLeave","skipGroup","disabled"]),{getPrefixCls:T,direction:O,checkbox:E}=t.useContext(o.ConfigContext),P=t.useContext(u.default),{isFormItemInput:$}=t.useContext(d.FormItemInputContext),_=t.useContext(i.default),R=null!=(h=(null==P?void 0:P.disabled)||S)?h:_,L=t.useRef(M.value),z=t.useRef(null),B=(0,l.composeRef)(p,z);t.useEffect(()=>{null==P||P.registerValue(M.value)},[]),t.useEffect(()=>{if(!N)return M.value!==L.current&&(null==P||P.cancelValue(L.current),null==P||P.registerValue(M.value),L.current=M.value),()=>null==P?void 0:P.cancelValue(M.value)},[M.value]),t.useEffect(()=>{var e;(null==(e=z.current)?void 0:e.input)&&(z.current.input.indeterminate=w)},[w]);let D=T("checkbox",x),F=(0,c.default)(D),[I,A,H]=(0,m.default)(D,F),q=Object.assign({},M);P&&!N&&(q.onChange=(...e)=>{M.onChange&&M.onChange.apply(M,e),P.toggleOption&&P.toggleOption({label:v,value:M.value})},q.name=P.name,q.checked=P.value.includes(M.value));let V=(0,r.default)(`${D}-wrapper`,{[`${D}-rtl`]:"rtl"===O,[`${D}-wrapper-checked`]:q.checked,[`${D}-wrapper-disabled`]:R,[`${D}-wrapper-in-form-item`]:$},null==E?void 0:E.className,b,y,H,F,A),G=(0,r.default)({[`${D}-indeterminate`]:w},s.TARGET_CLS,A),[K,X]=(0,g.default)(q.onClick);return I(t.createElement(n.default,{component:"Checkbox",disabled:R},t.createElement("label",{className:V,style:Object.assign(Object.assign({},null==E?void 0:E.style),k),onMouseEnter:C,onMouseLeave:j,onClick:K},t.createElement(a.default,Object.assign({},q,{onClick:X,prefixCls:D,className:G,disabled:R,ref:B})),null!=v&&t.createElement("span",{className:`${D}-label`},v))))});var h=e.i(8211),x=e.i(529681),b=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var l=0,a=Object.getOwnPropertySymbols(e);lt.indexOf(a[l])&&Object.prototype.propertyIsEnumerable.call(e,a[l])&&(r[a[l]]=e[a[l]]);return r};let y=t.forwardRef((e,a)=>{let{defaultValue:l,children:n,options:s=[],prefixCls:i,className:d,rootClassName:g,style:f,onChange:y}=e,v=b(e,["defaultValue","children","options","prefixCls","className","rootClassName","style","onChange"]),{getPrefixCls:w,direction:k}=t.useContext(o.ConfigContext),[C,j]=t.useState(v.value||l||[]),[N,S]=t.useState([]);t.useEffect(()=>{"value"in v&&j(v.value||[])},[v.value]);let M=t.useMemo(()=>s.map(e=>"string"==typeof e||"number"==typeof e?{label:e,value:e}:e),[s]),T=e=>{S(t=>t.filter(t=>t!==e))},O=e=>{S(t=>[].concat((0,h.default)(t),[e]))},E=e=>{let t=C.indexOf(e.value),r=(0,h.default)(C);-1===t?r.push(e.value):r.splice(t,1),"value"in v||j(r),null==y||y(r.filter(e=>N.includes(e)).sort((e,t)=>M.findIndex(t=>t.value===e)-M.findIndex(e=>e.value===t)))},P=w("checkbox",i),$=`${P}-group`,_=(0,c.default)(P),[R,L,z]=(0,m.default)(P,_),B=(0,x.default)(v,["value","disabled"]),D=s.length?M.map(e=>t.createElement(p,{prefixCls:P,key:e.value.toString(),disabled:"disabled"in e?e.disabled:v.disabled,value:e.value,checked:C.includes(e.value),onChange:e.onChange,className:(0,r.default)(`${$}-item`,e.className),style:e.style,title:e.title,id:e.id,required:e.required},e.label)):n,F=t.useMemo(()=>({toggleOption:E,value:C,disabled:v.disabled,name:v.name,registerValue:O,cancelValue:T}),[E,C,v.disabled,v.name,O,T]),I=(0,r.default)($,{[`${$}-rtl`]:"rtl"===k},d,g,z,_,L);return R(t.createElement("div",Object.assign({className:I,style:f},B,{ref:a}),t.createElement(u.default.Provider,{value:F},D)))});p.Group=y,p.__ANT_CHECKBOX=!0,e.s(["default",0,p],374276)},536916,e=>{"use strict";var t=e.i(374276);e.s(["Checkbox",()=>t.default])},292639,e=>{"use strict";var t=e.i(764205),r=e.i(266027);let a=(0,e.i(243652).createQueryKeys)("uiSettings");e.s(["useUISettings",0,()=>(0,r.useQuery)({queryKey:a.list({}),queryFn:async()=>await (0,t.getUiSettings)(),staleTime:36e5,gcTime:36e5})])},250980,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v3m0 0v3m0-3h3m-3 0H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z"}))});e.s(["PlusCircleIcon",0,r],250980)},502547,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"}))});e.s(["ChevronRightIcon",0,r],502547)},384767,e=>{"use strict";var t=e.i(843476),r=e.i(599724),a=e.i(271645),l=e.i(389083);let n=a.forwardRef(function(e,t){return a.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:t},e),a.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4m0 5c0 2.21-3.582 4-8 4s-8-1.79-8-4"}))});var s=e.i(764205);let o=function({vectorStores:e,accessToken:o}){let[i,c]=(0,a.useState)([]);return(0,a.useEffect)(()=>{(async()=>{if(o&&0!==e.length)try{let e=await (0,s.vectorStoreListCall)(o);e.data&&c(e.data.map(e=>({vector_store_id:e.vector_store_id,vector_store_name:e.vector_store_name})))}catch(e){console.error("Error fetching vector stores:",e)}})()},[o,e.length]),(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(n,{className:"h-4 w-4 text-blue-600"}),(0,t.jsx)(r.Text,{className:"font-semibold text-gray-900",children:"Vector Stores"}),(0,t.jsx)(l.Badge,{color:"blue",size:"xs",children:e.length})]}),e.length>0?(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:e.map((e,r)=>{let a;return(0,t.jsx)("div",{className:"inline-flex items-center px-3 py-1.5 rounded-lg bg-blue-50 border border-blue-200 text-blue-800 text-sm font-medium",children:(a=i.find(t=>t.vector_store_id===e))?`${a.vector_store_name||a.vector_store_id} (${a.vector_store_id})`:e},r)})}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 border border-gray-200",children:[(0,t.jsx)(n,{className:"h-4 w-4 text-gray-400"}),(0,t.jsx)(r.Text,{className:"text-gray-500 text-sm",children:"No vector stores configured"})]})]})},i=a.forwardRef(function(e,t){return a.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:t},e),a.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01"}))});var c=e.i(871943),d=e.i(502547),u=e.i(592968);let m=function({mcpServers:n,mcpAccessGroups:o=[],mcpToolPermissions:m={},accessToken:g}){let[f,p]=(0,a.useState)([]),[h,x]=(0,a.useState)([]),[b,y]=(0,a.useState)(new Set);(0,a.useEffect)(()=>{(async()=>{if(g&&n.length>0)try{let e=await (0,s.fetchMCPServers)(g);e&&Array.isArray(e)?p(e):e.data&&Array.isArray(e.data)&&p(e.data)}catch(e){console.error("Error fetching MCP servers:",e)}})()},[g,n.length]),(0,a.useEffect)(()=>{(async()=>{if(g&&o.length>0)try{let t=await e.A(601236).then(e=>e.fetchMCPAccessGroups(g));x(Array.isArray(t)?t:t.data||[])}catch(e){console.error("Error fetching MCP access groups:",e)}})()},[g,o.length]);let v=[...n.map(e=>({type:"server",value:e})),...o.map(e=>({type:"accessGroup",value:e}))],w=v.length;return(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(i,{className:"h-4 w-4 text-blue-600"}),(0,t.jsx)(r.Text,{className:"font-semibold text-gray-900",children:"MCP Servers"}),(0,t.jsx)(l.Badge,{color:"blue",size:"xs",children:w})]}),w>0?(0,t.jsx)("div",{className:"max-h-[400px] overflow-y-auto space-y-2 pr-1",children:v.map((e,r)=>{let a="server"===e.type?m[e.value]:void 0,l=a&&a.length>0,n=b.has(e.value);return(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{onClick:()=>{var t;return l&&(t=e.value,void y(e=>{let r=new Set(e);return r.has(t)?r.delete(t):r.add(t),r}))},className:`flex items-center gap-3 py-2 px-3 rounded-lg border border-gray-200 transition-all ${l?"cursor-pointer hover:bg-gray-50 hover:border-gray-300":"bg-white"}`,children:[(0,t.jsx)("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:"server"===e.type?(0,t.jsx)(u.Tooltip,{title:`Full ID: ${e.value}`,placement:"top",children:(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 min-w-0",children:[(0,t.jsx)("span",{className:"inline-block w-1.5 h-1.5 bg-blue-500 rounded-full flex-shrink-0"}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-900 truncate",children:(e=>{let t=f.find(t=>t.server_id===e);if(t){let r=e.length>7?`${e.slice(0,3)}...${e.slice(-4)}`:e;return`${t.alias} (${r})`}return e})(e.value)})]})}):(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 min-w-0",children:[(0,t.jsx)("span",{className:"inline-block w-1.5 h-1.5 bg-green-500 rounded-full flex-shrink-0"}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-900 truncate",children:e.value}),(0,t.jsx)("span",{className:"ml-1 px-1.5 py-0.5 text-[9px] font-semibold text-green-600 bg-green-50 border border-green-200 rounded uppercase tracking-wide flex-shrink-0",children:"Group"})]})}),l&&(0,t.jsxs)("div",{className:"flex items-center gap-1 flex-shrink-0 whitespace-nowrap",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-gray-600",children:a.length}),(0,t.jsx)("span",{className:"text-xs text-gray-500",children:1===a.length?"tool":"tools"}),n?(0,t.jsx)(c.ChevronDownIcon,{className:"h-3.5 w-3.5 text-gray-400 ml-0.5"}):(0,t.jsx)(d.ChevronRightIcon,{className:"h-3.5 w-3.5 text-gray-400 ml-0.5"})]})]}),l&&n&&(0,t.jsx)("div",{className:"ml-4 pl-4 border-l-2 border-blue-200 pb-1",children:(0,t.jsx)("div",{className:"flex flex-wrap gap-1.5",children:a.map((e,r)=>(0,t.jsx)("span",{className:"inline-flex items-center px-2.5 py-1 rounded-lg bg-blue-50 border border-blue-200 text-blue-800 text-xs font-medium",children:e},r))})})]},r)})}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 border border-gray-200",children:[(0,t.jsx)(i,{className:"h-4 w-4 text-gray-400"}),(0,t.jsx)(r.Text,{className:"text-gray-500 text-sm",children:"No MCP servers or access groups configured"})]})]})},g=a.forwardRef(function(e,t){return a.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:t},e),a.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"}))}),f=function({agents:e,agentAccessGroups:n=[],accessToken:o}){let[i,c]=(0,a.useState)([]);(0,a.useEffect)(()=>{(async()=>{if(o&&e.length>0)try{let e=await (0,s.getAgentsList)(o);e&&e.agents&&Array.isArray(e.agents)&&c(e.agents)}catch(e){console.error("Error fetching agents:",e)}})()},[o,e.length]);let d=[...e.map(e=>({type:"agent",value:e})),...n.map(e=>({type:"accessGroup",value:e}))],m=d.length;return(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(g,{className:"h-4 w-4 text-purple-600"}),(0,t.jsx)(r.Text,{className:"font-semibold text-gray-900",children:"Agents"}),(0,t.jsx)(l.Badge,{color:"purple",size:"xs",children:m})]}),m>0?(0,t.jsx)("div",{className:"max-h-[400px] overflow-y-auto space-y-2 pr-1",children:d.map((e,r)=>(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsx)("div",{className:"flex items-center gap-3 py-2 px-3 rounded-lg border border-gray-200 bg-white",children:(0,t.jsx)("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:"agent"===e.type?(0,t.jsx)(u.Tooltip,{title:`Full ID: ${e.value}`,placement:"top",children:(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 min-w-0",children:[(0,t.jsx)("span",{className:"inline-block w-1.5 h-1.5 bg-purple-500 rounded-full flex-shrink-0"}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-900 truncate",children:(e=>{let t=i.find(t=>t.agent_id===e);if(t){let r=e.length>7?`${e.slice(0,3)}...${e.slice(-4)}`:e;return`${t.agent_name} (${r})`}return e})(e.value)})]})}):(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 min-w-0",children:[(0,t.jsx)("span",{className:"inline-block w-1.5 h-1.5 bg-green-500 rounded-full flex-shrink-0"}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-900 truncate",children:e.value}),(0,t.jsx)("span",{className:"ml-1 px-1.5 py-0.5 text-[9px] font-semibold text-green-600 bg-green-50 border border-green-200 rounded uppercase tracking-wide flex-shrink-0",children:"Group"})]})})})},r))}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 border border-gray-200",children:[(0,t.jsx)(g,{className:"h-4 w-4 text-gray-400"}),(0,t.jsx)(r.Text,{className:"text-gray-500 text-sm",children:"No agents or access groups configured"})]})]})};e.s(["default",0,function({objectPermission:e,variant:a="card",className:l="",accessToken:n}){let s=e?.vector_stores||[],i=e?.mcp_servers||[],c=e?.mcp_access_groups||[],d=e?.mcp_tool_permissions||{},u=e?.agents||[],g=e?.agent_access_groups||[],p=(0,t.jsxs)("div",{className:"card"===a?"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6":"space-y-4",children:[(0,t.jsx)(o,{vectorStores:s,accessToken:n}),(0,t.jsx)(m,{mcpServers:i,mcpAccessGroups:c,mcpToolPermissions:d,accessToken:n}),(0,t.jsx)(f,{agents:u,agentAccessGroups:g,accessToken:n})]});return"card"===a?(0,t.jsxs)("div",{className:`bg-white border border-gray-200 rounded-lg p-6 ${l}`,children:[(0,t.jsx)("div",{className:"flex items-center gap-2 mb-6",children:(0,t.jsxs)("div",{children:[(0,t.jsx)(r.Text,{className:"font-semibold text-gray-900",children:"Object Permissions"}),(0,t.jsx)(r.Text,{className:"text-xs text-gray-500",children:"Access control for Vector Stores and MCP Servers"})]})}),p]}):(0,t.jsxs)("div",{className:`${l}`,children:[(0,t.jsx)(r.Text,{className:"font-medium text-gray-900 mb-3",children:"Object Permissions"}),p]})}],384767)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/0bd654557fbb50e9.js b/litellm/proxy/_experimental/out/_next/static/chunks/0bd654557fbb50e9.js deleted file mode 100644 index 57fabf81164..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/0bd654557fbb50e9.js +++ /dev/null @@ -1 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,207670,e=>{"use strict";function r(){for(var e,r,o=0,t="",l=arguments.length;or,"default",0,r])},115504,e=>{"use strict";var r=e.i(207670);let o=e=>"boolean"==typeof e?`${e}`:0===e?"0":e,t=e=>{let t=function(){for(var o,t,l=arguments.length,a=Array(l),n=0;n{let o=Object.fromEntries(Object.entries(e||{}).filter(e=>{let[r]=e;return!["class","className"].includes(r)}));return t(r.map(e=>e(o)),null==e?void 0:e.class,null==e?void 0:e.className)}},cva:e=>r=>{var l;if((null==e?void 0:e.variants)==null)return t(null==e?void 0:e.base,null==r?void 0:r.class,null==r?void 0:r.className);let{variants:a,defaultVariants:n}=e,s=Object.keys(a).map(e=>{let t=null==r?void 0:r[e],l=null==n?void 0:n[e],s=o(t)||o(l);return a[e][s]}),i={...n,...r&&Object.entries(r).reduce((e,r)=>{let[o,t]=r;return void 0===t?e:{...e,[o]:t}},{})},d=null==e||null==(l=e.compoundVariants)?void 0:l.reduce((e,r)=>{let{class:o,className:t,...l}=r;return Object.entries(l).every(e=>{let[r,o]=e,t=i[r];return Array.isArray(o)?o.includes(t):t===o})?[...e,o,t]:e},[]);return t(null==e?void 0:e.base,s,d,null==r?void 0:r.class,null==r?void 0:r.className)},cx:t}},{compose:l,cva:a,cx:n}=t(),s=(e=new Map,r=null,o)=>({nextPart:e,validators:r,classGroupId:o}),i=[],d=(e,r,o)=>{if(0==e.length-r)return o.classGroupId;let t=e[r],l=o.nextPart.get(t);if(l){let o=d(e,r+1,l);if(o)return o}let a=o.validators;if(null===a)return;let n=0===r?e.join("-"):e.slice(r).join("-"),s=a.length;for(let e=0;e{let o=s();for(let t in e)m(e[t],o,t,r);return o},m=(e,r,o,t)=>{let l=e.length;for(let a=0;a{"string"==typeof e?u(e,r,o):"function"==typeof e?b(e,r,o,t):f(e,r,o,t)},u=(e,r,o)=>{(""===e?r:g(r,e)).classGroupId=o},b=(e,r,o,t)=>{h(e)?m(e(t),r,o,t):(null===r.validators&&(r.validators=[]),r.validators.push({classGroupId:o,validator:e}))},f=(e,r,o,t)=>{let l=Object.entries(e),a=l.length;for(let e=0;e{let o=e,t=r.split("-"),l=t.length;for(let e=0;e"isThemeGetter"in e&&!0===e.isThemeGetter,k=[],x=(e,r,o,t,l)=>({modifiers:e,hasImportantModifier:r,baseClassName:o,maybePostfixModifierPosition:t,isExternal:l}),v=/\s+/,w=e=>{let r;if("string"==typeof e)return e;let o="";for(let t=0;t{let r=r=>r[e]||y;return r.isThemeGetter=!0,r},j=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,O=/^\((?:(\w[\w-]*):)?(.+)\)$/i,N=/^\d+\/\d+$/,C=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,G=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,A=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,$=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,I=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,T=e=>N.test(e),M=e=>!!e&&!Number.isNaN(Number(e)),W=e=>!!e&&Number.isInteger(Number(e)),P=e=>e.endsWith("%")&&M(e.slice(0,-1)),S=e=>C.test(e),q=()=>!0,B=e=>G.test(e)&&!A.test(e),E=()=>!1,K=e=>$.test(e),R=e=>I.test(e),U=e=>!V(e)&&!Q(e),_=e=>et(e,es,E),V=e=>j.test(e),D=e=>et(e,ei,B),F=e=>et(e,ed,M),H=e=>et(e,ea,E),J=e=>et(e,en,R),L=e=>et(e,em,K),Q=e=>O.test(e),X=e=>el(e,ei),Y=e=>el(e,ec),Z=e=>el(e,ea),ee=e=>el(e,es),er=e=>el(e,en),eo=e=>el(e,em,!0),et=(e,r,o)=>{let t=j.exec(e);return!!t&&(t[1]?r(t[1]):o(t[2]))},el=(e,r,o=!1)=>{let t=O.exec(e);return!!t&&(t[1]?r(t[1]):o)},ea=e=>"position"===e||"percentage"===e,en=e=>"image"===e||"url"===e,es=e=>"length"===e||"size"===e||"bg-size"===e,ei=e=>"length"===e,ed=e=>"number"===e,ec=e=>"family-name"===e,em=e=>"shadow"===e,ep=((e,...r)=>{let o,t,l,a,n=e=>{let r=t(e);if(r)return r;let a=((e,r)=>{let{parseClassName:o,getClassGroupId:t,getConflictingClassGroupIds:l,sortModifiers:a}=r,n=[],s=e.trim().split(v),i="";for(let e=s.length-1;e>=0;e-=1){let r=s[e],{isExternal:d,modifiers:c,hasImportantModifier:m,baseClassName:p,maybePostfixModifierPosition:u}=o(r);if(d){i=r+(i.length>0?" "+i:i);continue}let b=!!u,f=t(b?p.substring(0,u):p);if(!f){if(!b||!(f=t(p))){i=r+(i.length>0?" "+i:i);continue}b=!1}let g=0===c.length?"":1===c.length?c[0]:a(c).join(":"),h=m?g+"!":g,k=h+f;if(n.indexOf(k)>-1)continue;n.push(k);let x=l(f,b);for(let e=0;e0?" "+i:i)}return i})(e,o);return l(e,a),a};return a=s=>{var m;let p;return t=(o={cache:(e=>{if(e<1)return{get:()=>void 0,set:()=>{}};let r=0,o=Object.create(null),t=Object.create(null),l=(l,a)=>{o[l]=a,++r>e&&(r=0,t=o,o=Object.create(null))};return{get(e){let r=o[e];return void 0!==r?r:void 0!==(r=t[e])?(l(e,r),r):void 0},set(e,r){e in o?o[e]=r:l(e,r)}}})((m=r.reduce((e,r)=>r(e),e())).cacheSize),parseClassName:(e=>{let{prefix:r,experimentalParseClassName:o}=e,t=e=>{let r,o=[],t=0,l=0,a=0,n=e.length;for(let s=0;sa?r-a:void 0)};if(r){let e=r+":",o=t;t=r=>r.startsWith(e)?o(r.slice(e.length)):x(k,!1,r,void 0,!0)}if(o){let e=t;t=r=>o({className:r,parseClassName:e})}return t})(m),sortModifiers:(p=new Map,m.orderSensitiveModifiers.forEach((e,r)=>{p.set(e,1e6+r)}),e=>{let r=[],o=[];for(let t=0;t0&&(o.sort(),r.push(...o),o=[]),r.push(l)):o.push(l)}return o.length>0&&(o.sort(),r.push(...o)),r}),...(e=>{let r=(e=>{let{theme:r,classGroups:o}=e;return c(o,r)})(e),{conflictingClassGroups:o,conflictingClassGroupModifiers:t}=e;return{getClassGroupId:e=>{if(e.startsWith("[")&&e.endsWith("]")){var o;let r,t,l;return -1===(o=e).slice(1,-1).indexOf(":")?void 0:(t=(r=o.slice(1,-1)).indexOf(":"),(l=r.slice(0,t))?"arbitrary.."+l:void 0)}let t=e.split("-"),l=+(""===t[0]&&t.length>1);return d(t,l,r)},getConflictingClassGroupIds:(e,r)=>{if(r){let r=t[e],l=o[e];if(r){if(l){let e=Array(l.length+r.length);for(let r=0;ra(((...e)=>{let r,o,t=0,l="";for(;t{let e=z("color"),r=z("font"),o=z("text"),t=z("font-weight"),l=z("tracking"),a=z("leading"),n=z("breakpoint"),s=z("container"),i=z("spacing"),d=z("radius"),c=z("shadow"),m=z("inset-shadow"),p=z("text-shadow"),u=z("drop-shadow"),b=z("blur"),f=z("perspective"),g=z("aspect"),h=z("ease"),k=z("animate"),x=()=>["auto","avoid","all","avoid-page","page","left","right","column"],v=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],w=()=>[...v(),Q,V],y=()=>["auto","hidden","clip","visible","scroll"],j=()=>["auto","contain","none"],O=()=>[Q,V,i],N=()=>[T,"full","auto",...O()],C=()=>[W,"none","subgrid",Q,V],G=()=>["auto",{span:["full",W,Q,V]},W,Q,V],A=()=>[W,"auto",Q,V],$=()=>["auto","min","max","fr",Q,V],I=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],B=()=>["start","end","center","stretch","center-safe","end-safe"],E=()=>["auto",...O()],K=()=>[T,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...O()],R=()=>[e,Q,V],et=()=>[...v(),Z,H,{position:[Q,V]}],el=()=>["no-repeat",{repeat:["","x","y","space","round"]}],ea=()=>["auto","cover","contain",ee,_,{size:[Q,V]}],en=()=>[P,X,D],es=()=>["","none","full",d,Q,V],ei=()=>["",M,X,D],ed=()=>["solid","dashed","dotted","double"],ec=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],em=()=>[M,P,Z,H],ep=()=>["","none",b,Q,V],eu=()=>["none",M,Q,V],eb=()=>["none",M,Q,V],ef=()=>[M,Q,V],eg=()=>[T,"full",...O()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[S],breakpoint:[S],color:[q],container:[S],"drop-shadow":[S],ease:["in","out","in-out"],font:[U],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[S],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[S],shadow:[S],spacing:["px",M],text:[S],"text-shadow":[S],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",T,V,Q,g]}],container:["container"],columns:[{columns:[M,V,Q,s]}],"break-after":[{"break-after":x()}],"break-before":[{"break-before":x()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:w()}],overflow:[{overflow:y()}],"overflow-x":[{"overflow-x":y()}],"overflow-y":[{"overflow-y":y()}],overscroll:[{overscroll:j()}],"overscroll-x":[{"overscroll-x":j()}],"overscroll-y":[{"overscroll-y":j()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:N()}],"inset-x":[{"inset-x":N()}],"inset-y":[{"inset-y":N()}],start:[{start:N()}],end:[{end:N()}],top:[{top:N()}],right:[{right:N()}],bottom:[{bottom:N()}],left:[{left:N()}],visibility:["visible","invisible","collapse"],z:[{z:[W,"auto",Q,V]}],basis:[{basis:[T,"full","auto",s,...O()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[M,T,"auto","initial","none",V]}],grow:[{grow:["",M,Q,V]}],shrink:[{shrink:["",M,Q,V]}],order:[{order:[W,"first","last","none",Q,V]}],"grid-cols":[{"grid-cols":C()}],"col-start-end":[{col:G()}],"col-start":[{"col-start":A()}],"col-end":[{"col-end":A()}],"grid-rows":[{"grid-rows":C()}],"row-start-end":[{row:G()}],"row-start":[{"row-start":A()}],"row-end":[{"row-end":A()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":$()}],"auto-rows":[{"auto-rows":$()}],gap:[{gap:O()}],"gap-x":[{"gap-x":O()}],"gap-y":[{"gap-y":O()}],"justify-content":[{justify:[...I(),"normal"]}],"justify-items":[{"justify-items":[...B(),"normal"]}],"justify-self":[{"justify-self":["auto",...B()]}],"align-content":[{content:["normal",...I()]}],"align-items":[{items:[...B(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...B(),{baseline:["","last"]}]}],"place-content":[{"place-content":I()}],"place-items":[{"place-items":[...B(),"baseline"]}],"place-self":[{"place-self":["auto",...B()]}],p:[{p:O()}],px:[{px:O()}],py:[{py:O()}],ps:[{ps:O()}],pe:[{pe:O()}],pt:[{pt:O()}],pr:[{pr:O()}],pb:[{pb:O()}],pl:[{pl:O()}],m:[{m:E()}],mx:[{mx:E()}],my:[{my:E()}],ms:[{ms:E()}],me:[{me:E()}],mt:[{mt:E()}],mr:[{mr:E()}],mb:[{mb:E()}],ml:[{ml:E()}],"space-x":[{"space-x":O()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":O()}],"space-y-reverse":["space-y-reverse"],size:[{size:K()}],w:[{w:[s,"screen",...K()]}],"min-w":[{"min-w":[s,"screen","none",...K()]}],"max-w":[{"max-w":[s,"screen","none","prose",{screen:[n]},...K()]}],h:[{h:["screen","lh",...K()]}],"min-h":[{"min-h":["screen","lh","none",...K()]}],"max-h":[{"max-h":["screen","lh",...K()]}],"font-size":[{text:["base",o,X,D]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[t,Q,F]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",P,V]}],"font-family":[{font:[Y,V,r]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[l,Q,V]}],"line-clamp":[{"line-clamp":[M,"none",Q,F]}],leading:[{leading:[a,...O()]}],"list-image":[{"list-image":["none",Q,V]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Q,V]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:R()}],"text-color":[{text:R()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ed(),"wavy"]}],"text-decoration-thickness":[{decoration:[M,"from-font","auto",Q,D]}],"text-decoration-color":[{decoration:R()}],"underline-offset":[{"underline-offset":[M,"auto",Q,V]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:O()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Q,V]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Q,V]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:et()}],"bg-repeat":[{bg:el()}],"bg-size":[{bg:ea()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},W,Q,V],radial:["",Q,V],conic:[W,Q,V]},er,J]}],"bg-color":[{bg:R()}],"gradient-from-pos":[{from:en()}],"gradient-via-pos":[{via:en()}],"gradient-to-pos":[{to:en()}],"gradient-from":[{from:R()}],"gradient-via":[{via:R()}],"gradient-to":[{to:R()}],rounded:[{rounded:es()}],"rounded-s":[{"rounded-s":es()}],"rounded-e":[{"rounded-e":es()}],"rounded-t":[{"rounded-t":es()}],"rounded-r":[{"rounded-r":es()}],"rounded-b":[{"rounded-b":es()}],"rounded-l":[{"rounded-l":es()}],"rounded-ss":[{"rounded-ss":es()}],"rounded-se":[{"rounded-se":es()}],"rounded-ee":[{"rounded-ee":es()}],"rounded-es":[{"rounded-es":es()}],"rounded-tl":[{"rounded-tl":es()}],"rounded-tr":[{"rounded-tr":es()}],"rounded-br":[{"rounded-br":es()}],"rounded-bl":[{"rounded-bl":es()}],"border-w":[{border:ei()}],"border-w-x":[{"border-x":ei()}],"border-w-y":[{"border-y":ei()}],"border-w-s":[{"border-s":ei()}],"border-w-e":[{"border-e":ei()}],"border-w-t":[{"border-t":ei()}],"border-w-r":[{"border-r":ei()}],"border-w-b":[{"border-b":ei()}],"border-w-l":[{"border-l":ei()}],"divide-x":[{"divide-x":ei()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":ei()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...ed(),"hidden","none"]}],"divide-style":[{divide:[...ed(),"hidden","none"]}],"border-color":[{border:R()}],"border-color-x":[{"border-x":R()}],"border-color-y":[{"border-y":R()}],"border-color-s":[{"border-s":R()}],"border-color-e":[{"border-e":R()}],"border-color-t":[{"border-t":R()}],"border-color-r":[{"border-r":R()}],"border-color-b":[{"border-b":R()}],"border-color-l":[{"border-l":R()}],"divide-color":[{divide:R()}],"outline-style":[{outline:[...ed(),"none","hidden"]}],"outline-offset":[{"outline-offset":[M,Q,V]}],"outline-w":[{outline:["",M,X,D]}],"outline-color":[{outline:R()}],shadow:[{shadow:["","none",c,eo,L]}],"shadow-color":[{shadow:R()}],"inset-shadow":[{"inset-shadow":["none",m,eo,L]}],"inset-shadow-color":[{"inset-shadow":R()}],"ring-w":[{ring:ei()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:R()}],"ring-offset-w":[{"ring-offset":[M,D]}],"ring-offset-color":[{"ring-offset":R()}],"inset-ring-w":[{"inset-ring":ei()}],"inset-ring-color":[{"inset-ring":R()}],"text-shadow":[{"text-shadow":["none",p,eo,L]}],"text-shadow-color":[{"text-shadow":R()}],opacity:[{opacity:[M,Q,V]}],"mix-blend":[{"mix-blend":[...ec(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ec()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[M]}],"mask-image-linear-from-pos":[{"mask-linear-from":em()}],"mask-image-linear-to-pos":[{"mask-linear-to":em()}],"mask-image-linear-from-color":[{"mask-linear-from":R()}],"mask-image-linear-to-color":[{"mask-linear-to":R()}],"mask-image-t-from-pos":[{"mask-t-from":em()}],"mask-image-t-to-pos":[{"mask-t-to":em()}],"mask-image-t-from-color":[{"mask-t-from":R()}],"mask-image-t-to-color":[{"mask-t-to":R()}],"mask-image-r-from-pos":[{"mask-r-from":em()}],"mask-image-r-to-pos":[{"mask-r-to":em()}],"mask-image-r-from-color":[{"mask-r-from":R()}],"mask-image-r-to-color":[{"mask-r-to":R()}],"mask-image-b-from-pos":[{"mask-b-from":em()}],"mask-image-b-to-pos":[{"mask-b-to":em()}],"mask-image-b-from-color":[{"mask-b-from":R()}],"mask-image-b-to-color":[{"mask-b-to":R()}],"mask-image-l-from-pos":[{"mask-l-from":em()}],"mask-image-l-to-pos":[{"mask-l-to":em()}],"mask-image-l-from-color":[{"mask-l-from":R()}],"mask-image-l-to-color":[{"mask-l-to":R()}],"mask-image-x-from-pos":[{"mask-x-from":em()}],"mask-image-x-to-pos":[{"mask-x-to":em()}],"mask-image-x-from-color":[{"mask-x-from":R()}],"mask-image-x-to-color":[{"mask-x-to":R()}],"mask-image-y-from-pos":[{"mask-y-from":em()}],"mask-image-y-to-pos":[{"mask-y-to":em()}],"mask-image-y-from-color":[{"mask-y-from":R()}],"mask-image-y-to-color":[{"mask-y-to":R()}],"mask-image-radial":[{"mask-radial":[Q,V]}],"mask-image-radial-from-pos":[{"mask-radial-from":em()}],"mask-image-radial-to-pos":[{"mask-radial-to":em()}],"mask-image-radial-from-color":[{"mask-radial-from":R()}],"mask-image-radial-to-color":[{"mask-radial-to":R()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":v()}],"mask-image-conic-pos":[{"mask-conic":[M]}],"mask-image-conic-from-pos":[{"mask-conic-from":em()}],"mask-image-conic-to-pos":[{"mask-conic-to":em()}],"mask-image-conic-from-color":[{"mask-conic-from":R()}],"mask-image-conic-to-color":[{"mask-conic-to":R()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:et()}],"mask-repeat":[{mask:el()}],"mask-size":[{mask:ea()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Q,V]}],filter:[{filter:["","none",Q,V]}],blur:[{blur:ep()}],brightness:[{brightness:[M,Q,V]}],contrast:[{contrast:[M,Q,V]}],"drop-shadow":[{"drop-shadow":["","none",u,eo,L]}],"drop-shadow-color":[{"drop-shadow":R()}],grayscale:[{grayscale:["",M,Q,V]}],"hue-rotate":[{"hue-rotate":[M,Q,V]}],invert:[{invert:["",M,Q,V]}],saturate:[{saturate:[M,Q,V]}],sepia:[{sepia:["",M,Q,V]}],"backdrop-filter":[{"backdrop-filter":["","none",Q,V]}],"backdrop-blur":[{"backdrop-blur":ep()}],"backdrop-brightness":[{"backdrop-brightness":[M,Q,V]}],"backdrop-contrast":[{"backdrop-contrast":[M,Q,V]}],"backdrop-grayscale":[{"backdrop-grayscale":["",M,Q,V]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[M,Q,V]}],"backdrop-invert":[{"backdrop-invert":["",M,Q,V]}],"backdrop-opacity":[{"backdrop-opacity":[M,Q,V]}],"backdrop-saturate":[{"backdrop-saturate":[M,Q,V]}],"backdrop-sepia":[{"backdrop-sepia":["",M,Q,V]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":O()}],"border-spacing-x":[{"border-spacing-x":O()}],"border-spacing-y":[{"border-spacing-y":O()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Q,V]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[M,"initial",Q,V]}],ease:[{ease:["linear","initial",h,Q,V]}],delay:[{delay:[M,Q,V]}],animate:[{animate:["none",k,Q,V]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[f,Q,V]}],"perspective-origin":[{"perspective-origin":w()}],rotate:[{rotate:eu()}],"rotate-x":[{"rotate-x":eu()}],"rotate-y":[{"rotate-y":eu()}],"rotate-z":[{"rotate-z":eu()}],scale:[{scale:eb()}],"scale-x":[{"scale-x":eb()}],"scale-y":[{"scale-y":eb()}],"scale-z":[{"scale-z":eb()}],"scale-3d":["scale-3d"],skew:[{skew:ef()}],"skew-x":[{"skew-x":ef()}],"skew-y":[{"skew-y":ef()}],transform:[{transform:[Q,V,"","none","gpu","cpu"]}],"transform-origin":[{origin:w()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:eg()}],"translate-x":[{"translate-x":eg()}],"translate-y":[{"translate-y":eg()}],"translate-z":[{"translate-z":eg()}],"translate-none":["translate-none"],accent:[{accent:R()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:R()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Q,V]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":O()}],"scroll-mx":[{"scroll-mx":O()}],"scroll-my":[{"scroll-my":O()}],"scroll-ms":[{"scroll-ms":O()}],"scroll-me":[{"scroll-me":O()}],"scroll-mt":[{"scroll-mt":O()}],"scroll-mr":[{"scroll-mr":O()}],"scroll-mb":[{"scroll-mb":O()}],"scroll-ml":[{"scroll-ml":O()}],"scroll-p":[{"scroll-p":O()}],"scroll-px":[{"scroll-px":O()}],"scroll-py":[{"scroll-py":O()}],"scroll-ps":[{"scroll-ps":O()}],"scroll-pe":[{"scroll-pe":O()}],"scroll-pt":[{"scroll-pt":O()}],"scroll-pr":[{"scroll-pr":O()}],"scroll-pb":[{"scroll-pb":O()}],"scroll-pl":[{"scroll-pl":O()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Q,V]}],fill:[{fill:["none",...R()]}],"stroke-w":[{stroke:[M,X,D,F]}],stroke:[{stroke:["none",...R()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}}),{cva:eu,cx:eb,compose:ef}=t({hooks:{onComplete:e=>ep(e)}});e.s(["cx",0,eb],115504)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/0bffe854234d50c4.js b/litellm/proxy/_experimental/out/_next/static/chunks/0bffe854234d50c4.js new file mode 100644 index 00000000000..a2b8809a94a --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/0bffe854234d50c4.js @@ -0,0 +1,8 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,434626,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.createElement("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"}))});e.s(["ExternalLinkIcon",0,l],434626)},902555,e=>{"use strict";var t=e.i(843476),l=e.i(591935),a=e.i(122577),r=e.i(278587),n=e.i(68155),i=e.i(360820),o=e.i(871943),s=e.i(434626),c=e.i(592968),d=e.i(115504),u=e.i(752978);function m({icon:e,onClick:l,className:a,disabled:r,dataTestId:n}){return r?(0,t.jsx)(u.Icon,{icon:e,size:"sm",className:"opacity-50 cursor-not-allowed","data-testid":n}):(0,t.jsx)(u.Icon,{icon:e,size:"sm",onClick:l,className:(0,d.cx)("cursor-pointer",a),"data-testid":n})}let g={Edit:{icon:l.PencilAltIcon,className:"hover:text-blue-600"},Delete:{icon:n.TrashIcon,className:"hover:text-red-600"},Test:{icon:a.PlayIcon,className:"hover:text-blue-600"},Regenerate:{icon:r.RefreshIcon,className:"hover:text-green-600"},Up:{icon:i.ChevronUpIcon,className:"hover:text-blue-600"},Down:{icon:o.ChevronDownIcon,className:"hover:text-blue-600"},Open:{icon:s.ExternalLinkIcon,className:"hover:text-green-600"}};function b({onClick:e,tooltipText:l,disabled:a=!1,disabledTooltipText:r,dataTestId:n,variant:i}){let{icon:o,className:s}=g[i];return(0,t.jsx)(c.Tooltip,{title:a?r:l,children:(0,t.jsx)("span",{children:(0,t.jsx)(m,{icon:o,onClick:e,className:s,disabled:a,dataTestId:n})})})}e.s(["default",()=>b],902555)},122577,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"}),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 12a9 9 0 11-18 0 9 9 0 0118 0z"}))});e.s(["PlayIcon",0,l],122577)},591935,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.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.s(["PencilAltIcon",0,l],591935)},360820,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 15l7-7 7 7"}))});e.s(["ChevronUpIcon",0,l],360820)},871943,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"}))});e.s(["ChevronDownIcon",0,l],871943)},185793,e=>{"use strict";e.i(247167);var t=e.i(271645),l=e.i(343794),a=e.i(242064),r=e.i(529681);let n=e=>{let{prefixCls:a,className:r,style:n,size:i,shape:o}=e,s=(0,l.default)({[`${a}-lg`]:"large"===i,[`${a}-sm`]:"small"===i}),c=(0,l.default)({[`${a}-circle`]:"circle"===o,[`${a}-square`]:"square"===o,[`${a}-round`]:"round"===o}),d=t.useMemo(()=>"number"==typeof i?{width:i,height:i,lineHeight:`${i}px`}:{},[i]);return t.createElement("span",{className:(0,l.default)(a,s,c,r),style:Object.assign(Object.assign({},d),n)})};e.i(296059);var i=e.i(694758),o=e.i(915654),s=e.i(246422),c=e.i(838378);let d=new i.Keyframes("ant-skeleton-loading",{"0%":{backgroundPosition:"100% 50%"},"100%":{backgroundPosition:"0 50%"}}),u=e=>({height:e,lineHeight:(0,o.unit)(e)}),m=e=>Object.assign({width:e},u(e)),g=(e,t)=>Object.assign({width:t(e).mul(5).equal(),minWidth:t(e).mul(5).equal()},u(e)),b=e=>Object.assign({width:e},u(e)),p=(e,t,l)=>{let{skeletonButtonCls:a}=e;return{[`${l}${a}-circle`]:{width:t,minWidth:t,borderRadius:"50%"},[`${l}${a}-round`]:{borderRadius:t}}},f=(e,t)=>Object.assign({width:t(e).mul(2).equal(),minWidth:t(e).mul(2).equal()},u(e)),h=(0,s.genStyleHooks)("Skeleton",e=>{let{componentCls:t,calc:l}=e;return(e=>{let{componentCls:t,skeletonAvatarCls:l,skeletonTitleCls:a,skeletonParagraphCls:r,skeletonButtonCls:n,skeletonInputCls:i,skeletonImageCls:o,controlHeight:s,controlHeightLG:c,controlHeightSM:u,gradientFromColor:h,padding:v,marginSM:x,borderRadius:j,titleHeight:$,blockRadius:y,paragraphLiHeight:w,controlHeightXS:C,paragraphMarginTop:O}=e;return{[t]:{display:"table",width:"100%",[`${t}-header`]:{display:"table-cell",paddingInlineEnd:v,verticalAlign:"top",[l]:Object.assign({display:"inline-block",verticalAlign:"top",background:h},m(s)),[`${l}-circle`]:{borderRadius:"50%"},[`${l}-lg`]:Object.assign({},m(c)),[`${l}-sm`]:Object.assign({},m(u))},[`${t}-content`]:{display:"table-cell",width:"100%",verticalAlign:"top",[a]:{width:"100%",height:$,background:h,borderRadius:y,[`+ ${r}`]:{marginBlockStart:u}},[r]:{padding:0,"> li":{width:"100%",height:w,listStyle:"none",background:h,borderRadius:y,"+ li":{marginBlockStart:C}}},[`${r}> li:last-child:not(:first-child):not(:nth-child(2))`]:{width:"61%"}},[`&-round ${t}-content`]:{[`${a}, ${r} > li`]:{borderRadius:j}}},[`${t}-with-avatar ${t}-content`]:{[a]:{marginBlockStart:x,[`+ ${r}`]:{marginBlockStart:O}}},[`${t}${t}-element`]:Object.assign(Object.assign(Object.assign(Object.assign({display:"inline-block",width:"auto"},(e=>{let{borderRadiusSM:t,skeletonButtonCls:l,controlHeight:a,controlHeightLG:r,controlHeightSM:n,gradientFromColor:i,calc:o}=e;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({[l]:Object.assign({display:"inline-block",verticalAlign:"top",background:i,borderRadius:t,width:o(a).mul(2).equal(),minWidth:o(a).mul(2).equal()},f(a,o))},p(e,a,l)),{[`${l}-lg`]:Object.assign({},f(r,o))}),p(e,r,`${l}-lg`)),{[`${l}-sm`]:Object.assign({},f(n,o))}),p(e,n,`${l}-sm`))})(e)),(e=>{let{skeletonAvatarCls:t,gradientFromColor:l,controlHeight:a,controlHeightLG:r,controlHeightSM:n}=e;return{[t]:Object.assign({display:"inline-block",verticalAlign:"top",background:l},m(a)),[`${t}${t}-circle`]:{borderRadius:"50%"},[`${t}${t}-lg`]:Object.assign({},m(r)),[`${t}${t}-sm`]:Object.assign({},m(n))}})(e)),(e=>{let{controlHeight:t,borderRadiusSM:l,skeletonInputCls:a,controlHeightLG:r,controlHeightSM:n,gradientFromColor:i,calc:o}=e;return{[a]:Object.assign({display:"inline-block",verticalAlign:"top",background:i,borderRadius:l},g(t,o)),[`${a}-lg`]:Object.assign({},g(r,o)),[`${a}-sm`]:Object.assign({},g(n,o))}})(e)),(e=>{let{skeletonImageCls:t,imageSizeBase:l,gradientFromColor:a,borderRadiusSM:r,calc:n}=e;return{[t]:Object.assign(Object.assign({display:"inline-flex",alignItems:"center",justifyContent:"center",verticalAlign:"middle",background:a,borderRadius:r},b(n(l).mul(2).equal())),{[`${t}-path`]:{fill:"#bfbfbf"},[`${t}-svg`]:Object.assign(Object.assign({},b(l)),{maxWidth:n(l).mul(4).equal(),maxHeight:n(l).mul(4).equal()}),[`${t}-svg${t}-svg-circle`]:{borderRadius:"50%"}}),[`${t}${t}-circle`]:{borderRadius:"50%"}}})(e)),[`${t}${t}-block`]:{width:"100%",[n]:{width:"100%"},[i]:{width:"100%"}},[`${t}${t}-active`]:{[` + ${a}, + ${r} > li, + ${l}, + ${n}, + ${i}, + ${o} + `]:Object.assign({},{background:e.skeletonLoadingBackground,backgroundSize:"400% 100%",animationName:d,animationDuration:e.skeletonLoadingMotionDuration,animationTimingFunction:"ease",animationIterationCount:"infinite"})}}})((0,c.mergeToken)(e,{skeletonAvatarCls:`${t}-avatar`,skeletonTitleCls:`${t}-title`,skeletonParagraphCls:`${t}-paragraph`,skeletonButtonCls:`${t}-button`,skeletonInputCls:`${t}-input`,skeletonImageCls:`${t}-image`,imageSizeBase:l(e.controlHeight).mul(1.5).equal(),borderRadius:100,skeletonLoadingBackground:`linear-gradient(90deg, ${e.gradientFromColor} 25%, ${e.gradientToColor} 37%, ${e.gradientFromColor} 63%)`,skeletonLoadingMotionDuration:"1.4s"}))},e=>{let{colorFillContent:t,colorFill:l}=e;return{color:t,colorGradientEnd:l,gradientFromColor:t,gradientToColor:l,titleHeight:e.controlHeight/2,blockRadius:e.borderRadiusSM,paragraphMarginTop:e.marginLG+e.marginXXS,paragraphLiHeight:e.controlHeight/2}},{deprecatedTokens:[["color","gradientFromColor"],["colorGradientEnd","gradientToColor"]]}),v=e=>{let{prefixCls:a,className:r,style:n,rows:i=0}=e,o=Array.from({length:i}).map((l,a)=>t.createElement("li",{key:a,style:{width:((e,t)=>{let{width:l,rows:a=2}=t;return Array.isArray(l)?l[e]:a-1===e?l:void 0})(a,e)}}));return t.createElement("ul",{className:(0,l.default)(a,r),style:n},o)},x=({prefixCls:e,className:a,width:r,style:n})=>t.createElement("h3",{className:(0,l.default)(e,a),style:Object.assign({width:r},n)});function j(e){return e&&"object"==typeof e?e:{}}let $=e=>{let{prefixCls:r,loading:i,className:o,rootClassName:s,style:c,children:d,avatar:u=!1,title:m=!0,paragraph:g=!0,active:b,round:p}=e,{getPrefixCls:f,direction:$,className:y,style:w}=(0,a.useComponentConfig)("skeleton"),C=f("skeleton",r),[O,k,N]=h(C);if(i||!("loading"in e)){let e,a,r=!!u,i=!!m,d=!!g;if(r){let l=Object.assign(Object.assign({prefixCls:`${C}-avatar`},i&&!d?{size:"large",shape:"square"}:{size:"large",shape:"circle"}),j(u));e=t.createElement("div",{className:`${C}-header`},t.createElement(n,Object.assign({},l)))}if(i||d){let e,l;if(i){let l=Object.assign(Object.assign({prefixCls:`${C}-title`},!r&&d?{width:"38%"}:r&&d?{width:"50%"}:{}),j(m));e=t.createElement(x,Object.assign({},l))}if(d){let e,a=Object.assign(Object.assign({prefixCls:`${C}-paragraph`},(e={},r&&i||(e.width="61%"),!r&&i?e.rows=3:e.rows=2,e)),j(g));l=t.createElement(v,Object.assign({},a))}a=t.createElement("div",{className:`${C}-content`},e,l)}let f=(0,l.default)(C,{[`${C}-with-avatar`]:r,[`${C}-active`]:b,[`${C}-rtl`]:"rtl"===$,[`${C}-round`]:p},y,o,s,k,N);return O(t.createElement("div",{className:f,style:Object.assign(Object.assign({},w),c)},e,a))}return null!=d?d:null};$.Button=e=>{let{prefixCls:i,className:o,rootClassName:s,active:c,block:d=!1,size:u="default"}=e,{getPrefixCls:m}=t.useContext(a.ConfigContext),g=m("skeleton",i),[b,p,f]=h(g),v=(0,r.default)(e,["prefixCls"]),x=(0,l.default)(g,`${g}-element`,{[`${g}-active`]:c,[`${g}-block`]:d},o,s,p,f);return b(t.createElement("div",{className:x},t.createElement(n,Object.assign({prefixCls:`${g}-button`,size:u},v))))},$.Avatar=e=>{let{prefixCls:i,className:o,rootClassName:s,active:c,shape:d="circle",size:u="default"}=e,{getPrefixCls:m}=t.useContext(a.ConfigContext),g=m("skeleton",i),[b,p,f]=h(g),v=(0,r.default)(e,["prefixCls","className"]),x=(0,l.default)(g,`${g}-element`,{[`${g}-active`]:c},o,s,p,f);return b(t.createElement("div",{className:x},t.createElement(n,Object.assign({prefixCls:`${g}-avatar`,shape:d,size:u},v))))},$.Input=e=>{let{prefixCls:i,className:o,rootClassName:s,active:c,block:d,size:u="default"}=e,{getPrefixCls:m}=t.useContext(a.ConfigContext),g=m("skeleton",i),[b,p,f]=h(g),v=(0,r.default)(e,["prefixCls"]),x=(0,l.default)(g,`${g}-element`,{[`${g}-active`]:c,[`${g}-block`]:d},o,s,p,f);return b(t.createElement("div",{className:x},t.createElement(n,Object.assign({prefixCls:`${g}-input`,size:u},v))))},$.Image=e=>{let{prefixCls:r,className:n,rootClassName:i,style:o,active:s}=e,{getPrefixCls:c}=t.useContext(a.ConfigContext),d=c("skeleton",r),[u,m,g]=h(d),b=(0,l.default)(d,`${d}-element`,{[`${d}-active`]:s},n,i,m,g);return u(t.createElement("div",{className:b},t.createElement("div",{className:(0,l.default)(`${d}-image`,n),style:o},t.createElement("svg",{viewBox:"0 0 1098 1024",xmlns:"http://www.w3.org/2000/svg",className:`${d}-image-svg`},t.createElement("title",null,"Image placeholder"),t.createElement("path",{d:"M365.714286 329.142857q0 45.714286-32.036571 77.677714t-77.677714 32.036571-77.677714-32.036571-32.036571-77.677714 32.036571-77.677714 77.677714-32.036571 77.677714 32.036571 32.036571 77.677714zM950.857143 548.571429l0 256-804.571429 0 0-109.714286 182.857143-182.857143 91.428571 91.428571 292.571429-292.571429zM1005.714286 146.285714l-914.285714 0q-7.460571 0-12.873143 5.412571t-5.412571 12.873143l0 694.857143q0 7.460571 5.412571 12.873143t12.873143 5.412571l914.285714 0q7.460571 0 12.873143-5.412571t5.412571-12.873143l0-694.857143q0-7.460571-5.412571-12.873143t-12.873143-5.412571zM1097.142857 164.571429l0 694.857143q0 37.741714-26.843429 64.585143t-64.585143 26.843429l-914.285714 0q-37.741714 0-64.585143-26.843429t-26.843429-64.585143l0-694.857143q0-37.741714 26.843429-64.585143t64.585143-26.843429l914.285714 0q37.741714 0 64.585143 26.843429t26.843429 64.585143z",className:`${d}-image-path`})))))},$.Node=e=>{let{prefixCls:r,className:n,rootClassName:i,style:o,active:s,children:c}=e,{getPrefixCls:d}=t.useContext(a.ConfigContext),u=d("skeleton",r),[m,g,b]=h(u),p=(0,l.default)(u,`${u}-element`,{[`${u}-active`]:s},g,n,i,b);return m(t.createElement("div",{className:p},t.createElement("div",{className:(0,l.default)(`${u}-image`,n),style:o},c)))},e.s(["default",0,$],185793)},959013,e=>{"use strict";e.i(247167);var t=e.i(931067),l=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8z"}},{tag:"path",attrs:{d:"M192 474h672q8 0 8 8v60q0 8-8 8H160q-8 0-8-8v-60q0-8 8-8z"}}]},name:"plus",theme:"outlined"};var r=e.i(9583),n=l.forwardRef(function(e,n){return l.createElement(r.default,(0,t.default)({},e,{ref:n,icon:a}))});e.s(["default",0,n],959013)},269200,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("Table"),n=l.default.forwardRef((e,n)=>{let{children:i,className:o}=e,s=(0,t.__rest)(e,["children","className"]);return l.default.createElement("div",{className:(0,a.tremorTwMerge)(r("root"),"overflow-auto",o)},l.default.createElement("table",Object.assign({ref:n,className:(0,a.tremorTwMerge)(r("table"),"w-full text-tremor-default","text-tremor-content","dark:text-dark-tremor-content")},s),i))});n.displayName="Table",e.s(["Table",()=>n],269200)},427612,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("TableHead"),n=l.default.forwardRef((e,n)=>{let{children:i,className:o}=e,s=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("thead",Object.assign({ref:n,className:(0,a.tremorTwMerge)(r("root"),"text-left","text-tremor-content","dark:text-dark-tremor-content",o)},s),i))});n.displayName="TableHead",e.s(["TableHead",()=>n],427612)},64848,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("TableHeaderCell"),n=l.default.forwardRef((e,n)=>{let{children:i,className:o}=e,s=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("th",Object.assign({ref:n,className:(0,a.tremorTwMerge)(r("root"),"whitespace-nowrap text-left font-semibold top-0 px-4 py-3.5","text-tremor-content-strong","dark:text-dark-tremor-content-strong",o)},s),i))});n.displayName="TableHeaderCell",e.s(["TableHeaderCell",()=>n],64848)},942232,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("TableBody"),n=l.default.forwardRef((e,n)=>{let{children:i,className:o}=e,s=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("tbody",Object.assign({ref:n,className:(0,a.tremorTwMerge)(r("root"),"align-top divide-y","divide-tremor-border","dark:divide-dark-tremor-border",o)},s),i))});n.displayName="TableBody",e.s(["TableBody",()=>n],942232)},496020,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("TableRow"),n=l.default.forwardRef((e,n)=>{let{children:i,className:o}=e,s=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("tr",Object.assign({ref:n,className:(0,a.tremorTwMerge)(r("row"),o)},s),i))});n.displayName="TableRow",e.s(["TableRow",()=>n],496020)},977572,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("TableCell"),n=l.default.forwardRef((e,n)=>{let{children:i,className:o}=e,s=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("td",Object.assign({ref:n,className:(0,a.tremorTwMerge)(r("root"),"align-middle whitespace-nowrap text-left p-4",o)},s),i))});n.displayName="TableCell",e.s(["TableCell",()=>n],977572)},68155,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.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.s(["TrashIcon",0,l],68155)},278587,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",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"}))});e.s(["RefreshIcon",0,l],278587)},207670,e=>{"use strict";function t(){for(var e,t,l=0,a="",r=arguments.length;lt,"default",0,t])},906579,e=>{"use strict";e.i(247167);var t=e.i(271645),l=e.i(343794),a=e.i(361275),r=e.i(702779),n=e.i(763731),i=e.i(242064);e.i(296059);var o=e.i(915654),s=e.i(694758),c=e.i(183293),d=e.i(403541),u=e.i(246422),m=e.i(838378);let g=new s.Keyframes("antStatusProcessing",{"0%":{transform:"scale(0.8)",opacity:.5},"100%":{transform:"scale(2.4)",opacity:0}}),b=new s.Keyframes("antZoomBadgeIn",{"0%":{transform:"scale(0) translate(50%, -50%)",opacity:0},"100%":{transform:"scale(1) translate(50%, -50%)"}}),p=new s.Keyframes("antZoomBadgeOut",{"0%":{transform:"scale(1) translate(50%, -50%)"},"100%":{transform:"scale(0) translate(50%, -50%)",opacity:0}}),f=new s.Keyframes("antNoWrapperZoomBadgeIn",{"0%":{transform:"scale(0)",opacity:0},"100%":{transform:"scale(1)"}}),h=new s.Keyframes("antNoWrapperZoomBadgeOut",{"0%":{transform:"scale(1)"},"100%":{transform:"scale(0)",opacity:0}}),v=new s.Keyframes("antBadgeLoadingCircle",{"0%":{transformOrigin:"50%"},"100%":{transform:"translate(50%, -50%) rotate(360deg)",transformOrigin:"50%"}}),x=e=>{let{fontHeight:t,lineWidth:l,marginXS:a,colorBorderBg:r}=e,n=e.colorTextLightSolid,i=e.colorError,o=e.colorErrorHover;return(0,m.mergeToken)(e,{badgeFontHeight:t,badgeShadowSize:l,badgeTextColor:n,badgeColor:i,badgeColorHover:o,badgeShadowColor:r,badgeProcessingDuration:"1.2s",badgeRibbonOffset:a,badgeRibbonCornerTransform:"scaleY(0.75)",badgeRibbonCornerFilter:"brightness(75%)"})},j=e=>{let{fontSize:t,lineHeight:l,fontSizeSM:a,lineWidth:r}=e;return{indicatorZIndex:"auto",indicatorHeight:Math.round(t*l)-2*r,indicatorHeightSM:t,dotSize:a/2,textFontSize:a,textFontSizeSM:a,textFontWeight:"normal",statusSize:a/2}},$=(0,u.genStyleHooks)("Badge",e=>(e=>{let{componentCls:t,iconCls:l,antCls:a,badgeShadowSize:r,textFontSize:n,textFontSizeSM:i,statusSize:s,dotSize:u,textFontWeight:m,indicatorHeight:x,indicatorHeightSM:j,marginXS:$,calc:y}=e,w=`${a}-scroll-number`,C=(0,d.genPresetColor)(e,(e,{darkColor:l})=>({[`&${t} ${t}-color-${e}`]:{background:l,[`&:not(${t}-count)`]:{color:l},"a:hover &":{background:l}}}));return{[t]:Object.assign(Object.assign(Object.assign(Object.assign({},(0,c.resetComponent)(e)),{position:"relative",display:"inline-block",width:"fit-content",lineHeight:1,[`${t}-count`]:{display:"inline-flex",justifyContent:"center",zIndex:e.indicatorZIndex,minWidth:x,height:x,color:e.badgeTextColor,fontWeight:m,fontSize:n,lineHeight:(0,o.unit)(x),whiteSpace:"nowrap",textAlign:"center",background:e.badgeColor,borderRadius:y(x).div(2).equal(),boxShadow:`0 0 0 ${(0,o.unit)(r)} ${e.badgeShadowColor}`,transition:`background ${e.motionDurationMid}`,a:{color:e.badgeTextColor},"a:hover":{color:e.badgeTextColor},"a:hover &":{background:e.badgeColorHover}},[`${t}-count-sm`]:{minWidth:j,height:j,fontSize:i,lineHeight:(0,o.unit)(j),borderRadius:y(j).div(2).equal()},[`${t}-multiple-words`]:{padding:`0 ${(0,o.unit)(e.paddingXS)}`,bdi:{unicodeBidi:"plaintext"}},[`${t}-dot`]:{zIndex:e.indicatorZIndex,width:u,minWidth:u,height:u,background:e.badgeColor,borderRadius:"100%",boxShadow:`0 0 0 ${(0,o.unit)(r)} ${e.badgeShadowColor}`},[`${t}-count, ${t}-dot, ${w}-custom-component`]:{position:"absolute",top:0,insetInlineEnd:0,transform:"translate(50%, -50%)",transformOrigin:"100% 0%",[`&${l}-spin`]:{animationName:v,animationDuration:"1s",animationIterationCount:"infinite",animationTimingFunction:"linear"}},[`&${t}-status`]:{lineHeight:"inherit",verticalAlign:"baseline",[`${t}-status-dot`]:{position:"relative",top:-1,display:"inline-block",width:s,height:s,verticalAlign:"middle",borderRadius:"50%"},[`${t}-status-success`]:{backgroundColor:e.colorSuccess},[`${t}-status-processing`]:{overflow:"visible",color:e.colorInfo,backgroundColor:e.colorInfo,borderColor:"currentcolor","&::after":{position:"absolute",top:0,insetInlineStart:0,width:"100%",height:"100%",borderWidth:r,borderStyle:"solid",borderColor:"inherit",borderRadius:"50%",animationName:g,animationDuration:e.badgeProcessingDuration,animationIterationCount:"infinite",animationTimingFunction:"ease-in-out",content:'""'}},[`${t}-status-default`]:{backgroundColor:e.colorTextPlaceholder},[`${t}-status-error`]:{backgroundColor:e.colorError},[`${t}-status-warning`]:{backgroundColor:e.colorWarning},[`${t}-status-text`]:{marginInlineStart:$,color:e.colorText,fontSize:e.fontSize}}}),C),{[`${t}-zoom-appear, ${t}-zoom-enter`]:{animationName:b,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack,animationFillMode:"both"},[`${t}-zoom-leave`]:{animationName:p,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack,animationFillMode:"both"},[`&${t}-not-a-wrapper`]:{[`${t}-zoom-appear, ${t}-zoom-enter`]:{animationName:f,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack},[`${t}-zoom-leave`]:{animationName:h,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack},[`&:not(${t}-status)`]:{verticalAlign:"middle"},[`${w}-custom-component, ${t}-count`]:{transform:"none"},[`${w}-custom-component, ${w}`]:{position:"relative",top:"auto",display:"block",transformOrigin:"50% 50%"}},[w]:{overflow:"hidden",transition:`all ${e.motionDurationMid} ${e.motionEaseOutBack}`,[`${w}-only`]:{position:"relative",display:"inline-block",height:x,transition:`all ${e.motionDurationSlow} ${e.motionEaseOutBack}`,WebkitTransformStyle:"preserve-3d",WebkitBackfaceVisibility:"hidden",[`> p${w}-only-unit`]:{height:x,margin:0,WebkitTransformStyle:"preserve-3d",WebkitBackfaceVisibility:"hidden"}},[`${w}-symbol`]:{verticalAlign:"top"}},"&-rtl":{direction:"rtl",[`${t}-count, ${t}-dot, ${w}-custom-component`]:{transform:"translate(-50%, -50%)"}}})}})(x(e)),j),y=(0,u.genStyleHooks)(["Badge","Ribbon"],e=>(e=>{let{antCls:t,badgeFontHeight:l,marginXS:a,badgeRibbonOffset:r,calc:n}=e,i=`${t}-ribbon`,s=`${t}-ribbon-wrapper`,u=(0,d.genPresetColor)(e,(e,{darkColor:t})=>({[`&${i}-color-${e}`]:{background:t,color:t}}));return{[s]:{position:"relative"},[i]:Object.assign(Object.assign(Object.assign(Object.assign({},(0,c.resetComponent)(e)),{position:"absolute",top:a,padding:`0 ${(0,o.unit)(e.paddingXS)}`,color:e.colorPrimary,lineHeight:(0,o.unit)(l),whiteSpace:"nowrap",backgroundColor:e.colorPrimary,borderRadius:e.borderRadiusSM,[`${i}-text`]:{color:e.badgeTextColor},[`${i}-corner`]:{position:"absolute",top:"100%",width:r,height:r,color:"currentcolor",border:`${(0,o.unit)(n(r).div(2).equal())} solid`,transform:e.badgeRibbonCornerTransform,transformOrigin:"top",filter:e.badgeRibbonCornerFilter}}),u),{[`&${i}-placement-end`]:{insetInlineEnd:n(r).mul(-1).equal(),borderEndEndRadius:0,[`${i}-corner`]:{insetInlineEnd:0,borderInlineEndColor:"transparent",borderBlockEndColor:"transparent"}},[`&${i}-placement-start`]:{insetInlineStart:n(r).mul(-1).equal(),borderEndStartRadius:0,[`${i}-corner`]:{insetInlineStart:0,borderBlockEndColor:"transparent",borderInlineStartColor:"transparent"}},"&-rtl":{direction:"rtl"}})}})(x(e)),j),w=e=>{let a,{prefixCls:r,value:n,current:i,offset:o=0}=e;return o&&(a={position:"absolute",top:`${o}00%`,left:0}),t.createElement("span",{style:a,className:(0,l.default)(`${r}-only-unit`,{current:i})},n)},C=e=>{let l,a,{prefixCls:r,count:n,value:i}=e,o=Number(i),s=Math.abs(n),[c,d]=t.useState(o),[u,m]=t.useState(s),g=()=>{d(o),m(s)};if(t.useEffect(()=>{let e=setTimeout(g,1e3);return()=>clearTimeout(e)},[o]),c===o||Number.isNaN(o)||Number.isNaN(c))l=[t.createElement(w,Object.assign({},e,{key:o,current:!0}))],a={transition:"none"};else{l=[];let r=o+10,n=[];for(let e=o;e<=r;e+=1)n.push(e);let i=ue%10===c);l=(i<0?n.slice(0,d+1):n.slice(d)).map((l,a)=>t.createElement(w,Object.assign({},e,{key:l,value:l%10,offset:i<0?a-d:a,current:a===d}))),a={transform:`translateY(${-function(e,t,l){let a=e,r=0;for(;(a+10)%10!==t;)a+=l,r+=l;return r}(c,o,i)}00%)`}}return t.createElement("span",{className:`${r}-only`,style:a,onTransitionEnd:g},l)};var O=function(e,t){var l={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(l[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,a=Object.getOwnPropertySymbols(e);rt.indexOf(a[r])&&Object.prototype.propertyIsEnumerable.call(e,a[r])&&(l[a[r]]=e[a[r]]);return l};let k=t.forwardRef((e,a)=>{let{prefixCls:r,count:o,className:s,motionClassName:c,style:d,title:u,show:m,component:g="sup",children:b}=e,p=O(e,["prefixCls","count","className","motionClassName","style","title","show","component","children"]),{getPrefixCls:f}=t.useContext(i.ConfigContext),h=f("scroll-number",r),v=Object.assign(Object.assign({},p),{"data-show":m,style:d,className:(0,l.default)(h,s,c),title:u}),x=o;if(o&&Number(o)%1==0){let e=String(o).split("");x=t.createElement("bdi",null,e.map((l,a)=>t.createElement(C,{prefixCls:h,count:Number(o),value:l,key:e.length-a})))}return((null==d?void 0:d.borderColor)&&(v.style=Object.assign(Object.assign({},d),{boxShadow:`0 0 0 1px ${d.borderColor} inset`})),b)?(0,n.cloneElement)(b,e=>({className:(0,l.default)(`${h}-custom-component`,null==e?void 0:e.className,c)})):t.createElement(g,Object.assign({},v,{ref:a}),x)});var N=function(e,t){var l={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(l[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,a=Object.getOwnPropertySymbols(e);rt.indexOf(a[r])&&Object.prototype.propertyIsEnumerable.call(e,a[r])&&(l[a[r]]=e[a[r]]);return l};let E=t.forwardRef((e,o)=>{var s,c,d,u,m;let{prefixCls:g,scrollNumberPrefixCls:b,children:p,status:f,text:h,color:v,count:x=null,overflowCount:j=99,dot:y=!1,size:w="default",title:C,offset:O,style:E,className:S,rootClassName:T,classNames:I,styles:R,showZero:M=!1}=e,_=N(e,["prefixCls","scrollNumberPrefixCls","children","status","text","color","count","overflowCount","dot","size","title","offset","style","className","rootClassName","classNames","styles","showZero"]),{getPrefixCls:F,direction:A,badge:B}=t.useContext(i.ConfigContext),z=F("badge",g),[q,P,L]=$(z),H=x>j?`${j}+`:x,D="0"===H||0===H||"0"===h||0===h,W=null===x||D&&!M,U=(null!=f||null!=v)&&W,K=null!=f||!D,V=y&&!D,Z=V?"":H,X=(0,t.useMemo)(()=>((null==Z||""===Z)&&(null==h||""===h)||D&&!M)&&!V,[Z,D,M,V,h]),G=(0,t.useRef)(x);X||(G.current=x);let J=G.current,Q=(0,t.useRef)(Z);X||(Q.current=Z);let Y=Q.current,ee=(0,t.useRef)(V);X||(ee.current=V);let et=(0,t.useMemo)(()=>{if(!O)return Object.assign(Object.assign({},null==B?void 0:B.style),E);let e={marginTop:O[1]};return"rtl"===A?e.left=Number.parseInt(O[0],10):e.right=-Number.parseInt(O[0],10),Object.assign(Object.assign(Object.assign({},e),null==B?void 0:B.style),E)},[A,O,E,null==B?void 0:B.style]),el=null!=C?C:"string"==typeof J||"number"==typeof J?J:void 0,ea=!X&&(0===h?M:!!h&&!0!==h),er=ea?t.createElement("span",{className:`${z}-status-text`},h):null,en=J&&"object"==typeof J?(0,n.cloneElement)(J,e=>({style:Object.assign(Object.assign({},et),e.style)})):void 0,ei=(0,r.isPresetColor)(v,!1),eo=(0,l.default)(null==I?void 0:I.indicator,null==(s=null==B?void 0:B.classNames)?void 0:s.indicator,{[`${z}-status-dot`]:U,[`${z}-status-${f}`]:!!f,[`${z}-color-${v}`]:ei}),es={};v&&!ei&&(es.color=v,es.background=v);let ec=(0,l.default)(z,{[`${z}-status`]:U,[`${z}-not-a-wrapper`]:!p,[`${z}-rtl`]:"rtl"===A},S,T,null==B?void 0:B.className,null==(c=null==B?void 0:B.classNames)?void 0:c.root,null==I?void 0:I.root,P,L);if(!p&&U&&(h||K||!W)){let e=et.color;return q(t.createElement("span",Object.assign({},_,{className:ec,style:Object.assign(Object.assign(Object.assign({},null==R?void 0:R.root),null==(d=null==B?void 0:B.styles)?void 0:d.root),et)}),t.createElement("span",{className:eo,style:Object.assign(Object.assign(Object.assign({},null==R?void 0:R.indicator),null==(u=null==B?void 0:B.styles)?void 0:u.indicator),es)}),ea&&t.createElement("span",{style:{color:e},className:`${z}-status-text`},h)))}return q(t.createElement("span",Object.assign({ref:o},_,{className:ec,style:Object.assign(Object.assign({},null==(m=null==B?void 0:B.styles)?void 0:m.root),null==R?void 0:R.root)}),p,t.createElement(a.default,{visible:!X,motionName:`${z}-zoom`,motionAppear:!1,motionDeadline:1e3},({className:e})=>{var a,r;let n=F("scroll-number",b),i=ee.current,o=(0,l.default)(null==I?void 0:I.indicator,null==(a=null==B?void 0:B.classNames)?void 0:a.indicator,{[`${z}-dot`]:i,[`${z}-count`]:!i,[`${z}-count-sm`]:"small"===w,[`${z}-multiple-words`]:!i&&Y&&Y.toString().length>1,[`${z}-status-${f}`]:!!f,[`${z}-color-${v}`]:ei}),s=Object.assign(Object.assign(Object.assign({},null==R?void 0:R.indicator),null==(r=null==B?void 0:B.styles)?void 0:r.indicator),et);return v&&!ei&&((s=s||{}).background=v),t.createElement(k,{prefixCls:n,show:!X,motionClassName:e,className:o,count:Y,title:el,style:s,key:"scrollNumber"},en)}),er))});E.Ribbon=e=>{let{className:a,prefixCls:n,style:o,color:s,children:c,text:d,placement:u="end",rootClassName:m}=e,{getPrefixCls:g,direction:b}=t.useContext(i.ConfigContext),p=g("ribbon",n),f=`${p}-wrapper`,[h,v,x]=y(p,f),j=(0,r.isPresetColor)(s,!1),$=(0,l.default)(p,`${p}-placement-${u}`,{[`${p}-rtl`]:"rtl"===b,[`${p}-color-${s}`]:j},a),w={},C={};return s&&!j&&(w.background=s,C.color=s),h(t.createElement("div",{className:(0,l.default)(f,m,v,x)},c,t.createElement("div",{className:(0,l.default)($,v),style:Object.assign(Object.assign({},w),o)},t.createElement("span",{className:`${p}-text`},d),t.createElement("div",{className:`${p}-corner`,style:C}))))},e.s(["Badge",0,E],906579)},738014,e=>{"use strict";var t=e.i(135214),l=e.i(764205),a=e.i(266027);let r=(0,e.i(243652).createQueryKeys)("users");e.s(["useCurrentUser",0,()=>{let{accessToken:e,userId:n,userRole:i}=(0,t.default)();return(0,a.useQuery)({queryKey:r.detail(n),queryFn:async()=>{let t=await (0,l.userInfoCall)(e,n,i,!1,null,null);return console.log(`userInfo: ${JSON.stringify(t)}`),t.user_info},enabled:!!(e&&n&&i)})}])},907308,e=>{"use strict";var t=e.i(843476),l=e.i(271645),a=e.i(212931),r=e.i(808613),n=e.i(464571),i=e.i(199133),o=e.i(592968),s=e.i(213205),c=e.i(374009),d=e.i(764205);e.s(["default",0,({isVisible:e,onCancel:u,onSubmit:m,accessToken:g,title:b="Add Team Member",roles:p=[{label:"admin",value:"admin",description:"Admin role. Can create team keys, add members, and manage settings."},{label:"user",value:"user",description:"User role. Can view team info, but not manage it."}],defaultRole:f="user",teamId:h})=>{let[v]=r.Form.useForm(),[x,j]=(0,l.useState)([]),[$,y]=(0,l.useState)(!1),[w,C]=(0,l.useState)("user_email"),[O,k]=(0,l.useState)(!1),N=async(e,t)=>{if(!e)return void j([]);y(!0);try{let l=new URLSearchParams;if(l.append(t,e),h&&l.append("team_id",h),null==g)return;let a=(await (0,d.userFilterUICall)(g,l)).map(e=>({label:"user_email"===t?`${e.user_email}`:`${e.user_id}`,value:"user_email"===t?e.user_email:e.user_id,user:e}));j(a)}catch(e){console.error("Error fetching users:",e)}finally{y(!1)}},E=(0,l.useCallback)((0,c.default)((e,t)=>N(e,t),300),[]),S=(e,t)=>{C(t),E(e,t)},T=(e,t)=>{let l=t.user;v.setFieldsValue({user_email:l.user_email,user_id:l.user_id,role:v.getFieldValue("role")})},I=async e=>{k(!0);try{await m(e)}finally{k(!1)}};return(0,t.jsx)(a.Modal,{title:b,open:e,onCancel:()=>{v.resetFields(),j([]),u()},footer:null,width:800,maskClosable:!O,children:(0,t.jsxs)(r.Form,{form:v,onFinish:I,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",initialValues:{role:f},children:[(0,t.jsx)(r.Form.Item,{label:"Email",name:"user_email",className:"mb-4",children:(0,t.jsx)(i.Select,{showSearch:!0,className:"w-full",placeholder:"Search by email",filterOption:!1,onSearch:e=>S(e,"user_email"),onSelect:(e,t)=>T(e,t),options:"user_email"===w?x:[],loading:$,allowClear:!0})}),(0,t.jsx)("div",{className:"text-center mb-4",children:"OR"}),(0,t.jsx)(r.Form.Item,{label:"User ID",name:"user_id",className:"mb-4",children:(0,t.jsx)(i.Select,{showSearch:!0,className:"w-full",placeholder:"Search by user ID",filterOption:!1,onSearch:e=>S(e,"user_id"),onSelect:(e,t)=>T(e,t),options:"user_id"===w?x:[],loading:$,allowClear:!0})}),(0,t.jsx)(r.Form.Item,{label:"Member Role",name:"role",className:"mb-4",children:(0,t.jsx)(i.Select,{defaultValue:f,children:p.map(e=>(0,t.jsx)(i.Select.Option,{value:e.value,children:(0,t.jsxs)(o.Tooltip,{title:e.description,children:[(0,t.jsx)("span",{className:"font-medium",children:e.label}),(0,t.jsxs)("span",{className:"ml-2 text-gray-500 text-sm",children:["- ",e.description]})]})},e.value))})}),(0,t.jsx)("div",{className:"text-right mt-4",children:(0,t.jsx)(n.Button,{type:"primary",htmlType:"submit",icon:(0,t.jsx)(s.UserAddOutlined,{}),loading:O,children:O?"Adding...":"Add Member"})})]})})}])},162386,e=>{"use strict";var t=e.i(843476),l=e.i(625901),a=e.i(109799),r=e.i(785242),n=e.i(738014),i=e.i(199133),o=e.i(981339),s=e.i(592968);let c={label:"All Proxy Models",value:"all-proxy-models"},d={label:"No Default Models",value:"no-default-models"},u=[c,d],m={user:({allProxyModels:e,userModels:t,options:l})=>t&&l?.includeUserModels?t:[],team:({allProxyModels:e,selectedOrganization:t,userModels:l})=>t?t.models.includes(c.value)||0===t.models.length?e:e.filter(e=>t.models.includes(e)):e??[],organization:({allProxyModels:e})=>e,global:({allProxyModels:e})=>e};e.s(["ModelSelect",0,e=>{let{teamID:g,organizationID:b,options:p,context:f,dataTestId:h,value:v=[],onChange:x,style:j}=e,{includeUserModels:$,showAllTeamModelsOption:y,showAllProxyModelsOverride:w,includeSpecialOptions:C}=p||{},{data:O,isLoading:k}=(0,l.useAllProxyModels)(),{data:N,isLoading:E}=(0,r.useTeam)(g),{data:S,isLoading:T}=(0,a.useOrganization)(b),{data:I,isLoading:R}=(0,n.useCurrentUser)(),M=e=>u.some(t=>t.value===e),_=v.some(M),F=S?.models.includes(c.value)||S?.models.length===0;if(k||E||T||R)return(0,t.jsx)(o.Skeleton.Input,{active:!0,block:!0});let{wildcard:A,regular:B}=(e=>{let t=[],l=[];for(let a of e)a.endsWith("/*")?t.push(a):l.push(a);return{wildcard:t,regular:l}})(((e,t,l)=>{let a=Array.from(new Map(e.map(e=>[e.id,e])).values()).map(e=>e.id);if(t.options?.showAllProxyModelsOverride)return a;let r=m[t.context];return r?r({allProxyModels:a,...l,options:t.options}):[]})(O?.data??[],e,{selectedTeam:N,selectedOrganization:S,userModels:I?.models}));return(0,t.jsx)(i.Select,{"data-testid":h,value:v,onChange:e=>{let t=e.filter(M);x(t.length>0?[t[t.length-1]]:e)},style:j,options:[C?{label:(0,t.jsx)("span",{children:"Special Options"}),title:"Special Options",options:[...w||F&&C||"global"===f?[{label:(0,t.jsx)("span",{children:"All Proxy Models"}),value:c.value,disabled:v.length>0&&v.some(e=>M(e)&&e!==c.value),key:c.value}]:[],{label:(0,t.jsx)("span",{children:"No Default Models"}),value:d.value,disabled:v.length>0&&v.some(e=>M(e)&&e!==d.value),key:d.value}]}:[],...A.length>0?[{label:(0,t.jsx)("span",{children:"Wildcard Options"}),title:"Wildcard Options",options:A.map(e=>{let l=e.replace("/*",""),a=l.charAt(0).toUpperCase()+l.slice(1);return{label:(0,t.jsx)("span",{children:`All ${a} models`}),value:e,disabled:_}})}]:[],{label:(0,t.jsx)("span",{children:"Models"}),title:"Models",options:B.map(e=>({label:(0,t.jsx)("span",{children:e}),value:e,disabled:_}))}],mode:"multiple",placeholder:"Select Models",allowClear:!0,maxTagCount:"responsive",maxTagPlaceholder:e=>(0,t.jsx)(s.Tooltip,{styles:{root:{pointerEvents:"none"}},title:e.map(({value:e})=>e).join(", "),children:(0,t.jsxs)("span",{children:["+",e.length," more"]})})})}],162386)},276173,e=>{"use strict";var t=e.i(843476),l=e.i(599724),a=e.i(779241),r=e.i(464571),n=e.i(808613),i=e.i(212931),o=e.i(199133),s=e.i(271645),c=e.i(435451);e.s(["default",0,({visible:e,onCancel:d,onSubmit:u,initialData:m,mode:g,config:b})=>{let p,[f]=n.Form.useForm(),[h,v]=(0,s.useState)(!1);console.log("Initial Data:",m),(0,s.useEffect)(()=>{if(e)if("edit"===g&&m){let e={...m,role:m.role||b.defaultRole,max_budget_in_team:m.max_budget_in_team||null,tpm_limit:m.tpm_limit||null,rpm_limit:m.rpm_limit||null};console.log("Setting form values:",e),f.setFieldsValue(e)}else f.resetFields(),f.setFieldsValue({role:b.defaultRole||b.roleOptions[0]?.value})},[e,m,g,f,b.defaultRole,b.roleOptions]);let x=async e=>{try{v(!0);let t=Object.entries(e).reduce((e,[t,l])=>{if("string"==typeof l){let a=l.trim();return""===a&&("max_budget_in_team"===t||"tpm_limit"===t||"rpm_limit"===t)?{...e,[t]:null}:{...e,[t]:a}}return{...e,[t]:l}},{});console.log("Submitting form data:",t),await Promise.resolve(u(t)),f.resetFields()}catch(e){console.error("Form submission error:",e)}finally{v(!1)}};return(0,t.jsx)(i.Modal,{title:b.title||("add"===g?"Add Member":"Edit Member"),open:e,width:1e3,footer:null,onCancel:d,children:(0,t.jsxs)(n.Form,{form:f,onFinish:x,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[b.showEmail&&(0,t.jsx)(n.Form.Item,{label:"Email",name:"user_email",className:"mb-4",rules:[{type:"email",message:"Please enter a valid email!"}],children:(0,t.jsx)(a.TextInput,{placeholder:"user@example.com"})}),b.showEmail&&b.showUserId&&(0,t.jsx)("div",{className:"text-center mb-4",children:(0,t.jsx)(l.Text,{children:"OR"})}),b.showUserId&&(0,t.jsx)(n.Form.Item,{label:"User ID",name:"user_id",className:"mb-4",children:(0,t.jsx)(a.TextInput,{placeholder:"user_123"})}),(0,t.jsx)(n.Form.Item,{label:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{children:"Role"}),"edit"===g&&m&&(0,t.jsxs)("span",{className:"text-gray-500 text-sm",children:["(Current: ",(p=m.role,b.roleOptions.find(e=>e.value===p)?.label||p),")"]})]}),name:"role",className:"mb-4",rules:[{required:!0,message:"Please select a role!"}],children:(0,t.jsx)(o.Select,{children:"edit"===g&&m?[...b.roleOptions.filter(e=>e.value===m.role),...b.roleOptions.filter(e=>e.value!==m.role)].map(e=>(0,t.jsx)(o.Select.Option,{value:e.value,children:e.label},e.value)):b.roleOptions.map(e=>(0,t.jsx)(o.Select.Option,{value:e.value,children:e.label},e.value))})}),b.additionalFields?.map(e=>(0,t.jsx)(n.Form.Item,{label:e.label,name:e.name,className:"mb-4",rules:e.rules,children:(e=>{switch(e.type){case"input":return(0,t.jsx)(a.TextInput,{placeholder:e.placeholder});case"numerical":return(0,t.jsx)(c.default,{step:e.step||1,min:e.min||0,style:{width:"100%"},placeholder:e.placeholder||"Enter a numerical value"});case"select":return(0,t.jsx)(o.Select,{children:e.options?.map(e=>(0,t.jsx)(o.Select.Option,{value:e.value,children:e.label},e.value))});default:return null}})(e)},e.name)),(0,t.jsxs)("div",{className:"text-right mt-6",children:[(0,t.jsx)(r.Button,{onClick:d,className:"mr-2",disabled:h,children:"Cancel"}),(0,t.jsx)(r.Button,{type:"default",htmlType:"submit",loading:h,children:"add"===g?h?"Adding...":"Add Member":h?"Saving...":"Save Changes"})]})]})})}])},294612,e=>{"use strict";var t=e.i(843476),l=e.i(100486),a=e.i(827252),r=e.i(213205),n=e.i(771674),i=e.i(464571),o=e.i(770914),s=e.i(291542),c=e.i(262218),d=e.i(592968),u=e.i(898586),m=e.i(902555);let{Text:g}=u.Typography;function b({members:e,canEdit:u,onEdit:b,onDelete:p,onAddMember:f,roleColumnTitle:h="Role",roleTooltip:v,extraColumns:x=[],showDeleteForMember:j,emptyText:$}){let y=[{title:"User Email",dataIndex:"user_email",key:"user_email",render:e=>(0,t.jsx)(g,{children:e||"-"})},{title:"User ID",dataIndex:"user_id",key:"user_id",render:e=>"default_user_id"===e?(0,t.jsx)(c.Tag,{color:"blue",children:"Default Proxy Admin"}):(0,t.jsx)(g,{children:e||"-"})},{title:v?(0,t.jsxs)(o.Space,{direction:"horizontal",children:[h,(0,t.jsx)(d.Tooltip,{title:v,children:(0,t.jsx)(a.InfoCircleOutlined,{})})]}):h,dataIndex:"role",key:"role",render:e=>(0,t.jsxs)(o.Space,{children:[e?.toLowerCase()==="admin"||e?.toLowerCase()==="org_admin"?(0,t.jsx)(l.CrownOutlined,{}):(0,t.jsx)(n.UserOutlined,{}),(0,t.jsx)(g,{style:{textTransform:"capitalize"},children:e||"-"})]})},...x,{title:"Actions",key:"actions",fixed:"right",width:120,render:(e,l)=>u?(0,t.jsxs)(o.Space,{children:[(0,t.jsx)(m.default,{variant:"Edit",tooltipText:"Edit member",dataTestId:"edit-member",onClick:()=>b(l)}),(!j||j(l))&&(0,t.jsx)(m.default,{variant:"Delete",tooltipText:"Delete member",dataTestId:"delete-member",onClick:()=>p(l)})]}):null}];return(0,t.jsxs)(o.Space,{direction:"vertical",style:{width:"100%"},children:[(0,t.jsxs)("span",{className:"inline-flex text-sm text-gray-700",children:[e.length," Member",1!==e.length?"s":""]}),(0,t.jsx)(s.Table,{columns:y,dataSource:e,rowKey:e=>e.user_id??e.user_email??JSON.stringify(e),pagination:!1,size:"small",scroll:{x:"max-content"},locale:$?{emptyText:$}:void 0}),f&&u&&(0,t.jsx)(i.Button,{icon:(0,t.jsx)(r.UserAddOutlined,{}),type:"primary",onClick:f,children:"Add Member"})]})}e.s(["default",()=>b])}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/0ea9112947894f26.js b/litellm/proxy/_experimental/out/_next/static/chunks/0ea9112947894f26.js new file mode 100644 index 00000000000..48138189033 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/0ea9112947894f26.js @@ -0,0 +1 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,207082,e=>{"use strict";var t=e.i(619273),s=e.i(266027),a=e.i(243652),l=e.i(764205),r=e.i(135214);let i=(0,a.createQueryKeys)("keys"),n=async(e,t,s,a={})=>{try{let r=(0,l.getProxyBaseUrl)(),i=new URLSearchParams(Object.entries({team_id:a.teamID,project_id:a.projectID,organization_id:a.organizationID,key_alias:a.selectedKeyAlias,key_hash:a.keyHash,user_id:a.userID,page:t,size:s,sort_by:a.sortBy,sort_order:a.sortOrder,expand:a.expand,status:a.status,return_full_object:"true",include_team_keys:"true",include_created_by_keys:"true"}).filter(([,e])=>null!=e).map(([e,t])=>[e,String(t)])),n=`${r?`${r}/key/list`:"/key/list"}?${i}`,o=await fetch(n,{method:"GET",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!o.ok){let e=await o.json(),t=(0,l.deriveErrorMessage)(e);throw(0,l.handleError)(t),Error(t)}let c=await o.json();return console.log("/key/list API Response:",c),c}catch(e){throw console.error("Failed to list keys:",e),e}},o=(0,a.createQueryKeys)("deletedKeys");e.s(["keyKeys",0,i,"useDeletedKeys",0,(e,a,l={})=>{let{accessToken:i}=(0,r.default)();return(0,s.useQuery)({queryKey:o.list({page:e,limit:a,...l}),queryFn:async()=>await n(i,e,a,{...l,status:"deleted"}),enabled:!!i,staleTime:3e4,placeholderData:t.keepPreviousData})},"useKeys",0,(e,a,l={})=>{let{accessToken:o}=(0,r.default)();return(0,s.useQuery)({queryKey:i.list({page:e,limit:a,...l}),queryFn:async()=>await n(o,e,a,l),enabled:!!o,staleTime:3e4,placeholderData:t.keepPreviousData})}])},510674,e=>{"use strict";var t=e.i(266027),s=e.i(243652),a=e.i(764205),l=e.i(708347),r=e.i(135214);let i=(0,s.createQueryKeys)("projects"),n=async e=>{let t=(0,a.getProxyBaseUrl)(),s=`${t}/project/list`,l=await fetch(s,{method:"GET",headers:{[(0,a.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!l.ok){let e=await l.json(),t=(0,a.deriveErrorMessage)(e);throw(0,a.handleError)(t),Error(t)}return l.json()};e.s(["projectKeys",0,i,"useProjects",0,()=>{let{accessToken:e,userRole:s}=(0,r.default)();return(0,t.useQuery)({queryKey:i.list({}),queryFn:async()=>n(e),enabled:!!e&&l.all_admin_roles.includes(s||"")})}])},557662,e=>{"use strict";let t="../ui/assets/logos/",s=[{id:"arize",displayName:"Arize",logo:`${t}arize.png`,supports_key_team_logging:!0,dynamic_params:{arize_api_key:"password",arize_space_id:"password"},description:"Arize Logging Integration"},{id:"braintrust",displayName:"Braintrust",logo:`${t}braintrust.png`,supports_key_team_logging:!1,dynamic_params:{braintrust_api_key:"password",braintrust_project_name:"text"},description:"Braintrust Logging Integration"},{id:"custom_callback_api",displayName:"Custom Callback API",logo:`${t}custom.svg`,supports_key_team_logging:!0,dynamic_params:{custom_callback_api_url:"text",custom_callback_api_headers:"text"},description:"Custom Callback API Logging Integration"},{id:"datadog",displayName:"Datadog",logo:`${t}datadog.png`,supports_key_team_logging:!1,dynamic_params:{dd_api_key:"password",dd_site:"text"},description:"Datadog Logging Integration"},{id:"lago",displayName:"Lago",logo:`${t}lago.svg`,supports_key_team_logging:!1,dynamic_params:{lago_api_url:"text",lago_api_key:"password"},description:"Lago Billing Logging Integration"},{id:"langfuse",displayName:"Langfuse",logo:`${t}langfuse.png`,supports_key_team_logging:!0,dynamic_params:{langfuse_public_key:"text",langfuse_secret_key:"password",langfuse_host:"text"},description:"Langfuse v2 Logging Integration"},{id:"langfuse_otel",displayName:"Langfuse OTEL",logo:`${t}langfuse.png`,supports_key_team_logging:!0,dynamic_params:{langfuse_public_key:"text",langfuse_secret_key:"password",langfuse_host:"text"},description:"Langfuse v3 OTEL Logging Integration"},{id:"langsmith",displayName:"LangSmith",logo:`${t}langsmith.png`,supports_key_team_logging:!0,dynamic_params:{langsmith_api_key:"password",langsmith_project:"text",langsmith_base_url:"text",langsmith_sampling_rate:"number"},description:"Langsmith Logging Integration"},{id:"openmeter",displayName:"OpenMeter",logo:`${t}openmeter.png`,supports_key_team_logging:!1,dynamic_params:{openmeter_api_key:"password",openmeter_base_url:"text"},description:"OpenMeter Logging Integration"},{id:"otel",displayName:"Open Telemetry",logo:`${t}otel.png`,supports_key_team_logging:!1,dynamic_params:{otel_endpoint:"text",otel_headers:"text"},description:"OpenTelemetry Logging Integration"},{id:"s3",displayName:"S3",logo:`${t}aws.svg`,supports_key_team_logging:!1,dynamic_params:{s3_bucket_name:"text",aws_access_key_id:"password",aws_secret_access_key:"password",aws_region:"text"},description:"S3 Bucket (AWS) Logging Integration"},{id:"SQS",displayName:"SQS",logo:`${t}aws.svg`,supports_key_team_logging:!1,dynamic_params:{sqs_queue_url:"text",aws_access_key_id:"password",aws_secret_access_key:"password",aws_region:"text"},description:"SQS Queue (AWS) Logging Integration"}],a=s.reduce((e,t)=>(e[t.displayName]=t,e),{}),l=s.reduce((e,t)=>(e[t.displayName]=t.id,e),{}),r=s.reduce((e,t)=>(e[t.id]=t.displayName,e),{});e.s(["callbackInfo",0,a,"callback_map",0,l,"mapDisplayToInternalNames",0,e=>e.map(e=>l[e]||e),"mapInternalToDisplayNames",0,e=>e.map(e=>r[e]||e),"reverse_callback_map",0,r])},810757,477386,e=>{"use strict";var t=e.i(271645);let s=t.forwardRef(function(e,s){return t.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:s},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}))});e.s(["CogIcon",0,s],810757);let a=t.forwardRef(function(e,s){return t.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:s},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"}))});e.s(["BanIcon",0,a],477386)},552130,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(199133),l=e.i(764205);e.s(["default",0,({onChange:e,value:r,className:i,accessToken:n,placeholder:o="Select agents",disabled:c=!1})=>{let[d,u]=(0,s.useState)([]),[m,p]=(0,s.useState)([]),[g,h]=(0,s.useState)(!1);(0,s.useEffect)(()=>{(async()=>{if(n){h(!0);try{let e=await (0,l.getAgentsList)(n),t=e?.agents||[];u(t);let s=new Set;t.forEach(e=>{let t=e.agent_access_groups;t&&Array.isArray(t)&&t.forEach(e=>s.add(e))}),p(Array.from(s))}catch(e){console.error("Error fetching agents:",e)}finally{h(!1)}}})()},[n]);let x=[...m.map(e=>({label:e,value:`group:${e}`,isAccessGroup:!0,searchText:`${e} Access Group`})),...d.map(e=>({label:`${e.agent_name||e.agent_id}`,value:e.agent_id,isAccessGroup:!1,searchText:`${e.agent_name||e.agent_id} ${e.agent_id} Agent`}))],y=[...r?.agents||[],...(r?.accessGroups||[]).map(e=>`group:${e}`)];return(0,t.jsx)("div",{children:(0,t.jsx)(a.Select,{mode:"multiple",placeholder:o,onChange:t=>{e({agents:t.filter(e=>!e.startsWith("group:")),accessGroups:t.filter(e=>e.startsWith("group:")).map(e=>e.replace("group:",""))})},value:y,loading:g,className:i,allowClear:!0,showSearch:!0,style:{width:"100%"},disabled:c,filterOption:(e,t)=>(x.find(e=>e.value===t?.value)?.searchText||"").toLowerCase().includes(e.toLowerCase()),children:x.map(e=>(0,t.jsx)(a.Select.Option,{value:e.value,label:e.label,children:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[(0,t.jsx)("span",{style:{display:"inline-block",width:8,height:8,borderRadius:"50%",background:e.isAccessGroup?"#52c41a":"#722ed1",flexShrink:0}}),(0,t.jsx)("span",{style:{flex:1},children:e.label}),(0,t.jsx)("span",{style:{color:e.isAccessGroup?"#52c41a":"#722ed1",fontSize:"12px",fontWeight:500,opacity:.8},children:e.isAccessGroup?"Access Group":"Agent"})]})},e.value))})})}])},9314,263147,e=>{"use strict";var t=e.i(843476),s=e.i(199133),a=e.i(981339),l=e.i(645526),r=e.i(599724),i=e.i(266027),n=e.i(243652),o=e.i(764205),c=e.i(708347),d=e.i(135214);let u=(0,n.createQueryKeys)("accessGroups"),m=async e=>{let t=(0,o.getProxyBaseUrl)(),s=`${t}/v1/access_group`,a=await fetch(s,{method:"GET",headers:{[(0,o.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!a.ok){let e=await a.json(),t=(0,o.deriveErrorMessage)(e);throw(0,o.handleError)(t),Error(t)}return a.json()},p=()=>{let{accessToken:e,userRole:t}=(0,d.default)();return(0,i.useQuery)({queryKey:u.list({}),queryFn:async()=>m(e),enabled:!!e&&c.all_admin_roles.includes(t||"")})};e.s(["accessGroupKeys",0,u,"useAccessGroups",0,p],263147),e.s(["default",0,({value:e,onChange:i,placeholder:n="Select access groups",disabled:o=!1,style:c,className:d,showLabel:u=!1,labelText:m="Access Group",allowClear:g=!0})=>{let{data:h,isLoading:x,isError:y}=p();if(x)return(0,t.jsxs)("div",{children:[u&&(0,t.jsxs)(r.Text,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,t.jsx)(l.TeamOutlined,{className:"mr-2"})," ",m]}),(0,t.jsx)(a.Skeleton.Input,{active:!0,block:!0,style:{height:32,...c}})]});let f=(h??[]).map(e=>({label:(0,t.jsxs)("span",{children:[(0,t.jsx)("span",{className:"font-medium",children:e.access_group_name})," ",(0,t.jsxs)("span",{className:"text-gray-400 text-xs",children:["(",e.access_group_id,")"]})]}),value:e.access_group_id,selectedLabel:e.access_group_name,searchText:`${e.access_group_name} ${e.access_group_id}`}));return(0,t.jsxs)("div",{children:[u&&(0,t.jsxs)(r.Text,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,t.jsx)(l.TeamOutlined,{className:"mr-2"})," ",m]}),(0,t.jsx)(s.Select,{mode:"multiple",value:e,placeholder:n,onChange:i,disabled:o,allowClear:g,showSearch:!0,style:{width:"100%",...c},className:`rounded-md ${d??""}`,notFoundContent:y?(0,t.jsx)("span",{className:"text-red-500",children:"Failed to load access groups"}):"No access groups found",filterOption:(e,t)=>(f.find(e=>e.value===t?.value)?.searchText??"").toLowerCase().includes(e.toLowerCase()),optionLabelProp:"selectedLabel",options:f.map(e=>({label:e.label,value:e.value,selectedLabel:e.selectedLabel}))})]})}],9314)},392110,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(199133),l=e.i(592968),r=e.i(312361),i=e.i(790848),n=e.i(536916),o=e.i(827252),c=e.i(779241);let{Option:d}=a.Select;e.s(["default",0,({form:e,autoRotationEnabled:u,onAutoRotationChange:m,rotationInterval:p,onRotationIntervalChange:g,isCreateMode:h=!1,neverExpire:x=!1,onNeverExpireChange:y})=>{let f=p&&!["7d","30d","90d","180d","365d"].includes(p),[_,j]=(0,s.useState)(f),[b,v]=(0,s.useState)(f?p:""),[w,N]=(0,s.useState)(e?.getFieldValue?.("duration")||"");return(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Key Expiry Settings"}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,t.jsx)("span",{children:"Expire Key"}),(0,t.jsx)(l.Tooltip,{title:"Set when this key should expire. Format: 30s (seconds), 30m (minutes), 30h (hours), 30d (days). Leave empty to keep the current expiry unchanged.",children:(0,t.jsx)(o.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})}),!h&&y&&(0,t.jsx)(n.Checkbox,{checked:x,onChange:t=>{let s=t.target.checked;y(s),s&&(N(""),e&&"function"==typeof e.setFieldValue?e.setFieldValue("duration",""):e&&"function"==typeof e.setFieldsValue&&e.setFieldsValue({duration:""}))},className:"ml-2 text-sm font-normal text-gray-600",children:"Never Expire"})]}),(0,t.jsx)(c.TextInput,{name:"duration",placeholder:h?"e.g., 30d or leave empty to never expire":"e.g., 30d",className:"w-full",value:w,onValueChange:t=>{N(t),e&&"function"==typeof e.setFieldValue?e.setFieldValue("duration",t):e&&"function"==typeof e.setFieldsValue&&e.setFieldsValue({duration:t})},disabled:!h&&x})]})]}),(0,t.jsx)(r.Divider,{}),(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Auto-Rotation Settings"}),(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,t.jsx)("span",{children:"Enable Auto-Rotation"}),(0,t.jsx)(l.Tooltip,{title:"Key will automatically regenerate at the specified interval for enhanced security.",children:(0,t.jsx)(o.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})})]}),(0,t.jsx)(i.Switch,{checked:u,onChange:m,size:"default",className:u?"":"bg-gray-400"})]}),u&&(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,t.jsx)("span",{children:"Rotation Interval"}),(0,t.jsx)(l.Tooltip,{title:"How often the key should be automatically rotated. Choose the interval that best fits your security requirements.",children:(0,t.jsx)(o.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)(a.Select,{value:_?"custom":p,onChange:e=>{"custom"===e?j(!0):(j(!1),v(""),g(e))},className:"w-full",placeholder:"Select interval",children:[(0,t.jsx)(d,{value:"7d",children:"7 days"}),(0,t.jsx)(d,{value:"30d",children:"30 days"}),(0,t.jsx)(d,{value:"90d",children:"90 days"}),(0,t.jsx)(d,{value:"180d",children:"180 days"}),(0,t.jsx)(d,{value:"365d",children:"365 days"}),(0,t.jsx)(d,{value:"custom",children:"Custom interval"})]}),_&&(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(c.TextInput,{value:b,onChange:e=>{let t=e.target.value;v(t),g(t)},placeholder:"e.g., 1s, 5m, 2h, 14d"}),(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"Supported formats: seconds (s), minutes (m), hours (h), days (d)"})]})]})]})]}),u&&(0,t.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."})]})]})}])},844565,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(199133),l=e.i(764205);e.s(["default",0,({onChange:e,value:r,className:i,accessToken:n,placeholder:o="Select pass through routes",disabled:c=!1,teamId:d})=>{let[u,m]=(0,s.useState)([]),[p,g]=(0,s.useState)(!1);return(0,s.useEffect)(()=>{(async()=>{if(n){g(!0);try{let e=await (0,l.getPassThroughEndpointsCall)(n,d);if(e.endpoints){let t=e.endpoints.flatMap(e=>{let t=e.path,s=e.methods;return s&&s.length>0?s.map(e=>({label:`${e} ${t}`,value:t})):[{label:t,value:t}]});m(t)}}catch(e){console.error("Error fetching pass through routes:",e)}finally{g(!1)}}})()},[n,d]),(0,t.jsx)(a.Select,{mode:"tags",placeholder:o,onChange:e,value:r,loading:p,className:i,allowClear:!0,options:u,optionFilterProp:"label",showSearch:!0,style:{width:"100%"},disabled:c})}])},939510,e=>{"use strict";var t=e.i(843476),s=e.i(808613),a=e.i(199133),l=e.i(592968),r=e.i(827252);let{Option:i}=a.Select;e.s(["default",0,({type:e,name:n,showDetailedDescriptions:o=!0,className:c="",initialValue:d=null,form:u,onChange:m})=>{let p=e.toUpperCase(),g=e.toLowerCase(),h=`Select 'guaranteed_throughput' to prevent overallocating ${p} limit when the key belongs to a Team with specific ${p} limits.`;return(0,t.jsx)(s.Form.Item,{label:(0,t.jsxs)("span",{children:[p," Rate Limit Type"," ",(0,t.jsx)(l.Tooltip,{title:h,children:(0,t.jsx)(r.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:n,initialValue:d,className:c,children:(0,t.jsx)(a.Select,{defaultValue:o?"default":void 0,placeholder:"Select rate limit type",style:{width:"100%"},optionLabelProp:o?"label":void 0,onChange:e=>{u&&u.setFieldValue(n,e),m&&m(e)},children:o?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(i,{value:"best_effort_throughput",label:"Default",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Default"}),(0,t.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["Best effort throughput - no error if we're overallocating ",g," (Team/Key Limits checked at runtime)."]})]})}),(0,t.jsx)(i,{value:"guaranteed_throughput",label:"Guaranteed throughput",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Guaranteed throughput"}),(0,t.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["Guaranteed throughput - raise an error if we're overallocating ",g," (also checks model-specific limits)"]})]})}),(0,t.jsx)(i,{value:"dynamic",label:"Dynamic",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Dynamic"}),(0,t.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["If the key has a set ",p," (e.g. 2 ",p,") and there are no 429 errors, it can dynamically exceed the limit when the model being called is not erroring."]})]})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(i,{value:"best_effort_throughput",children:"Best effort throughput"}),(0,t.jsx)(i,{value:"guaranteed_throughput",children:"Guaranteed throughput"}),(0,t.jsx)(i,{value:"dynamic",children:"Dynamic"})]})})})}])},75921,e=>{"use strict";var t=e.i(843476),s=e.i(266027),a=e.i(243652),l=e.i(764205),r=e.i(135214);let i=(0,a.createQueryKeys)("mcpAccessGroups");var n=e.i(500727),o=e.i(199133);e.s(["default",0,({onChange:e,value:a,className:c,accessToken:d,placeholder:u="Select MCP servers",disabled:m=!1,teamId:p})=>{let{data:g=[],isLoading:h}=(0,n.useMCPServers)(p),{data:x=[],isLoading:y}=(()=>{let{accessToken:e}=(0,r.default)();return(0,s.useQuery)({queryKey:i.list({}),queryFn:async()=>await (0,l.fetchMCPAccessGroups)(e),enabled:!!e})})(),f=[...x.map(e=>({label:e,value:e,isAccessGroup:!0,searchText:`${e} Access Group`})),...g.map(e=>({label:`${e.server_name||e.server_id} (${e.server_id})`,value:e.server_id,isAccessGroup:!1,searchText:`${e.server_name||e.server_id} ${e.server_id} MCP Server`}))],_=[...a?.servers||[],...a?.accessGroups||[]];return(0,t.jsx)("div",{children:(0,t.jsx)(o.Select,{mode:"multiple",placeholder:u,onChange:t=>{e({servers:t.filter(e=>!x.includes(e)),accessGroups:t.filter(e=>x.includes(e))})},value:_,loading:h||y,className:c,allowClear:!0,showSearch:!0,style:{width:"100%"},disabled:m,filterOption:(e,t)=>(f.find(e=>e.value===t?.value)?.searchText||"").toLowerCase().includes(e.toLowerCase()),children:f.map(e=>(0,t.jsx)(o.Select.Option,{value:e.value,label:e.label,children:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[(0,t.jsx)("span",{style:{display:"inline-block",width:8,height:8,borderRadius:"50%",background:e.isAccessGroup?"#52c41a":"#1890ff",flexShrink:0}}),(0,t.jsx)("span",{style:{flex:1},children:e.label}),(0,t.jsx)("span",{style:{color:e.isAccessGroup?"#52c41a":"#1890ff",fontSize:"12px",fontWeight:500,opacity:.8},children:e.isAccessGroup?"Access Group":"MCP Server"})]})},e.value))})})}],75921)},390605,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(764205),l=e.i(599724),r=e.i(482725),i=e.i(91739),n=e.i(500727),o=e.i(531516),c=e.i(696609);e.s(["default",0,({accessToken:e,selectedServers:d,toolPermissions:u,onChange:m,disabled:p=!1})=>{let{data:g=[]}=(0,n.useMCPServers)(),[h,x]=(0,s.useState)({}),[y,f]=(0,s.useState)({}),[_,j]=(0,s.useState)({}),[b,v]=(0,s.useState)({}),w=(0,s.useRef)(u);(0,s.useEffect)(()=>{w.current=u},[u]);let N=(0,s.useMemo)(()=>0===d.length?[]:g.filter(e=>d.includes(e.server_id)),[g,d]),k=async(e,t)=>{f(t=>({...t,[e]:!0})),j(t=>({...t,[e]:""}));try{let s=await (0,a.listMCPTools)(t,e);if(s.error)j(t=>({...t,[e]:s.message||"Failed to fetch tools"})),x(t=>({...t,[e]:[]}));else{let t=s.tools||[];x(s=>({...s,[e]:t}));let a=w.current;if(!a[e]&&t.length>0){let s=t.filter(e=>"delete"!==(0,c.classifyToolOp)(e.name,e.description||"")).map(e=>e.name);m({...a,[e]:s})}}}catch(t){console.error(`Error fetching tools for server ${e}:`,t),j(t=>({...t,[e]:"Failed to fetch tools"})),x(t=>({...t,[e]:[]}))}finally{f(t=>({...t,[e]:!1}))}};(0,s.useEffect)(()=>{N.forEach(t=>{h[t.server_id]||y[t.server_id]||k(t.server_id,e)})},[N,e]);let S=(e,t)=>{m({...u,[e]:t})};return 0===d.length?null:(0,t.jsx)("div",{className:"space-y-4",children:N.map(e=>{let s=e.server_name||e.alias||e.server_id,a=h[e.server_id]||[],n=u[e.server_id]||[],c=y[e.server_id],d=_[e.server_id],g=b[e.server_id]??"crud";return(0,t.jsxs)("div",{className:"border rounded-lg bg-gray-50",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between p-4 border-b bg-white rounded-t-lg",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(l.Text,{className:"font-semibold text-gray-900",children:s}),e.description&&(0,t.jsx)(l.Text,{className:"text-sm text-gray-500",children:e.description})]}),(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[!p&&a.length>0&&(0,t.jsx)(i.Radio.Group,{value:g,onChange:t=>v(s=>({...s,[e.server_id]:t.target.value})),size:"small",optionType:"button",buttonStyle:"solid",options:[{label:"Risk Groups",value:"crud"},{label:"Flat List",value:"flat"}]}),!p&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("button",{type:"button",className:"text-sm text-blue-600 hover:text-blue-700 font-medium",onClick:()=>{var t;let s;return s=h[t=e.server_id]||[],void m({...u,[t]:s.map(e=>e.name)})},disabled:c,children:"Select All"}),(0,t.jsx)("button",{type:"button",className:"text-sm text-blue-600 hover:text-blue-700 font-medium",onClick:()=>{var t;return t=e.server_id,void m({...u,[t]:[]})},disabled:c,children:"Deselect All"})]})]})]}),(0,t.jsxs)("div",{className:"p-4",children:[c&&(0,t.jsxs)("div",{className:"flex items-center justify-center py-8",children:[(0,t.jsx)(r.Spin,{size:"large"}),(0,t.jsx)(l.Text,{className:"ml-3 text-gray-500",children:"Loading tools..."})]}),d&&!c&&(0,t.jsxs)("div",{className:"p-4 bg-red-50 border border-red-200 rounded-lg text-center",children:[(0,t.jsx)(l.Text,{className:"text-red-600 font-medium",children:"Unable to load tools"}),(0,t.jsx)(l.Text,{className:"text-sm text-red-500 mt-1",children:d})]}),!c&&!d&&a.length>0&&"crud"===g&&(0,t.jsx)(o.default,{tools:a,value:u[e.server_id]?n:void 0,onChange:t=>S(e.server_id,t),readOnly:p}),!c&&!d&&a.length>0&&"flat"===g&&(0,t.jsx)("div",{className:"space-y-2",children:a.map(s=>{let a=n.includes(s.name);return(0,t.jsxs)("div",{className:"flex items-start gap-2",children:[(0,t.jsx)("input",{type:"checkbox",checked:a,onChange:()=>{if(p)return;let t=a?n.filter(e=>e!==s.name):[...n,s.name];S(e.server_id,t)},disabled:p,className:"mt-0.5"}),(0,t.jsx)("div",{className:"flex-1 min-w-0",children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(l.Text,{className:"font-medium text-gray-900",children:s.name}),(0,t.jsxs)(l.Text,{className:"text-sm text-gray-500",children:["- ",s.description||"No description"]})]})})]},s.name)})}),!c&&!d&&0===a.length&&(0,t.jsx)("div",{className:"text-center py-6",children:(0,t.jsx)(l.Text,{className:"text-gray-500",children:"No tools available"})})]})]},e.server_id)})})}])},533882,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(250980),l=e.i(797672),r=e.i(68155),i=e.i(304967),n=e.i(629569),o=e.i(599724),c=e.i(269200),d=e.i(427612),u=e.i(64848),m=e.i(942232),p=e.i(496020),g=e.i(977572),h=e.i(992619),x=e.i(727749);e.s(["default",0,({accessToken:e,initialModelAliases:y={},onAliasUpdate:f,showExampleConfig:_=!0})=>{let[j,b]=(0,s.useState)([]),[v,w]=(0,s.useState)({aliasName:"",targetModel:""}),[N,k]=(0,s.useState)(null);(0,s.useEffect)(()=>{b(Object.entries(y).map(([e,t],s)=>({id:`${s}-${e}`,aliasName:e,targetModel:t})))},[y]);let S=()=>{if(!N)return;if(!N.aliasName||!N.targetModel)return void x.default.fromBackend("Please provide both alias name and target model");if(j.some(e=>e.id!==N.id&&e.aliasName===N.aliasName))return void x.default.fromBackend("An alias with this name already exists");let e=j.map(e=>e.id===N.id?N:e);b(e),k(null);let t={};e.forEach(e=>{t[e.aliasName]=e.targetModel}),f&&f(t),x.default.success("Alias updated successfully")},C=()=>{k(null)},T=j.reduce((e,t)=>(e[t.aliasName]=t.targetModel,e),{});return(0,t.jsxs)("div",{className:"mt-4",children:[(0,t.jsxs)("div",{className:"mb-6",children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium text-gray-700 mb-2",children:"Add New Alias"}),(0,t.jsxs)("div",{className:"grid grid-cols-3 gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-xs text-gray-500 mb-1",children:"Alias Name"}),(0,t.jsx)("input",{type:"text",value:v.aliasName,onChange:e=>w({...v,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,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-xs text-gray-500 mb-1",children:"Target Model"}),(0,t.jsx)(h.default,{accessToken:e,value:v.targetModel,placeholder:"Select target model",onChange:e=>w({...v,targetModel:e}),showLabel:!1})]}),(0,t.jsx)("div",{className:"flex items-end",children:(0,t.jsxs)("button",{onClick:()=>{if(!v.aliasName||!v.targetModel)return void x.default.fromBackend("Please provide both alias name and target model");if(j.some(e=>e.aliasName===v.aliasName))return void x.default.fromBackend("An alias with this name already exists");let e=[...j,{id:`${Date.now()}-${v.aliasName}`,aliasName:v.aliasName,targetModel:v.targetModel}];b(e),w({aliasName:"",targetModel:""});let t={};e.forEach(e=>{t[e.aliasName]=e.targetModel}),f&&f(t),x.default.success("Alias added successfully")},disabled:!v.aliasName||!v.targetModel,className:`flex items-center px-4 py-2 rounded-md text-sm ${!v.aliasName||!v.targetModel?"bg-gray-300 text-gray-500 cursor-not-allowed":"bg-green-600 text-white hover:bg-green-700"}`,children:[(0,t.jsx)(a.PlusCircleIcon,{className:"w-4 h-4 mr-1"}),"Add Alias"]})})]})]}),(0,t.jsx)(o.Text,{className:"text-sm font-medium text-gray-700 mb-2",children:"Manage Existing Aliases"}),(0,t.jsx)("div",{className:"rounded-lg custom-border relative mb-6",children:(0,t.jsx)("div",{className:"overflow-x-auto",children:(0,t.jsxs)(c.Table,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,t.jsx)(d.TableHead,{children:(0,t.jsxs)(p.TableRow,{children:[(0,t.jsx)(u.TableHeaderCell,{className:"py-1 h-8",children:"Alias Name"}),(0,t.jsx)(u.TableHeaderCell,{className:"py-1 h-8",children:"Target Model"}),(0,t.jsx)(u.TableHeaderCell,{className:"py-1 h-8",children:"Actions"})]})}),(0,t.jsxs)(m.TableBody,{children:[j.map(s=>(0,t.jsx)(p.TableRow,{className:"h-8",children:N&&N.id===s.id?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(g.TableCell,{className:"py-0.5",children:(0,t.jsx)("input",{type:"text",value:N.aliasName,onChange:e=>k({...N,aliasName:e.target.value}),className:"w-full px-2 py-1 border border-gray-300 rounded-md text-sm"})}),(0,t.jsx)(g.TableCell,{className:"py-0.5",children:(0,t.jsx)(h.default,{accessToken:e,value:N.targetModel,onChange:e=>k({...N,targetModel:e}),showLabel:!1,style:{height:"32px"}})}),(0,t.jsx)(g.TableCell,{className:"py-0.5 whitespace-nowrap",children:(0,t.jsxs)("div",{className:"flex space-x-2",children:[(0,t.jsx)("button",{onClick:S,className:"text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded hover:bg-blue-100",children:"Save"}),(0,t.jsx)("button",{onClick:C,className:"text-xs bg-gray-50 text-gray-600 px-2 py-1 rounded hover:bg-gray-100",children:"Cancel"})]})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(g.TableCell,{className:"py-0.5 text-sm text-gray-900",children:s.aliasName}),(0,t.jsx)(g.TableCell,{className:"py-0.5 text-sm text-gray-500",children:s.targetModel}),(0,t.jsx)(g.TableCell,{className:"py-0.5 whitespace-nowrap",children:(0,t.jsxs)("div",{className:"flex space-x-2",children:[(0,t.jsx)("button",{onClick:()=>{k({...s})},className:"text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded hover:bg-blue-100",children:(0,t.jsx)(l.PencilIcon,{className:"w-3 h-3"})}),(0,t.jsx)("button",{onClick:()=>{var e;let t,a;return e=s.id,b(t=j.filter(t=>t.id!==e)),a={},void(t.forEach(e=>{a[e.aliasName]=e.targetModel}),f&&f(a),x.default.success("Alias deleted successfully"))},className:"text-xs bg-red-50 text-red-600 px-2 py-1 rounded hover:bg-red-100",children:(0,t.jsx)(r.TrashIcon,{className:"w-3 h-3"})})]})})]})},s.id)),0===j.length&&(0,t.jsx)(p.TableRow,{children:(0,t.jsx)(g.TableCell,{colSpan:3,className:"py-0.5 text-sm text-gray-500 text-center",children:"No aliases added yet. Add a new alias above."})})]})]})})}),_&&(0,t.jsxs)(i.Card,{children:[(0,t.jsx)(n.Title,{className:"mb-4",children:"Configuration Example"}),(0,t.jsx)(o.Text,{className:"text-gray-600 mb-4",children:"Here's how your current aliases would look in the config:"}),(0,t.jsx)("div",{className:"bg-gray-100 rounded-lg p-4 font-mono text-sm",children:(0,t.jsxs)("div",{className:"text-gray-700",children:["model_aliases:",0===Object.keys(T).length?(0,t.jsxs)("span",{className:"text-gray-500",children:[(0,t.jsx)("br",{}),"  # No aliases configured yet"]}):Object.entries(T).map(([e,s])=>(0,t.jsxs)("span",{children:[(0,t.jsx)("br",{}),'  "',e,'": "',s,'"']},e))]})})]})]})}])},266484,e=>{"use strict";var t=e.i(843476),s=e.i(199133),a=e.i(592968),l=e.i(312361),r=e.i(827252),i=e.i(994388),n=e.i(304967),o=e.i(779241),c=e.i(988297),d=e.i(68155),u=e.i(810757),m=e.i(477386),p=e.i(557662),g=e.i(435451);let{Option:h}=s.Select;e.s(["default",0,({value:e=[],onChange:x,disabledCallbacks:y=[],onDisabledCallbacksChange:f})=>{let _=Object.entries(p.callbackInfo).filter(([e,t])=>t.supports_key_team_logging).map(([e,t])=>e),j=Object.keys(p.callbackInfo),b=e=>{x?.(e)},v=(t,s,a)=>{let l=[...e];if("callback_name"===s){let e=p.callback_map[a]||a;l[t]={...l[t],[s]:e,callback_vars:{}}}else l[t]={...l[t],[s]:a};b(l)},w=(t,s,a)=>{let l=[...e];l[t]={...l[t],callback_vars:{...l[t].callback_vars,[s]:a}},b(l)};return(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)(m.BanIcon,{className:"w-5 h-5 text-red-500"}),(0,t.jsx)("span",{className:"text-base font-semibold text-gray-800",children:"Disabled Callbacks"}),(0,t.jsx)(a.Tooltip,{title:"Select callbacks to disable for this key. Disabled callbacks will not receive any logging data.",children:(0,t.jsx)(r.InfoCircleOutlined,{className:"text-gray-400 cursor-help"})})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{className:"text-sm font-medium text-gray-700",children:"Disabled Callbacks"}),(0,t.jsx)(s.Select,{mode:"multiple",placeholder:"Select callbacks to disable",value:y,onChange:e=>{let t=(0,p.mapDisplayToInternalNames)(e);f?.(t)},style:{width:"100%"},optionLabelProp:"label",children:j.map(e=>{let s=p.callbackInfo[e]?.logo,l=p.callbackInfo[e]?.description;return(0,t.jsx)(h,{value:e,label:e,children:(0,t.jsx)(a.Tooltip,{title:l,placement:"right",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[s&&(0,t.jsx)("img",{src:s,alt:e,className:"w-4 h-4 object-contain",onError:t=>{let s=t.target,a=s.parentElement;if(a){let t=document.createElement("div");t.className="w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",t.textContent=e.charAt(0),a.replaceChild(t,s)}}}),(0,t.jsx)("span",{children:e})]})})},e)})}),(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"Select callbacks that should be disabled for this key. These callbacks will not receive any logging data."})]})]}),(0,t.jsx)(l.Divider,{}),(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)(u.CogIcon,{className:"w-5 h-5 text-blue-500"}),(0,t.jsx)("span",{className:"text-base font-semibold text-gray-800",children:"Logging Integrations"}),(0,t.jsx)(a.Tooltip,{title:"Configure callback logging integrations for this team.",children:(0,t.jsx)(r.InfoCircleOutlined,{className:"text-gray-400 cursor-help"})})]}),(0,t.jsx)(i.Button,{variant:"secondary",onClick:()=>{b([...e,{callback_name:"",callback_type:"success",callback_vars:{}}])},icon:c.PlusIcon,size:"sm",className:"hover:border-blue-400 hover:text-blue-500",type:"button",children:"Add Integration"})]}),(0,t.jsx)("div",{className:"space-y-4",children:e.map((l,c)=>{let u=l.callback_name?Object.entries(p.callback_map).find(([e,t])=>t===l.callback_name)?.[0]:void 0,m=u?p.callbackInfo[u]?.logo:null;return(0,t.jsxs)(n.Card,{className:"border border-gray-200 shadow-sm hover:shadow-md transition-shadow duration-200",decoration:"top",decorationColor:"blue",children:[(0,t.jsxs)("div",{className:"flex justify-between items-start mb-4",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[m&&(0,t.jsx)("img",{src:m,alt:u,className:"w-5 h-5 object-contain"}),(0,t.jsxs)("span",{className:"text-sm font-medium",children:[u||"New Integration"," Configuration"]})]}),(0,t.jsx)(i.Button,{variant:"light",onClick:()=>{b(e.filter((e,t)=>t!==c))},icon:d.TrashIcon,size:"xs",color:"red",className:"hover:bg-red-50",type:"button",children:"Remove"})]}),(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{className:"text-sm font-medium text-gray-700",children:"Integration Type"}),(0,t.jsx)(s.Select,{value:u,placeholder:"Select integration",onChange:e=>v(c,"callback_name",e),className:"w-full",optionLabelProp:"label",children:_.map(e=>{let s=p.callbackInfo[e]?.logo,l=p.callbackInfo[e]?.description;return(0,t.jsx)(h,{value:e,label:e,children:(0,t.jsx)(a.Tooltip,{title:l,placement:"right",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[s&&(0,t.jsx)("img",{src:s,alt:e,className:"w-4 h-4 object-contain",onError:t=>{let s=t.target,a=s.parentElement;if(a){let t=document.createElement("div");t.className="w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",t.textContent=e.charAt(0),a.replaceChild(t,s)}}}),(0,t.jsx)("span",{children:e})]})})},e)})})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{className:"text-sm font-medium text-gray-700",children:"Event Type"}),(0,t.jsxs)(s.Select,{value:l.callback_type,onChange:e=>v(c,"callback_type",e),className:"w-full",children:[(0,t.jsx)(h,{value:"success",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-green-500 rounded-full"}),(0,t.jsx)("span",{children:"Success Only"})]})}),(0,t.jsx)(h,{value:"failure",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-red-500 rounded-full"}),(0,t.jsx)("span",{children:"Failure Only"})]})}),(0,t.jsx)(h,{value:"success_and_failure",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)("span",{children:"Success & Failure"})]})})]})]})]}),((e,s)=>{if(!e.callback_name)return null;let l=Object.entries(p.callback_map).find(([t,s])=>s===e.callback_name)?.[0];if(!l)return null;let i=p.callbackInfo[l]?.dynamic_params||{};return 0===Object.keys(i).length?null:(0,t.jsxs)("div",{className:"mt-6 pt-4 border-t border-gray-100",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2 mb-4",children:[(0,t.jsx)("div",{className:"w-3 h-3 bg-blue-100 rounded-full flex items-center justify-center",children:(0,t.jsx)("div",{className:"w-1.5 h-1.5 bg-blue-500 rounded-full"})}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Integration Parameters"})]}),(0,t.jsx)("div",{className:"grid grid-cols-1 gap-4",children:Object.entries(i).map(([l,i])=>(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 capitalize flex items-center space-x-1",children:[(0,t.jsx)("span",{children:l.replace(/_/g," ")}),(0,t.jsx)(a.Tooltip,{title:`Environment variable reference recommended: os.environ/${l.toUpperCase()}`,children:(0,t.jsx)(r.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})}),"password"===i&&(0,t.jsx)("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-800",children:"Sensitive"}),"number"===i&&(0,t.jsx)("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-800",children:"Number"})]}),"number"===i&&(0,t.jsx)("span",{className:"text-xs text-gray-500",children:"Value must be between 0 and 1"}),"number"===i?(0,t.jsx)(g.default,{step:.01,width:400,placeholder:`os.environ/${l.toUpperCase()}`,value:e.callback_vars[l]||"",onChange:e=>w(s,l,e.target.value)}):(0,t.jsx)(o.TextInput,{type:"password"===i?"password":"text",placeholder:`os.environ/${l.toUpperCase()}`,value:e.callback_vars[l]||"",onChange:e=>w(s,l,e.target.value)})]},l))})]})})(l,c)]})]},c)})}),0===e.length&&(0,t.jsxs)("div",{className:"text-center py-12 text-gray-500 border-2 border-dashed border-gray-200 rounded-lg bg-gray-50/50",children:[(0,t.jsx)(u.CogIcon,{className:"w-12 h-12 text-gray-300 mb-3 mx-auto"}),(0,t.jsx)("div",{className:"text-base font-medium mb-1",children:"No logging integrations configured"}),(0,t.jsx)("div",{className:"text-sm text-gray-400",children:'Click "Add Integration" to configure logging for this team'})]})]})}])},651904,e=>{"use strict";var t=e.i(843476),s=e.i(599724),a=e.i(266484);e.s(["default",0,function({value:e,onChange:l,premiumUser:r=!1,disabledCallbacks:i=[],onDisabledCallbacksChange:n}){return r?(0,t.jsx)(a.default,{value:e,onChange:l,disabledCallbacks:i,onDisabledCallbacksChange:n}):(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex flex-wrap gap-2 mb-3",children:[(0,t.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,t.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,t.jsx)("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-lg",children:(0,t.jsxs)(s.Text,{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,t.jsx)("a",{href:"https://www.litellm.ai/#pricing",target:"_blank",rel:"noopener noreferrer",className:"underline",children:"here"}),"."]})})]})}])},460285,575260,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(404206),l=e.i(723731),r=e.i(653824),i=e.i(881073),n=e.i(197647),o=e.i(764205),c=e.i(158392),d=e.i(419470),u=e.i(689020);let m=(0,s.forwardRef)(({accessToken:e,value:m,onChange:p,modelData:g},h)=>{let[x,y]=(0,s.useState)({routerSettings:{},selectedStrategy:null,enableTagFiltering:!1}),[f,_]=(0,s.useState)([]),[j,b]=(0,s.useState)([]),[v,w]=(0,s.useState)([]),[N,k]=(0,s.useState)([]),[S,C]=(0,s.useState)({}),[T,I]=(0,s.useState)({}),A=(0,s.useRef)(!1),L=(0,s.useRef)(null);(0,s.useEffect)(()=>{let e=m?.router_settings?JSON.stringify({routing_strategy:m.router_settings.routing_strategy,fallbacks:m.router_settings.fallbacks,enable_tag_filtering:m.router_settings.enable_tag_filtering}):null;if(A.current&&e===L.current){A.current=!1;return}if(A.current&&e!==L.current&&(A.current=!1),e!==L.current)if(L.current=e,m?.router_settings){let e=m.router_settings,{fallbacks:t,...s}=e;y({routerSettings:s,selectedStrategy:e.routing_strategy||null,enableTagFiltering:e.enable_tag_filtering??!1});let a=e.fallbacks||[];_(a),b(a&&0!==a.length?a.map((e,t)=>{let[s,a]=Object.entries(e)[0];return{id:(t+1).toString(),primaryModel:s||null,fallbackModels:a||[]}}):[{id:"1",primaryModel:null,fallbackModels:[]}])}else y({routerSettings:{},selectedStrategy:null,enableTagFiltering:!1}),_([]),b([{id:"1",primaryModel:null,fallbackModels:[]}])},[m]),(0,s.useEffect)(()=>{e&&(0,o.getRouterSettingsCall)(e).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}}),C(t);let s=e.fields.find(e=>"routing_strategy"===e.field_name);s?.options&&k(s.options),e.routing_strategy_descriptions&&I(e.routing_strategy_descriptions)}})},[e]),(0,s.useEffect)(()=>{e&&(async()=>{try{let t=await (0,u.fetchAvailableModels)(e);w(t)}catch(e){console.error("Error fetching model info for fallbacks:",e)}})()},[e]);let F=()=>{let e=new Set(["allowed_fails","cooldown_time","num_retries","timeout","retry_after"]),t=new Set(["model_group_alias","retry_policy"]),s=Object.fromEntries(Object.entries({...x.routerSettings,enable_tag_filtering:x.enableTagFiltering,routing_strategy:x.selectedStrategy,fallbacks:f.length>0?f:null}).map(([s,a])=>{if("routing_strategy_args"!==s&&"routing_strategy"!==s&&"enable_tag_filtering"!==s&&"fallbacks"!==s){let l=document.querySelector(`input[name="${s}"]`);if(l&&void 0!==l.value&&""!==l.value){let r=((s,a,l)=>{if(null==a)return l;let r=String(a).trim();if(""===r||"null"===r.toLowerCase())return null;if(e.has(s)){let e=Number(r);return Number.isNaN(e)?l:e}if(t.has(s)){if(""===r)return null;try{return JSON.parse(r)}catch{return l}}return"true"===r.toLowerCase()||"false"!==r.toLowerCase()&&r})(s,l.value,a);return[s,r]}}else if("routing_strategy"===s)return[s,x.selectedStrategy];else if("enable_tag_filtering"===s)return[s,x.enableTagFiltering];else if("fallbacks"===s)return[s,f.length>0?f:null];else if("routing_strategy_args"===s&&"latency-based-routing"===x.selectedStrategy){let e=document.querySelector('input[name="lowest_latency_buffer"]'),t=document.querySelector('input[name="ttl"]'),s={};return e?.value&&(s.lowest_latency_buffer=Number(e.value)),t?.value&&(s.ttl=Number(t.value)),["routing_strategy_args",Object.keys(s).length>0?s:null]}return[s,a]}).filter(e=>null!=e)),a=(e,t=!1)=>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:f.length>0?f: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:x.enableTagFiltering,routing_strategy_args:a(s.routing_strategy_args)}};(0,s.useEffect)(()=>{if(!p)return;let e=setTimeout(()=>{A.current=!0,p({router_settings:F()})},100);return()=>clearTimeout(e)},[x,f]);let M=Array.from(new Set(v.map(e=>e.model_group))).sort();return((0,s.useImperativeHandle)(h,()=>({getValue:()=>({router_settings:F()})})),e)?(0,t.jsx)("div",{className:"w-full",children:(0,t.jsxs)(r.TabGroup,{className:"w-full",children:[(0,t.jsxs)(i.TabList,{variant:"line",defaultValue:"1",className:"px-8 pt-4",children:[(0,t.jsx)(n.Tab,{value:"1",children:"Loadbalancing"}),(0,t.jsx)(n.Tab,{value:"2",children:"Fallbacks"})]}),(0,t.jsxs)(l.TabPanels,{className:"px-8 py-6",children:[(0,t.jsx)(a.TabPanel,{children:(0,t.jsx)(c.default,{value:x,onChange:y,routerFieldsMetadata:S,availableRoutingStrategies:N,routingStrategyDescriptions:T})}),(0,t.jsx)(a.TabPanel,{children:(0,t.jsx)(d.FallbackSelectionForm,{groups:j,onGroupsChange:e=>{b(e),_(e.filter(e=>e.primaryModel&&e.fallbackModels.length>0).map(e=>({[e.primaryModel]:e.fallbackModels})))},availableModels:M,maxGroups:5})})]})]})}):null});m.displayName="RouterSettingsAccordion",e.s(["default",0,m],460285);var p=e.i(199133),g=e.i(482725),h=e.i(56456);e.s(["default",0,({projects:e,value:s,onChange:a,disabled:l,loading:r,teamId:i})=>{let n=i?e?.filter(e=>e.team_id===i):e;return(0,t.jsx)(p.Select,{showSearch:!0,placeholder:"Search or select a project",value:s,onChange:a,disabled:l,loading:r,allowClear:!0,notFoundContent:r?(0,t.jsx)(g.Spin,{indicator:(0,t.jsx)(h.LoadingOutlined,{spin:!0}),size:"small"}):void 0,filterOption:(e,t)=>{if(!t)return!1;let s=n?.find(e=>e.project_id===t.key);if(!s)return!1;let a=e.toLowerCase().trim(),l=(s.project_alias||"").toLowerCase(),r=(s.project_id||"").toLowerCase();return l.includes(a)||r.includes(a)},optionFilterProp:"children",children:!r&&n?.map(e=>(0,t.jsxs)(p.Select.Option,{value:e.project_id,children:[(0,t.jsx)("span",{className:"font-medium",children:e.project_alias||e.project_id})," ",(0,t.jsxs)("span",{className:"text-gray-500",children:["(",e.project_id,")"]})]},e.project_id))})}],575260)},702597,364769,e=>{"use strict";var t=e.i(843476),s=e.i(207082),a=e.i(510674),l=e.i(292639),r=e.i(135214),i=e.i(500330),n=e.i(827252),o=e.i(912598),c=e.i(677667),d=e.i(130643),u=e.i(898667),m=e.i(994388),p=e.i(309426),g=e.i(350967),h=e.i(599724),x=e.i(779241),y=e.i(629569),f=e.i(464571),_=e.i(808613),j=e.i(311451),b=e.i(212931),v=e.i(91739),w=e.i(199133),N=e.i(790848),k=e.i(262218),S=e.i(592968),C=e.i(374009),T=e.i(271645),I=e.i(708347),A=e.i(552130),L=e.i(557662),F=e.i(9314),M=e.i(860585),O=e.i(82946),P=e.i(392110),E=e.i(533882),$=e.i(844565),V=e.i(651904),B=e.i(939510),G=e.i(460285),R=e.i(663435),D=e.i(575260),K=e.i(371455),U=e.i(355619),q=e.i(75921),z=e.i(390605),W=e.i(727749),H=e.i(764205),Q=e.i(237016),J=e.i(998573);let Y=({apiKey:e})=>{let[s,a]=(0,T.useState)(!1);return(0,t.jsxs)("div",{children:[(0,t.jsxs)("p",{className:"mb-2",children:["Please save this secret key somewhere safe and accessible. For security reasons,"," ",(0,t.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,t.jsx)("p",{className:"text-sm text-gray-600 mt-3 mb-1",children:"Virtual Key:"}),(0,t.jsx)("div",{style:{background:"#f8f8f8",padding:"10px",borderRadius:"5px",marginBottom:"10px"},children:(0,t.jsx)("pre",{style:{wordWrap:"break-word",whiteSpace:"normal",margin:0},children:e})}),(0,t.jsx)(Q.CopyToClipboard,{text:e,onCopy:()=>{a(!0),J.message.success("Key copied to clipboard"),setTimeout(()=>a(!1),2e3)},children:(0,t.jsx)(f.Button,{type:"primary",style:{marginTop:12},children:s?"Copied!":"Copy Virtual Key"})})]})};e.s(["default",0,Y],364769);var X=e.i(435451),Z=e.i(916940);let{Option:ee}=w.Select,et=async(e,t,s,a)=>{try{if(null===e||null===t)return[];if(null!==s){let l=(await (0,H.modelAvailableCall)(s,e,t,!0,a,!0)).data.map(e=>e.id);return console.log("available_model_names:",l),l}return[]}catch(e){return console.error("Error fetching user models:",e),[]}},es=async(e,t,s,a)=>{try{if(null===e||null===t)return;if(null!==s){let l=(await (0,H.modelAvailableCall)(s,e,t)).data.map(e=>e.id);console.log("available_model_names:",l),a(l)}}catch(e){console.error("Error fetching user models:",e)}};e.s(["default",0,({team:e,teams:Q,data:J,addKey:ea,autoOpenCreate:el,prefillData:er})=>{let{accessToken:ei,userId:en,userRole:eo,premiumUser:ec}=(0,r.default)(),ed=ec||null!=eo&&I.rolesWithWriteAccess.includes(eo),{data:eu,isLoading:em}=(0,a.useProjects)(),{data:ep}=(0,l.useUISettings)(),eg=!!ep?.values?.enable_projects_ui,eh=(0,o.useQueryClient)(),[ex]=_.Form.useForm(),[ey,ef]=(0,T.useState)(!1),[e_,ej]=(0,T.useState)(null),[eb,ev]=(0,T.useState)(null),[ew,eN]=(0,T.useState)([]),[ek,eS]=(0,T.useState)([]),[eC,eT]=(0,T.useState)("you"),[eI,eA]=(0,T.useState)((e=>{let t=[];if(console.log("data:",JSON.stringify(e)),e)for(let s of e)s.metadata&&s.metadata.tags&&t.push(...s.metadata.tags);let s=Array.from(new Set(t)).map(e=>({value:e,label:e}));return console.log("uniqueTags:",s),s})(J)),[eL,eF]=(0,T.useState)(!1),[eM,eO]=(0,T.useState)(null),[eP,eE]=(0,T.useState)([]),[e$,eV]=(0,T.useState)([]),[eB,eG]=(0,T.useState)([]),[eR,eD]=(0,T.useState)([]),[eK,eU]=(0,T.useState)(e),[eq,ez]=(0,T.useState)(null),[eW,eH]=(0,T.useState)(!1),[eQ,eJ]=(0,T.useState)(null),[eY,eX]=(0,T.useState)({}),[eZ,e0]=(0,T.useState)([]),[e1,e2]=(0,T.useState)(!1),[e4,e5]=(0,T.useState)([]),[e3,e6]=(0,T.useState)([]),[e7,e9]=(0,T.useState)("llm_api"),[e8,te]=(0,T.useState)({}),[tt,ts]=(0,T.useState)(!1),[ta,tl]=(0,T.useState)("30d"),[tr,ti]=(0,T.useState)(null),[tn,to]=(0,T.useState)(0),[tc,td]=(0,T.useState)([]),[tu,tm]=(0,T.useState)(null),tp=()=>{ef(!1),ex.resetFields(),eD([]),e6([]),e9("llm_api"),te({}),ts(!1),tl("30d"),ti(null),to(e=>e+1),tm(null),ez(null)},tg=()=>{ef(!1),ej(null),eU(null),ex.resetFields(),eD([]),e6([]),e9("llm_api"),te({}),ts(!1),tl("30d"),ti(null),to(e=>e+1),tm(null),ez(null)};(0,T.useEffect)(()=>{en&&eo&&ei&&es(en,eo,ei,eN)},[ei,en,eo]),(0,T.useEffect)(()=>{ei&&(0,H.getAgentsList)(ei).then(e=>td(e?.agents||[])).catch(()=>td([]))},[ei]),(0,T.useEffect)(()=>{let e=async()=>{try{let e=(await (0,H.getPoliciesList)(ei)).policies.map(e=>e.policy_name);eV(e)}catch(e){console.error("Failed to fetch policies:",e)}},t=async()=>{try{let e=await (0,H.getPromptsList)(ei);eG(e.prompts.map(e=>e.prompt_id))}catch(e){console.error("Failed to fetch prompts:",e)}};(async()=>{try{let e=(await (0,H.getGuardrailsList)(ei)).guardrails.map(e=>e.guardrail_name);eE(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})(),e(),t()},[ei]),(0,T.useEffect)(()=>{(async()=>{try{if(ei){let e=sessionStorage.getItem("possibleUserRoles");if(e)eX(JSON.parse(e));else{let e=await (0,H.getPossibleUserRoles)(ei);sessionStorage.setItem("possibleUserRoles",JSON.stringify(e)),eX(e)}}}catch(e){console.error("Error fetching possible user roles:",e)}})()},[ei]),(0,T.useEffect)(()=>{if(el&&!eL&&Q&&eo&&I.rolesWithWriteAccess.includes(eo)&&(ef(!0),eF(!0),er)){if(er.owned_by&&("another_user"===er.owned_by&&"Admin"!==eo?eT("you"):eT(er.owned_by)),er.team_id){let e=Q?.find(e=>e.team_id===er.team_id)||null;e&&(eU(e),ex.setFieldsValue({team_id:er.team_id}))}er.key_alias&&ex.setFieldsValue({key_alias:er.key_alias}),er.models&&er.models.length>0&&eO(er.models),er.key_type&&(e9(er.key_type),ex.setFieldsValue({key_type:er.key_type}))}},[el,er,Q,eL,ex,eo]);let th=ek.includes("no-default-models")&&!eK,tx=async e=>{try{let t,a=e?.key_alias??"",l=e?.team_id??null;if((J?.filter(e=>e.team_id===l).map(e=>e.key_alias)??[]).includes(a))throw Error(`Key alias ${a} already exists for team with ID ${l}, please provide another key alias`);if(W.default.info("Making API Call"),ef(!0),"you"===eC)e.user_id=en;else if("agent"===eC){if(!tu)return void W.default.fromBackend("Please select an agent");e.agent_id=tu}let r={};try{r=JSON.parse(e.metadata||"{}")}catch(e){console.error("Error parsing metadata:",e)}if("service_account"===eC&&(r.service_account_id=e.key_alias),eR.length>0&&(r={...r,logging:eR.filter(e=>e.callback_name)}),e3.length>0){let e=(0,L.mapDisplayToInternalNames)(e3);r={...r,litellm_disabled_callbacks:e}}if(tt&&(e.auto_rotate=!0,e.rotation_interval=ta),e.duration&&""!==e.duration.trim()||(e.duration=null),e.metadata=JSON.stringify(r),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&&(e.allowed_mcp_servers_and_groups.servers?.length>0||e.allowed_mcp_servers_and_groups.accessGroups?.length>0)){e.object_permission||(e.object_permission={});let{servers:t,accessGroups:s}=e.allowed_mcp_servers_and_groups;t&&t.length>0&&(e.object_permission.mcp_servers=t),s&&s.length>0&&(e.object_permission.mcp_access_groups=s),delete e.allowed_mcp_servers_and_groups}let i=e.mcp_tool_permissions||{};if(Object.keys(i).length>0&&(e.object_permission||(e.object_permission={}),e.object_permission.mcp_tool_permissions=i),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&&(e.allowed_agents_and_groups.agents?.length>0||e.allowed_agents_and_groups.accessGroups?.length>0)){e.object_permission||(e.object_permission={});let{agents:t,accessGroups:s}=e.allowed_agents_and_groups;t&&t.length>0&&(e.object_permission.agents=t),s&&s.length>0&&(e.object_permission.agent_access_groups=s),delete e.allowed_agents_and_groups}Object.keys(e8).length>0&&(e.aliases=JSON.stringify(e8)),tr?.router_settings&&Object.values(tr.router_settings).some(e=>null!=e&&""!==e)&&(e.router_settings=tr.router_settings),t="service_account"===eC?await (0,H.keyCreateServiceAccountCall)(ei,e):await (0,H.keyCreateCall)(ei,en,e),console.log("key create Response:",t),ea(t),eh.invalidateQueries({queryKey:s.keyKeys.lists()}),ej(t.key),ev(t.soft_budget),W.default.success("Virtual Key Created"),ex.resetFields(),localStorage.removeItem("userData"+en)}catch(t){console.log("error in create key:",t);let e=(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: ${e}`;let s=t;try{if(!e||"object"!=typeof e||e instanceof Error){let e=t.match(/\{[\s\S]*\}/);if(e){let t=JSON.parse(e[0]),a=t?.error||t;a?.message&&(s=a.message)}}else{let t=e?.error||e;t?.message&&(s=t.message)}}catch(e){}return t.includes("team_member_permission_error")||s.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: ${e}`})(t);W.default.fromBackend(e)}};(0,T.useEffect)(()=>{if(eq){let e=eu?.find(e=>e.project_id===eq);eS(e?.models??[]),ex.setFieldValue("models",[]);return}en&&eo&&ei&&et(en,eo,ei,eK?.team_id??null).then(e=>{eS(Array.from(new Set([...eK?.models??[],...e])))}),eM||ex.setFieldValue("models",[]),ex.setFieldValue("allowed_mcp_servers_and_groups",{servers:[],accessGroups:[]})},[eK,eq,ei,en,eo,ex]),(0,T.useEffect)(()=>{if(!eM||0===eM.length||!ek||0===ek.length)return;let e=eM.filter(e=>ek.includes(e));e.length>0&&ex.setFieldsValue({models:e}),eO(null)},[eM,ek,ex]),(0,T.useEffect)(()=>{if(!eq||!Q)return;let e=eu?.find(e=>e.project_id===eq);if(!e?.team_id||eK?.team_id===e.team_id)return;let t=Q.find(t=>t.team_id===e.team_id)||null;t&&(eU(t),ex.setFieldValue("team_id",t.team_id))},[Q,eq,eu]);let ty=async e=>{if(!e)return void e0([]);e2(!0);try{let t=new URLSearchParams;if(t.append("user_email",e),null==ei)return;let s=(await (0,H.userFilterUICall)(ei,t)).map(e=>({label:`${e.user_email} (${e.user_id})`,value:e.user_id,user:e}));e0(s)}catch(e){console.error("Error fetching users:",e),W.default.fromBackend("Failed to search for users")}finally{e2(!1)}},tf=(0,T.useCallback)((0,C.default)(e=>ty(e),300),[ei]);return(0,t.jsxs)("div",{children:[eo&&I.rolesWithWriteAccess.includes(eo)&&(0,t.jsx)(m.Button,{className:"mx-auto",onClick:()=>ef(!0),children:"+ Create New Key"}),(0,t.jsx)(b.Modal,{open:ey,width:1e3,footer:null,onOk:tp,onCancel:tg,children:(0,t.jsxs)(_.Form,{form:ex,onFinish:tx,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,t.jsxs)("div",{className:"mb-8",children:[(0,t.jsx)(y.Title,{className:"mb-4",children:"Key Ownership"}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Owned By"," ",(0,t.jsx)(S.Tooltip,{title:"Select who will own this Virtual Key",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),className:"mb-4",children:(0,t.jsxs)(v.Radio.Group,{onChange:e=>eT(e.target.value),value:eC,children:[(0,t.jsx)(v.Radio,{value:"you",children:"You"}),(0,t.jsx)(v.Radio,{value:"service_account",children:"Service Account"}),"Admin"===eo&&(0,t.jsx)(v.Radio,{value:"another_user",children:"Another User"}),(0,t.jsxs)(v.Radio,{value:"agent",children:["Agent ",(0,t.jsx)(k.Tag,{color:"purple",children:"New"})]})]})}),"another_user"===eC&&(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["User ID"," ",(0,t.jsx)(S.Tooltip,{title:"The user who will own this key and be responsible for its usage",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"user_id",className:"mt-4",rules:[{required:"another_user"===eC,message:"Please input the user ID of the user you are assigning the key to"}],children:(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{style:{display:"flex",marginBottom:"8px"},children:[(0,t.jsx)(w.Select,{showSearch:!0,placeholder:"Type email to search for users",filterOption:!1,onSearch:e=>{tf(e)},onSelect:(e,t)=>{let s;return s=t.user,void ex.setFieldsValue({user_id:s.user_id})},options:eZ,loading:e1,allowClear:!0,style:{width:"100%"},notFoundContent:e1?"Searching...":"No users found"}),(0,t.jsx)(f.Button,{onClick:()=>eH(!0),style:{marginLeft:"8px"},children:"Create User"})]}),(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"Search by email to find users"})]})}),"agent"===eC&&(0,t.jsxs)("div",{className:"mt-4 p-4 bg-purple-50 border border-purple-200 rounded-md",children:[(0,t.jsx)("div",{className:"mb-3",children:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700",children:["Select Agent ",(0,t.jsx)("span",{className:"text-red-500",children:"*"})]})}),(0,t.jsx)(w.Select,{showSearch:!0,placeholder:"Select an agent",style:{width:"100%"},value:tu,onChange:e=>tm(e),filterOption:(e,t)=>t?.label?.toLowerCase().includes(e.toLowerCase()),options:tc.map(e=>({label:e.agent_name||e.agent_id,value:e.agent_id}))}),(0,t.jsx)("div",{className:"text-xs text-gray-500 mt-2",children:"This key will be used by the selected agent to make requests to LiteLLM"})]}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Team"," ",(0,t.jsx)(S.Tooltip,{title:"The team this key belongs to, which determines available models and budget limits",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"team_id",initialValue:e?e.team_id:null,className:"mt-4",rules:[{required:"service_account"===eC,message:"Please select a team for the service account"}],help:"service_account"===eC?"required":"",children:(0,t.jsx)(R.default,{teams:Q,disabled:null!==eq,loading:!Q,onChange:e=>{eU(Q?.find(t=>t.team_id===e)||null),ez(null),ex.setFieldValue("project_id",void 0)}})}),eg&&(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Project"," ",(0,t.jsx)(S.Tooltip,{title:"Assign this key to a project. Selecting a project will lock the team to the project's team.",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"project_id",className:"mt-4",children:(0,t.jsx)(D.default,{projects:eu,teamId:eK?.team_id,loading:em||!Q,onChange:e=>{if(!e){ez(null),eU(null),ex.setFieldValue("team_id",void 0);return}ez(e)}})})]}),th&&(0,t.jsx)("div",{className:"mb-8 p-4 bg-blue-50 border border-blue-200 rounded-md",children:(0,t.jsx)(h.Text,{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."})}),!th&&(0,t.jsxs)("div",{className:"mb-8",children:[(0,t.jsx)(y.Title,{className:"mb-4",children:"Key Details"}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["you"===eC||"another_user"===eC?"Key Name":"Service Account ID"," ",(0,t.jsx)(S.Tooltip,{title:"you"===eC||"another_user"===eC?"A descriptive name to identify this key":"Unique identifier for this service account",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"key_alias",rules:[{required:!0,message:`Please input a ${"you"===eC?"key name":"service account ID"}`}],help:"required",children:(0,t.jsx)(x.TextInput,{placeholder:""})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Models"," ",(0,t.jsx)(S.Tooltip,{title:"Select which models this key can access. Choose 'All Team Models' to grant access to all models available to the team. Leave empty to allow access to all models.",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"models",rules:[],help:"management"===e7||"read_only"===e7?"Models field is disabled for this key type":"optional - leave empty to allow access to all models",className:"mt-4",children:(0,t.jsxs)(w.Select,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},disabled:"management"===e7||"read_only"===e7,onChange:e=>{e.includes("all-team-models")&&ex.setFieldsValue({models:["all-team-models"]})},children:[!eq&&(0,t.jsx)(ee,{value:"all-team-models",children:"All Team Models"},"all-team-models"),ek.map(e=>(0,t.jsx)(ee,{value:e,children:(0,U.getModelDisplayName)(e)},e))]})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Key Type"," ",(0,t.jsx)(S.Tooltip,{title:"Select the type of key to determine what routes and operations this key can access",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"key_type",initialValue:"llm_api",className:"mt-4",children:(0,t.jsxs)(w.Select,{defaultValue:"llm_api",placeholder:"Select key type",style:{width:"100%"},optionLabelProp:"label",onChange:e=>{e9(e),("management"===e||"read_only"===e)&&ex.setFieldsValue({models:[]})},children:[(0,t.jsx)(ee,{value:"default",label:"Default",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Default"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call AI APIs + Management routes"})]})}),(0,t.jsx)(ee,{value:"llm_api",label:"AI APIs",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"AI APIs"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call only AI API routes (chat/completions, embeddings, etc.)"})]})}),(0,t.jsx)(ee,{value:"management",label:"Management",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Management"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call only management routes (user/team/key management)"})]})})]})})]}),!th&&(0,t.jsx)("div",{className:"mb-8",children:(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)(y.Title,{className:"m-0",children:"Optional Settings"})}),(0,t.jsxs)(d.AccordionBody,{children:[(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Max Budget (USD)"," ",(0,t.jsx)(S.Tooltip,{title:"Maximum amount in USD this key can spend. When reached, the key will be blocked from making further requests",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"max_budget",help:`Budget cannot exceed team max budget: $${e?.max_budget!==null&&e?.max_budget!==void 0?e?.max_budget:"unlimited"}`,rules:[{validator:async(t,s)=>{if(s&&e&&null!==e.max_budget&&s>e.max_budget)throw Error(`Budget cannot exceed team max budget: $${(0,i.formatNumberWithCommas)(e.max_budget,4)}`)}}],children:(0,t.jsx)(X.default,{step:.01,precision:2,width:200})}),(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Reset Budget"," ",(0,t.jsx)(S.Tooltip,{title:"How often the budget should reset. For example, setting 'daily' will reset the budget every 24 hours",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"budget_duration",help:`Team Reset Budget: ${e?.budget_duration!==null&&e?.budget_duration!==void 0?e?.budget_duration:"None"}`,children:(0,t.jsx)(M.default,{onChange:e=>ex.setFieldValue("budget_duration",e)})}),(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Tokens per minute Limit (TPM)"," ",(0,t.jsx)(S.Tooltip,{title:"Maximum number of tokens this key can process per minute. Helps control usage and costs",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"tpm_limit",help:`TPM cannot exceed team TPM limit: ${e?.tpm_limit!==null&&e?.tpm_limit!==void 0?e?.tpm_limit:"unlimited"}`,rules:[{validator:async(t,s)=>{if(s&&e&&null!==e.tpm_limit&&s>e.tpm_limit)throw Error(`TPM limit cannot exceed team TPM limit: ${e.tpm_limit}`)}}],children:(0,t.jsx)(X.default,{step:1,width:400})}),(0,t.jsx)(B.default,{type:"tpm",name:"tpm_limit_type",className:"mt-4",initialValue:null,form:ex,showDetailedDescriptions:!0}),(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Requests per minute Limit (RPM)"," ",(0,t.jsx)(S.Tooltip,{title:"Maximum number of API requests this key can make per minute. Helps prevent abuse and manage load",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"rpm_limit",help:`RPM cannot exceed team RPM limit: ${e?.rpm_limit!==null&&e?.rpm_limit!==void 0?e?.rpm_limit:"unlimited"}`,rules:[{validator:async(t,s)=>{if(s&&e&&null!==e.rpm_limit&&s>e.rpm_limit)throw Error(`RPM limit cannot exceed team RPM limit: ${e.rpm_limit}`)}}],children:(0,t.jsx)(X.default,{step:1,width:400})}),(0,t.jsx)(B.default,{type:"rpm",name:"rpm_limit_type",className:"mt-4",initialValue:null,form:ex,showDetailedDescriptions:!0}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Guardrails"," ",(0,t.jsx)(S.Tooltip,{title:"Apply safety guardrails to this key to filter content or enforce policies",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",className:"mt-4",help:ed?"Select existing guardrails or enter new ones":"Premium feature - Upgrade to set guardrails by key",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},disabled:!ed,placeholder:ed?"Select or enter guardrails":"Premium feature - Upgrade to set guardrails by key",options:eP.map(e=>({value:e,label:e}))})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Disable Global Guardrails"," ",(0,t.jsx)(S.Tooltip,{title:"When enabled, this key will bypass any guardrails configured to run on every request (global guardrails)",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"disable_global_guardrails",className:"mt-4",valuePropName:"checked",help:ed?"Bypass global guardrails for this key":"Premium feature - Upgrade to disable global guardrails by key",children:(0,t.jsx)(N.Switch,{disabled:!ed,checkedChildren:"Yes",unCheckedChildren:"No"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Policies"," ",(0,t.jsx)(S.Tooltip,{title:"Apply policies to this key to control guardrails and other settings",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/guardrail_policies",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"policies",className:"mt-4",help:ec?"Select existing policies or enter new ones":"Premium feature - Upgrade to set policies by key",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},disabled:!ec,placeholder:ec?"Select or enter policies":"Premium feature - Upgrade to set policies by key",options:e$.map(e=>({value:e,label:e}))})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Prompts"," ",(0,t.jsx)(S.Tooltip,{title:"Allow this key to use specific prompt templates",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/prompt_management",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"prompts",className:"mt-4",help:ec?"Select existing prompts or enter new ones":"Premium feature - Upgrade to set prompts by key",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},disabled:!ec,placeholder:ec?"Select or enter prompts":"Premium feature - Upgrade to set prompts by key",options:eB.map(e=>({value:e,label:e}))})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Access Groups"," ",(0,t.jsx)(S.Tooltip,{title:"Assign access groups to this key. Access groups control which models, MCP servers, and agents this key can use",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"access_group_ids",className:"mt-4",help:"Select access groups to assign to this key",children:(0,t.jsx)(F.default,{placeholder:"Select access groups (optional)"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Pass Through Routes"," ",(0,t.jsx)(S.Tooltip,{title:"Allow this key to use specific pass through routes",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/pass_through",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"allowed_passthrough_routes",className:"mt-4",help:ec?"Select existing pass through routes or enter new ones":"Premium feature - Upgrade to set pass through routes by key",children:(0,t.jsx)($.default,{onChange:e=>ex.setFieldValue("allowed_passthrough_routes",e),value:ex.getFieldValue("allowed_passthrough_routes"),accessToken:ei,placeholder:ec?"Select or enter pass through routes":"Premium feature - Upgrade to set pass through routes by key",disabled:!ec,teamId:eK?eK.team_id:null})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Vector Stores"," ",(0,t.jsx)(S.Tooltip,{title:"Select which vector stores this key can access. If none selected, the key will have access to all available vector stores",children:(0,t.jsx)(n.InfoCircleOutlined,{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,t.jsx)(Z.default,{onChange:e=>ex.setFieldValue("allowed_vector_store_ids",e),value:ex.getFieldValue("allowed_vector_store_ids"),accessToken:ei,placeholder:"Select vector stores (optional)"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Metadata"," ",(0,t.jsx)(S.Tooltip,{title:"JSON object with additional information about this key. Used for tracking or custom logic",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"metadata",className:"mt-4",children:(0,t.jsx)(j.Input.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Tags"," ",(0,t.jsx)(S.Tooltip,{title:"Tags for tracking spend and/or doing tag-based routing. Used for analytics and filtering",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"tags",className:"mt-4",help:"Tags for tracking spend and/or doing tag-based routing.",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},placeholder:"Enter tags",tokenSeparators:[","],options:eI})}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"MCP Settings"})}),(0,t.jsxs)(d.AccordionBody,{children:[(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed MCP Servers"," ",(0,t.jsx)(S.Tooltip,{title:"Select which MCP servers or access groups this key can access",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_mcp_servers_and_groups",help:"Select MCP servers or access groups this key can access",children:(0,t.jsx)(q.default,{onChange:e=>ex.setFieldValue("allowed_mcp_servers_and_groups",e),value:ex.getFieldValue("allowed_mcp_servers_and_groups"),accessToken:ei,teamId:eK?.team_id??null,placeholder:"Select MCP servers or access groups (optional)"})}),(0,t.jsx)(_.Form.Item,{name:"mcp_tool_permissions",initialValue:{},hidden:!0,children:(0,t.jsx)(j.Input,{type:"hidden"})}),(0,t.jsx)(_.Form.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:()=>(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(z.default,{accessToken:ei,selectedServers:ex.getFieldValue("allowed_mcp_servers_and_groups")?.servers||[],toolPermissions:ex.getFieldValue("mcp_tool_permissions")||{},onChange:e=>ex.setFieldsValue({mcp_tool_permissions:e})})})})]})]}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Agent Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Agents"," ",(0,t.jsx)(S.Tooltip,{title:"Select which agents or access groups this key can access",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_agents_and_groups",help:"Select agents or access groups this key can access",children:(0,t.jsx)(A.default,{onChange:e=>ex.setFieldValue("allowed_agents_and_groups",e),value:ex.getFieldValue("allowed_agents_and_groups"),accessToken:ei,placeholder:"Select agents or access groups (optional)"})})})]}),ec?(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Logging Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(V.default,{value:eR,onChange:eD,premiumUser:!0,disabledCallbacks:e3,onDisabledCallbacksChange:e6})})})]}):(0,t.jsx)(S.Tooltip,{title:(0,t.jsxs)("span",{children:["Key-level logging settings is an enterprise feature, get in touch -",(0,t.jsx)("a",{href:"https://www.litellm.ai/enterprise",target:"_blank",children:"https://www.litellm.ai/enterprise"})]}),placement:"top",children:(0,t.jsxs)("div",{style:{position:"relative"},children:[(0,t.jsx)("div",{style:{opacity:.5},children:(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Logging Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(V.default,{value:eR,onChange:eD,premiumUser:!1,disabledCallbacks:e3,onDisabledCallbacksChange:e6})})})]})}),(0,t.jsx)("div",{style:{position:"absolute",inset:0,cursor:"not-allowed"}})]})}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Router Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4 w-full",children:(0,t.jsx)(G.default,{accessToken:ei||"",value:tr||void 0,onChange:ti,modelData:ew.length>0?{data:ew.map(e=>({model_name:e}))}:void 0},tn)})})]},`router-settings-accordion-${tn}`),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Model Aliases"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsxs)("div",{className:"mt-4",children:[(0,t.jsx)(h.Text,{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,t.jsx)(E.default,{accessToken:ei,initialModelAliases:e8,onAliasUpdate:te,showExampleConfig:!1})]})})]}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Key Lifecycle"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(P.default,{form:ex,autoRotationEnabled:tt,onAutoRotationChange:ts,rotationInterval:ta,onRotationIntervalChange:tl,isCreateMode:!0})})}),(0,t.jsx)(_.Form.Item,{name:"duration",hidden:!0,initialValue:null,children:(0,t.jsx)(j.Input,{})})]}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("b",{children:"Advanced Settings"}),(0,t.jsx)(S.Tooltip,{title:(0,t.jsxs)("span",{children:["Learn more about advanced settings in our"," ",(0,t.jsx)("a",{href:H.proxyBaseUrl?`${H.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,t.jsx)(n.InfoCircleOutlined,{className:"text-gray-400 hover:text-gray-300 cursor-help"})})]})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)(O.default,{schemaComponent:"GenerateKeyRequest",form:ex,excludedFields:["key_alias","team_id","models","duration","metadata","tags","guardrails","max_budget","budget_duration","tpm_limit","rpm_limit"]})})]})]})]})}),(0,t.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,t.jsx)(f.Button,{htmlType:"submit",disabled:th,style:{opacity:th?.5:1},children:"Create Key"})})]})}),eW&&(0,t.jsx)(b.Modal,{title:"Create New User",open:eW,onCancel:()=>eH(!1),footer:null,width:800,children:(0,t.jsx)(K.CreateUserButton,{userID:en,accessToken:ei,teams:Q,possibleUIRoles:eY,onUserCreated:e=>{eJ(e),ex.setFieldsValue({user_id:e}),eH(!1)},isEmbedded:!0})}),e_&&(0,t.jsx)(b.Modal,{open:ey,onOk:tp,onCancel:tg,footer:null,children:(0,t.jsxs)(g.Grid,{numItems:1,className:"gap-2 w-full",children:[(0,t.jsx)(y.Title,{children:"Save your Key"}),(0,t.jsx)(p.Col,{numColSpan:1,children:null!=e_?(0,t.jsx)(Y,{apiKey:e_}):(0,t.jsx)(h.Text,{children:"Key being created, this might take 30s"})})]})})]})},"fetchTeamModels",0,et,"fetchUserModels",0,es],702597)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/0ed98235bd6bf63a.js b/litellm/proxy/_experimental/out/_next/static/chunks/0ed98235bd6bf63a.js deleted file mode 100644 index 90616f289f5..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/0ed98235bd6bf63a.js +++ /dev/null @@ -1 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,233525,(e,t,l)=>{"use strict";Object.defineProperty(l,"__esModule",{value:!0}),Object.defineProperty(l,"warnOnce",{enumerable:!0,get:function(){return r}});let r=e=>{}},645526,e=>{"use strict";e.i(247167);var t=e.i(931067),l=e.i(271645);let r={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M824.2 699.9a301.55 301.55 0 00-86.4-60.4C783.1 602.8 812 546.8 812 484c0-110.8-92.4-201.7-203.2-200-109.1 1.7-197 90.6-197 200 0 62.8 29 118.8 74.2 155.5a300.95 300.95 0 00-86.4 60.4C345 754.6 314 826.8 312 903.8a8 8 0 008 8.2h56c4.3 0 7.9-3.4 8-7.7 1.9-58 25.4-112.3 66.7-153.5A226.62 226.62 0 01612 684c60.9 0 118.2 23.7 161.3 66.8C814.5 792 838 846.3 840 904.3c.1 4.3 3.7 7.7 8 7.7h56a8 8 0 008-8.2c-2-77-33-149.2-87.8-203.9zM612 612c-34.2 0-66.4-13.3-90.5-37.5a126.86 126.86 0 01-37.5-91.8c.3-32.8 13.4-64.5 36.3-88 24-24.6 56.1-38.3 90.4-38.7 33.9-.3 66.8 12.9 91 36.6 24.8 24.3 38.4 56.8 38.4 91.4 0 34.2-13.3 66.3-37.5 90.5A127.3 127.3 0 01612 612zM361.5 510.4c-.9-8.7-1.4-17.5-1.4-26.4 0-15.9 1.5-31.4 4.3-46.5.7-3.6-1.2-7.3-4.5-8.8-13.6-6.1-26.1-14.5-36.9-25.1a127.54 127.54 0 01-38.7-95.4c.9-32.1 13.8-62.6 36.3-85.6 24.7-25.3 57.9-39.1 93.2-38.7 31.9.3 62.7 12.6 86 34.4 7.9 7.4 14.7 15.6 20.4 24.4 2 3.1 5.9 4.4 9.3 3.2 17.6-6.1 36.2-10.4 55.3-12.4 5.6-.6 8.8-6.6 6.3-11.6-32.5-64.3-98.9-108.7-175.7-109.9-110.9-1.7-203.3 89.2-203.3 199.9 0 62.8 28.9 118.8 74.2 155.5-31.8 14.7-61.1 35-86.5 60.4-54.8 54.7-85.8 126.9-87.8 204a8 8 0 008 8.2h56.1c4.3 0 7.9-3.4 8-7.7 1.9-58 25.4-112.3 66.7-153.5 29.4-29.4 65.4-49.8 104.7-59.7 3.9-1 6.5-4.7 6-8.7z"}}]},name:"team",theme:"outlined"};var a=e.i(9583),n=l.forwardRef(function(e,n){return l.createElement(a.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["TeamOutlined",0,n],645526)},56456,e=>{"use strict";var t=e.i(739295);e.s(["LoadingOutlined",()=>t.default])},771674,e=>{"use strict";e.i(247167);var t=e.i(931067),l=e.i(271645);let r={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M858.5 763.6a374 374 0 00-80.6-119.5 375.63 375.63 0 00-119.5-80.6c-.4-.2-.8-.3-1.2-.5C719.5 518 760 444.7 760 362c0-137-111-248-248-248S264 225 264 362c0 82.7 40.5 156 102.8 201.1-.4.2-.8.3-1.2.5-44.8 18.9-85 46-119.5 80.6a375.63 375.63 0 00-80.6 119.5A371.7 371.7 0 00136 901.8a8 8 0 008 8.2h60c4.4 0 7.9-3.5 8-7.8 2-77.2 33-149.5 87.8-204.3 56.7-56.7 132-87.9 212.2-87.9s155.5 31.2 212.2 87.9C779 752.7 810 825 812 902.2c.1 4.4 3.6 7.8 8 7.8h60a8 8 0 008-8.2c-1-47.8-10.9-94.3-29.5-138.2zM512 534c-45.9 0-89.1-17.9-121.6-50.4S340 407.9 340 362c0-45.9 17.9-89.1 50.4-121.6S466.1 190 512 190s89.1 17.9 121.6 50.4S684 316.1 684 362c0 45.9-17.9 89.1-50.4 121.6S557.9 534 512 534z"}}]},name:"user",theme:"outlined"};var a=e.i(9583),n=l.forwardRef(function(e,n){return l.createElement(a.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["UserOutlined",0,n],771674)},948401,e=>{"use strict";e.i(247167);var t=e.i(931067),l=e.i(271645);let r={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M928 160H96c-17.7 0-32 14.3-32 32v640c0 17.7 14.3 32 32 32h832c17.7 0 32-14.3 32-32V192c0-17.7-14.3-32-32-32zm-40 110.8V792H136V270.8l-27.6-21.5 39.3-50.5 42.8 33.3h643.1l42.8-33.3 39.3 50.5-27.7 21.5zM833.6 232L512 482 190.4 232l-42.8-33.3-39.3 50.5 27.6 21.5 341.6 265.6a55.99 55.99 0 0068.7 0L888 270.8l27.6-21.5-39.3-50.5-42.7 33.2z"}}]},name:"mail",theme:"outlined"};var a=e.i(9583),n=l.forwardRef(function(e,n){return l.createElement(a.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["MailOutlined",0,n],948401)},755151,e=>{"use strict";var t=e.i(247153);e.s(["DownOutlined",()=>t.default])},326373,e=>{"use strict";var t=e.i(21539);e.s(["Dropdown",()=>t.default])},264843,e=>{"use strict";e.i(247167);var t=e.i(931067),l=e.i(271645);let r={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M464 512a48 48 0 1096 0 48 48 0 10-96 0zm200 0a48 48 0 1096 0 48 48 0 10-96 0zm-400 0a48 48 0 1096 0 48 48 0 10-96 0zm661.2-173.6c-22.6-53.7-55-101.9-96.3-143.3a444.35 444.35 0 00-143.3-96.3C630.6 75.7 572.2 64 512 64h-2c-60.6.3-119.3 12.3-174.5 35.9a445.35 445.35 0 00-142 96.5c-40.9 41.3-73 89.3-95.2 142.8-23 55.4-34.6 114.3-34.3 174.9A449.4 449.4 0 00112 714v152a46 46 0 0046 46h152.1A449.4 449.4 0 00510 960h2.1c59.9 0 118-11.6 172.7-34.3a444.48 444.48 0 00142.8-95.2c41.3-40.9 73.8-88.7 96.5-142 23.6-55.2 35.6-113.9 35.9-174.5.3-60.9-11.5-120-34.8-175.6zm-151.1 438C704 845.8 611 884 512 884h-1.7c-60.3-.3-120.2-15.3-173.1-43.5l-8.4-4.5H188V695.2l-4.5-8.4C155.3 633.9 140.3 574 140 513.7c-.4-99.7 37.7-193.3 107.6-263.8 69.8-70.5 163.1-109.5 262.8-109.9h1.7c50 0 98.5 9.7 144.2 28.9 44.6 18.7 84.6 45.6 119 80 34.3 34.3 61.3 74.4 80 119 19.4 46.2 29.1 95.2 28.9 145.8-.6 99.6-39.7 192.9-110.1 262.7z"}}]},name:"message",theme:"outlined"};var a=e.i(9583),n=l.forwardRef(function(e,n){return l.createElement(a.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["MessageOutlined",0,n],264843)},44121,186515,e=>{"use strict";e.i(247167);var t=e.i(931067),l=e.i(271645);let r={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M408 442h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8zm-8 204c0 4.4 3.6 8 8 8h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56zm504-486H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm0 632H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zM115.4 518.9L271.7 642c5.8 4.6 14.4.5 14.4-6.9V388.9c0-7.4-8.5-11.5-14.4-6.9L115.4 505.1a8.74 8.74 0 000 13.8z"}}]},name:"menu-fold",theme:"outlined"};var a=e.i(9583),n=l.forwardRef(function(e,n){return l.createElement(a.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["MenuFoldOutlined",0,n],44121);let i={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M408 442h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8zm-8 204c0 4.4 3.6 8 8 8h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56zm504-486H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm0 632H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zM142.4 642.1L298.7 519a8.84 8.84 0 000-13.9L142.4 381.9c-5.8-4.6-14.4-.5-14.4 6.9v246.3a8.9 8.9 0 0014.4 7z"}}]},name:"menu-unfold",theme:"outlined"};var s=l.forwardRef(function(e,r){return l.createElement(a.default,(0,t.default)({},e,{ref:r,icon:i}))});e.s(["MenuUnfoldOutlined",0,s],186515)},115571,371401,e=>{"use strict";let t="local-storage-change";function l(e){window.dispatchEvent(new CustomEvent(t,{detail:{key:e}}))}function r(e){try{return window.localStorage.getItem(e)}catch(t){return console.warn(`Error reading localStorage key "${e}":`,t),null}}function a(e,t){try{window.localStorage.setItem(e,t)}catch(t){console.warn(`Error setting localStorage key "${e}":`,t)}}function n(e){try{window.localStorage.removeItem(e)}catch(t){console.warn(`Error removing localStorage key "${e}":`,t)}}e.s(["LOCAL_STORAGE_EVENT",0,t,"emitLocalStorageChange",()=>l,"getLocalStorageItem",()=>r,"removeLocalStorageItem",()=>n,"setLocalStorageItem",()=>a],115571);var i=e.i(271645);function s(e){let l=t=>{"disableUsageIndicator"===t.key&&e()},r=t=>{let{key:l}=t.detail;"disableUsageIndicator"===l&&e()};return window.addEventListener("storage",l),window.addEventListener(t,r),()=>{window.removeEventListener("storage",l),window.removeEventListener(t,r)}}function o(){return"true"===r("disableUsageIndicator")}function c(){return(0,i.useSyncExternalStore)(s,o)}e.s(["useDisableUsageIndicator",()=>c],371401)},275144,e=>{"use strict";var t=e.i(843476),l=e.i(271645),r=e.i(764205);let a=(0,l.createContext)(void 0);e.s(["ThemeProvider",0,({children:e,accessToken:n})=>{let[i,s]=(0,l.useState)(null),[o,c]=(0,l.useState)(null);return(0,l.useEffect)(()=>{(async()=>{try{let e=(0,r.getProxyBaseUrl)(),t=e?`${e}/get/ui_theme_settings`:"/get/ui_theme_settings",l=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}});if(l.ok){let e=await l.json();e.values?.logo_url&&s(e.values.logo_url),e.values?.favicon_url&&c(e.values.favicon_url)}}catch(e){console.warn("Failed to load theme settings from backend:",e)}})()},[]),(0,l.useEffect)(()=>{if(o){let e=document.querySelectorAll("link[rel*='icon']");if(e.length>0)e.forEach(e=>{e.href=o});else{let e=document.createElement("link");e.rel="icon",e.href=o,document.head.appendChild(e)}}},[o]),(0,t.jsx)(a.Provider,{value:{logoUrl:i,setLogoUrl:s,faviconUrl:o,setFaviconUrl:c},children:e})},"useTheme",0,()=>{let e=(0,l.useContext)(a);if(!e)throw Error("useTheme must be used within a ThemeProvider");return e}])},100486,e=>{"use strict";e.i(247167);var t=e.i(931067),l=e.i(271645);let r={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M899.6 276.5L705 396.4 518.4 147.5a8.06 8.06 0 00-12.9 0L319 396.4 124.3 276.5c-5.7-3.5-13.1 1.2-12.2 7.9L188.5 865c1.1 7.9 7.9 14 16 14h615.1c8 0 14.9-6 15.9-14l76.4-580.6c.8-6.7-6.5-11.4-12.3-7.9zm-126 534.1H250.3l-53.8-409.4 139.8 86.1L512 252.9l175.7 234.4 139.8-86.1-53.9 409.4zM512 509c-62.1 0-112.6 50.5-112.6 112.6S449.9 734.2 512 734.2s112.6-50.5 112.6-112.6S574.1 509 512 509zm0 160.9c-26.6 0-48.2-21.6-48.2-48.3 0-26.6 21.6-48.3 48.2-48.3s48.2 21.6 48.2 48.3c0 26.6-21.6 48.3-48.2 48.3z"}}]},name:"crown",theme:"outlined"};var a=e.i(9583),n=l.forwardRef(function(e,n){return l.createElement(a.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["CrownOutlined",0,n],100486)},602073,e=>{"use strict";e.i(247167);var t=e.i(931067),l=e.i(271645);let r={icon:{tag:"svg",attrs:{viewBox:"0 0 1024 1024",focusable:"false"},children:[{tag:"path",attrs:{d:"M512 64L128 192v384c0 212.1 171.9 384 384 384s384-171.9 384-384V192L512 64zm312 512c0 172.3-139.7 312-312 312S200 748.3 200 576V246l312-110 312 110v330z"}},{tag:"path",attrs:{d:"M378.4 475.1a35.91 35.91 0 00-50.9 0 35.91 35.91 0 000 50.9l129.4 129.4 2.1 2.1a33.98 33.98 0 0048.1 0L730.6 434a33.98 33.98 0 000-48.1l-2.8-2.8a33.98 33.98 0 00-48.1 0L483 579.7 378.4 475.1z"}}]},name:"safety",theme:"outlined"};var a=e.i(9583),n=l.forwardRef(function(e,n){return l.createElement(a.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["SafetyOutlined",0,n],602073)},62478,e=>{"use strict";var t=e.i(764205);let l=async e=>{if(!e)return null;try{return await (0,t.getProxyUISettings)(e)}catch(e){return console.error("Error fetching proxy settings:",e),null}};e.s(["fetchProxySettings",0,l])},818581,(e,t,l)=>{"use strict";Object.defineProperty(l,"__esModule",{value:!0}),Object.defineProperty(l,"useMergedRef",{enumerable:!0,get:function(){return a}});let r=e.r(271645);function a(e,t){let l=(0,r.useRef)(null),a=(0,r.useRef)(null);return(0,r.useCallback)(r=>{if(null===r){let e=l.current;e&&(l.current=null,e());let t=a.current;t&&(a.current=null,t())}else e&&(l.current=n(e,r)),t&&(a.current=n(t,r))},[e,t])}function n(e,t){if("function"!=typeof e)return e.current=t,()=>{e.current=null};{let l=e(t);return"function"==typeof l?l:()=>e(null)}}("function"==typeof l.default||"object"==typeof l.default&&null!==l.default)&&void 0===l.default.__esModule&&(Object.defineProperty(l.default,"__esModule",{value:!0}),Object.assign(l.default,l),t.exports=l.default)},216370,e=>{"use strict";e.i(247167);var t=e.i(843476),l=e.i(271645),r=e.i(402874),a=e.i(275144),n=e.i(372943),i=e.i(899268),s=e.i(592143),o=e.i(438957),c=e.i(788191),u=e.i(182399),d=e.i(153702),g=e.i(645526),f=e.i(299251),m=e.i(771674),h=e.i(313603),p=e.i(218129),y=e.i(477189),v=e.i(210612),b=e.i(993914),x=e.i(777579),S=e.i(602073),k=e.i(19732),z=e.i(366308),j=e.i(232164),_=e.i(457202),w=e.i(618566),O=e.i(708347),L=e.i(190983),M=e.i(764205);let{Sider:C}=n.Layout,E=()=>{let e="ui/".replace(/^\/+|\/+$/g,""),t=e?`/${e}/`:"/";if(M.serverRootPath&&"/"!==M.serverRootPath){let e=M.serverRootPath.replace(/\/+$/,""),l=t.replace(/^\/+/,"");return`${e}/${l}`}return t},P=e=>{switch(e){case"api-keys":return"virtual-keys";case"llm-playground":return"test-key";case"models":return"models-and-endpoints";case"new_usage":return"usage";case"teams":return"teams";case"organizations":return"organizations";case"users":return"users";case"api_ref":return"api-reference";case"model-hub-table":return"model-hub";case"logs":return"logs";case"guardrails":return"guardrails";case"policies":return"policies";case"mcp-servers":return"tools/mcp-servers";case"vector-stores":return"tools/vector-stores";case"byok-demo":return"tools/byok-demo";case"caching":return"experimental/caching";case"prompts":return"experimental/prompts";case"budgets":return"experimental/budgets";case"transform-request":return"experimental/api-playground";case"tag-management":return"experimental/tag-management";case"claude-code-plugins":return"experimental/claude-code-plugins";case"usage":return"experimental/old-usage";case"general-settings":return"settings/router-settings";case"settings":return"settings/logging-and-alerts";case"admin-panel":return"settings/admin-settings";case"ui-theme":return"settings/ui-theme";default:return e.replace(/^\/+/,"")}},T=e=>{let t=E(),l=P(e).replace(/^\/+|\/+$/g,"");return`${t}${l}`},R=[{key:"1",page:"api-keys",label:"Virtual Keys",icon:(0,t.jsx)(o.KeyOutlined,{style:{fontSize:18}})},{key:"3",page:"llm-playground",label:"Test Key",icon:(0,t.jsx)(c.PlayCircleOutlined,{style:{fontSize:18}}),roles:O.rolesWithWriteAccess},{key:"2",page:"models",label:"Models + Endpoints",icon:(0,t.jsx)(u.BlockOutlined,{style:{fontSize:18}}),roles:O.rolesWithWriteAccess},{key:"12",page:"new_usage",label:"Usage",icon:(0,t.jsx)(d.BarChartOutlined,{style:{fontSize:18}}),roles:[...O.all_admin_roles,...O.internalUserRoles]},{key:"6",page:"teams",label:"Teams",icon:(0,t.jsx)(g.TeamOutlined,{style:{fontSize:18}})},{key:"17",page:"organizations",label:"Organizations",icon:(0,t.jsx)(f.BankOutlined,{style:{fontSize:18}}),roles:O.all_admin_roles},{key:"5",page:"users",label:"Internal Users",icon:(0,t.jsx)(m.UserOutlined,{style:{fontSize:18}}),roles:O.all_admin_roles},{key:"14",page:"api_ref",label:"API Reference",icon:(0,t.jsx)(p.ApiOutlined,{style:{fontSize:18}})},{key:"16",page:"model-hub-table",label:"Model Hub",icon:(0,t.jsx)(y.AppstoreOutlined,{style:{fontSize:18}})},{key:"15",page:"logs",label:"Logs",icon:(0,t.jsx)(x.LineChartOutlined,{style:{fontSize:18}})},{key:"11",page:"guardrails",label:"Guardrails",icon:(0,t.jsx)(S.SafetyOutlined,{style:{fontSize:18}}),roles:O.all_admin_roles},{key:"28",page:"policies",label:"Policies",icon:(0,t.jsx)(_.AuditOutlined,{style:{fontSize:18}}),roles:O.all_admin_roles},{key:"26",page:"tools",label:"Tools",icon:(0,t.jsx)(z.ToolOutlined,{style:{fontSize:18}}),children:[{key:"18",page:"mcp-servers",label:"MCP Servers",icon:(0,t.jsx)(z.ToolOutlined,{style:{fontSize:18}})},{key:"21",page:"vector-stores",label:"Vector Stores",icon:(0,t.jsx)(v.DatabaseOutlined,{style:{fontSize:18}}),roles:O.all_admin_roles}]},{key:"experimental",page:"experimental",label:"Experimental",icon:(0,t.jsx)(k.ExperimentOutlined,{style:{fontSize:18}}),children:[{key:"9",page:"caching",label:"Caching",icon:(0,t.jsx)(v.DatabaseOutlined,{style:{fontSize:18}}),roles:O.all_admin_roles},{key:"25",page:"prompts",label:"Prompts",icon:(0,t.jsx)(b.FileTextOutlined,{style:{fontSize:18}}),roles:O.all_admin_roles},{key:"10",page:"budgets",label:"Budgets",icon:(0,t.jsx)(f.BankOutlined,{style:{fontSize:18}}),roles:O.all_admin_roles},{key:"20",page:"transform-request",label:"API Playground",icon:(0,t.jsx)(p.ApiOutlined,{style:{fontSize:18}}),roles:[...O.all_admin_roles,...O.internalUserRoles]},{key:"19",page:"tag-management",label:"Tag Management",icon:(0,t.jsx)(j.TagsOutlined,{style:{fontSize:18}}),roles:O.all_admin_roles},{key:"27",page:"claude-code-plugins",label:"Claude Code Plugins",icon:(0,t.jsx)(z.ToolOutlined,{style:{fontSize:18}}),roles:O.all_admin_roles},{key:"4",page:"usage",label:"Old Usage",icon:(0,t.jsx)(d.BarChartOutlined,{style:{fontSize:18}})}]},{key:"settings",page:"settings",label:"Settings",icon:(0,t.jsx)(h.SettingOutlined,{style:{fontSize:18}}),roles:O.all_admin_roles,children:[{key:"11",page:"general-settings",label:"Router Settings",icon:(0,t.jsx)(h.SettingOutlined,{style:{fontSize:18}}),roles:O.all_admin_roles},{key:"8",page:"settings",label:"Logging & Alerts",icon:(0,t.jsx)(h.SettingOutlined,{style:{fontSize:18}}),roles:O.all_admin_roles},{key:"13",page:"admin-panel",label:"Admin Settings",icon:(0,t.jsx)(h.SettingOutlined,{style:{fontSize:18}}),roles:O.all_admin_roles},{key:"14",page:"ui-theme",label:"UI Theme",icon:(0,t.jsx)(h.SettingOutlined,{style:{fontSize:18}}),roles:O.all_admin_roles}]}],A=({accessToken:e,userRole:r,defaultSelectedKey:a,collapsed:o=!1})=>{let c=(0,w.useRouter)(),u=(0,w.usePathname)()||"/",d=l.useMemo(()=>R.filter(e=>!e.roles||e.roles.includes(r)).map(e=>({...e,children:e.children?e.children.filter(e=>!e.roles||e.roles.includes(r)):void 0})),[r]),g=l.useMemo(()=>{let e=E(),t=(u.startsWith(e)?u.slice(e.length):u.replace(/^\/+/,"")).toLowerCase(),l=e=>{let l=P(e).toLowerCase();return t===l||t.startsWith(`${l}/`)};for(let e of d){if(!e.children&&l(e.page))return e.key;if(e.children){for(let t of e.children)if(l(t.page))return t.key}}let r=d.find(e=>e.page===a)?.key;if(r)return r;for(let e of d)if(e.children?.some(e=>e.page===a))return e.children.find(e=>e.page===a).key;return"1"},[u,d,a]),f=e=>{let t=T(e);c.push(t)},m=(e,l)=>{let r=T(l);return(0,t.jsx)("a",{href:r,onClick:e=>{e.metaKey||e.ctrlKey||e.shiftKey||1===e.button?e.stopPropagation():e.preventDefault()},style:{color:"inherit",textDecoration:"none"},children:e})};return(0,t.jsx)(n.Layout,{style:{minHeight:"100vh"},children:(0,t.jsxs)(C,{theme:"light",width:220,collapsed:o,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)(s.ConfigProvider,{theme:{components:{Menu:{iconSize:18,fontSize:14}}},children:(0,t.jsx)(i.Menu,{mode:"inline",selectedKeys:[g],defaultOpenKeys:o?[]:["llm-tools"],inlineCollapsed:o,className:"custom-sidebar-menu",style:{borderRight:0,backgroundColor:"transparent",fontSize:"14px"},items:d.map(e=>({key:e.key,icon:e.icon,label:m(e.label,e.page),children:e.children?.map(e=>({key:e.key,icon:e.icon,label:m(e.label,e.page),onClick:()=>f(e.page)})),onClick:e.children?void 0:()=>f(e.page)}))})}),(0,O.isAdminRole)(r)&&!o&&(0,t.jsx)(L.default,{accessToken:e,width:220})]})})};var B=e.i(135214),I=e.i(560445),U=e.i(521323);let H=()=>{let{data:e}=(0,U.useHealthReadiness)();return e?.is_detailed_debug?(0,t.jsx)(I.Alert,{message:"Performance Warning: Detailed Debug Mode Active",description:(0,t.jsxs)(t.Fragment,{children:["Detailed debug logging (",(0,t.jsx)("code",{children:"LITELLM_LOG=DEBUG"}),") is currently enabled. This mode logs extensive diagnostic information and will significantly degrade performance. It should only be used for troubleshooting and disabled in production environments."]}),type:"warning",showIcon:!0,banner:!0,style:{marginBottom:0,borderRadius:0}}):null};function D({children:e}){(0,w.useRouter)();let n=(0,w.useSearchParams)(),{accessToken:i,userRole:s,userId:o,userEmail:c,premiumUser:u}=(0,B.default)(),[d,g]=l.default.useState(!1),[f,m]=(0,l.useState)(()=>n.get("page")||"api-keys");return(0,l.useEffect)(()=>{m(n.get("page")||"api-keys")},[n]),(0,t.jsx)(a.ThemeProvider,{accessToken:"",children:(0,t.jsxs)("div",{className:"flex flex-col min-h-screen",children:[(0,t.jsx)(r.default,{isPublicPage:!1,sidebarCollapsed:d,onToggleSidebar:()=>g(e=>!e),userID:o,userEmail:c,userRole:s,premiumUser:u,proxySettings:void 0,setProxySettings:()=>{},accessToken:i,isDarkMode:!1,toggleDarkMode:()=>{}}),(0,t.jsx)(H,{}),(0,t.jsxs)("div",{className:"flex flex-1 overflow-auto",children:[(0,t.jsx)("div",{className:"mt-2",children:(0,t.jsx)(A,{defaultSelectedKey:f,accessToken:i,userRole:s})}),(0,t.jsx)("main",{className:"flex-1",children:e})]})]})})}function $({children:e}){return(0,t.jsx)(l.Suspense,{fallback:(0,t.jsx)("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:(0,t.jsx)(D,{children:e})})}!function(e){let t="ui/".trim();if(t)t.replace(/^\/+/,"").replace(/\/+$/,"")}(0),e.s(["default",()=>$],216370)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/10b2c4546ee6aca1.js b/litellm/proxy/_experimental/out/_next/static/chunks/10b2c4546ee6aca1.js new file mode 100644 index 00000000000..12a35af88d3 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/10b2c4546ee6aca1.js @@ -0,0 +1 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,269200,e=>{"use strict";var t=e.i(290571),i=e.i(271645),n=e.i(444755);let a=(0,e.i(673706).makeClassName)("Table"),l=i.default.forwardRef((e,l)=>{let{children:r,className:o}=e,d=(0,t.__rest)(e,["children","className"]);return i.default.createElement("div",{className:(0,n.tremorTwMerge)(a("root"),"overflow-auto",o)},i.default.createElement("table",Object.assign({ref:l,className:(0,n.tremorTwMerge)(a("table"),"w-full text-tremor-default","text-tremor-content","dark:text-dark-tremor-content")},d),r))});l.displayName="Table",e.s(["Table",()=>l],269200)},942232,e=>{"use strict";var t=e.i(290571),i=e.i(271645),n=e.i(444755);let a=(0,e.i(673706).makeClassName)("TableBody"),l=i.default.forwardRef((e,l)=>{let{children:r,className:o}=e,d=(0,t.__rest)(e,["children","className"]);return i.default.createElement(i.default.Fragment,null,i.default.createElement("tbody",Object.assign({ref:l,className:(0,n.tremorTwMerge)(a("root"),"align-top divide-y","divide-tremor-border","dark:divide-dark-tremor-border",o)},d),r))});l.displayName="TableBody",e.s(["TableBody",()=>l],942232)},977572,e=>{"use strict";var t=e.i(290571),i=e.i(271645),n=e.i(444755);let a=(0,e.i(673706).makeClassName)("TableCell"),l=i.default.forwardRef((e,l)=>{let{children:r,className:o}=e,d=(0,t.__rest)(e,["children","className"]);return i.default.createElement(i.default.Fragment,null,i.default.createElement("td",Object.assign({ref:l,className:(0,n.tremorTwMerge)(a("root"),"align-middle whitespace-nowrap text-left p-4",o)},d),r))});l.displayName="TableCell",e.s(["TableCell",()=>l],977572)},427612,e=>{"use strict";var t=e.i(290571),i=e.i(271645),n=e.i(444755);let a=(0,e.i(673706).makeClassName)("TableHead"),l=i.default.forwardRef((e,l)=>{let{children:r,className:o}=e,d=(0,t.__rest)(e,["children","className"]);return i.default.createElement(i.default.Fragment,null,i.default.createElement("thead",Object.assign({ref:l,className:(0,n.tremorTwMerge)(a("root"),"text-left","text-tremor-content","dark:text-dark-tremor-content",o)},d),r))});l.displayName="TableHead",e.s(["TableHead",()=>l],427612)},64848,e=>{"use strict";var t=e.i(290571),i=e.i(271645),n=e.i(444755);let a=(0,e.i(673706).makeClassName)("TableHeaderCell"),l=i.default.forwardRef((e,l)=>{let{children:r,className:o}=e,d=(0,t.__rest)(e,["children","className"]);return i.default.createElement(i.default.Fragment,null,i.default.createElement("th",Object.assign({ref:l,className:(0,n.tremorTwMerge)(a("root"),"whitespace-nowrap text-left font-semibold top-0 px-4 py-3.5","text-tremor-content-strong","dark:text-dark-tremor-content-strong",o)},d),r))});l.displayName="TableHeaderCell",e.s(["TableHeaderCell",()=>l],64848)},496020,e=>{"use strict";var t=e.i(290571),i=e.i(271645),n=e.i(444755);let a=(0,e.i(673706).makeClassName)("TableRow"),l=i.default.forwardRef((e,l)=>{let{children:r,className:o}=e,d=(0,t.__rest)(e,["children","className"]);return i.default.createElement(i.default.Fragment,null,i.default.createElement("tr",Object.assign({ref:l,className:(0,n.tremorTwMerge)(a("row"),o)},d),r))});l.displayName="TableRow",e.s(["TableRow",()=>l],496020)},389083,e=>{"use strict";var t=e.i(290571),i=e.i(271645),n=e.i(829087),a=e.i(480731),l=e.i(95779),r=e.i(444755),o=e.i(673706);let d={xs:{paddingX:"px-2",paddingY:"py-0.5",fontSize:"text-xs"},sm:{paddingX:"px-2.5",paddingY:"py-0.5",fontSize:"text-sm"},md:{paddingX:"px-3",paddingY:"py-0.5",fontSize:"text-md"},lg:{paddingX:"px-3.5",paddingY:"py-0.5",fontSize:"text-lg"},xl:{paddingX:"px-4",paddingY:"py-1",fontSize:"text-xl"}},s={xs:{height:"h-4",width:"w-4"},sm:{height:"h-4",width:"w-4"},md:{height:"h-4",width:"w-4"},lg:{height:"h-5",width:"w-5"},xl:{height:"h-6",width:"w-6"}},c=(0,o.makeClassName)("Badge"),u=i.default.forwardRef((e,u)=>{let{color:m,icon:g,size:h=a.Sizes.SM,tooltip:f,className:p,children:b}=e,v=(0,t.__rest)(e,["color","icon","size","tooltip","className","children"]),$=g||null,{tooltipProps:S,getReferenceProps:w}=(0,n.useTooltip)();return i.default.createElement("span",Object.assign({ref:(0,o.mergeRefs)([u,S.refs.setReference]),className:(0,r.tremorTwMerge)(c("root"),"w-max shrink-0 inline-flex justify-center items-center cursor-default rounded-tremor-small ring-1 ring-inset",m?(0,r.tremorTwMerge)((0,o.getColorClassNames)(m,l.colorPalette.background).bgColor,(0,o.getColorClassNames)(m,l.colorPalette.iconText).textColor,(0,o.getColorClassNames)(m,l.colorPalette.iconRing).ringColor,"bg-opacity-10 ring-opacity-20","dark:bg-opacity-5 dark:ring-opacity-60"):(0,r.tremorTwMerge)("bg-tremor-brand-faint text-tremor-brand-emphasis ring-tremor-brand/20","dark:bg-dark-tremor-brand-muted/50 dark:text-dark-tremor-brand dark:ring-dark-tremor-subtle/20"),d[h].paddingX,d[h].paddingY,d[h].fontSize,p)},w,v),i.default.createElement(n.default,Object.assign({text:f},S)),$?i.default.createElement($,{className:(0,r.tremorTwMerge)(c("icon"),"shrink-0 -ml-1 mr-1.5",s[h].height,s[h].width)}):null,i.default.createElement("span",{className:(0,r.tremorTwMerge)(c("text"),"whitespace-nowrap")},b))});u.displayName="Badge",e.s(["Badge",()=>u],389083)},244451,e=>{"use strict";let t;e.i(247167);var i=e.i(271645),n=e.i(343794),a=e.i(242064),l=e.i(763731),r=e.i(174428);let o=80*Math.PI,d=e=>{let{dotClassName:t,style:a,hasCircleCls:l}=e;return i.createElement("circle",{className:(0,n.default)(`${t}-circle`,{[`${t}-circle-bg`]:l}),r:40,cx:50,cy:50,strokeWidth:20,style:a})},s=({percent:e,prefixCls:t})=>{let a=`${t}-dot`,l=`${a}-holder`,s=`${l}-hidden`,[c,u]=i.useState(!1);(0,r.default)(()=>{0!==e&&u(!0)},[0!==e]);let m=Math.max(Math.min(e,100),0);if(!c)return null;let g={strokeDashoffset:`${o/4}`,strokeDasharray:`${o*m/100} ${o*(100-m)/100}`};return i.createElement("span",{className:(0,n.default)(l,`${a}-progress`,m<=0&&s)},i.createElement("svg",{viewBox:"0 0 100 100",role:"progressbar","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":m},i.createElement(d,{dotClassName:a,hasCircleCls:!0}),i.createElement(d,{dotClassName:a,style:g})))};function c(e){let{prefixCls:t,percent:a=0}=e,l=`${t}-dot`,r=`${l}-holder`,o=`${r}-hidden`;return i.createElement(i.Fragment,null,i.createElement("span",{className:(0,n.default)(r,a>0&&o)},i.createElement("span",{className:(0,n.default)(l,`${t}-dot-spin`)},[1,2,3,4].map(e=>i.createElement("i",{className:`${t}-dot-item`,key:e})))),i.createElement(s,{prefixCls:t,percent:a}))}function u(e){var t;let{prefixCls:a,indicator:r,percent:o}=e,d=`${a}-dot`;return r&&i.isValidElement(r)?(0,l.cloneElement)(r,{className:(0,n.default)(null==(t=r.props)?void 0:t.className,d),percent:o}):i.createElement(c,{prefixCls:a,percent:o})}e.i(296059);var m=e.i(694758),g=e.i(183293),h=e.i(246422),f=e.i(838378);let p=new m.Keyframes("antSpinMove",{to:{opacity:1}}),b=new m.Keyframes("antRotate",{to:{transform:"rotate(405deg)"}}),v=(0,h.genStyleHooks)("Spin",e=>(e=>{let{componentCls:t,calc:i}=e;return{[t]:Object.assign(Object.assign({},(0,g.resetComponent)(e)),{position:"absolute",display:"none",color:e.colorPrimary,fontSize:0,textAlign:"center",verticalAlign:"middle",opacity:0,transition:`transform ${e.motionDurationSlow} ${e.motionEaseInOutCirc}`,"&-spinning":{position:"relative",display:"inline-block",opacity:1},[`${t}-text`]:{fontSize:e.fontSize,paddingTop:i(i(e.dotSize).sub(e.fontSize)).div(2).add(2).equal()},"&-fullscreen":{position:"fixed",width:"100vw",height:"100vh",backgroundColor:e.colorBgMask,zIndex:e.zIndexPopupBase,inset:0,display:"flex",alignItems:"center",flexDirection:"column",justifyContent:"center",opacity:0,visibility:"hidden",transition:`all ${e.motionDurationMid}`,"&-show":{opacity:1,visibility:"visible"},[t]:{[`${t}-dot-holder`]:{color:e.colorWhite},[`${t}-text`]:{color:e.colorTextLightSolid}}},"&-nested-loading":{position:"relative",[`> div > ${t}`]:{position:"absolute",top:0,insetInlineStart:0,zIndex:4,display:"block",width:"100%",height:"100%",maxHeight:e.contentHeight,[`${t}-dot`]:{position:"absolute",top:"50%",insetInlineStart:"50%",margin:i(e.dotSize).mul(-1).div(2).equal()},[`${t}-text`]:{position:"absolute",top:"50%",width:"100%",textShadow:`0 1px 2px ${e.colorBgContainer}`},[`&${t}-show-text ${t}-dot`]:{marginTop:i(e.dotSize).div(2).mul(-1).sub(10).equal()},"&-sm":{[`${t}-dot`]:{margin:i(e.dotSizeSM).mul(-1).div(2).equal()},[`${t}-text`]:{paddingTop:i(i(e.dotSizeSM).sub(e.fontSize)).div(2).add(2).equal()},[`&${t}-show-text ${t}-dot`]:{marginTop:i(e.dotSizeSM).div(2).mul(-1).sub(10).equal()}},"&-lg":{[`${t}-dot`]:{margin:i(e.dotSizeLG).mul(-1).div(2).equal()},[`${t}-text`]:{paddingTop:i(i(e.dotSizeLG).sub(e.fontSize)).div(2).add(2).equal()},[`&${t}-show-text ${t}-dot`]:{marginTop:i(e.dotSizeLG).div(2).mul(-1).sub(10).equal()}}},[`${t}-container`]:{position:"relative",transition:`opacity ${e.motionDurationSlow}`,"&::after":{position:"absolute",top:0,insetInlineEnd:0,bottom:0,insetInlineStart:0,zIndex:10,width:"100%",height:"100%",background:e.colorBgContainer,opacity:0,transition:`all ${e.motionDurationSlow}`,content:'""',pointerEvents:"none"}},[`${t}-blur`]:{clear:"both",opacity:.5,userSelect:"none",pointerEvents:"none","&::after":{opacity:.4,pointerEvents:"auto"}}},"&-tip":{color:e.spinDotDefault},[`${t}-dot-holder`]:{width:"1em",height:"1em",fontSize:e.dotSize,display:"inline-block",transition:`transform ${e.motionDurationSlow} ease, opacity ${e.motionDurationSlow} ease`,transformOrigin:"50% 50%",lineHeight:1,color:e.colorPrimary,"&-hidden":{transform:"scale(0.3)",opacity:0}},[`${t}-dot-progress`]:{position:"absolute",inset:0},[`${t}-dot`]:{position:"relative",display:"inline-block",fontSize:e.dotSize,width:"1em",height:"1em","&-item":{position:"absolute",display:"block",width:i(e.dotSize).sub(i(e.marginXXS).div(2)).div(2).equal(),height:i(e.dotSize).sub(i(e.marginXXS).div(2)).div(2).equal(),background:"currentColor",borderRadius:"100%",transform:"scale(0.75)",transformOrigin:"50% 50%",opacity:.3,animationName:p,animationDuration:"1s",animationIterationCount:"infinite",animationTimingFunction:"linear",animationDirection:"alternate","&:nth-child(1)":{top:0,insetInlineStart:0,animationDelay:"0s"},"&:nth-child(2)":{top:0,insetInlineEnd:0,animationDelay:"0.4s"},"&:nth-child(3)":{insetInlineEnd:0,bottom:0,animationDelay:"0.8s"},"&:nth-child(4)":{bottom:0,insetInlineStart:0,animationDelay:"1.2s"}},"&-spin":{transform:"rotate(45deg)",animationName:b,animationDuration:"1.2s",animationIterationCount:"infinite",animationTimingFunction:"linear"},"&-circle":{strokeLinecap:"round",transition:["stroke-dashoffset","stroke-dasharray","stroke","stroke-width","opacity"].map(t=>`${t} ${e.motionDurationSlow} ease`).join(","),fillOpacity:0,stroke:"currentcolor"},"&-circle-bg":{stroke:e.colorFillSecondary}},[`&-sm ${t}-dot`]:{"&, &-holder":{fontSize:e.dotSizeSM}},[`&-sm ${t}-dot-holder`]:{i:{width:i(i(e.dotSizeSM).sub(i(e.marginXXS).div(2))).div(2).equal(),height:i(i(e.dotSizeSM).sub(i(e.marginXXS).div(2))).div(2).equal()}},[`&-lg ${t}-dot`]:{"&, &-holder":{fontSize:e.dotSizeLG}},[`&-lg ${t}-dot-holder`]:{i:{width:i(i(e.dotSizeLG).sub(e.marginXXS)).div(2).equal(),height:i(i(e.dotSizeLG).sub(e.marginXXS)).div(2).equal()}},[`&${t}-show-text ${t}-text`]:{display:"block"}})}})((0,f.mergeToken)(e,{spinDotDefault:e.colorTextDescription})),e=>{let{controlHeightLG:t,controlHeight:i}=e;return{contentHeight:400,dotSize:t/2,dotSizeSM:.35*t,dotSizeLG:i}}),$=[[30,.05],[70,.03],[96,.01]];var S=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&0>t.indexOf(n)&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var a=0,n=Object.getOwnPropertySymbols(e);at.indexOf(n[a])&&Object.prototype.propertyIsEnumerable.call(e,n[a])&&(i[n[a]]=e[n[a]]);return i};let w=e=>{var l;let{prefixCls:r,spinning:o=!0,delay:d=0,className:s,rootClassName:c,size:m="default",tip:g,wrapperClassName:h,style:f,children:p,fullscreen:b=!1,indicator:w,percent:y}=e,k=S(e,["prefixCls","spinning","delay","className","rootClassName","size","tip","wrapperClassName","style","children","fullscreen","indicator","percent"]),{getPrefixCls:x,direction:C,className:E,style:N,indicator:I}=(0,a.useComponentConfig)("spin"),z=x("spin",r),[T,M,O]=v(z),[D,q]=i.useState(()=>o&&(!o||!d||!!Number.isNaN(Number(d)))),j=function(e,t){let[n,a]=i.useState(0),l=i.useRef(null),r="auto"===t;return i.useEffect(()=>(r&&e&&(a(0),l.current=setInterval(()=>{a(e=>{let t=100-e;for(let i=0;i<$.length;i+=1){let[n,a]=$[i];if(e<=n)return e+t*a}return e})},200)),()=>{l.current&&(clearInterval(l.current),l.current=null)}),[r,e]),r?n:t}(D,y);i.useEffect(()=>{if(o){let e=function(e,t,i){var n,a=i||{},l=a.noTrailing,r=void 0!==l&&l,o=a.noLeading,d=void 0!==o&&o,s=a.debounceMode,c=void 0===s?void 0:s,u=!1,m=0;function g(){n&&clearTimeout(n)}function h(){for(var i=arguments.length,a=Array(i),l=0;le?d?(m=Date.now(),r||(n=setTimeout(c?f:h,e))):h():!0!==r&&(n=setTimeout(c?f:h,void 0===c?e-s:e)))}return h.cancel=function(e){var t=(e||{}).upcomingOnly;g(),u=!(void 0!==t&&t)},h}(d,()=>{q(!0)},{debounceMode:false});return e(),()=>{var t;null==(t=null==e?void 0:e.cancel)||t.call(e)}}q(!1)},[d,o]);let H=i.useMemo(()=>void 0!==p&&!b,[p,b]),R=(0,n.default)(z,E,{[`${z}-sm`]:"small"===m,[`${z}-lg`]:"large"===m,[`${z}-spinning`]:D,[`${z}-show-text`]:!!g,[`${z}-rtl`]:"rtl"===C},s,!b&&c,M,O),X=(0,n.default)(`${z}-container`,{[`${z}-blur`]:D}),L=null!=(l=null!=w?w:I)?l:t,_=Object.assign(Object.assign({},N),f),P=i.createElement("div",Object.assign({},k,{style:_,className:R,"aria-live":"polite","aria-busy":D}),i.createElement(u,{prefixCls:z,indicator:L,percent:j}),g&&(H||b)?i.createElement("div",{className:`${z}-text`},g):null);return T(H?i.createElement("div",Object.assign({},k,{className:(0,n.default)(`${z}-nested-loading`,h,M,O)}),D&&i.createElement("div",{key:"loading"},P),i.createElement("div",{className:X,key:"container"},p)):b?i.createElement("div",{className:(0,n.default)(`${z}-fullscreen`,{[`${z}-fullscreen-show`]:D},c,M,O)},P):P)};w.setDefaultIndicator=e=>{t=e},e.s(["default",0,w],244451)},482725,e=>{"use strict";var t=e.i(244451);e.s(["Spin",()=>t.default])},981339,e=>{"use strict";var t=e.i(185793);e.s(["Skeleton",()=>t.default])},646563,e=>{"use strict";var t=e.i(959013);e.s(["PlusOutlined",()=>t.default])},447566,e=>{"use strict";e.i(247167);var t=e.i(931067),i=e.i(271645);let n={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M872 474H286.9l350.2-304c5.6-4.9 2.2-14-5.2-14h-88.5c-3.9 0-7.6 1.4-10.5 3.9L155 487.8a31.96 31.96 0 000 48.3L535.1 866c1.5 1.3 3.3 2 5.2 2h91.5c7.4 0 10.8-9.2 5.2-14L286.9 550H872c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8z"}}]},name:"arrow-left",theme:"outlined"};var a=e.i(9583),l=i.forwardRef(function(e,l){return i.createElement(a.default,(0,t.default)({},e,{ref:l,icon:n}))});e.s(["ArrowLeftOutlined",0,l],447566)},790848,e=>{"use strict";e.i(247167);var t=e.i(271645),i=e.i(739295),n=e.i(343794),a=e.i(931067),l=e.i(211577),r=e.i(392221),o=e.i(703923),d=e.i(914949),s=e.i(404948),c=["prefixCls","className","checked","defaultChecked","disabled","loadingIcon","checkedChildren","unCheckedChildren","onClick","onChange","onKeyDown"],u=t.forwardRef(function(e,i){var u,m=e.prefixCls,g=void 0===m?"rc-switch":m,h=e.className,f=e.checked,p=e.defaultChecked,b=e.disabled,v=e.loadingIcon,$=e.checkedChildren,S=e.unCheckedChildren,w=e.onClick,y=e.onChange,k=e.onKeyDown,x=(0,o.default)(e,c),C=(0,d.default)(!1,{value:f,defaultValue:p}),E=(0,r.default)(C,2),N=E[0],I=E[1];function z(e,t){var i=N;return b||(I(i=e),null==y||y(i,t)),i}var T=(0,n.default)(g,h,(u={},(0,l.default)(u,"".concat(g,"-checked"),N),(0,l.default)(u,"".concat(g,"-disabled"),b),u));return t.createElement("button",(0,a.default)({},x,{type:"button",role:"switch","aria-checked":N,disabled:b,className:T,ref:i,onKeyDown:function(e){e.which===s.default.LEFT?z(!1,e):e.which===s.default.RIGHT&&z(!0,e),null==k||k(e)},onClick:function(e){var t=z(!N,e);null==w||w(t,e)}}),v,t.createElement("span",{className:"".concat(g,"-inner")},t.createElement("span",{className:"".concat(g,"-inner-checked")},$),t.createElement("span",{className:"".concat(g,"-inner-unchecked")},S)))});u.displayName="Switch";var m=e.i(121872),g=e.i(242064),h=e.i(937328),f=e.i(517455);e.i(296059);var p=e.i(915654);e.i(262370);var b=e.i(135551),v=e.i(183293),$=e.i(246422),S=e.i(838378);let w=(0,$.genStyleHooks)("Switch",e=>{let t=(0,S.mergeToken)(e,{switchDuration:e.motionDurationMid,switchColor:e.colorPrimary,switchDisabledOpacity:e.opacityLoading,switchLoadingIconSize:e.calc(e.fontSizeIcon).mul(.75).equal(),switchLoadingIconColor:`rgba(0, 0, 0, ${e.opacityLoading})`,switchHandleActiveInset:"-30%"});return[(e=>{let{componentCls:t,trackHeight:i,trackMinWidth:n}=e;return{[t]:Object.assign(Object.assign(Object.assign(Object.assign({},(0,v.resetComponent)(e)),{position:"relative",display:"inline-block",boxSizing:"border-box",minWidth:n,height:i,lineHeight:(0,p.unit)(i),verticalAlign:"middle",background:e.colorTextQuaternary,border:"0",borderRadius:100,cursor:"pointer",transition:`all ${e.motionDurationMid}`,userSelect:"none",[`&:hover:not(${t}-disabled)`]:{background:e.colorTextTertiary}}),(0,v.genFocusStyle)(e)),{[`&${t}-checked`]:{background:e.switchColor,[`&:hover:not(${t}-disabled)`]:{background:e.colorPrimaryHover}},[`&${t}-loading, &${t}-disabled`]:{cursor:"not-allowed",opacity:e.switchDisabledOpacity,"*":{boxShadow:"none",cursor:"not-allowed"}},[`&${t}-rtl`]:{direction:"rtl"}})}})(t),(e=>{let{componentCls:t,trackHeight:i,trackPadding:n,innerMinMargin:a,innerMaxMargin:l,handleSize:r,calc:o}=e,d=`${t}-inner`,s=(0,p.unit)(o(r).add(o(n).mul(2)).equal()),c=(0,p.unit)(o(l).mul(2).equal());return{[t]:{[d]:{display:"block",overflow:"hidden",borderRadius:100,height:"100%",paddingInlineStart:l,paddingInlineEnd:a,transition:`padding-inline-start ${e.switchDuration} ease-in-out, padding-inline-end ${e.switchDuration} ease-in-out`,[`${d}-checked, ${d}-unchecked`]:{display:"block",color:e.colorTextLightSolid,fontSize:e.fontSizeSM,transition:`margin-inline-start ${e.switchDuration} ease-in-out, margin-inline-end ${e.switchDuration} ease-in-out`,pointerEvents:"none",minHeight:i},[`${d}-checked`]:{marginInlineStart:`calc(-100% + ${s} - ${c})`,marginInlineEnd:`calc(100% - ${s} + ${c})`},[`${d}-unchecked`]:{marginTop:o(i).mul(-1).equal(),marginInlineStart:0,marginInlineEnd:0}},[`&${t}-checked ${d}`]:{paddingInlineStart:a,paddingInlineEnd:l,[`${d}-checked`]:{marginInlineStart:0,marginInlineEnd:0},[`${d}-unchecked`]:{marginInlineStart:`calc(100% - ${s} + ${c})`,marginInlineEnd:`calc(-100% + ${s} - ${c})`}},[`&:not(${t}-disabled):active`]:{[`&:not(${t}-checked) ${d}`]:{[`${d}-unchecked`]:{marginInlineStart:o(n).mul(2).equal(),marginInlineEnd:o(n).mul(-1).mul(2).equal()}},[`&${t}-checked ${d}`]:{[`${d}-checked`]:{marginInlineStart:o(n).mul(-1).mul(2).equal(),marginInlineEnd:o(n).mul(2).equal()}}}}}})(t),(e=>{let{componentCls:t,trackPadding:i,handleBg:n,handleShadow:a,handleSize:l,calc:r}=e,o=`${t}-handle`;return{[t]:{[o]:{position:"absolute",top:i,insetInlineStart:i,width:l,height:l,transition:`all ${e.switchDuration} ease-in-out`,"&::before":{position:"absolute",top:0,insetInlineEnd:0,bottom:0,insetInlineStart:0,backgroundColor:n,borderRadius:r(l).div(2).equal(),boxShadow:a,transition:`all ${e.switchDuration} ease-in-out`,content:'""'}},[`&${t}-checked ${o}`]:{insetInlineStart:`calc(100% - ${(0,p.unit)(r(l).add(i).equal())})`},[`&:not(${t}-disabled):active`]:{[`${o}::before`]:{insetInlineEnd:e.switchHandleActiveInset,insetInlineStart:0},[`&${t}-checked ${o}::before`]:{insetInlineEnd:0,insetInlineStart:e.switchHandleActiveInset}}}}})(t),(e=>{let{componentCls:t,handleSize:i,calc:n}=e;return{[t]:{[`${t}-loading-icon${e.iconCls}`]:{position:"relative",top:n(n(i).sub(e.fontSize)).div(2).equal(),color:e.switchLoadingIconColor,verticalAlign:"top"},[`&${t}-checked ${t}-loading-icon`]:{color:e.switchColor}}}})(t),(e=>{let{componentCls:t,trackHeightSM:i,trackPadding:n,trackMinWidthSM:a,innerMinMarginSM:l,innerMaxMarginSM:r,handleSizeSM:o,calc:d}=e,s=`${t}-inner`,c=(0,p.unit)(d(o).add(d(n).mul(2)).equal()),u=(0,p.unit)(d(r).mul(2).equal());return{[t]:{[`&${t}-small`]:{minWidth:a,height:i,lineHeight:(0,p.unit)(i),[`${t}-inner`]:{paddingInlineStart:r,paddingInlineEnd:l,[`${s}-checked, ${s}-unchecked`]:{minHeight:i},[`${s}-checked`]:{marginInlineStart:`calc(-100% + ${c} - ${u})`,marginInlineEnd:`calc(100% - ${c} + ${u})`},[`${s}-unchecked`]:{marginTop:d(i).mul(-1).equal(),marginInlineStart:0,marginInlineEnd:0}},[`${t}-handle`]:{width:o,height:o},[`${t}-loading-icon`]:{top:d(d(o).sub(e.switchLoadingIconSize)).div(2).equal(),fontSize:e.switchLoadingIconSize},[`&${t}-checked`]:{[`${t}-inner`]:{paddingInlineStart:l,paddingInlineEnd:r,[`${s}-checked`]:{marginInlineStart:0,marginInlineEnd:0},[`${s}-unchecked`]:{marginInlineStart:`calc(100% - ${c} + ${u})`,marginInlineEnd:`calc(-100% + ${c} - ${u})`}},[`${t}-handle`]:{insetInlineStart:`calc(100% - ${(0,p.unit)(d(o).add(n).equal())})`}},[`&:not(${t}-disabled):active`]:{[`&:not(${t}-checked) ${s}`]:{[`${s}-unchecked`]:{marginInlineStart:d(e.marginXXS).div(2).equal(),marginInlineEnd:d(e.marginXXS).mul(-1).div(2).equal()}},[`&${t}-checked ${s}`]:{[`${s}-checked`]:{marginInlineStart:d(e.marginXXS).mul(-1).div(2).equal(),marginInlineEnd:d(e.marginXXS).div(2).equal()}}}}}}})(t)]},e=>{let{fontSize:t,lineHeight:i,controlHeight:n,colorWhite:a}=e,l=t*i,r=n/2,o=l-4,d=r-4;return{trackHeight:l,trackHeightSM:r,trackMinWidth:2*o+8,trackMinWidthSM:2*d+4,trackPadding:2,handleBg:a,handleSize:o,handleSizeSM:d,handleShadow:`0 2px 4px 0 ${new b.FastColor("#00230b").setA(.2).toRgbString()}`,innerMinMargin:o/2,innerMaxMargin:o+2+4,innerMinMarginSM:d/2,innerMaxMarginSM:d+2+4}});var y=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&0>t.indexOf(n)&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var a=0,n=Object.getOwnPropertySymbols(e);at.indexOf(n[a])&&Object.prototype.propertyIsEnumerable.call(e,n[a])&&(i[n[a]]=e[n[a]]);return i};let k=t.forwardRef((e,a)=>{let{prefixCls:l,size:r,disabled:o,loading:s,className:c,rootClassName:p,style:b,checked:v,value:$,defaultChecked:S,defaultValue:k,onChange:x}=e,C=y(e,["prefixCls","size","disabled","loading","className","rootClassName","style","checked","value","defaultChecked","defaultValue","onChange"]),[E,N]=(0,d.default)(!1,{value:null!=v?v:$,defaultValue:null!=S?S:k}),{getPrefixCls:I,direction:z,switch:T}=t.useContext(g.ConfigContext),M=t.useContext(h.default),O=(null!=o?o:M)||s,D=I("switch",l),q=t.createElement("div",{className:`${D}-handle`},s&&t.createElement(i.default,{className:`${D}-loading-icon`})),[j,H,R]=w(D),X=(0,f.default)(r),L=(0,n.default)(null==T?void 0:T.className,{[`${D}-small`]:"small"===X,[`${D}-loading`]:s,[`${D}-rtl`]:"rtl"===z},c,p,H,R),_=Object.assign(Object.assign({},null==T?void 0:T.style),b);return j(t.createElement(m.default,{component:"Switch",disabled:O},t.createElement(u,Object.assign({},C,{checked:E,onChange:(...e)=>{N(e[0]),null==x||x.apply(void 0,e)},prefixCls:D,className:L,style:_,disabled:O,ref:a,loadingIcon:q}))))});k.__ANT_SWITCH=!0,e.s(["Switch",0,k],790848)},771674,e=>{"use strict";e.i(247167);var t=e.i(931067),i=e.i(271645);let n={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M858.5 763.6a374 374 0 00-80.6-119.5 375.63 375.63 0 00-119.5-80.6c-.4-.2-.8-.3-1.2-.5C719.5 518 760 444.7 760 362c0-137-111-248-248-248S264 225 264 362c0 82.7 40.5 156 102.8 201.1-.4.2-.8.3-1.2.5-44.8 18.9-85 46-119.5 80.6a375.63 375.63 0 00-80.6 119.5A371.7 371.7 0 00136 901.8a8 8 0 008 8.2h60c4.4 0 7.9-3.5 8-7.8 2-77.2 33-149.5 87.8-204.3 56.7-56.7 132-87.9 212.2-87.9s155.5 31.2 212.2 87.9C779 752.7 810 825 812 902.2c.1 4.4 3.6 7.8 8 7.8h60a8 8 0 008-8.2c-1-47.8-10.9-94.3-29.5-138.2zM512 534c-45.9 0-89.1-17.9-121.6-50.4S340 407.9 340 362c0-45.9 17.9-89.1 50.4-121.6S466.1 190 512 190s89.1 17.9 121.6 50.4S684 316.1 684 362c0 45.9-17.9 89.1-50.4 121.6S557.9 534 512 534z"}}]},name:"user",theme:"outlined"};var a=e.i(9583),l=i.forwardRef(function(e,l){return i.createElement(a.default,(0,t.default)({},e,{ref:l,icon:n}))});e.s(["UserOutlined",0,l],771674)},689020,e=>{"use strict";var t=e.i(764205);let i=async e=>{try{let i=await (0,t.modelHubCall)(e);if(console.log("model_info:",i),i?.data.length>0){let e=i.data.map(e=>({model_group:e.model_group,mode:e?.mode}));return e.sort((e,t)=>e.model_group.localeCompare(t.model_group)),e}return[]}catch(e){throw console.error("Error fetching model info:",e),e}};e.s(["fetchAvailableModels",0,i])},597440,e=>{"use strict";e.i(247167);var t=e.i(931067),i=e.i(271645);let n={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M360 184h-8c4.4 0 8-3.6 8-8v8h304v-8c0 4.4 3.6 8 8 8h-8v72h72v-80c0-35.3-28.7-64-64-64H352c-35.3 0-64 28.7-64 64v80h72v-72zm504 72H160c-17.7 0-32 14.3-32 32v32c0 4.4 3.6 8 8 8h60.4l24.7 523c1.6 34.1 29.8 61 63.9 61h454c34.2 0 62.3-26.8 63.9-61l24.7-523H888c4.4 0 8-3.6 8-8v-32c0-17.7-14.3-32-32-32zM731.3 840H292.7l-24.2-512h487l-24.2 512z"}}]},name:"delete",theme:"outlined"};var a=e.i(9583),l=i.forwardRef(function(e,l){return i.createElement(a.default,(0,t.default)({},e,{ref:l,icon:n}))});e.s(["default",0,l],597440)},955135,e=>{"use strict";var t=e.i(597440);e.s(["DeleteOutlined",()=>t.default])}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/11362340846735c3.js b/litellm/proxy/_experimental/out/_next/static/chunks/11362340846735c3.js new file mode 100644 index 00000000000..15dc8cc8608 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/11362340846735c3.js @@ -0,0 +1,420 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,166406,e=>{"use strict";var t=e.i(190144);e.s(["CopyOutlined",()=>t.default])},755151,e=>{"use strict";var t=e.i(247153);e.s(["DownOutlined",()=>t.default])},602073,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"0 0 1024 1024",focusable:"false"},children:[{tag:"path",attrs:{d:"M512 64L128 192v384c0 212.1 171.9 384 384 384s384-171.9 384-384V192L512 64zm312 512c0 172.3-139.7 312-312 312S200 748.3 200 576V246l312-110 312 110v330z"}},{tag:"path",attrs:{d:"M378.4 475.1a35.91 35.91 0 00-50.9 0 35.91 35.91 0 000 50.9l129.4 129.4 2.1 2.1a33.98 33.98 0 0048.1 0L730.6 434a33.98 33.98 0 000-48.1l-2.8-2.8a33.98 33.98 0 00-48.1 0L483 579.7 378.4 475.1z"}}]},name:"safety",theme:"outlined"};var o=e.i(9583),i=r.forwardRef(function(e,i){return r.createElement(o.default,(0,t.default)({},e,{ref:i,icon:a}))});e.s(["SafetyOutlined",0,i],602073)},818581,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"useMergedRef",{enumerable:!0,get:function(){return o}});let a=e.r(271645);function o(e,t){let r=(0,a.useRef)(null),o=(0,a.useRef)(null);return(0,a.useCallback)(a=>{if(null===a){let e=r.current;e&&(r.current=null,e());let t=o.current;t&&(o.current=null,t())}else e&&(r.current=i(e,a)),t&&(o.current=i(t,a))},[e,t])}function i(e,t){if("function"!=typeof e)return e.current=t,()=>{e.current=null};{let r=e(t);return"function"==typeof r?r:()=>e(null)}}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},62478,e=>{"use strict";var t=e.i(764205);let r=async e=>{if(!e)return null;try{return await (0,t.getProxyUISettings)(e)}catch(e){return console.error("Error fetching proxy settings:",e),null}};e.s(["fetchProxySettings",0,r])},190272,785913,e=>{"use strict";var t,r,a=((t={}).AUDIO_SPEECH="audio_speech",t.AUDIO_TRANSCRIPTION="audio_transcription",t.IMAGE_GENERATION="image_generation",t.VIDEO_GENERATION="video_generation",t.CHAT="chat",t.RESPONSES="responses",t.IMAGE_EDITS="image_edits",t.ANTHROPIC_MESSAGES="anthropic_messages",t.EMBEDDING="embedding",t),o=((r={}).IMAGE="image",r.VIDEO="video",r.CHAT="chat",r.RESPONSES="responses",r.IMAGE_EDITS="image_edits",r.ANTHROPIC_MESSAGES="anthropic_messages",r.EMBEDDINGS="embeddings",r.SPEECH="speech",r.TRANSCRIPTION="transcription",r.A2A_AGENTS="a2a_agents",r.MCP="mcp",r.REALTIME="realtime",r);let i={image_generation:"image",video_generation:"video",chat:"chat",responses:"responses",image_edits:"image_edits",anthropic_messages:"anthropic_messages",audio_speech:"speech",audio_transcription:"transcription",embedding:"embeddings"};e.s(["EndpointType",()=>o,"getEndpointType",0,e=>{if(console.log("getEndpointType:",e),Object.values(a).includes(e)){let t=i[e];return console.log("endpointType:",t),t}return"chat"}],785913),e.s(["generateCodeSnippet",0,e=>{let t,{apiKeySource:r,accessToken:a,apiKey:i,inputMessage:n,chatHistory:s,selectedTags:l,selectedVectorStores:c,selectedGuardrails:d,selectedPolicies:u,selectedMCPServers:g,mcpServers:p,mcpServerToolRestrictions:m,selectedVoice:f,endpointType:h,selectedModel:_,selectedSdk:b,proxySettings:A}=e,v="session"===r?a:i,I=window.location.origin,x=A?.LITELLM_UI_API_DOC_BASE_URL;x&&x.trim()?I=x:A?.PROXY_BASE_URL&&(I=A.PROXY_BASE_URL);let C=n||"Your prompt here",w=C.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n"),E=s.filter(e=>!e.isImage).map(({role:e,content:t})=>({role:e,content:t})),y={};l.length>0&&(y.tags=l),c.length>0&&(y.vector_stores=c),d.length>0&&(y.guardrails=d),u.length>0&&(y.policies=u);let O=_||"your-model-name",T="azure"===b?`import openai + +client = openai.AzureOpenAI( + api_key="${v||"YOUR_LITELLM_API_KEY"}", + azure_endpoint="${I}", + api_version="2024-02-01" +)`:`import openai + +client = openai.OpenAI( + api_key="${v||"YOUR_LITELLM_API_KEY"}", + base_url="${I}" +)`;switch(h){case o.CHAT:{let e=Object.keys(y).length>0,r="";if(e){let e=JSON.stringify({metadata:y},null,2).split("\n").map(e=>" ".repeat(4)+e).join("\n").trim();r=`, + extra_body=${e}`}let a=E.length>0?E:[{role:"user",content:C}];t=` +import base64 + +# Helper function to encode images to base64 +def encode_image(image_path): + with open(image_path, "rb") as image_file: + return base64.b64encode(image_file.read()).decode('utf-8') + +# Example with text only +response = client.chat.completions.create( + model="${O}", + messages=${JSON.stringify(a,null,4)}${r} +) + +print(response) + +# Example with image or PDF (uncomment and provide file path to use) +# base64_file = encode_image("path/to/your/file.jpg") # or .pdf +# response_with_file = client.chat.completions.create( +# model="${O}", +# messages=[ +# { +# "role": "user", +# "content": [ +# { +# "type": "text", +# "text": "${w}" +# }, +# { +# "type": "image_url", +# "image_url": { +# "url": f"data:image/jpeg;base64,{base64_file}" # or data:application/pdf;base64,{base64_file} +# } +# } +# ] +# } +# ]${r} +# ) +# print(response_with_file) +`;break}case o.RESPONSES:{let e=Object.keys(y).length>0,r="";if(e){let e=JSON.stringify({metadata:y},null,2).split("\n").map(e=>" ".repeat(4)+e).join("\n").trim();r=`, + extra_body=${e}`}let a=E.length>0?E:[{role:"user",content:C}];t=` +import base64 + +# Helper function to encode images to base64 +def encode_image(image_path): + with open(image_path, "rb") as image_file: + return base64.b64encode(image_file.read()).decode('utf-8') + +# Example with text only +response = client.responses.create( + model="${O}", + input=${JSON.stringify(a,null,4)}${r} +) + +print(response.output_text) + +# Example with image or PDF (uncomment and provide file path to use) +# base64_file = encode_image("path/to/your/file.jpg") # or .pdf +# response_with_file = client.responses.create( +# model="${O}", +# input=[ +# { +# "role": "user", +# "content": [ +# {"type": "input_text", "text": "${w}"}, +# { +# "type": "input_image", +# "image_url": f"data:image/jpeg;base64,{base64_file}", # or data:application/pdf;base64,{base64_file} +# }, +# ], +# } +# ]${r} +# ) +# print(response_with_file.output_text) +`;break}case o.IMAGE:t="azure"===b?` +# NOTE: The Azure SDK does not have a direct equivalent to the multi-modal 'responses.create' method shown for OpenAI. +# This snippet uses 'client.images.generate' and will create a new image based on your prompt. +# It does not use the uploaded image, as 'client.images.generate' does not support image inputs in this context. +import os +import requests +import json +import time +from PIL import Image + +result = client.images.generate( + model="${O}", + prompt="${n}", + n=1 +) + +json_response = json.loads(result.model_dump_json()) + +# Set the directory for the stored image +image_dir = os.path.join(os.curdir, 'images') + +# If the directory doesn't exist, create it +if not os.path.isdir(image_dir): + os.mkdir(image_dir) + +# Initialize the image path +image_filename = f"generated_image_{int(time.time())}.png" +image_path = os.path.join(image_dir, image_filename) + +try: + # Retrieve the generated image + if json_response.get("data") && len(json_response["data"]) > 0 && json_response["data"][0].get("url"): + image_url = json_response["data"][0]["url"] + generated_image = requests.get(image_url).content + with open(image_path, "wb") as image_file: + image_file.write(generated_image) + + print(f"Image saved to {image_path}") + # Display the image + image = Image.open(image_path) + image.show() + else: + print("Could not find image URL in response.") + print("Full response:", json_response) +except Exception as e: + print(f"An error occurred: {e}") + print("Full response:", json_response) +`:` +import base64 +import os +import time +import json +from PIL import Image +import requests + +# Helper function to encode images to base64 +def encode_image(image_path): + with open(image_path, "rb") as image_file: + return base64.b64encode(image_file.read()).decode('utf-8') + +# Helper function to create a file (simplified for this example) +def create_file(image_path): + # In a real implementation, this would upload the file to OpenAI + # For this example, we'll just return a placeholder ID + return f"file_{os.path.basename(image_path).replace('.', '_')}" + +# The prompt entered by the user +prompt = "${w}" + +# Encode images to base64 +base64_image1 = encode_image("body-lotion.png") +base64_image2 = encode_image("soap.png") + +# Create file IDs +file_id1 = create_file("body-lotion.png") +file_id2 = create_file("incense-kit.png") + +response = client.responses.create( + model="${O}", + input=[ + { + "role": "user", + "content": [ + {"type": "input_text", "text": prompt}, + { + "type": "input_image", + "image_url": f"data:image/jpeg;base64,{base64_image1}", + }, + { + "type": "input_image", + "image_url": f"data:image/jpeg;base64,{base64_image2}", + }, + { + "type": "input_image", + "file_id": file_id1, + }, + { + "type": "input_image", + "file_id": file_id2, + } + ], + } + ], + tools=[{"type": "image_generation"}], +) + +# Process the response +image_generation_calls = [ + output + for output in response.output + if output.type == "image_generation_call" +] + +image_data = [output.result for output in image_generation_calls] + +if image_data: + image_base64 = image_data[0] + image_filename = f"edited_image_{int(time.time())}.png" + with open(image_filename, "wb") as f: + f.write(base64.b64decode(image_base64)) + print(f"Image saved to {image_filename}") +else: + # If no image is generated, there might be a text response with an explanation + text_response = [output.text for output in response.output if hasattr(output, 'text')] + if text_response: + print("No image generated. Model response:") + print("\\n".join(text_response)) + else: + print("No image data found in response.") + print("Full response for debugging:") + print(response) +`;break;case o.IMAGE_EDITS:t="azure"===b?` +import base64 +import os +import time +import json +from PIL import Image +import requests + +# Helper function to encode images to base64 +def encode_image(image_path): + with open(image_path, "rb") as image_file: + return base64.b64encode(image_file.read()).decode('utf-8') + +# The prompt entered by the user +prompt = "${w}" + +# Encode images to base64 +base64_image1 = encode_image("body-lotion.png") +base64_image2 = encode_image("soap.png") + +# Create file IDs +file_id1 = create_file("body-lotion.png") +file_id2 = create_file("incense-kit.png") + +response = client.responses.create( + model="${O}", + input=[ + { + "role": "user", + "content": [ + {"type": "input_text", "text": prompt}, + { + "type": "input_image", + "image_url": f"data:image/jpeg;base64,{base64_image1}", + }, + { + "type": "input_image", + "image_url": f"data:image/jpeg;base64,{base64_image2}", + }, + { + "type": "input_image", + "file_id": file_id1, + }, + { + "type": "input_image", + "file_id": file_id2, + } + ], + } + ], + tools=[{"type": "image_generation"}], +) + +# Process the response +image_generation_calls = [ + output + for output in response.output + if output.type == "image_generation_call" +] + +image_data = [output.result for output in image_generation_calls] + +if image_data: + image_base64 = image_data[0] + image_filename = f"edited_image_{int(time.time())}.png" + with open(image_filename, "wb") as f: + f.write(base64.b64decode(image_base64)) + print(f"Image saved to {image_filename}") +else: + # If no image is generated, there might be a text response with an explanation + text_response = [output.text for output in response.output if hasattr(output, 'text')] + if text_response: + print("No image generated. Model response:") + print("\\n".join(text_response)) + else: + print("No image data found in response.") + print("Full response for debugging:") + print(response) +`:` +import base64 +import os +import time + +# Helper function to encode images to base64 +def encode_image(image_path): + with open(image_path, "rb") as image_file: + return base64.b64encode(image_file.read()).decode('utf-8') + +# Helper function to create a file (simplified for this example) +def create_file(image_path): + # In a real implementation, this would upload the file to OpenAI + # For this example, we'll just return a placeholder ID + return f"file_{os.path.basename(image_path).replace('.', '_')}" + +# The prompt entered by the user +prompt = "${w}" + +# Encode images to base64 +base64_image1 = encode_image("body-lotion.png") +base64_image2 = encode_image("soap.png") + +# Create file IDs +file_id1 = create_file("body-lotion.png") +file_id2 = create_file("incense-kit.png") + +response = client.responses.create( + model="${O}", + input=[ + { + "role": "user", + "content": [ + {"type": "input_text", "text": prompt}, + { + "type": "input_image", + "image_url": f"data:image/jpeg;base64,{base64_image1}", + }, + { + "type": "input_image", + "image_url": f"data:image/jpeg;base64,{base64_image2}", + }, + { + "type": "input_image", + "file_id": file_id1, + }, + { + "type": "input_image", + "file_id": file_id2, + } + ], + } + ], + tools=[{"type": "image_generation"}], +) + +# Process the response +image_generation_calls = [ + output + for output in response.output + if output.type == "image_generation_call" +] + +image_data = [output.result for output in image_generation_calls] + +if image_data: + image_base64 = image_data[0] + image_filename = f"edited_image_{int(time.time())}.png" + with open(image_filename, "wb") as f: + f.write(base64.b64decode(image_base64)) + print(f"Image saved to {image_filename}") +else: + # If no image is generated, there might be a text response with an explanation + text_response = [output.text for output in response.output if hasattr(output, 'text')] + if text_response: + print("No image generated. Model response:") + print("\\n".join(text_response)) + else: + print("No image data found in response.") + print("Full response for debugging:") + print(response) +`;break;case o.EMBEDDINGS:t=` +response = client.embeddings.create( + input="${n||"Your string here"}", + model="${O}", + encoding_format="base64" # or "float" +) + +print(response.data[0].embedding) +`;break;case o.TRANSCRIPTION:t=` +# Open the audio file +audio_file = open("path/to/your/audio/file.mp3", "rb") + +# Make the transcription request +response = client.audio.transcriptions.create( + model="${O}", + file=audio_file${n?`, + prompt="${n.replace(/"/g,'\\"')}"`:""} +) + +print(response.text) +`;break;case o.SPEECH:t=` +# Make the text-to-speech request +response = client.audio.speech.create( + model="${O}", + input="${n||"Your text to convert to speech here"}", + voice="${f}" # Options: alloy, ash, ballad, coral, echo, fable, nova, onyx, sage, shimmer +) + +# Save the audio to a file +output_filename = "output_speech.mp3" +response.stream_to_file(output_filename) +print(f"Audio saved to {output_filename}") + +# Optional: Customize response format and speed +# response = client.audio.speech.create( +# model="${O}", +# input="${n||"Your text to convert to speech here"}", +# voice="alloy", +# response_format="mp3", # Options: mp3, opus, aac, flac, wav, pcm +# speed=1.0 # Range: 0.25 to 4.0 +# ) +# response.stream_to_file("output_speech.mp3") +`;break;default:t="\n# Code generation for this endpoint is not implemented yet."}return`${T} +${t}`}],190272)},916925,e=>{"use strict";var t,r=((t={}).A2A_Agent="A2A Agent",t.AI21="Ai21",t.AI21_CHAT="Ai21 Chat",t.AIML="AI/ML API",t.AIOHTTP_OPENAI="Aiohttp Openai",t.Anthropic="Anthropic",t.ANTHROPIC_TEXT="Anthropic Text",t.AssemblyAI="AssemblyAI",t.AUTO_ROUTER="Auto Router",t.Bedrock="Amazon Bedrock",t.BedrockMantle="Amazon Bedrock Mantle",t.SageMaker="AWS SageMaker",t.Azure="Azure",t.Azure_AI_Studio="Azure AI Foundry (Studio)",t.AZURE_TEXT="Azure Text",t.BASETEN="Baseten",t.BYTEZ="Bytez",t.Cerebras="Cerebras",t.CLARIFAI="Clarifai",t.CLOUDFLARE="Cloudflare",t.CODESTRAL="Codestral",t.Cohere="Cohere",t.COHERE_CHAT="Cohere Chat",t.COMETAPI="Cometapi",t.COMPACTIFAI="Compactifai",t.Cursor="Cursor",t.Dashscope="Dashscope",t.Databricks="Databricks (Qwen API)",t.DATAROBOT="Datarobot",t.DeepInfra="DeepInfra",t.Deepgram="Deepgram",t.Deepseek="Deepseek",t.DOCKER_MODEL_RUNNER="Docker Model Runner",t.DOTPROMPT="Dotprompt",t.ElevenLabs="ElevenLabs",t.EMPOWER="Empower",t.FalAI="Fal AI",t.FEATHERLESS_AI="Featherless Ai",t.FireworksAI="Fireworks AI",t.FRIENDLIAI="Friendliai",t.GALADRIEL="Galadriel",t.GITHUB_COPILOT="Github Copilot",t.Google_AI_Studio="Google AI Studio",t.GradientAI="GradientAI",t.Groq="Groq",t.HEROKU="Heroku",t.Hosted_Vllm="vllm",t.HUGGINGFACE="Huggingface",t.HYPERBOLIC="Hyperbolic",t.Infinity="Infinity",t.JinaAI="Jina AI",t.LAMBDA_AI="Lambda Ai",t.LEMONADE="Lemonade",t.LLAMAFILE="Llamafile",t.LM_STUDIO="Lm Studio",t.LLAMA="Meta Llama",t.MARITALK="Maritalk",t.MiniMax="MiniMax",t.MistralAI="Mistral AI",t.MOONSHOT="Moonshot",t.MORPH="Morph",t.NEBIUS="Nebius",t.NLP_CLOUD="Nlp Cloud",t.NOVITA="Novita",t.NSCALE="Nscale",t.NVIDIA_NIM="Nvidia Nim",t.Ollama="Ollama",t.OLLAMA_CHAT="Ollama Chat",t.OOBABOOGA="Oobabooga",t.OpenAI="OpenAI",t.OPENAI_LIKE="Openai Like",t.OpenAI_Compatible="OpenAI-Compatible Endpoints (Together AI, etc.)",t.OpenAI_Text="OpenAI Text Completion",t.OpenAI_Text_Compatible="OpenAI-Compatible Text Completion Models (Together AI, etc.)",t.Openrouter="Openrouter",t.Oracle="Oracle Cloud Infrastructure (OCI)",t.OVHCLOUD="Ovhcloud",t.Perplexity="Perplexity",t.PETALS="Petals",t.PG_VECTOR="Pg Vector",t.PREDIBASE="Predibase",t.RECRAFT="Recraft",t.REPLICATE="Replicate",t.RunwayML="RunwayML",t.SAGEMAKER_LEGACY="Sagemaker",t.Sambanova="Sambanova",t.SAP="SAP Generative AI Hub",t.Snowflake="Snowflake",t.TEXT_COMPLETION_CODESTRAL="Text-Completion-Codestral",t.TogetherAI="TogetherAI",t.TOPAZ="Topaz",t.Triton="Triton",t.V0="V0",t.VERCEL_AI_GATEWAY="Vercel Ai Gateway",t.Vertex_AI="Vertex AI (Anthropic, Gemini, etc.)",t.VERTEX_AI_BETA="Vertex Ai Beta",t.VLLM="Vllm",t.VolcEngine="VolcEngine",t.Voyage="Voyage AI",t.WANDB="Wandb",t.WATSONX="Watsonx",t.WATSONX_TEXT="Watsonx Text",t.xAI="xAI",t.XINFERENCE="Xinference",t);let a={A2A_Agent:"a2a_agent",AI21:"ai21",AI21_CHAT:"ai21_chat",AIML:"aiml",AIOHTTP_OPENAI:"aiohttp_openai",Anthropic:"anthropic",ANTHROPIC_TEXT:"anthropic_text",AssemblyAI:"assemblyai",AUTO_ROUTER:"auto_router",Azure:"azure",Azure_AI_Studio:"azure_ai",AZURE_TEXT:"azure_text",BASETEN:"baseten",Bedrock:"bedrock",BedrockMantle:"bedrock_mantle",BYTEZ:"bytez",Cerebras:"cerebras",CLARIFAI:"clarifai",CLOUDFLARE:"cloudflare",CODESTRAL:"codestral",Cohere:"cohere",COHERE_CHAT:"cohere_chat",COMETAPI:"cometapi",COMPACTIFAI:"compactifai",Cursor:"cursor",Dashscope:"dashscope",Databricks:"databricks",DATAROBOT:"datarobot",DeepInfra:"deepinfra",Deepgram:"deepgram",Deepseek:"deepseek",DOCKER_MODEL_RUNNER:"docker_model_runner",DOTPROMPT:"dotprompt",ElevenLabs:"elevenlabs",EMPOWER:"empower",FalAI:"fal_ai",FEATHERLESS_AI:"featherless_ai",FireworksAI:"fireworks_ai",FRIENDLIAI:"friendliai",GALADRIEL:"galadriel",GITHUB_COPILOT:"github_copilot",Google_AI_Studio:"gemini",GradientAI:"gradient_ai",Groq:"groq",HEROKU:"heroku",Hosted_Vllm:"hosted_vllm",HUGGINGFACE:"huggingface",HYPERBOLIC:"hyperbolic",Infinity:"infinity",JinaAI:"jina_ai",LAMBDA_AI:"lambda_ai",LEMONADE:"lemonade",LLAMAFILE:"llamafile",LLAMA:"meta_llama",LM_STUDIO:"lm_studio",MARITALK:"maritalk",MiniMax:"minimax",MistralAI:"mistral",MOONSHOT:"moonshot",MORPH:"morph",NEBIUS:"nebius",NLP_CLOUD:"nlp_cloud",NOVITA:"novita",NSCALE:"nscale",NVIDIA_NIM:"nvidia_nim",Ollama:"ollama",OLLAMA_CHAT:"ollama_chat",OOBABOOGA:"oobabooga",OpenAI:"openai",OPENAI_LIKE:"openai_like",OpenAI_Compatible:"openai",OpenAI_Text:"text-completion-openai",OpenAI_Text_Compatible:"text-completion-openai",Openrouter:"openrouter",Oracle:"oci",OVHCLOUD:"ovhcloud",Perplexity:"perplexity",PETALS:"petals",PG_VECTOR:"pg_vector",PREDIBASE:"predibase",RECRAFT:"recraft",REPLICATE:"replicate",RunwayML:"runwayml",SAGEMAKER_LEGACY:"sagemaker",SageMaker:"sagemaker_chat",Sambanova:"sambanova",SAP:"sap",Snowflake:"snowflake",TEXT_COMPLETION_CODESTRAL:"text-completion-codestral",TogetherAI:"together_ai",TOPAZ:"topaz",Triton:"triton",V0:"v0",VERCEL_AI_GATEWAY:"vercel_ai_gateway",Vertex_AI:"vertex_ai",VERTEX_AI_BETA:"vertex_ai_beta",VLLM:"vllm",VolcEngine:"volcengine",Voyage:"voyage",WANDB:"wandb",WATSONX:"watsonx",WATSONX_TEXT:"watsonx_text",xAI:"xai",XINFERENCE:"xinference"},o="../ui/assets/logos/",i={"A2A Agent":`${o}a2a_agent.png`,Ai21:`${o}ai21.svg`,"Ai21 Chat":`${o}ai21.svg`,"AI/ML API":`${o}aiml_api.svg`,"Aiohttp Openai":`${o}openai_small.svg`,Anthropic:`${o}anthropic.svg`,"Anthropic Text":`${o}anthropic.svg`,AssemblyAI:`${o}assemblyai_small.png`,Azure:`${o}microsoft_azure.svg`,"Azure AI Foundry (Studio)":`${o}microsoft_azure.svg`,"Azure Text":`${o}microsoft_azure.svg`,Baseten:`${o}baseten.svg`,"Amazon Bedrock":`${o}bedrock.svg`,"Amazon Bedrock Mantle":`${o}bedrock.svg`,"AWS SageMaker":`${o}bedrock.svg`,Cerebras:`${o}cerebras.svg`,Cloudflare:`${o}cloudflare.svg`,Codestral:`${o}mistral.svg`,Cohere:`${o}cohere.svg`,"Cohere Chat":`${o}cohere.svg`,Cometapi:`${o}cometapi.svg`,Cursor:`${o}cursor.svg`,"Databricks (Qwen API)":`${o}databricks.svg`,Dashscope:`${o}dashscope.svg`,Deepseek:`${o}deepseek.svg`,Deepgram:`${o}deepgram.png`,DeepInfra:`${o}deepinfra.png`,ElevenLabs:`${o}elevenlabs.png`,"Fal AI":`${o}fal_ai.jpg`,"Featherless Ai":`${o}featherless.svg`,"Fireworks AI":`${o}fireworks.svg`,Friendliai:`${o}friendli.svg`,"Github Copilot":`${o}github_copilot.svg`,"Google AI Studio":`${o}google.svg`,GradientAI:`${o}gradientai.svg`,Groq:`${o}groq.svg`,vllm:`${o}vllm.png`,Huggingface:`${o}huggingface.svg`,Hyperbolic:`${o}hyperbolic.svg`,Infinity:`${o}infinity.png`,"Jina AI":`${o}jina.png`,"Lambda Ai":`${o}lambda.svg`,"Lm Studio":`${o}lmstudio.svg`,"Meta Llama":`${o}meta_llama.svg`,MiniMax:`${o}minimax.svg`,"Mistral AI":`${o}mistral.svg`,Moonshot:`${o}moonshot.svg`,Morph:`${o}morph.svg`,Nebius:`${o}nebius.svg`,Novita:`${o}novita.svg`,"Nvidia Nim":`${o}nvidia_nim.svg`,Ollama:`${o}ollama.svg`,"Ollama Chat":`${o}ollama.svg`,Oobabooga:`${o}openai_small.svg`,OpenAI:`${o}openai_small.svg`,"Openai Like":`${o}openai_small.svg`,"OpenAI Text Completion":`${o}openai_small.svg`,"OpenAI-Compatible Text Completion Models (Together AI, etc.)":`${o}openai_small.svg`,"OpenAI-Compatible Endpoints (Together AI, etc.)":`${o}openai_small.svg`,Openrouter:`${o}openrouter.svg`,"Oracle Cloud Infrastructure (OCI)":`${o}oracle.svg`,Perplexity:`${o}perplexity-ai.svg`,Recraft:`${o}recraft.svg`,Replicate:`${o}replicate.svg`,RunwayML:`${o}runwayml.png`,Sagemaker:`${o}bedrock.svg`,Sambanova:`${o}sambanova.svg`,"SAP Generative AI Hub":`${o}sap.png`,Snowflake:`${o}snowflake.svg`,"Text-Completion-Codestral":`${o}mistral.svg`,TogetherAI:`${o}togetherai.svg`,Topaz:`${o}topaz.svg`,Triton:`${o}nvidia_triton.png`,V0:`${o}v0.svg`,"Vercel Ai Gateway":`${o}vercel.svg`,"Vertex AI (Anthropic, Gemini, etc.)":`${o}google.svg`,"Vertex Ai Beta":`${o}google.svg`,Vllm:`${o}vllm.png`,VolcEngine:`${o}volcengine.png`,"Voyage AI":`${o}voyage.webp`,Watsonx:`${o}watsonx.svg`,"Watsonx Text":`${o}watsonx.svg`,xAI:`${o}xai.svg`,Xinference:`${o}xinference.svg`};e.s(["Providers",()=>r,"getPlaceholder",0,e=>{if("AI/ML API"===e)return"aiml/flux-pro/v1.1";if("Vertex AI (Anthropic, Gemini, etc.)"===e)return"gemini-pro";if("Anthropic"==e)return"claude-3-opus";if("Amazon Bedrock"==e)return"claude-3-opus";if("AWS SageMaker"==e)return"sagemaker/jumpstart-dft-meta-textgeneration-llama-2-7b";else if("Google AI Studio"==e)return"gemini-pro";else if("Azure AI Foundry (Studio)"==e)return"azure_ai/command-r-plus";else if("Azure"==e)return"my-deployment";else if("Oracle Cloud Infrastructure (OCI)"==e)return"oci/xai.grok-4";else if("Snowflake"==e)return"snowflake/mistral-7b";else if("Voyage AI"==e)return"voyage/";else if("Jina AI"==e)return"jina_ai/";else if("VolcEngine"==e)return"volcengine/";else if("DeepInfra"==e)return"deepinfra/";else if("Fal AI"==e)return"fal_ai/fal-ai/flux-pro/v1.1-ultra";else if("RunwayML"==e)return"runwayml/gen4_turbo";else if("Watsonx"===e)return"watsonx/ibm/granite-3-3-8b-instruct";else if("Cursor"===e)return"cursor/claude-4-sonnet";else return"gpt-3.5-turbo"},"getProviderLogoAndName",0,e=>{if(!e)return{logo:"",displayName:"-"};if("gemini"===e.toLowerCase()){let e="Google AI Studio";return{logo:i[e],displayName:e}}let t=Object.keys(a).find(t=>a[t].toLowerCase()===e.toLowerCase());if(!t)return{logo:"",displayName:e};let o=r[t];return{logo:i[o],displayName:o}},"getProviderModels",0,(e,t)=>{console.log(`Provider key: ${e}`);let r=a[e];console.log(`Provider mapped to: ${r}`);let o=[];return e&&"object"==typeof t&&(Object.entries(t).forEach(([e,t])=>{if(null!==t&&"object"==typeof t&&"litellm_provider"in t){let a=t.litellm_provider;(a===r||"string"==typeof a&&a.includes(r))&&o.push(e)}}),"Cohere"==e&&(console.log("Adding cohere chat models"),Object.entries(t).forEach(([e,t])=>{null!==t&&"object"==typeof t&&"litellm_provider"in t&&"cohere_chat"===t.litellm_provider&&o.push(e)})),"AWS SageMaker"==e&&(console.log("Adding sagemaker chat models"),Object.entries(t).forEach(([e,t])=>{null!==t&&"object"==typeof t&&"litellm_provider"in t&&"sagemaker_chat"===t.litellm_provider&&o.push(e)}))),o},"providerLogoMap",0,i,"provider_map",0,a])},798496,e=>{"use strict";var t=e.i(843476),r=e.i(152990),a=e.i(682830),o=e.i(271645),i=e.i(269200),n=e.i(427612),s=e.i(64848),l=e.i(942232),c=e.i(496020),d=e.i(977572),u=e.i(94629),g=e.i(360820),p=e.i(871943);function m({data:e=[],columns:m,isLoading:f=!1,defaultSorting:h=[],pagination:_,onPaginationChange:b,enablePagination:A=!1,onRowClick:v}){let[I,x]=o.default.useState(h),[C]=o.default.useState("onChange"),[w,E]=o.default.useState({}),[y,O]=o.default.useState({}),T=(0,r.useReactTable)({data:e,columns:m,state:{sorting:I,columnSizing:w,columnVisibility:y,...A&&_?{pagination:_}:{}},columnResizeMode:C,onSortingChange:x,onColumnSizingChange:E,onColumnVisibilityChange:O,...A&&b?{onPaginationChange:b}:{},getCoreRowModel:(0,a.getCoreRowModel)(),getSortedRowModel:(0,a.getSortedRowModel)(),...A?{getPaginationRowModel:(0,a.getPaginationRowModel)()}:{},enableSorting:!0,enableColumnResizing:!0,defaultColumn:{minSize:40,maxSize:500}});return(0,t.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,t.jsx)("div",{className:"overflow-x-auto",children:(0,t.jsx)("div",{className:"relative min-w-full",children:(0,t.jsxs)(i.Table,{className:"[&_td]:py-2 [&_th]:py-2",style:{width:T.getTotalSize(),minWidth:"100%",tableLayout:"fixed"},children:[(0,t.jsx)(n.TableHead,{children:T.getHeaderGroups().map(e=>(0,t.jsx)(c.TableRow,{children:e.headers.map(e=>(0,t.jsxs)(s.TableHeaderCell,{className:`py-1 h-8 relative ${"actions"===e.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)] w-[120px] ml-8":""} ${e.column.columnDef.meta?.className||""}`,style:{width:"actions"===e.id?120:e.getSize(),position:"actions"===e.id?"sticky":"relative",right:"actions"===e.id?0:"auto"},onClick:e.column.getCanSort()?e.column.getToggleSortingHandler():void 0,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,r.flexRender)(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)(g.ChevronUpIcon,{className:"h-4 w-4 text-blue-500"}),desc:(0,t.jsx)(p.ChevronDownIcon,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,t.jsx)(u.SwitchVerticalIcon,{className:"h-4 w-4 text-gray-400"})})]}),e.column.getCanResize()&&(0,t.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 ${e.column.getIsResizing()?"bg-blue-500":"hover:bg-blue-200"}`})]},e.id))},e.id))}),(0,t.jsx)(l.TableBody,{children:f?(0,t.jsx)(c.TableRow,{children:(0,t.jsx)(d.TableCell,{colSpan:m.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:"🚅 Loading models..."})})})}):T.getRowModel().rows.length>0?T.getRowModel().rows.map(e=>(0,t.jsx)(c.TableRow,{onClick:()=>v?.(e.original),className:v?"cursor-pointer hover:bg-gray-50":"",children:e.getVisibleCells().map(e=>(0,t.jsx)(d.TableCell,{className:`py-0.5 overflow-hidden ${"actions"===e.column.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)] w-[120px] ml-8":""} ${e.column.columnDef.meta?.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,r.flexRender)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,t.jsx)(c.TableRow,{children:(0,t.jsx)(d.TableCell,{colSpan:m.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:"No models found"})})})})})]})})})})}e.s(["ModelDataTable",()=>m])},56456,e=>{"use strict";var t=e.i(739295);e.s(["LoadingOutlined",()=>t.default])},771674,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M858.5 763.6a374 374 0 00-80.6-119.5 375.63 375.63 0 00-119.5-80.6c-.4-.2-.8-.3-1.2-.5C719.5 518 760 444.7 760 362c0-137-111-248-248-248S264 225 264 362c0 82.7 40.5 156 102.8 201.1-.4.2-.8.3-1.2.5-44.8 18.9-85 46-119.5 80.6a375.63 375.63 0 00-80.6 119.5A371.7 371.7 0 00136 901.8a8 8 0 008 8.2h60c4.4 0 7.9-3.5 8-7.8 2-77.2 33-149.5 87.8-204.3 56.7-56.7 132-87.9 212.2-87.9s155.5 31.2 212.2 87.9C779 752.7 810 825 812 902.2c.1 4.4 3.6 7.8 8 7.8h60a8 8 0 008-8.2c-1-47.8-10.9-94.3-29.5-138.2zM512 534c-45.9 0-89.1-17.9-121.6-50.4S340 407.9 340 362c0-45.9 17.9-89.1 50.4-121.6S466.1 190 512 190s89.1 17.9 121.6 50.4S684 316.1 684 362c0 45.9-17.9 89.1-50.4 121.6S557.9 534 512 534z"}}]},name:"user",theme:"outlined"};var o=e.i(9583),i=r.forwardRef(function(e,i){return r.createElement(o.default,(0,t.default)({},e,{ref:i,icon:a}))});e.s(["UserOutlined",0,i],771674)},948401,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M928 160H96c-17.7 0-32 14.3-32 32v640c0 17.7 14.3 32 32 32h832c17.7 0 32-14.3 32-32V192c0-17.7-14.3-32-32-32zm-40 110.8V792H136V270.8l-27.6-21.5 39.3-50.5 42.8 33.3h643.1l42.8-33.3 39.3 50.5-27.7 21.5zM833.6 232L512 482 190.4 232l-42.8-33.3-39.3 50.5 27.6 21.5 341.6 265.6a55.99 55.99 0 0068.7 0L888 270.8l27.6-21.5-39.3-50.5-42.7 33.2z"}}]},name:"mail",theme:"outlined"};var o=e.i(9583),i=r.forwardRef(function(e,i){return r.createElement(o.default,(0,t.default)({},e,{ref:i,icon:a}))});e.s(["MailOutlined",0,i],948401)},250980,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v3m0 0v3m0-3h3m-3 0H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z"}))});e.s(["PlusCircleIcon",0,r],250980)},502547,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"}))});e.s(["ChevronRightIcon",0,r],502547)},434626,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("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"}))});e.s(["ExternalLinkIcon",0,r],434626)},902555,e=>{"use strict";var t=e.i(843476),r=e.i(591935),a=e.i(122577),o=e.i(278587),i=e.i(68155),n=e.i(360820),s=e.i(871943),l=e.i(434626),c=e.i(592968),d=e.i(115504),u=e.i(752978);function g({icon:e,onClick:r,className:a,disabled:o,dataTestId:i}){return o?(0,t.jsx)(u.Icon,{icon:e,size:"sm",className:"opacity-50 cursor-not-allowed","data-testid":i}):(0,t.jsx)(u.Icon,{icon:e,size:"sm",onClick:r,className:(0,d.cx)("cursor-pointer",a),"data-testid":i})}let p={Edit:{icon:r.PencilAltIcon,className:"hover:text-blue-600"},Delete:{icon:i.TrashIcon,className:"hover:text-red-600"},Test:{icon:a.PlayIcon,className:"hover:text-blue-600"},Regenerate:{icon:o.RefreshIcon,className:"hover:text-green-600"},Up:{icon:n.ChevronUpIcon,className:"hover:text-blue-600"},Down:{icon:s.ChevronDownIcon,className:"hover:text-blue-600"},Open:{icon:l.ExternalLinkIcon,className:"hover:text-green-600"}};function m({onClick:e,tooltipText:r,disabled:a=!1,disabledTooltipText:o,dataTestId:i,variant:n}){let{icon:s,className:l}=p[n];return(0,t.jsx)(c.Tooltip,{title:a?o:r,children:(0,t.jsx)("span",{children:(0,t.jsx)(g,{icon:s,onClick:e,className:l,disabled:a,dataTestId:i})})})}e.s(["default",()=>m],902555)},122577,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"}),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 12a9 9 0 11-18 0 9 9 0 0118 0z"}))});e.s(["PlayIcon",0,r],122577)},278587,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",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"}))});e.s(["RefreshIcon",0,r],278587)},207670,e=>{"use strict";function t(){for(var e,t,r=0,a="",o=arguments.length;rt,"default",0,t])},728889,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(829087),o=e.i(480731),i=e.i(444755),n=e.i(673706),s=e.i(95779);let l={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"}},c={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"}},d={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:""}},u=(0,n.makeClassName)("Icon"),g=r.default.forwardRef((e,g)=>{let{icon:p,variant:m="simple",tooltip:f,size:h=o.Sizes.SM,color:_,className:b}=e,A=(0,t.__rest)(e,["icon","variant","tooltip","size","color","className"]),v=((e,t)=>{switch(e){case"simple":return{textColor:t?(0,n.getColorClassNames)(t,s.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",bgColor:"",borderColor:"",ringColor:""};case"light":return{textColor:t?(0,n.getColorClassNames)(t,s.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",bgColor:t?(0,i.tremorTwMerge)((0,n.getColorClassNames)(t,s.colorPalette.background).bgColor,"bg-opacity-20"):"bg-tremor-brand-muted dark:bg-dark-tremor-brand-muted",borderColor:"",ringColor:""};case"shadow":return{textColor:t?(0,n.getColorClassNames)(t,s.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",bgColor:t?(0,i.tremorTwMerge)((0,n.getColorClassNames)(t,s.colorPalette.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:t?(0,n.getColorClassNames)(t,s.colorPalette.text).textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",bgColor:t?(0,i.tremorTwMerge)((0,n.getColorClassNames)(t,s.colorPalette.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:t?(0,n.getColorClassNames)(t,s.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",bgColor:t?(0,i.tremorTwMerge)((0,n.getColorClassNames)(t,s.colorPalette.background).bgColor,"bg-opacity-20"):"bg-tremor-background dark:bg-dark-tremor-background",borderColor:t?(0,n.getColorClassNames)(t,s.colorPalette.ring).borderColor:"border-tremor-brand-subtle dark:border-dark-tremor-brand-subtle",ringColor:t?(0,i.tremorTwMerge)((0,n.getColorClassNames)(t,s.colorPalette.ring).ringColor,"ring-opacity-40"):"ring-tremor-brand-muted dark:ring-dark-tremor-brand-muted"}}})(m,_),{tooltipProps:I,getReferenceProps:x}=(0,a.useTooltip)();return r.default.createElement("span",Object.assign({ref:(0,n.mergeRefs)([g,I.refs.setReference]),className:(0,i.tremorTwMerge)(u("root"),"inline-flex shrink-0 items-center justify-center",v.bgColor,v.textColor,v.borderColor,v.ringColor,d[m].rounded,d[m].border,d[m].shadow,d[m].ring,l[h].paddingX,l[h].paddingY,b)},x,A),r.default.createElement(a.default,Object.assign({text:f},I)),r.default.createElement(p,{className:(0,i.tremorTwMerge)(u("icon"),"shrink-0",c[h].height,c[h].width)}))});g.displayName="Icon",e.s(["default",()=>g],728889)},752978,e=>{"use strict";var t=e.i(728889);e.s(["Icon",()=>t.default])},591935,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.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.s(["PencilAltIcon",0,r],591935)},100486,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M899.6 276.5L705 396.4 518.4 147.5a8.06 8.06 0 00-12.9 0L319 396.4 124.3 276.5c-5.7-3.5-13.1 1.2-12.2 7.9L188.5 865c1.1 7.9 7.9 14 16 14h615.1c8 0 14.9-6 15.9-14l76.4-580.6c.8-6.7-6.5-11.4-12.3-7.9zm-126 534.1H250.3l-53.8-409.4 139.8 86.1L512 252.9l175.7 234.4 139.8-86.1-53.9 409.4zM512 509c-62.1 0-112.6 50.5-112.6 112.6S449.9 734.2 512 734.2s112.6-50.5 112.6-112.6S574.1 509 512 509zm0 160.9c-26.6 0-48.2-21.6-48.2-48.3 0-26.6 21.6-48.3 48.2-48.3s48.2 21.6 48.2 48.3c0 26.6-21.6 48.3-48.2 48.3z"}}]},name:"crown",theme:"outlined"};var o=e.i(9583),i=r.forwardRef(function(e,i){return r.createElement(o.default,(0,t.default)({},e,{ref:i,icon:a}))});e.s(["CrownOutlined",0,i],100486)},209261,e=>{"use strict";e.s(["extractCategories",0,e=>{let t=new Set;return e.forEach(e=>{e.category&&""!==e.category.trim()&&t.add(e.category)}),["All",...Array.from(t).sort(),"Other"]},"filterPluginsByCategory",0,(e,t)=>"All"===t?e:"Other"===t?e.filter(e=>!e.category||""===e.category.trim()):e.filter(e=>e.category===t),"filterPluginsBySearch",0,(e,t)=>{if(!t||""===t.trim())return e;let r=t.toLowerCase().trim();return e.filter(e=>{let t=e.name.toLowerCase().includes(r),a=e.description?.toLowerCase().includes(r)||!1,o=e.keywords?.some(e=>e.toLowerCase().includes(r))||!1;return t||a||o})},"formatDateString",0,e=>{if(!e)return"N/A";try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}catch(e){return"Invalid date"}},"formatInstallCommand",0,e=>"github"===e.source.source&&e.source.repo?`/plugin marketplace add ${e.source.repo}`:"url"===e.source.source&&e.source.url?`/plugin marketplace add ${e.source.url}`:`/plugin marketplace add ${e.name}`,"getCategoryBadgeColor",0,e=>{if(!e)return"gray";let t=e.toLowerCase();if(t.includes("development")||t.includes("dev"))return"blue";if(t.includes("productivity")||t.includes("workflow"))return"green";if(t.includes("learning")||t.includes("education"))return"purple";if(t.includes("security")||t.includes("safety"))return"red";if(t.includes("data")||t.includes("analytics"))return"orange";else if(t.includes("integration")||t.includes("api"))return"yellow";return"gray"},"getSourceDisplayText",0,e=>"github"===e.source&&e.repo?`GitHub: ${e.repo}`:"url"===e.source&&e.url?e.url:"Unknown source","getSourceLink",0,e=>"github"===e.source&&e.repo?`https://github.com/${e.repo}`:"url"===e.source&&e.url?e.url:null,"isValidEmail",0,e=>!e||/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e),"isValidSemanticVersion",0,e=>!e||/^\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?(\+[a-zA-Z0-9.-]+)?$/.test(e),"isValidUrl",0,e=>{if(!e)return!0;try{return new URL(e),!0}catch{return!1}},"parseKeywords",0,e=>e&&""!==e.trim()?e.split(",").map(e=>e.trim()).filter(e=>""!==e):[],"validatePluginName",0,e=>!!e&&""!==e.trim()&&/^[a-z0-9-]+$/.test(e)])},94629,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4"}))});e.s(["SwitchVerticalIcon",0,r],94629)},991124,e=>{"use strict";let t=(0,e.i(475254).default)("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"}]]);e.s(["default",()=>t])},879664,e=>{"use strict";let t=(0,e.i(475254).default)("info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]);e.s(["default",()=>t])},115571,e=>{"use strict";let t="local-storage-change";function r(e){window.dispatchEvent(new CustomEvent(t,{detail:{key:e}}))}function a(e){try{return window.localStorage.getItem(e)}catch(t){return console.warn(`Error reading localStorage key "${e}":`,t),null}}function o(e,t){try{window.localStorage.setItem(e,t)}catch(t){console.warn(`Error setting localStorage key "${e}":`,t)}}function i(e){try{window.localStorage.removeItem(e)}catch(t){console.warn(`Error removing localStorage key "${e}":`,t)}}e.s(["LOCAL_STORAGE_EVENT",0,t,"emitLocalStorageChange",()=>r,"getLocalStorageItem",()=>a,"removeLocalStorageItem",()=>i,"setLocalStorageItem",()=>o])},371401,e=>{"use strict";var t=e.i(115571),r=e.i(271645);function a(e){let r=t=>{"disableUsageIndicator"===t.key&&e()},a=t=>{let{key:r}=t.detail;"disableUsageIndicator"===r&&e()};return window.addEventListener("storage",r),window.addEventListener(t.LOCAL_STORAGE_EVENT,a),()=>{window.removeEventListener("storage",r),window.removeEventListener(t.LOCAL_STORAGE_EVENT,a)}}function o(){return"true"===(0,t.getLocalStorageItem)("disableUsageIndicator")}function i(){return(0,r.useSyncExternalStore)(a,o)}e.s(["useDisableUsageIndicator",()=>i])},275144,e=>{"use strict";var t=e.i(843476),r=e.i(271645),a=e.i(764205);let o=(0,r.createContext)(void 0);e.s(["ThemeProvider",0,({children:e,accessToken:i})=>{let[n,s]=(0,r.useState)(null),[l,c]=(0,r.useState)(null);return(0,r.useEffect)(()=>{(async()=>{try{let e=(0,a.getProxyBaseUrl)(),t=e?`${e}/get/ui_theme_settings`:"/get/ui_theme_settings",r=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}});if(r.ok){let e=await r.json();e.values?.logo_url&&s(e.values.logo_url),e.values?.favicon_url&&c(e.values.favicon_url)}}catch(e){console.warn("Failed to load theme settings from backend:",e)}})()},[]),(0,r.useEffect)(()=>{if(l){let e=document.querySelectorAll("link[rel*='icon']");if(e.length>0)e.forEach(e=>{e.href=l});else{let e=document.createElement("link");e.rel="icon",e.href=l,document.head.appendChild(e)}}},[l]),(0,t.jsx)(o.Provider,{value:{logoUrl:n,setLogoUrl:s,faviconUrl:l,setFaviconUrl:c},children:e})},"useTheme",0,()=>{let e=(0,r.useContext)(o);if(!e)throw Error("useTheme must be used within a ThemeProvider");return e}])},326373,e=>{"use strict";var t=e.i(21539);e.s(["Dropdown",()=>t.default])},264843,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M464 512a48 48 0 1096 0 48 48 0 10-96 0zm200 0a48 48 0 1096 0 48 48 0 10-96 0zm-400 0a48 48 0 1096 0 48 48 0 10-96 0zm661.2-173.6c-22.6-53.7-55-101.9-96.3-143.3a444.35 444.35 0 00-143.3-96.3C630.6 75.7 572.2 64 512 64h-2c-60.6.3-119.3 12.3-174.5 35.9a445.35 445.35 0 00-142 96.5c-40.9 41.3-73 89.3-95.2 142.8-23 55.4-34.6 114.3-34.3 174.9A449.4 449.4 0 00112 714v152a46 46 0 0046 46h152.1A449.4 449.4 0 00510 960h2.1c59.9 0 118-11.6 172.7-34.3a444.48 444.48 0 00142.8-95.2c41.3-40.9 73.8-88.7 96.5-142 23.6-55.2 35.6-113.9 35.9-174.5.3-60.9-11.5-120-34.8-175.6zm-151.1 438C704 845.8 611 884 512 884h-1.7c-60.3-.3-120.2-15.3-173.1-43.5l-8.4-4.5H188V695.2l-4.5-8.4C155.3 633.9 140.3 574 140 513.7c-.4-99.7 37.7-193.3 107.6-263.8 69.8-70.5 163.1-109.5 262.8-109.9h1.7c50 0 98.5 9.7 144.2 28.9 44.6 18.7 84.6 45.6 119 80 34.3 34.3 61.3 74.4 80 119 19.4 46.2 29.1 95.2 28.9 145.8-.6 99.6-39.7 192.9-110.1 262.7z"}}]},name:"message",theme:"outlined"};var o=e.i(9583),i=r.forwardRef(function(e,i){return r.createElement(o.default,(0,t.default)({},e,{ref:i,icon:a}))});e.s(["MessageOutlined",0,i],264843)},44121,186515,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M408 442h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8zm-8 204c0 4.4 3.6 8 8 8h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56zm504-486H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm0 632H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zM115.4 518.9L271.7 642c5.8 4.6 14.4.5 14.4-6.9V388.9c0-7.4-8.5-11.5-14.4-6.9L115.4 505.1a8.74 8.74 0 000 13.8z"}}]},name:"menu-fold",theme:"outlined"};var o=e.i(9583),i=r.forwardRef(function(e,i){return r.createElement(o.default,(0,t.default)({},e,{ref:i,icon:a}))});e.s(["MenuFoldOutlined",0,i],44121);let n={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M408 442h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8zm-8 204c0 4.4 3.6 8 8 8h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56zm504-486H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm0 632H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zM142.4 642.1L298.7 519a8.84 8.84 0 000-13.9L142.4 381.9c-5.8-4.6-14.4-.5-14.4 6.9v246.3a8.9 8.9 0 0014.4 7z"}}]},name:"menu-unfold",theme:"outlined"};var s=r.forwardRef(function(e,a){return r.createElement(o.default,(0,t.default)({},e,{ref:a,icon:n}))});e.s(["MenuUnfoldOutlined",0,s],186515)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/117fd0772eee5df6.js b/litellm/proxy/_experimental/out/_next/static/chunks/117fd0772eee5df6.js new file mode 100644 index 00000000000..f469de11af7 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/117fd0772eee5df6.js @@ -0,0 +1 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,355619,e=>{"use strict";var s=e.i(764205);let t=async(e,t,l)=>{try{if(null===e||null===t)return;if(null!==l){let a=(await (0,s.modelAvailableCall)(l,e,t,!0,null,!0)).data.map(e=>e.id),r=[],i=[];return a.forEach(e=>{e.endsWith("/*")?r.push(e):i.push(e)}),[...r,...i]}}catch(e){console.error("Error fetching user models:",e)}};e.s(["fetchAvailableModelsForTeamOrKey",0,t,"getModelDisplayName",0,e=>{if("all-proxy-models"===e)return"All Proxy Models";if(e.endsWith("/*")){let s=e.replace("/*","");return`All ${s} models`}return e},"unfurlWildcardModelsInList",0,(e,s)=>{let t=[],l=[];return console.log("teamModels",e),console.log("allModels",s),e.forEach(e=>{if(e.endsWith("/*")){let a=e.replace("/*",""),r=s.filter(e=>e.startsWith(a+"/"));l.push(...r),t.push(e)}else l.push(e)}),[...t,...l].filter((e,s,t)=>t.indexOf(e)===s)}])},860585,e=>{"use strict";var s=e.i(843476),t=e.i(199133);let{Option:l}=t.Select;e.s(["default",0,({value:e,onChange:a,className:r="",style:i={}})=>(0,s.jsxs)(t.Select,{style:{width:"100%",...i},value:e||void 0,onChange:a,className:r,placeholder:"n/a",allowClear:!0,children:[(0,s.jsx)(l,{value:"24h",children:"daily"}),(0,s.jsx)(l,{value:"7d",children:"weekly"}),(0,s.jsx)(l,{value:"30d",children:"monthly"})]}),"getBudgetDurationLabel",0,e=>e?({"24h":"daily","7d":"weekly","30d":"monthly"})[e]||e:"Not set"])},663435,e=>{"use strict";var s=e.i(843476),t=e.i(199133);e.s(["default",0,({teams:e,value:l,onChange:a,disabled:r,loading:i})=>(0,s.jsx)(t.Select,{showSearch:!0,placeholder:"Search or select a team",value:l,onChange:a,disabled:r,loading:i,allowClear:!0,filterOption:(s,t)=>{if(!t)return!1;let l=e?.find(e=>e.team_id===t.key);if(!l)return!1;let a=s.toLowerCase().trim(),r=(l.team_alias||"").toLowerCase(),i=(l.team_id||"").toLowerCase();return r.includes(a)||i.includes(a)},optionFilterProp:"children",children:e?.map(e=>(0,s.jsxs)(t.Select.Option,{value:e.team_id,children:[(0,s.jsx)("span",{className:"font-medium",children:e.team_alias})," ",(0,s.jsxs)("span",{className:"text-gray-500",children:["(",e.team_id,")"]})]},e.team_id))})])},213205,e=>{"use strict";e.i(247167);var s=e.i(931067),t=e.i(271645);let l={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M678.3 642.4c24.2-13 51.9-20.4 81.4-20.4h.1c3 0 4.4-3.6 2.2-5.6a371.67 371.67 0 00-103.7-65.8c-.4-.2-.8-.3-1.2-.5C719.2 505 759.6 431.7 759.6 349c0-137-110.8-248-247.5-248S264.7 212 264.7 349c0 82.7 40.4 156 102.6 201.1-.4.2-.8.3-1.2.5-44.7 18.9-84.8 46-119.3 80.6a373.42 373.42 0 00-80.4 119.5A373.6 373.6 0 00137 888.8a8 8 0 008 8.2h59.9c4.3 0 7.9-3.5 8-7.8 2-77.2 32.9-149.5 87.6-204.3C357 628.2 432.2 597 512.2 597c56.7 0 111.1 15.7 158 45.1a8.1 8.1 0 008.1.3zM512.2 521c-45.8 0-88.9-17.9-121.4-50.4A171.2 171.2 0 01340.5 349c0-45.9 17.9-89.1 50.3-121.6S466.3 177 512.2 177s88.9 17.9 121.4 50.4A171.2 171.2 0 01683.9 349c0 45.9-17.9 89.1-50.3 121.6C601.1 503.1 558 521 512.2 521zM880 759h-84v-84c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v84h-84c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h84v84c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8v-84h84c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8z"}}]},name:"user-add",theme:"outlined"};var a=e.i(9583),r=t.forwardRef(function(e,r){return t.createElement(a.default,(0,s.default)({},e,{ref:r,icon:l}))});e.s(["UserAddOutlined",0,r],213205)},285027,e=>{"use strict";e.i(247167);var s=e.i(931067),t=e.i(271645);let l={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"};var a=e.i(9583),r=t.forwardRef(function(e,r){return t.createElement(a.default,(0,s.default)({},e,{ref:r,icon:l}))});e.s(["WarningOutlined",0,r],285027)},447082,e=>{"use strict";var s=e.i(843476),t=e.i(271645),l=e.i(599724),a=e.i(464571),r=e.i(212931),i=e.i(291542),n=e.i(515831),d=e.i(898586),o=e.i(519756),c=e.i(737434),m=e.i(285027),u=e.i(993914),x=e.i(955135);e.i(247167);var h=e.i(931067);let p={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"};var f=e.i(9583),g=t.forwardRef(function(e,s){return t.createElement(f.default,(0,h.default)({},e,{ref:s,icon:p}))}),j=e.i(764205),y=e.i(59935),v=e.i(220508),b=e.i(964306);let w=t.forwardRef(function(e,s){return t.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:s},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"}))});var N=e.i(237016),_=e.i(727749);e.s(["default",0,({accessToken:e,teams:h,possibleUIRoles:p,onUsersCreated:f})=>{let[C,S]=(0,t.useState)(!1),[k,I]=(0,t.useState)([]),[T,U]=(0,t.useState)(!1),[V,O]=(0,t.useState)(null),[B,L]=(0,t.useState)(null),[M,F]=(0,t.useState)(null),[z,E]=(0,t.useState)(null),[P,A]=(0,t.useState)(null),[R,D]=(0,t.useState)("http://localhost:4000");(0,t.useEffect)(()=>{(async()=>{try{let s=await (0,j.getProxyUISettings)(e);A(s)}catch(e){console.error("Error fetching UI settings:",e)}})(),D(new URL("/",window.location.href).toString())},[e]);let $=async()=>{U(!0);let s=k.map(e=>({...e,status:"pending"}));I(s);let t=!1;for(let l=0;le.trim()).filter(Boolean),0===s.teams.length&&delete s.teams),a.models&&"string"==typeof a.models&&""!==a.models.trim()&&(s.models=a.models.split(",").map(e=>e.trim()).filter(Boolean),0===s.models.length&&delete s.models),a.max_budget&&""!==a.max_budget.toString().trim()){let e=parseFloat(a.max_budget.toString());!isNaN(e)&&e>0&&(s.max_budget=e)}a.budget_duration&&""!==a.budget_duration.trim()&&(s.budget_duration=a.budget_duration.trim()),a.metadata&&"string"==typeof a.metadata&&""!==a.metadata.trim()&&(s.metadata=a.metadata.trim()),console.log("Sending user data:",s);let r=await (0,j.userCreateCall)(e,null,s);if(console.log("Full response:",r),r&&(r.key||r.user_id)){t=!0,console.log("Success case triggered");let s=r.data?.user_id||r.user_id;try{if(P?.SSO_ENABLED){let e=new URL("/ui",R).toString();I(s=>s.map((s,t)=>t===l?{...s,status:"success",key:r.key||r.user_id,invitation_link:e}:s))}else{let t=await (0,j.invitationCreateCall)(e,s),a=new URL(`/ui?invitation_id=${t.id}`,R).toString();I(e=>e.map((e,s)=>s===l?{...e,status:"success",key:r.key||r.user_id,invitation_link:a}:e))}}catch(e){console.error("Error creating invitation:",e),I(e=>e.map((e,s)=>s===l?{...e,status:"success",key:r.key||r.user_id,error:"User created but failed to generate invitation link"}:e))}}else{console.log("Error case triggered");let e=r?.error||"Failed to create user";console.log("Error message:",e),I(s=>s.map((s,t)=>t===l?{...s,status:"failed",error:e}:s))}}catch(s){console.error("Caught error:",s);let e=s?.response?.data?.error||s?.message||String(s);I(s=>s.map((s,t)=>t===l?{...s,status:"failed",error:e}:s))}}U(!1),t&&f&&f()},W=[{title:"Row",dataIndex:"rowNumber",key:"rowNumber",width:80},{title:"Email",dataIndex:"user_email",key:"user_email"},{title:"Role",dataIndex:"user_role",key:"user_role"},{title:"Teams",dataIndex:"teams",key:"teams"},{title:"Budget",dataIndex:"max_budget",key:"max_budget"},{title:"Status",key:"status",render:(e,t)=>t.isValid?t.status&&"pending"!==t.status?"success"===t.status?(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(v.CheckCircleIcon,{className:"h-5 w-5 text-green-500 mr-2"}),(0,s.jsx)("span",{className:"text-green-500",children:"Success"})]}),t.invitation_link&&(0,s.jsx)("div",{className:"mt-1",children:(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)("span",{className:"text-xs text-gray-500 truncate max-w-[150px]",children:t.invitation_link}),(0,s.jsx)(N.CopyToClipboard,{text:t.invitation_link,onCopy:()=>_.default.success("Invitation link copied!"),children:(0,s.jsx)("button",{className:"ml-1 text-blue-500 text-xs hover:text-blue-700",children:"Copy"})})]})})]}):(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(b.XCircleIcon,{className:"h-5 w-5 text-red-500 mr-2"}),(0,s.jsx)("span",{className:"text-red-500",children:"Failed"})]}),t.error&&(0,s.jsx)("span",{className:"text-sm text-red-500 ml-7",children:JSON.stringify(t.error)})]}):(0,s.jsx)("span",{className:"text-gray-500",children:"Pending"}):(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(b.XCircleIcon,{className:"h-5 w-5 text-red-500 mr-2"}),(0,s.jsx)("span",{className:"text-red-500",children:"Invalid"})]}),t.error&&(0,s.jsx)("span",{className:"text-sm text-red-500 ml-7",children:t.error})]})}];return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(a.Button,{type:"primary",className:"mb-0",onClick:()=>S(!0),children:"+ Bulk Invite Users"}),(0,s.jsx)(r.Modal,{title:"Bulk Invite Users",open:C,width:800,onCancel:()=>S(!1),bodyStyle:{maxHeight:"70vh",overflow:"auto"},footer:null,children:(0,s.jsx)("div",{className:"flex flex-col",children:0===k.length?(0,s.jsxs)("div",{className:"mb-6",children:[(0,s.jsxs)("div",{className:"flex items-center mb-4",children:[(0,s.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"1"}),(0,s.jsx)("h3",{className:"text-lg font-medium",children:"Download and fill the template"})]}),(0,s.jsxs)("div",{className:"ml-11 mb-6",children:[(0,s.jsx)("p",{className:"mb-4",children:"Add multiple users at once by following these steps:"}),(0,s.jsxs)("ol",{className:"list-decimal list-inside space-y-2 ml-2 mb-4",children:[(0,s.jsx)("li",{children:"Download our CSV template"}),(0,s.jsx)("li",{children:"Add your users' information to the spreadsheet"}),(0,s.jsx)("li",{children:"Save the file and upload it here"}),(0,s.jsx)("li",{children:"After creation, download the results file containing the Virtual Keys for each user"})]}),(0,s.jsxs)("div",{className:"bg-gray-50 p-4 rounded-md border border-gray-200 mb-4",children:[(0,s.jsx)("h4",{className:"font-medium mb-2",children:"Template Column Names"}),(0,s.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-red-500 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"user_email"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:"User's email address (required)"})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-red-500 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"user_role"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'User\'s role (one of: "proxy_admin", "proxy_admin_viewer", "internal_user", "internal_user_viewer")'})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"teams"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'Comma-separated team IDs (e.g., "team-1,team-2")'})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"max_budget"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'Maximum budget as a number (e.g., "100")'})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"budget_duration"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'Budget reset period (e.g., "30d", "1mo")'})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"models"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'Comma-separated allowed models (e.g., "gpt-3.5-turbo,gpt-4")'})]})]})]})]}),(0,s.jsx)(a.Button,{type:"primary",size:"large",className:"w-full md:w-auto",icon:(0,s.jsx)(c.DownloadOutlined,{}),children:"Download CSV Template"})]}),(0,s.jsxs)("div",{className:"flex items-center mb-4",children:[(0,s.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"2"}),(0,s.jsx)("h3",{className:"text-lg font-medium",children:"Upload your completed CSV"})]}),(0,s.jsxs)("div",{className:"ml-11",children:[z?(0,s.jsxs)("div",{className:`mb-4 p-4 rounded-md border ${M?"bg-red-50 border-red-200":"bg-blue-50 border-blue-200"}`,children:[(0,s.jsxs)("div",{className:"flex items-center justify-between",children:[(0,s.jsxs)("div",{className:"flex items-center",children:[M?(0,s.jsx)(g,{className:"text-red-500 text-xl mr-3"}):(0,s.jsx)(u.FileTextOutlined,{className:"text-blue-500 text-xl mr-3"}),(0,s.jsxs)("div",{children:[(0,s.jsx)(d.Typography.Text,{strong:!0,className:M?"text-red-800":"text-blue-800",children:z.name}),(0,s.jsxs)(d.Typography.Text,{className:`block text-xs ${M?"text-red-600":"text-blue-600"}`,children:[(z.size/1024).toFixed(1)," KB • ",new Date().toLocaleDateString()]})]})]}),(0,s.jsx)(a.Button,{size:"small",onClick:()=>{E(null),I([]),O(null),L(null),F(null)},className:"flex items-center",icon:(0,s.jsx)(x.DeleteOutlined,{}),children:"Remove"})]}),M?(0,s.jsxs)("div",{className:"mt-3 text-red-600 text-sm flex items-start",children:[(0,s.jsx)(m.WarningOutlined,{className:"mr-2 mt-0.5"}),(0,s.jsx)("span",{children:M})]}):!B&&(0,s.jsxs)("div",{className:"mt-3 flex items-center",children:[(0,s.jsx)("div",{className:"w-full bg-gray-200 rounded-full h-1.5",children:(0,s.jsx)("div",{className:"bg-blue-500 h-1.5 rounded-full w-full animate-pulse"})}),(0,s.jsx)("span",{className:"ml-2 text-xs text-blue-600",children:"Processing..."})]})]}):(0,s.jsx)(n.Upload,{beforeUpload:e=>((O(null),L(null),F(null),E(e),"text/csv"===e.type||e.name.endsWith(".csv"))?e.size>5242880?F(`File is too large (${(e.size/1048576).toFixed(1)} MB). Please upload a CSV file smaller than 5MB.`):y.default.parse(e,{complete:e=>{if(!e.data||0===e.data.length){L("The CSV file appears to be empty. Please upload a file with data."),I([]);return}if(1===e.data.length){L("The CSV file only contains headers but no user data. Please add user data to your CSV."),I([]);return}let s=e.data[0];if(0===s.length||1===s.length&&""===s[0]){L("The CSV file doesn't contain any column headers. Please make sure your CSV has headers."),I([]);return}let t=["user_email","user_role"].filter(e=>!s.includes(e));if(t.length>0){L(`Your CSV is missing these required columns: ${t.join(", ")}. Please add these columns to your CSV file.`),I([]);return}try{let t=e.data.slice(1).map((e,t)=>{if(0===e.length||1===e.length&&""===e[0])return null;if(e.length=parseFloat(l.max_budget.toString())&&a.push("Max budget must be greater than 0")),l.budget_duration&&!l.budget_duration.match(/^\d+[dhmwy]$|^\d+mo$/)&&a.push(`Invalid budget duration format "${l.budget_duration}". Use format like "30d", "1mo", "2w", "6h"`),l.teams&&"string"==typeof l.teams&&h&&h.length>0){let e=h.map(e=>e.team_id),s=l.teams.split(",").map(e=>e.trim()).filter(s=>!e.includes(s));s.length>0&&a.push(`Unknown team(s): ${s.join(", ")}`)}return a.length>0&&(l.isValid=!1,l.error=a.join(", ")),l}).filter(Boolean),l=t.filter(e=>e.isValid);I(t),0===t.length?L("No valid data rows found in the CSV file. Please check your file format."):0===l.length?O("No valid users found in the CSV. Please check the errors below and fix your CSV file."):l.length{O(`Failed to parse CSV file: ${e.message}`),I([])},header:!1}):(F(`Invalid file type: ${e.name}. Please upload a CSV file (.csv extension).`),_.default.fromBackend("Invalid file type. Please upload a CSV file.")),!1),accept:".csv",maxCount:1,showUploadList:!1,children:(0,s.jsxs)("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-blue-500 transition-colors cursor-pointer",children:[(0,s.jsx)(o.UploadOutlined,{className:"text-3xl text-gray-400 mb-2"}),(0,s.jsx)("p",{className:"mb-1",children:"Drag and drop your CSV file here"}),(0,s.jsx)("p",{className:"text-sm text-gray-500 mb-3",children:"or"}),(0,s.jsx)(a.Button,{size:"small",children:"Browse files"}),(0,s.jsx)("p",{className:"text-xs text-gray-500 mt-4",children:"Only CSV files (.csv) are supported"})]})}),B&&(0,s.jsx)("div",{className:"mb-4 p-4 bg-yellow-50 border border-yellow-200 rounded-md",children:(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)(w,{className:"h-5 w-5 text-yellow-500 mr-2 mt-0.5"}),(0,s.jsxs)("div",{children:[(0,s.jsx)(d.Typography.Text,{strong:!0,className:"text-yellow-800",children:"CSV Structure Error"}),(0,s.jsx)(d.Typography.Paragraph,{className:"text-yellow-700 mt-1 mb-0",children:B}),(0,s.jsx)(d.Typography.Paragraph,{className:"text-yellow-700 mt-2 mb-0",children:"Please download our template and ensure your CSV follows the required format."})]})]})})]})]}):(0,s.jsxs)("div",{className:"mb-6",children:[(0,s.jsxs)("div",{className:"flex items-center mb-4",children:[(0,s.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"3"}),(0,s.jsx)("h3",{className:"text-lg font-medium",children:k.some(e=>"success"===e.status||"failed"===e.status)?"User Creation Results":"Review and create users"})]}),V&&(0,s.jsx)("div",{className:"ml-11 mb-4 p-4 bg-red-50 border border-red-200 rounded-md",children:(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)(m.WarningOutlined,{className:"text-red-500 mr-2 mt-1"}),(0,s.jsxs)("div",{children:[(0,s.jsx)(l.Text,{className:"text-red-600 font-medium",children:V}),k.some(e=>!e.isValid)&&(0,s.jsxs)("ul",{className:"mt-2 list-disc list-inside text-red-600 text-sm",children:[(0,s.jsx)("li",{children:"Check the table below for specific errors in each row"}),(0,s.jsx)("li",{children:"Common issues include invalid email formats, missing required fields, or incorrect role values"}),(0,s.jsx)("li",{children:"Fix these issues in your CSV file and upload again"})]})]})]})}),(0,s.jsxs)("div",{className:"ml-11",children:[(0,s.jsxs)("div",{className:"flex justify-between items-center mb-3",children:[(0,s.jsx)("div",{className:"flex items-center",children:k.some(e=>"success"===e.status||"failed"===e.status)?(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(l.Text,{className:"text-lg font-medium mr-3",children:"Creation Summary"}),(0,s.jsxs)(l.Text,{className:"text-sm bg-green-100 text-green-800 px-2 py-1 rounded mr-2",children:[k.filter(e=>"success"===e.status).length," Successful"]}),k.some(e=>"failed"===e.status)&&(0,s.jsxs)(l.Text,{className:"text-sm bg-red-100 text-red-800 px-2 py-1 rounded",children:[k.filter(e=>"failed"===e.status).length," Failed"]})]}):(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(l.Text,{className:"text-lg font-medium mr-3",children:"User Preview"}),(0,s.jsxs)(l.Text,{className:"text-sm bg-blue-100 text-blue-800 px-2 py-1 rounded",children:[k.filter(e=>e.isValid).length," of ",k.length," users valid"]})]})}),!k.some(e=>"success"===e.status||"failed"===e.status)&&(0,s.jsxs)("div",{className:"flex space-x-3",children:[(0,s.jsx)(a.Button,{onClick:()=>{I([]),O(null)},children:"Back"}),(0,s.jsx)(a.Button,{type:"primary",onClick:$,disabled:0===k.filter(e=>e.isValid).length||T,children:T?"Creating...":`Create ${k.filter(e=>e.isValid).length} Users`})]})]}),k.some(e=>"success"===e.status)&&(0,s.jsx)("div",{className:"mb-4 p-4 bg-blue-50 border border-blue-200 rounded-md",children:(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"mr-3 mt-1",children:(0,s.jsx)(v.CheckCircleIcon,{className:"h-5 w-5 text-blue-500"})}),(0,s.jsxs)("div",{children:[(0,s.jsx)(l.Text,{className:"font-medium text-blue-800",children:"User creation complete"}),(0,s.jsxs)(l.Text,{className:"block text-sm text-blue-700 mt-1",children:[(0,s.jsx)("span",{className:"font-medium",children:"Next step:"})," Download the credentials file containing Virtual Keys and invitation links. Users will need these Virtual Keys to make LLM requests through LiteLLM."]})]})]})}),(0,s.jsx)(i.Table,{dataSource:k,columns:W,size:"small",pagination:{pageSize:5},scroll:{y:300},rowClassName:e=>e.isValid?"":"bg-red-50"}),!k.some(e=>"success"===e.status||"failed"===e.status)&&(0,s.jsxs)("div",{className:"flex justify-end mt-4",children:[(0,s.jsx)(a.Button,{onClick:()=>{I([]),O(null)},className:"mr-3",children:"Back"}),(0,s.jsx)(a.Button,{type:"primary",onClick:$,disabled:0===k.filter(e=>e.isValid).length||T,children:T?"Creating...":`Create ${k.filter(e=>e.isValid).length} Users`})]}),k.some(e=>"success"===e.status||"failed"===e.status)&&(0,s.jsxs)("div",{className:"flex justify-end mt-4",children:[(0,s.jsx)(a.Button,{onClick:()=>{I([]),O(null)},className:"mr-3",children:"Start New Bulk Import"}),(0,s.jsx)(a.Button,{type:"primary",onClick:()=>{let e=k.map(e=>({user_email:e.user_email,user_role:e.user_role,status:e.status,key:e.key||"",invitation_link:e.invitation_link||"",error:e.error||""})),s=new Blob([y.default.unparse(e)],{type:"text/csv"}),t=window.URL.createObjectURL(s),l=document.createElement("a");l.href=t,l.download="bulk_users_results.csv",document.body.appendChild(l),l.click(),document.body.removeChild(l),window.URL.revokeObjectURL(t)},icon:(0,s.jsx)(c.DownloadOutlined,{}),children:"Download User Credentials"})]})]})]})})})]})}],447082)},371455,172372,e=>{"use strict";var s=e.i(843476),t=e.i(827252),l=e.i(213205),a=e.i(912598),r=e.i(109799),i=e.i(677667),n=e.i(130643),d=e.i(898667),o=e.i(35983),c=e.i(779241),m=e.i(560445),u=e.i(464571),x=e.i(808613),h=e.i(311451),p=e.i(212931),f=e.i(199133),g=e.i(770914),j=e.i(592968),y=e.i(898586),v=e.i(271645),b=e.i(447082),w=e.i(663435),N=e.i(355619),_=e.i(727749),C=e.i(764205),S=e.i(237016),k=e.i(599724);function I({isInvitationLinkModalVisible:e,setIsInvitationLinkModalVisible:t,baseUrl:l,invitationLinkData:a,modalType:r="invitation"}){let{Title:i,Paragraph:n}=y.Typography,d=()=>{if(!l)return"";let e=new URL(l).pathname,s=e&&"/"!==e?`${e}/ui`:"ui";if(a?.has_user_setup_sso)return new URL(s,l).toString();let t=`${s}?invitation_id=${a?.id}`;return"resetPassword"===r&&(t+="&action=reset_password"),new URL(t,l).toString()};return(0,s.jsxs)(p.Modal,{title:"invitation"===r?"Invitation Link":"Reset Password Link",open:e,width:800,footer:null,onOk:()=>{t(!1)},onCancel:()=>{t(!1)},children:[(0,s.jsx)(n,{children:"invitation"===r?"Copy and send the generated link to onboard this user to the proxy.":"Copy and send the generated link to the user to reset their password."}),(0,s.jsxs)("div",{className:"flex justify-between pt-5 pb-2",children:[(0,s.jsx)(k.Text,{className:"text-base",children:"User ID"}),(0,s.jsx)(k.Text,{children:a?.user_id})]}),(0,s.jsxs)("div",{className:"flex justify-between pt-5 pb-2",children:[(0,s.jsx)(k.Text,{children:"invitation"===r?"Invitation Link":"Reset Password Link"}),(0,s.jsx)(k.Text,{children:(0,s.jsx)(k.Text,{children:d()})})]}),(0,s.jsx)("div",{className:"flex justify-end mt-5",children:(0,s.jsx)(S.CopyToClipboard,{text:d(),onCopy:()=>_.default.success("Copied!"),children:(0,s.jsx)(u.Button,{type:"primary",children:"invitation"===r?"Copy invitation link":"Copy password reset link"})})})]})}e.s(["default",()=>I],172372);let{Option:T}=f.Select,{Text:U,Link:V,Title:O}=y.Typography;e.s(["CreateUserButton",0,({userID:e,accessToken:y,teams:S,possibleUIRoles:k,onUserCreated:O,isEmbedded:B=!1})=>{let L=(0,a.useQueryClient)(),[M,F]=(0,v.useState)(null),[z]=x.Form.useForm(),[E,P]=(0,v.useState)(!1),[A,R]=(0,v.useState)(!1),[D,$]=(0,v.useState)([]),[W,K]=(0,v.useState)(!1),[q,H]=(0,v.useState)(null),[G,J]=(0,v.useState)(null),{data:Q=[]}=(0,r.useOrganizations)(),X=(0,v.useMemo)(()=>{let e=Q.flatMap(e=>e.teams||[]);return e.length>0?e:S||[]},[Q,S]);(0,v.useEffect)(()=>{let s=async()=>{try{let s=await (0,C.modelAvailableCall)(y,e,"any"),t=[];for(let e=0;e{try{_.default.info("Making API Call"),B||P(!0),s.models&&0!==s.models.length||"proxy_admin"===s.user_role||(s.models=["no-default-models"]),s.organization_ids&&(s.organizations=s.organization_ids,delete s.organization_ids);let t=await (0,C.userCreateCall)(y,null,s);await L.invalidateQueries({queryKey:["userList"]}),R(!0);let l=t.data?.user_id||t.user_id;if(O&&B){O(l),z.resetFields();return}if(M?.SSO_ENABLED){let s={id:"u">typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){let s=16*Math.random()|0;return("x"==e?s:3&s|8).toString(16)}),user_id:l,is_accepted:!1,accepted_at:null,expires_at:new Date(Date.now()+6048e5),created_at:new Date,created_by:e,updated_at:new Date,updated_by:e,has_user_setup_sso:!0};H(s),K(!0)}else(0,C.invitationCreateCall)(y,l).then(e=>{e.has_user_setup_sso=!1,H(e),K(!0)});_.default.success("API user Created"),z.resetFields(),localStorage.removeItem("userData"+e)}catch(s){let e=s.response?.data?.detail||s?.message||"Error creating the user";_.default.fromBackend(e),console.error("Error creating the user:",s)}};return B?(0,s.jsxs)(x.Form,{form:z,onFinish:Y,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,s.jsx)(m.Alert,{message:"Email invitations",description:(0,s.jsxs)(s.Fragment,{children:["New users receive an email invite only when an email integration (SMTP, Resend, or SendGrid) is configured."," ",(0,s.jsx)(V,{href:"https://docs.litellm.ai/docs/proxy/email",target:"_blank",children:"Learn how to set up email notifications"})]}),type:"info",showIcon:!0,className:"mb-4"}),(0,s.jsx)(x.Form.Item,{label:"User Email",name:"user_email",children:(0,s.jsx)(c.TextInput,{placeholder:""})}),(0,s.jsx)(x.Form.Item,{label:"User Role",name:"user_role",children:(0,s.jsx)(f.Select,{children:k&&Object.entries(k).map(([e,{ui_label:t,description:l}])=>(0,s.jsx)(o.SelectItem,{value:e,title:t,children:(0,s.jsxs)("div",{className:"flex",children:[t," ",(0,s.jsx)(U,{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:l})]})},e))})}),(0,s.jsx)(x.Form.Item,{label:"Team",name:"team_id",children:(0,s.jsx)(f.Select,{placeholder:"Select Team",style:{width:"100%"},children:(0,s.jsx)(w.default,{teams:X})})}),(0,s.jsx)(x.Form.Item,{label:"Metadata",name:"metadata",children:(0,s.jsx)(h.Input.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,s.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,s.jsx)(u.Button,{htmlType:"submit",children:"Create User"})})]}):(0,s.jsxs)("div",{className:"flex gap-2",children:[(0,s.jsx)(u.Button,{type:"primary",className:"mb-0",onClick:()=>P(!0),children:"+ Invite User"}),(0,s.jsx)(b.default,{accessToken:y,teams:S,possibleUIRoles:k}),(0,s.jsxs)(p.Modal,{title:"Invite User",open:E,width:800,footer:null,onOk:()=>{P(!1),z.resetFields()},onCancel:()=>{P(!1),R(!1),z.resetFields()},children:[(0,s.jsxs)(g.Space,{direction:"vertical",size:"middle",children:[(0,s.jsx)(U,{className:"mb-1",children:"Create a User who can own keys"}),(0,s.jsx)(m.Alert,{message:"Email invitations",description:(0,s.jsxs)(s.Fragment,{children:["New users receive an email invite only when an email integration (SMTP, Resend, or SendGrid) is configured."," ",(0,s.jsx)(V,{href:"https://docs.litellm.ai/docs/proxy/email",target:"_blank",children:"Learn how to set up email notifications"})]}),type:"info",showIcon:!0,className:"mb-4"})]}),(0,s.jsxs)(x.Form,{form:z,onFinish:Y,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,s.jsx)(x.Form.Item,{label:"User Email",name:"user_email",children:(0,s.jsx)(h.Input,{})}),(0,s.jsx)(x.Form.Item,{label:(0,s.jsxs)("span",{children:["Global Proxy Role"," ",(0,s.jsx)(j.Tooltip,{title:"This role is independent of any team/org specific roles. Configure Team / Organization Admins in the Settings",children:(0,s.jsx)(t.InfoCircleOutlined,{})})]}),name:"user_role",children:(0,s.jsx)(f.Select,{children:k&&Object.entries(k).map(([e,{ui_label:t,description:l}])=>(0,s.jsxs)(o.SelectItem,{value:e,title:t,children:[(0,s.jsx)(U,{children:t}),(0,s.jsxs)(U,{type:"secondary",children:[" - ",l]})]},e))})}),(0,s.jsx)(x.Form.Item,{label:"Team",className:"gap-2",name:"team_id",help:"If selected, user will be added as a 'user' role to the team.",children:(0,s.jsx)(w.default,{teams:X})}),(0,s.jsx)(x.Form.Item,{label:"Organization",name:"organization_ids",help:"The user will be added to the selected organization(s).",children:(0,s.jsx)(f.Select,{mode:"multiple",placeholder:"Select Organization",style:{width:"100%"},children:Q.map(e=>(0,s.jsxs)(T,{value:e.organization_id,children:[e.organization_alias," (",e.organization_id,")"]},e.organization_id))})}),(0,s.jsx)(x.Form.Item,{label:"Metadata",name:"metadata",children:(0,s.jsx)(h.Input.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,s.jsxs)(i.Accordion,{children:[(0,s.jsx)(d.AccordionHeader,{children:(0,s.jsx)(U,{strong:!0,children:"Personal Key Creation"})}),(0,s.jsx)(n.AccordionBody,{children:(0,s.jsx)(x.Form.Item,{className:"gap-2",label:(0,s.jsxs)("span",{children:["Models"," ",(0,s.jsx)(j.Tooltip,{title:"Models user has access to, outside of team scope.",children:(0,s.jsx)(t.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"models",help:"Models user has access to, outside of team scope.",children:(0,s.jsxs)(f.Select,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[(0,s.jsx)(f.Select.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),(0,s.jsx)(f.Select.Option,{value:"no-default-models",children:"No Default Models"},"no-default-models"),D.map(e=>(0,s.jsx)(f.Select.Option,{value:e,children:(0,N.getModelDisplayName)(e)},e))]})})})]}),(0,s.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,s.jsx)(u.Button,{type:"primary",icon:(0,s.jsx)(l.UserAddOutlined,{}),htmlType:"submit",children:"Invite User"})})]})]}),A&&(0,s.jsx)(I,{isInvitationLinkModalVisible:W,setIsInvitationLinkModalVisible:K,baseUrl:G||"",invitationLinkData:q})]})}],371455)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/124fefccff39e221.js b/litellm/proxy/_experimental/out/_next/static/chunks/124fefccff39e221.js deleted file mode 100644 index 084a2b54610..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/124fefccff39e221.js +++ /dev/null @@ -1 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,519756,e=>{"use strict";e.i(247167);var t=e.i(931067),s=e.i(271645);let r={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"};var i=e.i(9583),a=s.forwardRef(function(e,a){return s.createElement(i.default,(0,t.default)({},e,{ref:a,icon:r}))});e.s(["UploadOutlined",0,a],519756)},981339,e=>{"use strict";var t=e.i(185793);e.s(["Skeleton",()=>t.default])},500330,e=>{"use strict";var t=e.i(727749);function s(e,t){let s=structuredClone(e);for(let[e,r]of Object.entries(t))e in s&&(s[e]=r);return s}let r=(e,t=0,s=!1,r=!0)=>{if(null==e||!Number.isFinite(e)||0===e&&!r)return"-";let i={minimumFractionDigits:t,maximumFractionDigits:t};if(!s)return e.toLocaleString("en-US",i);let a=e<0?"-":"",n=Math.abs(e),l=n,o="";return n>=1e6?(l=n/1e6,o="M"):n>=1e3&&(l=n/1e3,o="K"),`${a}${l.toLocaleString("en-US",i)}${o}`},i=async(e,s="Copied to clipboard")=>{if(!e)return!1;if(!navigator||!navigator.clipboard||!navigator.clipboard.writeText)return a(e,s);try{return await navigator.clipboard.writeText(e),t.default.success(s),!0}catch(t){return console.error("Clipboard API failed: ",t),a(e,s)}},a=(e,s)=>{try{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",r.setAttribute("readonly",""),document.body.appendChild(r),r.focus(),r.select();let i=document.execCommand("copy");if(document.body.removeChild(r),i)return t.default.success(s),!0;throw Error("execCommand failed")}catch(e){return t.default.fromBackend("Failed to copy to clipboard"),console.error("Failed to copy: ",e),!1}};e.s(["copyToClipboard",0,i,"formatNumberWithCommas",0,r,"getSpendString",0,(e,t=6)=>{if(null==e||!Number.isFinite(e)||0===e)return"-";let s=r(e,t,!1,!1);if(0===Number(s.replace(/,/g,""))){let e=(1/10**t).toFixed(t);return`< $${e}`}return`$${s}`},"updateExistingKeys",()=>s])},59935,(e,t,s)=>{var r;let i;e.e,r=function e(){var t,s="u">typeof self?self:"u">typeof window?window:void 0!==s?s:{},r=!s.document&&!!s.postMessage,i=s.IS_PAPA_WORKER||!1,a={},n=0,l={};function o(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=_(e);t.chunkSize=parseInt(t.chunkSize),e.step||e.chunk||(t.chunkSize=null),this._handle=new m(t),(this._handle.streamer=this)._config=t}).call(this,e),this.parseChunk=function(e,t){var r=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&0=this._config.preview,i)s.postMessage({results:a,workerId:l.WORKER_ID,finished:r});else if(b(this._config.chunk)&&!t){if(this._config.chunk(a,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);this._completeResults=a=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(a.data),this._completeResults.errors=this._completeResults.errors.concat(a.errors),this._completeResults.meta=a.meta),this._completed||!r||!b(this._config.complete)||a&&a.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),r||a&&a.meta.paused||this._nextChunk(),a}this._halted=!0},this._sendError=function(e){b(this._config.error)?this._config.error(e):i&&this._config.error&&s.postMessage({workerId:l.WORKER_ID,error:e,finished:!1})}}function d(e){var t;(e=e||{}).chunkSize||(e.chunkSize=l.RemoteChunkSize),o.call(this,e),this._nextChunk=r?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),r||(t.onload=v(this._chunkLoaded,this),t.onerror=v(this._chunkError,this)),t.open(this._config.downloadRequestBody?"POST":"GET",this._input,!r),this._config.downloadRequestHeaders){var e,s,i=this._config.downloadRequestHeaders;for(s in i)t.setRequestHeader(s,i[s])}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)}r&&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=l.LocalChunkSize),o.call(this,e);var t,s,r="u">typeof FileReader;this.stream=function(e){this._input=e,s=e.slice||e.webkitSlice||e.mozSlice,r?((t=new FileReader).onload=v(this._chunkLoaded,this),t.onerror=v(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 u(e){var t;o.call(this,e=e||{}),this.stream=function(e){return t=e,this._nextChunk()},this._nextChunk=function(){var e,s;if(!this._finished)return t=(e=this._config.chunkSize)?(s=t.substring(0,e),t.substring(e)):(s=t,""),this._finished=!t,this.parseChunk(s)}}function h(e){o.call(this,e=e||{});var t=[],s=!0,r=!1;this.pause=function(){o.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){o.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(){r&&1===t.length&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),t.length?this.parseChunk(t.shift()):s=!0},this._streamData=v(function(e){try{t.push("string"==typeof e?e:e.toString(this._config.encoding)),s&&(s=!1,this._checkIsFinished(),this.parseChunk(t.shift()))}catch(e){this._streamError(e)}},this),this._streamError=v(function(e){this._streamCleanUp(),this._sendError(e)},this),this._streamEnd=v(function(){this._streamCleanUp(),r=!0,this._streamData("")},this),this._streamCleanUp=v(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}function m(e){var t,s,r,i,a=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,n=/^((\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)))$/,o=this,d=0,c=0,u=!1,h=!1,m=[],x={data:[],errors:[],meta:{}};function g(t){return"greedy"===e.skipEmptyLines?""===t.join("").trim():1===t.length&&0===t[0].length}function y(){if(x&&r&&(j("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+l.DefaultDelimiter+"'"),r=!1),e.skipEmptyLines&&(x.data=x.data.filter(function(e){return!g(e)})),v()){if(x)if(Array.isArray(x.data[0])){for(var t,s=0;v()&&s(e.dynamicTypingFunction&&void 0===e.dynamicTyping[t]&&(e.dynamicTyping[t]=e.dynamicTypingFunction(t)),!0===(e.dynamicTyping[t]||e.dynamicTyping))?"true"===s||"TRUE"===s||"false"!==s&&"FALSE"!==s&&((e=>{if(a.test(e)&&-0x20000000000000<(e=parseFloat(e))&&e<0x20000000000000)return 1})(s)?parseFloat(s):n.test(s)?new Date(s):""===s?null:s):s)(l=e.header?i>=m.length?"__parsed_extra":m[i]:l,o=e.transform?e.transform(o,l):o);"__parsed_extra"===l?(r[l]=r[l]||[],r[l].push(o)):r[l]=o}return e.header&&(i>m.length?j("FieldMismatch","TooManyFields","Too many fields: expected "+m.length+" fields but parsed "+i,c+s):ie.preview?s.abort():(x.data=x.data[0],i(x,o))))}),this.parse=function(i,a,n){var o=e.quoteChar||'"',o=(e.newline||(e.newline=this.guessLineEndings(i,o)),r=!1,e.delimiter?b(e.delimiter)&&(e.delimiter=e.delimiter(i),x.meta.delimiter=e.delimiter):((o=((t,s,r,i,a)=>{var n,o,d,c;a=a||[","," ","|",";",l.RECORD_SEP,l.UNIT_SEP];for(var u=0;u=s.length/2?"\r\n":"\r"}}function f(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function p(e){var t=(e=e||{}).delimiter,s=e.newline,r=e.comments,i=e.step,a=e.preview,n=e.fastMode,o=null,d=!1,c=null==e.quoteChar?'"':e.quoteChar,u=c;if(void 0!==e.escapeChar&&(u=e.escapeChar),("string"!=typeof t||-1=a)return M(!0);break}k.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:w.length,index:h}),T++}}else if(r&&0===C.length&&l.substring(h,h+v)===r){if(-1===I)return M();h=I+_,I=l.indexOf(s,h),R=l.indexOf(t,h)}else if(-1!==R&&(R=a)return M(!0)}return A();function F(e){w.push(e),N=h}function U(e){return -1!==e&&(e=l.substring(T+1,e))&&""===e.trim()?e.length:0}function A(e){return x||(void 0===e&&(e=l.substring(h)),C.push(e),h=g,F(C),j&&B()),M()}function D(e){h=e,F(C),C=[],I=l.indexOf(s,h)}function M(r){if(e.header&&!p&&w.length&&!d){var i=w[0],a=Object.create(null),n=new Set(i);let t=!1;for(let s=0;s{if("object"==typeof t){if("string"!=typeof t.delimiter||l.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))&&(s=t.quotes),"boolean"!=typeof t.skipEmptyLines&&"string"!=typeof t.skipEmptyLines||(d=t.skipEmptyLines),"string"==typeof t.newline&&(a=t.newline),"string"==typeof t.quoteChar&&(n=t.quoteChar),"boolean"==typeof t.header&&(r=t.header),Array.isArray(t.columns)){if(0===t.columns.length)throw Error("Option columns is empty");c=t.columns}void 0!==t.escapeChar&&(o=t.escapeChar+n),t.escapeFormulae instanceof RegExp?u=t.escapeFormulae:"boolean"==typeof t.escapeFormulae&&t.escapeFormulae&&(u=/^[=+\-@\t\r].*$/)}})(),RegExp(f(n),"g"));if("string"==typeof e&&(e=JSON.parse(e)),Array.isArray(e)){if(!e.length||Array.isArray(e[0]))return m(null,e,d);if("object"==typeof e[0])return m(c||Object.keys(e[0]),e,d)}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])),m(e.fields||[],e.data||[],d);throw Error("Unable to serialize unrecognized input");function m(e,t,s){var n="",l=("string"==typeof e&&(e=JSON.parse(e)),"string"==typeof t&&(t=JSON.parse(t)),Array.isArray(e)&&0{for(var s=0;s{"use strict";e.i(247167);var t=e.i(931067),s=e.i(271645);let r={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"};var i=e.i(9583),a=s.forwardRef(function(e,a){return s.createElement(i.default,(0,t.default)({},e,{ref:a,icon:r}))});e.s(["WarningOutlined",0,a],285027)},663435,e=>{"use strict";var t=e.i(843476),s=e.i(199133);e.s(["default",0,({teams:e,value:r,onChange:i,disabled:a,loading:n})=>(0,t.jsx)(s.Select,{showSearch:!0,placeholder:"Search or select a team",value:r,onChange:i,disabled:a,loading:n,allowClear:!0,filterOption:(t,s)=>{if(!s)return!1;let r=e?.find(e=>e.team_id===s.key);if(!r)return!1;let i=t.toLowerCase().trim(),a=(r.team_alias||"").toLowerCase(),n=(r.team_id||"").toLowerCase();return a.includes(i)||n.includes(i)},optionFilterProp:"children",children:e?.map(e=>(0,t.jsxs)(s.Select.Option,{value:e.team_id,children:[(0,t.jsx)("span",{className:"font-medium",children:e.team_alias})," ",(0,t.jsxs)("span",{className:"text-gray-500",children:["(",e.team_id,")"]})]},e.team_id))})])},213205,e=>{"use strict";e.i(247167);var t=e.i(931067),s=e.i(271645);let r={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M678.3 642.4c24.2-13 51.9-20.4 81.4-20.4h.1c3 0 4.4-3.6 2.2-5.6a371.67 371.67 0 00-103.7-65.8c-.4-.2-.8-.3-1.2-.5C719.2 505 759.6 431.7 759.6 349c0-137-110.8-248-247.5-248S264.7 212 264.7 349c0 82.7 40.4 156 102.6 201.1-.4.2-.8.3-1.2.5-44.7 18.9-84.8 46-119.3 80.6a373.42 373.42 0 00-80.4 119.5A373.6 373.6 0 00137 888.8a8 8 0 008 8.2h59.9c4.3 0 7.9-3.5 8-7.8 2-77.2 32.9-149.5 87.6-204.3C357 628.2 432.2 597 512.2 597c56.7 0 111.1 15.7 158 45.1a8.1 8.1 0 008.1.3zM512.2 521c-45.8 0-88.9-17.9-121.4-50.4A171.2 171.2 0 01340.5 349c0-45.9 17.9-89.1 50.3-121.6S466.3 177 512.2 177s88.9 17.9 121.4 50.4A171.2 171.2 0 01683.9 349c0 45.9-17.9 89.1-50.3 121.6C601.1 503.1 558 521 512.2 521zM880 759h-84v-84c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v84h-84c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h84v84c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8v-84h84c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8z"}}]},name:"user-add",theme:"outlined"};var i=e.i(9583),a=s.forwardRef(function(e,a){return s.createElement(i.default,(0,t.default)({},e,{ref:a,icon:r}))});e.s(["UserAddOutlined",0,a],213205)},355619,e=>{"use strict";var t=e.i(764205);let s=async(e,s,r)=>{try{if(null===e||null===s)return;if(null!==r){let i=(await (0,t.modelAvailableCall)(r,e,s,!0,null,!0)).data.map(e=>e.id),a=[],n=[];return i.forEach(e=>{e.endsWith("/*")?a.push(e):n.push(e)}),[...a,...n]}}catch(e){console.error("Error fetching user models:",e)}};e.s(["fetchAvailableModelsForTeamOrKey",0,s,"getModelDisplayName",0,e=>{if("all-proxy-models"===e)return"All Proxy Models";if(e.endsWith("/*")){let t=e.replace("/*","");return`All ${t} models`}return e},"unfurlWildcardModelsInList",0,(e,t)=>{let s=[],r=[];return console.log("teamModels",e),console.log("allModels",t),e.forEach(e=>{if(e.endsWith("/*")){let i=e.replace("/*",""),a=t.filter(e=>e.startsWith(i+"/"));r.push(...a),s.push(e)}else r.push(e)}),[...s,...r].filter((e,t,s)=>s.indexOf(e)===t)}])},860585,e=>{"use strict";var t=e.i(843476),s=e.i(199133);let{Option:r}=s.Select;e.s(["default",0,({value:e,onChange:i,className:a="",style:n={}})=>(0,t.jsxs)(s.Select,{style:{width:"100%",...n},value:e||void 0,onChange:i,className:a,placeholder:"n/a",allowClear:!0,children:[(0,t.jsx)(r,{value:"24h",children:"daily"}),(0,t.jsx)(r,{value:"7d",children:"weekly"}),(0,t.jsx)(r,{value:"30d",children:"monthly"})]}),"getBudgetDurationLabel",0,e=>e?({"24h":"daily","7d":"weekly","30d":"monthly"})[e]||e:"Not set"])},447082,e=>{"use strict";var t=e.i(843476),s=e.i(271645),r=e.i(994388),i=e.i(599724),a=e.i(212931),n=e.i(291542),l=e.i(515831),o=e.i(898586),d=e.i(519756),c=e.i(737434),u=e.i(285027),h=e.i(993914),m=e.i(955135);e.i(247167);var f=e.i(931067);let p={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"};var x=e.i(9583),g=s.forwardRef(function(e,t){return s.createElement(x.default,(0,f.default)({},e,{ref:t,icon:p}))}),y=e.i(764205),_=e.i(59935),v=e.i(220508),b=e.i(964306);let j=s.forwardRef(function(e,t){return s.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:t},e),s.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"}))});var w=e.i(237016),k=e.i(727749);e.s(["default",0,({accessToken:e,teams:f,possibleUIRoles:p,onUsersCreated:x})=>{let[C,N]=(0,s.useState)(!1),[S,E]=(0,s.useState)([]),[R,I]=(0,s.useState)(!1),[O,T]=(0,s.useState)(null),[L,F]=(0,s.useState)(null),[U,A]=(0,s.useState)(null),[D,M]=(0,s.useState)(null),[B,P]=(0,s.useState)(null),[z,V]=(0,s.useState)("http://localhost:4000");(0,s.useEffect)(()=>{(async()=>{try{let t=await (0,y.getProxyUISettings)(e);P(t)}catch(e){console.error("Error fetching UI settings:",e)}})(),V(new URL("/",window.location.href).toString())},[e]);let $=async()=>{I(!0);let t=S.map(e=>({...e,status:"pending"}));E(t);let s=!1;for(let r=0;re.trim()).filter(Boolean),0===t.teams.length&&delete t.teams),i.models&&"string"==typeof i.models&&""!==i.models.trim()&&(t.models=i.models.split(",").map(e=>e.trim()).filter(Boolean),0===t.models.length&&delete t.models),i.max_budget&&""!==i.max_budget.toString().trim()){let e=parseFloat(i.max_budget.toString());!isNaN(e)&&e>0&&(t.max_budget=e)}i.budget_duration&&""!==i.budget_duration.trim()&&(t.budget_duration=i.budget_duration.trim()),i.metadata&&"string"==typeof i.metadata&&""!==i.metadata.trim()&&(t.metadata=i.metadata.trim()),console.log("Sending user data:",t);let a=await (0,y.userCreateCall)(e,null,t);if(console.log("Full response:",a),a&&(a.key||a.user_id)){s=!0,console.log("Success case triggered");let t=a.data?.user_id||a.user_id;try{if(B?.SSO_ENABLED){let e=new URL("/ui",z).toString();E(t=>t.map((t,s)=>s===r?{...t,status:"success",key:a.key||a.user_id,invitation_link:e}:t))}else{let s=await (0,y.invitationCreateCall)(e,t),i=new URL(`/ui?invitation_id=${s.id}`,z).toString();E(e=>e.map((e,t)=>t===r?{...e,status:"success",key:a.key||a.user_id,invitation_link:i}:e))}}catch(e){console.error("Error creating invitation:",e),E(e=>e.map((e,t)=>t===r?{...e,status:"success",key:a.key||a.user_id,error:"User created but failed to generate invitation link"}:e))}}else{console.log("Error case triggered");let e=a?.error||"Failed to create user";console.log("Error message:",e),E(t=>t.map((t,s)=>s===r?{...t,status:"failed",error:e}:t))}}catch(t){console.error("Caught error:",t);let e=t?.response?.data?.error||t?.message||String(t);E(t=>t.map((t,s)=>s===r?{...t,status:"failed",error:e}:t))}}I(!1),s&&x&&x()},q=[{title:"Row",dataIndex:"rowNumber",key:"rowNumber",width:80},{title:"Email",dataIndex:"user_email",key:"user_email"},{title:"Role",dataIndex:"user_role",key:"user_role"},{title:"Teams",dataIndex:"teams",key:"teams"},{title:"Budget",dataIndex:"max_budget",key:"max_budget"},{title:"Status",key:"status",render:(e,s)=>s.isValid?s.status&&"pending"!==s.status?"success"===s.status?(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(v.CheckCircleIcon,{className:"h-5 w-5 text-green-500 mr-2"}),(0,t.jsx)("span",{className:"text-green-500",children:"Success"})]}),s.invitation_link&&(0,t.jsx)("div",{className:"mt-1",children:(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)("span",{className:"text-xs text-gray-500 truncate max-w-[150px]",children:s.invitation_link}),(0,t.jsx)(w.CopyToClipboard,{text:s.invitation_link,onCopy:()=>k.default.success("Invitation link copied!"),children:(0,t.jsx)("button",{className:"ml-1 text-blue-500 text-xs hover:text-blue-700",children:"Copy"})})]})})]}):(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(b.XCircleIcon,{className:"h-5 w-5 text-red-500 mr-2"}),(0,t.jsx)("span",{className:"text-red-500",children:"Failed"})]}),s.error&&(0,t.jsx)("span",{className:"text-sm text-red-500 ml-7",children:JSON.stringify(s.error)})]}):(0,t.jsx)("span",{className:"text-gray-500",children:"Pending"}):(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(b.XCircleIcon,{className:"h-5 w-5 text-red-500 mr-2"}),(0,t.jsx)("span",{className:"text-red-500",children:"Invalid"})]}),s.error&&(0,t.jsx)("span",{className:"text-sm text-red-500 ml-7",children:s.error})]})}];return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(r.Button,{className:"mb-0",onClick:()=>N(!0),children:"+ Bulk Invite Users"}),(0,t.jsx)(a.Modal,{title:"Bulk Invite Users",open:C,width:800,onCancel:()=>N(!1),bodyStyle:{maxHeight:"70vh",overflow:"auto"},footer:null,children:(0,t.jsx)("div",{className:"flex flex-col",children:0===S.length?(0,t.jsxs)("div",{className:"mb-6",children:[(0,t.jsxs)("div",{className:"flex items-center mb-4",children:[(0,t.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"1"}),(0,t.jsx)("h3",{className:"text-lg font-medium",children:"Download and fill the template"})]}),(0,t.jsxs)("div",{className:"ml-11 mb-6",children:[(0,t.jsx)("p",{className:"mb-4",children:"Add multiple users at once by following these steps:"}),(0,t.jsxs)("ol",{className:"list-decimal list-inside space-y-2 ml-2 mb-4",children:[(0,t.jsx)("li",{children:"Download our CSV template"}),(0,t.jsx)("li",{children:"Add your users' information to the spreadsheet"}),(0,t.jsx)("li",{children:"Save the file and upload it here"}),(0,t.jsx)("li",{children:"After creation, download the results file containing the Virtual Keys for each user"})]}),(0,t.jsxs)("div",{className:"bg-gray-50 p-4 rounded-md border border-gray-200 mb-4",children:[(0,t.jsx)("h4",{className:"font-medium mb-2",children:"Template Column Names"}),(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[(0,t.jsxs)("div",{className:"flex items-start",children:[(0,t.jsx)("div",{className:"w-3 h-3 rounded-full bg-red-500 mt-1.5 mr-2 flex-shrink-0"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{className:"font-medium",children:"user_email"}),(0,t.jsx)("p",{className:"text-sm text-gray-600",children:"User's email address (required)"})]})]}),(0,t.jsxs)("div",{className:"flex items-start",children:[(0,t.jsx)("div",{className:"w-3 h-3 rounded-full bg-red-500 mt-1.5 mr-2 flex-shrink-0"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{className:"font-medium",children:"user_role"}),(0,t.jsx)("p",{className:"text-sm text-gray-600",children:'User\'s role (one of: "proxy_admin", "proxy_admin_viewer", "internal_user", "internal_user_viewer")'})]})]}),(0,t.jsxs)("div",{className:"flex items-start",children:[(0,t.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{className:"font-medium",children:"teams"}),(0,t.jsx)("p",{className:"text-sm text-gray-600",children:'Comma-separated team IDs (e.g., "team-1,team-2")'})]})]}),(0,t.jsxs)("div",{className:"flex items-start",children:[(0,t.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{className:"font-medium",children:"max_budget"}),(0,t.jsx)("p",{className:"text-sm text-gray-600",children:'Maximum budget as a number (e.g., "100")'})]})]}),(0,t.jsxs)("div",{className:"flex items-start",children:[(0,t.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{className:"font-medium",children:"budget_duration"}),(0,t.jsx)("p",{className:"text-sm text-gray-600",children:'Budget reset period (e.g., "30d", "1mo")'})]})]}),(0,t.jsxs)("div",{className:"flex items-start",children:[(0,t.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{className:"font-medium",children:"models"}),(0,t.jsx)("p",{className:"text-sm text-gray-600",children:'Comma-separated allowed models (e.g., "gpt-3.5-turbo,gpt-4")'})]})]})]})]}),(0,t.jsxs)(r.Button,{onClick:()=>{let e=new Blob([_.default.unparse([["user_email","user_role","teams","max_budget","budget_duration","models"],["user@example.com","internal_user","team-id-1,team-id-2","100","30d","gpt-3.5-turbo,gpt-4"]])],{type:"text/csv"}),t=window.URL.createObjectURL(e),s=document.createElement("a");s.href=t,s.download="bulk_users_template.csv",document.body.appendChild(s),s.click(),document.body.removeChild(s),window.URL.revokeObjectURL(t)},size:"lg",className:"w-full md:w-auto",children:[(0,t.jsx)(c.DownloadOutlined,{className:"mr-2"})," Download CSV Template"]})]}),(0,t.jsxs)("div",{className:"flex items-center mb-4",children:[(0,t.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"2"}),(0,t.jsx)("h3",{className:"text-lg font-medium",children:"Upload your completed CSV"})]}),(0,t.jsxs)("div",{className:"ml-11",children:[D?(0,t.jsxs)("div",{className:`mb-4 p-4 rounded-md border ${U?"bg-red-50 border-red-200":"bg-blue-50 border-blue-200"}`,children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsxs)("div",{className:"flex items-center",children:[U?(0,t.jsx)(g,{className:"text-red-500 text-xl mr-3"}):(0,t.jsx)(h.FileTextOutlined,{className:"text-blue-500 text-xl mr-3"}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Typography.Text,{strong:!0,className:U?"text-red-800":"text-blue-800",children:D.name}),(0,t.jsxs)(o.Typography.Text,{className:`block text-xs ${U?"text-red-600":"text-blue-600"}`,children:[(D.size/1024).toFixed(1)," KB • ",new Date().toLocaleDateString()]})]})]}),(0,t.jsxs)(r.Button,{size:"xs",variant:"secondary",onClick:()=>{M(null),E([]),T(null),F(null),A(null)},className:"flex items-center",children:[(0,t.jsx)(m.DeleteOutlined,{className:"mr-1"})," Remove"]})]}),U?(0,t.jsxs)("div",{className:"mt-3 text-red-600 text-sm flex items-start",children:[(0,t.jsx)(u.WarningOutlined,{className:"mr-2 mt-0.5"}),(0,t.jsx)("span",{children:U})]}):!L&&(0,t.jsxs)("div",{className:"mt-3 flex items-center",children:[(0,t.jsx)("div",{className:"w-full bg-gray-200 rounded-full h-1.5",children:(0,t.jsx)("div",{className:"bg-blue-500 h-1.5 rounded-full w-full animate-pulse"})}),(0,t.jsx)("span",{className:"ml-2 text-xs text-blue-600",children:"Processing..."})]})]}):(0,t.jsx)(l.Upload,{beforeUpload:e=>((T(null),F(null),A(null),M(e),"text/csv"===e.type||e.name.endsWith(".csv"))?e.size>5242880?A(`File is too large (${(e.size/1048576).toFixed(1)} MB). Please upload a CSV file smaller than 5MB.`):_.default.parse(e,{complete:e=>{if(!e.data||0===e.data.length){F("The CSV file appears to be empty. Please upload a file with data."),E([]);return}if(1===e.data.length){F("The CSV file only contains headers but no user data. Please add user data to your CSV."),E([]);return}let t=e.data[0];if(0===t.length||1===t.length&&""===t[0]){F("The CSV file doesn't contain any column headers. Please make sure your CSV has headers."),E([]);return}let s=["user_email","user_role"].filter(e=>!t.includes(e));if(s.length>0){F(`Your CSV is missing these required columns: ${s.join(", ")}. Please add these columns to your CSV file.`),E([]);return}try{let s=e.data.slice(1).map((e,s)=>{if(0===e.length||1===e.length&&""===e[0])return null;if(e.length=parseFloat(r.max_budget.toString())&&i.push("Max budget must be greater than 0")),r.budget_duration&&!r.budget_duration.match(/^\d+[dhmwy]$|^\d+mo$/)&&i.push(`Invalid budget duration format "${r.budget_duration}". Use format like "30d", "1mo", "2w", "6h"`),r.teams&&"string"==typeof r.teams&&f&&f.length>0){let e=f.map(e=>e.team_id),t=r.teams.split(",").map(e=>e.trim()).filter(t=>!e.includes(t));t.length>0&&i.push(`Unknown team(s): ${t.join(", ")}`)}return i.length>0&&(r.isValid=!1,r.error=i.join(", ")),r}).filter(Boolean),r=s.filter(e=>e.isValid);E(s),0===s.length?F("No valid data rows found in the CSV file. Please check your file format."):0===r.length?T("No valid users found in the CSV. Please check the errors below and fix your CSV file."):r.length{T(`Failed to parse CSV file: ${e.message}`),E([])},header:!1}):(A(`Invalid file type: ${e.name}. Please upload a CSV file (.csv extension).`),k.default.fromBackend("Invalid file type. Please upload a CSV file.")),!1),accept:".csv",maxCount:1,showUploadList:!1,children:(0,t.jsxs)("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-blue-500 transition-colors cursor-pointer",children:[(0,t.jsx)(d.UploadOutlined,{className:"text-3xl text-gray-400 mb-2"}),(0,t.jsx)("p",{className:"mb-1",children:"Drag and drop your CSV file here"}),(0,t.jsx)("p",{className:"text-sm text-gray-500 mb-3",children:"or"}),(0,t.jsx)(r.Button,{size:"sm",children:"Browse files"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-4",children:"Only CSV files (.csv) are supported"})]})}),L&&(0,t.jsx)("div",{className:"mb-4 p-4 bg-yellow-50 border border-yellow-200 rounded-md",children:(0,t.jsxs)("div",{className:"flex items-start",children:[(0,t.jsx)(j,{className:"h-5 w-5 text-yellow-500 mr-2 mt-0.5"}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Typography.Text,{strong:!0,className:"text-yellow-800",children:"CSV Structure Error"}),(0,t.jsx)(o.Typography.Paragraph,{className:"text-yellow-700 mt-1 mb-0",children:L}),(0,t.jsx)(o.Typography.Paragraph,{className:"text-yellow-700 mt-2 mb-0",children:"Please download our template and ensure your CSV follows the required format."})]})]})})]})]}):(0,t.jsxs)("div",{className:"mb-6",children:[(0,t.jsxs)("div",{className:"flex items-center mb-4",children:[(0,t.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"3"}),(0,t.jsx)("h3",{className:"text-lg font-medium",children:S.some(e=>"success"===e.status||"failed"===e.status)?"User Creation Results":"Review and create users"})]}),O&&(0,t.jsx)("div",{className:"ml-11 mb-4 p-4 bg-red-50 border border-red-200 rounded-md",children:(0,t.jsxs)("div",{className:"flex items-start",children:[(0,t.jsx)(u.WarningOutlined,{className:"text-red-500 mr-2 mt-1"}),(0,t.jsxs)("div",{children:[(0,t.jsx)(i.Text,{className:"text-red-600 font-medium",children:O}),S.some(e=>!e.isValid)&&(0,t.jsxs)("ul",{className:"mt-2 list-disc list-inside text-red-600 text-sm",children:[(0,t.jsx)("li",{children:"Check the table below for specific errors in each row"}),(0,t.jsx)("li",{children:"Common issues include invalid email formats, missing required fields, or incorrect role values"}),(0,t.jsx)("li",{children:"Fix these issues in your CSV file and upload again"})]})]})]})}),(0,t.jsxs)("div",{className:"ml-11",children:[(0,t.jsxs)("div",{className:"flex justify-between items-center mb-3",children:[(0,t.jsx)("div",{className:"flex items-center",children:S.some(e=>"success"===e.status||"failed"===e.status)?(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(i.Text,{className:"text-lg font-medium mr-3",children:"Creation Summary"}),(0,t.jsxs)(i.Text,{className:"text-sm bg-green-100 text-green-800 px-2 py-1 rounded mr-2",children:[S.filter(e=>"success"===e.status).length," Successful"]}),S.some(e=>"failed"===e.status)&&(0,t.jsxs)(i.Text,{className:"text-sm bg-red-100 text-red-800 px-2 py-1 rounded",children:[S.filter(e=>"failed"===e.status).length," Failed"]})]}):(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(i.Text,{className:"text-lg font-medium mr-3",children:"User Preview"}),(0,t.jsxs)(i.Text,{className:"text-sm bg-blue-100 text-blue-800 px-2 py-1 rounded",children:[S.filter(e=>e.isValid).length," of ",S.length," users valid"]})]})}),!S.some(e=>"success"===e.status||"failed"===e.status)&&(0,t.jsxs)("div",{className:"flex space-x-3",children:[(0,t.jsx)(r.Button,{onClick:()=>{E([]),T(null)},variant:"secondary",children:"Back"}),(0,t.jsx)(r.Button,{onClick:$,disabled:0===S.filter(e=>e.isValid).length||R,children:R?"Creating...":`Create ${S.filter(e=>e.isValid).length} Users`})]})]}),S.some(e=>"success"===e.status)&&(0,t.jsx)("div",{className:"mb-4 p-4 bg-blue-50 border border-blue-200 rounded-md",children:(0,t.jsxs)("div",{className:"flex items-start",children:[(0,t.jsx)("div",{className:"mr-3 mt-1",children:(0,t.jsx)(v.CheckCircleIcon,{className:"h-5 w-5 text-blue-500"})}),(0,t.jsxs)("div",{children:[(0,t.jsx)(i.Text,{className:"font-medium text-blue-800",children:"User creation complete"}),(0,t.jsxs)(i.Text,{className:"block text-sm text-blue-700 mt-1",children:[(0,t.jsx)("span",{className:"font-medium",children:"Next step:"})," Download the credentials file containing Virtual Keys and invitation links. Users will need these Virtual Keys to make LLM requests through LiteLLM."]})]})]})}),(0,t.jsx)(n.Table,{dataSource:S,columns:q,size:"small",pagination:{pageSize:5},scroll:{y:300},rowClassName:e=>e.isValid?"":"bg-red-50"}),!S.some(e=>"success"===e.status||"failed"===e.status)&&(0,t.jsxs)("div",{className:"flex justify-end mt-4",children:[(0,t.jsx)(r.Button,{onClick:()=>{E([]),T(null)},variant:"secondary",className:"mr-3",children:"Back"}),(0,t.jsx)(r.Button,{onClick:$,disabled:0===S.filter(e=>e.isValid).length||R,children:R?"Creating...":`Create ${S.filter(e=>e.isValid).length} Users`})]}),S.some(e=>"success"===e.status||"failed"===e.status)&&(0,t.jsxs)("div",{className:"flex justify-end mt-4",children:[(0,t.jsx)(r.Button,{onClick:()=>{E([]),T(null)},variant:"secondary",className:"mr-3",children:"Start New Bulk Import"}),(0,t.jsxs)(r.Button,{onClick:()=>{let e=S.map(e=>({user_email:e.user_email,user_role:e.user_role,status:e.status,key:e.key||"",invitation_link:e.invitation_link||"",error:e.error||""})),t=new Blob([_.default.unparse(e)],{type:"text/csv"}),s=window.URL.createObjectURL(t),r=document.createElement("a");r.href=s,r.download="bulk_users_results.csv",document.body.appendChild(r),r.click(),document.body.removeChild(r),window.URL.revokeObjectURL(s)},variant:"primary",className:"flex items-center",children:[(0,t.jsx)(c.DownloadOutlined,{className:"mr-2"})," Download User Credentials"]})]})]})]})})})]})}],447082)},371455,172372,e=>{"use strict";var t=e.i(843476),s=e.i(827252),r=e.i(213205),i=e.i(912598),a=e.i(677667),n=e.i(130643),l=e.i(898667),o=e.i(994388),d=e.i(35983),c=e.i(779241),u=e.i(560445),h=e.i(464571),m=e.i(808613),f=e.i(311451),p=e.i(212931),x=e.i(199133),g=e.i(770914),y=e.i(592968),_=e.i(898586),v=e.i(271645),b=e.i(447082),j=e.i(663435),w=e.i(355619),k=e.i(727749),C=e.i(764205),N=e.i(237016),S=e.i(599724);function E({isInvitationLinkModalVisible:e,setIsInvitationLinkModalVisible:s,baseUrl:r,invitationLinkData:i,modalType:a="invitation"}){let{Title:n,Paragraph:l}=_.Typography,d=()=>{if(!r)return"";let e=new URL(r).pathname,t=e&&"/"!==e?`${e}/ui`:"ui";if(i?.has_user_setup_sso)return new URL(t,r).toString();let s=`${t}?invitation_id=${i?.id}`;return"resetPassword"===a&&(s+="&action=reset_password"),new URL(s,r).toString()};return(0,t.jsxs)(p.Modal,{title:"invitation"===a?"Invitation Link":"Reset Password Link",open:e,width:800,footer:null,onOk:()=>{s(!1)},onCancel:()=>{s(!1)},children:[(0,t.jsx)(l,{children:"invitation"===a?"Copy and send the generated link to onboard this user to the proxy.":"Copy and send the generated link to the user to reset their password."}),(0,t.jsxs)("div",{className:"flex justify-between pt-5 pb-2",children:[(0,t.jsx)(S.Text,{className:"text-base",children:"User ID"}),(0,t.jsx)(S.Text,{children:i?.user_id})]}),(0,t.jsxs)("div",{className:"flex justify-between pt-5 pb-2",children:[(0,t.jsx)(S.Text,{children:"invitation"===a?"Invitation Link":"Reset Password Link"}),(0,t.jsx)(S.Text,{children:(0,t.jsx)(S.Text,{children:d()})})]}),(0,t.jsx)("div",{className:"flex justify-end mt-5",children:(0,t.jsx)(N.CopyToClipboard,{text:d(),onCopy:()=>k.default.success("Copied!"),children:(0,t.jsx)(o.Button,{variant:"primary",children:"invitation"===a?"Copy invitation link":"Copy password reset link"})})})]})}e.s(["default",()=>E],172372);let{Option:R}=x.Select,{Text:I,Link:O,Title:T}=_.Typography;e.s(["CreateUserButton",0,({userID:e,accessToken:_,teams:N,possibleUIRoles:S,onUserCreated:R,isEmbedded:T=!1})=>{let L=(0,i.useQueryClient)(),[F,U]=(0,v.useState)(null),[A]=m.Form.useForm(),[D,M]=(0,v.useState)(!1),[B,P]=(0,v.useState)(!1),[z,V]=(0,v.useState)([]),[$,q]=(0,v.useState)(!1),[K,W]=(0,v.useState)(null),[H,Q]=(0,v.useState)(null);(0,v.useEffect)(()=>{let t=async()=>{try{let t=await (0,C.modelAvailableCall)(_,e,"any"),s=[];for(let e=0;e{try{k.default.info("Making API Call"),T||M(!0),t.models&&0!==t.models.length||"proxy_admin"===t.user_role||(t.models=["no-default-models"]);let s=await (0,C.userCreateCall)(_,null,t);await L.invalidateQueries({queryKey:["userList"]}),P(!0);let r=s.data?.user_id||s.user_id;if(R&&T){R(r),A.resetFields();return}if(F?.SSO_ENABLED){let t={id:"u">typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){let t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}),user_id:r,is_accepted:!1,accepted_at:null,expires_at:new Date(Date.now()+6048e5),created_at:new Date,created_by:e,updated_at:new Date,updated_by:e,has_user_setup_sso:!0};W(t),q(!0)}else(0,C.invitationCreateCall)(_,r).then(e=>{e.has_user_setup_sso=!1,W(e),q(!0)});k.default.success("API user Created"),A.resetFields(),localStorage.removeItem("userData"+e)}catch(t){let e=t.response?.data?.detail||t?.message||"Error creating the user";k.default.fromBackend(e),console.error("Error creating the user:",t)}};return T?(0,t.jsxs)(m.Form,{form:A,onFinish:J,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,t.jsx)(u.Alert,{message:"Email invitations",description:(0,t.jsxs)(t.Fragment,{children:["New users receive an email invite only when an email integration (SMTP, Resend, or SendGrid) is configured."," ",(0,t.jsx)(O,{href:"https://docs.litellm.ai/docs/proxy/email",target:"_blank",children:"Learn how to set up email notifications"})]}),type:"info",showIcon:!0,className:"mb-4"}),(0,t.jsx)(m.Form.Item,{label:"User Email",name:"user_email",children:(0,t.jsx)(c.TextInput,{placeholder:""})}),(0,t.jsx)(m.Form.Item,{label:"User Role",name:"user_role",children:(0,t.jsx)(x.Select,{children:S&&Object.entries(S).map(([e,{ui_label:s,description:r}])=>(0,t.jsx)(d.SelectItem,{value:e,title:s,children:(0,t.jsxs)("div",{className:"flex",children:[s," ",(0,t.jsx)(I,{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:r})]})},e))})}),(0,t.jsx)(m.Form.Item,{label:"Team",name:"team_id",children:(0,t.jsx)(x.Select,{placeholder:"Select Team",style:{width:"100%"},children:(0,t.jsx)(j.default,{teams:N})})}),(0,t.jsx)(m.Form.Item,{label:"Metadata",name:"metadata",children:(0,t.jsx)(f.Input.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,t.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,t.jsx)(h.Button,{htmlType:"submit",children:"Create User"})})]}):(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(o.Button,{className:"mb-0",onClick:()=>M(!0),children:"+ Invite User"}),(0,t.jsx)(b.default,{accessToken:_,teams:N,possibleUIRoles:S}),(0,t.jsxs)(p.Modal,{title:"Invite User",open:D,width:800,footer:null,onOk:()=>{M(!1),A.resetFields()},onCancel:()=>{M(!1),P(!1),A.resetFields()},children:[(0,t.jsxs)(g.Space,{direction:"vertical",size:"middle",children:[(0,t.jsx)(I,{className:"mb-1",children:"Create a User who can own keys"}),(0,t.jsx)(u.Alert,{message:"Email invitations",description:(0,t.jsxs)(t.Fragment,{children:["New users receive an email invite only when an email integration (SMTP, Resend, or SendGrid) is configured."," ",(0,t.jsx)(O,{href:"https://docs.litellm.ai/docs/proxy/email",target:"_blank",children:"Learn how to set up email notifications"})]}),type:"info",showIcon:!0,className:"mb-4"})]}),(0,t.jsxs)(m.Form,{form:A,onFinish:J,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,t.jsx)(m.Form.Item,{label:"User Email",name:"user_email",children:(0,t.jsx)(f.Input,{})}),(0,t.jsx)(m.Form.Item,{label:(0,t.jsxs)("span",{children:["Global Proxy Role"," ",(0,t.jsx)(y.Tooltip,{title:"This role is independent of any team/org specific roles. Configure Team / Organization Admins in the Settings",children:(0,t.jsx)(s.InfoCircleOutlined,{})})]}),name:"user_role",children:(0,t.jsx)(x.Select,{children:S&&Object.entries(S).map(([e,{ui_label:s,description:r}])=>(0,t.jsxs)(d.SelectItem,{value:e,title:s,children:[(0,t.jsx)(I,{children:s}),(0,t.jsxs)(I,{type:"secondary",children:[" - ",r]})]},e))})}),(0,t.jsx)(m.Form.Item,{label:"Team",className:"gap-2",name:"team_id",help:"If selected, user will be added as a 'user' role to the team.",children:(0,t.jsx)(j.default,{teams:N})}),(0,t.jsx)(m.Form.Item,{label:"Metadata",name:"metadata",children:(0,t.jsx)(f.Input.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,t.jsxs)(a.Accordion,{children:[(0,t.jsx)(l.AccordionHeader,{children:(0,t.jsx)(I,{strong:!0,children:"Personal Key Creation"})}),(0,t.jsx)(n.AccordionBody,{children:(0,t.jsx)(m.Form.Item,{className:"gap-2",label:(0,t.jsxs)("span",{children:["Models"," ",(0,t.jsx)(y.Tooltip,{title:"Models user has access to, outside of team scope.",children:(0,t.jsx)(s.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"models",help:"Models user has access to, outside of team scope.",children:(0,t.jsxs)(x.Select,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[(0,t.jsx)(x.Select.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),(0,t.jsx)(x.Select.Option,{value:"no-default-models",children:"No Default Models"},"no-default-models"),z.map(e=>(0,t.jsx)(x.Select.Option,{value:e,children:(0,w.getModelDisplayName)(e)},e))]})})})]}),(0,t.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,t.jsx)(h.Button,{type:"primary",icon:(0,t.jsx)(r.UserAddOutlined,{}),htmlType:"submit",children:"Invite User"})})]})]}),B&&(0,t.jsx)(E,{isInvitationLinkModalVisible:$,setIsInvitationLinkModalVisible:q,baseUrl:H||"",invitationLinkData:K})]})}],371455)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/125e23733670afea.js b/litellm/proxy/_experimental/out/_next/static/chunks/125e23733670afea.js deleted file mode 100644 index b1503987ffd..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/125e23733670afea.js +++ /dev/null @@ -1 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,525720,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),o=e.i(529681),i=e.i(908286),n=e.i(242064),a=e.i(246422),s=e.i(838378);let l=["wrap","nowrap","wrap-reverse"],c=["flex-start","flex-end","start","end","center","space-between","space-around","space-evenly","stretch","normal","left","right"],d=["center","start","end","flex-start","flex-end","self-start","self-end","baseline","normal","stretch"],u=function(e,t){let o,i,n;return(0,r.default)(Object.assign(Object.assign(Object.assign({},(o=!0===t.wrap?"wrap":t.wrap,{[`${e}-wrap-${o}`]:o&&l.includes(o)})),(i={},d.forEach(r=>{i[`${e}-align-${r}`]=t.align===r}),i[`${e}-align-stretch`]=!t.align&&!!t.vertical,i)),(n={},c.forEach(r=>{n[`${e}-justify-${r}`]=t.justify===r}),n)))},m=(0,a.genStyleHooks)("Flex",e=>{let{paddingXS:t,padding:r,paddingLG:o}=e,i=(0,s.mergeToken)(e,{flexGapSM:t,flexGap:r,flexGapLG:o});return[(e=>{let{componentCls:t}=e;return{[t]:{display:"flex",margin:0,padding:0,"&-vertical":{flexDirection:"column"},"&-rtl":{direction:"rtl"},"&:empty":{display:"none"}}}})(i),(e=>{let{componentCls:t}=e;return{[t]:{"&-gap-small":{gap:e.flexGapSM},"&-gap-middle":{gap:e.flexGap},"&-gap-large":{gap:e.flexGapLG}}}})(i),(e=>{let{componentCls:t}=e,r={};return l.forEach(e=>{r[`${t}-wrap-${e}`]={flexWrap:e}}),r})(i),(e=>{let{componentCls:t}=e,r={};return d.forEach(e=>{r[`${t}-align-${e}`]={alignItems:e}}),r})(i),(e=>{let{componentCls:t}=e,r={};return c.forEach(e=>{r[`${t}-justify-${e}`]={justifyContent:e}}),r})(i)]},()=>({}),{resetStyle:!1});var p=function(e,t){var r={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&0>t.indexOf(o)&&(r[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,o=Object.getOwnPropertySymbols(e);it.indexOf(o[i])&&Object.prototype.propertyIsEnumerable.call(e,o[i])&&(r[o[i]]=e[o[i]]);return r};let g=t.default.forwardRef((e,a)=>{let{prefixCls:s,rootClassName:l,className:c,style:d,flex:g,gap:f,vertical:h=!1,component:b="div",children:y}=e,v=p(e,["prefixCls","rootClassName","className","style","flex","gap","vertical","component","children"]),{flex:x,direction:C,getPrefixCls:w}=t.default.useContext(n.ConfigContext),S=w("flex",s),[O,k,$]=m(S),E=null!=h?h:null==x?void 0:x.vertical,M=(0,r.default)(c,l,null==x?void 0:x.className,S,k,$,u(S,e),{[`${S}-rtl`]:"rtl"===C,[`${S}-gap-${f}`]:(0,i.isPresetSize)(f),[`${S}-vertical`]:E}),z=Object.assign(Object.assign({},null==x?void 0:x.style),d);return g&&(z.flex=g),f&&!(0,i.isPresetSize)(f)&&(z.gap=f),O(t.default.createElement(b,Object.assign({ref:a,className:M,style:z},(0,o.default)(v,["justify","wrap","align"])),y))});e.s(["Flex",0,g],525720)},954616,e=>{"use strict";var t=e.i(271645),r=e.i(114272),o=e.i(540143),i=e.i(915823),n=e.i(619273),a=class extends i.Subscribable{#e;#t=void 0;#r;#o;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),(0,n.shallowEqualObjects)(this.options,t)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#r,observer:this}),t?.mutationKey&&this.options.mutationKey&&(0,n.hashKey)(t.mutationKey)!==(0,n.hashKey)(this.options.mutationKey)?this.reset():this.#r?.state.status==="pending"&&this.#r.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#r?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#n(e)}getCurrentResult(){return this.#t}reset(){this.#r?.removeObserver(this),this.#r=void 0,this.#i(),this.#n()}mutate(e,t){return this.#o=t,this.#r?.removeObserver(this),this.#r=this.#e.getMutationCache().build(this.#e,this.options),this.#r.addObserver(this),this.#r.execute(e)}#i(){let e=this.#r?.state??(0,r.getDefaultState)();this.#t={...e,isPending:"pending"===e.status,isSuccess:"success"===e.status,isError:"error"===e.status,isIdle:"idle"===e.status,mutate:this.mutate,reset:this.reset}}#n(e){o.notifyManager.batch(()=>{if(this.#o&&this.hasListeners()){let t=this.#t.variables,r=this.#t.context,o={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#o.onSuccess?.(e.data,t,r,o)}catch(e){Promise.reject(e)}try{this.#o.onSettled?.(e.data,null,t,r,o)}catch(e){Promise.reject(e)}}else if(e?.type==="error"){try{this.#o.onError?.(e.error,t,r,o)}catch(e){Promise.reject(e)}try{this.#o.onSettled?.(void 0,e.error,t,r,o)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},s=e.i(912598);function l(e,r){let i=(0,s.useQueryClient)(r),[l]=t.useState(()=>new a(i,e));t.useEffect(()=>{l.setOptions(e)},[l,e]);let c=t.useSyncExternalStore(t.useCallback(e=>l.subscribe(o.notifyManager.batchCalls(e)),[l]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),d=t.useCallback((e,t)=>{l.mutate(e,t).catch(n.noop)},[l]);if(c.error&&(0,n.shouldThrowError)(l.options.throwOnError,[c.error]))throw c.error;return{...c,mutate:d,mutateAsync:c.mutate}}e.s(["useMutation",()=>l],954616)},270345,e=>{"use strict";var t=e.i(764205);let r=async(e,r,o,i)=>"Admin"!=o&&"Admin Viewer"!=o?await (0,t.teamListCall)(e,i?.organization_id||null,r):await (0,t.teamListCall)(e,i?.organization_id||null);e.s(["fetchTeams",0,r])},653496,e=>{"use strict";var t=e.i(721369);e.s(["Tabs",()=>t.default])},983561,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let o={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"};var i=e.i(9583),n=r.forwardRef(function(e,n){return r.createElement(i.default,(0,t.default)({},e,{ref:n,icon:o}))});e.s(["RobotOutlined",0,n],983561)},350967,46757,e=>{"use strict";var t=e.i(290571),r=e.i(444755),o=e.i(673706),i=e.i(271645);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"},a={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"},s={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"},l={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"},d={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"},u={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"},m={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"};e.s(["colSpan",()=>c,"colSpanLg",()=>m,"colSpanMd",()=>u,"colSpanSm",()=>d,"gridCols",()=>n,"gridColsLg",()=>l,"gridColsMd",()=>s,"gridColsSm",()=>a],46757);let p=(0,o.makeClassName)("Grid"),g=(e,t)=>e&&Object.keys(t).includes(String(e))?t[e]:"",f=i.default.forwardRef((e,o)=>{let{numItems:c=1,numItemsSm:d,numItemsMd:u,numItemsLg:m,children:f,className:h}=e,b=(0,t.__rest)(e,["numItems","numItemsSm","numItemsMd","numItemsLg","children","className"]),y=g(c,n),v=g(d,a),x=g(u,s),C=g(m,l),w=(0,r.tremorTwMerge)(y,v,x,C);return i.default.createElement("div",Object.assign({ref:o,className:(0,r.tremorTwMerge)(p("root"),"grid",w,h)},b),f)});f.displayName="Grid",e.s(["Grid",()=>f],350967)},599724,936325,e=>{"use strict";var t=e.i(95779),r=e.i(444755),o=e.i(673706),i=e.i(271645);let n=i.default.forwardRef((e,n)=>{let{color:a,className:s,children:l}=e;return i.default.createElement("p",{ref:n,className:(0,r.tremorTwMerge)("text-tremor-default",a?(0,o.getColorClassNames)(a,t.colorPalette.text).textColor:(0,r.tremorTwMerge)("text-tremor-content","dark:text-dark-tremor-content"),s)},l)});n.displayName="Text",e.s(["default",()=>n],936325),e.s(["Text",()=>n],599724)},994388,e=>{"use strict";var t=e.i(290571),r=e.i(829087),o=e.i(271645);let i=["preEnter","entering","entered","preExit","exiting","exited","unmounted"],n=e=>({_s:e,status:i[e],isEnter:e<3,isMounted:6!==e,isResolved:2===e||e>4}),a=e=>e?6:5,s=(e,t,r,o,i)=>{clearTimeout(o.current);let a=n(e);t(a),r.current=a,i&&i({current:a})};var l=e.i(480731),c=e.i(444755),d=e.i(673706);let u=e=>{var r=(0,t.__rest)(e,[]);return o.default.createElement("svg",Object.assign({},r,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"}),o.default.createElement("path",{fill:"none",d:"M0 0h24v24H0z"}),o.default.createElement("path",{d:"M18.364 5.636L16.95 7.05A7 7 0 1 0 19 12h2a9 9 0 1 1-2.636-6.364z"}))};var m=e.i(95779);let p={xs:{height:"h-4",width:"w-4"},sm:{height:"h-5",width:"w-5"},md:{height:"h-5",width:"w-5"},lg:{height:"h-6",width:"w-6"},xl:{height:"h-6",width:"w-6"}},g=(e,t)=>{switch(e){case"primary":return{textColor:t?(0,d.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",hoverTextColor:t?(0,d.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",bgColor:t?(0,d.getColorClassNames)(t,m.colorPalette.background).bgColor:"bg-tremor-brand dark:bg-dark-tremor-brand",hoverBgColor:t?(0,d.getColorClassNames)(t,m.colorPalette.darkBackground).hoverBgColor:"hover:bg-tremor-brand-emphasis dark:hover:bg-dark-tremor-brand-emphasis",borderColor:t?(0,d.getColorClassNames)(t,m.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",hoverBorderColor:t?(0,d.getColorClassNames)(t,m.colorPalette.darkBorder).hoverBorderColor:"hover:border-tremor-brand-emphasis dark:hover:border-dark-tremor-brand-emphasis"};case"secondary":return{textColor:t?(0,d.getColorClassNames)(t,m.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,d.getColorClassNames)(t,m.colorPalette.text).textColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,d.getColorClassNames)("transparent").bgColor,hoverBgColor:t?(0,c.tremorTwMerge)((0,d.getColorClassNames)(t,m.colorPalette.background).hoverBgColor,"hover:bg-opacity-20 dark:hover:bg-opacity-20"):"hover:bg-tremor-brand-faint dark:hover:bg-dark-tremor-brand-faint",borderColor:t?(0,d.getColorClassNames)(t,m.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand"};case"light":return{textColor:t?(0,d.getColorClassNames)(t,m.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,d.getColorClassNames)(t,m.colorPalette.darkText).hoverTextColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,d.getColorClassNames)("transparent").bgColor,borderColor:"",hoverBorderColor:""}}},f=(0,d.makeClassName)("Button"),h=({loading:e,iconSize:t,iconPosition:r,Icon:i,needMargin:n,transitionStatus:a})=>{let s=n?r===l.HorizontalPositions.Left?(0,c.tremorTwMerge)("-ml-1","mr-1.5"):(0,c.tremorTwMerge)("-mr-1","ml-1.5"):"",d=(0,c.tremorTwMerge)("w-0 h-0"),m={default:d,entering:d,entered:t,exiting:t,exited:d};return e?o.default.createElement(u,{className:(0,c.tremorTwMerge)(f("icon"),"animate-spin shrink-0",s,m.default,m[a]),style:{transition:"width 150ms"}}):o.default.createElement(i,{className:(0,c.tremorTwMerge)(f("icon"),"shrink-0",t,s)})},b=o.default.forwardRef((e,i)=>{let{icon:u,iconPosition:m=l.HorizontalPositions.Left,size:b=l.Sizes.SM,color:y,variant:v="primary",disabled:x,loading:C=!1,loadingText:w,children:S,tooltip:O,className:k}=e,$=(0,t.__rest)(e,["icon","iconPosition","size","color","variant","disabled","loading","loadingText","children","tooltip","className"]),E=C||x,M=void 0!==u||C,z=C&&w,N=!(!S&&!z),j=(0,c.tremorTwMerge)(p[b].height,p[b].width),P="light"!==v?(0,c.tremorTwMerge)("rounded-tremor-default border","shadow-tremor-input","dark:shadow-dark-tremor-input"):"",T=g(v,y),R=("light"!==v?{xs:{paddingX:"px-2.5",paddingY:"py-1.5",fontSize:"text-xs"},sm:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-sm"},md:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-md"},lg:{paddingX:"px-4",paddingY:"py-2.5",fontSize:"text-lg"},xl:{paddingX:"px-4",paddingY:"py-3",fontSize:"text-xl"}}:{xs:{paddingX:"",paddingY:"",fontSize:"text-xs"},sm:{paddingX:"",paddingY:"",fontSize:"text-sm"},md:{paddingX:"",paddingY:"",fontSize:"text-md"},lg:{paddingX:"",paddingY:"",fontSize:"text-lg"},xl:{paddingX:"",paddingY:"",fontSize:"text-xl"}})[b],{tooltipProps:I,getReferenceProps:D}=(0,r.useTooltip)(300),[B,_]=(({enter:e=!0,exit:t=!0,preEnter:r,preExit:i,timeout:l,initialEntered:c,mountOnEnter:d,unmountOnExit:u,onStateChange:m}={})=>{let[p,g]=(0,o.useState)(()=>n(c?2:a(d))),f=(0,o.useRef)(p),h=(0,o.useRef)(0),[b,y]="object"==typeof l?[l.enter,l.exit]:[l,l],v=(0,o.useCallback)(()=>{let e=((e,t)=>{switch(e){case 1:case 0:return 2;case 4:case 3:return a(t)}})(f.current._s,u);e&&s(e,g,f,h,m)},[m,u]);return[p,(0,o.useCallback)(o=>{let n=e=>{switch(s(e,g,f,h,m),e){case 1:b>=0&&(h.current=((...e)=>setTimeout(...e))(v,b));break;case 4:y>=0&&(h.current=((...e)=>setTimeout(...e))(v,y));break;case 0:case 3:h.current=((...e)=>setTimeout(...e))(()=>{isNaN(document.body.offsetTop)||n(e+1)},0)}},l=f.current.isEnter;"boolean"!=typeof o&&(o=!l),o?l||n(e?+!r:2):l&&n(t?i?3:4:a(u))},[v,m,e,t,r,i,b,y,u]),v]})({timeout:50});return(0,o.useEffect)(()=>{_(C)},[C]),o.default.createElement("button",Object.assign({ref:(0,d.mergeRefs)([i,I.refs.setReference]),className:(0,c.tremorTwMerge)(f("root"),"shrink-0 inline-flex justify-center items-center group font-medium outline-none",P,R.paddingX,R.paddingY,R.fontSize,T.textColor,T.bgColor,T.borderColor,T.hoverBorderColor,E?"opacity-50 cursor-not-allowed":(0,c.tremorTwMerge)(g(v,y).hoverTextColor,g(v,y).hoverBgColor,g(v,y).hoverBorderColor),k),disabled:E},D,$),o.default.createElement(r.default,Object.assign({text:O},I)),M&&m!==l.HorizontalPositions.Right?o.default.createElement(h,{loading:C,iconSize:j,iconPosition:m,Icon:u,transitionStatus:B.status,needMargin:N}):null,z||S?o.default.createElement("span",{className:(0,c.tremorTwMerge)(f("text"),"text-tremor-default whitespace-nowrap")},z?w:S):null,M&&m===l.HorizontalPositions.Right?o.default.createElement(h,{loading:C,iconSize:j,iconPosition:m,Icon:u,transitionStatus:B.status,needMargin:N}):null)});b.displayName="Button",e.s(["Button",()=>b],994388)},304967,e=>{"use strict";var t=e.i(290571),r=e.i(271645),o=e.i(480731),i=e.i(95779),n=e.i(444755),a=e.i(673706);let s=(0,a.makeClassName)("Card"),l=r.default.forwardRef((e,l)=>{let{decoration:c="",decorationColor:d,children:u,className:m}=e,p=(0,t.__rest)(e,["decoration","decorationColor","children","className"]);return r.default.createElement("div",Object.assign({ref:l,className:(0,n.tremorTwMerge)(s("root"),"relative w-full text-left ring-1 rounded-tremor-default p-6","bg-tremor-background ring-tremor-ring shadow-tremor-card","dark:bg-dark-tremor-background dark:ring-dark-tremor-ring dark:shadow-dark-tremor-card",d?(0,a.getColorClassNames)(d,i.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",(e=>{if(!e)return"";switch(e){case o.HorizontalPositions.Left:return"border-l-4";case o.VerticalPositions.Top:return"border-t-4";case o.HorizontalPositions.Right:return"border-r-4";case o.VerticalPositions.Bottom:return"border-b-4";default:return""}})(c),m)},p),u)});l.displayName="Card",e.s(["Card",()=>l],304967)},629569,e=>{"use strict";var t=e.i(290571),r=e.i(95779),o=e.i(444755),i=e.i(673706),n=e.i(271645);let a=n.default.forwardRef((e,a)=>{let{color:s,children:l,className:c}=e,d=(0,t.__rest)(e,["color","children","className"]);return n.default.createElement("p",Object.assign({ref:a,className:(0,o.tremorTwMerge)("font-medium text-tremor-title",s?(0,i.getColorClassNames)(s,r.colorPalette.darkText).textColor:"text-tremor-content-strong dark:text-dark-tremor-content-strong",c)},d),l)});a.displayName="Title",e.s(["Title",()=>a],629569)},244451,e=>{"use strict";let t;e.i(247167);var r=e.i(271645),o=e.i(343794),i=e.i(242064),n=e.i(763731),a=e.i(174428);let s=80*Math.PI,l=e=>{let{dotClassName:t,style:i,hasCircleCls:n}=e;return r.createElement("circle",{className:(0,o.default)(`${t}-circle`,{[`${t}-circle-bg`]:n}),r:40,cx:50,cy:50,strokeWidth:20,style:i})},c=({percent:e,prefixCls:t})=>{let i=`${t}-dot`,n=`${i}-holder`,c=`${n}-hidden`,[d,u]=r.useState(!1);(0,a.default)(()=>{0!==e&&u(!0)},[0!==e]);let m=Math.max(Math.min(e,100),0);if(!d)return null;let p={strokeDashoffset:`${s/4}`,strokeDasharray:`${s*m/100} ${s*(100-m)/100}`};return r.createElement("span",{className:(0,o.default)(n,`${i}-progress`,m<=0&&c)},r.createElement("svg",{viewBox:"0 0 100 100",role:"progressbar","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":m},r.createElement(l,{dotClassName:i,hasCircleCls:!0}),r.createElement(l,{dotClassName:i,style:p})))};function d(e){let{prefixCls:t,percent:i=0}=e,n=`${t}-dot`,a=`${n}-holder`,s=`${a}-hidden`;return r.createElement(r.Fragment,null,r.createElement("span",{className:(0,o.default)(a,i>0&&s)},r.createElement("span",{className:(0,o.default)(n,`${t}-dot-spin`)},[1,2,3,4].map(e=>r.createElement("i",{className:`${t}-dot-item`,key:e})))),r.createElement(c,{prefixCls:t,percent:i}))}function u(e){var t;let{prefixCls:i,indicator:a,percent:s}=e,l=`${i}-dot`;return a&&r.isValidElement(a)?(0,n.cloneElement)(a,{className:(0,o.default)(null==(t=a.props)?void 0:t.className,l),percent:s}):r.createElement(d,{prefixCls:i,percent:s})}e.i(296059);var m=e.i(694758),p=e.i(183293),g=e.i(246422),f=e.i(838378);let h=new m.Keyframes("antSpinMove",{to:{opacity:1}}),b=new m.Keyframes("antRotate",{to:{transform:"rotate(405deg)"}}),y=(0,g.genStyleHooks)("Spin",e=>(e=>{let{componentCls:t,calc:r}=e;return{[t]:Object.assign(Object.assign({},(0,p.resetComponent)(e)),{position:"absolute",display:"none",color:e.colorPrimary,fontSize:0,textAlign:"center",verticalAlign:"middle",opacity:0,transition:`transform ${e.motionDurationSlow} ${e.motionEaseInOutCirc}`,"&-spinning":{position:"relative",display:"inline-block",opacity:1},[`${t}-text`]:{fontSize:e.fontSize,paddingTop:r(r(e.dotSize).sub(e.fontSize)).div(2).add(2).equal()},"&-fullscreen":{position:"fixed",width:"100vw",height:"100vh",backgroundColor:e.colorBgMask,zIndex:e.zIndexPopupBase,inset:0,display:"flex",alignItems:"center",flexDirection:"column",justifyContent:"center",opacity:0,visibility:"hidden",transition:`all ${e.motionDurationMid}`,"&-show":{opacity:1,visibility:"visible"},[t]:{[`${t}-dot-holder`]:{color:e.colorWhite},[`${t}-text`]:{color:e.colorTextLightSolid}}},"&-nested-loading":{position:"relative",[`> div > ${t}`]:{position:"absolute",top:0,insetInlineStart:0,zIndex:4,display:"block",width:"100%",height:"100%",maxHeight:e.contentHeight,[`${t}-dot`]:{position:"absolute",top:"50%",insetInlineStart:"50%",margin:r(e.dotSize).mul(-1).div(2).equal()},[`${t}-text`]:{position:"absolute",top:"50%",width:"100%",textShadow:`0 1px 2px ${e.colorBgContainer}`},[`&${t}-show-text ${t}-dot`]:{marginTop:r(e.dotSize).div(2).mul(-1).sub(10).equal()},"&-sm":{[`${t}-dot`]:{margin:r(e.dotSizeSM).mul(-1).div(2).equal()},[`${t}-text`]:{paddingTop:r(r(e.dotSizeSM).sub(e.fontSize)).div(2).add(2).equal()},[`&${t}-show-text ${t}-dot`]:{marginTop:r(e.dotSizeSM).div(2).mul(-1).sub(10).equal()}},"&-lg":{[`${t}-dot`]:{margin:r(e.dotSizeLG).mul(-1).div(2).equal()},[`${t}-text`]:{paddingTop:r(r(e.dotSizeLG).sub(e.fontSize)).div(2).add(2).equal()},[`&${t}-show-text ${t}-dot`]:{marginTop:r(e.dotSizeLG).div(2).mul(-1).sub(10).equal()}}},[`${t}-container`]:{position:"relative",transition:`opacity ${e.motionDurationSlow}`,"&::after":{position:"absolute",top:0,insetInlineEnd:0,bottom:0,insetInlineStart:0,zIndex:10,width:"100%",height:"100%",background:e.colorBgContainer,opacity:0,transition:`all ${e.motionDurationSlow}`,content:'""',pointerEvents:"none"}},[`${t}-blur`]:{clear:"both",opacity:.5,userSelect:"none",pointerEvents:"none","&::after":{opacity:.4,pointerEvents:"auto"}}},"&-tip":{color:e.spinDotDefault},[`${t}-dot-holder`]:{width:"1em",height:"1em",fontSize:e.dotSize,display:"inline-block",transition:`transform ${e.motionDurationSlow} ease, opacity ${e.motionDurationSlow} ease`,transformOrigin:"50% 50%",lineHeight:1,color:e.colorPrimary,"&-hidden":{transform:"scale(0.3)",opacity:0}},[`${t}-dot-progress`]:{position:"absolute",inset:0},[`${t}-dot`]:{position:"relative",display:"inline-block",fontSize:e.dotSize,width:"1em",height:"1em","&-item":{position:"absolute",display:"block",width:r(e.dotSize).sub(r(e.marginXXS).div(2)).div(2).equal(),height:r(e.dotSize).sub(r(e.marginXXS).div(2)).div(2).equal(),background:"currentColor",borderRadius:"100%",transform:"scale(0.75)",transformOrigin:"50% 50%",opacity:.3,animationName:h,animationDuration:"1s",animationIterationCount:"infinite",animationTimingFunction:"linear",animationDirection:"alternate","&:nth-child(1)":{top:0,insetInlineStart:0,animationDelay:"0s"},"&:nth-child(2)":{top:0,insetInlineEnd:0,animationDelay:"0.4s"},"&:nth-child(3)":{insetInlineEnd:0,bottom:0,animationDelay:"0.8s"},"&:nth-child(4)":{bottom:0,insetInlineStart:0,animationDelay:"1.2s"}},"&-spin":{transform:"rotate(45deg)",animationName:b,animationDuration:"1.2s",animationIterationCount:"infinite",animationTimingFunction:"linear"},"&-circle":{strokeLinecap:"round",transition:["stroke-dashoffset","stroke-dasharray","stroke","stroke-width","opacity"].map(t=>`${t} ${e.motionDurationSlow} ease`).join(","),fillOpacity:0,stroke:"currentcolor"},"&-circle-bg":{stroke:e.colorFillSecondary}},[`&-sm ${t}-dot`]:{"&, &-holder":{fontSize:e.dotSizeSM}},[`&-sm ${t}-dot-holder`]:{i:{width:r(r(e.dotSizeSM).sub(r(e.marginXXS).div(2))).div(2).equal(),height:r(r(e.dotSizeSM).sub(r(e.marginXXS).div(2))).div(2).equal()}},[`&-lg ${t}-dot`]:{"&, &-holder":{fontSize:e.dotSizeLG}},[`&-lg ${t}-dot-holder`]:{i:{width:r(r(e.dotSizeLG).sub(e.marginXXS)).div(2).equal(),height:r(r(e.dotSizeLG).sub(e.marginXXS)).div(2).equal()}},[`&${t}-show-text ${t}-text`]:{display:"block"}})}})((0,f.mergeToken)(e,{spinDotDefault:e.colorTextDescription})),e=>{let{controlHeightLG:t,controlHeight:r}=e;return{contentHeight:400,dotSize:t/2,dotSizeSM:.35*t,dotSizeLG:r}}),v=[[30,.05],[70,.03],[96,.01]];var x=function(e,t){var r={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&0>t.indexOf(o)&&(r[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,o=Object.getOwnPropertySymbols(e);it.indexOf(o[i])&&Object.prototype.propertyIsEnumerable.call(e,o[i])&&(r[o[i]]=e[o[i]]);return r};let C=e=>{var n;let{prefixCls:a,spinning:s=!0,delay:l=0,className:c,rootClassName:d,size:m="default",tip:p,wrapperClassName:g,style:f,children:h,fullscreen:b=!1,indicator:C,percent:w}=e,S=x(e,["prefixCls","spinning","delay","className","rootClassName","size","tip","wrapperClassName","style","children","fullscreen","indicator","percent"]),{getPrefixCls:O,direction:k,className:$,style:E,indicator:M}=(0,i.useComponentConfig)("spin"),z=O("spin",a),[N,j,P]=y(z),[T,R]=r.useState(()=>s&&(!s||!l||!!Number.isNaN(Number(l)))),I=function(e,t){let[o,i]=r.useState(0),n=r.useRef(null),a="auto"===t;return r.useEffect(()=>(a&&e&&(i(0),n.current=setInterval(()=>{i(e=>{let t=100-e;for(let r=0;r{n.current&&(clearInterval(n.current),n.current=null)}),[a,e]),a?o:t}(T,w);r.useEffect(()=>{if(s){let e=function(e,t,r){var o,i=r||{},n=i.noTrailing,a=void 0!==n&&n,s=i.noLeading,l=void 0!==s&&s,c=i.debounceMode,d=void 0===c?void 0:c,u=!1,m=0;function p(){o&&clearTimeout(o)}function g(){for(var r=arguments.length,i=Array(r),n=0;ne?l?(m=Date.now(),a||(o=setTimeout(d?f:g,e))):g():!0!==a&&(o=setTimeout(d?f:g,void 0===d?e-c:e)))}return g.cancel=function(e){var t=(e||{}).upcomingOnly;p(),u=!(void 0!==t&&t)},g}(l,()=>{R(!0)},{debounceMode:false});return e(),()=>{var t;null==(t=null==e?void 0:e.cancel)||t.call(e)}}R(!1)},[l,s]);let D=r.useMemo(()=>void 0!==h&&!b,[h,b]),B=(0,o.default)(z,$,{[`${z}-sm`]:"small"===m,[`${z}-lg`]:"large"===m,[`${z}-spinning`]:T,[`${z}-show-text`]:!!p,[`${z}-rtl`]:"rtl"===k},c,!b&&d,j,P),_=(0,o.default)(`${z}-container`,{[`${z}-blur`]:T}),L=null!=(n=null!=C?C:M)?n:t,X=Object.assign(Object.assign({},E),f),q=r.createElement("div",Object.assign({},S,{style:X,className:B,"aria-live":"polite","aria-busy":T}),r.createElement(u,{prefixCls:z,indicator:L,percent:I}),p&&(D||b)?r.createElement("div",{className:`${z}-text`},p):null);return N(D?r.createElement("div",Object.assign({},S,{className:(0,o.default)(`${z}-nested-loading`,g,j,P)}),T&&r.createElement("div",{key:"loading"},q),r.createElement("div",{className:_,key:"container"},h)):b?r.createElement("div",{className:(0,o.default)(`${z}-fullscreen`,{[`${z}-fullscreen-show`]:T},d,j,P)},q):q)};C.setDefaultIndicator=e=>{t=e},e.s(["default",0,C],244451)},981339,e=>{"use strict";var t=e.i(185793);e.s(["Skeleton",()=>t.default])},292639,e=>{"use strict";var t=e.i(764205),r=e.i(266027);let o=(0,e.i(243652).createQueryKeys)("uiSettings");e.s(["useUISettings",0,()=>(0,r.useQuery)({queryKey:o.list({}),queryFn:async()=>await (0,t.getUiSettings)(),staleTime:36e5,gcTime:36e5})])},743151,(e,t,r)=>{"use strict";function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}Object.defineProperty(r,"__esModule",{value:!0}),r.CopyToClipboard=void 0;var i=s(e.r(271645)),n=s(e.r(844343)),a=["text","onCopy","options","children"];function s(e){return e&&e.__esModule?e:{default:e}}function l(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,o)}return r}function c(e){for(var t=1;t=0||(i[r]=e[r]);return i}(e,t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);for(o=0;o=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(i[r]=e[r])}return i}(e,a),o=i.default.Children.only(t);return i.default.cloneElement(o,c(c({},r),{},{onClick:this.onClick}))}}],function(e,t){for(var r=0;r{"use strict";var o=e.r(743151).CopyToClipboard;o.CopyToClipboard=o,t.exports=o}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/12a00fb6ae67dbdf.js b/litellm/proxy/_experimental/out/_next/static/chunks/12a00fb6ae67dbdf.js deleted file mode 100644 index 5a565c21add..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/12a00fb6ae67dbdf.js +++ /dev/null @@ -1 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,916925,e=>{"use strict";var t,r=((t={}).A2A_Agent="A2A Agent",t.AI21="Ai21",t.AI21_CHAT="Ai21 Chat",t.AIML="AI/ML API",t.AIOHTTP_OPENAI="Aiohttp Openai",t.Anthropic="Anthropic",t.ANTHROPIC_TEXT="Anthropic Text",t.AssemblyAI="AssemblyAI",t.AUTO_ROUTER="Auto Router",t.Bedrock="Amazon Bedrock",t.BedrockMantle="Amazon Bedrock Mantle",t.SageMaker="AWS SageMaker",t.Azure="Azure",t.Azure_AI_Studio="Azure AI Foundry (Studio)",t.AZURE_TEXT="Azure Text",t.BASETEN="Baseten",t.BYTEZ="Bytez",t.Cerebras="Cerebras",t.CLARIFAI="Clarifai",t.CLOUDFLARE="Cloudflare",t.CODESTRAL="Codestral",t.Cohere="Cohere",t.COHERE_CHAT="Cohere Chat",t.COMETAPI="Cometapi",t.COMPACTIFAI="Compactifai",t.Cursor="Cursor",t.Dashscope="Dashscope",t.Databricks="Databricks (Qwen API)",t.DATAROBOT="Datarobot",t.DeepInfra="DeepInfra",t.Deepgram="Deepgram",t.Deepseek="Deepseek",t.DOCKER_MODEL_RUNNER="Docker Model Runner",t.DOTPROMPT="Dotprompt",t.ElevenLabs="ElevenLabs",t.EMPOWER="Empower",t.FalAI="Fal AI",t.FEATHERLESS_AI="Featherless Ai",t.FireworksAI="Fireworks AI",t.FRIENDLIAI="Friendliai",t.GALADRIEL="Galadriel",t.GITHUB_COPILOT="Github Copilot",t.Google_AI_Studio="Google AI Studio",t.GradientAI="GradientAI",t.Groq="Groq",t.HEROKU="Heroku",t.Hosted_Vllm="vllm",t.HUGGINGFACE="Huggingface",t.HYPERBOLIC="Hyperbolic",t.Infinity="Infinity",t.JinaAI="Jina AI",t.LAMBDA_AI="Lambda Ai",t.LEMONADE="Lemonade",t.LLAMAFILE="Llamafile",t.LM_STUDIO="Lm Studio",t.LLAMA="Meta Llama",t.MARITALK="Maritalk",t.MiniMax="MiniMax",t.MistralAI="Mistral AI",t.MOONSHOT="Moonshot",t.MORPH="Morph",t.NEBIUS="Nebius",t.NLP_CLOUD="Nlp Cloud",t.NOVITA="Novita",t.NSCALE="Nscale",t.NVIDIA_NIM="Nvidia Nim",t.Ollama="Ollama",t.OLLAMA_CHAT="Ollama Chat",t.OOBABOOGA="Oobabooga",t.OpenAI="OpenAI",t.OPENAI_LIKE="Openai Like",t.OpenAI_Compatible="OpenAI-Compatible Endpoints (Together AI, etc.)",t.OpenAI_Text="OpenAI Text Completion",t.OpenAI_Text_Compatible="OpenAI-Compatible Text Completion Models (Together AI, etc.)",t.Openrouter="Openrouter",t.Oracle="Oracle Cloud Infrastructure (OCI)",t.OVHCLOUD="Ovhcloud",t.Perplexity="Perplexity",t.PETALS="Petals",t.PG_VECTOR="Pg Vector",t.PREDIBASE="Predibase",t.RECRAFT="Recraft",t.REPLICATE="Replicate",t.RunwayML="RunwayML",t.SAGEMAKER_LEGACY="Sagemaker",t.Sambanova="Sambanova",t.SAP="SAP Generative AI Hub",t.Snowflake="Snowflake",t.TEXT_COMPLETION_CODESTRAL="Text-Completion-Codestral",t.TogetherAI="TogetherAI",t.TOPAZ="Topaz",t.Triton="Triton",t.V0="V0",t.VERCEL_AI_GATEWAY="Vercel Ai Gateway",t.Vertex_AI="Vertex AI (Anthropic, Gemini, etc.)",t.VERTEX_AI_BETA="Vertex Ai Beta",t.VLLM="Vllm",t.VolcEngine="VolcEngine",t.Voyage="Voyage AI",t.WANDB="Wandb",t.WATSONX="Watsonx",t.WATSONX_TEXT="Watsonx Text",t.xAI="xAI",t.XINFERENCE="Xinference",t);let a={A2A_Agent:"a2a_agent",AI21:"ai21",AI21_CHAT:"ai21_chat",AIML:"aiml",AIOHTTP_OPENAI:"aiohttp_openai",Anthropic:"anthropic",ANTHROPIC_TEXT:"anthropic_text",AssemblyAI:"assemblyai",AUTO_ROUTER:"auto_router",Azure:"azure",Azure_AI_Studio:"azure_ai",AZURE_TEXT:"azure_text",BASETEN:"baseten",Bedrock:"bedrock",BedrockMantle:"bedrock_mantle",BYTEZ:"bytez",Cerebras:"cerebras",CLARIFAI:"clarifai",CLOUDFLARE:"cloudflare",CODESTRAL:"codestral",Cohere:"cohere",COHERE_CHAT:"cohere_chat",COMETAPI:"cometapi",COMPACTIFAI:"compactifai",Cursor:"cursor",Dashscope:"dashscope",Databricks:"databricks",DATAROBOT:"datarobot",DeepInfra:"deepinfra",Deepgram:"deepgram",Deepseek:"deepseek",DOCKER_MODEL_RUNNER:"docker_model_runner",DOTPROMPT:"dotprompt",ElevenLabs:"elevenlabs",EMPOWER:"empower",FalAI:"fal_ai",FEATHERLESS_AI:"featherless_ai",FireworksAI:"fireworks_ai",FRIENDLIAI:"friendliai",GALADRIEL:"galadriel",GITHUB_COPILOT:"github_copilot",Google_AI_Studio:"gemini",GradientAI:"gradient_ai",Groq:"groq",HEROKU:"heroku",Hosted_Vllm:"hosted_vllm",HUGGINGFACE:"huggingface",HYPERBOLIC:"hyperbolic",Infinity:"infinity",JinaAI:"jina_ai",LAMBDA_AI:"lambda_ai",LEMONADE:"lemonade",LLAMAFILE:"llamafile",LLAMA:"meta_llama",LM_STUDIO:"lm_studio",MARITALK:"maritalk",MiniMax:"minimax",MistralAI:"mistral",MOONSHOT:"moonshot",MORPH:"morph",NEBIUS:"nebius",NLP_CLOUD:"nlp_cloud",NOVITA:"novita",NSCALE:"nscale",NVIDIA_NIM:"nvidia_nim",Ollama:"ollama",OLLAMA_CHAT:"ollama_chat",OOBABOOGA:"oobabooga",OpenAI:"openai",OPENAI_LIKE:"openai_like",OpenAI_Compatible:"openai",OpenAI_Text:"text-completion-openai",OpenAI_Text_Compatible:"text-completion-openai",Openrouter:"openrouter",Oracle:"oci",OVHCLOUD:"ovhcloud",Perplexity:"perplexity",PETALS:"petals",PG_VECTOR:"pg_vector",PREDIBASE:"predibase",RECRAFT:"recraft",REPLICATE:"replicate",RunwayML:"runwayml",SAGEMAKER_LEGACY:"sagemaker",SageMaker:"sagemaker_chat",Sambanova:"sambanova",SAP:"sap",Snowflake:"snowflake",TEXT_COMPLETION_CODESTRAL:"text-completion-codestral",TogetherAI:"together_ai",TOPAZ:"topaz",Triton:"triton",V0:"v0",VERCEL_AI_GATEWAY:"vercel_ai_gateway",Vertex_AI:"vertex_ai",VERTEX_AI_BETA:"vertex_ai_beta",VLLM:"vllm",VolcEngine:"volcengine",Voyage:"voyage",WANDB:"wandb",WATSONX:"watsonx",WATSONX_TEXT:"watsonx_text",xAI:"xai",XINFERENCE:"xinference"},i="../ui/assets/logos/",o={"A2A Agent":`${i}a2a_agent.png`,Ai21:`${i}ai21.svg`,"Ai21 Chat":`${i}ai21.svg`,"AI/ML API":`${i}aiml_api.svg`,"Aiohttp Openai":`${i}openai_small.svg`,Anthropic:`${i}anthropic.svg`,"Anthropic Text":`${i}anthropic.svg`,AssemblyAI:`${i}assemblyai_small.png`,Azure:`${i}microsoft_azure.svg`,"Azure AI Foundry (Studio)":`${i}microsoft_azure.svg`,"Azure Text":`${i}microsoft_azure.svg`,Baseten:`${i}baseten.svg`,"Amazon Bedrock":`${i}bedrock.svg`,"Amazon Bedrock Mantle":`${i}bedrock.svg`,"AWS SageMaker":`${i}bedrock.svg`,Cerebras:`${i}cerebras.svg`,Cloudflare:`${i}cloudflare.svg`,Codestral:`${i}mistral.svg`,Cohere:`${i}cohere.svg`,"Cohere Chat":`${i}cohere.svg`,Cometapi:`${i}cometapi.svg`,Cursor:`${i}cursor.svg`,"Databricks (Qwen API)":`${i}databricks.svg`,Dashscope:`${i}dashscope.svg`,Deepseek:`${i}deepseek.svg`,Deepgram:`${i}deepgram.png`,DeepInfra:`${i}deepinfra.png`,ElevenLabs:`${i}elevenlabs.png`,"Fal AI":`${i}fal_ai.jpg`,"Featherless Ai":`${i}featherless.svg`,"Fireworks AI":`${i}fireworks.svg`,Friendliai:`${i}friendli.svg`,"Github Copilot":`${i}github_copilot.svg`,"Google AI Studio":`${i}google.svg`,GradientAI:`${i}gradientai.svg`,Groq:`${i}groq.svg`,vllm:`${i}vllm.png`,Huggingface:`${i}huggingface.svg`,Hyperbolic:`${i}hyperbolic.svg`,Infinity:`${i}infinity.png`,"Jina AI":`${i}jina.png`,"Lambda Ai":`${i}lambda.svg`,"Lm Studio":`${i}lmstudio.svg`,"Meta Llama":`${i}meta_llama.svg`,MiniMax:`${i}minimax.svg`,"Mistral AI":`${i}mistral.svg`,Moonshot:`${i}moonshot.svg`,Morph:`${i}morph.svg`,Nebius:`${i}nebius.svg`,Novita:`${i}novita.svg`,"Nvidia Nim":`${i}nvidia_nim.svg`,Ollama:`${i}ollama.svg`,"Ollama Chat":`${i}ollama.svg`,Oobabooga:`${i}openai_small.svg`,OpenAI:`${i}openai_small.svg`,"Openai Like":`${i}openai_small.svg`,"OpenAI Text Completion":`${i}openai_small.svg`,"OpenAI-Compatible Text Completion Models (Together AI, etc.)":`${i}openai_small.svg`,"OpenAI-Compatible Endpoints (Together AI, etc.)":`${i}openai_small.svg`,Openrouter:`${i}openrouter.svg`,"Oracle Cloud Infrastructure (OCI)":`${i}oracle.svg`,Perplexity:`${i}perplexity-ai.svg`,Recraft:`${i}recraft.svg`,Replicate:`${i}replicate.svg`,RunwayML:`${i}runwayml.png`,Sagemaker:`${i}bedrock.svg`,Sambanova:`${i}sambanova.svg`,"SAP Generative AI Hub":`${i}sap.png`,Snowflake:`${i}snowflake.svg`,"Text-Completion-Codestral":`${i}mistral.svg`,TogetherAI:`${i}togetherai.svg`,Topaz:`${i}topaz.svg`,Triton:`${i}nvidia_triton.png`,V0:`${i}v0.svg`,"Vercel Ai Gateway":`${i}vercel.svg`,"Vertex AI (Anthropic, Gemini, etc.)":`${i}google.svg`,"Vertex Ai Beta":`${i}google.svg`,Vllm:`${i}vllm.png`,VolcEngine:`${i}volcengine.png`,"Voyage AI":`${i}voyage.webp`,Watsonx:`${i}watsonx.svg`,"Watsonx Text":`${i}watsonx.svg`,xAI:`${i}xai.svg`,Xinference:`${i}xinference.svg`};e.s(["Providers",()=>r,"getPlaceholder",0,e=>{if("AI/ML API"===e)return"aiml/flux-pro/v1.1";if("Vertex AI (Anthropic, Gemini, etc.)"===e)return"gemini-pro";if("Anthropic"==e)return"claude-3-opus";if("Amazon Bedrock"==e)return"claude-3-opus";if("AWS SageMaker"==e)return"sagemaker/jumpstart-dft-meta-textgeneration-llama-2-7b";else if("Google AI Studio"==e)return"gemini-pro";else if("Azure AI Foundry (Studio)"==e)return"azure_ai/command-r-plus";else if("Azure"==e)return"my-deployment";else if("Oracle Cloud Infrastructure (OCI)"==e)return"oci/xai.grok-4";else if("Snowflake"==e)return"snowflake/mistral-7b";else if("Voyage AI"==e)return"voyage/";else if("Jina AI"==e)return"jina_ai/";else if("VolcEngine"==e)return"volcengine/";else if("DeepInfra"==e)return"deepinfra/";else if("Fal AI"==e)return"fal_ai/fal-ai/flux-pro/v1.1-ultra";else if("RunwayML"==e)return"runwayml/gen4_turbo";else if("Watsonx"===e)return"watsonx/ibm/granite-3-3-8b-instruct";else if("Cursor"===e)return"cursor/claude-4-sonnet";else return"gpt-3.5-turbo"},"getProviderLogoAndName",0,e=>{if(!e)return{logo:"",displayName:"-"};if("gemini"===e.toLowerCase()){let e="Google AI Studio";return{logo:o[e],displayName:e}}let t=Object.keys(a).find(t=>a[t].toLowerCase()===e.toLowerCase());if(!t)return{logo:"",displayName:e};let i=r[t];return{logo:o[i],displayName:i}},"getProviderModels",0,(e,t)=>{console.log(`Provider key: ${e}`);let r=a[e];console.log(`Provider mapped to: ${r}`);let i=[];return e&&"object"==typeof t&&(Object.entries(t).forEach(([e,t])=>{if(null!==t&&"object"==typeof t&&"litellm_provider"in t){let a=t.litellm_provider;(a===r||"string"==typeof a&&a.includes(r))&&i.push(e)}}),"Cohere"==e&&(console.log("Adding cohere chat models"),Object.entries(t).forEach(([e,t])=>{null!==t&&"object"==typeof t&&"litellm_provider"in t&&"cohere_chat"===t.litellm_provider&&i.push(e)})),"AWS SageMaker"==e&&(console.log("Adding sagemaker chat models"),Object.entries(t).forEach(([e,t])=>{null!==t&&"object"==typeof t&&"litellm_provider"in t&&"sagemaker_chat"===t.litellm_provider&&i.push(e)}))),i},"providerLogoMap",0,o,"provider_map",0,a])},362024,e=>{"use strict";var t=e.i(988122);e.s(["Collapse",()=>t.default])},152473,e=>{"use strict";var t=e.i(271645);let r={enabled:!0,leading:!1,trailing:!0,wait:0,onExecute:()=>{}};class a{constructor(e,t){this.fn=e,this._canLeadingExecute=!0,this._isPending=!1,this._executionCount=0,this._options={...r,...t}}setOptions(e){return this._options={...this._options,...e},this._options.enabled||(this._isPending=!1),this._options}getOptions(){return this._options}maybeExecute(...e){this._options.leading&&this._canLeadingExecute&&(this.executeFunction(...e),this._canLeadingExecute=!1),(this._options.leading||this._options.trailing)&&(this._isPending=!0),this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=setTimeout(()=>{this._canLeadingExecute=!0,this._isPending=!1,this._options.trailing&&this.executeFunction(...e)},this._options.wait)}executeFunction(...e){this._options.enabled&&(this.fn(...e),this._executionCount++,this._options.onExecute(this))}cancel(){this._timeoutId&&(clearTimeout(this._timeoutId),this._canLeadingExecute=!0,this._isPending=!1)}getExecutionCount(){return this._executionCount}getIsPending(){return this._options.enabled&&this._isPending}}function i(e,r){let[i,o]=(0,t.useState)(e),n=function(e,r){let[i]=(0,t.useState)(()=>{var t;return Object.getOwnPropertyNames(Object.getPrototypeOf(t=new a(e,r))).filter(e=>"function"==typeof t[e]).reduce((e,r)=>{let a=t[r];return"function"==typeof a&&(e[r]=a.bind(t)),e},{})});return i.setOptions(r),i}(o,r);return[i,n.maybeExecute,n]}e.s(["useDebouncedState",()=>i],152473)},738014,e=>{"use strict";var t=e.i(135214),r=e.i(764205),a=e.i(266027);let i=(0,e.i(243652).createQueryKeys)("users");e.s(["useCurrentUser",0,()=>{let{accessToken:e,userId:o,userRole:n}=(0,t.default)();return(0,a.useQuery)({queryKey:i.detail(o),queryFn:async()=>{let t=await (0,r.userInfoCall)(e,o,n,!1,null,null);return console.log(`userInfo: ${JSON.stringify(t)}`),t.user_info},enabled:!!(e&&o&&n)})}])},906579,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),a=e.i(361275),i=e.i(702779),o=e.i(763731),n=e.i(242064);e.i(296059);var s=e.i(915654),l=e.i(694758),c=e.i(183293),u=e.i(403541),d=e.i(246422),m=e.i(838378);let g=new l.Keyframes("antStatusProcessing",{"0%":{transform:"scale(0.8)",opacity:.5},"100%":{transform:"scale(2.4)",opacity:0}}),p=new l.Keyframes("antZoomBadgeIn",{"0%":{transform:"scale(0) translate(50%, -50%)",opacity:0},"100%":{transform:"scale(1) translate(50%, -50%)"}}),f=new l.Keyframes("antZoomBadgeOut",{"0%":{transform:"scale(1) translate(50%, -50%)"},"100%":{transform:"scale(0) translate(50%, -50%)",opacity:0}}),h=new l.Keyframes("antNoWrapperZoomBadgeIn",{"0%":{transform:"scale(0)",opacity:0},"100%":{transform:"scale(1)"}}),b=new l.Keyframes("antNoWrapperZoomBadgeOut",{"0%":{transform:"scale(1)"},"100%":{transform:"scale(0)",opacity:0}}),v=new l.Keyframes("antBadgeLoadingCircle",{"0%":{transformOrigin:"50%"},"100%":{transform:"translate(50%, -50%) rotate(360deg)",transformOrigin:"50%"}}),A=e=>{let{fontHeight:t,lineWidth:r,marginXS:a,colorBorderBg:i}=e,o=e.colorTextLightSolid,n=e.colorError,s=e.colorErrorHover;return(0,m.mergeToken)(e,{badgeFontHeight:t,badgeShadowSize:r,badgeTextColor:o,badgeColor:n,badgeColorHover:s,badgeShadowColor:i,badgeProcessingDuration:"1.2s",badgeRibbonOffset:a,badgeRibbonCornerTransform:"scaleY(0.75)",badgeRibbonCornerFilter:"brightness(75%)"})},y=e=>{let{fontSize:t,lineHeight:r,fontSizeSM:a,lineWidth:i}=e;return{indicatorZIndex:"auto",indicatorHeight:Math.round(t*r)-2*i,indicatorHeightSM:t,dotSize:a/2,textFontSize:a,textFontSizeSM:a,textFontWeight:"normal",statusSize:a/2}},O=(0,d.genStyleHooks)("Badge",e=>(e=>{let{componentCls:t,iconCls:r,antCls:a,badgeShadowSize:i,textFontSize:o,textFontSizeSM:n,statusSize:l,dotSize:d,textFontWeight:m,indicatorHeight:A,indicatorHeightSM:y,marginXS:O,calc:x}=e,C=`${a}-scroll-number`,I=(0,u.genPresetColor)(e,(e,{darkColor:r})=>({[`&${t} ${t}-color-${e}`]:{background:r,[`&:not(${t}-count)`]:{color:r},"a:hover &":{background:r}}}));return{[t]:Object.assign(Object.assign(Object.assign(Object.assign({},(0,c.resetComponent)(e)),{position:"relative",display:"inline-block",width:"fit-content",lineHeight:1,[`${t}-count`]:{display:"inline-flex",justifyContent:"center",zIndex:e.indicatorZIndex,minWidth:A,height:A,color:e.badgeTextColor,fontWeight:m,fontSize:o,lineHeight:(0,s.unit)(A),whiteSpace:"nowrap",textAlign:"center",background:e.badgeColor,borderRadius:x(A).div(2).equal(),boxShadow:`0 0 0 ${(0,s.unit)(i)} ${e.badgeShadowColor}`,transition:`background ${e.motionDurationMid}`,a:{color:e.badgeTextColor},"a:hover":{color:e.badgeTextColor},"a:hover &":{background:e.badgeColorHover}},[`${t}-count-sm`]:{minWidth:y,height:y,fontSize:n,lineHeight:(0,s.unit)(y),borderRadius:x(y).div(2).equal()},[`${t}-multiple-words`]:{padding:`0 ${(0,s.unit)(e.paddingXS)}`,bdi:{unicodeBidi:"plaintext"}},[`${t}-dot`]:{zIndex:e.indicatorZIndex,width:d,minWidth:d,height:d,background:e.badgeColor,borderRadius:"100%",boxShadow:`0 0 0 ${(0,s.unit)(i)} ${e.badgeShadowColor}`},[`${t}-count, ${t}-dot, ${C}-custom-component`]:{position:"absolute",top:0,insetInlineEnd:0,transform:"translate(50%, -50%)",transformOrigin:"100% 0%",[`&${r}-spin`]:{animationName:v,animationDuration:"1s",animationIterationCount:"infinite",animationTimingFunction:"linear"}},[`&${t}-status`]:{lineHeight:"inherit",verticalAlign:"baseline",[`${t}-status-dot`]:{position:"relative",top:-1,display:"inline-block",width:l,height:l,verticalAlign:"middle",borderRadius:"50%"},[`${t}-status-success`]:{backgroundColor:e.colorSuccess},[`${t}-status-processing`]:{overflow:"visible",color:e.colorInfo,backgroundColor:e.colorInfo,borderColor:"currentcolor","&::after":{position:"absolute",top:0,insetInlineStart:0,width:"100%",height:"100%",borderWidth:i,borderStyle:"solid",borderColor:"inherit",borderRadius:"50%",animationName:g,animationDuration:e.badgeProcessingDuration,animationIterationCount:"infinite",animationTimingFunction:"ease-in-out",content:'""'}},[`${t}-status-default`]:{backgroundColor:e.colorTextPlaceholder},[`${t}-status-error`]:{backgroundColor:e.colorError},[`${t}-status-warning`]:{backgroundColor:e.colorWarning},[`${t}-status-text`]:{marginInlineStart:O,color:e.colorText,fontSize:e.fontSize}}}),I),{[`${t}-zoom-appear, ${t}-zoom-enter`]:{animationName:p,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack,animationFillMode:"both"},[`${t}-zoom-leave`]:{animationName:f,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack,animationFillMode:"both"},[`&${t}-not-a-wrapper`]:{[`${t}-zoom-appear, ${t}-zoom-enter`]:{animationName:h,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack},[`${t}-zoom-leave`]:{animationName:b,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack},[`&:not(${t}-status)`]:{verticalAlign:"middle"},[`${C}-custom-component, ${t}-count`]:{transform:"none"},[`${C}-custom-component, ${C}`]:{position:"relative",top:"auto",display:"block",transformOrigin:"50% 50%"}},[C]:{overflow:"hidden",transition:`all ${e.motionDurationMid} ${e.motionEaseOutBack}`,[`${C}-only`]:{position:"relative",display:"inline-block",height:A,transition:`all ${e.motionDurationSlow} ${e.motionEaseOutBack}`,WebkitTransformStyle:"preserve-3d",WebkitBackfaceVisibility:"hidden",[`> p${C}-only-unit`]:{height:A,margin:0,WebkitTransformStyle:"preserve-3d",WebkitBackfaceVisibility:"hidden"}},[`${C}-symbol`]:{verticalAlign:"top"}},"&-rtl":{direction:"rtl",[`${t}-count, ${t}-dot, ${C}-custom-component`]:{transform:"translate(-50%, -50%)"}}})}})(A(e)),y),x=(0,d.genStyleHooks)(["Badge","Ribbon"],e=>(e=>{let{antCls:t,badgeFontHeight:r,marginXS:a,badgeRibbonOffset:i,calc:o}=e,n=`${t}-ribbon`,l=`${t}-ribbon-wrapper`,d=(0,u.genPresetColor)(e,(e,{darkColor:t})=>({[`&${n}-color-${e}`]:{background:t,color:t}}));return{[l]:{position:"relative"},[n]:Object.assign(Object.assign(Object.assign(Object.assign({},(0,c.resetComponent)(e)),{position:"absolute",top:a,padding:`0 ${(0,s.unit)(e.paddingXS)}`,color:e.colorPrimary,lineHeight:(0,s.unit)(r),whiteSpace:"nowrap",backgroundColor:e.colorPrimary,borderRadius:e.borderRadiusSM,[`${n}-text`]:{color:e.badgeTextColor},[`${n}-corner`]:{position:"absolute",top:"100%",width:i,height:i,color:"currentcolor",border:`${(0,s.unit)(o(i).div(2).equal())} solid`,transform:e.badgeRibbonCornerTransform,transformOrigin:"top",filter:e.badgeRibbonCornerFilter}}),d),{[`&${n}-placement-end`]:{insetInlineEnd:o(i).mul(-1).equal(),borderEndEndRadius:0,[`${n}-corner`]:{insetInlineEnd:0,borderInlineEndColor:"transparent",borderBlockEndColor:"transparent"}},[`&${n}-placement-start`]:{insetInlineStart:o(i).mul(-1).equal(),borderEndStartRadius:0,[`${n}-corner`]:{insetInlineStart:0,borderBlockEndColor:"transparent",borderInlineStartColor:"transparent"}},"&-rtl":{direction:"rtl"}})}})(A(e)),y),C=e=>{let a,{prefixCls:i,value:o,current:n,offset:s=0}=e;return s&&(a={position:"absolute",top:`${s}00%`,left:0}),t.createElement("span",{style:a,className:(0,r.default)(`${i}-only-unit`,{current:n})},o)},I=e=>{let r,a,{prefixCls:i,count:o,value:n}=e,s=Number(n),l=Math.abs(o),[c,u]=t.useState(s),[d,m]=t.useState(l),g=()=>{u(s),m(l)};if(t.useEffect(()=>{let e=setTimeout(g,1e3);return()=>clearTimeout(e)},[s]),c===s||Number.isNaN(s)||Number.isNaN(c))r=[t.createElement(C,Object.assign({},e,{key:s,current:!0}))],a={transition:"none"};else{r=[];let i=s+10,o=[];for(let e=s;e<=i;e+=1)o.push(e);let n=de%10===c);r=(n<0?o.slice(0,u+1):o.slice(u)).map((r,a)=>t.createElement(C,Object.assign({},e,{key:r,value:r%10,offset:n<0?a-u:a,current:a===u}))),a={transform:`translateY(${-function(e,t,r){let a=e,i=0;for(;(a+10)%10!==t;)a+=r,i+=r;return i}(c,s,n)}00%)`}}return t.createElement("span",{className:`${i}-only`,style:a,onTransitionEnd:g},r)};var E=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,a=Object.getOwnPropertySymbols(e);it.indexOf(a[i])&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(r[a[i]]=e[a[i]]);return r};let $=t.forwardRef((e,a)=>{let{prefixCls:i,count:s,className:l,motionClassName:c,style:u,title:d,show:m,component:g="sup",children:p}=e,f=E(e,["prefixCls","count","className","motionClassName","style","title","show","component","children"]),{getPrefixCls:h}=t.useContext(n.ConfigContext),b=h("scroll-number",i),v=Object.assign(Object.assign({},f),{"data-show":m,style:u,className:(0,r.default)(b,l,c),title:d}),A=s;if(s&&Number(s)%1==0){let e=String(s).split("");A=t.createElement("bdi",null,e.map((r,a)=>t.createElement(I,{prefixCls:b,count:Number(s),value:r,key:e.length-a})))}return((null==u?void 0:u.borderColor)&&(v.style=Object.assign(Object.assign({},u),{boxShadow:`0 0 0 1px ${u.borderColor} inset`})),p)?(0,o.cloneElement)(p,e=>({className:(0,r.default)(`${b}-custom-component`,null==e?void 0:e.className,c)})):t.createElement(g,Object.assign({},v,{ref:a}),A)});var _=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,a=Object.getOwnPropertySymbols(e);it.indexOf(a[i])&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(r[a[i]]=e[a[i]]);return r};let T=t.forwardRef((e,s)=>{var l,c,u,d,m;let{prefixCls:g,scrollNumberPrefixCls:p,children:f,status:h,text:b,color:v,count:A=null,overflowCount:y=99,dot:x=!1,size:C="default",title:I,offset:E,style:T,className:w,rootClassName:S,classNames:N,styles:M,showZero:R=!1}=e,P=_(e,["prefixCls","scrollNumberPrefixCls","children","status","text","color","count","overflowCount","dot","size","title","offset","style","className","rootClassName","classNames","styles","showZero"]),{getPrefixCls:k,direction:j,badge:L}=t.useContext(n.ConfigContext),D=k("badge",g),[B,F,z]=O(D),H=A>y?`${y}+`:A,G="0"===H||0===H||"0"===b||0===b,V=null===A||G&&!R,W=(null!=h||null!=v)&&V,K=null!=h||!G,U=x&&!G,q=U?"":H,X=(0,t.useMemo)(()=>((null==q||""===q)&&(null==b||""===b)||G&&!R)&&!U,[q,G,R,U,b]),Q=(0,t.useRef)(A);X||(Q.current=A);let Z=Q.current,Y=(0,t.useRef)(q);X||(Y.current=q);let J=Y.current,ee=(0,t.useRef)(U);X||(ee.current=U);let et=(0,t.useMemo)(()=>{if(!E)return Object.assign(Object.assign({},null==L?void 0:L.style),T);let e={marginTop:E[1]};return"rtl"===j?e.left=Number.parseInt(E[0],10):e.right=-Number.parseInt(E[0],10),Object.assign(Object.assign(Object.assign({},e),null==L?void 0:L.style),T)},[j,E,T,null==L?void 0:L.style]),er=null!=I?I:"string"==typeof Z||"number"==typeof Z?Z:void 0,ea=!X&&(0===b?R:!!b&&!0!==b),ei=ea?t.createElement("span",{className:`${D}-status-text`},b):null,eo=Z&&"object"==typeof Z?(0,o.cloneElement)(Z,e=>({style:Object.assign(Object.assign({},et),e.style)})):void 0,en=(0,i.isPresetColor)(v,!1),es=(0,r.default)(null==N?void 0:N.indicator,null==(l=null==L?void 0:L.classNames)?void 0:l.indicator,{[`${D}-status-dot`]:W,[`${D}-status-${h}`]:!!h,[`${D}-color-${v}`]:en}),el={};v&&!en&&(el.color=v,el.background=v);let ec=(0,r.default)(D,{[`${D}-status`]:W,[`${D}-not-a-wrapper`]:!f,[`${D}-rtl`]:"rtl"===j},w,S,null==L?void 0:L.className,null==(c=null==L?void 0:L.classNames)?void 0:c.root,null==N?void 0:N.root,F,z);if(!f&&W&&(b||K||!V)){let e=et.color;return B(t.createElement("span",Object.assign({},P,{className:ec,style:Object.assign(Object.assign(Object.assign({},null==M?void 0:M.root),null==(u=null==L?void 0:L.styles)?void 0:u.root),et)}),t.createElement("span",{className:es,style:Object.assign(Object.assign(Object.assign({},null==M?void 0:M.indicator),null==(d=null==L?void 0:L.styles)?void 0:d.indicator),el)}),ea&&t.createElement("span",{style:{color:e},className:`${D}-status-text`},b)))}return B(t.createElement("span",Object.assign({ref:s},P,{className:ec,style:Object.assign(Object.assign({},null==(m=null==L?void 0:L.styles)?void 0:m.root),null==M?void 0:M.root)}),f,t.createElement(a.default,{visible:!X,motionName:`${D}-zoom`,motionAppear:!1,motionDeadline:1e3},({className:e})=>{var a,i;let o=k("scroll-number",p),n=ee.current,s=(0,r.default)(null==N?void 0:N.indicator,null==(a=null==L?void 0:L.classNames)?void 0:a.indicator,{[`${D}-dot`]:n,[`${D}-count`]:!n,[`${D}-count-sm`]:"small"===C,[`${D}-multiple-words`]:!n&&J&&J.toString().length>1,[`${D}-status-${h}`]:!!h,[`${D}-color-${v}`]:en}),l=Object.assign(Object.assign(Object.assign({},null==M?void 0:M.indicator),null==(i=null==L?void 0:L.styles)?void 0:i.indicator),et);return v&&!en&&((l=l||{}).background=v),t.createElement($,{prefixCls:o,show:!X,motionClassName:e,className:s,count:J,title:er,style:l,key:"scrollNumber"},eo)}),ei))});T.Ribbon=e=>{let{className:a,prefixCls:o,style:s,color:l,children:c,text:u,placement:d="end",rootClassName:m}=e,{getPrefixCls:g,direction:p}=t.useContext(n.ConfigContext),f=g("ribbon",o),h=`${f}-wrapper`,[b,v,A]=x(f,h),y=(0,i.isPresetColor)(l,!1),O=(0,r.default)(f,`${f}-placement-${d}`,{[`${f}-rtl`]:"rtl"===p,[`${f}-color-${l}`]:y},a),C={},I={};return l&&!y&&(C.background=l,I.color=l),b(t.createElement("div",{className:(0,r.default)(h,m,v,A)},c,t.createElement("div",{className:(0,r.default)(O,v),style:Object.assign(Object.assign({},C),s)},t.createElement("span",{className:`${f}-text`},u),t.createElement("div",{className:`${f}-corner`,style:I}))))},e.s(["Badge",0,T],906579)},621482,e=>{"use strict";var t=e.i(869230),r=e.i(992571),a=class extends t.QueryObserver{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){super.setOptions({...e,behavior:(0,r.infiniteQueryBehavior)()})}getOptimisticResult(e){return e.behavior=(0,r.infiniteQueryBehavior)(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:a}=e,i=super.createResult(e,t),{isFetching:o,isRefetching:n,isError:s,isRefetchError:l}=i,c=a.fetchMeta?.fetchMore?.direction,u=s&&"forward"===c,d=o&&"forward"===c,m=s&&"backward"===c,g=o&&"backward"===c;return{...i,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:(0,r.hasNextPage)(t,a.data),hasPreviousPage:(0,r.hasPreviousPage)(t,a.data),isFetchNextPageError:u,isFetchingNextPage:d,isFetchPreviousPageError:m,isFetchingPreviousPage:g,isRefetchError:l&&!u&&!m,isRefetching:n&&!d&&!g}}},i=e.i(469637);function o(e,t){return(0,i.useBaseQuery)(e,a,t)}e.s(["useInfiniteQuery",()=>o],621482)},785242,e=>{"use strict";var t=e.i(619273),r=e.i(266027),a=e.i(912598),i=e.i(135214),o=e.i(270345),n=e.i(243652),s=e.i(764205);let l=(0,n.createQueryKeys)("teams"),c=async(e,t,r,a={})=>{try{let i=(0,s.getProxyBaseUrl)(),o=new URLSearchParams(Object.entries({team_id:a.teamID,organization_id:a.organizationID,team_alias:a.team_alias,user_id:a.userID,page:t,page_size:r,sort_by:a.sortBy,sort_order:a.sortOrder,status:"deleted"}).filter(([,e])=>null!=e).map(([e,t])=>[e,String(t)])),n=`${i?`${i}/v2/team/list`:"/v2/team/list"}?${o}`,l=await fetch(n,{method:"GET",headers:{[(0,s.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!l.ok){let e=await l.json(),t=(0,s.deriveErrorMessage)(e);throw(0,s.handleError)(t),Error(t)}let c=await l.json();if(console.log("/team/list?status=deleted API Response:",c),c&&"object"==typeof c&&"teams"in c)return c.teams;return c}catch(e){throw console.error("Failed to list deleted teams:",e),e}},u=(0,n.createQueryKeys)("deletedTeams");e.s(["useDeletedTeams",0,(e,a,o={})=>{let{accessToken:n}=(0,i.default)();return(0,r.useQuery)({queryKey:u.list({page:e,limit:a,...o}),queryFn:async()=>await c(n,e,a,o),enabled:!!n,staleTime:3e4,placeholderData:t.keepPreviousData})},"useTeam",0,e=>{let{accessToken:t}=(0,i.default)(),o=(0,a.useQueryClient)();return(0,r.useQuery)({queryKey:l.detail(e),enabled:!!(t&&e),queryFn:async()=>{if(!t||!e)throw Error("Missing auth or teamId");return(0,s.teamInfoCall)(t,e)},initialData:()=>{if(!e)return;let t=o.getQueryData(l.list({}));return t?.find(t=>t.team_id===e)}})},"useTeams",0,()=>{let{accessToken:e,userId:t,userRole:a}=(0,i.default)();return(0,r.useQuery)({queryKey:l.list({}),queryFn:async()=>await (0,o.fetchTeams)(e,t,a,null),enabled:!!e})}])},980187,e=>{"use strict";e.s(["createTeamAliasMap",0,e=>e?e.reduce((e,t)=>(e[t.team_id]=t.team_alias,e),{}):{},"resolveTeamAliasFromTeamID",0,(e,t)=>{let r=t.find(t=>t.team_id===e);return r?r.team_alias:null}])},571303,e=>{"use strict";var t=e.i(843476),r=e.i(271645),a=e.i(115504);function i({className:e="",...i}){var o,n;let s=(0,r.useId)();return o=()=>{let e=document.getAnimations().filter(e=>e instanceof CSSAnimation&&"spin"===e.animationName),t=e.find(e=>e.effect.target?.getAttribute("data-spinner-id")===s),r=e.find(e=>e.effect instanceof KeyframeEffect&&e.effect.target?.getAttribute("data-spinner-id")!==s);t&&r&&(t.currentTime=r.currentTime)},n=[s],(0,r.useLayoutEffect)(o,n),(0,t.jsxs)("svg",{"data-spinner-id":s,className:(0,a.cx)("pointer-events-none size-12 animate-spin text-current",e),fill:"none",viewBox:"0 0 24 24",...i,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"})]})}e.s(["UiLoadingSpinner",()=>i],571303)},366283,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(95779),i=e.i(444755),o=e.i(673706);let n=(0,o.makeClassName)("Callout"),s=r.default.forwardRef((e,s)=>{let{title:l,icon:c,color:u,className:d,children:m}=e,g=(0,t.__rest)(e,["title","icon","color","className","children"]);return r.default.createElement("div",Object.assign({ref:s,className:(0,i.tremorTwMerge)(n("root"),"flex flex-col overflow-hidden rounded-tremor-default text-tremor-default border-l-4 py-3 pr-3 pl-4",u?(0,i.tremorTwMerge)((0,o.getColorClassNames)(u,a.colorPalette.background).bgColor,(0,o.getColorClassNames)(u,a.colorPalette.darkBorder).borderColor,(0,o.getColorClassNames)(u,a.colorPalette.darkText).textColor,"dark:bg-opacity-10 bg-opacity-10"):(0,i.tremorTwMerge)("bg-tremor-brand-faint border-tremor-brand-emphasis text-tremor-brand-emphasis","dark:bg-dark-tremor-brand-muted/70 dark:border-dark-tremor-brand-emphasis dark:text-dark-tremor-brand-emphasis"),d)},g),r.default.createElement("div",{className:(0,i.tremorTwMerge)(n("header"),"flex items-start")},c?r.default.createElement(c,{className:(0,i.tremorTwMerge)(n("icon"),"flex-none h-5 w-5 mr-1.5")}):null,r.default.createElement("h4",{className:(0,i.tremorTwMerge)(n("title"),"font-semibold")},l)),r.default.createElement("p",{className:(0,i.tremorTwMerge)(n("body"),"overflow-y-auto",m?"mt-2":"")},m))});s.displayName="Callout",e.s(["Callout",()=>s],366283)},418371,e=>{"use strict";var t=e.i(843476),r=e.i(271645),a=e.i(916925);e.s(["ProviderLogo",0,({provider:e,className:i="w-4 h-4"})=>{let[o,n]=(0,r.useState)(!1),{logo:s}=(0,a.getProviderLogoAndName)(e);return o||!s?(0,t.jsx)("div",{className:`${i} rounded-full bg-gray-200 flex items-center justify-center text-xs`,children:e?.charAt(0)||"-"}):(0,t.jsx)("img",{src:s,alt:`${e} logo`,className:i,onError:()=>n(!0)})}])},37091,e=>{"use strict";var t=e.i(290571),r=e.i(95779),a=e.i(444755),i=e.i(673706),o=e.i(271645);let n=o.default.forwardRef((e,n)=>{let{color:s,children:l,className:c}=e,u=(0,t.__rest)(e,["color","children","className"]);return o.default.createElement("p",Object.assign({ref:n,className:(0,a.tremorTwMerge)(s?(0,i.getColorClassNames)(s,r.colorPalette.lightText).textColor:"text-tremor-content-emphasis dark:text-dark-tremor-content-emphasis",c)},u),l)});n.displayName="Subtitle",e.s(["Subtitle",()=>n],37091)},214541,e=>{"use strict";var t=e.i(271645),r=e.i(135214),a=e.i(270345);e.s(["default",0,()=>{let[e,i]=(0,t.useState)([]),{accessToken:o,userId:n,userRole:s}=(0,r.default)();return(0,t.useEffect)(()=>{(async()=>{i(await (0,a.fetchTeams)(o,n,s,null))})()},[o,n,s]),{teams:e,setTeams:i}}])},439189,435684,96226,497245,e=>{"use strict";function t(e){let t=Object.prototype.toString.call(e);return e instanceof Date||"object"==typeof e&&"[object Date]"===t?new e.constructor(+e):new Date("number"==typeof e||"[object Number]"===t||"string"==typeof e||"[object String]"===t?e:NaN)}function r(e,t){return e instanceof Date?new e.constructor(t):new Date(t)}function a(e,a){let i=t(e);return isNaN(a)?r(e,NaN):(a&&i.setDate(i.getDate()+a),i)}function i(e,a){let i=t(e);if(isNaN(a))return r(e,NaN);if(!a)return i;let o=i.getDate(),n=r(e,i.getTime());return(n.setMonth(i.getMonth()+a+1,0),o>=n.getDate())?n:(i.setFullYear(n.getFullYear(),n.getMonth(),o),i)}e.s(["toDate",()=>t],435684),e.s(["constructFrom",()=>r],96226),e.s(["addDays",()=>a],439189),e.s(["addMonths",()=>i],497245)},891547,e=>{"use strict";var t=e.i(843476),r=e.i(271645),a=e.i(199133),i=e.i(764205);e.s(["default",0,({onChange:e,value:o,className:n,accessToken:s,disabled:l})=>{let[c,u]=(0,r.useState)([]),[d,m]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{(async()=>{if(s){m(!0);try{let e=await (0,i.getGuardrailsList)(s);console.log("Guardrails response:",e),e.guardrails&&(console.log("Guardrails data:",e.guardrails),u(e.guardrails))}catch(e){console.error("Error fetching guardrails:",e)}finally{m(!1)}}})()},[s]),(0,t.jsx)("div",{children:(0,t.jsx)(a.Select,{mode:"multiple",disabled:l,placeholder:l?"Setting guardrails is a premium feature.":"Select guardrails",onChange:t=>{console.log("Selected guardrails:",t),e(t)},value:o,loading:d,className:n,allowClear:!0,options:c.map(e=>(console.log("Mapping guardrail:",e),{label:`${e.guardrail_name}`,value:e.guardrail_name})),optionFilterProp:"label",showSearch:!0,style:{width:"100%"}})})}])},921511,e=>{"use strict";var t=e.i(843476),r=e.i(271645),a=e.i(199133),i=e.i(764205);function o(e){return e.filter(e=>(e.version_status??"draft")!=="draft").map(e=>{var t;let r=e.version_number??1,a=e.version_status??"draft";return{label:`${e.policy_name} — v${r} (${a})${e.description?` — ${e.description}`:""}`,value:"production"===a?e.policy_name:e.policy_id?(t=e.policy_id,`policy_${t}`):e.policy_name}})}e.s(["default",0,({onChange:e,value:n,className:s,accessToken:l,disabled:c,onPoliciesLoaded:u})=>{let[d,m]=(0,r.useState)([]),[g,p]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{(async()=>{if(l){p(!0);try{let e=await (0,i.getPoliciesList)(l);e.policies&&(m(e.policies),u?.(e.policies))}catch(e){console.error("Error fetching policies:",e)}finally{p(!1)}}})()},[l,u]),(0,t.jsx)("div",{children:(0,t.jsx)(a.Select,{mode:"multiple",disabled:c,placeholder:c?"Setting policies is a premium feature.":"Select policies (production or published versions)",onChange:t=>{e(t)},value:n,loading:g,className:s,allowClear:!0,options:o(d),optionFilterProp:"label",showSearch:!0,style:{width:"100%"}})})},"getPolicyOptionEntries",()=>o])},637235,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let 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 372z"}},{tag:"path",attrs:{d:"M686.7 638.6L544.1 535.5V288c0-4.4-3.6-8-8-8H488c-4.4 0-8 3.6-8 8v275.4c0 2.6 1.2 5 3.3 6.5l165.4 120.6c3.6 2.6 8.6 1.8 11.2-1.7l28.6-39c2.6-3.7 1.8-8.7-1.8-11.2z"}}]},name:"clock-circle",theme:"outlined"};var i=e.i(9583),o=r.forwardRef(function(e,o){return r.createElement(i.default,(0,t.default)({},e,{ref:o,icon:a}))});e.s(["ClockCircleOutlined",0,o],637235)},646563,e=>{"use strict";var t=e.i(959013);e.s(["PlusOutlined",()=>t.default])},447566,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M872 474H286.9l350.2-304c5.6-4.9 2.2-14-5.2-14h-88.5c-3.9 0-7.6 1.4-10.5 3.9L155 487.8a31.96 31.96 0 000 48.3L535.1 866c1.5 1.3 3.3 2 5.2 2h91.5c7.4 0 10.8-9.2 5.2-14L286.9 550H872c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8z"}}]},name:"arrow-left",theme:"outlined"};var i=e.i(9583),o=r.forwardRef(function(e,o){return r.createElement(i.default,(0,t.default)({},e,{ref:o,icon:a}))});e.s(["ArrowLeftOutlined",0,o],447566)},954616,e=>{"use strict";var t=e.i(271645),r=e.i(114272),a=e.i(540143),i=e.i(915823),o=e.i(619273),n=class extends i.Subscribable{#e;#t=void 0;#r;#a;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),(0,o.shallowEqualObjects)(this.options,t)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#r,observer:this}),t?.mutationKey&&this.options.mutationKey&&(0,o.hashKey)(t.mutationKey)!==(0,o.hashKey)(this.options.mutationKey)?this.reset():this.#r?.state.status==="pending"&&this.#r.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#r?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#o(e)}getCurrentResult(){return this.#t}reset(){this.#r?.removeObserver(this),this.#r=void 0,this.#i(),this.#o()}mutate(e,t){return this.#a=t,this.#r?.removeObserver(this),this.#r=this.#e.getMutationCache().build(this.#e,this.options),this.#r.addObserver(this),this.#r.execute(e)}#i(){let e=this.#r?.state??(0,r.getDefaultState)();this.#t={...e,isPending:"pending"===e.status,isSuccess:"success"===e.status,isError:"error"===e.status,isIdle:"idle"===e.status,mutate:this.mutate,reset:this.reset}}#o(e){a.notifyManager.batch(()=>{if(this.#a&&this.hasListeners()){let t=this.#t.variables,r=this.#t.context,a={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#a.onSuccess?.(e.data,t,r,a)}catch(e){Promise.reject(e)}try{this.#a.onSettled?.(e.data,null,t,r,a)}catch(e){Promise.reject(e)}}else if(e?.type==="error"){try{this.#a.onError?.(e.error,t,r,a)}catch(e){Promise.reject(e)}try{this.#a.onSettled?.(void 0,e.error,t,r,a)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},s=e.i(912598);function l(e,r){let i=(0,s.useQueryClient)(r),[l]=t.useState(()=>new n(i,e));t.useEffect(()=>{l.setOptions(e)},[l,e]);let c=t.useSyncExternalStore(t.useCallback(e=>l.subscribe(a.notifyManager.batchCalls(e)),[l]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),u=t.useCallback((e,t)=>{l.mutate(e,t).catch(o.noop)},[l]);if(c.error&&(0,o.shouldThrowError)(l.options.throwOnError,[c.error]))throw c.error;return{...c,mutate:u,mutateAsync:c.mutate}}e.s(["useMutation",()=>l],954616)},525720,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),a=e.i(529681),i=e.i(908286),o=e.i(242064),n=e.i(246422),s=e.i(838378);let l=["wrap","nowrap","wrap-reverse"],c=["flex-start","flex-end","start","end","center","space-between","space-around","space-evenly","stretch","normal","left","right"],u=["center","start","end","flex-start","flex-end","self-start","self-end","baseline","normal","stretch"],d=function(e,t){let a,i,o;return(0,r.default)(Object.assign(Object.assign(Object.assign({},(a=!0===t.wrap?"wrap":t.wrap,{[`${e}-wrap-${a}`]:a&&l.includes(a)})),(i={},u.forEach(r=>{i[`${e}-align-${r}`]=t.align===r}),i[`${e}-align-stretch`]=!t.align&&!!t.vertical,i)),(o={},c.forEach(r=>{o[`${e}-justify-${r}`]=t.justify===r}),o)))},m=(0,n.genStyleHooks)("Flex",e=>{let{paddingXS:t,padding:r,paddingLG:a}=e,i=(0,s.mergeToken)(e,{flexGapSM:t,flexGap:r,flexGapLG:a});return[(e=>{let{componentCls:t}=e;return{[t]:{display:"flex",margin:0,padding:0,"&-vertical":{flexDirection:"column"},"&-rtl":{direction:"rtl"},"&:empty":{display:"none"}}}})(i),(e=>{let{componentCls:t}=e;return{[t]:{"&-gap-small":{gap:e.flexGapSM},"&-gap-middle":{gap:e.flexGap},"&-gap-large":{gap:e.flexGapLG}}}})(i),(e=>{let{componentCls:t}=e,r={};return l.forEach(e=>{r[`${t}-wrap-${e}`]={flexWrap:e}}),r})(i),(e=>{let{componentCls:t}=e,r={};return u.forEach(e=>{r[`${t}-align-${e}`]={alignItems:e}}),r})(i),(e=>{let{componentCls:t}=e,r={};return c.forEach(e=>{r[`${t}-justify-${e}`]={justifyContent:e}}),r})(i)]},()=>({}),{resetStyle:!1});var g=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,a=Object.getOwnPropertySymbols(e);it.indexOf(a[i])&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(r[a[i]]=e[a[i]]);return r};let p=t.default.forwardRef((e,n)=>{let{prefixCls:s,rootClassName:l,className:c,style:u,flex:p,gap:f,vertical:h=!1,component:b="div",children:v}=e,A=g(e,["prefixCls","rootClassName","className","style","flex","gap","vertical","component","children"]),{flex:y,direction:O,getPrefixCls:x}=t.default.useContext(o.ConfigContext),C=x("flex",s),[I,E,$]=m(C),_=null!=h?h:null==y?void 0:y.vertical,T=(0,r.default)(c,l,null==y?void 0:y.className,C,E,$,d(C,e),{[`${C}-rtl`]:"rtl"===O,[`${C}-gap-${f}`]:(0,i.isPresetSize)(f),[`${C}-vertical`]:_}),w=Object.assign(Object.assign({},null==y?void 0:y.style),u);return p&&(w.flex=p),f&&!(0,i.isPresetSize)(f)&&(w.gap=f),I(t.default.createElement(b,Object.assign({ref:n,className:T,style:w},(0,a.default)(A,["justify","wrap","align"])),v))});e.s(["Flex",0,p],525720)},149121,e=>{"use strict";var t=e.i(843476),r=e.i(271645),a=e.i(152990),i=e.i(682830),o=e.i(269200),n=e.i(427612),s=e.i(64848),l=e.i(942232),c=e.i(496020),u=e.i(977572);function d({data:e=[],columns:d,onRowClick:m,renderSubComponent:g,renderChildRows:p,getRowCanExpand:f,isLoading:h=!1,loadingMessage:b="🚅 Loading logs...",noDataMessage:v="No logs found",enableSorting:A=!1}){let y=!!(g||p)&&!!f,[O,x]=(0,r.useState)([]),C=(0,a.useReactTable)({data:e,columns:d,...A&&{state:{sorting:O},onSortingChange:x,enableSortingRemoval:!1},...y&&{getRowCanExpand:f},getRowId:(e,t)=>e?.request_id??String(t),getCoreRowModel:(0,i.getCoreRowModel)(),...A&&{getSortedRowModel:(0,i.getSortedRowModel)()},...y&&{getExpandedRowModel:(0,i.getExpandedRowModel)()}});return(0,t.jsx)("div",{className:"rounded-lg custom-border overflow-x-auto w-full max-w-full box-border",children:(0,t.jsxs)(o.Table,{className:"[&_td]:py-0.5 [&_th]:py-1 table-fixed w-full box-border",style:{minWidth:"400px"},children:[(0,t.jsx)(n.TableHead,{children:C.getHeaderGroups().map(e=>(0,t.jsx)(c.TableRow,{children:e.headers.map(e=>{let r=A&&e.column.getCanSort(),i=e.column.getIsSorted();return(0,t.jsx)(s.TableHeaderCell,{className:`py-1 h-8 ${r?"cursor-pointer select-none hover:bg-gray-50":""}`,onClick:r?e.column.getToggleSortingHandler():void 0,children:e.isPlaceholder?null:(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,a.flexRender)(e.column.columnDef.header,e.getContext()),r&&(0,t.jsx)("span",{className:"text-gray-400",children:"asc"===i?"↑":"desc"===i?"↓":"⇅"})]})},e.id)})},e.id))}),(0,t.jsx)(l.TableBody,{children:h?(0,t.jsx)(c.TableRow,{children:(0,t.jsx)(u.TableCell,{colSpan:d.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:b})})})}):C.getRowModel().rows.length>0?C.getRowModel().rows.map(e=>(0,t.jsxs)(r.Fragment,{children:[(0,t.jsx)(c.TableRow,{className:`h-8 ${m?"cursor-pointer hover:bg-gray-50":""}`,onClick:()=>m?.(e.original),children:e.getVisibleCells().map(e=>(0,t.jsx)(u.TableCell,{className:"py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap",children:(0,a.flexRender)(e.column.columnDef.cell,e.getContext())},e.id))}),y&&e.getIsExpanded()&&p&&p({row:e}),y&&e.getIsExpanded()&&g&&!p&&(0,t.jsx)(c.TableRow,{children:(0,t.jsx)(u.TableCell,{colSpan:e.getVisibleCells().length,className:"p-0",children:(0,t.jsx)("div",{className:"w-full max-w-full overflow-hidden box-border",children:g({row:e})})})})]},e.id)):(0,t.jsx)(c.TableRow,{children:(0,t.jsx)(u.TableCell,{colSpan:d.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:v})})})})})]})})}e.s(["DataTable",()=>d])},986888,e=>{"use strict";var t=e.i(843476),r=e.i(797305),a=e.i(135214),i=e.i(214541);e.s(["default",0,()=>{let{accessToken:e,userRole:o,userId:n,premiumUser:s}=(0,a.default)(),{teams:l}=(0,i.default)();return(0,t.jsx)(r.default,{teams:l??[],organizations:[]})}])},601236,e=>{e.v(e=>Promise.resolve().then(()=>e(764205)))}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/12b229c40945c2e9.js b/litellm/proxy/_experimental/out/_next/static/chunks/12b229c40945c2e9.js deleted file mode 100644 index 29e7acf5eb1..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/12b229c40945c2e9.js +++ /dev/null @@ -1 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,772345,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M168 504.2c1-43.7 10-86.1 26.9-126 17.3-41 42.1-77.7 73.7-109.4S337 212.3 378 195c42.4-17.9 87.4-27 133.9-27s91.5 9.1 133.8 27A341.5 341.5 0 01755 268.8c9.9 9.9 19.2 20.4 27.8 31.4l-60.2 47a8 8 0 003 14.1l175.7 43c5 1.2 9.9-2.6 9.9-7.7l.8-180.9c0-6.7-7.7-10.5-12.9-6.3l-56.4 44.1C765.8 155.1 646.2 92 511.8 92 282.7 92 96.3 275.6 92 503.8a8 8 0 008 8.2h60c4.4 0 7.9-3.5 8-7.8zm756 7.8h-60c-4.4 0-7.9 3.5-8 7.8-1 43.7-10 86.1-26.9 126-17.3 41-42.1 77.8-73.7 109.4A342.45 342.45 0 01512.1 856a342.24 342.24 0 01-243.2-100.8c-9.9-9.9-19.2-20.4-27.8-31.4l60.2-47a8 8 0 00-3-14.1l-175.7-43c-5-1.2-9.9 2.6-9.9 7.7l-.7 181c0 6.7 7.7 10.5 12.9 6.3l56.4-44.1C258.2 868.9 377.8 932 512.2 932c229.2 0 415.5-183.7 419.8-411.8a8 8 0 00-8-8.2z"}}]},name:"sync",theme:"outlined"};var l=e.i(9583),r=a.forwardRef(function(e,r){return a.createElement(l.default,(0,t.default)({},e,{ref:r,icon:s}))});e.s(["SyncOutlined",0,r],772345)},11751,e=>{"use strict";function t(e){return""===e?null:e}e.s(["mapEmptyStringToNull",()=>t])},72713,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M880 184H712v-64c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v64H384v-64c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v64H144c-17.7 0-32 14.3-32 32v664c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V216c0-17.7-14.3-32-32-32zm-40 656H184V460h656v380zM184 392V256h128v48c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8v-48h256v48c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8v-48h128v136H184z"}}]},name:"calendar",theme:"outlined"};var l=e.i(9583),r=a.forwardRef(function(e,r){return a.createElement(l.default,(0,t.default)({},e,{ref:r,icon:s}))});e.s(["CalendarOutlined",0,r],72713)},962944,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M848 359.3H627.7L825.8 109c4.1-5.3.4-13-6.3-13H436c-2.8 0-5.5 1.5-6.9 4L170 547.5c-3.1 5.3.7 12 6.9 12h174.4l-89.4 357.6c-1.9 7.8 7.5 13.3 13.3 7.7L853.5 373c5.2-4.9 1.7-13.7-5.5-13.7zM378.2 732.5l60.3-241H281.1l189.6-327.4h224.6L487 427.4h211L378.2 732.5z"}}]},name:"thunderbolt",theme:"outlined"};var l=e.i(9583),r=a.forwardRef(function(e,r){return a.createElement(l.default,(0,t.default)({},e,{ref:r,icon:s}))});e.s(["ThunderboltOutlined",0,r],962944)},784647,304911,505022,721929,e=>{"use strict";var t=e.i(843476),a=e.i(464571),s=e.i(898586),l=e.i(592968),r=e.i(770914),i=e.i(312361),n=e.i(525720),o=e.i(447566),d=e.i(772345),c=e.i(955135),m=e.i(646563),u=e.i(771674),x=e.i(948401),p=e.i(72713),g=e.i(637235),h=e.i(962944);e.i(247167);var j=e.i(931067),_=e.i(271645);let y={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M866.9 169.9L527.1 54.1C523 52.7 517.5 52 512 52s-11 .7-15.1 2.1L157.1 169.9c-8.3 2.8-15.1 12.4-15.1 21.2v482.4c0 8.8 5.7 20.4 12.6 25.9L499.3 968c3.5 2.7 8 4.1 12.6 4.1s9.2-1.4 12.6-4.1l344.7-268.6c6.9-5.4 12.6-17 12.6-25.9V191.1c.2-8.8-6.6-18.3-14.9-21.2zM810 654.3L512 886.5 214 654.3V226.7l298-101.6 298 101.6v427.6zm-405.8-201c-3-4.1-7.8-6.6-13-6.6H336c-6.5 0-10.3 7.4-6.5 12.7l126.4 174a16.1 16.1 0 0026 0l212.6-292.7c3.8-5.3 0-12.7-6.5-12.7h-55.2c-5.1 0-10 2.5-13 6.6L468.9 542.4l-64.7-89.1z"}}]},name:"safety-certificate",theme:"outlined"};var b=e.i(9583),f=_.forwardRef(function(e,t){return _.createElement(b.default,(0,j.default)({},e,{ref:t,icon:y}))});let v={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M668.6 320c0-4.4-3.6-8-8-8h-54.5c-3 0-5.8 1.7-7.1 4.4l-84.7 168.8H511l-84.7-168.8a8 8 0 00-7.1-4.4h-55.7c-1.3 0-2.6.3-3.8 1-3.9 2.1-5.3 7-3.2 10.8l103.9 191.6h-57c-4.4 0-8 3.6-8 8v27.1c0 4.4 3.6 8 8 8h76v39h-76c-4.4 0-8 3.6-8 8v27.1c0 4.4 3.6 8 8 8h76V704c0 4.4 3.6 8 8 8h49.9c4.4 0 8-3.6 8-8v-63.5h76.3c4.4 0 8-3.6 8-8v-27.1c0-4.4-3.6-8-8-8h-76.3v-39h76.3c4.4 0 8-3.6 8-8v-27.1c0-4.4-3.6-8-8-8H564l103.7-191.6c.5-1.1.9-2.4.9-3.7zM157.9 504.2a352.7 352.7 0 01103.5-242.4c32.5-32.5 70.3-58.1 112.4-75.9 43.6-18.4 89.9-27.8 137.6-27.8 47.8 0 94.1 9.3 137.6 27.8 42.1 17.8 79.9 43.4 112.4 75.9 10 10 19.3 20.5 27.9 31.4l-50 39.1a8 8 0 003 14.1l156.8 38.3c5 1.2 9.9-2.6 9.9-7.7l.8-161.5c0-6.7-7.7-10.5-12.9-6.3l-47.8 37.4C770.7 146.3 648.6 82 511.5 82 277 82 86.3 270.1 82 503.8a8 8 0 008 8.2h60c4.3 0 7.8-3.5 7.9-7.8zM934 512h-60c-4.3 0-7.9 3.5-8 7.8a352.7 352.7 0 01-103.5 242.4 352.57 352.57 0 01-112.4 75.9c-43.6 18.4-89.9 27.8-137.6 27.8s-94.1-9.3-137.6-27.8a352.57 352.57 0 01-112.4-75.9c-10-10-19.3-20.5-27.9-31.4l49.9-39.1a8 8 0 00-3-14.1l-156.8-38.3c-5-1.2-9.9 2.6-9.9 7.7l-.8 161.7c0 6.7 7.7 10.5 12.9 6.3l47.8-37.4C253.3 877.7 375.4 942 512.5 942 747 942 937.7 753.9 942 520.2a8 8 0 00-8-8.2z"}}]},name:"transaction",theme:"outlined"};var N=_.forwardRef(function(e,t){return _.createElement(b.default,(0,j.default)({},e,{ref:t,icon:v}))}),k=e.i(262218);let{Text:T}=s.Typography;function w({userId:e}){return"default_user_id"===e?(0,t.jsx)(k.Tag,{color:"blue",children:"Default Proxy Admin"}):(0,t.jsx)(T,{children:e})}e.s(["default",()=>w],304911);let{Text:S}=s.Typography;function I({label:e,value:a,icon:s,truncate:l=!1,copyable:i=!1,defaultUserIdCheck:n=!1}){let o=!a,d=n&&"default_user_id"===a,c=d?(0,t.jsx)(w,{userId:a}):(0,t.jsx)(S,{strong:!0,copyable:!!(i&&!o&&!d)&&{tooltips:[`Copy ${e}`,"Copied!"]},ellipsis:l,style:l?{maxWidth:160,display:"block"}:void 0,children:o?"-":a});return(0,t.jsxs)("div",{children:[(0,t.jsxs)(r.Space,{size:4,children:[(0,t.jsx)(S,{type:"secondary",children:s}),(0,t.jsx)(S,{type:"secondary",style:{fontSize:12,textTransform:"uppercase",letterSpacing:"0.05em"},children:e})]}),(0,t.jsx)("div",{children:c})]})}let{Title:C,Text:A}=s.Typography;function F({data:e,onBack:s,onCreateNew:j,onRegenerate:_,onDelete:y,onResetSpend:b,canModifyKey:v=!0,backButtonText:k="Back to Keys",regenerateDisabled:T=!1,regenerateTooltip:w}){return(0,t.jsxs)("div",{children:[j&&(0,t.jsx)("div",{style:{marginBottom:16},children:(0,t.jsx)(a.Button,{type:"primary",icon:(0,t.jsx)(m.PlusOutlined,{}),onClick:j,children:"Create New Key"})}),(0,t.jsx)("div",{style:{marginBottom:16},children:(0,t.jsx)(a.Button,{type:"text",icon:(0,t.jsx)(o.ArrowLeftOutlined,{}),onClick:s,children:k})}),(0,t.jsxs)(n.Flex,{justify:"space-between",align:"start",style:{marginBottom:20},children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(C,{level:3,copyable:{tooltips:["Copy Key Alias","Copied!"]},style:{margin:0},children:e.keyName}),(0,t.jsxs)(A,{type:"secondary",copyable:{text:e.keyId,tooltips:["Copy Key ID","Copied!"]},children:["Key ID: ",e.keyId]})]}),v&&(0,t.jsxs)(r.Space,{children:[(0,t.jsx)(l.Tooltip,{title:w||"",children:(0,t.jsx)("span",{children:(0,t.jsx)(a.Button,{icon:(0,t.jsx)(d.SyncOutlined,{}),onClick:_,disabled:T,children:"Regenerate Key"})})}),b&&(0,t.jsx)(a.Button,{danger:!0,icon:(0,t.jsx)(N,{}),onClick:b,children:"Reset Spend"}),(0,t.jsx)(a.Button,{danger:!0,icon:(0,t.jsx)(c.DeleteOutlined,{}),onClick:y,children:"Delete Key"})]})]}),(0,t.jsxs)(n.Flex,{align:"stretch",gap:40,style:{marginBottom:40},children:[(0,t.jsxs)(r.Space,{direction:"vertical",size:16,children:[(0,t.jsx)(I,{label:"User Email",value:e.userEmail,icon:(0,t.jsx)(x.MailOutlined,{})}),(0,t.jsx)(I,{label:"User ID",value:e.userId,icon:(0,t.jsx)(u.UserOutlined,{}),truncate:!0,copyable:!0,defaultUserIdCheck:!0})]}),(0,t.jsx)(i.Divider,{type:"vertical",style:{height:"auto"}}),(0,t.jsxs)(r.Space,{direction:"vertical",size:16,children:[(0,t.jsx)(I,{label:"Created At",value:e.createdAt,icon:(0,t.jsx)(p.CalendarOutlined,{})}),(0,t.jsx)(I,{label:"Created By",value:e.createdBy,icon:(0,t.jsx)(f,{}),truncate:!0,copyable:!0,defaultUserIdCheck:!0})]}),(0,t.jsx)(i.Divider,{type:"vertical",style:{height:"auto"}}),(0,t.jsxs)(r.Space,{direction:"vertical",size:16,children:[(0,t.jsx)(I,{label:"Last Updated",value:e.lastUpdated,icon:(0,t.jsx)(g.ClockCircleOutlined,{})}),(0,t.jsx)(I,{label:"Last Active",value:e.lastActive,icon:(0,t.jsx)(h.ThunderboltOutlined,{})})]})]})]})}e.s(["KeyInfoHeader",()=>F],784647);var L=e.i(599724),M=e.i(389083),R=e.i(278587);let D=_.forwardRef(function(e,t){return _.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:t},e),_.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"}))});e.s(["default",0,({autoRotate:e=!1,rotationInterval:a,lastRotationAt:s,keyRotationAt:l,nextRotationAt:r,variant:i="card",className:n=""})=>{let o=e=>{let t=new Date(e),a=t.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"}),s=t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0});return`${a} at ${s}`},d=(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsx)("div",{className:"space-y-3",children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(R.RefreshIcon,{className:"h-4 w-4 text-blue-600"}),(0,t.jsx)(L.Text,{className:"font-semibold text-gray-900",children:"Auto-Rotation"}),(0,t.jsx)(M.Badge,{color:e?"green":"gray",size:"xs",children:e?"Enabled":"Disabled"}),e&&a&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(L.Text,{className:"text-gray-400",children:"•"}),(0,t.jsxs)(L.Text,{className:"text-sm text-gray-600",children:["Every ",a]})]})]})}),(e||s||l||r)&&(0,t.jsxs)("div",{className:"space-y-3",children:[s&&(0,t.jsxs)("div",{className:"flex items-center gap-2 p-3 bg-gray-50 border border-gray-200 rounded-md",children:[(0,t.jsx)(D,{className:"w-4 h-4 text-gray-500"}),(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsx)(L.Text,{className:"font-medium text-gray-700",children:"Last Rotation"}),(0,t.jsx)(L.Text,{className:"text-sm text-gray-600",children:o(s)})]})]}),(l||r)&&(0,t.jsxs)("div",{className:"flex items-center gap-2 p-3 bg-gray-50 border border-gray-200 rounded-md",children:[(0,t.jsx)(D,{className:"w-4 h-4 text-gray-500"}),(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsx)(L.Text,{className:"font-medium text-gray-700",children:"Next Scheduled Rotation"}),(0,t.jsx)(L.Text,{className:"text-sm text-gray-600",children:o(r||l||"")})]})]}),e&&!s&&!l&&!r&&(0,t.jsxs)("div",{className:"flex items-center gap-2 p-3 bg-gray-50 border border-gray-100 rounded-md",children:[(0,t.jsx)(D,{className:"w-4 h-4 text-gray-500"}),(0,t.jsx)(L.Text,{className:"text-gray-600",children:"No rotation history available"})]})]}),!e&&!s&&!l&&!r&&(0,t.jsxs)("div",{className:"flex items-center gap-2 p-3 bg-gray-50 border border-gray-100 rounded-md",children:[(0,t.jsx)(R.RefreshIcon,{className:"w-4 h-4 text-gray-400"}),(0,t.jsx)(L.Text,{className:"text-gray-600",children:"Auto-rotation is not enabled for this key"})]})]});return"card"===i?(0,t.jsxs)("div",{className:`bg-white border border-gray-200 rounded-lg p-6 ${n}`,children:[(0,t.jsx)("div",{className:"flex items-center gap-2 mb-6",children:(0,t.jsxs)("div",{children:[(0,t.jsx)(L.Text,{className:"font-semibold text-gray-900",children:"Auto-Rotation"}),(0,t.jsx)(L.Text,{className:"text-xs text-gray-500",children:"Automatic key rotation settings and status for this key"})]})}),d]}):(0,t.jsxs)("div",{className:`${n}`,children:[(0,t.jsx)(L.Text,{className:"font-medium text-gray-900 mb-3",children:"Auto-Rotation"}),d]})}],505022);let B=["logging"];e.s(["extractLoggingSettings",0,e=>e&&"object"==typeof e&&Array.isArray(e.logging)?e.logging:[],"formatMetadataForDisplay",0,(e,t=2)=>JSON.stringify(e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([e])=>!B.includes(e))):{},null,t),"stripTagsFromMetadata",0,e=>{if(!e||"object"!=typeof e)return e;let{tags:t,...a}=e;return a}],721929)},643449,e=>{"use strict";var t=e.i(843476),a=e.i(599724),s=e.i(389083),l=e.i(810757),r=e.i(477386),i=e.i(557662);e.s(["default",0,function({loggingConfigs:e=[],disabledCallbacks:n=[],variant:o="card",className:d=""}){let c=(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(l.CogIcon,{className:"h-4 w-4 text-blue-600"}),(0,t.jsx)(a.Text,{className:"font-semibold text-gray-900",children:"Logging Integrations"}),(0,t.jsx)(s.Badge,{color:"blue",size:"xs",children:e.length})]}),e.length>0?(0,t.jsx)("div",{className:"space-y-3",children:e.map((e,r)=>{var n;let o=(n=e.callback_name,Object.entries(i.callback_map).find(([e,t])=>t===n)?.[0]||n),d=i.callbackInfo[o]?.logo;return(0,t.jsxs)("div",{className:"flex items-center justify-between p-3 rounded-lg bg-blue-50 border border-blue-200",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[d?(0,t.jsx)("img",{src:d,alt:o,className:"w-5 h-5 object-contain"}):(0,t.jsx)(l.CogIcon,{className:"h-5 w-5 text-gray-400"}),(0,t.jsxs)("div",{children:[(0,t.jsx)(a.Text,{className:"font-medium text-blue-800",children:o}),(0,t.jsxs)(a.Text,{className:"text-xs text-blue-600",children:[Object.keys(e.callback_vars).length," parameters configured"]})]})]}),(0,t.jsx)(s.Badge,{color:(e=>{switch(e){case"success":return"green";case"failure":return"red";case"success_and_failure":return"blue";default:return"gray"}})(e.callback_type),size:"sm",children:(e=>{switch(e){case"success":return"Success Only";case"failure":return"Failure Only";case"success_and_failure":return"Success & Failure";default:return e}})(e.callback_type)})]},r)})}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 border border-gray-200",children:[(0,t.jsx)(l.CogIcon,{className:"h-4 w-4 text-gray-400"}),(0,t.jsx)(a.Text,{className:"text-gray-500 text-sm",children:"No logging integrations configured"})]})]}),(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(r.BanIcon,{className:"h-4 w-4 text-red-600"}),(0,t.jsx)(a.Text,{className:"font-semibold text-gray-900",children:"Disabled Callbacks"}),(0,t.jsx)(s.Badge,{color:"red",size:"xs",children:n.length})]}),n.length>0?(0,t.jsx)("div",{className:"space-y-3",children:n.map((e,l)=>{let n=i.reverse_callback_map[e]||e,o=i.callbackInfo[n]?.logo;return(0,t.jsxs)("div",{className:"flex items-center justify-between p-3 rounded-lg bg-red-50 border border-red-200",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[o?(0,t.jsx)("img",{src:o,alt:n,className:"w-5 h-5 object-contain"}):(0,t.jsx)(r.BanIcon,{className:"h-5 w-5 text-gray-400"}),(0,t.jsxs)("div",{children:[(0,t.jsx)(a.Text,{className:"font-medium text-red-800",children:n}),(0,t.jsx)(a.Text,{className:"text-xs text-red-600",children:"Disabled for this key"})]})]}),(0,t.jsx)(s.Badge,{color:"red",size:"sm",children:"Disabled"})]},l)})}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 border border-gray-200",children:[(0,t.jsx)(r.BanIcon,{className:"h-4 w-4 text-gray-400"}),(0,t.jsx)(a.Text,{className:"text-gray-500 text-sm",children:"No callbacks disabled"})]})]})]});return"card"===o?(0,t.jsxs)("div",{className:`bg-white border border-gray-200 rounded-lg p-6 ${d}`,children:[(0,t.jsx)("div",{className:"flex items-center gap-2 mb-6",children:(0,t.jsxs)("div",{children:[(0,t.jsx)(a.Text,{className:"font-semibold text-gray-900",children:"Logging Settings"}),(0,t.jsx)(a.Text,{className:"text-xs text-gray-500",children:"Active logging integrations and disabled callbacks for this key"})]})}),c]}):(0,t.jsxs)("div",{className:`${d}`,children:[(0,t.jsx)(a.Text,{className:"font-medium text-gray-900 mb-3",children:"Logging Settings"}),c]})}])},65932,690284,e=>{"use strict";var t=e.i(954616),a=e.i(912598),s=e.i(764205),l=e.i(135214),r=e.i(207082);let i=async(e,t)=>{let a=(0,s.getProxyBaseUrl)(),l=`${a?`${a}/key/${t}/reset_spend`:`/key/${t}/reset_spend`}`,r=await fetch(l,{method:"POST",headers:{[(0,s.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({reset_to:0})});if(!r.ok){let e=await r.json(),t=(0,s.deriveErrorMessage)(e);throw(0,s.handleError)(t),Error(t)}return r.json()};e.s(["useResetKeySpend",0,()=>{let{accessToken:e}=(0,l.default)(),s=(0,a.useQueryClient)();return(0,t.useMutation)({mutationFn:async t=>{if(!e)throw Error("Access token is required");return i(e,t)},onSuccess:()=>{s.invalidateQueries({queryKey:r.keyKeys.all})}})}],65932);var n=e.i(843476),o=e.i(994388),d=e.i(309426),c=e.i(350967),m=e.i(599724),u=e.i(779241),x=e.i(629569),p=e.i(808613),g=e.i(28651),h=e.i(212931),j=e.i(439189),_=e.i(497245),y=e.i(96226),b=e.i(435684);function f(e,t){let{years:a=0,months:s=0,weeks:l=0,days:r=0,hours:i=0,minutes:n=0,seconds:o=0}=t,d=(0,b.toDate)(e),c=s||a?(0,_.addMonths)(d,s+12*a):d,m=r||l?(0,j.addDays)(c,r+7*l):c;return(0,y.constructFrom)(e,m.getTime()+1e3*(o+60*(n+60*i)))}var v=e.i(271645),N=e.i(237016),k=e.i(727749);function T({selectedToken:e,visible:t,onClose:a,onKeyUpdate:r}){let{accessToken:i}=(0,l.default)(),[j]=p.Form.useForm(),[_,y]=(0,v.useState)(null),[b,T]=(0,v.useState)(null),[w,S]=(0,v.useState)(null),[I,C]=(0,v.useState)(!1),[A,F]=(0,v.useState)(!1),[L,M]=(0,v.useState)(null);(0,v.useEffect)(()=>{t&&e&&i&&(j.setFieldsValue({key_alias:e.key_alias,max_budget:e.max_budget,tpm_limit:e.tpm_limit,rpm_limit:e.rpm_limit,duration:e.duration||"",grace_period:""}),M(i),F(e.key_name===i))},[t,e,j,i]),(0,v.useEffect)(()=>{t||(y(null),C(!1),F(!1),M(null),j.resetFields())},[t,j]);let R=e=>{if(!e)return null;try{let t,a=new Date;if(e.endsWith("s"))t=f(a,{seconds:parseInt(e)});else if(e.endsWith("h"))t=f(a,{hours:parseInt(e)});else if(e.endsWith("d"))t=f(a,{days:parseInt(e)});else throw Error("Invalid duration format");return t.toLocaleString()}catch(e){return null}};(0,v.useEffect)(()=>{b?.duration?S(R(b.duration)):S(null)},[b?.duration]);let D=async()=>{if(e&&L){C(!0);try{let t=await j.validateFields(),a=await (0,s.regenerateKeyCall)(L,e.token||e.token_id,t);y(a.key),k.default.success("Virtual Key regenerated successfully"),console.log("Full regenerate response:",a);let l={token:a.token||a.key_id||e.token,key_name:a.key,max_budget:t.max_budget,tpm_limit:t.tpm_limit,rpm_limit:t.rpm_limit,expires:t.duration?R(t.duration):e.expires,...a};console.log("Updated key data with new token:",l),r&&r(l),C(!1)}catch(e){console.error("Error regenerating key:",e),k.default.fromBackend(e),C(!1)}}},B=()=>{y(null),C(!1),F(!1),M(null),j.resetFields(),a()};return(0,n.jsx)(h.Modal,{title:"Regenerate Virtual Key",open:t,onCancel:B,footer:_?[(0,n.jsx)(o.Button,{onClick:B,children:"Close"},"close")]:[(0,n.jsx)(o.Button,{onClick:B,className:"mr-2",children:"Cancel"},"cancel"),(0,n.jsx)(o.Button,{onClick:D,disabled:I,children:I?"Regenerating...":"Regenerate"},"regenerate")],children:_?(0,n.jsxs)(c.Grid,{numItems:1,className:"gap-2 w-full",children:[(0,n.jsx)(x.Title,{children:"Regenerated Key"}),(0,n.jsx)(d.Col,{numColSpan:1,children:(0,n.jsxs)("p",{children:["Please replace your old key with the new key generated. For security reasons,"," ",(0,n.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,n.jsxs)(d.Col,{numColSpan:1,children:[(0,n.jsx)(m.Text,{className:"mt-3",children:"Key Alias:"}),(0,n.jsx)("div",{className:"bg-gray-100 p-2 rounded mb-2",children:(0,n.jsx)("pre",{className:"break-words whitespace-normal",children:e?.key_alias||"No alias set"})}),(0,n.jsx)(m.Text,{className:"mt-3",children:"New Virtual Key:"}),(0,n.jsx)("div",{className:"bg-gray-100 p-2 rounded mb-2",children:(0,n.jsx)("pre",{className:"break-words whitespace-normal",children:_})}),(0,n.jsx)(N.CopyToClipboard,{text:_,onCopy:()=>k.default.success("Virtual Key copied to clipboard"),children:(0,n.jsx)(o.Button,{className:"mt-3",children:"Copy Virtual Key"})})]})]}):(0,n.jsxs)(p.Form,{form:j,layout:"vertical",onValuesChange:e=>{"duration"in e&&T(t=>({...t,duration:e.duration}))},children:[(0,n.jsx)(p.Form.Item,{name:"key_alias",label:"Key Alias",children:(0,n.jsx)(u.TextInput,{disabled:!0})}),(0,n.jsx)(p.Form.Item,{name:"max_budget",label:"Max Budget (USD)",children:(0,n.jsx)(g.InputNumber,{step:.01,precision:2,style:{width:"100%"}})}),(0,n.jsx)(p.Form.Item,{name:"tpm_limit",label:"TPM Limit",children:(0,n.jsx)(g.InputNumber,{style:{width:"100%"}})}),(0,n.jsx)(p.Form.Item,{name:"rpm_limit",label:"RPM Limit",children:(0,n.jsx)(g.InputNumber,{style:{width:"100%"}})}),(0,n.jsx)(p.Form.Item,{name:"duration",label:"Expire Key (eg: 30s, 30h, 30d)",className:"mt-8",children:(0,n.jsx)(u.TextInput,{placeholder:""})}),(0,n.jsxs)("div",{className:"mt-2 text-sm text-gray-500",children:["Current expiry: ",e?.expires?new Date(e.expires).toLocaleString():"Never"]}),w&&(0,n.jsxs)("div",{className:"mt-2 text-sm text-green-600",children:["New expiry: ",w]}),(0,n.jsx)(p.Form.Item,{name:"grace_period",label:"Grace Period (eg: 24h, 2d)",tooltip:"Keep the old key valid for this duration after rotation. Both keys work during this period for seamless cutover. Empty = immediate revoke.",className:"mt-8",rules:[{pattern:/^(\d+(s|m|h|d|w|mo))?$/,message:"Must be a duration like 30s, 30m, 24h, 2d, 1w, or 1mo"}],children:(0,n.jsx)(u.TextInput,{placeholder:"e.g. 24h, 2d (empty = immediate revoke)"})}),(0,n.jsx)("div",{className:"mt-2 text-sm text-gray-500",children:"Recommended: 24h to 72h for production keys to allow seamless client migration."})]})})}e.s(["RegenerateKeyModal",()=>T],690284)},183588,e=>{"use strict";var t=e.i(843476),a=e.i(266484);e.s(["default",0,({value:e,onChange:s,disabledCallbacks:l=[],onDisabledCallbacksChange:r})=>(0,t.jsx)(a.default,{value:e,onChange:s,disabledCallbacks:l,onDisabledCallbacksChange:r})])},20147,e=>{"use strict";var t=e.i(843476),a=e.i(135214),s=e.i(510674),l=e.i(292639),r=e.i(214541),i=e.i(500330),n=e.i(11751),o=e.i(530212),d=e.i(389083),c=e.i(994388),m=e.i(304967),u=e.i(350967),x=e.i(197647),p=e.i(653824),g=e.i(881073),h=e.i(404206),j=e.i(723731),_=e.i(599724),y=e.i(629569),b=e.i(808613),f=e.i(212931),v=e.i(262218),N=e.i(784647),k=e.i(271645),T=e.i(708347),w=e.i(557662),S=e.i(505022),I=e.i(127952),C=e.i(721929),A=e.i(643449),F=e.i(727749),L=e.i(764205),M=e.i(65932),R=e.i(384767),D=e.i(690284),B=e.i(190702),E=e.i(891547),P=e.i(921511),O=e.i(827252),K=e.i(779241),U=e.i(311451),V=e.i(199133),$=e.i(790848),z=e.i(592968),G=e.i(552130),W=e.i(9314),H=e.i(392110),q=e.i(844565),J=e.i(939510),Q=e.i(75921),Y=e.i(390605),X=e.i(702597),Z=e.i(435451),ee=e.i(183588),et=e.i(916940);function ea({keyData:e,onCancel:a,onSubmit:r,teams:i,accessToken:n,userID:o,userRole:d,premiumUser:m=!1}){let u=m||null!=d&&T.rolesWithWriteAccess.includes(d),[x]=b.Form.useForm(),[p,g]=(0,k.useState)([]),[h,j]=(0,k.useState)({}),_=i?.find(t=>t.team_id===e.team_id),[y,f]=(0,k.useState)([]),[v,N]=(0,k.useState)(Array.isArray(e.metadata?.litellm_disabled_callbacks)?(0,w.mapInternalToDisplayNames)(e.metadata.litellm_disabled_callbacks):[]),[S,I]=(0,k.useState)(e.auto_rotate||!1),[A,M]=(0,k.useState)(e.rotation_interval||""),[R,D]=(0,k.useState)(!e.expires),[B,ea]=(0,k.useState)(!1),{data:es}=(0,s.useProjects)(),{data:el}=(0,l.useUISettings)(),er=!!el?.values?.enable_projects_ui,ei=!!e.project_id,en=(()=>{if(!e.project_id)return null;let t=es?.find(t=>t.project_id===e.project_id);return t?.project_alias?`${t.project_alias} (${e.project_id})`:e.project_id})();(0,k.useEffect)(()=>{let t=async()=>{if(o&&d&&n)try{if(null===e.team_id){let e=(await (0,L.modelAvailableCall)(n,o,d)).data.map(e=>e.id);f(e)}else if(_?.team_id){let e=await (0,X.fetchTeamModels)(o,d,n,_.team_id);f(Array.from(new Set([..._.models,...e])))}}catch(e){console.error("Error fetching models:",e)}};(async()=>{if(n)try{let e=await (0,L.getPromptsList)(n);g(e.prompts.map(e=>e.prompt_id))}catch(e){console.error("Failed to fetch prompts:",e)}})(),t()},[o,d,n,_,e.team_id]),(0,k.useEffect)(()=>{x.setFieldValue("disabled_callbacks",v)},[x,v]);let eo=e=>e&&({"24h":"daily","7d":"weekly","30d":"monthly"})[e]||null,ed={...e,token:e.token||e.token_id,budget_duration:eo(e.budget_duration),metadata:(0,C.formatMetadataForDisplay)((0,C.stripTagsFromMetadata)(e.metadata)),guardrails:e.metadata?.guardrails,disable_global_guardrails:e.metadata?.disable_global_guardrails||!1,prompts:e.metadata?.prompts,tags:e.metadata?.tags,vector_stores:e.object_permission?.vector_stores||[],mcp_servers_and_groups:{servers:e.object_permission?.mcp_servers||[],accessGroups:e.object_permission?.mcp_access_groups||[]},mcp_tool_permissions:e.object_permission?.mcp_tool_permissions||{},agents_and_groups:{agents:e.object_permission?.agents||[],accessGroups:e.object_permission?.agent_access_groups||[]},logging_settings:(0,C.extractLoggingSettings)(e.metadata),disabled_callbacks:Array.isArray(e.metadata?.litellm_disabled_callbacks)?(0,w.mapInternalToDisplayNames)(e.metadata.litellm_disabled_callbacks):[],access_group_ids:e.access_group_ids||[],auto_rotate:e.auto_rotate||!1,...e.rotation_interval&&{rotation_interval:e.rotation_interval},allowed_routes:Array.isArray(e.allowed_routes)&&e.allowed_routes.length>0?e.allowed_routes.join(", "):""};(0,k.useEffect)(()=>{x.setFieldsValue({...e,token:e.token||e.token_id,budget_duration:eo(e.budget_duration),metadata:(0,C.formatMetadataForDisplay)((0,C.stripTagsFromMetadata)(e.metadata)),guardrails:e.metadata?.guardrails,disable_global_guardrails:e.metadata?.disable_global_guardrails||!1,prompts:e.metadata?.prompts,tags:e.metadata?.tags,vector_stores:e.object_permission?.vector_stores||[],mcp_servers_and_groups:{servers:e.object_permission?.mcp_servers||[],accessGroups:e.object_permission?.mcp_access_groups||[]},mcp_tool_permissions:e.object_permission?.mcp_tool_permissions||{},logging_settings:(0,C.extractLoggingSettings)(e.metadata),disabled_callbacks:Array.isArray(e.metadata?.litellm_disabled_callbacks)?(0,w.mapInternalToDisplayNames)(e.metadata.litellm_disabled_callbacks):[],access_group_ids:e.access_group_ids||[],auto_rotate:e.auto_rotate||!1,...e.rotation_interval&&{rotation_interval:e.rotation_interval},allowed_routes:Array.isArray(e.allowed_routes)&&e.allowed_routes.length>0?e.allowed_routes.join(", "):""})},[e,x]),(0,k.useEffect)(()=>{x.setFieldValue("auto_rotate",S)},[S,x]),(0,k.useEffect)(()=>{A&&x.setFieldValue("rotation_interval",A)},[A,x]),(0,k.useEffect)(()=>{(async()=>{if(n)try{let e=await (0,L.tagListCall)(n);j(e)}catch(e){F.default.fromBackend("Error fetching tags: "+e)}})()},[n]);let ec=async e=>{try{if(ea(!0),"string"==typeof e.allowed_routes){let t=e.allowed_routes.trim();""===t?e.allowed_routes=[]:e.allowed_routes=t.split(",").map(e=>e.trim()).filter(e=>e.length>0)}R&&(e.duration=null),await r(e)}finally{ea(!1)}};return(0,t.jsxs)(b.Form,{form:x,onFinish:ec,initialValues:ed,layout:"vertical",children:[(0,t.jsx)(b.Form.Item,{label:"Key Alias",name:"key_alias",children:(0,t.jsx)(K.TextInput,{})}),(0,t.jsx)(b.Form.Item,{label:"Models",name:"models",children:(0,t.jsx)(b.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.allowed_routes!==t.allowed_routes||e.models!==t.models,children:({getFieldValue:e,setFieldValue:a})=>{let s=e("allowed_routes")||"",l="string"==typeof s&&""!==s.trim()?s.split(",").map(e=>e.trim()).filter(e=>e.length>0):[],r=l.includes("management_routes")||l.includes("info_routes"),i=e("models")||[];return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(V.Select,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},disabled:r,value:r?[]:i,onChange:e=>a("models",e),children:[y.length>0&&(0,t.jsx)(V.Select.Option,{value:"all-team-models",children:"All Team Models"}),y.map(e=>(0,t.jsx)(V.Select.Option,{value:e,children:e},e))]}),r&&(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Models field is disabled for this key type"})]})}})}),(0,t.jsx)(b.Form.Item,{label:"Key Type",children:(0,t.jsx)(b.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.allowed_routes!==t.allowed_routes,children:({getFieldValue:e,setFieldValue:a})=>{var s;let l=e("allowed_routes")||"",r=(s="string"==typeof l&&""!==l.trim()?l.split(",").map(e=>e.trim()).filter(e=>e.length>0):[])&&0!==s.length?s.includes("llm_api_routes")?"llm_api":s.includes("management_routes")?"management":s.includes("info_routes")?"read_only":"default":"default";return(0,t.jsxs)(V.Select,{placeholder:"Select key type",style:{width:"100%"},optionLabelProp:"label",value:r,onChange:e=>{switch(e){case"default":a("allowed_routes","");break;case"llm_api":a("allowed_routes","llm_api_routes");break;case"management":a("allowed_routes","management_routes"),a("models",[])}},children:[(0,t.jsx)(V.Select.Option,{value:"default",label:"Default",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Default"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call AI APIs + Management routes"})]})}),(0,t.jsx)(V.Select.Option,{value:"llm_api",label:"AI APIs",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"AI APIs"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call only AI API routes (chat/completions, embeddings, etc.)"})]})}),(0,t.jsx)(V.Select.Option,{value:"management",label:"Management",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Management"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call only management routes (user/team/key management)"})]})})]})}})}),(0,t.jsx)(b.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Routes"," ",(0,t.jsx)(z.Tooltip,{title:"List of allowed routes for the key (comma-separated). Can be specific routes (e.g., '/chat/completions') or route patterns (e.g., 'llm_api_routes', 'management_routes', '/keys/*'). Leave empty to allow all routes.",children:(0,t.jsx)(O.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_routes",children:(0,t.jsx)(U.Input,{placeholder:"Enter allowed routes (comma-separated). Special values: llm_api_routes, management_routes. Examples: llm_api_routes, /chat/completions, /keys/*. Leave empty to allow all routes"})}),(0,t.jsx)(b.Form.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,t.jsx)(Z.default,{step:.01,style:{width:"100%"},placeholder:"Enter a numerical value"})}),(0,t.jsx)(b.Form.Item,{label:"Reset Budget",name:"budget_duration",children:(0,t.jsxs)(V.Select,{placeholder:"n/a",children:[(0,t.jsx)(V.Select.Option,{value:"daily",children:"Daily"}),(0,t.jsx)(V.Select.Option,{value:"weekly",children:"Weekly"}),(0,t.jsx)(V.Select.Option,{value:"monthly",children:"Monthly"})]})}),(0,t.jsx)(b.Form.Item,{label:"TPM Limit",name:"tpm_limit",children:(0,t.jsx)(Z.default,{min:0})}),(0,t.jsx)(J.default,{type:"tpm",name:"tpm_limit_type",showDetailedDescriptions:!1}),(0,t.jsx)(b.Form.Item,{label:"RPM Limit",name:"rpm_limit",children:(0,t.jsx)(Z.default,{min:0})}),(0,t.jsx)(J.default,{type:"rpm",name:"rpm_limit_type",showDetailedDescriptions:!1}),(0,t.jsx)(b.Form.Item,{label:"Max Parallel Requests",name:"max_parallel_requests",children:(0,t.jsx)(Z.default,{min:0})}),(0,t.jsx)(b.Form.Item,{label:"Model TPM Limit",name:"model_tpm_limit",children:(0,t.jsx)(U.Input.TextArea,{rows:4,placeholder:'{"gpt-4": 100, "claude-v1": 200}'})}),(0,t.jsx)(b.Form.Item,{label:"Model RPM Limit",name:"model_rpm_limit",children:(0,t.jsx)(U.Input.TextArea,{rows:4,placeholder:'{"gpt-4": 100, "claude-v1": 200}'})}),(0,t.jsx)(b.Form.Item,{label:"Guardrails",name:"guardrails",children:n&&(0,t.jsx)(E.default,{onChange:e=>{x.setFieldValue("guardrails",e)},accessToken:n,disabled:!u})}),(0,t.jsx)(b.Form.Item,{label:(0,t.jsxs)("span",{children:["Disable Global Guardrails"," ",(0,t.jsx)(z.Tooltip,{title:"When enabled, this key will bypass any guardrails configured to run on every request (global guardrails)",children:(0,t.jsx)(O.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"disable_global_guardrails",valuePropName:"checked",children:(0,t.jsx)($.Switch,{disabled:!u,checkedChildren:"Yes",unCheckedChildren:"No"})}),(0,t.jsx)(b.Form.Item,{label:(0,t.jsxs)("span",{children:["Policies"," ",(0,t.jsx)(z.Tooltip,{title:"Apply policies to this key to control guardrails and other settings",children:(0,t.jsx)(O.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"policies",children:n&&(0,t.jsx)(P.default,{onChange:e=>{x.setFieldValue("policies",e)},accessToken:n,disabled:!m})}),(0,t.jsx)(b.Form.Item,{label:"Tags",name:"tags",children:(0,t.jsx)(V.Select,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter tags",options:Object.values(h).map(e=>({value:e.name,label:e.name,title:e.description||e.name}))})}),(0,t.jsx)(b.Form.Item,{label:"Prompts",name:"prompts",children:(0,t.jsx)(z.Tooltip,{title:m?"":"Setting prompts by key is a premium feature",placement:"top",children:(0,t.jsx)(V.Select,{mode:"tags",style:{width:"100%"},disabled:!m,placeholder:m?Array.isArray(e.metadata?.prompts)&&e.metadata.prompts.length>0?`Current: ${e.metadata.prompts.join(", ")}`:"Select or enter prompts":"Premium feature - Upgrade to set prompts by key",options:p.map(e=>({value:e,label:e}))})})}),(0,t.jsx)(b.Form.Item,{label:(0,t.jsxs)("span",{children:["Access Groups"," ",(0,t.jsx)(z.Tooltip,{title:"Assign access groups to this key. Access groups control which models, MCP servers, and agents this key can use",children:(0,t.jsx)(O.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"access_group_ids",children:(0,t.jsx)(W.default,{placeholder:"Select access groups (optional)"})}),(0,t.jsx)(b.Form.Item,{label:"Allowed Pass Through Routes",name:"allowed_passthrough_routes",children:(0,t.jsx)(z.Tooltip,{title:m?"":"Setting allowed pass through routes by key is a premium feature",placement:"top",children:(0,t.jsx)(q.default,{onChange:e=>x.setFieldValue("allowed_passthrough_routes",e),value:x.getFieldValue("allowed_passthrough_routes"),accessToken:n||"",placeholder:m?Array.isArray(e.metadata?.allowed_passthrough_routes)&&e.metadata.allowed_passthrough_routes.length>0?`Current: ${e.metadata.allowed_passthrough_routes.join(", ")}`:"Select or enter allowed pass through routes":"Premium feature - Upgrade to set allowed pass through routes by key",disabled:!m})})}),(0,t.jsx)(b.Form.Item,{label:"Vector Stores",name:"vector_stores",children:(0,t.jsx)(et.default,{onChange:e=>x.setFieldValue("vector_stores",e),value:x.getFieldValue("vector_stores"),accessToken:n||"",placeholder:"Select vector stores"})}),(0,t.jsx)(b.Form.Item,{label:"MCP Servers / Access Groups",name:"mcp_servers_and_groups",children:(0,t.jsx)(Q.default,{onChange:e=>x.setFieldValue("mcp_servers_and_groups",e),value:x.getFieldValue("mcp_servers_and_groups"),accessToken:n||"",placeholder:"Select MCP servers or access groups (optional)"})}),(0,t.jsx)(b.Form.Item,{name:"mcp_tool_permissions",initialValue:{},hidden:!0,children:(0,t.jsx)(U.Input,{type:"hidden"})}),(0,t.jsx)(b.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.mcp_servers_and_groups!==t.mcp_servers_and_groups||e.mcp_tool_permissions!==t.mcp_tool_permissions,children:()=>(0,t.jsx)("div",{className:"mb-6",children:(0,t.jsx)(Y.default,{accessToken:n||"",selectedServers:x.getFieldValue("mcp_servers_and_groups")?.servers||[],toolPermissions:x.getFieldValue("mcp_tool_permissions")||{},onChange:e=>x.setFieldsValue({mcp_tool_permissions:e})})})}),(0,t.jsx)(b.Form.Item,{label:"Agents / Access Groups",name:"agents_and_groups",children:(0,t.jsx)(G.default,{onChange:e=>x.setFieldValue("agents_and_groups",e),value:x.getFieldValue("agents_and_groups"),accessToken:n||"",placeholder:"Select agents or access groups (optional)"})}),(0,t.jsx)(b.Form.Item,{label:"Team ID",name:"team_id",help:er&&ei?"Team is locked because this key belongs to a project":void 0,children:(0,t.jsx)(V.Select,{placeholder:"Select team",showSearch:!0,disabled:er&&ei,style:{width:"100%"},filterOption:(e,t)=>{let a=i?.find(e=>e.team_id===t?.value);return!!a&&(a.team_alias?.toLowerCase().includes(e.toLowerCase())??!1)},children:i?.map(e=>(0,t.jsx)(V.Select.Option,{value:e.team_id,children:`${e.team_alias} (${e.team_id})`},e.team_id))})}),er&&ei&&(0,t.jsx)(b.Form.Item,{label:"Project",children:(0,t.jsx)(U.Input,{value:en??"",disabled:!0})}),(0,t.jsx)(b.Form.Item,{label:"Logging Settings",name:"logging_settings",children:(0,t.jsx)(ee.default,{value:x.getFieldValue("logging_settings"),onChange:e=>x.setFieldValue("logging_settings",e),disabledCallbacks:v,onDisabledCallbacksChange:e=>{N((0,w.mapInternalToDisplayNames)(e)),x.setFieldValue("disabled_callbacks",e)}})}),(0,t.jsx)(b.Form.Item,{label:"Metadata",name:"metadata",children:(0,t.jsx)(U.Input.TextArea,{rows:10})}),(0,t.jsxs)("div",{className:"mb-4",children:[(0,t.jsx)(H.default,{form:x,autoRotationEnabled:S,onAutoRotationChange:I,rotationInterval:A,onRotationIntervalChange:M,neverExpire:R,onNeverExpireChange:D}),(0,t.jsx)(b.Form.Item,{name:"duration",hidden:!0,initialValue:"",children:(0,t.jsx)(U.Input,{})})]}),(0,t.jsx)(b.Form.Item,{name:"token",hidden:!0,children:(0,t.jsx)(U.Input,{})}),(0,t.jsx)(b.Form.Item,{name:"disabled_callbacks",hidden:!0,children:(0,t.jsx)(U.Input,{})}),(0,t.jsx)(b.Form.Item,{name:"auto_rotate",hidden:!0,children:(0,t.jsx)(U.Input,{})}),(0,t.jsx)(b.Form.Item,{name:"rotation_interval",hidden:!0,children:(0,t.jsx)(U.Input,{})}),(0,t.jsx)("div",{className:"sticky z-10 bg-white p-4 border-t border-gray-200 bottom-[-1.5rem] inset-x-[-1.5rem]",children:(0,t.jsxs)("div",{className:"flex justify-end items-center gap-2",children:[(0,t.jsx)(c.Button,{variant:"secondary",onClick:a,disabled:B,children:"Cancel"}),(0,t.jsx)(c.Button,{type:"submit",loading:B,children:"Save Changes"})]})})]})}function es({onClose:e,keyData:E,teams:P,onKeyDataUpdate:O,onDelete:K,backButtonText:U="Back to Keys"}){let V,{accessToken:$,userId:z,userRole:G,premiumUser:W}=(0,a.default)(),H=W||null!=G&&T.rolesWithWriteAccess.includes(G),{teams:q}=(0,r.default)(),{data:J}=(0,s.useProjects)(),{data:Q}=(0,l.useUISettings)(),Y=!!Q?.values?.enable_projects_ui,[X,Z]=(0,k.useState)(!1),[ee]=b.Form.useForm(),[et,es]=(0,k.useState)(!1),[el,er]=(0,k.useState)(!1),[ei,en]=(0,k.useState)(""),[eo,ed]=(0,k.useState)(!1),[ec,em]=(0,k.useState)(!1),{mutate:eu,isPending:ex}=(0,M.useResetKeySpend)(),[ep,eg]=(0,k.useState)(E),[eh,ej]=(0,k.useState)(null),[e_,ey]=(0,k.useState)(!1),[eb,ef]=(0,k.useState)({}),[ev,eN]=(0,k.useState)(!1);if((0,k.useEffect)(()=>{E&&eg(E)},[E]),(0,k.useEffect)(()=>{(async()=>{let e=ep?.metadata?.policies;if(!$||!e||!Array.isArray(e)||0===e.length)return;eN(!0);let t={};try{await Promise.all(e.map(async e=>{try{let a=await (0,L.getPolicyInfoWithGuardrails)($,e);t[e]=a.resolved_guardrails||[]}catch(a){console.error(`Failed to fetch guardrails for policy ${e}:`,a),t[e]=[]}})),ef(t)}catch(e){console.error("Failed to fetch policy guardrails:",e)}finally{eN(!1)}})()},[$,ep?.metadata?.policies]),(0,k.useEffect)(()=>{if(e_){let e=setTimeout(()=>{ey(!1)},5e3);return()=>clearTimeout(e)}},[e_]),!ep)return(0,t.jsxs)("div",{className:"p-4",children:[(0,t.jsx)(c.Button,{icon:o.ArrowLeftIcon,variant:"light",onClick:e,className:"mb-4",children:U}),(0,t.jsx)(_.Text,{children:"Key not found"})]});let ek=async e=>{try{if(!$)return;let t=e.token;if(e.key=t,H||(delete e.guardrails,delete e.prompts),e.max_budget=(0,n.mapEmptyStringToNull)(e.max_budget),void 0!==e.vector_stores&&(e.object_permission={...ep.object_permission,vector_stores:e.vector_stores||[]},delete e.vector_stores),void 0!==e.mcp_servers_and_groups){let{servers:t,accessGroups:a}=e.mcp_servers_and_groups||{servers:[],accessGroups:[]};e.object_permission={...ep.object_permission,mcp_servers:t||[],mcp_access_groups:a||[]},delete e.mcp_servers_and_groups}if(void 0!==e.mcp_tool_permissions){let t=e.mcp_tool_permissions||{};Object.keys(t).length>0&&(e.object_permission={...e.object_permission,mcp_tool_permissions:t}),delete e.mcp_tool_permissions}if(void 0!==e.agents_and_groups){let{agents:t,accessGroups:a}=e.agents_and_groups||{agents:[],accessGroups:[]};e.object_permission={...e.object_permission,agents:t||[],agent_access_groups:a||[]},delete e.agents_and_groups}if(e.max_budget=(0,n.mapEmptyStringToNull)(e.max_budget),e.tpm_limit=(0,n.mapEmptyStringToNull)(e.tpm_limit),e.rpm_limit=(0,n.mapEmptyStringToNull)(e.rpm_limit),e.max_parallel_requests=(0,n.mapEmptyStringToNull)(e.max_parallel_requests),e.metadata&&"string"==typeof e.metadata)try{let t=JSON.parse(e.metadata);"tags"in t&&delete t.tags,e.metadata={...t,...Array.isArray(e.tags)&&e.tags.length>0?{tags:e.tags}:{},...e.guardrails?.length>0?{guardrails:e.guardrails}:{},...Array.isArray(e.logging_settings)&&e.logging_settings.length>0?{logging:e.logging_settings}:{},...e.disabled_callbacks?.length>0?{litellm_disabled_callbacks:(0,w.mapDisplayToInternalNames)(e.disabled_callbacks)}:{}}}catch(e){console.error("Error parsing metadata JSON:",e),F.default.error("Invalid metadata JSON");return}else{let{tags:t,...a}=e.metadata||{};e.metadata={...a,...Array.isArray(e.tags)&&e.tags.length>0?{tags:e.tags}:{},...e.guardrails?.length>0?{guardrails:e.guardrails}:{},...Array.isArray(e.logging_settings)&&e.logging_settings.length>0?{logging:e.logging_settings}:{},...e.disabled_callbacks?.length>0?{litellm_disabled_callbacks:(0,w.mapDisplayToInternalNames)(e.disabled_callbacks)}:{}}}"tags"in e&&delete e.tags,delete e.logging_settings,e.budget_duration&&(e.budget_duration=({daily:"24h",weekly:"7d",monthly:"30d"})[e.budget_duration]);let a=await (0,L.keyUpdateCall)($,e);eg(e=>e?{...e,...a}:void 0),O&&O(a),F.default.success("Key updated successfully"),Z(!1)}catch(e){F.default.fromBackend((0,B.parseErrorMessage)(e)),console.error("Error updating key:",e)}},eT=async()=>{try{if(er(!0),!$)return;await (0,L.keyDeleteCall)($,ep.token||ep.token_id),F.default.success("Key deleted successfully"),K&&K(),e()}catch(e){console.error("Error deleting the key:",e),F.default.fromBackend(e)}finally{er(!1),es(!1),en("")}},ew=e=>{let t=new Date(e),a=t.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"}),s=t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0});return`${a} at ${s}`},eS=(0,T.isProxyAdminRole)(G||"")||q&&(0,T.isUserTeamAdminForSingleTeam)(q?.filter(e=>e.team_id===ep.team_id)[0]?.members_with_roles,z||"")||z===ep.user_id&&"Internal Viewer"!==G,eI=(0,T.isProxyAdminRole)(G||"")||q&&(0,T.isUserTeamAdminForSingleTeam)(q?.filter(e=>e.team_id===ep.team_id)[0]?.members_with_roles,z||"");return(0,t.jsxs)("div",{className:"w-full h-screen p-4",children:[(0,t.jsx)(N.KeyInfoHeader,{data:{keyName:ep.key_alias||"Virtual Key",keyId:ep.token_id||ep.token,userId:ep.user_id||"",userEmail:ep.user_email||"",createdBy:ep.user_email||ep.user_id||"",createdAt:ep.created_at?ew(ep.created_at):"",lastUpdated:ep.updated_at?ew(ep.updated_at):"",lastActive:ep.last_active?ew(ep.last_active):"Never"},onBack:e,onRegenerate:()=>ed(!0),onDelete:()=>es(!0),onResetSpend:eI?()=>em(!0):void 0,canModifyKey:eS,backButtonText:U,regenerateDisabled:!W,regenerateTooltip:W?void 0:"This is a LiteLLM Enterprise feature, and requires a valid key to use."}),(0,t.jsx)(D.RegenerateKeyModal,{selectedToken:ep,visible:eo,onClose:()=>ed(!1),onKeyUpdate:e=>{eg(t=>{if(t)return{...t,...e,created_at:new Date().toLocaleString()}}),ej(new Date),ey(!0),O&&O({...e,created_at:new Date().toLocaleString()})}}),(0,t.jsx)(I.default,{isOpen:et,title:"Delete Key",alertMessage:"This action is irreversible and will immediately revoke access for any applications using this key.",message:"Are you sure you want to delete this Virtual Key?",resourceInformationTitle:"Key Information",resourceInformation:[{label:"Key Alias",value:ep?.key_alias||"-"},{label:"Key ID",value:ep?.token_id||ep?.token||"-",code:!0},{label:"Team ID",value:ep?.team_id||"-",code:!0},{label:"Spend",value:ep?.spend?`$${(0,i.formatNumberWithCommas)(ep.spend,4)}`:"$0.0000"}],onCancel:()=>{es(!1),en("")},onOk:eT,confirmLoading:el,requiredConfirmation:ep?.key_alias}),(0,t.jsxs)(f.Modal,{title:"Reset Key Spend",open:ec,onOk:()=>{eu(ep.token||ep.token_id,{onSuccess:()=>{eg(e=>e?{...e,spend:0}:void 0),O&&O({spend:0}),F.default.success("Key spend reset to $0"),em(!1)},onError:e=>{F.default.fromBackend((0,B.parseErrorMessage)(e)),console.error("Error resetting key spend:",e)}})},onCancel:()=>em(!1),okText:"Reset",okButtonProps:{danger:!0},confirmLoading:ex,children:[(0,t.jsxs)("p",{children:["Reset spend for ",(0,t.jsx)("strong",{children:ep?.key_alias||ep?.token_id||"this key"})," to"," ",(0,t.jsx)("strong",{children:"$0"}),"?"]}),(0,t.jsxs)("p",{style:{color:"#666",fontSize:"0.875rem",marginTop:8},children:["Current spend: ",(0,t.jsxs)("strong",{children:["$",(0,i.formatNumberWithCommas)(ep.spend,4)]}),". Spend history is preserved in logs. This resets the current period spend counter, the same as an automatic budget reset."]})]}),(0,t.jsxs)(p.TabGroup,{children:[(0,t.jsxs)(g.TabList,{className:"mb-4",children:[(0,t.jsx)(x.Tab,{children:"Overview"}),(0,t.jsx)(x.Tab,{children:"Settings"})]}),(0,t.jsxs)(j.TabPanels,{children:[(0,t.jsx)(h.TabPanel,{children:(0,t.jsxs)(u.Grid,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,t.jsxs)(m.Card,{children:[(0,t.jsx)(_.Text,{children:"Spend"}),(0,t.jsxs)("div",{className:"mt-2",children:[(0,t.jsxs)(y.Title,{children:["$",(0,i.formatNumberWithCommas)(ep.spend,4)]}),(0,t.jsxs)(_.Text,{children:["of"," ",null!==ep.max_budget?`$${(0,i.formatNumberWithCommas)(ep.max_budget)}`:"Unlimited"]})]})]}),(0,t.jsxs)(m.Card,{children:[(0,t.jsx)(_.Text,{children:"Rate Limits"}),(0,t.jsxs)("div",{className:"mt-2",children:[(0,t.jsxs)(_.Text,{children:["TPM: ",null!==ep.tpm_limit?ep.tpm_limit:"Unlimited"]}),(0,t.jsxs)(_.Text,{children:["RPM: ",null!==ep.rpm_limit?ep.rpm_limit:"Unlimited"]})]})]}),(0,t.jsxs)(m.Card,{children:[(0,t.jsx)(_.Text,{children:"Models"}),(0,t.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:ep.models&&ep.models.length>0?ep.models.map((e,a)=>(0,t.jsx)(d.Badge,{color:"red",children:e},a)):(0,t.jsx)(_.Text,{children:"No models specified"})})]}),(0,t.jsx)(m.Card,{children:(0,t.jsx)(R.default,{objectPermission:ep.object_permission,variant:"inline",accessToken:$})}),(0,t.jsxs)(m.Card,{children:[(0,t.jsx)(_.Text,{className:"font-medium mb-3",children:"Guardrails"}),Array.isArray(ep.metadata?.guardrails)&&ep.metadata.guardrails.length>0?(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:ep.metadata.guardrails.map((e,a)=>(0,t.jsx)(d.Badge,{color:"blue",children:e},a))}):(0,t.jsx)(_.Text,{className:"text-gray-500",children:"No guardrails configured"}),"boolean"==typeof ep.metadata?.disable_global_guardrails&&!0===ep.metadata.disable_global_guardrails&&(0,t.jsx)("div",{className:"mt-3 pt-3 border-t border-gray-200",children:(0,t.jsx)(d.Badge,{color:"yellow",children:"Global Guardrails Disabled"})})]}),(0,t.jsxs)(m.Card,{children:[(0,t.jsx)(_.Text,{className:"font-medium mb-3",children:"Policies"}),Array.isArray(ep.metadata?.policies)&&ep.metadata.policies.length>0?(0,t.jsx)("div",{className:"space-y-4",children:ep.metadata.policies.map((e,a)=>(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(d.Badge,{color:"purple",children:e}),ev&&(0,t.jsx)(_.Text,{className:"text-xs text-gray-400",children:"Loading guardrails..."})]}),!ev&&eb[e]&&eb[e].length>0&&(0,t.jsxs)("div",{className:"ml-4 pl-3 border-l-2 border-gray-200",children:[(0,t.jsx)(_.Text,{className:"text-xs text-gray-500 mb-1",children:"Resolved Guardrails:"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:eb[e].map((e,a)=>(0,t.jsx)(d.Badge,{color:"blue",size:"xs",children:e},a))})]})]},a))}):(0,t.jsx)(_.Text,{className:"text-gray-500",children:"No policies configured"})]}),(0,t.jsx)(A.default,{loggingConfigs:(0,C.extractLoggingSettings)(ep.metadata),disabledCallbacks:Array.isArray(ep.metadata?.litellm_disabled_callbacks)?(0,w.mapInternalToDisplayNames)(ep.metadata.litellm_disabled_callbacks):[],variant:"card"}),(0,t.jsx)(S.default,{autoRotate:ep.auto_rotate,rotationInterval:ep.rotation_interval,lastRotationAt:ep.last_rotation_at,keyRotationAt:ep.key_rotation_at,nextRotationAt:ep.next_rotation_at,variant:"card"})]})}),(0,t.jsx)(h.TabPanel,{children:(0,t.jsxs)(m.Card,{className:"overflow-y-auto max-h-[65vh]",children:[(0,t.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,t.jsx)(y.Title,{children:"Key Settings"}),!X&&eS&&(0,t.jsx)(c.Button,{onClick:()=>Z(!0),children:"Edit Settings"})]}),X?(0,t.jsx)(ea,{keyData:ep,onCancel:()=>Z(!1),onSubmit:ek,teams:P,accessToken:$,userID:z,userRole:G,premiumUser:W}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Key ID"}),(0,t.jsx)(_.Text,{className:"font-mono",children:ep.token_id||ep.token})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Key Alias"}),(0,t.jsx)(_.Text,{children:ep.key_alias||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Secret Key"}),(0,t.jsx)(_.Text,{className:"font-mono",children:ep.key_name})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Team ID"}),(0,t.jsx)(_.Text,{children:ep.team_id||"Not Set"})]}),Y&&(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Project"}),(0,t.jsx)(_.Text,{children:ep.project_id?(V=J?.find(e=>e.project_id===ep.project_id),V?.project_alias?`${V.project_alias} (${ep.project_id})`:ep.project_id):"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Organization"}),(0,t.jsx)(_.Text,{children:(ep.organization_id??ep.org_id)||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Created"}),(0,t.jsx)(_.Text,{children:ew(ep.created_at)})]}),eh&&(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Last Regenerated"}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(_.Text,{children:ew(eh)}),(0,t.jsx)(d.Badge,{color:"green",size:"xs",children:"Recent"})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Expires"}),(0,t.jsx)(_.Text,{children:ep.expires?ew(ep.expires):"Never"})]}),(0,t.jsx)(S.default,{autoRotate:ep.auto_rotate,rotationInterval:ep.rotation_interval,lastRotationAt:ep.last_rotation_at,keyRotationAt:ep.key_rotation_at,nextRotationAt:ep.next_rotation_at,variant:"inline",className:"pt-4 border-t border-gray-200"}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Spend"}),(0,t.jsxs)(_.Text,{children:["$",(0,i.formatNumberWithCommas)(ep.spend,4)," USD"]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Budget"}),(0,t.jsx)(_.Text,{children:null!==ep.max_budget?`$${(0,i.formatNumberWithCommas)(ep.max_budget,2)}`:"Unlimited"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Tags"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:Array.isArray(ep.metadata?.tags)&&ep.metadata.tags.length>0?ep.metadata.tags.map((e,a)=>(0,t.jsx)("span",{className:"px-2 mr-2 py-1 bg-blue-100 rounded text-xs",children:e},a)):"No tags specified"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Prompts"}),(0,t.jsx)(_.Text,{children:Array.isArray(ep.metadata?.prompts)&&ep.metadata.prompts.length>0?ep.metadata.prompts.map((e,a)=>(0,t.jsx)("span",{className:"px-2 mr-2 py-1 bg-blue-100 rounded text-xs",children:e},a)):"No prompts specified"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Allowed Routes"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:Array.isArray(ep.allowed_routes)&&ep.allowed_routes.length>0?ep.allowed_routes.map((e,a)=>(0,t.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:e},a)):(0,t.jsx)(v.Tag,{color:"green",children:"All routes allowed"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Allowed Pass Through Routes"}),(0,t.jsx)(_.Text,{children:Array.isArray(ep.metadata?.allowed_passthrough_routes)&&ep.metadata.allowed_passthrough_routes.length>0?ep.metadata.allowed_passthrough_routes.map((e,a)=>(0,t.jsx)("span",{className:"px-2 mr-2 py-1 bg-blue-100 rounded text-xs",children:e},a)):"No pass through routes specified"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Disable Global Guardrails"}),(0,t.jsx)(_.Text,{children:ep.metadata?.disable_global_guardrails===!0?(0,t.jsx)(d.Badge,{color:"yellow",children:"Enabled - Global guardrails bypassed"}):(0,t.jsx)(d.Badge,{color:"green",children:"Disabled - Global guardrails active"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Models"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:ep.models&&ep.models.length>0?ep.models.map((e,a)=>(0,t.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:e},a)):(0,t.jsx)(_.Text,{children:"No models specified"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Rate Limits"}),(0,t.jsxs)(_.Text,{children:["TPM: ",null!==ep.tpm_limit?ep.tpm_limit:"Unlimited"]}),(0,t.jsxs)(_.Text,{children:["RPM: ",null!==ep.rpm_limit?ep.rpm_limit:"Unlimited"]}),(0,t.jsxs)(_.Text,{children:["Max Parallel Requests:"," ",null!==ep.max_parallel_requests?ep.max_parallel_requests:"Unlimited"]}),(0,t.jsxs)(_.Text,{children:["Model TPM Limits:"," ",ep.metadata?.model_tpm_limit?JSON.stringify(ep.metadata.model_tpm_limit):"Unlimited"]}),(0,t.jsxs)(_.Text,{children:["Model RPM Limits:"," ",ep.metadata?.model_rpm_limit?JSON.stringify(ep.metadata.model_rpm_limit):"Unlimited"]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Metadata"}),(0,t.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:(0,C.formatMetadataForDisplay)((0,C.stripTagsFromMetadata)(ep.metadata))})]}),(0,t.jsx)(R.default,{objectPermission:ep.object_permission,variant:"inline",className:"pt-4 border-t border-gray-200",accessToken:$}),(0,t.jsx)(A.default,{loggingConfigs:(0,C.extractLoggingSettings)(ep.metadata),disabledCallbacks:Array.isArray(ep.metadata?.litellm_disabled_callbacks)?(0,w.mapInternalToDisplayNames)(ep.metadata.litellm_disabled_callbacks):[],variant:"inline",className:"pt-4 border-t border-gray-200"})]})]})})]})]})]})}e.s(["default",()=>es],20147)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/16d77647b44247de.js b/litellm/proxy/_experimental/out/_next/static/chunks/16d77647b44247de.js new file mode 100644 index 00000000000..e1a9f60f2ba --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/16d77647b44247de.js @@ -0,0 +1,7 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,384767,e=>{"use strict";var t=e.i(843476),r=e.i(599724),a=e.i(271645),l=e.i(389083);let o=a.forwardRef(function(e,t){return a.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:t},e),a.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4m0 5c0 2.21-3.582 4-8 4s-8-1.79-8-4"}))});var n=e.i(764205);let s=function({vectorStores:e,accessToken:s}){let[i,c]=(0,a.useState)([]);return(0,a.useEffect)(()=>{(async()=>{if(s&&0!==e.length)try{let e=await (0,n.vectorStoreListCall)(s);e.data&&c(e.data.map(e=>({vector_store_id:e.vector_store_id,vector_store_name:e.vector_store_name})))}catch(e){console.error("Error fetching vector stores:",e)}})()},[s,e.length]),(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(o,{className:"h-4 w-4 text-blue-600"}),(0,t.jsx)(r.Text,{className:"font-semibold text-gray-900",children:"Vector Stores"}),(0,t.jsx)(l.Badge,{color:"blue",size:"xs",children:e.length})]}),e.length>0?(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:e.map((e,r)=>{let a;return(0,t.jsx)("div",{className:"inline-flex items-center px-3 py-1.5 rounded-lg bg-blue-50 border border-blue-200 text-blue-800 text-sm font-medium",children:(a=i.find(t=>t.vector_store_id===e))?`${a.vector_store_name||a.vector_store_id} (${a.vector_store_id})`:e},r)})}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 border border-gray-200",children:[(0,t.jsx)(o,{className:"h-4 w-4 text-gray-400"}),(0,t.jsx)(r.Text,{className:"text-gray-500 text-sm",children:"No vector stores configured"})]})]})},i=a.forwardRef(function(e,t){return a.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:t},e),a.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01"}))});var c=e.i(871943),d=e.i(502547),u=e.i(592968);let m=function({mcpServers:o,mcpAccessGroups:s=[],mcpToolPermissions:m={},accessToken:g}){let[p,f]=(0,a.useState)([]),[h,x]=(0,a.useState)([]),[b,y]=(0,a.useState)(new Set);(0,a.useEffect)(()=>{(async()=>{if(g&&o.length>0)try{let e=await (0,n.fetchMCPServers)(g);e&&Array.isArray(e)?f(e):e.data&&Array.isArray(e.data)&&f(e.data)}catch(e){console.error("Error fetching MCP servers:",e)}})()},[g,o.length]),(0,a.useEffect)(()=>{(async()=>{if(g&&s.length>0)try{let t=await e.A(601236).then(e=>e.fetchMCPAccessGroups(g));x(Array.isArray(t)?t:t.data||[])}catch(e){console.error("Error fetching MCP access groups:",e)}})()},[g,s.length]);let v=[...o.map(e=>({type:"server",value:e})),...s.map(e=>({type:"accessGroup",value:e}))],w=v.length;return(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(i,{className:"h-4 w-4 text-blue-600"}),(0,t.jsx)(r.Text,{className:"font-semibold text-gray-900",children:"MCP Servers"}),(0,t.jsx)(l.Badge,{color:"blue",size:"xs",children:w})]}),w>0?(0,t.jsx)("div",{className:"max-h-[400px] overflow-y-auto space-y-2 pr-1",children:v.map((e,r)=>{let a="server"===e.type?m[e.value]:void 0,l=a&&a.length>0,o=b.has(e.value);return(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{onClick:()=>{var t;return l&&(t=e.value,void y(e=>{let r=new Set(e);return r.has(t)?r.delete(t):r.add(t),r}))},className:`flex items-center gap-3 py-2 px-3 rounded-lg border border-gray-200 transition-all ${l?"cursor-pointer hover:bg-gray-50 hover:border-gray-300":"bg-white"}`,children:[(0,t.jsx)("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:"server"===e.type?(0,t.jsx)(u.Tooltip,{title:`Full ID: ${e.value}`,placement:"top",children:(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 min-w-0",children:[(0,t.jsx)("span",{className:"inline-block w-1.5 h-1.5 bg-blue-500 rounded-full flex-shrink-0"}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-900 truncate",children:(e=>{let t=p.find(t=>t.server_id===e);if(t){let r=e.length>7?`${e.slice(0,3)}...${e.slice(-4)}`:e;return`${t.alias} (${r})`}return e})(e.value)})]})}):(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 min-w-0",children:[(0,t.jsx)("span",{className:"inline-block w-1.5 h-1.5 bg-green-500 rounded-full flex-shrink-0"}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-900 truncate",children:e.value}),(0,t.jsx)("span",{className:"ml-1 px-1.5 py-0.5 text-[9px] font-semibold text-green-600 bg-green-50 border border-green-200 rounded uppercase tracking-wide flex-shrink-0",children:"Group"})]})}),l&&(0,t.jsxs)("div",{className:"flex items-center gap-1 flex-shrink-0 whitespace-nowrap",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-gray-600",children:a.length}),(0,t.jsx)("span",{className:"text-xs text-gray-500",children:1===a.length?"tool":"tools"}),o?(0,t.jsx)(c.ChevronDownIcon,{className:"h-3.5 w-3.5 text-gray-400 ml-0.5"}):(0,t.jsx)(d.ChevronRightIcon,{className:"h-3.5 w-3.5 text-gray-400 ml-0.5"})]})]}),l&&o&&(0,t.jsx)("div",{className:"ml-4 pl-4 border-l-2 border-blue-200 pb-1",children:(0,t.jsx)("div",{className:"flex flex-wrap gap-1.5",children:a.map((e,r)=>(0,t.jsx)("span",{className:"inline-flex items-center px-2.5 py-1 rounded-lg bg-blue-50 border border-blue-200 text-blue-800 text-xs font-medium",children:e},r))})})]},r)})}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 border border-gray-200",children:[(0,t.jsx)(i,{className:"h-4 w-4 text-gray-400"}),(0,t.jsx)(r.Text,{className:"text-gray-500 text-sm",children:"No MCP servers or access groups configured"})]})]})},g=a.forwardRef(function(e,t){return a.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:t},e),a.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"}))}),p=function({agents:e,agentAccessGroups:o=[],accessToken:s}){let[i,c]=(0,a.useState)([]);(0,a.useEffect)(()=>{(async()=>{if(s&&e.length>0)try{let e=await (0,n.getAgentsList)(s);e&&e.agents&&Array.isArray(e.agents)&&c(e.agents)}catch(e){console.error("Error fetching agents:",e)}})()},[s,e.length]);let d=[...e.map(e=>({type:"agent",value:e})),...o.map(e=>({type:"accessGroup",value:e}))],m=d.length;return(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(g,{className:"h-4 w-4 text-purple-600"}),(0,t.jsx)(r.Text,{className:"font-semibold text-gray-900",children:"Agents"}),(0,t.jsx)(l.Badge,{color:"purple",size:"xs",children:m})]}),m>0?(0,t.jsx)("div",{className:"max-h-[400px] overflow-y-auto space-y-2 pr-1",children:d.map((e,r)=>(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsx)("div",{className:"flex items-center gap-3 py-2 px-3 rounded-lg border border-gray-200 bg-white",children:(0,t.jsx)("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:"agent"===e.type?(0,t.jsx)(u.Tooltip,{title:`Full ID: ${e.value}`,placement:"top",children:(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 min-w-0",children:[(0,t.jsx)("span",{className:"inline-block w-1.5 h-1.5 bg-purple-500 rounded-full flex-shrink-0"}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-900 truncate",children:(e=>{let t=i.find(t=>t.agent_id===e);if(t){let r=e.length>7?`${e.slice(0,3)}...${e.slice(-4)}`:e;return`${t.agent_name} (${r})`}return e})(e.value)})]})}):(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 min-w-0",children:[(0,t.jsx)("span",{className:"inline-block w-1.5 h-1.5 bg-green-500 rounded-full flex-shrink-0"}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-900 truncate",children:e.value}),(0,t.jsx)("span",{className:"ml-1 px-1.5 py-0.5 text-[9px] font-semibold text-green-600 bg-green-50 border border-green-200 rounded uppercase tracking-wide flex-shrink-0",children:"Group"})]})})})},r))}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 border border-gray-200",children:[(0,t.jsx)(g,{className:"h-4 w-4 text-gray-400"}),(0,t.jsx)(r.Text,{className:"text-gray-500 text-sm",children:"No agents or access groups configured"})]})]})};e.s(["default",0,function({objectPermission:e,variant:a="card",className:l="",accessToken:o}){let n=e?.vector_stores||[],i=e?.mcp_servers||[],c=e?.mcp_access_groups||[],d=e?.mcp_tool_permissions||{},u=e?.agents||[],g=e?.agent_access_groups||[],f=(0,t.jsxs)("div",{className:"card"===a?"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6":"space-y-4",children:[(0,t.jsx)(s,{vectorStores:n,accessToken:o}),(0,t.jsx)(m,{mcpServers:i,mcpAccessGroups:c,mcpToolPermissions:d,accessToken:o}),(0,t.jsx)(p,{agents:u,agentAccessGroups:g,accessToken:o})]});return"card"===a?(0,t.jsxs)("div",{className:`bg-white border border-gray-200 rounded-lg p-6 ${l}`,children:[(0,t.jsx)("div",{className:"flex items-center gap-2 mb-6",children:(0,t.jsxs)("div",{children:[(0,t.jsx)(r.Text,{className:"font-semibold text-gray-900",children:"Object Permissions"}),(0,t.jsx)(r.Text,{className:"text-xs text-gray-500",children:"Access control for Vector Stores and MCP Servers"})]})}),f]}):(0,t.jsxs)("div",{className:`${l}`,children:[(0,t.jsx)(r.Text,{className:"font-medium text-gray-900 mb-3",children:"Object Permissions"}),f]})}],384767)},270345,e=>{"use strict";var t=e.i(764205);let r=async(e,r,a,l)=>"Admin"!=a&&"Admin Viewer"!=a?await (0,t.teamListCall)(e,l?.organization_id||null,r):await (0,t.teamListCall)(e,l?.organization_id||null);e.s(["fetchTeams",0,r])},519756,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={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"};var l=e.i(9583),o=r.forwardRef(function(e,o){return r.createElement(l.default,(0,t.default)({},e,{ref:o,icon:a}))});e.s(["UploadOutlined",0,o],519756)},981339,e=>{"use strict";var t=e.i(185793);e.s(["Skeleton",()=>t.default])},500330,e=>{"use strict";var t=e.i(727749);function r(e,t){let r=structuredClone(e);for(let[e,a]of Object.entries(t))e in r&&(r[e]=a);return r}let a=(e,t=0,r=!1,a=!0)=>{if(null==e||!Number.isFinite(e)||0===e&&!a)return"-";let l={minimumFractionDigits:t,maximumFractionDigits:t};if(!r)return e.toLocaleString("en-US",l);let o=e<0?"-":"",n=Math.abs(e),s=n,i="";return n>=1e6?(s=n/1e6,i="M"):n>=1e3&&(s=n/1e3,i="K"),`${o}${s.toLocaleString("en-US",l)}${i}`},l=async(e,r="Copied to clipboard")=>{if(!e)return!1;if(!navigator||!navigator.clipboard||!navigator.clipboard.writeText)return o(e,r);try{return await navigator.clipboard.writeText(e),t.default.success(r),!0}catch(t){return console.error("Clipboard API failed: ",t),o(e,r)}},o=(e,r)=>{try{let a=document.createElement("textarea");a.value=e,a.style.position="fixed",a.style.left="-999999px",a.style.top="-999999px",a.setAttribute("readonly",""),document.body.appendChild(a),a.focus(),a.select();let l=document.execCommand("copy");if(document.body.removeChild(a),l)return t.default.success(r),!0;throw Error("execCommand failed")}catch(e){return t.default.fromBackend("Failed to copy to clipboard"),console.error("Failed to copy: ",e),!1}};e.s(["copyToClipboard",0,l,"formatNumberWithCommas",0,a,"getSpendString",0,(e,t=6)=>{if(null==e||!Number.isFinite(e)||0===e)return"-";let r=a(e,t,!1,!1);if(0===Number(r.replace(/,/g,""))){let e=(1/10**t).toFixed(t);return`< $${e}`}return`$${r}`},"updateExistingKeys",()=>r])},109799,e=>{"use strict";var t=e.i(135214),r=e.i(764205),a=e.i(266027),l=e.i(912598);let o=(0,e.i(243652).createQueryKeys)("organizations");e.s(["useOrganization",0,e=>{let n=(0,l.useQueryClient)(),{accessToken:s}=(0,t.default)();return(0,a.useQuery)({queryKey:o.detail(e),enabled:!!(s&&e),queryFn:async()=>{if(!s||!e)throw Error("Missing auth or teamId");return(0,r.organizationInfoCall)(s,e)},initialData:()=>{if(!e)return;let t=n.getQueryData(o.list({}));return t?.find(t=>t.organization_id===e)}})},"useOrganizations",0,()=>{let{accessToken:e,userId:l,userRole:n}=(0,t.default)();return(0,a.useQuery)({queryKey:o.list({}),queryFn:async()=>await (0,r.organizationListCall)(e),enabled:!!(e&&l&&n)})}])},743151,(e,t,r)=>{"use strict";function a(e){return(a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}Object.defineProperty(r,"__esModule",{value:!0}),r.CopyToClipboard=void 0;var l=s(e.r(271645)),o=s(e.r(844343)),n=["text","onCopy","options","children"];function s(e){return e&&e.__esModule?e:{default:e}}function i(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,a)}return r}function c(e){for(var t=1;t=0||(l[r]=e[r]);return l}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(l[r]=e[r])}return l}(e,n),a=l.default.Children.only(t);return l.default.cloneElement(a,c(c({},r),{},{onClick:this.onClick}))}}],function(e,t){for(var r=0;r{"use strict";var a=e.r(743151).CopyToClipboard;a.CopyToClipboard=a,t.exports=a},244451,e=>{"use strict";let t;e.i(247167);var r=e.i(271645),a=e.i(343794),l=e.i(242064),o=e.i(763731),n=e.i(174428);let s=80*Math.PI,i=e=>{let{dotClassName:t,style:l,hasCircleCls:o}=e;return r.createElement("circle",{className:(0,a.default)(`${t}-circle`,{[`${t}-circle-bg`]:o}),r:40,cx:50,cy:50,strokeWidth:20,style:l})},c=({percent:e,prefixCls:t})=>{let l=`${t}-dot`,o=`${l}-holder`,c=`${o}-hidden`,[d,u]=r.useState(!1);(0,n.default)(()=>{0!==e&&u(!0)},[0!==e]);let m=Math.max(Math.min(e,100),0);if(!d)return null;let g={strokeDashoffset:`${s/4}`,strokeDasharray:`${s*m/100} ${s*(100-m)/100}`};return r.createElement("span",{className:(0,a.default)(o,`${l}-progress`,m<=0&&c)},r.createElement("svg",{viewBox:"0 0 100 100",role:"progressbar","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":m},r.createElement(i,{dotClassName:l,hasCircleCls:!0}),r.createElement(i,{dotClassName:l,style:g})))};function d(e){let{prefixCls:t,percent:l=0}=e,o=`${t}-dot`,n=`${o}-holder`,s=`${n}-hidden`;return r.createElement(r.Fragment,null,r.createElement("span",{className:(0,a.default)(n,l>0&&s)},r.createElement("span",{className:(0,a.default)(o,`${t}-dot-spin`)},[1,2,3,4].map(e=>r.createElement("i",{className:`${t}-dot-item`,key:e})))),r.createElement(c,{prefixCls:t,percent:l}))}function u(e){var t;let{prefixCls:l,indicator:n,percent:s}=e,i=`${l}-dot`;return n&&r.isValidElement(n)?(0,o.cloneElement)(n,{className:(0,a.default)(null==(t=n.props)?void 0:t.className,i),percent:s}):r.createElement(d,{prefixCls:l,percent:s})}e.i(296059);var m=e.i(694758),g=e.i(183293),p=e.i(246422),f=e.i(838378);let h=new m.Keyframes("antSpinMove",{to:{opacity:1}}),x=new m.Keyframes("antRotate",{to:{transform:"rotate(405deg)"}}),b=(0,p.genStyleHooks)("Spin",e=>(e=>{let{componentCls:t,calc:r}=e;return{[t]:Object.assign(Object.assign({},(0,g.resetComponent)(e)),{position:"absolute",display:"none",color:e.colorPrimary,fontSize:0,textAlign:"center",verticalAlign:"middle",opacity:0,transition:`transform ${e.motionDurationSlow} ${e.motionEaseInOutCirc}`,"&-spinning":{position:"relative",display:"inline-block",opacity:1},[`${t}-text`]:{fontSize:e.fontSize,paddingTop:r(r(e.dotSize).sub(e.fontSize)).div(2).add(2).equal()},"&-fullscreen":{position:"fixed",width:"100vw",height:"100vh",backgroundColor:e.colorBgMask,zIndex:e.zIndexPopupBase,inset:0,display:"flex",alignItems:"center",flexDirection:"column",justifyContent:"center",opacity:0,visibility:"hidden",transition:`all ${e.motionDurationMid}`,"&-show":{opacity:1,visibility:"visible"},[t]:{[`${t}-dot-holder`]:{color:e.colorWhite},[`${t}-text`]:{color:e.colorTextLightSolid}}},"&-nested-loading":{position:"relative",[`> div > ${t}`]:{position:"absolute",top:0,insetInlineStart:0,zIndex:4,display:"block",width:"100%",height:"100%",maxHeight:e.contentHeight,[`${t}-dot`]:{position:"absolute",top:"50%",insetInlineStart:"50%",margin:r(e.dotSize).mul(-1).div(2).equal()},[`${t}-text`]:{position:"absolute",top:"50%",width:"100%",textShadow:`0 1px 2px ${e.colorBgContainer}`},[`&${t}-show-text ${t}-dot`]:{marginTop:r(e.dotSize).div(2).mul(-1).sub(10).equal()},"&-sm":{[`${t}-dot`]:{margin:r(e.dotSizeSM).mul(-1).div(2).equal()},[`${t}-text`]:{paddingTop:r(r(e.dotSizeSM).sub(e.fontSize)).div(2).add(2).equal()},[`&${t}-show-text ${t}-dot`]:{marginTop:r(e.dotSizeSM).div(2).mul(-1).sub(10).equal()}},"&-lg":{[`${t}-dot`]:{margin:r(e.dotSizeLG).mul(-1).div(2).equal()},[`${t}-text`]:{paddingTop:r(r(e.dotSizeLG).sub(e.fontSize)).div(2).add(2).equal()},[`&${t}-show-text ${t}-dot`]:{marginTop:r(e.dotSizeLG).div(2).mul(-1).sub(10).equal()}}},[`${t}-container`]:{position:"relative",transition:`opacity ${e.motionDurationSlow}`,"&::after":{position:"absolute",top:0,insetInlineEnd:0,bottom:0,insetInlineStart:0,zIndex:10,width:"100%",height:"100%",background:e.colorBgContainer,opacity:0,transition:`all ${e.motionDurationSlow}`,content:'""',pointerEvents:"none"}},[`${t}-blur`]:{clear:"both",opacity:.5,userSelect:"none",pointerEvents:"none","&::after":{opacity:.4,pointerEvents:"auto"}}},"&-tip":{color:e.spinDotDefault},[`${t}-dot-holder`]:{width:"1em",height:"1em",fontSize:e.dotSize,display:"inline-block",transition:`transform ${e.motionDurationSlow} ease, opacity ${e.motionDurationSlow} ease`,transformOrigin:"50% 50%",lineHeight:1,color:e.colorPrimary,"&-hidden":{transform:"scale(0.3)",opacity:0}},[`${t}-dot-progress`]:{position:"absolute",inset:0},[`${t}-dot`]:{position:"relative",display:"inline-block",fontSize:e.dotSize,width:"1em",height:"1em","&-item":{position:"absolute",display:"block",width:r(e.dotSize).sub(r(e.marginXXS).div(2)).div(2).equal(),height:r(e.dotSize).sub(r(e.marginXXS).div(2)).div(2).equal(),background:"currentColor",borderRadius:"100%",transform:"scale(0.75)",transformOrigin:"50% 50%",opacity:.3,animationName:h,animationDuration:"1s",animationIterationCount:"infinite",animationTimingFunction:"linear",animationDirection:"alternate","&:nth-child(1)":{top:0,insetInlineStart:0,animationDelay:"0s"},"&:nth-child(2)":{top:0,insetInlineEnd:0,animationDelay:"0.4s"},"&:nth-child(3)":{insetInlineEnd:0,bottom:0,animationDelay:"0.8s"},"&:nth-child(4)":{bottom:0,insetInlineStart:0,animationDelay:"1.2s"}},"&-spin":{transform:"rotate(45deg)",animationName:x,animationDuration:"1.2s",animationIterationCount:"infinite",animationTimingFunction:"linear"},"&-circle":{strokeLinecap:"round",transition:["stroke-dashoffset","stroke-dasharray","stroke","stroke-width","opacity"].map(t=>`${t} ${e.motionDurationSlow} ease`).join(","),fillOpacity:0,stroke:"currentcolor"},"&-circle-bg":{stroke:e.colorFillSecondary}},[`&-sm ${t}-dot`]:{"&, &-holder":{fontSize:e.dotSizeSM}},[`&-sm ${t}-dot-holder`]:{i:{width:r(r(e.dotSizeSM).sub(r(e.marginXXS).div(2))).div(2).equal(),height:r(r(e.dotSizeSM).sub(r(e.marginXXS).div(2))).div(2).equal()}},[`&-lg ${t}-dot`]:{"&, &-holder":{fontSize:e.dotSizeLG}},[`&-lg ${t}-dot-holder`]:{i:{width:r(r(e.dotSizeLG).sub(e.marginXXS)).div(2).equal(),height:r(r(e.dotSizeLG).sub(e.marginXXS)).div(2).equal()}},[`&${t}-show-text ${t}-text`]:{display:"block"}})}})((0,f.mergeToken)(e,{spinDotDefault:e.colorTextDescription})),e=>{let{controlHeightLG:t,controlHeight:r}=e;return{contentHeight:400,dotSize:t/2,dotSizeSM:.35*t,dotSizeLG:r}}),y=[[30,.05],[70,.03],[96,.01]];var v=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var l=0,a=Object.getOwnPropertySymbols(e);lt.indexOf(a[l])&&Object.prototype.propertyIsEnumerable.call(e,a[l])&&(r[a[l]]=e[a[l]]);return r};let w=e=>{var o;let{prefixCls:n,spinning:s=!0,delay:i=0,className:c,rootClassName:d,size:m="default",tip:g,wrapperClassName:p,style:f,children:h,fullscreen:x=!1,indicator:w,percent:k}=e,C=v(e,["prefixCls","spinning","delay","className","rootClassName","size","tip","wrapperClassName","style","children","fullscreen","indicator","percent"]),{getPrefixCls:j,direction:N,className:S,style:$,indicator:M}=(0,l.useComponentConfig)("spin"),E=j("spin",n),[O,T,P]=b(E),[_,z]=r.useState(()=>s&&(!s||!i||!!Number.isNaN(Number(i)))),R=function(e,t){let[a,l]=r.useState(0),o=r.useRef(null),n="auto"===t;return r.useEffect(()=>(n&&e&&(l(0),o.current=setInterval(()=>{l(e=>{let t=100-e;for(let r=0;r{o.current&&(clearInterval(o.current),o.current=null)}),[n,e]),n?a:t}(_,k);r.useEffect(()=>{if(s){let e=function(e,t,r){var a,l=r||{},o=l.noTrailing,n=void 0!==o&&o,s=l.noLeading,i=void 0!==s&&s,c=l.debounceMode,d=void 0===c?void 0:c,u=!1,m=0;function g(){a&&clearTimeout(a)}function p(){for(var r=arguments.length,l=Array(r),o=0;oe?i?(m=Date.now(),n||(a=setTimeout(d?f:p,e))):p():!0!==n&&(a=setTimeout(d?f:p,void 0===d?e-c:e)))}return p.cancel=function(e){var t=(e||{}).upcomingOnly;g(),u=!(void 0!==t&&t)},p}(i,()=>{z(!0)},{debounceMode:false});return e(),()=>{var t;null==(t=null==e?void 0:e.cancel)||t.call(e)}}z(!1)},[i,s]);let I=r.useMemo(()=>void 0!==h&&!x,[h,x]),L=(0,a.default)(E,S,{[`${E}-sm`]:"small"===m,[`${E}-lg`]:"large"===m,[`${E}-spinning`]:_,[`${E}-show-text`]:!!g,[`${E}-rtl`]:"rtl"===N},c,!x&&d,T,P),D=(0,a.default)(`${E}-container`,{[`${E}-blur`]:_}),B=null!=(o=null!=w?w:M)?o:t,F=Object.assign(Object.assign({},$),f),A=r.createElement("div",Object.assign({},C,{style:F,className:L,"aria-live":"polite","aria-busy":_}),r.createElement(u,{prefixCls:E,indicator:B,percent:R}),g&&(I||x)?r.createElement("div",{className:`${E}-text`},g):null);return O(I?r.createElement("div",Object.assign({},C,{className:(0,a.default)(`${E}-nested-loading`,p,T,P)}),_&&r.createElement("div",{key:"loading"},A),r.createElement("div",{className:D,key:"container"},h)):x?r.createElement("div",{className:(0,a.default)(`${E}-fullscreen`,{[`${E}-fullscreen-show`]:_},d,T,P)},A):A)};w.setDefaultIndicator=e=>{t=e},e.s(["default",0,w],244451)},482725,e=>{"use strict";var t=e.i(244451);e.s(["Spin",()=>t.default])},350967,46757,e=>{"use strict";var t=e.i(290571),r=e.i(444755),a=e.i(673706),l=e.i(271645);let o={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"},n={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"},s={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"},d={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"},u={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"},m={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"};e.s(["colSpan",()=>c,"colSpanLg",()=>m,"colSpanMd",()=>u,"colSpanSm",()=>d,"gridCols",()=>o,"gridColsLg",()=>i,"gridColsMd",()=>s,"gridColsSm",()=>n],46757);let g=(0,a.makeClassName)("Grid"),p=(e,t)=>e&&Object.keys(t).includes(String(e))?t[e]:"",f=l.default.forwardRef((e,a)=>{let{numItems:c=1,numItemsSm:d,numItemsMd:u,numItemsLg:m,children:f,className:h}=e,x=(0,t.__rest)(e,["numItems","numItemsSm","numItemsMd","numItemsLg","children","className"]),b=p(c,o),y=p(d,n),v=p(u,s),w=p(m,i),k=(0,r.tremorTwMerge)(b,y,v,w);return l.default.createElement("div",Object.assign({ref:a,className:(0,r.tremorTwMerge)(g("root"),"grid",k,h)},x),f)});f.displayName="Grid",e.s(["Grid",()=>f],350967)},530212,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10 19l-7-7m0 0l7-7m-7 7h18"}))});e.s(["ArrowLeftIcon",0,r],530212)},309426,e=>{"use strict";var t=e.i(290571),r=e.i(444755),a=e.i(673706),l=e.i(271645),o=e.i(46757);let n=(0,a.makeClassName)("Col"),s=l.default.forwardRef((e,a)=>{let s,i,c,d,{numColSpan:u=1,numColSpanSm:m,numColSpanMd:g,numColSpanLg:p,children:f,className:h}=e,x=(0,t.__rest)(e,["numColSpan","numColSpanSm","numColSpanMd","numColSpanLg","children","className"]),b=(e,t)=>e&&Object.keys(t).includes(String(e))?t[e]:"";return l.default.createElement("div",Object.assign({ref:a,className:(0,r.tremorTwMerge)(n("root"),(s=b(u,o.colSpan),i=b(m,o.colSpanSm),c=b(g,o.colSpanMd),d=b(p,o.colSpanLg),(0,r.tremorTwMerge)(s,i,c,d)),h)},x),f)});s.displayName="Col",e.s(["Col",()=>s],309426)},653496,e=>{"use strict";var t=e.i(721369);e.s(["Tabs",()=>t.default])},599724,936325,e=>{"use strict";var t=e.i(95779),r=e.i(444755),a=e.i(673706),l=e.i(271645);let o=l.default.forwardRef((e,o)=>{let{color:n,className:s,children:i}=e;return l.default.createElement("p",{ref:o,className:(0,r.tremorTwMerge)("text-tremor-default",n?(0,a.getColorClassNames)(n,t.colorPalette.text).textColor:(0,r.tremorTwMerge)("text-tremor-content","dark:text-dark-tremor-content"),s)},i)});o.displayName="Text",e.s(["default",()=>o],936325),e.s(["Text",()=>o],599724)},994388,e=>{"use strict";var t=e.i(290571),r=e.i(829087),a=e.i(271645);let l=["preEnter","entering","entered","preExit","exiting","exited","unmounted"],o=e=>({_s:e,status:l[e],isEnter:e<3,isMounted:6!==e,isResolved:2===e||e>4}),n=e=>e?6:5,s=(e,t,r,a,l)=>{clearTimeout(a.current);let n=o(e);t(n),r.current=n,l&&l({current:n})};var i=e.i(480731),c=e.i(444755),d=e.i(673706);let u=e=>{var r=(0,t.__rest)(e,[]);return a.default.createElement("svg",Object.assign({},r,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"}),a.default.createElement("path",{fill:"none",d:"M0 0h24v24H0z"}),a.default.createElement("path",{d:"M18.364 5.636L16.95 7.05A7 7 0 1 0 19 12h2a9 9 0 1 1-2.636-6.364z"}))};var m=e.i(95779);let g={xs:{height:"h-4",width:"w-4"},sm:{height:"h-5",width:"w-5"},md:{height:"h-5",width:"w-5"},lg:{height:"h-6",width:"w-6"},xl:{height:"h-6",width:"w-6"}},p=(e,t)=>{switch(e){case"primary":return{textColor:t?(0,d.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",hoverTextColor:t?(0,d.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",bgColor:t?(0,d.getColorClassNames)(t,m.colorPalette.background).bgColor:"bg-tremor-brand dark:bg-dark-tremor-brand",hoverBgColor:t?(0,d.getColorClassNames)(t,m.colorPalette.darkBackground).hoverBgColor:"hover:bg-tremor-brand-emphasis dark:hover:bg-dark-tremor-brand-emphasis",borderColor:t?(0,d.getColorClassNames)(t,m.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",hoverBorderColor:t?(0,d.getColorClassNames)(t,m.colorPalette.darkBorder).hoverBorderColor:"hover:border-tremor-brand-emphasis dark:hover:border-dark-tremor-brand-emphasis"};case"secondary":return{textColor:t?(0,d.getColorClassNames)(t,m.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,d.getColorClassNames)(t,m.colorPalette.text).textColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,d.getColorClassNames)("transparent").bgColor,hoverBgColor:t?(0,c.tremorTwMerge)((0,d.getColorClassNames)(t,m.colorPalette.background).hoverBgColor,"hover:bg-opacity-20 dark:hover:bg-opacity-20"):"hover:bg-tremor-brand-faint dark:hover:bg-dark-tremor-brand-faint",borderColor:t?(0,d.getColorClassNames)(t,m.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand"};case"light":return{textColor:t?(0,d.getColorClassNames)(t,m.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,d.getColorClassNames)(t,m.colorPalette.darkText).hoverTextColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,d.getColorClassNames)("transparent").bgColor,borderColor:"",hoverBorderColor:""}}},f=(0,d.makeClassName)("Button"),h=({loading:e,iconSize:t,iconPosition:r,Icon:l,needMargin:o,transitionStatus:n})=>{let s=o?r===i.HorizontalPositions.Left?(0,c.tremorTwMerge)("-ml-1","mr-1.5"):(0,c.tremorTwMerge)("-mr-1","ml-1.5"):"",d=(0,c.tremorTwMerge)("w-0 h-0"),m={default:d,entering:d,entered:t,exiting:t,exited:d};return e?a.default.createElement(u,{className:(0,c.tremorTwMerge)(f("icon"),"animate-spin shrink-0",s,m.default,m[n]),style:{transition:"width 150ms"}}):a.default.createElement(l,{className:(0,c.tremorTwMerge)(f("icon"),"shrink-0",t,s)})},x=a.default.forwardRef((e,l)=>{let{icon:u,iconPosition:m=i.HorizontalPositions.Left,size:x=i.Sizes.SM,color:b,variant:y="primary",disabled:v,loading:w=!1,loadingText:k,children:C,tooltip:j,className:N}=e,S=(0,t.__rest)(e,["icon","iconPosition","size","color","variant","disabled","loading","loadingText","children","tooltip","className"]),$=w||v,M=void 0!==u||w,E=w&&k,O=!(!C&&!E),T=(0,c.tremorTwMerge)(g[x].height,g[x].width),P="light"!==y?(0,c.tremorTwMerge)("rounded-tremor-default border","shadow-tremor-input","dark:shadow-dark-tremor-input"):"",_=p(y,b),z=("light"!==y?{xs:{paddingX:"px-2.5",paddingY:"py-1.5",fontSize:"text-xs"},sm:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-sm"},md:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-md"},lg:{paddingX:"px-4",paddingY:"py-2.5",fontSize:"text-lg"},xl:{paddingX:"px-4",paddingY:"py-3",fontSize:"text-xl"}}:{xs:{paddingX:"",paddingY:"",fontSize:"text-xs"},sm:{paddingX:"",paddingY:"",fontSize:"text-sm"},md:{paddingX:"",paddingY:"",fontSize:"text-md"},lg:{paddingX:"",paddingY:"",fontSize:"text-lg"},xl:{paddingX:"",paddingY:"",fontSize:"text-xl"}})[x],{tooltipProps:R,getReferenceProps:I}=(0,r.useTooltip)(300),[L,D]=(({enter:e=!0,exit:t=!0,preEnter:r,preExit:l,timeout:i,initialEntered:c,mountOnEnter:d,unmountOnExit:u,onStateChange:m}={})=>{let[g,p]=(0,a.useState)(()=>o(c?2:n(d))),f=(0,a.useRef)(g),h=(0,a.useRef)(0),[x,b]="object"==typeof i?[i.enter,i.exit]:[i,i],y=(0,a.useCallback)(()=>{let e=((e,t)=>{switch(e){case 1:case 0:return 2;case 4:case 3:return n(t)}})(f.current._s,u);e&&s(e,p,f,h,m)},[m,u]);return[g,(0,a.useCallback)(a=>{let o=e=>{switch(s(e,p,f,h,m),e){case 1:x>=0&&(h.current=((...e)=>setTimeout(...e))(y,x));break;case 4:b>=0&&(h.current=((...e)=>setTimeout(...e))(y,b));break;case 0:case 3:h.current=((...e)=>setTimeout(...e))(()=>{isNaN(document.body.offsetTop)||o(e+1)},0)}},i=f.current.isEnter;"boolean"!=typeof a&&(a=!i),a?i||o(e?+!r:2):i&&o(t?l?3:4:n(u))},[y,m,e,t,r,l,x,b,u]),y]})({timeout:50});return(0,a.useEffect)(()=>{D(w)},[w]),a.default.createElement("button",Object.assign({ref:(0,d.mergeRefs)([l,R.refs.setReference]),className:(0,c.tremorTwMerge)(f("root"),"shrink-0 inline-flex justify-center items-center group font-medium outline-none",P,z.paddingX,z.paddingY,z.fontSize,_.textColor,_.bgColor,_.borderColor,_.hoverBorderColor,$?"opacity-50 cursor-not-allowed":(0,c.tremorTwMerge)(p(y,b).hoverTextColor,p(y,b).hoverBgColor,p(y,b).hoverBorderColor),N),disabled:$},I,S),a.default.createElement(r.default,Object.assign({text:j},R)),M&&m!==i.HorizontalPositions.Right?a.default.createElement(h,{loading:w,iconSize:T,iconPosition:m,Icon:u,transitionStatus:L.status,needMargin:O}):null,E||C?a.default.createElement("span",{className:(0,c.tremorTwMerge)(f("text"),"text-tremor-default whitespace-nowrap")},E?k:C):null,M&&m===i.HorizontalPositions.Right?a.default.createElement(h,{loading:w,iconSize:T,iconPosition:m,Icon:u,transitionStatus:L.status,needMargin:O}):null)});x.displayName="Button",e.s(["Button",()=>x],994388)},304967,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(480731),l=e.i(95779),o=e.i(444755),n=e.i(673706);let s=(0,n.makeClassName)("Card"),i=r.default.forwardRef((e,i)=>{let{decoration:c="",decorationColor:d,children:u,className:m}=e,g=(0,t.__rest)(e,["decoration","decorationColor","children","className"]);return r.default.createElement("div",Object.assign({ref:i,className:(0,o.tremorTwMerge)(s("root"),"relative w-full text-left ring-1 rounded-tremor-default p-6","bg-tremor-background ring-tremor-ring shadow-tremor-card","dark:bg-dark-tremor-background dark:ring-dark-tremor-ring dark:shadow-dark-tremor-card",d?(0,n.getColorClassNames)(d,l.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",(e=>{if(!e)return"";switch(e){case a.HorizontalPositions.Left:return"border-l-4";case a.VerticalPositions.Top:return"border-t-4";case a.HorizontalPositions.Right:return"border-r-4";case a.VerticalPositions.Bottom:return"border-b-4";default:return""}})(c),m)},g),u)});i.displayName="Card",e.s(["Card",()=>i],304967)},629569,e=>{"use strict";var t=e.i(290571),r=e.i(95779),a=e.i(444755),l=e.i(673706),o=e.i(271645);let n=o.default.forwardRef((e,n)=>{let{color:s,children:i,className:c}=e,d=(0,t.__rest)(e,["color","children","className"]);return o.default.createElement("p",Object.assign({ref:n,className:(0,a.tremorTwMerge)("font-medium text-tremor-title",s?(0,l.getColorClassNames)(s,r.colorPalette.darkText).textColor:"text-tremor-content-strong dark:text-dark-tremor-content-strong",c)},d),i)});n.displayName="Title",e.s(["Title",()=>n],629569)},91874,e=>{"use strict";var t=e.i(931067),r=e.i(209428),a=e.i(211577),l=e.i(392221),o=e.i(703923),n=e.i(343794),s=e.i(914949),i=e.i(271645),c=["prefixCls","className","style","checked","disabled","defaultChecked","type","title","onChange"],d=(0,i.forwardRef)(function(e,d){var u=e.prefixCls,m=void 0===u?"rc-checkbox":u,g=e.className,p=e.style,f=e.checked,h=e.disabled,x=e.defaultChecked,b=e.type,y=void 0===b?"checkbox":b,v=e.title,w=e.onChange,k=(0,o.default)(e,c),C=(0,i.useRef)(null),j=(0,i.useRef)(null),N=(0,s.default)(void 0!==x&&x,{value:f}),S=(0,l.default)(N,2),$=S[0],M=S[1];(0,i.useImperativeHandle)(d,function(){return{focus:function(e){var t;null==(t=C.current)||t.focus(e)},blur:function(){var e;null==(e=C.current)||e.blur()},input:C.current,nativeElement:j.current}});var E=(0,n.default)(m,g,(0,a.default)((0,a.default)({},"".concat(m,"-checked"),$),"".concat(m,"-disabled"),h));return i.createElement("span",{className:E,title:v,style:p,ref:j},i.createElement("input",(0,t.default)({},k,{className:"".concat(m,"-input"),ref:C,onChange:function(t){h||("checked"in e||M(t.target.checked),null==w||w({target:(0,r.default)((0,r.default)({},e),{},{type:y,checked:t.target.checked}),stopPropagation:function(){t.stopPropagation()},preventDefault:function(){t.preventDefault()},nativeEvent:t.nativeEvent}))},disabled:h,checked:!!$,type:y})),i.createElement("span",{className:"".concat(m,"-inner")}))});e.s(["default",0,d])},681216,e=>{"use strict";var t=e.i(271645),r=e.i(963188);function a(e){let a=t.default.useRef(null),l=()=>{r.default.cancel(a.current),a.current=null};return[()=>{l(),a.current=(0,r.default)(()=>{a.current=null})},t=>{a.current&&(t.stopPropagation(),l()),null==e||e(t)}]}e.s(["default",()=>a])},421512,236836,e=>{"use strict";let t=e.i(271645).default.createContext(null);e.s(["default",0,t],421512),e.i(296059);var r=e.i(915654),a=e.i(183293),l=e.i(246422),o=e.i(838378);function n(e,t){return(e=>{let{checkboxCls:t}=e,l=`${t}-wrapper`;return[{[`${t}-group`]:Object.assign(Object.assign({},(0,a.resetComponent)(e)),{display:"inline-flex",flexWrap:"wrap",columnGap:e.marginXS,[`> ${e.antCls}-row`]:{flex:1}}),[l]:Object.assign(Object.assign({},(0,a.resetComponent)(e)),{display:"inline-flex",alignItems:"baseline",cursor:"pointer","&:after":{display:"inline-block",width:0,overflow:"hidden",content:"'\\a0'"},[`& + ${l}`]:{marginInlineStart:0},[`&${l}-in-form-item`]:{'input[type="checkbox"]':{width:14,height:14}}}),[t]:Object.assign(Object.assign({},(0,a.resetComponent)(e)),{position:"relative",whiteSpace:"nowrap",lineHeight:1,cursor:"pointer",borderRadius:e.borderRadiusSM,alignSelf:"center",[`${t}-input`]:{position:"absolute",inset:0,zIndex:1,cursor:"pointer",opacity:0,margin:0,[`&:focus-visible + ${t}-inner`]:(0,a.genFocusOutline)(e)},[`${t}-inner`]:{boxSizing:"border-box",display:"block",width:e.checkboxSize,height:e.checkboxSize,direction:"ltr",backgroundColor:e.colorBgContainer,border:`${(0,r.unit)(e.lineWidth)} ${e.lineType} ${e.colorBorder}`,borderRadius:e.borderRadiusSM,borderCollapse:"separate",transition:`all ${e.motionDurationSlow}`,"&:after":{boxSizing:"border-box",position:"absolute",top:"50%",insetInlineStart:"25%",display:"table",width:e.calc(e.checkboxSize).div(14).mul(5).equal(),height:e.calc(e.checkboxSize).div(14).mul(8).equal(),border:`${(0,r.unit)(e.lineWidthBold)} solid ${e.colorWhite}`,borderTop:0,borderInlineStart:0,transform:"rotate(45deg) scale(0) translate(-50%,-50%)",opacity:0,content:'""',transition:`all ${e.motionDurationFast} ${e.motionEaseInBack}, opacity ${e.motionDurationFast}`}},"& + span":{paddingInlineStart:e.paddingXS,paddingInlineEnd:e.paddingXS}})},{[` + ${l}:not(${l}-disabled), + ${t}:not(${t}-disabled) + `]:{[`&:hover ${t}-inner`]:{borderColor:e.colorPrimary}},[`${l}:not(${l}-disabled)`]:{[`&:hover ${t}-checked:not(${t}-disabled) ${t}-inner`]:{backgroundColor:e.colorPrimaryHover,borderColor:"transparent"},[`&:hover ${t}-checked:not(${t}-disabled):after`]:{borderColor:e.colorPrimaryHover}}},{[`${t}-checked`]:{[`${t}-inner`]:{backgroundColor:e.colorPrimary,borderColor:e.colorPrimary,"&:after":{opacity:1,transform:"rotate(45deg) scale(1) translate(-50%,-50%)",transition:`all ${e.motionDurationMid} ${e.motionEaseOutBack} ${e.motionDurationFast}`}}},[` + ${l}-checked:not(${l}-disabled), + ${t}-checked:not(${t}-disabled) + `]:{[`&:hover ${t}-inner`]:{backgroundColor:e.colorPrimaryHover,borderColor:"transparent"}}},{[t]:{"&-indeterminate":{"&":{[`${t}-inner`]:{backgroundColor:`${e.colorBgContainer}`,borderColor:`${e.colorBorder}`,"&:after":{top:"50%",insetInlineStart:"50%",width:e.calc(e.fontSizeLG).div(2).equal(),height:e.calc(e.fontSizeLG).div(2).equal(),backgroundColor:e.colorPrimary,border:0,transform:"translate(-50%, -50%) scale(1)",opacity:1,content:'""'}},[`&:hover ${t}-inner`]:{backgroundColor:`${e.colorBgContainer}`,borderColor:`${e.colorPrimary}`}}}}},{[`${l}-disabled`]:{cursor:"not-allowed"},[`${t}-disabled`]:{[`&, ${t}-input`]:{cursor:"not-allowed",pointerEvents:"none"},[`${t}-inner`]:{background:e.colorBgContainerDisabled,borderColor:e.colorBorder,"&:after":{borderColor:e.colorTextDisabled}},"&:after":{display:"none"},"& + span":{color:e.colorTextDisabled},[`&${t}-indeterminate ${t}-inner::after`]:{background:e.colorTextDisabled}}}]})((0,o.mergeToken)(t,{checkboxCls:`.${e}`,checkboxSize:t.controlInteractiveSize}))}let s=(0,l.genStyleHooks)("Checkbox",(e,{prefixCls:t})=>[n(t,e)]);e.s(["default",0,s,"getStyle",()=>n],236836)},374276,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),a=e.i(91874),l=e.i(611935),o=e.i(121872),n=e.i(26905),s=e.i(242064),i=e.i(937328),c=e.i(321883),d=e.i(62139),u=e.i(421512),m=e.i(236836),g=e.i(681216),p=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var l=0,a=Object.getOwnPropertySymbols(e);lt.indexOf(a[l])&&Object.prototype.propertyIsEnumerable.call(e,a[l])&&(r[a[l]]=e[a[l]]);return r};let f=t.forwardRef((e,f)=>{var h;let{prefixCls:x,className:b,rootClassName:y,children:v,indeterminate:w=!1,style:k,onMouseEnter:C,onMouseLeave:j,skipGroup:N=!1,disabled:S}=e,$=p(e,["prefixCls","className","rootClassName","children","indeterminate","style","onMouseEnter","onMouseLeave","skipGroup","disabled"]),{getPrefixCls:M,direction:E,checkbox:O}=t.useContext(s.ConfigContext),T=t.useContext(u.default),{isFormItemInput:P}=t.useContext(d.FormItemInputContext),_=t.useContext(i.default),z=null!=(h=(null==T?void 0:T.disabled)||S)?h:_,R=t.useRef($.value),I=t.useRef(null),L=(0,l.composeRef)(f,I);t.useEffect(()=>{null==T||T.registerValue($.value)},[]),t.useEffect(()=>{if(!N)return $.value!==R.current&&(null==T||T.cancelValue(R.current),null==T||T.registerValue($.value),R.current=$.value),()=>null==T?void 0:T.cancelValue($.value)},[$.value]),t.useEffect(()=>{var e;(null==(e=I.current)?void 0:e.input)&&(I.current.input.indeterminate=w)},[w]);let D=M("checkbox",x),B=(0,c.default)(D),[F,A,q]=(0,m.default)(D,B),H=Object.assign({},$);T&&!N&&(H.onChange=(...e)=>{$.onChange&&$.onChange.apply($,e),T.toggleOption&&T.toggleOption({label:v,value:$.value})},H.name=T.name,H.checked=T.value.includes($.value));let G=(0,r.default)(`${D}-wrapper`,{[`${D}-rtl`]:"rtl"===E,[`${D}-wrapper-checked`]:H.checked,[`${D}-wrapper-disabled`]:z,[`${D}-wrapper-in-form-item`]:P},null==O?void 0:O.className,b,y,q,B,A),X=(0,r.default)({[`${D}-indeterminate`]:w},n.TARGET_CLS,A),[V,K]=(0,g.default)(H.onClick);return F(t.createElement(o.default,{component:"Checkbox",disabled:z},t.createElement("label",{className:G,style:Object.assign(Object.assign({},null==O?void 0:O.style),k),onMouseEnter:C,onMouseLeave:j,onClick:V},t.createElement(a.default,Object.assign({},H,{onClick:K,prefixCls:D,className:X,disabled:z,ref:L})),null!=v&&t.createElement("span",{className:`${D}-label`},v))))});var h=e.i(8211),x=e.i(529681),b=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var l=0,a=Object.getOwnPropertySymbols(e);lt.indexOf(a[l])&&Object.prototype.propertyIsEnumerable.call(e,a[l])&&(r[a[l]]=e[a[l]]);return r};let y=t.forwardRef((e,a)=>{let{defaultValue:l,children:o,options:n=[],prefixCls:i,className:d,rootClassName:g,style:p,onChange:y}=e,v=b(e,["defaultValue","children","options","prefixCls","className","rootClassName","style","onChange"]),{getPrefixCls:w,direction:k}=t.useContext(s.ConfigContext),[C,j]=t.useState(v.value||l||[]),[N,S]=t.useState([]);t.useEffect(()=>{"value"in v&&j(v.value||[])},[v.value]);let $=t.useMemo(()=>n.map(e=>"string"==typeof e||"number"==typeof e?{label:e,value:e}:e),[n]),M=e=>{S(t=>t.filter(t=>t!==e))},E=e=>{S(t=>[].concat((0,h.default)(t),[e]))},O=e=>{let t=C.indexOf(e.value),r=(0,h.default)(C);-1===t?r.push(e.value):r.splice(t,1),"value"in v||j(r),null==y||y(r.filter(e=>N.includes(e)).sort((e,t)=>$.findIndex(t=>t.value===e)-$.findIndex(e=>e.value===t)))},T=w("checkbox",i),P=`${T}-group`,_=(0,c.default)(T),[z,R,I]=(0,m.default)(T,_),L=(0,x.default)(v,["value","disabled"]),D=n.length?$.map(e=>t.createElement(f,{prefixCls:T,key:e.value.toString(),disabled:"disabled"in e?e.disabled:v.disabled,value:e.value,checked:C.includes(e.value),onChange:e.onChange,className:(0,r.default)(`${P}-item`,e.className),style:e.style,title:e.title,id:e.id,required:e.required},e.label)):o,B=t.useMemo(()=>({toggleOption:O,value:C,disabled:v.disabled,name:v.name,registerValue:E,cancelValue:M}),[O,C,v.disabled,v.name,E,M]),F=(0,r.default)(P,{[`${P}-rtl`]:"rtl"===k},d,g,I,_,R);return z(t.createElement("div",Object.assign({className:F,style:p},L,{ref:a}),t.createElement(u.default.Provider,{value:B},D)))});f.Group=y,f.__ANT_CHECKBOX=!0,e.s(["default",0,f],374276)},536916,e=>{"use strict";var t=e.i(374276);e.s(["Checkbox",()=>t.default])},292639,e=>{"use strict";var t=e.i(764205),r=e.i(266027);let a=(0,e.i(243652).createQueryKeys)("uiSettings");e.s(["useUISettings",0,()=>(0,r.useQuery)({queryKey:a.list({}),queryFn:async()=>await (0,t.getUiSettings)(),staleTime:36e5,gcTime:36e5})])},250980,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v3m0 0v3m0-3h3m-3 0H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z"}))});e.s(["PlusCircleIcon",0,r],250980)},502547,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"}))});e.s(["ChevronRightIcon",0,r],502547)},988297,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 4v16m8-8H4"}))});e.s(["PlusIcon",0,r],988297)},797672,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"}))});e.s(["PencilIcon",0,r],797672)},992619,e=>{"use strict";var t=e.i(843476),r=e.i(271645),a=e.i(779241),l=e.i(599724),o=e.i(199133),n=e.i(983561),s=e.i(689020);e.s(["default",0,({accessToken:e,value:i,placeholder:c="Select a Model",onChange:d,disabled:u=!1,style:m,className:g,showLabel:p=!0,labelText:f="Select Model"})=>{let[h,x]=(0,r.useState)(i),[b,y]=(0,r.useState)(!1),[v,w]=(0,r.useState)([]),k=(0,r.useRef)(null);return(0,r.useEffect)(()=>{x(i)},[i]),(0,r.useEffect)(()=>{e&&(async()=>{try{let t=await (0,s.fetchAvailableModels)(e);console.log("Fetched models for selector:",t),t.length>0&&w(t)}catch(e){console.error("Error fetching model info:",e)}})()},[e]),(0,t.jsxs)("div",{children:[p&&(0,t.jsxs)(l.Text,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,t.jsx)(n.RobotOutlined,{className:"mr-2"})," ",f]}),(0,t.jsx)(o.Select,{value:h,placeholder:c,onChange:e=>{"custom"===e?(y(!0),x(void 0)):(y(!1),x(e),d&&d(e))},options:[...Array.from(new Set(v.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%",...m},showSearch:!0,className:`rounded-md ${g||""}`,disabled:u}),b&&(0,t.jsx)(a.TextInput,{className:"mt-2",placeholder:"Enter custom model name",onValueChange:e=>{k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{x(e),d&&d(e)},500)},disabled:u})]})}])},409797,e=>{"use strict";var t=e.i(631171);e.s(["ChevronDownIcon",()=>t.default])},91739,e=>{"use strict";var t=e.i(544195);e.s(["Radio",()=>t.default])},500727,696609,531516,e=>{"use strict";var t=e.i(266027),r=e.i(243652),a=e.i(764205),l=e.i(135214);let o=(0,r.createQueryKeys)("mcpServers");e.s(["useMCPServers",0,e=>{let{accessToken:r}=(0,l.default)();return(0,t.useQuery)({queryKey:o.list(e?{filters:{teamId:e}}:void 0),queryFn:async()=>await (0,a.fetchMCPServers)(r,e),enabled:!!r})}],500727);var n=e.i(843476),s=e.i(271645),i=e.i(536916),c=e.i(599724),d=e.i(409797),u=e.i(246349),u=u;let m=/\b(delete|remove|destroy|purge|drop|erase|unlink)\b/i,g=/\b(create|add|insert|new|post|submit|register|make|generate|write|upload)\b/i,p=/\b(update|edit|modify|change|patch|put|set|rename|move|transform)\b/i,f=/\b(get|read|list|fetch|search|find|query|retrieve|show|view|check|describe|info)\b/i;function h(e,t=""){let r=e.toLowerCase();if(f.test(r))return"read";if(m.test(r))return"delete";if(p.test(r))return"update";if(g.test(r))return"create";if(t){let e=t.toLowerCase();if(f.test(e))return"read";if(m.test(e))return"delete";if(p.test(e))return"update";if(g.test(e))return"create"}return"unknown"}function x(e){let t={read:[],create:[],update:[],delete:[],unknown:[]};for(let r of e)t[h(r.name,r.description)].push(r);return t}let b={read:{label:"Read",description:"Safe operations — fetch, list, search. No side effects.",risk:"low"},create:{label:"Create",description:"Add new resources — insert, upload, register.",risk:"medium"},update:{label:"Update",description:"Modify existing resources — edit, patch, rename.",risk:"medium"},delete:{label:"Delete",description:"Destructive operations — remove, purge, destroy.",risk:"high"},unknown:{label:"Other",description:"Operations that could not be automatically classified.",risk:"unknown"}};e.s(["CRUD_GROUP_META",0,b,"classifyToolOp",()=>h,"groupToolsByCrud",()=>x],696609);let y=["read","create","update","delete","unknown"],v={low:"bg-green-100 text-green-800",medium:"bg-yellow-100 text-yellow-800",high:"bg-red-100 text-red-800 font-semibold",unknown:"bg-gray-100 text-gray-700"},w={read:"border-green-200",create:"border-blue-200",update:"border-yellow-200",delete:"border-red-300",unknown:"border-gray-200"},k={read:"bg-green-50",create:"bg-blue-50",update:"bg-yellow-50",delete:"bg-red-50",unknown:"bg-gray-50"};e.s(["default",0,({tools:e,value:t,onChange:r,readOnly:a=!1,searchFilter:l=""})=>{let[o,m]=(0,s.useState)({read:!1,create:!1,update:!1,delete:!1,unknown:!0}),g=(0,s.useMemo)(()=>x(e),[e]),p=(0,s.useMemo)(()=>new Set(void 0===t?e.map(e=>e.name):t),[t,e]),f=e=>{if(a)return;let t=new Set(p);t.has(e)?t.delete(e):t.add(e),r(Array.from(t))};return 0===e.length?null:(0,n.jsx)("div",{className:"space-y-3",children:y.map(e=>{let t,s=g[e];if(0===s.length)return null;if(l){let e=l.toLowerCase();if(!s.some(t=>t.name.toLowerCase().includes(e)||(t.description??"").toLowerCase().includes(e)))return null}let h=b[e],x=(t=g[e]).length>0&&t.every(e=>p.has(e.name)),y=(e=>{let t=g[e];if(0===t.length)return!1;let r=t.filter(e=>p.has(e.name)).length;return r>0&&r{m(t=>({...t,[e]:!t[e]}))},children:[C?(0,n.jsx)(u.default,{className:"w-4 h-4 text-gray-500 flex-shrink-0"}):(0,n.jsx)(d.ChevronDownIcon,{className:"w-4 h-4 text-gray-500 flex-shrink-0"}),(0,n.jsx)("span",{className:"font-semibold text-gray-900 text-sm",children:h.label}),(0,n.jsx)("span",{className:`text-xs px-2 py-0.5 rounded-full ${v[h.risk]}`,children:"high"===h.risk?"High Risk":"medium"===h.risk?"Medium Risk":"low"===h.risk?"Safe":"Unclassified"}),(0,n.jsxs)("span",{className:"text-xs text-gray-500 ml-1",children:[s.filter(e=>p.has(e.name)).length,"/",s.length," allowed"]})]}),!a&&(0,n.jsxs)("div",{className:"flex items-center gap-2 ml-4",children:[(0,n.jsx)(c.Text,{className:"text-xs text-gray-500",children:x?"All on":y?"Partial":"All off"}),(0,n.jsx)(i.Checkbox,{checked:x,indeterminate:y,onChange:t=>((e,t)=>{if(a)return;let l=new Set(p);for(let r of g[e])t?l.add(r.name):l.delete(r.name);r(Array.from(l))})(e,t.target.checked),onClick:e=>e.stopPropagation()})]})]}),!C&&(0,n.jsx)("div",{className:"px-4 pt-2 pb-1 text-xs text-gray-500 bg-white border-b border-gray-100",children:h.description}),!C&&(0,n.jsx)("div",{className:"bg-white divide-y divide-gray-50",children:s.filter(e=>!l||e.name.toLowerCase().includes(l.toLowerCase())||(e.description??"").toLowerCase().includes(l.toLowerCase())).map(e=>{let t,r=(t=e.name,p.has(t));return(0,n.jsxs)("div",{className:`flex items-start gap-3 px-4 py-2.5 transition-colors hover:bg-gray-50 ${!a?"cursor-pointer":""} ${r?"":"opacity-60"}`,onClick:()=>f(e.name),children:[(0,n.jsx)(i.Checkbox,{checked:r,onChange:()=>f(e.name),disabled:a,onClick:e=>e.stopPropagation()}),(0,n.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,n.jsx)(c.Text,{className:"font-medium text-gray-900 text-sm",children:e.name}),e.description&&(0,n.jsx)(c.Text,{className:"text-xs text-gray-500 mt-0.5 leading-snug",children:e.description})]}),(0,n.jsx)("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${r?"bg-green-100 text-green-700":"bg-gray-100 text-gray-500"}`,children:r?"on":"off"})]},e.name)})})]},e)})})}],531516)},361653,e=>{"use strict";let t=(0,e.i(475254).default)("circle-alert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);e.s(["default",()=>t])},603908,e=>{"use strict";let t=(0,e.i(475254).default)("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);e.s(["default",()=>t])},841947,e=>{"use strict";let t=(0,e.i(475254).default)("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);e.s(["default",()=>t])},793130,e=>{"use strict";var t=e.i(290571),r=e.i(429427),a=e.i(371330),l=e.i(271645),o=e.i(394487),n=e.i(503269),s=e.i(214520),i=e.i(746725),c=e.i(914189),d=e.i(144279),u=e.i(294316),m=e.i(601893),g=e.i(140721),p=e.i(942803),f=e.i(233538),h=e.i(694421),x=e.i(700020),b=e.i(35889),y=e.i(998348),v=e.i(722678);let w=(0,l.createContext)(null);w.displayName="GroupContext";let k=l.Fragment,C=Object.assign((0,x.forwardRefWithAs)(function(e,t){var k;let C=(0,l.useId)(),j=(0,p.useProvidedId)(),N=(0,m.useDisabled)(),{id:S=j||`headlessui-switch-${C}`,disabled:$=N||!1,checked:M,defaultChecked:E,onChange:O,name:T,value:P,form:_,autoFocus:z=!1,...R}=e,I=(0,l.useContext)(w),[L,D]=(0,l.useState)(null),B=(0,l.useRef)(null),F=(0,u.useSyncRefs)(B,t,null===I?null:I.setSwitch,D),A=(0,s.useDefaultValue)(E),[q,H]=(0,n.useControllable)(M,O,null!=A&&A),G=(0,i.useDisposables)(),[X,V]=(0,l.useState)(!1),K=(0,c.useEvent)(()=>{V(!0),null==H||H(!q),G.nextFrame(()=>{V(!1)})}),W=(0,c.useEvent)(e=>{if((0,f.isDisabledReactIssue7711)(e.currentTarget))return e.preventDefault();e.preventDefault(),K()}),U=(0,c.useEvent)(e=>{e.key===y.Keys.Space?(e.preventDefault(),K()):e.key===y.Keys.Enter&&(0,h.attemptSubmit)(e.currentTarget)}),Y=(0,c.useEvent)(e=>e.preventDefault()),Q=(0,v.useLabelledBy)(),J=(0,b.useDescribedBy)(),{isFocusVisible:Z,focusProps:ee}=(0,r.useFocusRing)({autoFocus:z}),{isHovered:et,hoverProps:er}=(0,a.useHover)({isDisabled:$}),{pressed:ea,pressProps:el}=(0,o.useActivePress)({disabled:$}),eo=(0,l.useMemo)(()=>({checked:q,disabled:$,hover:et,focus:Z,active:ea,autofocus:z,changing:X}),[q,et,Z,ea,$,X,z]),en=(0,x.mergeProps)({id:S,ref:F,role:"switch",type:(0,d.useResolveButtonType)(e,L),tabIndex:-1===e.tabIndex?0:null!=(k=e.tabIndex)?k:0,"aria-checked":q,"aria-labelledby":Q,"aria-describedby":J,disabled:$||void 0,autoFocus:z,onClick:W,onKeyUp:U,onKeyPress:Y},ee,er,el),es=(0,l.useCallback)(()=>{if(void 0!==A)return null==H?void 0:H(A)},[H,A]),ei=(0,x.useRender)();return l.default.createElement(l.default.Fragment,null,null!=T&&l.default.createElement(g.FormFields,{disabled:$,data:{[T]:P||"on"},overrides:{type:"checkbox",checked:q},form:_,onReset:es}),ei({ourProps:en,theirProps:R,slot:eo,defaultTag:"button",name:"Switch"}))}),{Group:function(e){var t;let[r,a]=(0,l.useState)(null),[o,n]=(0,v.useLabels)(),[s,i]=(0,b.useDescriptions)(),c=(0,l.useMemo)(()=>({switch:r,setSwitch:a}),[r,a]),d=(0,x.useRender)();return l.default.createElement(i,{name:"Switch.Description",value:s},l.default.createElement(n,{name:"Switch.Label",value:o,props:{htmlFor:null==(t=c.switch)?void 0:t.id,onClick(e){r&&(e.currentTarget instanceof HTMLLabelElement&&e.preventDefault(),r.click(),r.focus({preventScroll:!0}))}}},l.default.createElement(w.Provider,{value:c},d({ourProps:{},theirProps:e,slot:{},defaultTag:k,name:"Switch.Group"}))))},Label:v.Label,Description:b.Description});var j=e.i(888288),N=e.i(95779),S=e.i(444755),$=e.i(673706),M=e.i(829087);let E=(0,$.makeClassName)("Switch"),O=l.default.forwardRef((e,r)=>{let{checked:a,defaultChecked:o=!1,onChange:n,color:s,name:i,error:c,errorMessage:d,disabled:u,required:m,tooltip:g,id:p}=e,f=(0,t.__rest)(e,["checked","defaultChecked","onChange","color","name","error","errorMessage","disabled","required","tooltip","id"]),h={bgColor:s?(0,$.getColorClassNames)(s,N.colorPalette.background).bgColor:"bg-tremor-brand dark:bg-dark-tremor-brand",ringColor:s?(0,$.getColorClassNames)(s,N.colorPalette.ring).ringColor:"ring-tremor-brand-muted dark:ring-dark-tremor-brand-muted"},[x,b]=(0,j.default)(o,a),[y,v]=(0,l.useState)(!1),{tooltipProps:w,getReferenceProps:k}=(0,M.useTooltip)(300);return l.default.createElement("div",{className:"flex flex-row items-center justify-start"},l.default.createElement(M.default,Object.assign({text:g},w)),l.default.createElement("div",Object.assign({ref:(0,$.mergeRefs)([r,w.refs.setReference]),className:(0,S.tremorTwMerge)(E("root"),"flex flex-row relative h-5")},f,k),l.default.createElement("input",{type:"checkbox",className:(0,S.tremorTwMerge)(E("input"),"absolute w-5 h-5 cursor-pointer left-0 top-0 opacity-0"),name:i,required:m,checked:x,onChange:e=>{e.preventDefault()}}),l.default.createElement(C,{checked:x,onChange:e=>{b(e),null==n||n(e)},disabled:u,className:(0,S.tremorTwMerge)(E("switch"),"w-10 h-5 group relative inline-flex shrink-0 cursor-pointer items-center justify-center rounded-tremor-full","focus:outline-none",u?"cursor-not-allowed":""),onFocus:()=>v(!0),onBlur:()=>v(!1),id:p},l.default.createElement("span",{className:(0,S.tremorTwMerge)(E("sr-only"),"sr-only")},"Switch ",x?"on":"off"),l.default.createElement("span",{"aria-hidden":"true",className:(0,S.tremorTwMerge)(E("background"),x?h.bgColor:"bg-tremor-border dark:bg-dark-tremor-border","pointer-events-none absolute mx-auto h-3 w-9 rounded-tremor-full transition-colors duration-100 ease-in-out")}),l.default.createElement("span",{"aria-hidden":"true",className:(0,S.tremorTwMerge)(E("round"),x?(0,S.tremorTwMerge)(h.bgColor,"translate-x-5 border-tremor-background dark:border-dark-tremor-background"):"translate-x-0 bg-tremor-border dark:bg-dark-tremor-border border-tremor-background dark:border-dark-tremor-background","pointer-events-none absolute left-0 inline-block h-5 w-5 transform rounded-tremor-full border-2 shadow-tremor-input duration-100 ease-in-out transition",y?(0,S.tremorTwMerge)("ring-2",h.ringColor):"")}))),c&&d?l.default.createElement("p",{className:(0,S.tremorTwMerge)(E("errorMessage"),"text-sm text-red-500 mt-1 ")},d):null)});O.displayName="Switch",e.s(["Switch",()=>O],793130)},158392,419470,e=>{"use strict";var t=e.i(843476),r=e.i(779241);let a={ttl:3600,lowest_latency_buffer:0},l=({routingStrategyArgs:e})=>{let 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,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"max-w-3xl",children:[(0,t.jsx)("h3",{className:"text-sm font-medium text-gray-900",children:"Latency-Based Configuration"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Fine-tune latency-based routing behavior"})]}),(0,t.jsx)("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2 xl:grid-cols-3",children:Object.entries(e||a).map(([e,a])=>(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsxs)("label",{className:"block",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:e.replace(/_/g," ")}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-2",children:l[e]||""}),(0,t.jsx)(r.TextInput,{name:e,defaultValue:"object"==typeof a?JSON.stringify(a,null,2):a?.toString(),className:"font-mono text-sm w-full"})]})},e))})]}),(0,t.jsx)("div",{className:"border-t border-gray-200"})]})},o=({routerSettings:e,routerFieldsMetadata:a})=>(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"max-w-3xl",children:[(0,t.jsx)("h3",{className:"text-sm font-medium text-gray-900",children:"Reliability & Retries"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Configure retry logic and failure handling"})]}),(0,t.jsx)("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2 xl:grid-cols-3",children:Object.entries(e).filter(([e,t])=>"fallbacks"!=e&&"context_window_fallbacks"!=e&&"routing_strategy_args"!=e&&"routing_strategy"!=e&&"enable_tag_filtering"!=e).map(([e,l])=>(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsxs)("label",{className:"block",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:a[e]?.ui_field_name||e}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-2",children:a[e]?.field_description||""}),(0,t.jsx)(r.TextInput,{name:e,defaultValue:null==l||"null"===l?"":"object"==typeof l?JSON.stringify(l,null,2):l?.toString()||"",placeholder:"—",className:"font-mono text-sm w-full"})]})},e))})]});var n=e.i(199133);let s=({selectedStrategy:e,availableStrategies:r,routingStrategyDescriptions:a,routerFieldsMetadata:l,onStrategyChange:o})=>(0,t.jsxs)("div",{className:"space-y-2 max-w-3xl",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:l.routing_strategy?.ui_field_name||"Routing Strategy"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-2",children:l.routing_strategy?.field_description||""})]}),(0,t.jsx)("div",{className:"routing-strategy-select max-w-3xl",children:(0,t.jsx)(n.Select,{value:e,onChange:o,style:{width:"100%"},size:"large",children:r.map(e=>(0,t.jsx)(n.Select.Option,{value:e,label:e,children:(0,t.jsxs)("div",{className:"flex flex-col gap-0.5 py-1",children:[(0,t.jsx)("span",{className:"font-mono text-sm font-medium",children:e}),a[e]&&(0,t.jsx)("span",{className:"text-xs text-gray-500 font-normal",children:a[e]})]})},e))})})]});var i=e.i(793130);let c=({enabled:e,routerFieldsMetadata:r,onToggle:a})=>(0,t.jsx)("div",{className:"space-y-3 max-w-3xl",children:(0,t.jsxs)("div",{className:"flex items-start justify-between",children:[(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsx)("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:r.enable_tag_filtering?.ui_field_name||"Enable Tag Filtering"}),(0,t.jsxs)("p",{className:"text-xs text-gray-500 mt-0.5",children:[r.enable_tag_filtering?.field_description||"",r.enable_tag_filtering?.link&&(0,t.jsxs)(t.Fragment,{children:[" ",(0,t.jsx)("a",{href:r.enable_tag_filtering.link,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"Learn more"})]})]})]}),(0,t.jsx)(i.Switch,{checked:e,onChange:a,className:"ml-4"})]})});e.s(["default",0,({value:e,onChange:r,routerFieldsMetadata:a,availableRoutingStrategies:n,routingStrategyDescriptions:i})=>(0,t.jsxs)("div",{className:"w-full space-y-8 py-2",children:[(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"max-w-3xl",children:[(0,t.jsx)("h3",{className:"text-sm font-medium text-gray-900",children:"Routing Settings"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Configure how requests are routed to deployments"})]}),n.length>0&&(0,t.jsx)(s,{selectedStrategy:e.selectedStrategy||e.routerSettings.routing_strategy||null,availableStrategies:n,routingStrategyDescriptions:i,routerFieldsMetadata:a,onStrategyChange:t=>{r({...e,selectedStrategy:t})}}),(0,t.jsx)(c,{enabled:e.enableTagFiltering,routerFieldsMetadata:a,onToggle:t=>{r({...e,enableTagFiltering:t})}})]}),(0,t.jsx)("div",{className:"border-t border-gray-200"}),"latency-based-routing"===e.selectedStrategy&&(0,t.jsx)(l,{routingStrategyArgs:e.routerSettings.routing_strategy_args}),(0,t.jsx)(o,{routerSettings:e.routerSettings,routerFieldsMetadata:a})]})],158392);var d=e.i(994388),u=e.i(998573),m=e.i(653496),g=e.i(107233),p=e.i(271645),f=e.i(592968),h=e.i(361653),h=h;let x=(0,e.i(475254).default)("arrow-down",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);var b=e.i(37727);function y({group:e,onChange:r,availableModels:a,maxFallbacks:l}){let o=a.filter(t=>t!==e.primaryModel),s=e.fallbackModels.length{let a=[...e.fallbackModels];a.includes(t)&&(a=a.filter(e=>e!==t)),r({...e,primaryModel:t,fallbackModels:a})},showSearch:!0,filterOption:(e,t)=>(t?.label??"").toLowerCase().includes(e.toLowerCase()),options:a.map(e=>({label:e,value:e}))}),!e.primaryModel&&(0,t.jsxs)("div",{className:"mt-2 flex items-center gap-2 text-amber-600 text-xs bg-amber-50 p-2 rounded",children:[(0,t.jsx)(h.default,{className:"w-4 h-4"}),(0,t.jsx)("span",{children:"Select a model to begin configuring fallbacks"})]})]}),(0,t.jsx)("div",{className:"flex items-center justify-center -my-4 z-10",children:(0,t.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,t.jsx)(x,{className:"w-4 h-4"}),"IF FAILS, TRY..."]})}),(0,t.jsxs)("div",{className:`transition-opacity duration-300 ${!e.primaryModel?"opacity-50 pointer-events-none":"opacity-100"}`,children:[(0,t.jsxs)("label",{className:"block text-sm font-semibold text-gray-700 mb-2",children:["Fallback Chain ",(0,t.jsx)("span",{className:"text-red-500",children:"*"}),(0,t.jsxs)("span",{className:"text-xs text-gray-500 font-normal ml-2",children:["(Max ",l," fallbacks at a time)"]})]}),(0,t.jsxs)("div",{className:"bg-gray-50 rounded-xl p-4 border border-gray-200",children:[(0,t.jsxs)("div",{className:"mb-4",children:[(0,t.jsx)(n.Select,{mode:"multiple",className:"w-full",size:"large",placeholder:s?"Select fallback models to add...":`Maximum ${l} fallbacks reached`,value:e.fallbackModels,onChange:t=>{let a=t.slice(0,l);r({...e,fallbackModels:a})},disabled:!e.primaryModel,options:o.map(e=>({label:e,value:e})),optionRender:(r,a)=>{let l=e.fallbackModels.includes(r.value),o=l?e.fallbackModels.indexOf(r.value)+1:null;return(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[l&&null!==o&&(0,t.jsx)("span",{className:"flex items-center justify-center w-5 h-5 rounded bg-indigo-100 text-indigo-600 text-xs font-bold",children:o}),(0,t.jsx)("span",{children:r.label})]})},maxTagCount:"responsive",maxTagPlaceholder:e=>(0,t.jsx)(f.Tooltip,{styles:{root:{pointerEvents:"none"}},title:e.map(({value:e})=>e).join(", "),children:(0,t.jsxs)("span",{children:["+",e.length," more"]})}),showSearch:!0,filterOption:(e,t)=>(t?.label??"").toLowerCase().includes(e.toLowerCase())}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1 ml-1",children:s?`Search and select multiple models. Selected models will appear below in order. (${e.fallbackModels.length}/${l} used)`:`Maximum ${l} fallbacks reached. Remove some to add more.`})]}),(0,t.jsx)("div",{className:"space-y-2 min-h-[100px]",children:0===e.fallbackModels.length?(0,t.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,t.jsx)("span",{className:"text-sm",children:"No fallback models selected"}),(0,t.jsx)("span",{className:"text-xs mt-1",children:"Add models from the dropdown above"})]}):e.fallbackModels.map((a,l)=>(0,t.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,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.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,t.jsx)("span",{className:"text-xs font-bold",children:l+1})}),(0,t.jsx)("div",{children:(0,t.jsx)("span",{className:"font-medium text-gray-800",children:a})})]}),(0,t.jsx)("button",{type:"button",onClick:()=>{let t;return t=e.fallbackModels.filter((e,t)=>t!==l),void r({...e,fallbackModels:t})},className:"opacity-0 group-hover:opacity-100 transition-opacity text-gray-400 hover:text-red-500 p-1",children:(0,t.jsx)(b.X,{className:"w-4 h-4"})})]},`${a}-${l}`))})]})]})]})}function v({groups:e,onGroupsChange:r,availableModels:a,maxFallbacks:l=10,maxGroups:o=5}){let[n,s]=(0,p.useState)(e.length>0?e[0].id:"1");(0,p.useEffect)(()=>{e.length>0?e.some(e=>e.id===n)||s(e[0].id):s("1")},[e]);let i=()=>{if(e.length>=o)return;let t=Date.now().toString();r([...e,{id:t,primaryModel:null,fallbackModels:[]}]),s(t)},c=t=>{r(e.map(e=>e.id===t.id?t:e))},f=e.map((r,o)=>{let n=r.primaryModel?r.primaryModel:`Group ${o+1}`;return{key:r.id,label:n,closable:e.length>1,children:(0,t.jsx)(y,{group:r,onChange:c,availableModels:a,maxFallbacks:l})}});return 0===e.length?(0,t.jsxs)("div",{className:"text-center py-12 bg-gray-50 rounded-lg border border-dashed border-gray-300",children:[(0,t.jsx)("p",{className:"text-gray-500 mb-4",children:"No fallback groups configured"}),(0,t.jsx)(d.Button,{variant:"primary",onClick:i,icon:()=>(0,t.jsx)(g.Plus,{className:"w-4 h-4"}),children:"Create First Group"})]}):(0,t.jsx)(m.Tabs,{type:"editable-card",activeKey:n,onChange:s,onEdit:(t,a)=>{"add"===a?i():"remove"===a&&e.length>1&&(t=>{if(1===e.length)return u.message.warning("At least one group is required");let a=e.filter(e=>e.id!==t);r(a),n===t&&a.length>0&&s(a[a.length-1].id)})(t)},items:f,className:"fallback-tabs",tabBarStyle:{marginBottom:0},hideAdd:e.length>=o})}e.s(["FallbackSelectionForm",()=>v],419470)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/16ee7f92da0b1f99.js b/litellm/proxy/_experimental/out/_next/static/chunks/16ee7f92da0b1f99.js deleted file mode 100644 index ee8d6b03d5e..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/16ee7f92da0b1f99.js +++ /dev/null @@ -1,8 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,907308,e=>{"use strict";var t=e.i(843476),l=e.i(271645),a=e.i(212931),r=e.i(808613),i=e.i(464571),s=e.i(199133),n=e.i(592968),o=e.i(213205),d=e.i(374009),c=e.i(764205);e.s(["default",0,({isVisible:e,onCancel:u,onSubmit:m,accessToken:g,title:h="Add Team Member",roles:f=[{label:"admin",value:"admin",description:"Admin role. Can create team keys, add members, and manage settings."},{label:"user",value:"user",description:"User role. Can view team info, but not manage it."}],defaultRole:p="user"})=>{let[b]=r.Form.useForm(),[x,v]=(0,l.useState)([]),[j,y]=(0,l.useState)(!1),[w,k]=(0,l.useState)("user_email"),[C,O]=(0,l.useState)(!1),$=async(e,t)=>{if(!e)return void v([]);y(!0);try{let l=new URLSearchParams;if(l.append(t,e),null==g)return;let a=(await (0,c.userFilterUICall)(g,l)).map(e=>({label:"user_email"===t?`${e.user_email}`:`${e.user_id}`,value:"user_email"===t?e.user_email:e.user_id,user:e}));v(a)}catch(e){console.error("Error fetching users:",e)}finally{y(!1)}},N=(0,l.useCallback)((0,d.default)((e,t)=>$(e,t),300),[]),E=(e,t)=>{k(t),N(e,t)},T=(e,t)=>{let l=t.user;b.setFieldsValue({user_email:l.user_email,user_id:l.user_id,role:b.getFieldValue("role")})},_=async e=>{O(!0);try{await m(e)}finally{O(!1)}};return(0,t.jsx)(a.Modal,{title:h,open:e,onCancel:()=>{b.resetFields(),v([]),u()},footer:null,width:800,maskClosable:!C,children:(0,t.jsxs)(r.Form,{form:b,onFinish:_,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",initialValues:{role:p},children:[(0,t.jsx)(r.Form.Item,{label:"Email",name:"user_email",className:"mb-4",children:(0,t.jsx)(s.Select,{showSearch:!0,className:"w-full",placeholder:"Search by email",filterOption:!1,onSearch:e=>E(e,"user_email"),onSelect:(e,t)=>T(e,t),options:"user_email"===w?x:[],loading:j,allowClear:!0})}),(0,t.jsx)("div",{className:"text-center mb-4",children:"OR"}),(0,t.jsx)(r.Form.Item,{label:"User ID",name:"user_id",className:"mb-4",children:(0,t.jsx)(s.Select,{showSearch:!0,className:"w-full",placeholder:"Search by user ID",filterOption:!1,onSearch:e=>E(e,"user_id"),onSelect:(e,t)=>T(e,t),options:"user_id"===w?x:[],loading:j,allowClear:!0})}),(0,t.jsx)(r.Form.Item,{label:"Member Role",name:"role",className:"mb-4",children:(0,t.jsx)(s.Select,{defaultValue:p,children:f.map(e=>(0,t.jsx)(s.Select.Option,{value:e.value,children:(0,t.jsxs)(n.Tooltip,{title:e.description,children:[(0,t.jsx)("span",{className:"font-medium",children:e.label}),(0,t.jsxs)("span",{className:"ml-2 text-gray-500 text-sm",children:["- ",e.description]})]})},e.value))})}),(0,t.jsx)("div",{className:"text-right mt-4",children:(0,t.jsx)(i.Button,{type:"primary",htmlType:"submit",icon:(0,t.jsx)(o.UserAddOutlined,{}),loading:C,children:C?"Adding...":"Add Member"})})]})})}])},162386,e=>{"use strict";var t=e.i(843476),l=e.i(625901),a=e.i(109799),r=e.i(785242),i=e.i(738014),s=e.i(199133),n=e.i(981339),o=e.i(592968);let d={label:"All Proxy Models",value:"all-proxy-models"},c={label:"No Default Models",value:"no-default-models"},u=[d,c],m={user:({allProxyModels:e,userModels:t,options:l})=>t&&l?.includeUserModels?t:[],team:({allProxyModels:e,selectedOrganization:t,userModels:l})=>t?t.models.includes(d.value)||0===t.models.length?e:e.filter(e=>t.models.includes(e)):e??[],organization:({allProxyModels:e})=>e,global:({allProxyModels:e})=>e};e.s(["ModelSelect",0,e=>{let{teamID:g,organizationID:h,options:f,context:p,dataTestId:b,value:x=[],onChange:v,style:j}=e,{includeUserModels:y,showAllTeamModelsOption:w,showAllProxyModelsOverride:k,includeSpecialOptions:C}=f||{},{data:O,isLoading:$}=(0,l.useAllProxyModels)(),{data:N,isLoading:E}=(0,r.useTeam)(g),{data:T,isLoading:_}=(0,a.useOrganization)(h),{data:M,isLoading:I}=(0,i.useCurrentUser)(),S=e=>u.some(t=>t.value===e),R=x.some(S),A=T?.models.includes(d.value)||T?.models.length===0;if($||E||_||I)return(0,t.jsx)(n.Skeleton.Input,{active:!0,block:!0});let{wildcard:q,regular:F}=(e=>{let t=[],l=[];for(let a of e)a.endsWith("/*")?t.push(a):l.push(a);return{wildcard:t,regular:l}})(((e,t,l)=>{let a=Array.from(new Map(e.map(e=>[e.id,e])).values()).map(e=>e.id);if(t.options?.showAllProxyModelsOverride)return a;let r=m[t.context];return r?r({allProxyModels:a,...l,options:t.options}):[]})(O?.data??[],e,{selectedTeam:N,selectedOrganization:T,userModels:M?.models}));return(0,t.jsx)(s.Select,{"data-testid":b,value:x,onChange:e=>{let t=e.filter(S);v(t.length>0?[t[t.length-1]]:e)},style:j,options:[C?{label:(0,t.jsx)("span",{children:"Special Options"}),title:"Special Options",options:[...k||A&&C||"global"===p?[{label:(0,t.jsx)("span",{children:"All Proxy Models"}),value:d.value,disabled:x.length>0&&x.some(e=>S(e)&&e!==d.value),key:d.value}]:[],{label:(0,t.jsx)("span",{children:"No Default Models"}),value:c.value,disabled:x.length>0&&x.some(e=>S(e)&&e!==c.value),key:c.value}]}:[],...q.length>0?[{label:(0,t.jsx)("span",{children:"Wildcard Options"}),title:"Wildcard Options",options:q.map(e=>{let l=e.replace("/*",""),a=l.charAt(0).toUpperCase()+l.slice(1);return{label:(0,t.jsx)("span",{children:`All ${a} models`}),value:e,disabled:R}})}]:[],{label:(0,t.jsx)("span",{children:"Models"}),title:"Models",options:F.map(e=>({label:(0,t.jsx)("span",{children:e}),value:e,disabled:R}))}],mode:"multiple",placeholder:"Select Models",allowClear:!0,maxTagCount:"responsive",maxTagPlaceholder:e=>(0,t.jsx)(o.Tooltip,{styles:{root:{pointerEvents:"none"}},title:e.map(({value:e})=>e).join(", "),children:(0,t.jsxs)("span",{children:["+",e.length," more"]})})})}],162386)},276173,e=>{"use strict";var t=e.i(843476),l=e.i(599724),a=e.i(779241),r=e.i(464571),i=e.i(808613),s=e.i(212931),n=e.i(199133),o=e.i(271645),d=e.i(435451);e.s(["default",0,({visible:e,onCancel:c,onSubmit:u,initialData:m,mode:g,config:h})=>{let f,[p]=i.Form.useForm(),[b,x]=(0,o.useState)(!1);console.log("Initial Data:",m),(0,o.useEffect)(()=>{if(e)if("edit"===g&&m){let e={...m,role:m.role||h.defaultRole,max_budget_in_team:m.max_budget_in_team||null,tpm_limit:m.tpm_limit||null,rpm_limit:m.rpm_limit||null};console.log("Setting form values:",e),p.setFieldsValue(e)}else p.resetFields(),p.setFieldsValue({role:h.defaultRole||h.roleOptions[0]?.value})},[e,m,g,p,h.defaultRole,h.roleOptions]);let v=async e=>{try{x(!0);let t=Object.entries(e).reduce((e,[t,l])=>{if("string"==typeof l){let a=l.trim();return""===a&&("max_budget_in_team"===t||"tpm_limit"===t||"rpm_limit"===t)?{...e,[t]:null}:{...e,[t]:a}}return{...e,[t]:l}},{});console.log("Submitting form data:",t),await Promise.resolve(u(t)),p.resetFields()}catch(e){console.error("Form submission error:",e)}finally{x(!1)}};return(0,t.jsx)(s.Modal,{title:h.title||("add"===g?"Add Member":"Edit Member"),open:e,width:1e3,footer:null,onCancel:c,children:(0,t.jsxs)(i.Form,{form:p,onFinish:v,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[h.showEmail&&(0,t.jsx)(i.Form.Item,{label:"Email",name:"user_email",className:"mb-4",rules:[{type:"email",message:"Please enter a valid email!"}],children:(0,t.jsx)(a.TextInput,{placeholder:"user@example.com"})}),h.showEmail&&h.showUserId&&(0,t.jsx)("div",{className:"text-center mb-4",children:(0,t.jsx)(l.Text,{children:"OR"})}),h.showUserId&&(0,t.jsx)(i.Form.Item,{label:"User ID",name:"user_id",className:"mb-4",children:(0,t.jsx)(a.TextInput,{placeholder:"user_123"})}),(0,t.jsx)(i.Form.Item,{label:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{children:"Role"}),"edit"===g&&m&&(0,t.jsxs)("span",{className:"text-gray-500 text-sm",children:["(Current: ",(f=m.role,h.roleOptions.find(e=>e.value===f)?.label||f),")"]})]}),name:"role",className:"mb-4",rules:[{required:!0,message:"Please select a role!"}],children:(0,t.jsx)(n.Select,{children:"edit"===g&&m?[...h.roleOptions.filter(e=>e.value===m.role),...h.roleOptions.filter(e=>e.value!==m.role)].map(e=>(0,t.jsx)(n.Select.Option,{value:e.value,children:e.label},e.value)):h.roleOptions.map(e=>(0,t.jsx)(n.Select.Option,{value:e.value,children:e.label},e.value))})}),h.additionalFields?.map(e=>(0,t.jsx)(i.Form.Item,{label:e.label,name:e.name,className:"mb-4",rules:e.rules,children:(e=>{switch(e.type){case"input":return(0,t.jsx)(a.TextInput,{placeholder:e.placeholder});case"numerical":return(0,t.jsx)(d.default,{step:e.step||1,min:e.min||0,style:{width:"100%"},placeholder:e.placeholder||"Enter a numerical value"});case"select":return(0,t.jsx)(n.Select,{children:e.options?.map(e=>(0,t.jsx)(n.Select.Option,{value:e.value,children:e.label},e.value))});default:return null}})(e)},e.name)),(0,t.jsxs)("div",{className:"text-right mt-6",children:[(0,t.jsx)(r.Button,{onClick:c,className:"mr-2",disabled:b,children:"Cancel"}),(0,t.jsx)(r.Button,{type:"default",htmlType:"submit",loading:b,children:"add"===g?b?"Adding...":"Add Member":b?"Saving...":"Save Changes"})]})]})})}])},294612,e=>{"use strict";var t=e.i(843476),l=e.i(100486),a=e.i(827252),r=e.i(213205),i=e.i(771674),s=e.i(464571),n=e.i(770914),o=e.i(291542),d=e.i(262218),c=e.i(592968),u=e.i(898586),m=e.i(902555);let{Text:g}=u.Typography;function h({members:e,canEdit:u,onEdit:h,onDelete:f,onAddMember:p,roleColumnTitle:b="Role",roleTooltip:x,extraColumns:v=[],showDeleteForMember:j,emptyText:y}){let w=[{title:"User Email",dataIndex:"user_email",key:"user_email",render:e=>(0,t.jsx)(g,{children:e||"-"})},{title:"User ID",dataIndex:"user_id",key:"user_id",render:e=>"default_user_id"===e?(0,t.jsx)(d.Tag,{color:"blue",children:"Default Proxy Admin"}):(0,t.jsx)(g,{children:e||"-"})},{title:x?(0,t.jsxs)(n.Space,{direction:"horizontal",children:[b,(0,t.jsx)(c.Tooltip,{title:x,children:(0,t.jsx)(a.InfoCircleOutlined,{})})]}):b,dataIndex:"role",key:"role",render:e=>(0,t.jsxs)(n.Space,{children:[e?.toLowerCase()==="admin"||e?.toLowerCase()==="org_admin"?(0,t.jsx)(l.CrownOutlined,{}):(0,t.jsx)(i.UserOutlined,{}),(0,t.jsx)(g,{style:{textTransform:"capitalize"},children:e||"-"})]})},...v,{title:"Actions",key:"actions",fixed:"right",width:120,render:(e,l)=>u?(0,t.jsxs)(n.Space,{children:[(0,t.jsx)(m.default,{variant:"Edit",tooltipText:"Edit member",dataTestId:"edit-member",onClick:()=>h(l)}),(!j||j(l))&&(0,t.jsx)(m.default,{variant:"Delete",tooltipText:"Delete member",dataTestId:"delete-member",onClick:()=>f(l)})]}):null}];return(0,t.jsxs)(n.Space,{direction:"vertical",style:{width:"100%"},children:[(0,t.jsx)(o.Table,{columns:w,dataSource:e,rowKey:e=>e.user_id??e.user_email??JSON.stringify(e),pagination:!1,size:"small",scroll:{x:"max-content"},locale:y?{emptyText:y}:void 0}),p&&u&&(0,t.jsx)(s.Button,{icon:(0,t.jsx)(r.UserAddOutlined,{}),type:"primary",onClick:p,children:"Add Member"})]})}e.s(["default",()=>h])},434626,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.createElement("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"}))});e.s(["ExternalLinkIcon",0,l],434626)},902555,e=>{"use strict";var t=e.i(843476),l=e.i(591935),a=e.i(122577),r=e.i(278587),i=e.i(68155),s=e.i(360820),n=e.i(871943),o=e.i(434626),d=e.i(592968),c=e.i(115504),u=e.i(752978);function m({icon:e,onClick:l,className:a,disabled:r,dataTestId:i}){return r?(0,t.jsx)(u.Icon,{icon:e,size:"sm",className:"opacity-50 cursor-not-allowed","data-testid":i}):(0,t.jsx)(u.Icon,{icon:e,size:"sm",onClick:l,className:(0,c.cx)("cursor-pointer",a),"data-testid":i})}let g={Edit:{icon:l.PencilAltIcon,className:"hover:text-blue-600"},Delete:{icon:i.TrashIcon,className:"hover:text-red-600"},Test:{icon:a.PlayIcon,className:"hover:text-blue-600"},Regenerate:{icon:r.RefreshIcon,className:"hover:text-green-600"},Up:{icon:s.ChevronUpIcon,className:"hover:text-blue-600"},Down:{icon:n.ChevronDownIcon,className:"hover:text-blue-600"},Open:{icon:o.ExternalLinkIcon,className:"hover:text-green-600"}};function h({onClick:e,tooltipText:l,disabled:a=!1,disabledTooltipText:r,dataTestId:i,variant:s}){let{icon:n,className:o}=g[s];return(0,t.jsx)(d.Tooltip,{title:a?r:l,children:(0,t.jsx)("span",{children:(0,t.jsx)(m,{icon:n,onClick:e,className:o,disabled:a,dataTestId:i})})})}e.s(["default",()=>h],902555)},122577,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"}),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 12a9 9 0 11-18 0 9 9 0 0118 0z"}))});e.s(["PlayIcon",0,l],122577)},591935,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.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.s(["PencilAltIcon",0,l],591935)},871943,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"}))});e.s(["ChevronDownIcon",0,l],871943)},360820,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 15l7-7 7 7"}))});e.s(["ChevronUpIcon",0,l],360820)},185793,e=>{"use strict";e.i(247167);var t=e.i(271645),l=e.i(343794),a=e.i(242064),r=e.i(529681);let i=e=>{let{prefixCls:a,className:r,style:i,size:s,shape:n}=e,o=(0,l.default)({[`${a}-lg`]:"large"===s,[`${a}-sm`]:"small"===s}),d=(0,l.default)({[`${a}-circle`]:"circle"===n,[`${a}-square`]:"square"===n,[`${a}-round`]:"round"===n}),c=t.useMemo(()=>"number"==typeof s?{width:s,height:s,lineHeight:`${s}px`}:{},[s]);return t.createElement("span",{className:(0,l.default)(a,o,d,r),style:Object.assign(Object.assign({},c),i)})};e.i(296059);var s=e.i(694758),n=e.i(915654),o=e.i(246422),d=e.i(838378);let c=new s.Keyframes("ant-skeleton-loading",{"0%":{backgroundPosition:"100% 50%"},"100%":{backgroundPosition:"0 50%"}}),u=e=>({height:e,lineHeight:(0,n.unit)(e)}),m=e=>Object.assign({width:e},u(e)),g=(e,t)=>Object.assign({width:t(e).mul(5).equal(),minWidth:t(e).mul(5).equal()},u(e)),h=e=>Object.assign({width:e},u(e)),f=(e,t,l)=>{let{skeletonButtonCls:a}=e;return{[`${l}${a}-circle`]:{width:t,minWidth:t,borderRadius:"50%"},[`${l}${a}-round`]:{borderRadius:t}}},p=(e,t)=>Object.assign({width:t(e).mul(2).equal(),minWidth:t(e).mul(2).equal()},u(e)),b=(0,o.genStyleHooks)("Skeleton",e=>{let{componentCls:t,calc:l}=e;return(e=>{let{componentCls:t,skeletonAvatarCls:l,skeletonTitleCls:a,skeletonParagraphCls:r,skeletonButtonCls:i,skeletonInputCls:s,skeletonImageCls:n,controlHeight:o,controlHeightLG:d,controlHeightSM:u,gradientFromColor:b,padding:x,marginSM:v,borderRadius:j,titleHeight:y,blockRadius:w,paragraphLiHeight:k,controlHeightXS:C,paragraphMarginTop:O}=e;return{[t]:{display:"table",width:"100%",[`${t}-header`]:{display:"table-cell",paddingInlineEnd:x,verticalAlign:"top",[l]:Object.assign({display:"inline-block",verticalAlign:"top",background:b},m(o)),[`${l}-circle`]:{borderRadius:"50%"},[`${l}-lg`]:Object.assign({},m(d)),[`${l}-sm`]:Object.assign({},m(u))},[`${t}-content`]:{display:"table-cell",width:"100%",verticalAlign:"top",[a]:{width:"100%",height:y,background:b,borderRadius:w,[`+ ${r}`]:{marginBlockStart:u}},[r]:{padding:0,"> li":{width:"100%",height:k,listStyle:"none",background:b,borderRadius:w,"+ li":{marginBlockStart:C}}},[`${r}> li:last-child:not(:first-child):not(:nth-child(2))`]:{width:"61%"}},[`&-round ${t}-content`]:{[`${a}, ${r} > li`]:{borderRadius:j}}},[`${t}-with-avatar ${t}-content`]:{[a]:{marginBlockStart:v,[`+ ${r}`]:{marginBlockStart:O}}},[`${t}${t}-element`]:Object.assign(Object.assign(Object.assign(Object.assign({display:"inline-block",width:"auto"},(e=>{let{borderRadiusSM:t,skeletonButtonCls:l,controlHeight:a,controlHeightLG:r,controlHeightSM:i,gradientFromColor:s,calc:n}=e;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({[l]:Object.assign({display:"inline-block",verticalAlign:"top",background:s,borderRadius:t,width:n(a).mul(2).equal(),minWidth:n(a).mul(2).equal()},p(a,n))},f(e,a,l)),{[`${l}-lg`]:Object.assign({},p(r,n))}),f(e,r,`${l}-lg`)),{[`${l}-sm`]:Object.assign({},p(i,n))}),f(e,i,`${l}-sm`))})(e)),(e=>{let{skeletonAvatarCls:t,gradientFromColor:l,controlHeight:a,controlHeightLG:r,controlHeightSM:i}=e;return{[t]:Object.assign({display:"inline-block",verticalAlign:"top",background:l},m(a)),[`${t}${t}-circle`]:{borderRadius:"50%"},[`${t}${t}-lg`]:Object.assign({},m(r)),[`${t}${t}-sm`]:Object.assign({},m(i))}})(e)),(e=>{let{controlHeight:t,borderRadiusSM:l,skeletonInputCls:a,controlHeightLG:r,controlHeightSM:i,gradientFromColor:s,calc:n}=e;return{[a]:Object.assign({display:"inline-block",verticalAlign:"top",background:s,borderRadius:l},g(t,n)),[`${a}-lg`]:Object.assign({},g(r,n)),[`${a}-sm`]:Object.assign({},g(i,n))}})(e)),(e=>{let{skeletonImageCls:t,imageSizeBase:l,gradientFromColor:a,borderRadiusSM:r,calc:i}=e;return{[t]:Object.assign(Object.assign({display:"inline-flex",alignItems:"center",justifyContent:"center",verticalAlign:"middle",background:a,borderRadius:r},h(i(l).mul(2).equal())),{[`${t}-path`]:{fill:"#bfbfbf"},[`${t}-svg`]:Object.assign(Object.assign({},h(l)),{maxWidth:i(l).mul(4).equal(),maxHeight:i(l).mul(4).equal()}),[`${t}-svg${t}-svg-circle`]:{borderRadius:"50%"}}),[`${t}${t}-circle`]:{borderRadius:"50%"}}})(e)),[`${t}${t}-block`]:{width:"100%",[i]:{width:"100%"},[s]:{width:"100%"}},[`${t}${t}-active`]:{[` - ${a}, - ${r} > li, - ${l}, - ${i}, - ${s}, - ${n} - `]:Object.assign({},{background:e.skeletonLoadingBackground,backgroundSize:"400% 100%",animationName:c,animationDuration:e.skeletonLoadingMotionDuration,animationTimingFunction:"ease",animationIterationCount:"infinite"})}}})((0,d.mergeToken)(e,{skeletonAvatarCls:`${t}-avatar`,skeletonTitleCls:`${t}-title`,skeletonParagraphCls:`${t}-paragraph`,skeletonButtonCls:`${t}-button`,skeletonInputCls:`${t}-input`,skeletonImageCls:`${t}-image`,imageSizeBase:l(e.controlHeight).mul(1.5).equal(),borderRadius:100,skeletonLoadingBackground:`linear-gradient(90deg, ${e.gradientFromColor} 25%, ${e.gradientToColor} 37%, ${e.gradientFromColor} 63%)`,skeletonLoadingMotionDuration:"1.4s"}))},e=>{let{colorFillContent:t,colorFill:l}=e;return{color:t,colorGradientEnd:l,gradientFromColor:t,gradientToColor:l,titleHeight:e.controlHeight/2,blockRadius:e.borderRadiusSM,paragraphMarginTop:e.marginLG+e.marginXXS,paragraphLiHeight:e.controlHeight/2}},{deprecatedTokens:[["color","gradientFromColor"],["colorGradientEnd","gradientToColor"]]}),x=e=>{let{prefixCls:a,className:r,style:i,rows:s=0}=e,n=Array.from({length:s}).map((l,a)=>t.createElement("li",{key:a,style:{width:((e,t)=>{let{width:l,rows:a=2}=t;return Array.isArray(l)?l[e]:a-1===e?l:void 0})(a,e)}}));return t.createElement("ul",{className:(0,l.default)(a,r),style:i},n)},v=({prefixCls:e,className:a,width:r,style:i})=>t.createElement("h3",{className:(0,l.default)(e,a),style:Object.assign({width:r},i)});function j(e){return e&&"object"==typeof e?e:{}}let y=e=>{let{prefixCls:r,loading:s,className:n,rootClassName:o,style:d,children:c,avatar:u=!1,title:m=!0,paragraph:g=!0,active:h,round:f}=e,{getPrefixCls:p,direction:y,className:w,style:k}=(0,a.useComponentConfig)("skeleton"),C=p("skeleton",r),[O,$,N]=b(C);if(s||!("loading"in e)){let e,a,r=!!u,s=!!m,c=!!g;if(r){let l=Object.assign(Object.assign({prefixCls:`${C}-avatar`},s&&!c?{size:"large",shape:"square"}:{size:"large",shape:"circle"}),j(u));e=t.createElement("div",{className:`${C}-header`},t.createElement(i,Object.assign({},l)))}if(s||c){let e,l;if(s){let l=Object.assign(Object.assign({prefixCls:`${C}-title`},!r&&c?{width:"38%"}:r&&c?{width:"50%"}:{}),j(m));e=t.createElement(v,Object.assign({},l))}if(c){let e,a=Object.assign(Object.assign({prefixCls:`${C}-paragraph`},(e={},r&&s||(e.width="61%"),!r&&s?e.rows=3:e.rows=2,e)),j(g));l=t.createElement(x,Object.assign({},a))}a=t.createElement("div",{className:`${C}-content`},e,l)}let p=(0,l.default)(C,{[`${C}-with-avatar`]:r,[`${C}-active`]:h,[`${C}-rtl`]:"rtl"===y,[`${C}-round`]:f},w,n,o,$,N);return O(t.createElement("div",{className:p,style:Object.assign(Object.assign({},k),d)},e,a))}return null!=c?c:null};y.Button=e=>{let{prefixCls:s,className:n,rootClassName:o,active:d,block:c=!1,size:u="default"}=e,{getPrefixCls:m}=t.useContext(a.ConfigContext),g=m("skeleton",s),[h,f,p]=b(g),x=(0,r.default)(e,["prefixCls"]),v=(0,l.default)(g,`${g}-element`,{[`${g}-active`]:d,[`${g}-block`]:c},n,o,f,p);return h(t.createElement("div",{className:v},t.createElement(i,Object.assign({prefixCls:`${g}-button`,size:u},x))))},y.Avatar=e=>{let{prefixCls:s,className:n,rootClassName:o,active:d,shape:c="circle",size:u="default"}=e,{getPrefixCls:m}=t.useContext(a.ConfigContext),g=m("skeleton",s),[h,f,p]=b(g),x=(0,r.default)(e,["prefixCls","className"]),v=(0,l.default)(g,`${g}-element`,{[`${g}-active`]:d},n,o,f,p);return h(t.createElement("div",{className:v},t.createElement(i,Object.assign({prefixCls:`${g}-avatar`,shape:c,size:u},x))))},y.Input=e=>{let{prefixCls:s,className:n,rootClassName:o,active:d,block:c,size:u="default"}=e,{getPrefixCls:m}=t.useContext(a.ConfigContext),g=m("skeleton",s),[h,f,p]=b(g),x=(0,r.default)(e,["prefixCls"]),v=(0,l.default)(g,`${g}-element`,{[`${g}-active`]:d,[`${g}-block`]:c},n,o,f,p);return h(t.createElement("div",{className:v},t.createElement(i,Object.assign({prefixCls:`${g}-input`,size:u},x))))},y.Image=e=>{let{prefixCls:r,className:i,rootClassName:s,style:n,active:o}=e,{getPrefixCls:d}=t.useContext(a.ConfigContext),c=d("skeleton",r),[u,m,g]=b(c),h=(0,l.default)(c,`${c}-element`,{[`${c}-active`]:o},i,s,m,g);return u(t.createElement("div",{className:h},t.createElement("div",{className:(0,l.default)(`${c}-image`,i),style:n},t.createElement("svg",{viewBox:"0 0 1098 1024",xmlns:"http://www.w3.org/2000/svg",className:`${c}-image-svg`},t.createElement("title",null,"Image placeholder"),t.createElement("path",{d:"M365.714286 329.142857q0 45.714286-32.036571 77.677714t-77.677714 32.036571-77.677714-32.036571-32.036571-77.677714 32.036571-77.677714 77.677714-32.036571 77.677714 32.036571 32.036571 77.677714zM950.857143 548.571429l0 256-804.571429 0 0-109.714286 182.857143-182.857143 91.428571 91.428571 292.571429-292.571429zM1005.714286 146.285714l-914.285714 0q-7.460571 0-12.873143 5.412571t-5.412571 12.873143l0 694.857143q0 7.460571 5.412571 12.873143t12.873143 5.412571l914.285714 0q7.460571 0 12.873143-5.412571t5.412571-12.873143l0-694.857143q0-7.460571-5.412571-12.873143t-12.873143-5.412571zM1097.142857 164.571429l0 694.857143q0 37.741714-26.843429 64.585143t-64.585143 26.843429l-914.285714 0q-37.741714 0-64.585143-26.843429t-26.843429-64.585143l0-694.857143q0-37.741714 26.843429-64.585143t64.585143-26.843429l914.285714 0q37.741714 0 64.585143 26.843429t26.843429 64.585143z",className:`${c}-image-path`})))))},y.Node=e=>{let{prefixCls:r,className:i,rootClassName:s,style:n,active:o,children:d}=e,{getPrefixCls:c}=t.useContext(a.ConfigContext),u=c("skeleton",r),[m,g,h]=b(u),f=(0,l.default)(u,`${u}-element`,{[`${u}-active`]:o},g,i,s,h);return m(t.createElement("div",{className:f},t.createElement("div",{className:(0,l.default)(`${u}-image`,i),style:n},d)))},e.s(["default",0,y],185793)},959013,e=>{"use strict";e.i(247167);var t=e.i(931067),l=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8z"}},{tag:"path",attrs:{d:"M192 474h672q8 0 8 8v60q0 8-8 8H160q-8 0-8-8v-60q0-8 8-8z"}}]},name:"plus",theme:"outlined"};var r=e.i(9583),i=l.forwardRef(function(e,i){return l.createElement(r.default,(0,t.default)({},e,{ref:i,icon:a}))});e.s(["default",0,i],959013)},269200,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("Table"),i=l.default.forwardRef((e,i)=>{let{children:s,className:n}=e,o=(0,t.__rest)(e,["children","className"]);return l.default.createElement("div",{className:(0,a.tremorTwMerge)(r("root"),"overflow-auto",n)},l.default.createElement("table",Object.assign({ref:i,className:(0,a.tremorTwMerge)(r("table"),"w-full text-tremor-default","text-tremor-content","dark:text-dark-tremor-content")},o),s))});i.displayName="Table",e.s(["Table",()=>i],269200)},942232,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("TableBody"),i=l.default.forwardRef((e,i)=>{let{children:s,className:n}=e,o=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("tbody",Object.assign({ref:i,className:(0,a.tremorTwMerge)(r("root"),"align-top divide-y","divide-tremor-border","dark:divide-dark-tremor-border",n)},o),s))});i.displayName="TableBody",e.s(["TableBody",()=>i],942232)},977572,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("TableCell"),i=l.default.forwardRef((e,i)=>{let{children:s,className:n}=e,o=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("td",Object.assign({ref:i,className:(0,a.tremorTwMerge)(r("root"),"align-middle whitespace-nowrap text-left p-4",n)},o),s))});i.displayName="TableCell",e.s(["TableCell",()=>i],977572)},427612,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("TableHead"),i=l.default.forwardRef((e,i)=>{let{children:s,className:n}=e,o=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("thead",Object.assign({ref:i,className:(0,a.tremorTwMerge)(r("root"),"text-left","text-tremor-content","dark:text-dark-tremor-content",n)},o),s))});i.displayName="TableHead",e.s(["TableHead",()=>i],427612)},64848,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("TableHeaderCell"),i=l.default.forwardRef((e,i)=>{let{children:s,className:n}=e,o=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("th",Object.assign({ref:i,className:(0,a.tremorTwMerge)(r("root"),"whitespace-nowrap text-left font-semibold top-0 px-4 py-3.5","text-tremor-content-strong","dark:text-dark-tremor-content-strong",n)},o),s))});i.displayName="TableHeaderCell",e.s(["TableHeaderCell",()=>i],64848)},496020,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("TableRow"),i=l.default.forwardRef((e,i)=>{let{children:s,className:n}=e,o=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("tr",Object.assign({ref:i,className:(0,a.tremorTwMerge)(r("row"),n)},o),s))});i.displayName="TableRow",e.s(["TableRow",()=>i],496020)},68155,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.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.s(["TrashIcon",0,l],68155)},278587,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",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"}))});e.s(["RefreshIcon",0,l],278587)},207670,e=>{"use strict";function t(){for(var e,t,l=0,a="",r=arguments.length;lt,"default",0,t])},109799,e=>{"use strict";var t=e.i(135214),l=e.i(764205),a=e.i(266027),r=e.i(912598);let i=(0,e.i(243652).createQueryKeys)("organizations");e.s(["useOrganization",0,e=>{let s=(0,r.useQueryClient)(),{accessToken:n}=(0,t.default)();return(0,a.useQuery)({queryKey:i.detail(e),enabled:!!(n&&e),queryFn:async()=>{if(!n||!e)throw Error("Missing auth or teamId");return(0,l.organizationInfoCall)(n,e)},initialData:()=>{if(!e)return;let t=s.getQueryData(i.list({}));return t?.find(t=>t.organization_id===e)}})},"useOrganizations",0,()=>{let{accessToken:e,userId:r,userRole:s}=(0,t.default)();return(0,a.useQuery)({queryKey:i.list({}),queryFn:async()=>await (0,l.organizationListCall)(e),enabled:!!(e&&r&&s)})}])},625901,e=>{"use strict";var t=e.i(266027),l=e.i(621482),a=e.i(243652),r=e.i(764205),i=e.i(135214);let s=(0,a.createQueryKeys)("models"),n=(0,a.createQueryKeys)("modelHub"),o=(0,a.createQueryKeys)("allProxyModels");(0,a.createQueryKeys)("selectedTeamModels");let d=(0,a.createQueryKeys)("infiniteModels");e.s(["useAllProxyModels",0,()=>{let{accessToken:e,userId:l,userRole:a}=(0,i.default)();return(0,t.useQuery)({queryKey:o.list({}),queryFn:async()=>await (0,r.modelAvailableCall)(e,l,a,!0,null,!0,!1,"expand"),enabled:!!(e&&l&&a)})},"useInfiniteModelInfo",0,(e=50,t)=>{let{accessToken:a,userId:s,userRole:n}=(0,i.default)();return(0,l.useInfiniteQuery)({queryKey:d.list({filters:{...s&&{userId:s},...n&&{userRole:n},size:e,...t&&{search:t}}}),queryFn:async({pageParam:l})=>await (0,r.modelInfoCall)(a,s,n,l,e,t),initialPageParam:1,getNextPageParam:e=>{if(e.current_page{let{accessToken:e}=(0,i.default)();return(0,t.useQuery)({queryKey:n.list({}),queryFn:async()=>await (0,r.modelHubCall)(e),enabled:!!e})},"useModelsInfo",0,(e=1,l=50,a,n,o,d,c)=>{let{accessToken:u,userId:m,userRole:g}=(0,i.default)();return(0,t.useQuery)({queryKey:s.list({filters:{...m&&{userId:m},...g&&{userRole:g},page:e,size:l,...a&&{search:a},...n&&{modelId:n},...o&&{teamId:o},...d&&{sortBy:d},...c&&{sortOrder:c}}}),queryFn:async()=>await (0,r.modelInfoCall)(u,m,g,e,l,a,n,o,d,c),enabled:!!(u&&m&&g)})}])}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/17741b7a77c20f1b.js b/litellm/proxy/_experimental/out/_next/static/chunks/17741b7a77c20f1b.js new file mode 100644 index 00000000000..de3b88089a9 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/17741b7a77c20f1b.js @@ -0,0 +1 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,860585,e=>{"use strict";var s=e.i(843476),t=e.i(199133);let{Option:l}=t.Select;e.s(["default",0,({value:e,onChange:a,className:r="",style:i={}})=>(0,s.jsxs)(t.Select,{style:{width:"100%",...i},value:e||void 0,onChange:a,className:r,placeholder:"n/a",allowClear:!0,children:[(0,s.jsx)(l,{value:"24h",children:"daily"}),(0,s.jsx)(l,{value:"7d",children:"weekly"}),(0,s.jsx)(l,{value:"30d",children:"monthly"})]}),"getBudgetDurationLabel",0,e=>e?({"24h":"daily","7d":"weekly","30d":"monthly"})[e]||e:"Not set"])},355619,e=>{"use strict";var s=e.i(764205);let t=async(e,t,l)=>{try{if(null===e||null===t)return;if(null!==l){let a=(await (0,s.modelAvailableCall)(l,e,t,!0,null,!0)).data.map(e=>e.id),r=[],i=[];return a.forEach(e=>{e.endsWith("/*")?r.push(e):i.push(e)}),[...r,...i]}}catch(e){console.error("Error fetching user models:",e)}};e.s(["fetchAvailableModelsForTeamOrKey",0,t,"getModelDisplayName",0,e=>{if("all-proxy-models"===e)return"All Proxy Models";if(e.endsWith("/*")){let s=e.replace("/*","");return`All ${s} models`}return e},"unfurlWildcardModelsInList",0,(e,s)=>{let t=[],l=[];return console.log("teamModels",e),console.log("allModels",s),e.forEach(e=>{if(e.endsWith("/*")){let a=e.replace("/*",""),r=s.filter(e=>e.startsWith(a+"/"));l.push(...r),t.push(e)}else l.push(e)}),[...t,...l].filter((e,s,t)=>t.indexOf(e)===s)}])},213205,e=>{"use strict";e.i(247167);var s=e.i(931067),t=e.i(271645);let l={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M678.3 642.4c24.2-13 51.9-20.4 81.4-20.4h.1c3 0 4.4-3.6 2.2-5.6a371.67 371.67 0 00-103.7-65.8c-.4-.2-.8-.3-1.2-.5C719.2 505 759.6 431.7 759.6 349c0-137-110.8-248-247.5-248S264.7 212 264.7 349c0 82.7 40.4 156 102.6 201.1-.4.2-.8.3-1.2.5-44.7 18.9-84.8 46-119.3 80.6a373.42 373.42 0 00-80.4 119.5A373.6 373.6 0 00137 888.8a8 8 0 008 8.2h59.9c4.3 0 7.9-3.5 8-7.8 2-77.2 32.9-149.5 87.6-204.3C357 628.2 432.2 597 512.2 597c56.7 0 111.1 15.7 158 45.1a8.1 8.1 0 008.1.3zM512.2 521c-45.8 0-88.9-17.9-121.4-50.4A171.2 171.2 0 01340.5 349c0-45.9 17.9-89.1 50.3-121.6S466.3 177 512.2 177s88.9 17.9 121.4 50.4A171.2 171.2 0 01683.9 349c0 45.9-17.9 89.1-50.3 121.6C601.1 503.1 558 521 512.2 521zM880 759h-84v-84c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v84h-84c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h84v84c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8v-84h84c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8z"}}]},name:"user-add",theme:"outlined"};var a=e.i(9583),r=t.forwardRef(function(e,r){return t.createElement(a.default,(0,s.default)({},e,{ref:r,icon:l}))});e.s(["UserAddOutlined",0,r],213205)},285027,e=>{"use strict";e.i(247167);var s=e.i(931067),t=e.i(271645);let l={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"};var a=e.i(9583),r=t.forwardRef(function(e,r){return t.createElement(a.default,(0,s.default)({},e,{ref:r,icon:l}))});e.s(["WarningOutlined",0,r],285027)},447082,e=>{"use strict";var s=e.i(843476),t=e.i(271645),l=e.i(599724),a=e.i(464571),r=e.i(212931),i=e.i(291542),n=e.i(515831),d=e.i(898586),o=e.i(519756),c=e.i(737434),m=e.i(285027),u=e.i(993914),x=e.i(955135);e.i(247167);var h=e.i(931067);let p={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"};var f=e.i(9583),g=t.forwardRef(function(e,s){return t.createElement(f.default,(0,h.default)({},e,{ref:s,icon:p}))}),j=e.i(764205),y=e.i(59935),v=e.i(220508),b=e.i(964306);let w=t.forwardRef(function(e,s){return t.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:s},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"}))});var N=e.i(237016),_=e.i(727749);e.s(["default",0,({accessToken:e,teams:h,possibleUIRoles:p,onUsersCreated:f})=>{let[C,S]=(0,t.useState)(!1),[k,I]=(0,t.useState)([]),[T,U]=(0,t.useState)(!1),[V,O]=(0,t.useState)(null),[B,L]=(0,t.useState)(null),[M,F]=(0,t.useState)(null),[z,E]=(0,t.useState)(null),[P,A]=(0,t.useState)(null),[R,D]=(0,t.useState)("http://localhost:4000");(0,t.useEffect)(()=>{(async()=>{try{let s=await (0,j.getProxyUISettings)(e);A(s)}catch(e){console.error("Error fetching UI settings:",e)}})(),D(new URL("/",window.location.href).toString())},[e]);let $=async()=>{U(!0);let s=k.map(e=>({...e,status:"pending"}));I(s);let t=!1;for(let l=0;le.trim()).filter(Boolean),0===s.teams.length&&delete s.teams),a.models&&"string"==typeof a.models&&""!==a.models.trim()&&(s.models=a.models.split(",").map(e=>e.trim()).filter(Boolean),0===s.models.length&&delete s.models),a.max_budget&&""!==a.max_budget.toString().trim()){let e=parseFloat(a.max_budget.toString());!isNaN(e)&&e>0&&(s.max_budget=e)}a.budget_duration&&""!==a.budget_duration.trim()&&(s.budget_duration=a.budget_duration.trim()),a.metadata&&"string"==typeof a.metadata&&""!==a.metadata.trim()&&(s.metadata=a.metadata.trim()),console.log("Sending user data:",s);let r=await (0,j.userCreateCall)(e,null,s);if(console.log("Full response:",r),r&&(r.key||r.user_id)){t=!0,console.log("Success case triggered");let s=r.data?.user_id||r.user_id;try{if(P?.SSO_ENABLED){let e=new URL("/ui",R).toString();I(s=>s.map((s,t)=>t===l?{...s,status:"success",key:r.key||r.user_id,invitation_link:e}:s))}else{let t=await (0,j.invitationCreateCall)(e,s),a=new URL(`/ui?invitation_id=${t.id}`,R).toString();I(e=>e.map((e,s)=>s===l?{...e,status:"success",key:r.key||r.user_id,invitation_link:a}:e))}}catch(e){console.error("Error creating invitation:",e),I(e=>e.map((e,s)=>s===l?{...e,status:"success",key:r.key||r.user_id,error:"User created but failed to generate invitation link"}:e))}}else{console.log("Error case triggered");let e=r?.error||"Failed to create user";console.log("Error message:",e),I(s=>s.map((s,t)=>t===l?{...s,status:"failed",error:e}:s))}}catch(s){console.error("Caught error:",s);let e=s?.response?.data?.error||s?.message||String(s);I(s=>s.map((s,t)=>t===l?{...s,status:"failed",error:e}:s))}}U(!1),t&&f&&f()},W=[{title:"Row",dataIndex:"rowNumber",key:"rowNumber",width:80},{title:"Email",dataIndex:"user_email",key:"user_email"},{title:"Role",dataIndex:"user_role",key:"user_role"},{title:"Teams",dataIndex:"teams",key:"teams"},{title:"Budget",dataIndex:"max_budget",key:"max_budget"},{title:"Status",key:"status",render:(e,t)=>t.isValid?t.status&&"pending"!==t.status?"success"===t.status?(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(v.CheckCircleIcon,{className:"h-5 w-5 text-green-500 mr-2"}),(0,s.jsx)("span",{className:"text-green-500",children:"Success"})]}),t.invitation_link&&(0,s.jsx)("div",{className:"mt-1",children:(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)("span",{className:"text-xs text-gray-500 truncate max-w-[150px]",children:t.invitation_link}),(0,s.jsx)(N.CopyToClipboard,{text:t.invitation_link,onCopy:()=>_.default.success("Invitation link copied!"),children:(0,s.jsx)("button",{className:"ml-1 text-blue-500 text-xs hover:text-blue-700",children:"Copy"})})]})})]}):(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(b.XCircleIcon,{className:"h-5 w-5 text-red-500 mr-2"}),(0,s.jsx)("span",{className:"text-red-500",children:"Failed"})]}),t.error&&(0,s.jsx)("span",{className:"text-sm text-red-500 ml-7",children:JSON.stringify(t.error)})]}):(0,s.jsx)("span",{className:"text-gray-500",children:"Pending"}):(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(b.XCircleIcon,{className:"h-5 w-5 text-red-500 mr-2"}),(0,s.jsx)("span",{className:"text-red-500",children:"Invalid"})]}),t.error&&(0,s.jsx)("span",{className:"text-sm text-red-500 ml-7",children:t.error})]})}];return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(a.Button,{type:"primary",className:"mb-0",onClick:()=>S(!0),children:"+ Bulk Invite Users"}),(0,s.jsx)(r.Modal,{title:"Bulk Invite Users",open:C,width:800,onCancel:()=>S(!1),bodyStyle:{maxHeight:"70vh",overflow:"auto"},footer:null,children:(0,s.jsx)("div",{className:"flex flex-col",children:0===k.length?(0,s.jsxs)("div",{className:"mb-6",children:[(0,s.jsxs)("div",{className:"flex items-center mb-4",children:[(0,s.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"1"}),(0,s.jsx)("h3",{className:"text-lg font-medium",children:"Download and fill the template"})]}),(0,s.jsxs)("div",{className:"ml-11 mb-6",children:[(0,s.jsx)("p",{className:"mb-4",children:"Add multiple users at once by following these steps:"}),(0,s.jsxs)("ol",{className:"list-decimal list-inside space-y-2 ml-2 mb-4",children:[(0,s.jsx)("li",{children:"Download our CSV template"}),(0,s.jsx)("li",{children:"Add your users' information to the spreadsheet"}),(0,s.jsx)("li",{children:"Save the file and upload it here"}),(0,s.jsx)("li",{children:"After creation, download the results file containing the Virtual Keys for each user"})]}),(0,s.jsxs)("div",{className:"bg-gray-50 p-4 rounded-md border border-gray-200 mb-4",children:[(0,s.jsx)("h4",{className:"font-medium mb-2",children:"Template Column Names"}),(0,s.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-red-500 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"user_email"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:"User's email address (required)"})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-red-500 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"user_role"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'User\'s role (one of: "proxy_admin", "proxy_admin_viewer", "internal_user", "internal_user_viewer")'})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"teams"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'Comma-separated team IDs (e.g., "team-1,team-2")'})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"max_budget"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'Maximum budget as a number (e.g., "100")'})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"budget_duration"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'Budget reset period (e.g., "30d", "1mo")'})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"models"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'Comma-separated allowed models (e.g., "gpt-3.5-turbo,gpt-4")'})]})]})]})]}),(0,s.jsx)(a.Button,{type:"primary",size:"large",className:"w-full md:w-auto",icon:(0,s.jsx)(c.DownloadOutlined,{}),children:"Download CSV Template"})]}),(0,s.jsxs)("div",{className:"flex items-center mb-4",children:[(0,s.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"2"}),(0,s.jsx)("h3",{className:"text-lg font-medium",children:"Upload your completed CSV"})]}),(0,s.jsxs)("div",{className:"ml-11",children:[z?(0,s.jsxs)("div",{className:`mb-4 p-4 rounded-md border ${M?"bg-red-50 border-red-200":"bg-blue-50 border-blue-200"}`,children:[(0,s.jsxs)("div",{className:"flex items-center justify-between",children:[(0,s.jsxs)("div",{className:"flex items-center",children:[M?(0,s.jsx)(g,{className:"text-red-500 text-xl mr-3"}):(0,s.jsx)(u.FileTextOutlined,{className:"text-blue-500 text-xl mr-3"}),(0,s.jsxs)("div",{children:[(0,s.jsx)(d.Typography.Text,{strong:!0,className:M?"text-red-800":"text-blue-800",children:z.name}),(0,s.jsxs)(d.Typography.Text,{className:`block text-xs ${M?"text-red-600":"text-blue-600"}`,children:[(z.size/1024).toFixed(1)," KB • ",new Date().toLocaleDateString()]})]})]}),(0,s.jsx)(a.Button,{size:"small",onClick:()=>{E(null),I([]),O(null),L(null),F(null)},className:"flex items-center",icon:(0,s.jsx)(x.DeleteOutlined,{}),children:"Remove"})]}),M?(0,s.jsxs)("div",{className:"mt-3 text-red-600 text-sm flex items-start",children:[(0,s.jsx)(m.WarningOutlined,{className:"mr-2 mt-0.5"}),(0,s.jsx)("span",{children:M})]}):!B&&(0,s.jsxs)("div",{className:"mt-3 flex items-center",children:[(0,s.jsx)("div",{className:"w-full bg-gray-200 rounded-full h-1.5",children:(0,s.jsx)("div",{className:"bg-blue-500 h-1.5 rounded-full w-full animate-pulse"})}),(0,s.jsx)("span",{className:"ml-2 text-xs text-blue-600",children:"Processing..."})]})]}):(0,s.jsx)(n.Upload,{beforeUpload:e=>((O(null),L(null),F(null),E(e),"text/csv"===e.type||e.name.endsWith(".csv"))?e.size>5242880?F(`File is too large (${(e.size/1048576).toFixed(1)} MB). Please upload a CSV file smaller than 5MB.`):y.default.parse(e,{complete:e=>{if(!e.data||0===e.data.length){L("The CSV file appears to be empty. Please upload a file with data."),I([]);return}if(1===e.data.length){L("The CSV file only contains headers but no user data. Please add user data to your CSV."),I([]);return}let s=e.data[0];if(0===s.length||1===s.length&&""===s[0]){L("The CSV file doesn't contain any column headers. Please make sure your CSV has headers."),I([]);return}let t=["user_email","user_role"].filter(e=>!s.includes(e));if(t.length>0){L(`Your CSV is missing these required columns: ${t.join(", ")}. Please add these columns to your CSV file.`),I([]);return}try{let t=e.data.slice(1).map((e,t)=>{if(0===e.length||1===e.length&&""===e[0])return null;if(e.length=parseFloat(l.max_budget.toString())&&a.push("Max budget must be greater than 0")),l.budget_duration&&!l.budget_duration.match(/^\d+[dhmwy]$|^\d+mo$/)&&a.push(`Invalid budget duration format "${l.budget_duration}". Use format like "30d", "1mo", "2w", "6h"`),l.teams&&"string"==typeof l.teams&&h&&h.length>0){let e=h.map(e=>e.team_id),s=l.teams.split(",").map(e=>e.trim()).filter(s=>!e.includes(s));s.length>0&&a.push(`Unknown team(s): ${s.join(", ")}`)}return a.length>0&&(l.isValid=!1,l.error=a.join(", ")),l}).filter(Boolean),l=t.filter(e=>e.isValid);I(t),0===t.length?L("No valid data rows found in the CSV file. Please check your file format."):0===l.length?O("No valid users found in the CSV. Please check the errors below and fix your CSV file."):l.length{O(`Failed to parse CSV file: ${e.message}`),I([])},header:!1}):(F(`Invalid file type: ${e.name}. Please upload a CSV file (.csv extension).`),_.default.fromBackend("Invalid file type. Please upload a CSV file.")),!1),accept:".csv",maxCount:1,showUploadList:!1,children:(0,s.jsxs)("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-blue-500 transition-colors cursor-pointer",children:[(0,s.jsx)(o.UploadOutlined,{className:"text-3xl text-gray-400 mb-2"}),(0,s.jsx)("p",{className:"mb-1",children:"Drag and drop your CSV file here"}),(0,s.jsx)("p",{className:"text-sm text-gray-500 mb-3",children:"or"}),(0,s.jsx)(a.Button,{size:"small",children:"Browse files"}),(0,s.jsx)("p",{className:"text-xs text-gray-500 mt-4",children:"Only CSV files (.csv) are supported"})]})}),B&&(0,s.jsx)("div",{className:"mb-4 p-4 bg-yellow-50 border border-yellow-200 rounded-md",children:(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)(w,{className:"h-5 w-5 text-yellow-500 mr-2 mt-0.5"}),(0,s.jsxs)("div",{children:[(0,s.jsx)(d.Typography.Text,{strong:!0,className:"text-yellow-800",children:"CSV Structure Error"}),(0,s.jsx)(d.Typography.Paragraph,{className:"text-yellow-700 mt-1 mb-0",children:B}),(0,s.jsx)(d.Typography.Paragraph,{className:"text-yellow-700 mt-2 mb-0",children:"Please download our template and ensure your CSV follows the required format."})]})]})})]})]}):(0,s.jsxs)("div",{className:"mb-6",children:[(0,s.jsxs)("div",{className:"flex items-center mb-4",children:[(0,s.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"3"}),(0,s.jsx)("h3",{className:"text-lg font-medium",children:k.some(e=>"success"===e.status||"failed"===e.status)?"User Creation Results":"Review and create users"})]}),V&&(0,s.jsx)("div",{className:"ml-11 mb-4 p-4 bg-red-50 border border-red-200 rounded-md",children:(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)(m.WarningOutlined,{className:"text-red-500 mr-2 mt-1"}),(0,s.jsxs)("div",{children:[(0,s.jsx)(l.Text,{className:"text-red-600 font-medium",children:V}),k.some(e=>!e.isValid)&&(0,s.jsxs)("ul",{className:"mt-2 list-disc list-inside text-red-600 text-sm",children:[(0,s.jsx)("li",{children:"Check the table below for specific errors in each row"}),(0,s.jsx)("li",{children:"Common issues include invalid email formats, missing required fields, or incorrect role values"}),(0,s.jsx)("li",{children:"Fix these issues in your CSV file and upload again"})]})]})]})}),(0,s.jsxs)("div",{className:"ml-11",children:[(0,s.jsxs)("div",{className:"flex justify-between items-center mb-3",children:[(0,s.jsx)("div",{className:"flex items-center",children:k.some(e=>"success"===e.status||"failed"===e.status)?(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(l.Text,{className:"text-lg font-medium mr-3",children:"Creation Summary"}),(0,s.jsxs)(l.Text,{className:"text-sm bg-green-100 text-green-800 px-2 py-1 rounded mr-2",children:[k.filter(e=>"success"===e.status).length," Successful"]}),k.some(e=>"failed"===e.status)&&(0,s.jsxs)(l.Text,{className:"text-sm bg-red-100 text-red-800 px-2 py-1 rounded",children:[k.filter(e=>"failed"===e.status).length," Failed"]})]}):(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(l.Text,{className:"text-lg font-medium mr-3",children:"User Preview"}),(0,s.jsxs)(l.Text,{className:"text-sm bg-blue-100 text-blue-800 px-2 py-1 rounded",children:[k.filter(e=>e.isValid).length," of ",k.length," users valid"]})]})}),!k.some(e=>"success"===e.status||"failed"===e.status)&&(0,s.jsxs)("div",{className:"flex space-x-3",children:[(0,s.jsx)(a.Button,{onClick:()=>{I([]),O(null)},children:"Back"}),(0,s.jsx)(a.Button,{type:"primary",onClick:$,disabled:0===k.filter(e=>e.isValid).length||T,children:T?"Creating...":`Create ${k.filter(e=>e.isValid).length} Users`})]})]}),k.some(e=>"success"===e.status)&&(0,s.jsx)("div",{className:"mb-4 p-4 bg-blue-50 border border-blue-200 rounded-md",children:(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"mr-3 mt-1",children:(0,s.jsx)(v.CheckCircleIcon,{className:"h-5 w-5 text-blue-500"})}),(0,s.jsxs)("div",{children:[(0,s.jsx)(l.Text,{className:"font-medium text-blue-800",children:"User creation complete"}),(0,s.jsxs)(l.Text,{className:"block text-sm text-blue-700 mt-1",children:[(0,s.jsx)("span",{className:"font-medium",children:"Next step:"})," Download the credentials file containing Virtual Keys and invitation links. Users will need these Virtual Keys to make LLM requests through LiteLLM."]})]})]})}),(0,s.jsx)(i.Table,{dataSource:k,columns:W,size:"small",pagination:{pageSize:5},scroll:{y:300},rowClassName:e=>e.isValid?"":"bg-red-50"}),!k.some(e=>"success"===e.status||"failed"===e.status)&&(0,s.jsxs)("div",{className:"flex justify-end mt-4",children:[(0,s.jsx)(a.Button,{onClick:()=>{I([]),O(null)},className:"mr-3",children:"Back"}),(0,s.jsx)(a.Button,{type:"primary",onClick:$,disabled:0===k.filter(e=>e.isValid).length||T,children:T?"Creating...":`Create ${k.filter(e=>e.isValid).length} Users`})]}),k.some(e=>"success"===e.status||"failed"===e.status)&&(0,s.jsxs)("div",{className:"flex justify-end mt-4",children:[(0,s.jsx)(a.Button,{onClick:()=>{I([]),O(null)},className:"mr-3",children:"Start New Bulk Import"}),(0,s.jsx)(a.Button,{type:"primary",onClick:()=>{let e=k.map(e=>({user_email:e.user_email,user_role:e.user_role,status:e.status,key:e.key||"",invitation_link:e.invitation_link||"",error:e.error||""})),s=new Blob([y.default.unparse(e)],{type:"text/csv"}),t=window.URL.createObjectURL(s),l=document.createElement("a");l.href=t,l.download="bulk_users_results.csv",document.body.appendChild(l),l.click(),document.body.removeChild(l),window.URL.revokeObjectURL(t)},icon:(0,s.jsx)(c.DownloadOutlined,{}),children:"Download User Credentials"})]})]})]})})})]})}],447082)},663435,e=>{"use strict";var s=e.i(843476),t=e.i(199133);e.s(["default",0,({teams:e,value:l,onChange:a,disabled:r,loading:i})=>(0,s.jsx)(t.Select,{showSearch:!0,placeholder:"Search or select a team",value:l,onChange:a,disabled:r,loading:i,allowClear:!0,filterOption:(s,t)=>{if(!t)return!1;let l=e?.find(e=>e.team_id===t.key);if(!l)return!1;let a=s.toLowerCase().trim(),r=(l.team_alias||"").toLowerCase(),i=(l.team_id||"").toLowerCase();return r.includes(a)||i.includes(a)},optionFilterProp:"children",children:e?.map(e=>(0,s.jsxs)(t.Select.Option,{value:e.team_id,children:[(0,s.jsx)("span",{className:"font-medium",children:e.team_alias})," ",(0,s.jsxs)("span",{className:"text-gray-500",children:["(",e.team_id,")"]})]},e.team_id))})])},371455,172372,e=>{"use strict";var s=e.i(843476),t=e.i(827252),l=e.i(213205),a=e.i(912598),r=e.i(109799),i=e.i(677667),n=e.i(130643),d=e.i(898667),o=e.i(35983),c=e.i(779241),m=e.i(560445),u=e.i(464571),x=e.i(808613),h=e.i(311451),p=e.i(212931),f=e.i(199133),g=e.i(770914),j=e.i(592968),y=e.i(898586),v=e.i(271645),b=e.i(447082),w=e.i(663435),N=e.i(355619),_=e.i(727749),C=e.i(764205),S=e.i(237016),k=e.i(599724);function I({isInvitationLinkModalVisible:e,setIsInvitationLinkModalVisible:t,baseUrl:l,invitationLinkData:a,modalType:r="invitation"}){let{Title:i,Paragraph:n}=y.Typography,d=()=>{if(!l)return"";let e=new URL(l).pathname,s=e&&"/"!==e?`${e}/ui`:"ui";if(a?.has_user_setup_sso)return new URL(s,l).toString();let t=`${s}?invitation_id=${a?.id}`;return"resetPassword"===r&&(t+="&action=reset_password"),new URL(t,l).toString()};return(0,s.jsxs)(p.Modal,{title:"invitation"===r?"Invitation Link":"Reset Password Link",open:e,width:800,footer:null,onOk:()=>{t(!1)},onCancel:()=>{t(!1)},children:[(0,s.jsx)(n,{children:"invitation"===r?"Copy and send the generated link to onboard this user to the proxy.":"Copy and send the generated link to the user to reset their password."}),(0,s.jsxs)("div",{className:"flex justify-between pt-5 pb-2",children:[(0,s.jsx)(k.Text,{className:"text-base",children:"User ID"}),(0,s.jsx)(k.Text,{children:a?.user_id})]}),(0,s.jsxs)("div",{className:"flex justify-between pt-5 pb-2",children:[(0,s.jsx)(k.Text,{children:"invitation"===r?"Invitation Link":"Reset Password Link"}),(0,s.jsx)(k.Text,{children:(0,s.jsx)(k.Text,{children:d()})})]}),(0,s.jsx)("div",{className:"flex justify-end mt-5",children:(0,s.jsx)(S.CopyToClipboard,{text:d(),onCopy:()=>_.default.success("Copied!"),children:(0,s.jsx)(u.Button,{type:"primary",children:"invitation"===r?"Copy invitation link":"Copy password reset link"})})})]})}e.s(["default",()=>I],172372);let{Option:T}=f.Select,{Text:U,Link:V,Title:O}=y.Typography;e.s(["CreateUserButton",0,({userID:e,accessToken:y,teams:S,possibleUIRoles:k,onUserCreated:O,isEmbedded:B=!1})=>{let L=(0,a.useQueryClient)(),[M,F]=(0,v.useState)(null),[z]=x.Form.useForm(),[E,P]=(0,v.useState)(!1),[A,R]=(0,v.useState)(!1),[D,$]=(0,v.useState)([]),[W,K]=(0,v.useState)(!1),[q,H]=(0,v.useState)(null),[G,J]=(0,v.useState)(null),{data:Q=[]}=(0,r.useOrganizations)(),X=(0,v.useMemo)(()=>{let e=Q.flatMap(e=>e.teams||[]);return e.length>0?e:S||[]},[Q,S]);(0,v.useEffect)(()=>{let s=async()=>{try{let s=await (0,C.modelAvailableCall)(y,e,"any"),t=[];for(let e=0;e{try{_.default.info("Making API Call"),B||P(!0),s.models&&0!==s.models.length||"proxy_admin"===s.user_role||(s.models=["no-default-models"]),s.organization_ids&&(s.organizations=s.organization_ids,delete s.organization_ids);let t=await (0,C.userCreateCall)(y,null,s);await L.invalidateQueries({queryKey:["userList"]}),R(!0);let l=t.data?.user_id||t.user_id;if(O&&B){O(l),z.resetFields();return}if(M?.SSO_ENABLED){let s={id:"u">typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){let s=16*Math.random()|0;return("x"==e?s:3&s|8).toString(16)}),user_id:l,is_accepted:!1,accepted_at:null,expires_at:new Date(Date.now()+6048e5),created_at:new Date,created_by:e,updated_at:new Date,updated_by:e,has_user_setup_sso:!0};H(s),K(!0)}else(0,C.invitationCreateCall)(y,l).then(e=>{e.has_user_setup_sso=!1,H(e),K(!0)});_.default.success("API user Created"),z.resetFields(),localStorage.removeItem("userData"+e)}catch(s){let e=s.response?.data?.detail||s?.message||"Error creating the user";_.default.fromBackend(e),console.error("Error creating the user:",s)}};return B?(0,s.jsxs)(x.Form,{form:z,onFinish:Y,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,s.jsx)(m.Alert,{message:"Email invitations",description:(0,s.jsxs)(s.Fragment,{children:["New users receive an email invite only when an email integration (SMTP, Resend, or SendGrid) is configured."," ",(0,s.jsx)(V,{href:"https://docs.litellm.ai/docs/proxy/email",target:"_blank",children:"Learn how to set up email notifications"})]}),type:"info",showIcon:!0,className:"mb-4"}),(0,s.jsx)(x.Form.Item,{label:"User Email",name:"user_email",children:(0,s.jsx)(c.TextInput,{placeholder:""})}),(0,s.jsx)(x.Form.Item,{label:"User Role",name:"user_role",children:(0,s.jsx)(f.Select,{children:k&&Object.entries(k).map(([e,{ui_label:t,description:l}])=>(0,s.jsx)(o.SelectItem,{value:e,title:t,children:(0,s.jsxs)("div",{className:"flex",children:[t," ",(0,s.jsx)(U,{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:l})]})},e))})}),(0,s.jsx)(x.Form.Item,{label:"Team",name:"team_id",children:(0,s.jsx)(f.Select,{placeholder:"Select Team",style:{width:"100%"},children:(0,s.jsx)(w.default,{teams:X})})}),(0,s.jsx)(x.Form.Item,{label:"Metadata",name:"metadata",children:(0,s.jsx)(h.Input.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,s.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,s.jsx)(u.Button,{htmlType:"submit",children:"Create User"})})]}):(0,s.jsxs)("div",{className:"flex gap-2",children:[(0,s.jsx)(u.Button,{type:"primary",className:"mb-0",onClick:()=>P(!0),children:"+ Invite User"}),(0,s.jsx)(b.default,{accessToken:y,teams:S,possibleUIRoles:k}),(0,s.jsxs)(p.Modal,{title:"Invite User",open:E,width:800,footer:null,onOk:()=>{P(!1),z.resetFields()},onCancel:()=>{P(!1),R(!1),z.resetFields()},children:[(0,s.jsxs)(g.Space,{direction:"vertical",size:"middle",children:[(0,s.jsx)(U,{className:"mb-1",children:"Create a User who can own keys"}),(0,s.jsx)(m.Alert,{message:"Email invitations",description:(0,s.jsxs)(s.Fragment,{children:["New users receive an email invite only when an email integration (SMTP, Resend, or SendGrid) is configured."," ",(0,s.jsx)(V,{href:"https://docs.litellm.ai/docs/proxy/email",target:"_blank",children:"Learn how to set up email notifications"})]}),type:"info",showIcon:!0,className:"mb-4"})]}),(0,s.jsxs)(x.Form,{form:z,onFinish:Y,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,s.jsx)(x.Form.Item,{label:"User Email",name:"user_email",children:(0,s.jsx)(h.Input,{})}),(0,s.jsx)(x.Form.Item,{label:(0,s.jsxs)("span",{children:["Global Proxy Role"," ",(0,s.jsx)(j.Tooltip,{title:"This role is independent of any team/org specific roles. Configure Team / Organization Admins in the Settings",children:(0,s.jsx)(t.InfoCircleOutlined,{})})]}),name:"user_role",children:(0,s.jsx)(f.Select,{children:k&&Object.entries(k).map(([e,{ui_label:t,description:l}])=>(0,s.jsxs)(o.SelectItem,{value:e,title:t,children:[(0,s.jsx)(U,{children:t}),(0,s.jsxs)(U,{type:"secondary",children:[" - ",l]})]},e))})}),(0,s.jsx)(x.Form.Item,{label:"Team",className:"gap-2",name:"team_id",help:"If selected, user will be added as a 'user' role to the team.",children:(0,s.jsx)(w.default,{teams:X})}),(0,s.jsx)(x.Form.Item,{label:"Organization",name:"organization_ids",help:"The user will be added to the selected organization(s).",children:(0,s.jsx)(f.Select,{mode:"multiple",placeholder:"Select Organization",style:{width:"100%"},children:Q.map(e=>(0,s.jsxs)(T,{value:e.organization_id,children:[e.organization_alias," (",e.organization_id,")"]},e.organization_id))})}),(0,s.jsx)(x.Form.Item,{label:"Metadata",name:"metadata",children:(0,s.jsx)(h.Input.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,s.jsxs)(i.Accordion,{children:[(0,s.jsx)(d.AccordionHeader,{children:(0,s.jsx)(U,{strong:!0,children:"Personal Key Creation"})}),(0,s.jsx)(n.AccordionBody,{children:(0,s.jsx)(x.Form.Item,{className:"gap-2",label:(0,s.jsxs)("span",{children:["Models"," ",(0,s.jsx)(j.Tooltip,{title:"Models user has access to, outside of team scope.",children:(0,s.jsx)(t.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"models",help:"Models user has access to, outside of team scope.",children:(0,s.jsxs)(f.Select,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[(0,s.jsx)(f.Select.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),(0,s.jsx)(f.Select.Option,{value:"no-default-models",children:"No Default Models"},"no-default-models"),D.map(e=>(0,s.jsx)(f.Select.Option,{value:e,children:(0,N.getModelDisplayName)(e)},e))]})})})]}),(0,s.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,s.jsx)(u.Button,{type:"primary",icon:(0,s.jsx)(l.UserAddOutlined,{}),htmlType:"submit",children:"Invite User"})})]})]}),A&&(0,s.jsx)(I,{isInvitationLinkModalVisible:W,setIsInvitationLinkModalVisible:K,baseUrl:G||"",invitationLinkData:q})]})}],371455)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/179f4b987bc9083f.js b/litellm/proxy/_experimental/out/_next/static/chunks/179f4b987bc9083f.js new file mode 100644 index 00000000000..46e69247adc --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/179f4b987bc9083f.js @@ -0,0 +1,9 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,677667,674175,886148,543086,e=>{"use strict";let t,r;var a,l=e.i(290571),n=e.i(429427),o=e.i(371330),s=e.i(271645),i=e.i(394487),d=e.i(914189),c=e.i(144279),u=e.i(294316),m=e.i(83733);let g=(0,s.createContext)(()=>{});function f({value:e,children:t}){return s.default.createElement(g.Provider,{value:e},t)}e.s(["CloseProvider",()=>f],674175);var p=e.i(233137),b=e.i(233538),h=e.i(397701),v=e.i(402155),C=e.i(700020);let k=null!=(a=s.default.startTransition)?a:function(e){e()};var x=e.i(998348),w=((t=w||{})[t.Open=0]="Open",t[t.Closed=1]="Closed",t),E=((r=E||{})[r.ToggleDisclosure=0]="ToggleDisclosure",r[r.CloseDisclosure=1]="CloseDisclosure",r[r.SetButtonId=2]="SetButtonId",r[r.SetPanelId=3]="SetPanelId",r[r.SetButtonElement=4]="SetButtonElement",r[r.SetPanelElement=5]="SetPanelElement",r);let y={0:e=>({...e,disclosureState:(0,h.match)(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}},N=(0,s.createContext)(null);function T(e){let t=(0,s.useContext)(N);if(null===t){let t=Error(`<${e} /> is missing a parent component.`);throw Error.captureStackTrace&&Error.captureStackTrace(t,T),t}return t}N.displayName="DisclosureContext";let O=(0,s.createContext)(null);O.displayName="DisclosureAPIContext";let $=(0,s.createContext)(null);function j(e,t){return(0,h.match)(t.type,y,e,t)}$.displayName="DisclosurePanelContext";let S=s.Fragment,P=C.RenderFeatures.RenderStrategy|C.RenderFeatures.Static,R=Object.assign((0,C.forwardRefWithAs)(function(e,t){let{defaultOpen:r=!1,...a}=e,l=(0,s.useRef)(null),n=(0,u.useSyncRefs)(t,(0,u.optionalRef)(e=>{l.current=e},void 0===e.as||e.as===s.Fragment)),o=(0,s.useReducer)(j,{disclosureState:+!r,buttonElement:null,panelElement:null,buttonId:null,panelId:null}),[{disclosureState:i,buttonId:c},m]=o,g=(0,d.useEvent)(e=>{m({type:1});let t=(0,v.getOwnerDocument)(l);if(!t||!c)return;let r=e?e instanceof HTMLElement?e:e.current instanceof HTMLElement?e.current:t.getElementById(c):t.getElementById(c);null==r||r.focus()}),b=(0,s.useMemo)(()=>({close:g}),[g]),k=(0,s.useMemo)(()=>({open:0===i,close:g}),[i,g]),x=(0,C.useRender)();return s.default.createElement(N.Provider,{value:o},s.default.createElement(O.Provider,{value:b},s.default.createElement(f,{value:g},s.default.createElement(p.OpenClosedProvider,{value:(0,h.match)(i,{0:p.State.Open,1:p.State.Closed})},x({ourProps:{ref:n},theirProps:a,slot:k,defaultTag:S,name:"Disclosure"})))))}),{Button:(0,C.forwardRefWithAs)(function(e,t){let r=(0,s.useId)(),{id:a=`headlessui-disclosure-button-${r}`,disabled:l=!1,autoFocus:m=!1,...g}=e,[f,p]=T("Disclosure.Button"),h=(0,s.useContext)($),v=null!==h&&h===f.panelId,k=(0,s.useRef)(null),w=(0,u.useSyncRefs)(k,t,(0,d.useEvent)(e=>{if(!v)return p({type:4,element:e})}));(0,s.useEffect)(()=>{if(!v)return p({type:2,buttonId:a}),()=>{p({type:2,buttonId:null})}},[a,p,v]);let E=(0,d.useEvent)(e=>{var t;if(v){if(1===f.disclosureState)return;switch(e.key){case x.Keys.Space:case x.Keys.Enter:e.preventDefault(),e.stopPropagation(),p({type:0}),null==(t=f.buttonElement)||t.focus()}}else switch(e.key){case x.Keys.Space:case x.Keys.Enter:e.preventDefault(),e.stopPropagation(),p({type:0})}}),y=(0,d.useEvent)(e=>{e.key===x.Keys.Space&&e.preventDefault()}),N=(0,d.useEvent)(e=>{var t;(0,b.isDisabledReactIssue7711)(e.currentTarget)||l||(v?(p({type:0}),null==(t=f.buttonElement)||t.focus()):p({type:0}))}),{isFocusVisible:O,focusProps:j}=(0,n.useFocusRing)({autoFocus:m}),{isHovered:S,hoverProps:P}=(0,o.useHover)({isDisabled:l}),{pressed:R,pressProps:M}=(0,i.useActivePress)({disabled:l}),B=(0,s.useMemo)(()=>({open:0===f.disclosureState,hover:S,active:R,disabled:l,focus:O,autofocus:m}),[f,S,R,O,l,m]),I=(0,c.useResolveButtonType)(e,f.buttonElement),A=v?(0,C.mergeProps)({ref:w,type:I,disabled:l||void 0,autoFocus:m,onKeyDown:E,onClick:N},j,P,M):(0,C.mergeProps)({ref:w,id:a,type:I,"aria-expanded":0===f.disclosureState,"aria-controls":f.panelElement?f.panelId:void 0,disabled:l||void 0,autoFocus:m,onKeyDown:E,onKeyUp:y,onClick:N},j,P,M);return(0,C.useRender)()({ourProps:A,theirProps:g,slot:B,defaultTag:"button",name:"Disclosure.Button"})}),Panel:(0,C.forwardRefWithAs)(function(e,t){let r=(0,s.useId)(),{id:a=`headlessui-disclosure-panel-${r}`,transition:l=!1,...n}=e,[o,i]=T("Disclosure.Panel"),{close:c}=function e(t){let r=(0,s.useContext)(O);if(null===r){let r=Error(`<${t} /> is missing a parent component.`);throw Error.captureStackTrace&&Error.captureStackTrace(r,e),r}return r}("Disclosure.Panel"),[g,f]=(0,s.useState)(null),b=(0,u.useSyncRefs)(t,(0,d.useEvent)(e=>{k(()=>i({type:5,element:e}))}),f);(0,s.useEffect)(()=>(i({type:3,panelId:a}),()=>{i({type:3,panelId:null})}),[a,i]);let h=(0,p.useOpenClosed)(),[v,x]=(0,m.useTransition)(l,g,null!==h?(h&p.State.Open)===p.State.Open:0===o.disclosureState),w=(0,s.useMemo)(()=>({open:0===o.disclosureState,close:c}),[o.disclosureState,c]),E={ref:b,id:a,...(0,m.transitionDataAttributes)(x)},y=(0,C.useRender)();return s.default.createElement(p.ResetOpenClosedProvider,null,s.default.createElement($.Provider,{value:o.panelId},y({ourProps:E,theirProps:n,slot:w,defaultTag:"div",features:P,visible:v,name:"Disclosure.Panel"})))})});e.s(["Disclosure",()=>R],886148);let M=(0,s.createContext)(void 0);var B=e.i(444755);let I=(0,e.i(673706).makeClassName)("Accordion"),A=(0,s.createContext)({isOpen:!1}),z=s.default.forwardRef((e,t)=>{var r;let{defaultOpen:a=!1,children:n,className:o}=e,i=(0,l.__rest)(e,["defaultOpen","children","className"]),d=null!=(r=(0,s.useContext)(M))?r:(0,B.tremorTwMerge)("rounded-tremor-default border");return s.default.createElement(R,Object.assign({as:"div",ref:t,className:(0,B.tremorTwMerge)(I("root"),"overflow-hidden","bg-tremor-background border-tremor-border","dark:bg-dark-tremor-background dark:border-dark-tremor-border",d,o),defaultOpen:a},i),({open:e})=>s.default.createElement(A.Provider,{value:{isOpen:e}},n))});z.displayName="Accordion",e.s(["OpenContext",()=>A,"default",()=>z],543086),e.s(["Accordion",()=>z],677667)},898667,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(886148);let l=e=>{var a=(0,t.__rest)(e,[]);return r.default.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"},a),r.default.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 n=e.i(543086),o=e.i(444755);let s=(0,e.i(673706).makeClassName)("AccordionHeader"),i=r.default.forwardRef((e,i)=>{let{children:d,className:c}=e,u=(0,t.__rest)(e,["children","className"]),{isOpen:m}=(0,r.useContext)(n.OpenContext);return r.default.createElement(a.Disclosure.Button,Object.assign({ref:i,className:(0,o.tremorTwMerge)(s("root"),"w-full flex items-center justify-between px-4 py-3","text-tremor-content-emphasis","dark:text-dark-tremor-content-emphasis",c)},u),r.default.createElement("div",{className:(0,o.tremorTwMerge)(s("children"),"flex flex-1 text-inherit mr-4")},d),r.default.createElement("div",null,r.default.createElement(l,{className:(0,o.tremorTwMerge)(s("arrowIcon"),"h-5 w-5 -mr-1","text-tremor-content-subtle","dark:text-dark-tremor-content-subtle",m?"transition-all":"transition-all -rotate-180")})))});i.displayName="AccordionHeader",e.s(["AccordionHeader",()=>i],898667)},130643,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(886148),l=e.i(444755);let n=(0,e.i(673706).makeClassName)("AccordionBody"),o=r.default.forwardRef((e,o)=>{let{children:s,className:i}=e,d=(0,t.__rest)(e,["children","className"]);return r.default.createElement(a.Disclosure.Panel,Object.assign({ref:o,className:(0,l.tremorTwMerge)(n("root"),"w-full text-tremor-default px-4 pb-3","text-tremor-content","dark:text-dark-tremor-content",i)},d),s)});o.displayName="AccordionBody",e.s(["AccordionBody",()=>o],130643)},599724,936325,e=>{"use strict";var t=e.i(95779),r=e.i(444755),a=e.i(673706),l=e.i(271645);let n=l.default.forwardRef((e,n)=>{let{color:o,className:s,children:i}=e;return l.default.createElement("p",{ref:n,className:(0,r.tremorTwMerge)("text-tremor-default",o?(0,a.getColorClassNames)(o,t.colorPalette.text).textColor:(0,r.tremorTwMerge)("text-tremor-content","dark:text-dark-tremor-content"),s)},i)});n.displayName="Text",e.s(["default",()=>n],936325),e.s(["Text",()=>n],599724)},994388,e=>{"use strict";var t=e.i(290571),r=e.i(829087),a=e.i(271645);let l=["preEnter","entering","entered","preExit","exiting","exited","unmounted"],n=e=>({_s:e,status:l[e],isEnter:e<3,isMounted:6!==e,isResolved:2===e||e>4}),o=e=>e?6:5,s=(e,t,r,a,l)=>{clearTimeout(a.current);let o=n(e);t(o),r.current=o,l&&l({current:o})};var i=e.i(480731),d=e.i(444755),c=e.i(673706);let u=e=>{var r=(0,t.__rest)(e,[]);return a.default.createElement("svg",Object.assign({},r,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"}),a.default.createElement("path",{fill:"none",d:"M0 0h24v24H0z"}),a.default.createElement("path",{d:"M18.364 5.636L16.95 7.05A7 7 0 1 0 19 12h2a9 9 0 1 1-2.636-6.364z"}))};var m=e.i(95779);let g={xs:{height:"h-4",width:"w-4"},sm:{height:"h-5",width:"w-5"},md:{height:"h-5",width:"w-5"},lg:{height:"h-6",width:"w-6"},xl:{height:"h-6",width:"w-6"}},f=(e,t)=>{switch(e){case"primary":return{textColor:t?(0,c.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",hoverTextColor:t?(0,c.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",bgColor:t?(0,c.getColorClassNames)(t,m.colorPalette.background).bgColor:"bg-tremor-brand dark:bg-dark-tremor-brand",hoverBgColor:t?(0,c.getColorClassNames)(t,m.colorPalette.darkBackground).hoverBgColor:"hover:bg-tremor-brand-emphasis dark:hover:bg-dark-tremor-brand-emphasis",borderColor:t?(0,c.getColorClassNames)(t,m.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",hoverBorderColor:t?(0,c.getColorClassNames)(t,m.colorPalette.darkBorder).hoverBorderColor:"hover:border-tremor-brand-emphasis dark:hover:border-dark-tremor-brand-emphasis"};case"secondary":return{textColor:t?(0,c.getColorClassNames)(t,m.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,c.getColorClassNames)(t,m.colorPalette.text).textColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,c.getColorClassNames)("transparent").bgColor,hoverBgColor:t?(0,d.tremorTwMerge)((0,c.getColorClassNames)(t,m.colorPalette.background).hoverBgColor,"hover:bg-opacity-20 dark:hover:bg-opacity-20"):"hover:bg-tremor-brand-faint dark:hover:bg-dark-tremor-brand-faint",borderColor:t?(0,c.getColorClassNames)(t,m.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand"};case"light":return{textColor:t?(0,c.getColorClassNames)(t,m.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,c.getColorClassNames)(t,m.colorPalette.darkText).hoverTextColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,c.getColorClassNames)("transparent").bgColor,borderColor:"",hoverBorderColor:""}}},p=(0,c.makeClassName)("Button"),b=({loading:e,iconSize:t,iconPosition:r,Icon:l,needMargin:n,transitionStatus:o})=>{let s=n?r===i.HorizontalPositions.Left?(0,d.tremorTwMerge)("-ml-1","mr-1.5"):(0,d.tremorTwMerge)("-mr-1","ml-1.5"):"",c=(0,d.tremorTwMerge)("w-0 h-0"),m={default:c,entering:c,entered:t,exiting:t,exited:c};return e?a.default.createElement(u,{className:(0,d.tremorTwMerge)(p("icon"),"animate-spin shrink-0",s,m.default,m[o]),style:{transition:"width 150ms"}}):a.default.createElement(l,{className:(0,d.tremorTwMerge)(p("icon"),"shrink-0",t,s)})},h=a.default.forwardRef((e,l)=>{let{icon:u,iconPosition:m=i.HorizontalPositions.Left,size:h=i.Sizes.SM,color:v,variant:C="primary",disabled:k,loading:x=!1,loadingText:w,children:E,tooltip:y,className:N}=e,T=(0,t.__rest)(e,["icon","iconPosition","size","color","variant","disabled","loading","loadingText","children","tooltip","className"]),O=x||k,$=void 0!==u||x,j=x&&w,S=!(!E&&!j),P=(0,d.tremorTwMerge)(g[h].height,g[h].width),R="light"!==C?(0,d.tremorTwMerge)("rounded-tremor-default border","shadow-tremor-input","dark:shadow-dark-tremor-input"):"",M=f(C,v),B=("light"!==C?{xs:{paddingX:"px-2.5",paddingY:"py-1.5",fontSize:"text-xs"},sm:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-sm"},md:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-md"},lg:{paddingX:"px-4",paddingY:"py-2.5",fontSize:"text-lg"},xl:{paddingX:"px-4",paddingY:"py-3",fontSize:"text-xl"}}:{xs:{paddingX:"",paddingY:"",fontSize:"text-xs"},sm:{paddingX:"",paddingY:"",fontSize:"text-sm"},md:{paddingX:"",paddingY:"",fontSize:"text-md"},lg:{paddingX:"",paddingY:"",fontSize:"text-lg"},xl:{paddingX:"",paddingY:"",fontSize:"text-xl"}})[h],{tooltipProps:I,getReferenceProps:A}=(0,r.useTooltip)(300),[z,H]=(({enter:e=!0,exit:t=!0,preEnter:r,preExit:l,timeout:i,initialEntered:d,mountOnEnter:c,unmountOnExit:u,onStateChange:m}={})=>{let[g,f]=(0,a.useState)(()=>n(d?2:o(c))),p=(0,a.useRef)(g),b=(0,a.useRef)(0),[h,v]="object"==typeof i?[i.enter,i.exit]:[i,i],C=(0,a.useCallback)(()=>{let e=((e,t)=>{switch(e){case 1:case 0:return 2;case 4:case 3:return o(t)}})(p.current._s,u);e&&s(e,f,p,b,m)},[m,u]);return[g,(0,a.useCallback)(a=>{let n=e=>{switch(s(e,f,p,b,m),e){case 1:h>=0&&(b.current=((...e)=>setTimeout(...e))(C,h));break;case 4:v>=0&&(b.current=((...e)=>setTimeout(...e))(C,v));break;case 0:case 3:b.current=((...e)=>setTimeout(...e))(()=>{isNaN(document.body.offsetTop)||n(e+1)},0)}},i=p.current.isEnter;"boolean"!=typeof a&&(a=!i),a?i||n(e?+!r:2):i&&n(t?l?3:4:o(u))},[C,m,e,t,r,l,h,v,u]),C]})({timeout:50});return(0,a.useEffect)(()=>{H(x)},[x]),a.default.createElement("button",Object.assign({ref:(0,c.mergeRefs)([l,I.refs.setReference]),className:(0,d.tremorTwMerge)(p("root"),"shrink-0 inline-flex justify-center items-center group font-medium outline-none",R,B.paddingX,B.paddingY,B.fontSize,M.textColor,M.bgColor,M.borderColor,M.hoverBorderColor,O?"opacity-50 cursor-not-allowed":(0,d.tremorTwMerge)(f(C,v).hoverTextColor,f(C,v).hoverBgColor,f(C,v).hoverBorderColor),N),disabled:O},A,T),a.default.createElement(r.default,Object.assign({text:y},I)),$&&m!==i.HorizontalPositions.Right?a.default.createElement(b,{loading:x,iconSize:P,iconPosition:m,Icon:u,transitionStatus:z.status,needMargin:S}):null,j||E?a.default.createElement("span",{className:(0,d.tremorTwMerge)(p("text"),"text-tremor-default whitespace-nowrap")},j?w:E):null,$&&m===i.HorizontalPositions.Right?a.default.createElement(b,{loading:x,iconSize:P,iconPosition:m,Icon:u,transitionStatus:z.status,needMargin:S}):null)});h.displayName="Button",e.s(["Button",()=>h],994388)},304967,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(480731),l=e.i(95779),n=e.i(444755),o=e.i(673706);let s=(0,o.makeClassName)("Card"),i=r.default.forwardRef((e,i)=>{let{decoration:d="",decorationColor:c,children:u,className:m}=e,g=(0,t.__rest)(e,["decoration","decorationColor","children","className"]);return r.default.createElement("div",Object.assign({ref:i,className:(0,n.tremorTwMerge)(s("root"),"relative w-full text-left ring-1 rounded-tremor-default p-6","bg-tremor-background ring-tremor-ring shadow-tremor-card","dark:bg-dark-tremor-background dark:ring-dark-tremor-ring dark:shadow-dark-tremor-card",c?(0,o.getColorClassNames)(c,l.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",(e=>{if(!e)return"";switch(e){case a.HorizontalPositions.Left:return"border-l-4";case a.VerticalPositions.Top:return"border-t-4";case a.HorizontalPositions.Right:return"border-r-4";case a.VerticalPositions.Bottom:return"border-b-4";default:return""}})(d),m)},g),u)});i.displayName="Card",e.s(["Card",()=>i],304967)},185793,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),a=e.i(242064),l=e.i(529681);let n=e=>{let{prefixCls:a,className:l,style:n,size:o,shape:s}=e,i=(0,r.default)({[`${a}-lg`]:"large"===o,[`${a}-sm`]:"small"===o}),d=(0,r.default)({[`${a}-circle`]:"circle"===s,[`${a}-square`]:"square"===s,[`${a}-round`]:"round"===s}),c=t.useMemo(()=>"number"==typeof o?{width:o,height:o,lineHeight:`${o}px`}:{},[o]);return t.createElement("span",{className:(0,r.default)(a,i,d,l),style:Object.assign(Object.assign({},c),n)})};e.i(296059);var o=e.i(694758),s=e.i(915654),i=e.i(246422),d=e.i(838378);let c=new o.Keyframes("ant-skeleton-loading",{"0%":{backgroundPosition:"100% 50%"},"100%":{backgroundPosition:"0 50%"}}),u=e=>({height:e,lineHeight:(0,s.unit)(e)}),m=e=>Object.assign({width:e},u(e)),g=(e,t)=>Object.assign({width:t(e).mul(5).equal(),minWidth:t(e).mul(5).equal()},u(e)),f=e=>Object.assign({width:e},u(e)),p=(e,t,r)=>{let{skeletonButtonCls:a}=e;return{[`${r}${a}-circle`]:{width:t,minWidth:t,borderRadius:"50%"},[`${r}${a}-round`]:{borderRadius:t}}},b=(e,t)=>Object.assign({width:t(e).mul(2).equal(),minWidth:t(e).mul(2).equal()},u(e)),h=(0,i.genStyleHooks)("Skeleton",e=>{let{componentCls:t,calc:r}=e;return(e=>{let{componentCls:t,skeletonAvatarCls:r,skeletonTitleCls:a,skeletonParagraphCls:l,skeletonButtonCls:n,skeletonInputCls:o,skeletonImageCls:s,controlHeight:i,controlHeightLG:d,controlHeightSM:u,gradientFromColor:h,padding:v,marginSM:C,borderRadius:k,titleHeight:x,blockRadius:w,paragraphLiHeight:E,controlHeightXS:y,paragraphMarginTop:N}=e;return{[t]:{display:"table",width:"100%",[`${t}-header`]:{display:"table-cell",paddingInlineEnd:v,verticalAlign:"top",[r]:Object.assign({display:"inline-block",verticalAlign:"top",background:h},m(i)),[`${r}-circle`]:{borderRadius:"50%"},[`${r}-lg`]:Object.assign({},m(d)),[`${r}-sm`]:Object.assign({},m(u))},[`${t}-content`]:{display:"table-cell",width:"100%",verticalAlign:"top",[a]:{width:"100%",height:x,background:h,borderRadius:w,[`+ ${l}`]:{marginBlockStart:u}},[l]:{padding:0,"> li":{width:"100%",height:E,listStyle:"none",background:h,borderRadius:w,"+ li":{marginBlockStart:y}}},[`${l}> li:last-child:not(:first-child):not(:nth-child(2))`]:{width:"61%"}},[`&-round ${t}-content`]:{[`${a}, ${l} > li`]:{borderRadius:k}}},[`${t}-with-avatar ${t}-content`]:{[a]:{marginBlockStart:C,[`+ ${l}`]:{marginBlockStart:N}}},[`${t}${t}-element`]:Object.assign(Object.assign(Object.assign(Object.assign({display:"inline-block",width:"auto"},(e=>{let{borderRadiusSM:t,skeletonButtonCls:r,controlHeight:a,controlHeightLG:l,controlHeightSM:n,gradientFromColor:o,calc:s}=e;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({[r]:Object.assign({display:"inline-block",verticalAlign:"top",background:o,borderRadius:t,width:s(a).mul(2).equal(),minWidth:s(a).mul(2).equal()},b(a,s))},p(e,a,r)),{[`${r}-lg`]:Object.assign({},b(l,s))}),p(e,l,`${r}-lg`)),{[`${r}-sm`]:Object.assign({},b(n,s))}),p(e,n,`${r}-sm`))})(e)),(e=>{let{skeletonAvatarCls:t,gradientFromColor:r,controlHeight:a,controlHeightLG:l,controlHeightSM:n}=e;return{[t]:Object.assign({display:"inline-block",verticalAlign:"top",background:r},m(a)),[`${t}${t}-circle`]:{borderRadius:"50%"},[`${t}${t}-lg`]:Object.assign({},m(l)),[`${t}${t}-sm`]:Object.assign({},m(n))}})(e)),(e=>{let{controlHeight:t,borderRadiusSM:r,skeletonInputCls:a,controlHeightLG:l,controlHeightSM:n,gradientFromColor:o,calc:s}=e;return{[a]:Object.assign({display:"inline-block",verticalAlign:"top",background:o,borderRadius:r},g(t,s)),[`${a}-lg`]:Object.assign({},g(l,s)),[`${a}-sm`]:Object.assign({},g(n,s))}})(e)),(e=>{let{skeletonImageCls:t,imageSizeBase:r,gradientFromColor:a,borderRadiusSM:l,calc:n}=e;return{[t]:Object.assign(Object.assign({display:"inline-flex",alignItems:"center",justifyContent:"center",verticalAlign:"middle",background:a,borderRadius:l},f(n(r).mul(2).equal())),{[`${t}-path`]:{fill:"#bfbfbf"},[`${t}-svg`]:Object.assign(Object.assign({},f(r)),{maxWidth:n(r).mul(4).equal(),maxHeight:n(r).mul(4).equal()}),[`${t}-svg${t}-svg-circle`]:{borderRadius:"50%"}}),[`${t}${t}-circle`]:{borderRadius:"50%"}}})(e)),[`${t}${t}-block`]:{width:"100%",[n]:{width:"100%"},[o]:{width:"100%"}},[`${t}${t}-active`]:{[` + ${a}, + ${l} > li, + ${r}, + ${n}, + ${o}, + ${s} + `]:Object.assign({},{background:e.skeletonLoadingBackground,backgroundSize:"400% 100%",animationName:c,animationDuration:e.skeletonLoadingMotionDuration,animationTimingFunction:"ease",animationIterationCount:"infinite"})}}})((0,d.mergeToken)(e,{skeletonAvatarCls:`${t}-avatar`,skeletonTitleCls:`${t}-title`,skeletonParagraphCls:`${t}-paragraph`,skeletonButtonCls:`${t}-button`,skeletonInputCls:`${t}-input`,skeletonImageCls:`${t}-image`,imageSizeBase:r(e.controlHeight).mul(1.5).equal(),borderRadius:100,skeletonLoadingBackground:`linear-gradient(90deg, ${e.gradientFromColor} 25%, ${e.gradientToColor} 37%, ${e.gradientFromColor} 63%)`,skeletonLoadingMotionDuration:"1.4s"}))},e=>{let{colorFillContent:t,colorFill:r}=e;return{color:t,colorGradientEnd:r,gradientFromColor:t,gradientToColor:r,titleHeight:e.controlHeight/2,blockRadius:e.borderRadiusSM,paragraphMarginTop:e.marginLG+e.marginXXS,paragraphLiHeight:e.controlHeight/2}},{deprecatedTokens:[["color","gradientFromColor"],["colorGradientEnd","gradientToColor"]]}),v=e=>{let{prefixCls:a,className:l,style:n,rows:o=0}=e,s=Array.from({length:o}).map((r,a)=>t.createElement("li",{key:a,style:{width:((e,t)=>{let{width:r,rows:a=2}=t;return Array.isArray(r)?r[e]:a-1===e?r:void 0})(a,e)}}));return t.createElement("ul",{className:(0,r.default)(a,l),style:n},s)},C=({prefixCls:e,className:a,width:l,style:n})=>t.createElement("h3",{className:(0,r.default)(e,a),style:Object.assign({width:l},n)});function k(e){return e&&"object"==typeof e?e:{}}let x=e=>{let{prefixCls:l,loading:o,className:s,rootClassName:i,style:d,children:c,avatar:u=!1,title:m=!0,paragraph:g=!0,active:f,round:p}=e,{getPrefixCls:b,direction:x,className:w,style:E}=(0,a.useComponentConfig)("skeleton"),y=b("skeleton",l),[N,T,O]=h(y);if(o||!("loading"in e)){let e,a,l=!!u,o=!!m,c=!!g;if(l){let r=Object.assign(Object.assign({prefixCls:`${y}-avatar`},o&&!c?{size:"large",shape:"square"}:{size:"large",shape:"circle"}),k(u));e=t.createElement("div",{className:`${y}-header`},t.createElement(n,Object.assign({},r)))}if(o||c){let e,r;if(o){let r=Object.assign(Object.assign({prefixCls:`${y}-title`},!l&&c?{width:"38%"}:l&&c?{width:"50%"}:{}),k(m));e=t.createElement(C,Object.assign({},r))}if(c){let e,a=Object.assign(Object.assign({prefixCls:`${y}-paragraph`},(e={},l&&o||(e.width="61%"),!l&&o?e.rows=3:e.rows=2,e)),k(g));r=t.createElement(v,Object.assign({},a))}a=t.createElement("div",{className:`${y}-content`},e,r)}let b=(0,r.default)(y,{[`${y}-with-avatar`]:l,[`${y}-active`]:f,[`${y}-rtl`]:"rtl"===x,[`${y}-round`]:p},w,s,i,T,O);return N(t.createElement("div",{className:b,style:Object.assign(Object.assign({},E),d)},e,a))}return null!=c?c:null};x.Button=e=>{let{prefixCls:o,className:s,rootClassName:i,active:d,block:c=!1,size:u="default"}=e,{getPrefixCls:m}=t.useContext(a.ConfigContext),g=m("skeleton",o),[f,p,b]=h(g),v=(0,l.default)(e,["prefixCls"]),C=(0,r.default)(g,`${g}-element`,{[`${g}-active`]:d,[`${g}-block`]:c},s,i,p,b);return f(t.createElement("div",{className:C},t.createElement(n,Object.assign({prefixCls:`${g}-button`,size:u},v))))},x.Avatar=e=>{let{prefixCls:o,className:s,rootClassName:i,active:d,shape:c="circle",size:u="default"}=e,{getPrefixCls:m}=t.useContext(a.ConfigContext),g=m("skeleton",o),[f,p,b]=h(g),v=(0,l.default)(e,["prefixCls","className"]),C=(0,r.default)(g,`${g}-element`,{[`${g}-active`]:d},s,i,p,b);return f(t.createElement("div",{className:C},t.createElement(n,Object.assign({prefixCls:`${g}-avatar`,shape:c,size:u},v))))},x.Input=e=>{let{prefixCls:o,className:s,rootClassName:i,active:d,block:c,size:u="default"}=e,{getPrefixCls:m}=t.useContext(a.ConfigContext),g=m("skeleton",o),[f,p,b]=h(g),v=(0,l.default)(e,["prefixCls"]),C=(0,r.default)(g,`${g}-element`,{[`${g}-active`]:d,[`${g}-block`]:c},s,i,p,b);return f(t.createElement("div",{className:C},t.createElement(n,Object.assign({prefixCls:`${g}-input`,size:u},v))))},x.Image=e=>{let{prefixCls:l,className:n,rootClassName:o,style:s,active:i}=e,{getPrefixCls:d}=t.useContext(a.ConfigContext),c=d("skeleton",l),[u,m,g]=h(c),f=(0,r.default)(c,`${c}-element`,{[`${c}-active`]:i},n,o,m,g);return u(t.createElement("div",{className:f},t.createElement("div",{className:(0,r.default)(`${c}-image`,n),style:s},t.createElement("svg",{viewBox:"0 0 1098 1024",xmlns:"http://www.w3.org/2000/svg",className:`${c}-image-svg`},t.createElement("title",null,"Image placeholder"),t.createElement("path",{d:"M365.714286 329.142857q0 45.714286-32.036571 77.677714t-77.677714 32.036571-77.677714-32.036571-32.036571-77.677714 32.036571-77.677714 77.677714-32.036571 77.677714 32.036571 32.036571 77.677714zM950.857143 548.571429l0 256-804.571429 0 0-109.714286 182.857143-182.857143 91.428571 91.428571 292.571429-292.571429zM1005.714286 146.285714l-914.285714 0q-7.460571 0-12.873143 5.412571t-5.412571 12.873143l0 694.857143q0 7.460571 5.412571 12.873143t12.873143 5.412571l914.285714 0q7.460571 0 12.873143-5.412571t5.412571-12.873143l0-694.857143q0-7.460571-5.412571-12.873143t-12.873143-5.412571zM1097.142857 164.571429l0 694.857143q0 37.741714-26.843429 64.585143t-64.585143 26.843429l-914.285714 0q-37.741714 0-64.585143-26.843429t-26.843429-64.585143l0-694.857143q0-37.741714 26.843429-64.585143t64.585143-26.843429l914.285714 0q37.741714 0 64.585143 26.843429t26.843429 64.585143z",className:`${c}-image-path`})))))},x.Node=e=>{let{prefixCls:l,className:n,rootClassName:o,style:s,active:i,children:d}=e,{getPrefixCls:c}=t.useContext(a.ConfigContext),u=c("skeleton",l),[m,g,f]=h(u),p=(0,r.default)(u,`${u}-element`,{[`${u}-active`]:i},g,n,o,f);return m(t.createElement("div",{className:p},t.createElement("div",{className:(0,r.default)(`${u}-image`,n),style:s},d)))},e.s(["default",0,x],185793)},959013,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8z"}},{tag:"path",attrs:{d:"M192 474h672q8 0 8 8v60q0 8-8 8H160q-8 0-8-8v-60q0-8 8-8z"}}]},name:"plus",theme:"outlined"};var l=e.i(9583),n=r.forwardRef(function(e,n){return r.createElement(l.default,(0,t.default)({},e,{ref:n,icon:a}))});e.s(["default",0,n],959013)},269200,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let l=(0,e.i(673706).makeClassName)("Table"),n=r.default.forwardRef((e,n)=>{let{children:o,className:s}=e,i=(0,t.__rest)(e,["children","className"]);return r.default.createElement("div",{className:(0,a.tremorTwMerge)(l("root"),"overflow-auto",s)},r.default.createElement("table",Object.assign({ref:n,className:(0,a.tremorTwMerge)(l("table"),"w-full text-tremor-default","text-tremor-content","dark:text-dark-tremor-content")},i),o))});n.displayName="Table",e.s(["Table",()=>n],269200)},942232,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let l=(0,e.i(673706).makeClassName)("TableBody"),n=r.default.forwardRef((e,n)=>{let{children:o,className:s}=e,i=(0,t.__rest)(e,["children","className"]);return r.default.createElement(r.default.Fragment,null,r.default.createElement("tbody",Object.assign({ref:n,className:(0,a.tremorTwMerge)(l("root"),"align-top divide-y","divide-tremor-border","dark:divide-dark-tremor-border",s)},i),o))});n.displayName="TableBody",e.s(["TableBody",()=>n],942232)},977572,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let l=(0,e.i(673706).makeClassName)("TableCell"),n=r.default.forwardRef((e,n)=>{let{children:o,className:s}=e,i=(0,t.__rest)(e,["children","className"]);return r.default.createElement(r.default.Fragment,null,r.default.createElement("td",Object.assign({ref:n,className:(0,a.tremorTwMerge)(l("root"),"align-middle whitespace-nowrap text-left p-4",s)},i),o))});n.displayName="TableCell",e.s(["TableCell",()=>n],977572)},427612,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let l=(0,e.i(673706).makeClassName)("TableHead"),n=r.default.forwardRef((e,n)=>{let{children:o,className:s}=e,i=(0,t.__rest)(e,["children","className"]);return r.default.createElement(r.default.Fragment,null,r.default.createElement("thead",Object.assign({ref:n,className:(0,a.tremorTwMerge)(l("root"),"text-left","text-tremor-content","dark:text-dark-tremor-content",s)},i),o))});n.displayName="TableHead",e.s(["TableHead",()=>n],427612)},64848,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let l=(0,e.i(673706).makeClassName)("TableHeaderCell"),n=r.default.forwardRef((e,n)=>{let{children:o,className:s}=e,i=(0,t.__rest)(e,["children","className"]);return r.default.createElement(r.default.Fragment,null,r.default.createElement("th",Object.assign({ref:n,className:(0,a.tremorTwMerge)(l("root"),"whitespace-nowrap text-left font-semibold top-0 px-4 py-3.5","text-tremor-content-strong","dark:text-dark-tremor-content-strong",s)},i),o))});n.displayName="TableHeaderCell",e.s(["TableHeaderCell",()=>n],64848)},496020,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let l=(0,e.i(673706).makeClassName)("TableRow"),n=r.default.forwardRef((e,n)=>{let{children:o,className:s}=e,i=(0,t.__rest)(e,["children","className"]);return r.default.createElement(r.default.Fragment,null,r.default.createElement("tr",Object.assign({ref:n,className:(0,a.tremorTwMerge)(l("row"),s)},i),o))});n.displayName="TableRow",e.s(["TableRow",()=>n],496020)},68155,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.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.s(["TrashIcon",0,r],68155)},360820,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 15l7-7 7 7"}))});e.s(["ChevronUpIcon",0,r],360820)},871943,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"}))});e.s(["ChevronDownIcon",0,r],871943)},278587,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",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"}))});e.s(["RefreshIcon",0,r],278587)},233538,e=>{"use strict";function t(e){let t=e.parentElement,r=null;for(;t&&!(t instanceof HTMLFieldSetElement);)t instanceof HTMLLegendElement&&(r=t),t=t.parentElement;let a=(null==t?void 0:t.getAttribute("disabled"))==="";return!(a&&function(e){if(!e)return!1;let t=e.previousElementSibling;for(;null!==t;){if(t instanceof HTMLLegendElement)return!1;t=t.previousElementSibling}return!0}(r))&&a}e.s(["isDisabledReactIssue7711",()=>t])},83733,233137,e=>{"use strict";let t,r;var a,l,n=e.i(247167),o=e.i(271645),s=e.i(544508),i=e.i(746725),d=e.i(835696);void 0!==n.default&&"u">typeof globalThis&&"u">typeof Element&&(null==(a=null==n.default?void 0:n.default.env)?void 0:a.NODE_ENV)==="test"&&void 0===(null==(l=null==Element?void 0:Element.prototype)?void 0:l.getAnimations)&&(Element.prototype.getAnimations=function(){return console.warn(["Headless UI has polyfilled `Element.prototype.getAnimations` for your tests.","Please install a proper polyfill e.g. `jsdom-testing-mocks`, to silence these warnings.","","Example usage:","```js","import { mockAnimationsApi } from 'jsdom-testing-mocks'","mockAnimationsApi()","```"].join(` +`)),[]});var c=((t=c||{})[t.None=0]="None",t[t.Closed=1]="Closed",t[t.Enter=2]="Enter",t[t.Leave=4]="Leave",t);function u(e){let t={};for(let r in e)!0===e[r]&&(t[`data-${r}`]="");return t}function m(e,t,r,a){let[l,n]=(0,o.useState)(r),{hasFlag:c,addFlag:u,removeFlag:m}=function(e=0){let[t,r]=(0,o.useState)(e),a=(0,o.useCallback)(e=>r(e),[t]),l=(0,o.useCallback)(e=>r(t=>t|e),[t]),n=(0,o.useCallback)(e=>(t&e)===e,[t]);return{flags:t,setFlag:a,addFlag:l,hasFlag:n,removeFlag:(0,o.useCallback)(e=>r(t=>t&~e),[r]),toggleFlag:(0,o.useCallback)(e=>r(t=>t^e),[r])}}(e&&l?3:0),g=(0,o.useRef)(!1),f=(0,o.useRef)(!1),p=(0,i.useDisposables)();return(0,d.useIsoMorphicEffect)(()=>{var l;if(e){if(r&&n(!0),!t){r&&u(3);return}return null==(l=null==a?void 0:a.start)||l.call(a,r),function(e,{prepare:t,run:r,done:a,inFlight:l}){let n=(0,s.disposables)();return function(e,{inFlight:t,prepare:r}){if(null!=t&&t.current)return r();let a=e.style.transition;e.style.transition="none",r(),e.offsetHeight,e.style.transition=a}(e,{prepare:t,inFlight:l}),n.nextFrame(()=>{r(),n.requestAnimationFrame(()=>{n.add(function(e,t){var r,a;let l=(0,s.disposables)();if(!e)return l.dispose;let n=!1;l.add(()=>{n=!0});let o=null!=(a=null==(r=e.getAnimations)?void 0:r.call(e).filter(e=>e instanceof CSSTransition))?a:[];return 0===o.length?t():Promise.allSettled(o.map(e=>e.finished)).then(()=>{n||t()}),l.dispose}(e,a))})}),n.dispose}(t,{inFlight:g,prepare(){f.current?f.current=!1:f.current=g.current,g.current=!0,f.current||(r?(u(3),m(4)):(u(4),m(2)))},run(){f.current?r?(m(3),u(4)):(m(4),u(3)):r?m(1):u(1)},done(){var e;f.current&&"function"==typeof t.getAnimations&&t.getAnimations().length>0||(g.current=!1,m(7),r||n(!1),null==(e=null==a?void 0:a.end)||e.call(a,r))}})}},[e,r,t,p]),e?[l,{closed:c(1),enter:c(2),leave:c(4),transition:c(2)||c(4)}]:[r,{closed:void 0,enter:void 0,leave:void 0,transition:void 0}]}e.s(["transitionDataAttributes",()=>u,"useTransition",()=>m],83733);let g=(0,o.createContext)(null);g.displayName="OpenClosedContext";var f=((r=f||{})[r.Open=1]="Open",r[r.Closed=2]="Closed",r[r.Closing=4]="Closing",r[r.Opening=8]="Opening",r);function p(){return(0,o.useContext)(g)}function b({value:e,children:t}){return o.default.createElement(g.Provider,{value:e},t)}function h({children:e}){return o.default.createElement(g.Provider,{value:null},e)}e.s(["OpenClosedProvider",()=>b,"ResetOpenClosedProvider",()=>h,"State",()=>f,"useOpenClosed",()=>p],233137)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/1a04d31843c96649.js b/litellm/proxy/_experimental/out/_next/static/chunks/1a04d31843c96649.js new file mode 100644 index 00000000000..a9a583efa3e --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/1a04d31843c96649.js @@ -0,0 +1,598 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,602073,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"0 0 1024 1024",focusable:"false"},children:[{tag:"path",attrs:{d:"M512 64L128 192v384c0 212.1 171.9 384 384 384s384-171.9 384-384V192L512 64zm312 512c0 172.3-139.7 312-312 312S200 748.3 200 576V246l312-110 312 110v330z"}},{tag:"path",attrs:{d:"M378.4 475.1a35.91 35.91 0 00-50.9 0 35.91 35.91 0 000 50.9l129.4 129.4 2.1 2.1a33.98 33.98 0 0048.1 0L730.6 434a33.98 33.98 0 000-48.1l-2.8-2.8a33.98 33.98 0 00-48.1 0L483 579.7 378.4 475.1z"}}]},name:"safety",theme:"outlined"};var r=e.i(9583),i=a.forwardRef(function(e,i){return a.createElement(r.default,(0,t.default)({},e,{ref:i,icon:s}))});e.s(["SafetyOutlined",0,i],602073)},818581,(e,t,a)=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0}),Object.defineProperty(a,"useMergedRef",{enumerable:!0,get:function(){return r}});let s=e.r(271645);function r(e,t){let a=(0,s.useRef)(null),r=(0,s.useRef)(null);return(0,s.useCallback)(s=>{if(null===s){let e=a.current;e&&(a.current=null,e());let t=r.current;t&&(r.current=null,t())}else e&&(a.current=i(e,s)),t&&(r.current=i(t,s))},[e,t])}function i(e,t){if("function"!=typeof e)return e.current=t,()=>{e.current=null};{let a=e(t);return"function"==typeof a?a:()=>e(null)}}("function"==typeof a.default||"object"==typeof a.default&&null!==a.default)&&void 0===a.default.__esModule&&(Object.defineProperty(a.default,"__esModule",{value:!0}),Object.assign(a.default,a),t.exports=a.default)},62478,e=>{"use strict";var t=e.i(764205);let a=async e=>{if(!e)return null;try{return await (0,t.getProxyUISettings)(e)}catch(e){return console.error("Error fetching proxy settings:",e),null}};e.s(["fetchProxySettings",0,a])},190272,785913,e=>{"use strict";var t,a,s=((t={}).AUDIO_SPEECH="audio_speech",t.AUDIO_TRANSCRIPTION="audio_transcription",t.IMAGE_GENERATION="image_generation",t.VIDEO_GENERATION="video_generation",t.CHAT="chat",t.RESPONSES="responses",t.IMAGE_EDITS="image_edits",t.ANTHROPIC_MESSAGES="anthropic_messages",t.EMBEDDING="embedding",t),r=((a={}).IMAGE="image",a.VIDEO="video",a.CHAT="chat",a.RESPONSES="responses",a.IMAGE_EDITS="image_edits",a.ANTHROPIC_MESSAGES="anthropic_messages",a.EMBEDDINGS="embeddings",a.SPEECH="speech",a.TRANSCRIPTION="transcription",a.A2A_AGENTS="a2a_agents",a.MCP="mcp",a.REALTIME="realtime",a);let i={image_generation:"image",video_generation:"video",chat:"chat",responses:"responses",image_edits:"image_edits",anthropic_messages:"anthropic_messages",audio_speech:"speech",audio_transcription:"transcription",embedding:"embeddings"};e.s(["EndpointType",()=>r,"getEndpointType",0,e=>{if(console.log("getEndpointType:",e),Object.values(s).includes(e)){let t=i[e];return console.log("endpointType:",t),t}return"chat"}],785913),e.s(["generateCodeSnippet",0,e=>{let t,{apiKeySource:a,accessToken:s,apiKey:i,inputMessage:l,chatHistory:n,selectedTags:o,selectedVectorStores:c,selectedGuardrails:d,selectedPolicies:m,selectedMCPServers:p,mcpServers:u,mcpServerToolRestrictions:g,selectedVoice:x,endpointType:h,selectedModel:_,selectedSdk:f,proxySettings:b}=e,v="session"===a?s:i,j=window.location.origin,A=b?.LITELLM_UI_API_DOC_BASE_URL;A&&A.trim()?j=A:b?.PROXY_BASE_URL&&(j=b.PROXY_BASE_URL);let y=l||"Your prompt here",N=y.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n"),T=n.filter(e=>!e.isImage).map(({role:e,content:t})=>({role:e,content:t})),C={};o.length>0&&(C.tags=o),c.length>0&&(C.vector_stores=c),d.length>0&&(C.guardrails=d),m.length>0&&(C.policies=m);let S=_||"your-model-name",I="azure"===f?`import openai + +client = openai.AzureOpenAI( + api_key="${v||"YOUR_LITELLM_API_KEY"}", + azure_endpoint="${j}", + api_version="2024-02-01" +)`:`import openai + +client = openai.OpenAI( + api_key="${v||"YOUR_LITELLM_API_KEY"}", + base_url="${j}" +)`;switch(h){case r.CHAT:{let e=Object.keys(C).length>0,a="";if(e){let e=JSON.stringify({metadata:C},null,2).split("\n").map(e=>" ".repeat(4)+e).join("\n").trim();a=`, + extra_body=${e}`}let s=T.length>0?T:[{role:"user",content:y}];t=` +import base64 + +# Helper function to encode images to base64 +def encode_image(image_path): + with open(image_path, "rb") as image_file: + return base64.b64encode(image_file.read()).decode('utf-8') + +# Example with text only +response = client.chat.completions.create( + model="${S}", + messages=${JSON.stringify(s,null,4)}${a} +) + +print(response) + +# Example with image or PDF (uncomment and provide file path to use) +# base64_file = encode_image("path/to/your/file.jpg") # or .pdf +# response_with_file = client.chat.completions.create( +# model="${S}", +# messages=[ +# { +# "role": "user", +# "content": [ +# { +# "type": "text", +# "text": "${N}" +# }, +# { +# "type": "image_url", +# "image_url": { +# "url": f"data:image/jpeg;base64,{base64_file}" # or data:application/pdf;base64,{base64_file} +# } +# } +# ] +# } +# ]${a} +# ) +# print(response_with_file) +`;break}case r.RESPONSES:{let e=Object.keys(C).length>0,a="";if(e){let e=JSON.stringify({metadata:C},null,2).split("\n").map(e=>" ".repeat(4)+e).join("\n").trim();a=`, + extra_body=${e}`}let s=T.length>0?T:[{role:"user",content:y}];t=` +import base64 + +# Helper function to encode images to base64 +def encode_image(image_path): + with open(image_path, "rb") as image_file: + return base64.b64encode(image_file.read()).decode('utf-8') + +# Example with text only +response = client.responses.create( + model="${S}", + input=${JSON.stringify(s,null,4)}${a} +) + +print(response.output_text) + +# Example with image or PDF (uncomment and provide file path to use) +# base64_file = encode_image("path/to/your/file.jpg") # or .pdf +# response_with_file = client.responses.create( +# model="${S}", +# input=[ +# { +# "role": "user", +# "content": [ +# {"type": "input_text", "text": "${N}"}, +# { +# "type": "input_image", +# "image_url": f"data:image/jpeg;base64,{base64_file}", # or data:application/pdf;base64,{base64_file} +# }, +# ], +# } +# ]${a} +# ) +# print(response_with_file.output_text) +`;break}case r.IMAGE:t="azure"===f?` +# NOTE: The Azure SDK does not have a direct equivalent to the multi-modal 'responses.create' method shown for OpenAI. +# This snippet uses 'client.images.generate' and will create a new image based on your prompt. +# It does not use the uploaded image, as 'client.images.generate' does not support image inputs in this context. +import os +import requests +import json +import time +from PIL import Image + +result = client.images.generate( + model="${S}", + prompt="${l}", + n=1 +) + +json_response = json.loads(result.model_dump_json()) + +# Set the directory for the stored image +image_dir = os.path.join(os.curdir, 'images') + +# If the directory doesn't exist, create it +if not os.path.isdir(image_dir): + os.mkdir(image_dir) + +# Initialize the image path +image_filename = f"generated_image_{int(time.time())}.png" +image_path = os.path.join(image_dir, image_filename) + +try: + # Retrieve the generated image + if json_response.get("data") && len(json_response["data"]) > 0 && json_response["data"][0].get("url"): + image_url = json_response["data"][0]["url"] + generated_image = requests.get(image_url).content + with open(image_path, "wb") as image_file: + image_file.write(generated_image) + + print(f"Image saved to {image_path}") + # Display the image + image = Image.open(image_path) + image.show() + else: + print("Could not find image URL in response.") + print("Full response:", json_response) +except Exception as e: + print(f"An error occurred: {e}") + print("Full response:", json_response) +`:` +import base64 +import os +import time +import json +from PIL import Image +import requests + +# Helper function to encode images to base64 +def encode_image(image_path): + with open(image_path, "rb") as image_file: + return base64.b64encode(image_file.read()).decode('utf-8') + +# Helper function to create a file (simplified for this example) +def create_file(image_path): + # In a real implementation, this would upload the file to OpenAI + # For this example, we'll just return a placeholder ID + return f"file_{os.path.basename(image_path).replace('.', '_')}" + +# The prompt entered by the user +prompt = "${N}" + +# Encode images to base64 +base64_image1 = encode_image("body-lotion.png") +base64_image2 = encode_image("soap.png") + +# Create file IDs +file_id1 = create_file("body-lotion.png") +file_id2 = create_file("incense-kit.png") + +response = client.responses.create( + model="${S}", + input=[ + { + "role": "user", + "content": [ + {"type": "input_text", "text": prompt}, + { + "type": "input_image", + "image_url": f"data:image/jpeg;base64,{base64_image1}", + }, + { + "type": "input_image", + "image_url": f"data:image/jpeg;base64,{base64_image2}", + }, + { + "type": "input_image", + "file_id": file_id1, + }, + { + "type": "input_image", + "file_id": file_id2, + } + ], + } + ], + tools=[{"type": "image_generation"}], +) + +# Process the response +image_generation_calls = [ + output + for output in response.output + if output.type == "image_generation_call" +] + +image_data = [output.result for output in image_generation_calls] + +if image_data: + image_base64 = image_data[0] + image_filename = f"edited_image_{int(time.time())}.png" + with open(image_filename, "wb") as f: + f.write(base64.b64decode(image_base64)) + print(f"Image saved to {image_filename}") +else: + # If no image is generated, there might be a text response with an explanation + text_response = [output.text for output in response.output if hasattr(output, 'text')] + if text_response: + print("No image generated. Model response:") + print("\\n".join(text_response)) + else: + print("No image data found in response.") + print("Full response for debugging:") + print(response) +`;break;case r.IMAGE_EDITS:t="azure"===f?` +import base64 +import os +import time +import json +from PIL import Image +import requests + +# Helper function to encode images to base64 +def encode_image(image_path): + with open(image_path, "rb") as image_file: + return base64.b64encode(image_file.read()).decode('utf-8') + +# The prompt entered by the user +prompt = "${N}" + +# Encode images to base64 +base64_image1 = encode_image("body-lotion.png") +base64_image2 = encode_image("soap.png") + +# Create file IDs +file_id1 = create_file("body-lotion.png") +file_id2 = create_file("incense-kit.png") + +response = client.responses.create( + model="${S}", + input=[ + { + "role": "user", + "content": [ + {"type": "input_text", "text": prompt}, + { + "type": "input_image", + "image_url": f"data:image/jpeg;base64,{base64_image1}", + }, + { + "type": "input_image", + "image_url": f"data:image/jpeg;base64,{base64_image2}", + }, + { + "type": "input_image", + "file_id": file_id1, + }, + { + "type": "input_image", + "file_id": file_id2, + } + ], + } + ], + tools=[{"type": "image_generation"}], +) + +# Process the response +image_generation_calls = [ + output + for output in response.output + if output.type == "image_generation_call" +] + +image_data = [output.result for output in image_generation_calls] + +if image_data: + image_base64 = image_data[0] + image_filename = f"edited_image_{int(time.time())}.png" + with open(image_filename, "wb") as f: + f.write(base64.b64decode(image_base64)) + print(f"Image saved to {image_filename}") +else: + # If no image is generated, there might be a text response with an explanation + text_response = [output.text for output in response.output if hasattr(output, 'text')] + if text_response: + print("No image generated. Model response:") + print("\\n".join(text_response)) + else: + print("No image data found in response.") + print("Full response for debugging:") + print(response) +`:` +import base64 +import os +import time + +# Helper function to encode images to base64 +def encode_image(image_path): + with open(image_path, "rb") as image_file: + return base64.b64encode(image_file.read()).decode('utf-8') + +# Helper function to create a file (simplified for this example) +def create_file(image_path): + # In a real implementation, this would upload the file to OpenAI + # For this example, we'll just return a placeholder ID + return f"file_{os.path.basename(image_path).replace('.', '_')}" + +# The prompt entered by the user +prompt = "${N}" + +# Encode images to base64 +base64_image1 = encode_image("body-lotion.png") +base64_image2 = encode_image("soap.png") + +# Create file IDs +file_id1 = create_file("body-lotion.png") +file_id2 = create_file("incense-kit.png") + +response = client.responses.create( + model="${S}", + input=[ + { + "role": "user", + "content": [ + {"type": "input_text", "text": prompt}, + { + "type": "input_image", + "image_url": f"data:image/jpeg;base64,{base64_image1}", + }, + { + "type": "input_image", + "image_url": f"data:image/jpeg;base64,{base64_image2}", + }, + { + "type": "input_image", + "file_id": file_id1, + }, + { + "type": "input_image", + "file_id": file_id2, + } + ], + } + ], + tools=[{"type": "image_generation"}], +) + +# Process the response +image_generation_calls = [ + output + for output in response.output + if output.type == "image_generation_call" +] + +image_data = [output.result for output in image_generation_calls] + +if image_data: + image_base64 = image_data[0] + image_filename = f"edited_image_{int(time.time())}.png" + with open(image_filename, "wb") as f: + f.write(base64.b64decode(image_base64)) + print(f"Image saved to {image_filename}") +else: + # If no image is generated, there might be a text response with an explanation + text_response = [output.text for output in response.output if hasattr(output, 'text')] + if text_response: + print("No image generated. Model response:") + print("\\n".join(text_response)) + else: + print("No image data found in response.") + print("Full response for debugging:") + print(response) +`;break;case r.EMBEDDINGS:t=` +response = client.embeddings.create( + input="${l||"Your string here"}", + model="${S}", + encoding_format="base64" # or "float" +) + +print(response.data[0].embedding) +`;break;case r.TRANSCRIPTION:t=` +# Open the audio file +audio_file = open("path/to/your/audio/file.mp3", "rb") + +# Make the transcription request +response = client.audio.transcriptions.create( + model="${S}", + file=audio_file${l?`, + prompt="${l.replace(/"/g,'\\"')}"`:""} +) + +print(response.text) +`;break;case r.SPEECH:t=` +# Make the text-to-speech request +response = client.audio.speech.create( + model="${S}", + input="${l||"Your text to convert to speech here"}", + voice="${x}" # Options: alloy, ash, ballad, coral, echo, fable, nova, onyx, sage, shimmer +) + +# Save the audio to a file +output_filename = "output_speech.mp3" +response.stream_to_file(output_filename) +print(f"Audio saved to {output_filename}") + +# Optional: Customize response format and speed +# response = client.audio.speech.create( +# model="${S}", +# input="${l||"Your text to convert to speech here"}", +# voice="alloy", +# response_format="mp3", # Options: mp3, opus, aac, flac, wav, pcm +# speed=1.0 # Range: 0.25 to 4.0 +# ) +# response.stream_to_file("output_speech.mp3") +`;break;default:t="\n# Code generation for this endpoint is not implemented yet."}return`${I} +${t}`}],190272)},879664,e=>{"use strict";let t=(0,e.i(475254).default)("info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]);e.s(["default",()=>t])},916925,e=>{"use strict";var t,a=((t={}).A2A_Agent="A2A Agent",t.AI21="Ai21",t.AI21_CHAT="Ai21 Chat",t.AIML="AI/ML API",t.AIOHTTP_OPENAI="Aiohttp Openai",t.Anthropic="Anthropic",t.ANTHROPIC_TEXT="Anthropic Text",t.AssemblyAI="AssemblyAI",t.AUTO_ROUTER="Auto Router",t.Bedrock="Amazon Bedrock",t.BedrockMantle="Amazon Bedrock Mantle",t.SageMaker="AWS SageMaker",t.Azure="Azure",t.Azure_AI_Studio="Azure AI Foundry (Studio)",t.AZURE_TEXT="Azure Text",t.BASETEN="Baseten",t.BYTEZ="Bytez",t.Cerebras="Cerebras",t.CLARIFAI="Clarifai",t.CLOUDFLARE="Cloudflare",t.CODESTRAL="Codestral",t.Cohere="Cohere",t.COHERE_CHAT="Cohere Chat",t.COMETAPI="Cometapi",t.COMPACTIFAI="Compactifai",t.Cursor="Cursor",t.Dashscope="Dashscope",t.Databricks="Databricks (Qwen API)",t.DATAROBOT="Datarobot",t.DeepInfra="DeepInfra",t.Deepgram="Deepgram",t.Deepseek="Deepseek",t.DOCKER_MODEL_RUNNER="Docker Model Runner",t.DOTPROMPT="Dotprompt",t.ElevenLabs="ElevenLabs",t.EMPOWER="Empower",t.FalAI="Fal AI",t.FEATHERLESS_AI="Featherless Ai",t.FireworksAI="Fireworks AI",t.FRIENDLIAI="Friendliai",t.GALADRIEL="Galadriel",t.GITHUB_COPILOT="Github Copilot",t.Google_AI_Studio="Google AI Studio",t.GradientAI="GradientAI",t.Groq="Groq",t.HEROKU="Heroku",t.Hosted_Vllm="vllm",t.HUGGINGFACE="Huggingface",t.HYPERBOLIC="Hyperbolic",t.Infinity="Infinity",t.JinaAI="Jina AI",t.LAMBDA_AI="Lambda Ai",t.LEMONADE="Lemonade",t.LLAMAFILE="Llamafile",t.LM_STUDIO="Lm Studio",t.LLAMA="Meta Llama",t.MARITALK="Maritalk",t.MiniMax="MiniMax",t.MistralAI="Mistral AI",t.MOONSHOT="Moonshot",t.MORPH="Morph",t.NEBIUS="Nebius",t.NLP_CLOUD="Nlp Cloud",t.NOVITA="Novita",t.NSCALE="Nscale",t.NVIDIA_NIM="Nvidia Nim",t.Ollama="Ollama",t.OLLAMA_CHAT="Ollama Chat",t.OOBABOOGA="Oobabooga",t.OpenAI="OpenAI",t.OPENAI_LIKE="Openai Like",t.OpenAI_Compatible="OpenAI-Compatible Endpoints (Together AI, etc.)",t.OpenAI_Text="OpenAI Text Completion",t.OpenAI_Text_Compatible="OpenAI-Compatible Text Completion Models (Together AI, etc.)",t.Openrouter="Openrouter",t.Oracle="Oracle Cloud Infrastructure (OCI)",t.OVHCLOUD="Ovhcloud",t.Perplexity="Perplexity",t.PETALS="Petals",t.PG_VECTOR="Pg Vector",t.PREDIBASE="Predibase",t.RECRAFT="Recraft",t.REPLICATE="Replicate",t.RunwayML="RunwayML",t.SAGEMAKER_LEGACY="Sagemaker",t.Sambanova="Sambanova",t.SAP="SAP Generative AI Hub",t.Snowflake="Snowflake",t.TEXT_COMPLETION_CODESTRAL="Text-Completion-Codestral",t.TogetherAI="TogetherAI",t.TOPAZ="Topaz",t.Triton="Triton",t.V0="V0",t.VERCEL_AI_GATEWAY="Vercel Ai Gateway",t.Vertex_AI="Vertex AI (Anthropic, Gemini, etc.)",t.VERTEX_AI_BETA="Vertex Ai Beta",t.VLLM="Vllm",t.VolcEngine="VolcEngine",t.Voyage="Voyage AI",t.WANDB="Wandb",t.WATSONX="Watsonx",t.WATSONX_TEXT="Watsonx Text",t.xAI="xAI",t.XINFERENCE="Xinference",t);let s={A2A_Agent:"a2a_agent",AI21:"ai21",AI21_CHAT:"ai21_chat",AIML:"aiml",AIOHTTP_OPENAI:"aiohttp_openai",Anthropic:"anthropic",ANTHROPIC_TEXT:"anthropic_text",AssemblyAI:"assemblyai",AUTO_ROUTER:"auto_router",Azure:"azure",Azure_AI_Studio:"azure_ai",AZURE_TEXT:"azure_text",BASETEN:"baseten",Bedrock:"bedrock",BedrockMantle:"bedrock_mantle",BYTEZ:"bytez",Cerebras:"cerebras",CLARIFAI:"clarifai",CLOUDFLARE:"cloudflare",CODESTRAL:"codestral",Cohere:"cohere",COHERE_CHAT:"cohere_chat",COMETAPI:"cometapi",COMPACTIFAI:"compactifai",Cursor:"cursor",Dashscope:"dashscope",Databricks:"databricks",DATAROBOT:"datarobot",DeepInfra:"deepinfra",Deepgram:"deepgram",Deepseek:"deepseek",DOCKER_MODEL_RUNNER:"docker_model_runner",DOTPROMPT:"dotprompt",ElevenLabs:"elevenlabs",EMPOWER:"empower",FalAI:"fal_ai",FEATHERLESS_AI:"featherless_ai",FireworksAI:"fireworks_ai",FRIENDLIAI:"friendliai",GALADRIEL:"galadriel",GITHUB_COPILOT:"github_copilot",Google_AI_Studio:"gemini",GradientAI:"gradient_ai",Groq:"groq",HEROKU:"heroku",Hosted_Vllm:"hosted_vllm",HUGGINGFACE:"huggingface",HYPERBOLIC:"hyperbolic",Infinity:"infinity",JinaAI:"jina_ai",LAMBDA_AI:"lambda_ai",LEMONADE:"lemonade",LLAMAFILE:"llamafile",LLAMA:"meta_llama",LM_STUDIO:"lm_studio",MARITALK:"maritalk",MiniMax:"minimax",MistralAI:"mistral",MOONSHOT:"moonshot",MORPH:"morph",NEBIUS:"nebius",NLP_CLOUD:"nlp_cloud",NOVITA:"novita",NSCALE:"nscale",NVIDIA_NIM:"nvidia_nim",Ollama:"ollama",OLLAMA_CHAT:"ollama_chat",OOBABOOGA:"oobabooga",OpenAI:"openai",OPENAI_LIKE:"openai_like",OpenAI_Compatible:"openai",OpenAI_Text:"text-completion-openai",OpenAI_Text_Compatible:"text-completion-openai",Openrouter:"openrouter",Oracle:"oci",OVHCLOUD:"ovhcloud",Perplexity:"perplexity",PETALS:"petals",PG_VECTOR:"pg_vector",PREDIBASE:"predibase",RECRAFT:"recraft",REPLICATE:"replicate",RunwayML:"runwayml",SAGEMAKER_LEGACY:"sagemaker",SageMaker:"sagemaker_chat",Sambanova:"sambanova",SAP:"sap",Snowflake:"snowflake",TEXT_COMPLETION_CODESTRAL:"text-completion-codestral",TogetherAI:"together_ai",TOPAZ:"topaz",Triton:"triton",V0:"v0",VERCEL_AI_GATEWAY:"vercel_ai_gateway",Vertex_AI:"vertex_ai",VERTEX_AI_BETA:"vertex_ai_beta",VLLM:"vllm",VolcEngine:"volcengine",Voyage:"voyage",WANDB:"wandb",WATSONX:"watsonx",WATSONX_TEXT:"watsonx_text",xAI:"xai",XINFERENCE:"xinference"},r="../ui/assets/logos/",i={"A2A Agent":`${r}a2a_agent.png`,Ai21:`${r}ai21.svg`,"Ai21 Chat":`${r}ai21.svg`,"AI/ML API":`${r}aiml_api.svg`,"Aiohttp Openai":`${r}openai_small.svg`,Anthropic:`${r}anthropic.svg`,"Anthropic Text":`${r}anthropic.svg`,AssemblyAI:`${r}assemblyai_small.png`,Azure:`${r}microsoft_azure.svg`,"Azure AI Foundry (Studio)":`${r}microsoft_azure.svg`,"Azure Text":`${r}microsoft_azure.svg`,Baseten:`${r}baseten.svg`,"Amazon Bedrock":`${r}bedrock.svg`,"Amazon Bedrock Mantle":`${r}bedrock.svg`,"AWS SageMaker":`${r}bedrock.svg`,Cerebras:`${r}cerebras.svg`,Cloudflare:`${r}cloudflare.svg`,Codestral:`${r}mistral.svg`,Cohere:`${r}cohere.svg`,"Cohere Chat":`${r}cohere.svg`,Cometapi:`${r}cometapi.svg`,Cursor:`${r}cursor.svg`,"Databricks (Qwen API)":`${r}databricks.svg`,Dashscope:`${r}dashscope.svg`,Deepseek:`${r}deepseek.svg`,Deepgram:`${r}deepgram.png`,DeepInfra:`${r}deepinfra.png`,ElevenLabs:`${r}elevenlabs.png`,"Fal AI":`${r}fal_ai.jpg`,"Featherless Ai":`${r}featherless.svg`,"Fireworks AI":`${r}fireworks.svg`,Friendliai:`${r}friendli.svg`,"Github Copilot":`${r}github_copilot.svg`,"Google AI Studio":`${r}google.svg`,GradientAI:`${r}gradientai.svg`,Groq:`${r}groq.svg`,vllm:`${r}vllm.png`,Huggingface:`${r}huggingface.svg`,Hyperbolic:`${r}hyperbolic.svg`,Infinity:`${r}infinity.png`,"Jina AI":`${r}jina.png`,"Lambda Ai":`${r}lambda.svg`,"Lm Studio":`${r}lmstudio.svg`,"Meta Llama":`${r}meta_llama.svg`,MiniMax:`${r}minimax.svg`,"Mistral AI":`${r}mistral.svg`,Moonshot:`${r}moonshot.svg`,Morph:`${r}morph.svg`,Nebius:`${r}nebius.svg`,Novita:`${r}novita.svg`,"Nvidia Nim":`${r}nvidia_nim.svg`,Ollama:`${r}ollama.svg`,"Ollama Chat":`${r}ollama.svg`,Oobabooga:`${r}openai_small.svg`,OpenAI:`${r}openai_small.svg`,"Openai Like":`${r}openai_small.svg`,"OpenAI Text Completion":`${r}openai_small.svg`,"OpenAI-Compatible Text Completion Models (Together AI, etc.)":`${r}openai_small.svg`,"OpenAI-Compatible Endpoints (Together AI, etc.)":`${r}openai_small.svg`,Openrouter:`${r}openrouter.svg`,"Oracle Cloud Infrastructure (OCI)":`${r}oracle.svg`,Perplexity:`${r}perplexity-ai.svg`,Recraft:`${r}recraft.svg`,Replicate:`${r}replicate.svg`,RunwayML:`${r}runwayml.png`,Sagemaker:`${r}bedrock.svg`,Sambanova:`${r}sambanova.svg`,"SAP Generative AI Hub":`${r}sap.png`,Snowflake:`${r}snowflake.svg`,"Text-Completion-Codestral":`${r}mistral.svg`,TogetherAI:`${r}togetherai.svg`,Topaz:`${r}topaz.svg`,Triton:`${r}nvidia_triton.png`,V0:`${r}v0.svg`,"Vercel Ai Gateway":`${r}vercel.svg`,"Vertex AI (Anthropic, Gemini, etc.)":`${r}google.svg`,"Vertex Ai Beta":`${r}google.svg`,Vllm:`${r}vllm.png`,VolcEngine:`${r}volcengine.png`,"Voyage AI":`${r}voyage.webp`,Watsonx:`${r}watsonx.svg`,"Watsonx Text":`${r}watsonx.svg`,xAI:`${r}xai.svg`,Xinference:`${r}xinference.svg`};e.s(["Providers",()=>a,"getPlaceholder",0,e=>{if("AI/ML API"===e)return"aiml/flux-pro/v1.1";if("Vertex AI (Anthropic, Gemini, etc.)"===e)return"gemini-pro";if("Anthropic"==e)return"claude-3-opus";if("Amazon Bedrock"==e)return"claude-3-opus";if("AWS SageMaker"==e)return"sagemaker/jumpstart-dft-meta-textgeneration-llama-2-7b";else if("Google AI Studio"==e)return"gemini-pro";else if("Azure AI Foundry (Studio)"==e)return"azure_ai/command-r-plus";else if("Azure"==e)return"my-deployment";else if("Oracle Cloud Infrastructure (OCI)"==e)return"oci/xai.grok-4";else if("Snowflake"==e)return"snowflake/mistral-7b";else if("Voyage AI"==e)return"voyage/";else if("Jina AI"==e)return"jina_ai/";else if("VolcEngine"==e)return"volcengine/";else if("DeepInfra"==e)return"deepinfra/";else if("Fal AI"==e)return"fal_ai/fal-ai/flux-pro/v1.1-ultra";else if("RunwayML"==e)return"runwayml/gen4_turbo";else if("Watsonx"===e)return"watsonx/ibm/granite-3-3-8b-instruct";else if("Cursor"===e)return"cursor/claude-4-sonnet";else return"gpt-3.5-turbo"},"getProviderLogoAndName",0,e=>{if(!e)return{logo:"",displayName:"-"};if("gemini"===e.toLowerCase()){let e="Google AI Studio";return{logo:i[e],displayName:e}}let t=Object.keys(s).find(t=>s[t].toLowerCase()===e.toLowerCase());if(!t)return{logo:"",displayName:e};let r=a[t];return{logo:i[r],displayName:r}},"getProviderModels",0,(e,t)=>{console.log(`Provider key: ${e}`);let a=s[e];console.log(`Provider mapped to: ${a}`);let r=[];return e&&"object"==typeof t&&(Object.entries(t).forEach(([e,t])=>{if(null!==t&&"object"==typeof t&&"litellm_provider"in t){let s=t.litellm_provider;(s===a||"string"==typeof s&&s.includes(a))&&r.push(e)}}),"Cohere"==e&&(console.log("Adding cohere chat models"),Object.entries(t).forEach(([e,t])=>{null!==t&&"object"==typeof t&&"litellm_provider"in t&&"cohere_chat"===t.litellm_provider&&r.push(e)})),"AWS SageMaker"==e&&(console.log("Adding sagemaker chat models"),Object.entries(t).forEach(([e,t])=>{null!==t&&"object"==typeof t&&"litellm_provider"in t&&"sagemaker_chat"===t.litellm_provider&&r.push(e)}))),r},"providerLogoMap",0,i,"provider_map",0,s])},798496,e=>{"use strict";var t=e.i(843476),a=e.i(152990),s=e.i(682830),r=e.i(271645),i=e.i(269200),l=e.i(427612),n=e.i(64848),o=e.i(942232),c=e.i(496020),d=e.i(977572),m=e.i(94629),p=e.i(360820),u=e.i(871943);function g({data:e=[],columns:g,isLoading:x=!1,defaultSorting:h=[],pagination:_,onPaginationChange:f,enablePagination:b=!1,onRowClick:v}){let[j,A]=r.default.useState(h),[y]=r.default.useState("onChange"),[N,T]=r.default.useState({}),[C,S]=r.default.useState({}),I=(0,a.useReactTable)({data:e,columns:g,state:{sorting:j,columnSizing:N,columnVisibility:C,...b&&_?{pagination:_}:{}},columnResizeMode:y,onSortingChange:A,onColumnSizingChange:T,onColumnVisibilityChange:S,...b&&f?{onPaginationChange:f}:{},getCoreRowModel:(0,s.getCoreRowModel)(),getSortedRowModel:(0,s.getSortedRowModel)(),...b?{getPaginationRowModel:(0,s.getPaginationRowModel)()}:{},enableSorting:!0,enableColumnResizing:!0,defaultColumn:{minSize:40,maxSize:500}});return(0,t.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,t.jsx)("div",{className:"overflow-x-auto",children:(0,t.jsx)("div",{className:"relative min-w-full",children:(0,t.jsxs)(i.Table,{className:"[&_td]:py-2 [&_th]:py-2",style:{width:I.getTotalSize(),minWidth:"100%",tableLayout:"fixed"},children:[(0,t.jsx)(l.TableHead,{children:I.getHeaderGroups().map(e=>(0,t.jsx)(c.TableRow,{children:e.headers.map(e=>(0,t.jsxs)(n.TableHeaderCell,{className:`py-1 h-8 relative ${"actions"===e.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)] w-[120px] ml-8":""} ${e.column.columnDef.meta?.className||""}`,style:{width:"actions"===e.id?120:e.getSize(),position:"actions"===e.id?"sticky":"relative",right:"actions"===e.id?0:"auto"},onClick:e.column.getCanSort()?e.column.getToggleSortingHandler():void 0,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,a.flexRender)(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)(p.ChevronUpIcon,{className:"h-4 w-4 text-blue-500"}),desc:(0,t.jsx)(u.ChevronDownIcon,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,t.jsx)(m.SwitchVerticalIcon,{className:"h-4 w-4 text-gray-400"})})]}),e.column.getCanResize()&&(0,t.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 ${e.column.getIsResizing()?"bg-blue-500":"hover:bg-blue-200"}`})]},e.id))},e.id))}),(0,t.jsx)(o.TableBody,{children:x?(0,t.jsx)(c.TableRow,{children:(0,t.jsx)(d.TableCell,{colSpan:g.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:"🚅 Loading models..."})})})}):I.getRowModel().rows.length>0?I.getRowModel().rows.map(e=>(0,t.jsx)(c.TableRow,{onClick:()=>v?.(e.original),className:v?"cursor-pointer hover:bg-gray-50":"",children:e.getVisibleCells().map(e=>(0,t.jsx)(d.TableCell,{className:`py-0.5 overflow-hidden ${"actions"===e.column.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)] w-[120px] ml-8":""} ${e.column.columnDef.meta?.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,a.flexRender)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,t.jsx)(c.TableRow,{children:(0,t.jsx)(d.TableCell,{colSpan:g.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:"No models found"})})})})})]})})})})}e.s(["ModelDataTable",()=>g])},976883,174886,e=>{"use strict";var t=e.i(843476),a=e.i(275144),s=e.i(434626),r=e.i(271645);let i=r.forwardRef(function(e,t){return r.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:t},e),r.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"}))});var l=e.i(994388),n=e.i(304967),o=e.i(599724),c=e.i(629569),d=e.i(212931),m=e.i(199133),p=e.i(653496),u=e.i(262218),g=e.i(592968),x=e.i(991124);e.s(["Copy",()=>x.default],174886);var x=x,h=e.i(879664),h=h,_=e.i(798496),f=e.i(727749),b=e.i(402874),v=e.i(764205),j=e.i(190272),A=e.i(785913),y=e.i(916925);let{TabPane:N}=p.Tabs;e.s(["default",0,({accessToken:e,isEmbedded:T=!1})=>{let C,S,I,w,E,O,M,[k,L]=(0,r.useState)(null),[R,P]=(0,r.useState)(null),[$,D]=(0,r.useState)(null),[z,H]=(0,r.useState)("LiteLLM Gateway"),[G,F]=(0,r.useState)(null),[U,B]=(0,r.useState)(""),[V,K]=(0,r.useState)({}),[W,X]=(0,r.useState)(!0),[q,Y]=(0,r.useState)(!0),[J,Z]=(0,r.useState)(!0),[Q,ee]=(0,r.useState)(""),[et,ea]=(0,r.useState)(""),[es,er]=(0,r.useState)(""),[ei,el]=(0,r.useState)([]),[en,eo]=(0,r.useState)([]),[ec,ed]=(0,r.useState)([]),[em,ep]=(0,r.useState)([]),[eu,eg]=(0,r.useState)([]),[ex,eh]=(0,r.useState)("I'm alive! ✓"),[e_,ef]=(0,r.useState)(!1),[eb,ev]=(0,r.useState)(!1),[ej,eA]=(0,r.useState)(!1),[ey,eN]=(0,r.useState)(null),[eT,eC]=(0,r.useState)(null),[eS,eI]=(0,r.useState)(null),[ew,eE]=(0,r.useState)({}),[eO,eM]=(0,r.useState)("models");(0,r.useEffect)(()=>{(async()=>{try{await (0,v.getUiConfig)()}catch(e){console.error("Failed to get UI config:",e)}let e=async()=>{try{X(!0);let e=await (0,v.modelHubPublicModelsCall)();console.log("ModelHubData:",e),L(Array.isArray(e)?e:[])}catch(e){console.error("There was an error fetching the public model data",e),eh("Service unavailable")}finally{X(!1)}},t=async()=>{try{Y(!0);let e=await (0,v.agentHubPublicModelsCall)();console.log("AgentHubData:",e),P(Array.isArray(e)?e:[])}catch(e){console.error("There was an error fetching the public agent data",e)}finally{Y(!1)}},a=async()=>{try{Z(!0);let e=await (0,v.mcpHubPublicServersCall)();console.log("MCPHubData:",e),D(Array.isArray(e)?e:[])}catch(e){console.error("There was an error fetching the public MCP server data",e)}finally{Z(!1)}};(async()=>{let e=await (0,v.getPublicModelHubInfo)();console.log("Public Model Hub Info:",e),H(e.docs_title),F(e.custom_docs_description),B(e.litellm_version),K(e.useful_links||{})})(),e(),t(),a()})()},[]),(0,r.useEffect)(()=>{},[Q,ei,en,ec]);let ek=(0,r.useMemo)(()=>{if(!k||!Array.isArray(k))return[];let e=k;if(Q.trim()){let t=Q.toLowerCase(),a=t.split(/\s+/),s=k.filter(e=>{let s=e.model_group.toLowerCase();return!!s.includes(t)||a.every(e=>s.includes(e))});s.length>0&&(e=s.sort((e,a)=>{let s=e.model_group.toLowerCase(),r=a.model_group.toLowerCase(),i=1e3*(s===t),l=1e3*(r===t),n=100*!!s.startsWith(t),o=100*!!r.startsWith(t),c=50*!!t.split(/\s+/).every(e=>s.includes(e)),d=50*!!t.split(/\s+/).every(e=>r.includes(e)),m=s.length;return l+o+d+(1e3-r.length)-(i+n+c+(1e3-m))}))}return e.filter(e=>{let t=0===ei.length||ei.some(t=>e.providers.includes(t)),a=0===en.length||en.includes(e.mode||""),s=0===ec.length||Object.entries(e).filter(([e,t])=>e.startsWith("supports_")&&!0===t).some(([e])=>{let t=e.replace(/^supports_/,"").split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");return ec.includes(t)});return t&&a&&s})},[k,Q,ei,en,ec]),eL=(0,r.useMemo)(()=>{if(!R||!Array.isArray(R))return[];let e=R;if(et.trim()){let t=et.toLowerCase(),a=t.split(/\s+/);e=(e=R.filter(e=>{let s=e.name.toLowerCase(),r=e.description.toLowerCase();return!!(s.includes(t)||r.includes(t))||a.every(e=>s.includes(e)||r.includes(e))})).sort((e,a)=>{let s=e.name.toLowerCase(),r=a.name.toLowerCase(),i=1e3*(s===t),l=1e3*(r===t),n=100*!!s.startsWith(t),o=100*!!r.startsWith(t),c=i+n+(1e3-s.length);return l+o+(1e3-r.length)-c})}return e.filter(e=>0===em.length||e.skills?.some(e=>e.tags?.some(e=>em.includes(e))))},[R,et,em]),eR=(0,r.useMemo)(()=>{if(!$||!Array.isArray($))return[];let e=$;if(es.trim()){let t=es.toLowerCase(),a=t.split(/\s+/);e=(e=$.filter(e=>{let s=e.server_name.toLowerCase(),r=(e.mcp_info?.description||"").toLowerCase();return!!(s.includes(t)||r.includes(t))||a.every(e=>s.includes(e)||r.includes(e))})).sort((e,a)=>{let s=e.server_name.toLowerCase(),r=a.server_name.toLowerCase(),i=1e3*(s===t),l=1e3*(r===t),n=100*!!s.startsWith(t),o=100*!!r.startsWith(t),c=i+n+(1e3-s.length);return l+o+(1e3-r.length)-c})}return e.filter(e=>0===eu.length||eu.includes(e.transport))},[$,es,eu]),eP=e=>{navigator.clipboard.writeText(e),f.default.success("Copied to clipboard!")},e$=e=>e.replace(/^supports_/,"").split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" "),eD=e=>`$${(1e6*e).toFixed(4)}`,ez=e=>e?e>=1e3?`${(e/1e3).toFixed(0)}K`:e.toString():"N/A";return(0,t.jsx)(a.ThemeProvider,{accessToken:e,children:(0,t.jsxs)("div",{className:T?"w-full":"min-h-screen bg-white",children:[!T&&(0,t.jsx)(b.default,{userID:null,userEmail:null,userRole:null,premiumUser:!1,setProxySettings:eE,proxySettings:ew,accessToken:e||null,isPublicPage:!0,isDarkMode:!1,toggleDarkMode:()=>{}}),(0,t.jsxs)("div",{className:T?"w-full p-6":"w-full px-8 py-12",children:[T&&(0,t.jsx)("div",{className:"mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg",children:(0,t.jsx)("p",{className:"text-sm text-gray-700",children:"These are models, agents, and MCP servers your proxy admin has indicated are available in your company."})}),!T&&(0,t.jsxs)(n.Card,{className:"mb-10 p-8 bg-white border border-gray-200 rounded-lg shadow-sm",children:[(0,t.jsx)(c.Title,{className:"text-2xl font-semibold mb-6 text-gray-900",children:"About"}),(0,t.jsx)("p",{className:"text-gray-700 mb-6 text-base leading-relaxed",children:G||"Proxy Server to call 100+ LLMs in the OpenAI format."}),(0,t.jsx)("div",{className:"flex items-center space-x-3 text-sm text-gray-600",children:(0,t.jsxs)("span",{className:"flex items-center",children:[(0,t.jsx)("span",{className:"w-4 h-4 mr-2",children:"🔧"}),"Built with litellm: v",U]})})]}),V&&Object.keys(V).length>0&&(0,t.jsxs)(n.Card,{className:"mb-10 p-8 bg-white border border-gray-200 rounded-lg shadow-sm",children:[(0,t.jsx)(c.Title,{className:"text-2xl font-semibold mb-6 text-gray-900",children:"Useful Links"}),(0,t.jsx)("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:Object.entries(V||{}).map(([e,t])=>({title:e,url:"string"==typeof t?t:t.url,index:"string"==typeof t?0:t.index??0})).sort((e,t)=>e.index-t.index).map(({title:e,url:a})=>(0,t.jsxs)("button",{onClick:()=>window.open(a,"_blank"),className:"flex items-center space-x-3 text-blue-600 hover:text-blue-800 transition-colors p-3 rounded-lg hover:bg-blue-50 border border-gray-200",children:[(0,t.jsx)(s.ExternalLinkIcon,{className:"w-4 h-4"}),(0,t.jsx)(o.Text,{className:"text-sm font-medium",children:e})]},e))})]}),!T&&(0,t.jsxs)(n.Card,{className:"mb-10 p-8 bg-white border border-gray-200 rounded-lg shadow-sm",children:[(0,t.jsx)(c.Title,{className:"text-2xl font-semibold mb-6 text-gray-900",children:"Health and Endpoint Status"}),(0,t.jsx)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:(0,t.jsxs)(o.Text,{className:"text-green-600 font-medium text-sm",children:["Service status: ",ex]})})]}),(0,t.jsx)(n.Card,{className:"p-8 bg-white border border-gray-200 rounded-lg shadow-sm",children:(0,t.jsxs)(p.Tabs,{activeKey:eO,onChange:eM,size:"large",className:"public-hub-tabs",children:[(0,t.jsxs)(N,{tab:"Model Hub",children:[(0,t.jsx)("div",{className:"flex justify-between items-center mb-8",children:(0,t.jsx)(c.Title,{className:"text-2xl font-semibold text-gray-900",children:"Available Models"})}),(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8 p-6 bg-gray-50 rounded-lg border border-gray-200",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2 mb-3",children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium text-gray-700",children:"Search Models:"}),(0,t.jsx)(g.Tooltip,{title:"Smart search with relevance ranking - finds models containing your search terms, ranked by relevance. Try searching 'xai grok-4', 'claude-4', 'gpt-4', or 'sonnet'",placement:"top",children:(0,t.jsx)(h.default,{className:"w-4 h-4 text-gray-400 cursor-help"})})]}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(i,{className:"w-4 h-4 text-gray-400 absolute left-3 top-1/2 transform -translate-y-1/2"}),(0,t.jsx)("input",{type:"text",placeholder:"Search model names... (smart search enabled)",value:Q,onChange:e=>ee(e.target.value),className:"border border-gray-300 rounded-lg pl-10 pr-4 py-2 w-full text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white"})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium mb-3 text-gray-700",children:"Provider:"}),(0,t.jsx)(m.Select,{mode:"multiple",value:ei,onChange:e=>el(e),placeholder:"Select providers",className:"w-full",size:"large",allowClear:!0,optionRender:e=>{let{logo:a}=(0,y.getProviderLogoAndName)(e.value);return(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[a&&(0,t.jsx)("img",{src:a,alt:e.label,className:"w-5 h-5 flex-shrink-0 object-contain",onError:e=>{e.target.style.display="none"}}),(0,t.jsx)("span",{className:"capitalize",children:e.label})]})},children:k&&Array.isArray(k)&&(C=new Set,k.forEach(e=>{(e.providers??[]).forEach(e=>C.add(e))}),Array.from(C)).map(e=>(0,t.jsx)(m.Select.Option,{value:e,children:e},e))})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium mb-3 text-gray-700",children:"Mode:"}),(0,t.jsx)(m.Select,{mode:"multiple",value:en,onChange:e=>eo(e),placeholder:"Select modes",className:"w-full",size:"large",allowClear:!0,children:k&&Array.isArray(k)&&(S=new Set,k.forEach(e=>{e.mode&&S.add(e.mode)}),Array.from(S)).map(e=>(0,t.jsx)(m.Select.Option,{value:e,children:e},e))})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium mb-3 text-gray-700",children:"Features:"}),(0,t.jsx)(m.Select,{mode:"multiple",value:ec,onChange:e=>ed(e),placeholder:"Select features",className:"w-full",size:"large",allowClear:!0,children:k&&Array.isArray(k)&&(I=new Set,k.forEach(e=>{Object.entries(e).filter(([e,t])=>e.startsWith("supports_")&&!0===t).forEach(([e])=>{let t=e.replace(/^supports_/,"").split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");I.add(t)})}),Array.from(I).sort()).map(e=>(0,t.jsx)(m.Select.Option,{value:e,children:e},e))})]})]}),(0,t.jsx)(_.ModelDataTable,{columns:[{header:"Model Name",accessorKey:"model_group",enableSorting:!0,cell:({row:e})=>(0,t.jsx)("div",{className:"overflow-hidden",children:(0,t.jsx)(g.Tooltip,{title:e.original.model_group,children:(0,t.jsx)(l.Button,{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",onClick:()=>{eN(e.original),ef(!0)},children:e.original.model_group})})}),size:150},{header:"Providers",accessorKey:"providers",enableSorting:!0,cell:({row:e})=>{let a=e.original.providers??[];return(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:a.map(e=>{let{logo:a}=(0,y.getProviderLogoAndName)(e);return(0,t.jsxs)("div",{className:"flex items-center space-x-1 px-2 py-1 bg-gray-100 rounded text-xs",children:[a&&(0,t.jsx)("img",{src:a,alt:e,className:"w-3 h-3 flex-shrink-0 object-contain",onError:e=>{e.target.style.display="none"}}),(0,t.jsx)("span",{className:"capitalize",children:e})]},e)})})},size:120},{header:"Mode",accessorKey:"mode",enableSorting:!0,cell:({row:e})=>{let a=e.original.mode;return(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("span",{children:(e=>{switch(e?.toLowerCase()){case"chat":return"💬";case"rerank":return"🔄";case"embedding":return"📄";default:return"🤖"}})(a||"")}),(0,t.jsx)(o.Text,{children:a||"Chat"})]})},size:100},{header:"Max Input",accessorKey:"max_input_tokens",enableSorting:!0,cell:({row:e})=>(0,t.jsx)(o.Text,{className:"text-center",children:ez(e.original.max_input_tokens)}),size:100,meta:{className:"text-center"}},{header:"Max Output",accessorKey:"max_output_tokens",enableSorting:!0,cell:({row:e})=>(0,t.jsx)(o.Text,{className:"text-center",children:ez(e.original.max_output_tokens)}),size:100,meta:{className:"text-center"}},{header:"Input $/1M",accessorKey:"input_cost_per_token",enableSorting:!0,cell:({row:e})=>{let a=e.original.input_cost_per_token;return(0,t.jsx)(o.Text,{className:"text-center",children:a?eD(a):"Free"})},size:100,meta:{className:"text-center"}},{header:"Output $/1M",accessorKey:"output_cost_per_token",enableSorting:!0,cell:({row:e})=>{let a=e.original.output_cost_per_token;return(0,t.jsx)(o.Text,{className:"text-center",children:a?eD(a):"Free"})},size:100,meta:{className:"text-center"}},{header:"Features",accessorKey:"supports_vision",enableSorting:!1,cell:({row:e})=>{let a=Object.entries(e.original).filter(([e,t])=>e.startsWith("supports_")&&!0===t).map(([e])=>e$(e));return 0===a.length?(0,t.jsx)(o.Text,{className:"text-gray-400",children:"-"}):1===a.length?(0,t.jsx)("div",{className:"h-6 flex items-center",children:(0,t.jsx)(u.Tag,{color:"blue",className:"text-xs",children:a[0]})}):(0,t.jsxs)("div",{className:"h-6 flex items-center space-x-1",children:[(0,t.jsx)(u.Tag,{color:"blue",className:"text-xs",children:a[0]}),(0,t.jsx)(g.Tooltip,{title:(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("div",{className:"font-medium",children:"All Features:"}),a.map((e,a)=>(0,t.jsxs)("div",{className:"text-xs",children:["• ",e]},a))]}),trigger:"click",placement:"topLeft",children:(0,t.jsxs)("span",{className:"text-xs text-blue-600 cursor-pointer hover:text-blue-800 hover:underline",onClick:e=>e.stopPropagation(),children:["+",a.length-1]})})]})},size:120},{header:"Health Status",accessorKey:"health_status",enableSorting:!0,cell:({row:e})=>{let a=e.original,s="healthy"===a.health_status?"green":"unhealthy"===a.health_status?"red":"default",r=a.health_response_time?`Response Time: ${Number(a.health_response_time).toFixed(2)}ms`:"N/A",i=a.health_checked_at?`Last Checked: ${new Date(a.health_checked_at).toLocaleString()}`:"N/A";return(0,t.jsx)(g.Tooltip,{title:(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{children:r}),(0,t.jsx)("div",{children:i})]}),children:(0,t.jsx)(u.Tag,{color:s,children:(0,t.jsx)("span",{className:"capitalize",children:a.health_status??"Unknown"})},a.model_group)})},size:100},{header:"Limits",accessorKey:"rpm",enableSorting:!0,cell:({row:e})=>{var a,s;let r,i=e.original;return(0,t.jsx)(o.Text,{className:"text-xs text-gray-600",children:(a=i.rpm,s=i.tpm,r=[],a&&r.push(`RPM: ${a.toLocaleString()}`),s&&r.push(`TPM: ${s.toLocaleString()}`),r.length>0?r.join(", "):"N/A")})},size:150}],data:ek,isLoading:W,defaultSorting:[{id:"model_group",desc:!1}]}),(0,t.jsx)("div",{className:"mt-8 text-center",children:(0,t.jsxs)(o.Text,{className:"text-sm text-gray-600",children:["Showing ",ek.length," of ",k?.length||0," models"]})})]},"models"),R&&Array.isArray(R)&&R.length>0&&(0,t.jsxs)(N,{tab:"Agent Hub",children:[(0,t.jsx)("div",{className:"flex justify-between items-center mb-8",children:(0,t.jsx)(c.Title,{className:"text-2xl font-semibold text-gray-900",children:"Available Agents"})}),(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6 mb-8 p-6 bg-gray-50 rounded-lg border border-gray-200",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2 mb-3",children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium text-gray-700",children:"Search Agents:"}),(0,t.jsx)(g.Tooltip,{title:"Search agents by name or description",placement:"top",children:(0,t.jsx)(h.default,{className:"w-4 h-4 text-gray-400 cursor-help"})})]}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(i,{className:"w-4 h-4 text-gray-400 absolute left-3 top-1/2 transform -translate-y-1/2"}),(0,t.jsx)("input",{type:"text",placeholder:"Search agent names or descriptions...",value:et,onChange:e=>ea(e.target.value),className:"border border-gray-300 rounded-lg pl-10 pr-4 py-2 w-full text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white"})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium mb-3 text-gray-700",children:"Skills:"}),(0,t.jsx)(m.Select,{mode:"multiple",value:em,onChange:e=>ep(e),placeholder:"Select skills",className:"w-full",size:"large",allowClear:!0,children:R&&Array.isArray(R)&&(w=new Set,R.forEach(e=>{e.skills?.forEach(e=>{e.tags?.forEach(e=>w.add(e))})}),Array.from(w).sort()).map(e=>(0,t.jsx)(m.Select.Option,{value:e,children:e},e))})]})]}),(0,t.jsx)(_.ModelDataTable,{columns:[{header:"Agent Name",accessorKey:"name",enableSorting:!0,cell:({row:e})=>(0,t.jsx)("div",{className:"overflow-hidden",children:(0,t.jsx)(g.Tooltip,{title:e.original.name,children:(0,t.jsx)(l.Button,{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",onClick:()=>{eC(e.original),ev(!0)},children:e.original.name})})}),size:150},{header:"Description",accessorKey:"description",enableSorting:!1,cell:({row:e})=>{let a=e.original.description??"",s=a.length>80?a.substring(0,80)+"...":a;return(0,t.jsx)(g.Tooltip,{title:a,children:(0,t.jsx)(o.Text,{className:"text-sm text-gray-700",children:s})})},size:250},{header:"Version",accessorKey:"version",enableSorting:!0,cell:({row:e})=>(0,t.jsx)(o.Text,{className:"text-sm",children:e.original.version}),size:80},{header:"Provider",accessorKey:"provider",enableSorting:!1,cell:({row:e})=>{let a=e.original.provider;return a?(0,t.jsx)("div",{className:"text-sm",children:(0,t.jsx)(o.Text,{className:"font-medium",children:a.organization})}):(0,t.jsx)(o.Text,{className:"text-gray-400",children:"-"})},size:120},{header:"Skills",accessorKey:"skills",enableSorting:!1,cell:({row:e})=>{let a=e.original.skills||[];return 0===a.length?(0,t.jsx)(o.Text,{className:"text-gray-400",children:"-"}):1===a.length?(0,t.jsx)("div",{className:"h-6 flex items-center",children:(0,t.jsx)(u.Tag,{color:"purple",className:"text-xs",children:a[0].name})}):(0,t.jsxs)("div",{className:"h-6 flex items-center space-x-1",children:[(0,t.jsx)(u.Tag,{color:"purple",className:"text-xs",children:a[0].name}),(0,t.jsx)(g.Tooltip,{title:(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("div",{className:"font-medium",children:"All Skills:"}),a.map((e,a)=>(0,t.jsxs)("div",{className:"text-xs",children:["• ",e.name]},a))]}),trigger:"click",placement:"topLeft",children:(0,t.jsxs)("span",{className:"text-xs text-purple-600 cursor-pointer hover:text-purple-800 hover:underline",onClick:e=>e.stopPropagation(),children:["+",a.length-1]})})]})},size:150},{header:"Capabilities",accessorKey:"capabilities",enableSorting:!1,cell:({row:e})=>{let a=Object.entries(e.original.capabilities||{}).filter(([e,t])=>!0===t).map(([e])=>e);return 0===a.length?(0,t.jsx)(o.Text,{className:"text-gray-400",children:"-"}):(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:a.map(e=>(0,t.jsx)(u.Tag,{color:"green",className:"text-xs capitalize",children:e},e))})},size:150}],data:eL,isLoading:q,defaultSorting:[{id:"name",desc:!1}]}),(0,t.jsx)("div",{className:"mt-8 text-center",children:(0,t.jsxs)(o.Text,{className:"text-sm text-gray-600",children:["Showing ",eL.length," of ",R?.length||0," agents"]})})]},"agents"),$&&Array.isArray($)&&$.length>0&&(0,t.jsxs)(N,{tab:"MCP Hub",children:[(0,t.jsx)("div",{className:"flex justify-between items-center mb-8",children:(0,t.jsx)(c.Title,{className:"text-2xl font-semibold text-gray-900",children:"Available MCP Servers"})}),(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6 mb-8 p-6 bg-gray-50 rounded-lg border border-gray-200",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2 mb-3",children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium text-gray-700",children:"Search MCP Servers:"}),(0,t.jsx)(g.Tooltip,{title:"Search MCP servers by name or description",placement:"top",children:(0,t.jsx)(h.default,{className:"w-4 h-4 text-gray-400 cursor-help"})})]}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(i,{className:"w-4 h-4 text-gray-400 absolute left-3 top-1/2 transform -translate-y-1/2"}),(0,t.jsx)("input",{type:"text",placeholder:"Search MCP server names or descriptions...",value:es,onChange:e=>er(e.target.value),className:"border border-gray-300 rounded-lg pl-10 pr-4 py-2 w-full text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white"})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium mb-3 text-gray-700",children:"Transport:"}),(0,t.jsx)(m.Select,{mode:"multiple",value:eu,onChange:e=>eg(e),placeholder:"Select transport types",className:"w-full",size:"large",allowClear:!0,children:$&&Array.isArray($)&&(E=new Set,$.forEach(e=>{e.transport&&E.add(e.transport)}),Array.from(E).sort()).map(e=>(0,t.jsx)(m.Select.Option,{value:e,children:e},e))})]})]}),(0,t.jsx)(_.ModelDataTable,{columns:[{header:"Server Name",accessorKey:"server_name",enableSorting:!0,cell:({row:e})=>(0,t.jsx)("div",{className:"overflow-hidden",children:(0,t.jsx)(g.Tooltip,{title:e.original.server_name,children:(0,t.jsx)(l.Button,{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",onClick:()=>{eI(e.original),eA(!0)},children:e.original.server_name})})}),size:150},{header:"Description",accessorKey:"mcp_info.description",enableSorting:!1,cell:({row:e})=>{let a=String(e.original.mcp_info?.description??"-"),s=a.length>80?a.substring(0,80)+"...":a;return(0,t.jsx)(g.Tooltip,{title:a,children:(0,t.jsx)(o.Text,{className:"text-sm text-gray-700",children:s})})},size:250},{header:"URL",accessorKey:"url",enableSorting:!1,cell:({row:e})=>{let a=e.original.url??"",s=a.length>40?a.substring(0,40)+"...":a;return(0,t.jsx)(g.Tooltip,{title:a,children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)(o.Text,{className:"text-xs font-mono",children:s}),(0,t.jsx)(x.default,{onClick:()=>eP(a),className:"cursor-pointer text-gray-500 hover:text-blue-500 w-3 h-3"})]})})},size:200},{header:"Transport",accessorKey:"transport",enableSorting:!0,cell:({row:e})=>{let a=e.original.transport;return(0,t.jsx)(u.Tag,{color:"blue",className:"text-xs uppercase",children:a})},size:100},{header:"Auth Type",accessorKey:"auth_type",enableSorting:!0,cell:({row:e})=>{let a=e.original.auth_type;return(0,t.jsx)(u.Tag,{color:"none"===a?"gray":"green",className:"text-xs capitalize",children:a})},size:100}],data:eR,isLoading:J,defaultSorting:[{id:"server_name",desc:!1}]}),(0,t.jsx)("div",{className:"mt-8 text-center",children:(0,t.jsxs)(o.Text,{className:"text-sm text-gray-600",children:["Showing ",eR.length," of ",$?.length||0," MCP servers"]})})]},"mcp")]})})]}),(0,t.jsx)(d.Modal,{title:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("span",{children:ey?.model_group||"Model Details"}),ey&&(0,t.jsx)(g.Tooltip,{title:"Copy model name",children:(0,t.jsx)(x.default,{onClick:()=>eP(ey.model_group),className:"cursor-pointer text-gray-500 hover:text-blue-500 w-4 h-4"})})]}),width:1e3,open:e_,footer:null,onOk:()=>{ef(!1),eN(null)},onCancel:()=>{ef(!1),eN(null)},children:ey&&(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Model Overview"}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-4 mb-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Model Name:"}),(0,t.jsx)(o.Text,{children:ey.model_group})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Mode:"}),(0,t.jsx)(o.Text,{children:ey.mode||"Not specified"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Providers:"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-1 mt-1",children:(ey.providers??[]).map(e=>{let{logo:a}=(0,y.getProviderLogoAndName)(e);return(0,t.jsx)(u.Tag,{color:"blue",children:(0,t.jsxs)("div",{className:"flex items-center space-x-1",children:[a&&(0,t.jsx)("img",{src:a,alt:e,className:"w-3 h-3 flex-shrink-0 object-contain",onError:e=>{e.target.style.display="none"}}),(0,t.jsx)("span",{className:"capitalize",children:e})]})},e)})})]})]}),ey.model_group.includes("*")&&(0,t.jsx)("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 mb-4",children:(0,t.jsxs)("div",{className:"flex items-start space-x-2",children:[(0,t.jsx)(h.default,{className:"w-4 h-4 text-blue-600 mt-0.5 flex-shrink-0"}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium text-blue-900 mb-2",children:"Wildcard Routing"}),(0,t.jsxs)(o.Text,{className:"text-sm text-blue-800 mb-2",children:["This model uses wildcard routing. You can pass any value where you see the"," ",(0,t.jsx)("code",{className:"bg-blue-100 px-1 py-0.5 rounded text-xs",children:"*"})," symbol."]}),(0,t.jsxs)(o.Text,{className:"text-sm text-blue-800",children:["For example, with"," ",(0,t.jsx)("code",{className:"bg-blue-100 px-1 py-0.5 rounded text-xs",children:ey.model_group}),", you can use any string (",(0,t.jsx)("code",{className:"bg-blue-100 px-1 py-0.5 rounded text-xs",children:ey.model_group.replace("*","my-custom-value")}),") that matches this pattern."]})]})]})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Token & Cost Information"}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Max Input Tokens:"}),(0,t.jsx)(o.Text,{children:ey.max_input_tokens?.toLocaleString()||"Not specified"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Max Output Tokens:"}),(0,t.jsx)(o.Text,{children:ey.max_output_tokens?.toLocaleString()||"Not specified"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Input Cost per 1M Tokens:"}),(0,t.jsx)(o.Text,{children:ey.input_cost_per_token?eD(ey.input_cost_per_token):"Not specified"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Output Cost per 1M Tokens:"}),(0,t.jsx)(o.Text,{children:ey.output_cost_per_token?eD(ey.output_cost_per_token):"Not specified"})]})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Capabilities"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:(O=Object.entries(ey).filter(([e,t])=>e.startsWith("supports_")&&!0===t).map(([e])=>e),M=["green","blue","purple","orange","red","yellow"],0===O.length?(0,t.jsx)(o.Text,{className:"text-gray-500",children:"No special capabilities listed"}):O.map((e,a)=>(0,t.jsx)(u.Tag,{color:M[a%M.length],children:e$(e)},e)))})]}),(ey.tpm||ey.rpm)&&(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Rate Limits"}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-4",children:[ey.tpm&&(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Tokens per Minute:"}),(0,t.jsx)(o.Text,{children:ey.tpm.toLocaleString()})]}),ey.rpm&&(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Requests per Minute:"}),(0,t.jsx)(o.Text,{children:ey.rpm.toLocaleString()})]})]})]}),ey.supported_openai_params&&ey.supported_openai_params.length>0&&(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Supported OpenAI Parameters"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:ey.supported_openai_params.map(e=>(0,t.jsx)(u.Tag,{color:"green",children:e},e))})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Usage Example"}),(0,t.jsx)("div",{className:"bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto",children:(0,t.jsx)("pre",{className:"text-sm",children:(0,j.generateCodeSnippet)({apiKeySource:"custom",accessToken:null,apiKey:"your_api_key",inputMessage:"Hello, how are you?",chatHistory:[{role:"user",content:"Hello, how are you?",isImage:!1}],selectedTags:[],selectedVectorStores:[],selectedGuardrails:[],selectedPolicies:[],selectedMCPServers:[],endpointType:(0,A.getEndpointType)(ey.mode||"chat"),selectedModel:ey.model_group,selectedSdk:"openai"})})}),(0,t.jsx)("div",{className:"mt-2 text-right",children:(0,t.jsx)("button",{onClick:()=>{eP((0,j.generateCodeSnippet)({apiKeySource:"custom",accessToken:null,apiKey:"your_api_key",inputMessage:"Hello, how are you?",chatHistory:[{role:"user",content:"Hello, how are you?",isImage:!1}],selectedTags:[],selectedVectorStores:[],selectedGuardrails:[],selectedPolicies:[],selectedMCPServers:[],endpointType:(0,A.getEndpointType)(ey.mode||"chat"),selectedModel:ey.model_group,selectedSdk:"openai"}))},className:"text-sm text-blue-600 hover:text-blue-800 cursor-pointer",children:"Copy to clipboard"})})]})]})}),(0,t.jsx)(d.Modal,{title:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("span",{children:eT?.name||"Agent Details"}),eT&&(0,t.jsx)(g.Tooltip,{title:"Copy agent name",children:(0,t.jsx)(x.default,{onClick:()=>eP(eT.name),className:"cursor-pointer text-gray-500 hover:text-blue-500 w-4 h-4"})})]}),width:1e3,open:eb,footer:null,onOk:()=>{ev(!1),eC(null)},onCancel:()=>{ev(!1),eC(null)},children:eT&&(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Agent Overview"}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-4 mb-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Name:"}),(0,t.jsx)(o.Text,{children:eT.name})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Version:"}),(0,t.jsx)(o.Text,{children:eT.version})]}),(0,t.jsxs)("div",{className:"col-span-2",children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Description:"}),(0,t.jsx)(o.Text,{children:eT.description})]}),eT.url&&(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"URL:"}),(0,t.jsx)("a",{href:eT.url,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 text-sm break-all",children:eT.url})]})]})]}),eT.capabilities&&(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Capabilities"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:Object.entries(eT.capabilities).filter(([e,t])=>!0===t).map(([e])=>(0,t.jsx)(u.Tag,{color:"green",className:"capitalize",children:e},e))})]}),eT.skills&&eT.skills.length>0&&(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Skills"}),(0,t.jsx)("div",{className:"space-y-4",children:eT.skills.map((e,a)=>(0,t.jsxs)("div",{className:"border border-gray-200 rounded-lg p-4",children:[(0,t.jsx)("div",{className:"flex items-start justify-between mb-2",children:(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium text-base",children:e.name}),(0,t.jsx)(o.Text,{className:"text-sm text-gray-600",children:e.description})]})}),e.tags&&e.tags.length>0&&(0,t.jsx)("div",{className:"flex flex-wrap gap-1 mt-2",children:e.tags.map(e=>(0,t.jsx)(u.Tag,{color:"purple",className:"text-xs",children:e},e))})]},a))})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Input/Output Modes"}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Input Modes:"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-1 mt-1",children:(eT.defaultInputModes??[]).map(e=>(0,t.jsx)(u.Tag,{color:"blue",children:e},e))})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Output Modes:"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-1 mt-1",children:(eT.defaultOutputModes??[]).map(e=>(0,t.jsx)(u.Tag,{color:"blue",children:e},e))})]})]})]}),eT.documentationUrl&&(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Documentation"}),(0,t.jsxs)("a",{href:eT.documentationUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 flex items-center space-x-2",children:[(0,t.jsx)(s.ExternalLinkIcon,{className:"w-4 h-4"}),(0,t.jsx)("span",{children:"View Documentation"})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Usage Example (A2A Protocol)"}),(0,t.jsxs)("div",{className:"mb-4",children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium mb-2 text-gray-700",children:"Step 1: Retrieve Agent Card"}),(0,t.jsx)("div",{className:"bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto",children:(0,t.jsx)("pre",{className:"text-xs",children:`base_url = '${eT.url}' + +resolver = A2ACardResolver( + httpx_client=httpx_client, + base_url=base_url, + # agent_card_path uses default, extended_agent_card_path also uses default +) + +# Fetch Public Agent Card and Initialize Client +final_agent_card_to_use: AgentCard | None = None +_public_card = ( + await resolver.get_agent_card() +) # Fetches from default public path - \`/agents/{agent_id}/\` +final_agent_card_to_use = _public_card + +if _public_card.supports_authenticated_extended_card: + try: + auth_headers_dict = { + 'Authorization': 'Bearer dummy-token-for-extended-card' + } + _extended_card = await resolver.get_agent_card( + relative_card_path=EXTENDED_AGENT_CARD_PATH, + http_kwargs={'headers': auth_headers_dict}, + ) + final_agent_card_to_use = ( + _extended_card # Update to use the extended card + ) + except Exception as e_extended: + logger.warning( + f'Failed to fetch extended agent card: {e_extended}. Will proceed with public card.', + exc_info=True, + )`})}),(0,t.jsx)("div",{className:"mt-2 text-right",children:(0,t.jsx)("button",{onClick:()=>{eP(`from a2a.client import A2ACardResolver, A2AClient +from a2a.types import ( + AgentCard, + MessageSendParams, + SendMessageRequest, + SendStreamingMessageRequest, +) +from a2a.utils.constants import ( + AGENT_CARD_WELL_KNOWN_PATH, + EXTENDED_AGENT_CARD_PATH, +) + +base_url = '${eT.url}' + +resolver = A2ACardResolver( + httpx_client=httpx_client, + base_url=base_url, + # agent_card_path uses default, extended_agent_card_path also uses default +) + +# Fetch Public Agent Card and Initialize Client +final_agent_card_to_use: AgentCard | None = None +_public_card = ( + await resolver.get_agent_card() +) # Fetches from default public path - \`/agents/{agent_id}/\` +final_agent_card_to_use = _public_card + +if _public_card.supports_authenticated_extended_card: + try: + auth_headers_dict = { + 'Authorization': 'Bearer dummy-token-for-extended-card' + } + _extended_card = await resolver.get_agent_card( + relative_card_path=EXTENDED_AGENT_CARD_PATH, + http_kwargs={'headers': auth_headers_dict}, + ) + final_agent_card_to_use = ( + _extended_card # Update to use the extended card + ) + except Exception as e_extended: + logger.warning( + f'Failed to fetch extended agent card: {e_extended}. Will proceed with public card.', + exc_info=True, + )`)},className:"text-sm text-blue-600 hover:text-blue-800 cursor-pointer",children:"Copy to clipboard"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium mb-2 text-gray-700",children:"Step 2: Call the Agent"}),(0,t.jsx)("div",{className:"bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto",children:(0,t.jsx)("pre",{className:"text-xs",children:`client = A2AClient( + httpx_client=httpx_client, agent_card=final_agent_card_to_use +) + +send_message_payload: dict[str, Any] = { + 'message': { + 'role': 'user', + 'parts': [ + {'kind': 'text', 'text': 'how much is 10 USD in INR?'} + ], + 'messageId': uuid4().hex, + }, +} +request = SendMessageRequest( + id=str(uuid4()), params=MessageSendParams(**send_message_payload) +) + +response = await client.send_message(request) +print(response.model_dump(mode='json', exclude_none=True))`})}),(0,t.jsx)("div",{className:"mt-2 text-right",children:(0,t.jsx)("button",{onClick:()=>{eP(`client = A2AClient( + httpx_client=httpx_client, agent_card=final_agent_card_to_use +) + +send_message_payload: dict[str, Any] = { + 'message': { + 'role': 'user', + 'parts': [ + {'kind': 'text', 'text': 'how much is 10 USD in INR?'} + ], + 'messageId': uuid4().hex, + }, +} +request = SendMessageRequest( + id=str(uuid4()), params=MessageSendParams(**send_message_payload) +) + +response = await client.send_message(request) +print(response.model_dump(mode='json', exclude_none=True))`)},className:"text-sm text-blue-600 hover:text-blue-800 cursor-pointer",children:"Copy to clipboard"})})]})]})]})}),(0,t.jsx)(d.Modal,{title:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("span",{children:eS?.server_name||"MCP Server Details"}),eS&&(0,t.jsx)(g.Tooltip,{title:"Copy server name",children:(0,t.jsx)(x.default,{onClick:()=>eP(eS.server_name),className:"cursor-pointer text-gray-500 hover:text-blue-500 w-4 h-4"})})]}),width:1e3,open:ej,footer:null,onOk:()=>{eA(!1),eI(null)},onCancel:()=>{eA(!1),eI(null)},children:eS&&(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Server Overview"}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-4 mb-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Server Name:"}),(0,t.jsx)(o.Text,{children:eS.server_name})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Transport:"}),(0,t.jsx)(u.Tag,{color:"blue",children:eS.transport})]}),eS.alias&&(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Alias:"}),(0,t.jsx)(o.Text,{children:eS.alias})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Auth Type:"}),(0,t.jsx)(u.Tag,{color:"none"===eS.auth_type?"gray":"green",children:eS.auth_type})]}),(0,t.jsxs)("div",{className:"col-span-2",children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Description:"}),(0,t.jsx)(o.Text,{children:eS.mcp_info?.description||"-"})]}),(0,t.jsxs)("div",{className:"col-span-2",children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"URL:"}),(0,t.jsxs)("a",{href:eS.url,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 text-sm break-all flex items-center space-x-2",children:[(0,t.jsx)("span",{children:eS.url}),(0,t.jsx)(s.ExternalLinkIcon,{className:"w-4 h-4"})]})]})]})]}),eS.mcp_info&&Object.keys(eS.mcp_info).length>0&&(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Additional Information"}),(0,t.jsx)("div",{className:"bg-gray-50 p-4 rounded-lg",children:(0,t.jsx)("pre",{className:"text-xs overflow-x-auto",children:JSON.stringify(eS.mcp_info,null,2)})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Usage Example"}),(0,t.jsx)("div",{className:"bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto",children:(0,t.jsx)("pre",{className:"text-sm",children:`# Using MCP Server with Python FastMCP + +from fastmcp import Client +import asyncio + +# Standard MCP configuration +config = { + "mcpServers": { + "${eS.server_name}": { + "url": "http://localhost:4000/${eS.server_name}/mcp", + "headers": { + "x-litellm-api-key": "Bearer sk-1234" + } + } + } +} + +# Create a client that connects to the server +client = Client(config) + +async def main(): + async with client: + # List available tools + tools = await client.list_tools() + print(f"Available tools: {[tool.name for tool in tools]}") + + # Call a tool + response = await client.call_tool( + name="tool_name", + arguments={"arg": "value"} + ) + print(f"Response: {response}") + +if __name__ == "__main__": + asyncio.run(main())`})}),(0,t.jsx)("div",{className:"mt-2 text-right",children:(0,t.jsx)("button",{onClick:()=>{eP(`# Using MCP Server with Python FastMCP + +from fastmcp import Client +import asyncio + +# Standard MCP configuration +config = { + "mcpServers": { + "${eS.server_name}": { + "url": "http://localhost:4000/${eS.server_name}/mcp", + "headers": { + "x-litellm-api-key": "Bearer sk-1234" + } + } + } +} + +# Create a client that connects to the server +client = Client(config) + +async def main(): + async with client: + # List available tools + tools = await client.list_tools() + print(f"Available tools: {[tool.name for tool in tools]}") + + # Call a tool + response = await client.call_tool( + name="tool_name", + arguments={"arg": "value"} + ) + print(f"Response: {response}") + +if __name__ == "__main__": + asyncio.run(main())`)},className:"text-sm text-blue-600 hover:text-blue-800 cursor-pointer",children:"Copy to clipboard"})})]})]})})]})})}],976883)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/1a87dd202db8e85d.js b/litellm/proxy/_experimental/out/_next/static/chunks/1a87dd202db8e85d.js deleted file mode 100644 index 26999d732c0..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/1a87dd202db8e85d.js +++ /dev/null @@ -1 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,355619,e=>{"use strict";var s=e.i(764205);let t=async(e,t,l)=>{try{if(null===e||null===t)return;if(null!==l){let a=(await (0,s.modelAvailableCall)(l,e,t,!0,null,!0)).data.map(e=>e.id),r=[],i=[];return a.forEach(e=>{e.endsWith("/*")?r.push(e):i.push(e)}),[...r,...i]}}catch(e){console.error("Error fetching user models:",e)}};e.s(["fetchAvailableModelsForTeamOrKey",0,t,"getModelDisplayName",0,e=>{if("all-proxy-models"===e)return"All Proxy Models";if(e.endsWith("/*")){let s=e.replace("/*","");return`All ${s} models`}return e},"unfurlWildcardModelsInList",0,(e,s)=>{let t=[],l=[];return console.log("teamModels",e),console.log("allModels",s),e.forEach(e=>{if(e.endsWith("/*")){let a=e.replace("/*",""),r=s.filter(e=>e.startsWith(a+"/"));l.push(...r),t.push(e)}else l.push(e)}),[...t,...l].filter((e,s,t)=>t.indexOf(e)===s)}])},860585,e=>{"use strict";var s=e.i(843476),t=e.i(199133);let{Option:l}=t.Select;e.s(["default",0,({value:e,onChange:a,className:r="",style:i={}})=>(0,s.jsxs)(t.Select,{style:{width:"100%",...i},value:e||void 0,onChange:a,className:r,placeholder:"n/a",allowClear:!0,children:[(0,s.jsx)(l,{value:"24h",children:"daily"}),(0,s.jsx)(l,{value:"7d",children:"weekly"}),(0,s.jsx)(l,{value:"30d",children:"monthly"})]}),"getBudgetDurationLabel",0,e=>e?({"24h":"daily","7d":"weekly","30d":"monthly"})[e]||e:"Not set"])},663435,e=>{"use strict";var s=e.i(843476),t=e.i(199133);e.s(["default",0,({teams:e,value:l,onChange:a,disabled:r,loading:i})=>(0,s.jsx)(t.Select,{showSearch:!0,placeholder:"Search or select a team",value:l,onChange:a,disabled:r,loading:i,allowClear:!0,filterOption:(s,t)=>{if(!t)return!1;let l=e?.find(e=>e.team_id===t.key);if(!l)return!1;let a=s.toLowerCase().trim(),r=(l.team_alias||"").toLowerCase(),i=(l.team_id||"").toLowerCase();return r.includes(a)||i.includes(a)},optionFilterProp:"children",children:e?.map(e=>(0,s.jsxs)(t.Select.Option,{value:e.team_id,children:[(0,s.jsx)("span",{className:"font-medium",children:e.team_alias})," ",(0,s.jsxs)("span",{className:"text-gray-500",children:["(",e.team_id,")"]})]},e.team_id))})])},213205,e=>{"use strict";e.i(247167);var s=e.i(931067),t=e.i(271645);let l={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M678.3 642.4c24.2-13 51.9-20.4 81.4-20.4h.1c3 0 4.4-3.6 2.2-5.6a371.67 371.67 0 00-103.7-65.8c-.4-.2-.8-.3-1.2-.5C719.2 505 759.6 431.7 759.6 349c0-137-110.8-248-247.5-248S264.7 212 264.7 349c0 82.7 40.4 156 102.6 201.1-.4.2-.8.3-1.2.5-44.7 18.9-84.8 46-119.3 80.6a373.42 373.42 0 00-80.4 119.5A373.6 373.6 0 00137 888.8a8 8 0 008 8.2h59.9c4.3 0 7.9-3.5 8-7.8 2-77.2 32.9-149.5 87.6-204.3C357 628.2 432.2 597 512.2 597c56.7 0 111.1 15.7 158 45.1a8.1 8.1 0 008.1.3zM512.2 521c-45.8 0-88.9-17.9-121.4-50.4A171.2 171.2 0 01340.5 349c0-45.9 17.9-89.1 50.3-121.6S466.3 177 512.2 177s88.9 17.9 121.4 50.4A171.2 171.2 0 01683.9 349c0 45.9-17.9 89.1-50.3 121.6C601.1 503.1 558 521 512.2 521zM880 759h-84v-84c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v84h-84c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h84v84c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8v-84h84c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8z"}}]},name:"user-add",theme:"outlined"};var a=e.i(9583),r=t.forwardRef(function(e,r){return t.createElement(a.default,(0,s.default)({},e,{ref:r,icon:l}))});e.s(["UserAddOutlined",0,r],213205)},285027,e=>{"use strict";e.i(247167);var s=e.i(931067),t=e.i(271645);let l={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"};var a=e.i(9583),r=t.forwardRef(function(e,r){return t.createElement(a.default,(0,s.default)({},e,{ref:r,icon:l}))});e.s(["WarningOutlined",0,r],285027)},447082,e=>{"use strict";var s=e.i(843476),t=e.i(271645),l=e.i(994388),a=e.i(599724),r=e.i(212931),i=e.i(291542),n=e.i(515831),d=e.i(898586),o=e.i(519756),c=e.i(737434),m=e.i(285027),u=e.i(993914),x=e.i(955135);e.i(247167);var h=e.i(931067);let f={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"};var p=e.i(9583),g=t.forwardRef(function(e,s){return t.createElement(p.default,(0,h.default)({},e,{ref:s,icon:f}))}),j=e.i(764205),v=e.i(59935),b=e.i(220508),y=e.i(964306);let w=t.forwardRef(function(e,s){return t.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:s},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"}))});var N=e.i(237016),_=e.i(727749);e.s(["default",0,({accessToken:e,teams:h,possibleUIRoles:f,onUsersCreated:p})=>{let[C,S]=(0,t.useState)(!1),[k,I]=(0,t.useState)([]),[U,T]=(0,t.useState)(!1),[L,V]=(0,t.useState)(null),[B,O]=(0,t.useState)(null),[M,F]=(0,t.useState)(null),[E,P]=(0,t.useState)(null),[R,A]=(0,t.useState)(null),[D,$]=(0,t.useState)("http://localhost:4000");(0,t.useEffect)(()=>{(async()=>{try{let s=await (0,j.getProxyUISettings)(e);A(s)}catch(e){console.error("Error fetching UI settings:",e)}})(),$(new URL("/",window.location.href).toString())},[e]);let z=async()=>{T(!0);let s=k.map(e=>({...e,status:"pending"}));I(s);let t=!1;for(let l=0;le.trim()).filter(Boolean),0===s.teams.length&&delete s.teams),a.models&&"string"==typeof a.models&&""!==a.models.trim()&&(s.models=a.models.split(",").map(e=>e.trim()).filter(Boolean),0===s.models.length&&delete s.models),a.max_budget&&""!==a.max_budget.toString().trim()){let e=parseFloat(a.max_budget.toString());!isNaN(e)&&e>0&&(s.max_budget=e)}a.budget_duration&&""!==a.budget_duration.trim()&&(s.budget_duration=a.budget_duration.trim()),a.metadata&&"string"==typeof a.metadata&&""!==a.metadata.trim()&&(s.metadata=a.metadata.trim()),console.log("Sending user data:",s);let r=await (0,j.userCreateCall)(e,null,s);if(console.log("Full response:",r),r&&(r.key||r.user_id)){t=!0,console.log("Success case triggered");let s=r.data?.user_id||r.user_id;try{if(R?.SSO_ENABLED){let e=new URL("/ui",D).toString();I(s=>s.map((s,t)=>t===l?{...s,status:"success",key:r.key||r.user_id,invitation_link:e}:s))}else{let t=await (0,j.invitationCreateCall)(e,s),a=new URL(`/ui?invitation_id=${t.id}`,D).toString();I(e=>e.map((e,s)=>s===l?{...e,status:"success",key:r.key||r.user_id,invitation_link:a}:e))}}catch(e){console.error("Error creating invitation:",e),I(e=>e.map((e,s)=>s===l?{...e,status:"success",key:r.key||r.user_id,error:"User created but failed to generate invitation link"}:e))}}else{console.log("Error case triggered");let e=r?.error||"Failed to create user";console.log("Error message:",e),I(s=>s.map((s,t)=>t===l?{...s,status:"failed",error:e}:s))}}catch(s){console.error("Caught error:",s);let e=s?.response?.data?.error||s?.message||String(s);I(s=>s.map((s,t)=>t===l?{...s,status:"failed",error:e}:s))}}T(!1),t&&p&&p()},W=[{title:"Row",dataIndex:"rowNumber",key:"rowNumber",width:80},{title:"Email",dataIndex:"user_email",key:"user_email"},{title:"Role",dataIndex:"user_role",key:"user_role"},{title:"Teams",dataIndex:"teams",key:"teams"},{title:"Budget",dataIndex:"max_budget",key:"max_budget"},{title:"Status",key:"status",render:(e,t)=>t.isValid?t.status&&"pending"!==t.status?"success"===t.status?(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(b.CheckCircleIcon,{className:"h-5 w-5 text-green-500 mr-2"}),(0,s.jsx)("span",{className:"text-green-500",children:"Success"})]}),t.invitation_link&&(0,s.jsx)("div",{className:"mt-1",children:(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)("span",{className:"text-xs text-gray-500 truncate max-w-[150px]",children:t.invitation_link}),(0,s.jsx)(N.CopyToClipboard,{text:t.invitation_link,onCopy:()=>_.default.success("Invitation link copied!"),children:(0,s.jsx)("button",{className:"ml-1 text-blue-500 text-xs hover:text-blue-700",children:"Copy"})})]})})]}):(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(y.XCircleIcon,{className:"h-5 w-5 text-red-500 mr-2"}),(0,s.jsx)("span",{className:"text-red-500",children:"Failed"})]}),t.error&&(0,s.jsx)("span",{className:"text-sm text-red-500 ml-7",children:JSON.stringify(t.error)})]}):(0,s.jsx)("span",{className:"text-gray-500",children:"Pending"}):(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(y.XCircleIcon,{className:"h-5 w-5 text-red-500 mr-2"}),(0,s.jsx)("span",{className:"text-red-500",children:"Invalid"})]}),t.error&&(0,s.jsx)("span",{className:"text-sm text-red-500 ml-7",children:t.error})]})}];return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(l.Button,{className:"mb-0",onClick:()=>S(!0),children:"+ Bulk Invite Users"}),(0,s.jsx)(r.Modal,{title:"Bulk Invite Users",open:C,width:800,onCancel:()=>S(!1),bodyStyle:{maxHeight:"70vh",overflow:"auto"},footer:null,children:(0,s.jsx)("div",{className:"flex flex-col",children:0===k.length?(0,s.jsxs)("div",{className:"mb-6",children:[(0,s.jsxs)("div",{className:"flex items-center mb-4",children:[(0,s.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"1"}),(0,s.jsx)("h3",{className:"text-lg font-medium",children:"Download and fill the template"})]}),(0,s.jsxs)("div",{className:"ml-11 mb-6",children:[(0,s.jsx)("p",{className:"mb-4",children:"Add multiple users at once by following these steps:"}),(0,s.jsxs)("ol",{className:"list-decimal list-inside space-y-2 ml-2 mb-4",children:[(0,s.jsx)("li",{children:"Download our CSV template"}),(0,s.jsx)("li",{children:"Add your users' information to the spreadsheet"}),(0,s.jsx)("li",{children:"Save the file and upload it here"}),(0,s.jsx)("li",{children:"After creation, download the results file containing the Virtual Keys for each user"})]}),(0,s.jsxs)("div",{className:"bg-gray-50 p-4 rounded-md border border-gray-200 mb-4",children:[(0,s.jsx)("h4",{className:"font-medium mb-2",children:"Template Column Names"}),(0,s.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-red-500 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"user_email"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:"User's email address (required)"})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-red-500 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"user_role"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'User\'s role (one of: "proxy_admin", "proxy_admin_viewer", "internal_user", "internal_user_viewer")'})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"teams"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'Comma-separated team IDs (e.g., "team-1,team-2")'})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"max_budget"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'Maximum budget as a number (e.g., "100")'})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"budget_duration"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'Budget reset period (e.g., "30d", "1mo")'})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"models"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'Comma-separated allowed models (e.g., "gpt-3.5-turbo,gpt-4")'})]})]})]})]}),(0,s.jsxs)(l.Button,{onClick:()=>{let e=new Blob([v.default.unparse([["user_email","user_role","teams","max_budget","budget_duration","models"],["user@example.com","internal_user","team-id-1,team-id-2","100","30d","gpt-3.5-turbo,gpt-4"]])],{type:"text/csv"}),s=window.URL.createObjectURL(e),t=document.createElement("a");t.href=s,t.download="bulk_users_template.csv",document.body.appendChild(t),t.click(),document.body.removeChild(t),window.URL.revokeObjectURL(s)},size:"lg",className:"w-full md:w-auto",children:[(0,s.jsx)(c.DownloadOutlined,{className:"mr-2"})," Download CSV Template"]})]}),(0,s.jsxs)("div",{className:"flex items-center mb-4",children:[(0,s.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"2"}),(0,s.jsx)("h3",{className:"text-lg font-medium",children:"Upload your completed CSV"})]}),(0,s.jsxs)("div",{className:"ml-11",children:[E?(0,s.jsxs)("div",{className:`mb-4 p-4 rounded-md border ${M?"bg-red-50 border-red-200":"bg-blue-50 border-blue-200"}`,children:[(0,s.jsxs)("div",{className:"flex items-center justify-between",children:[(0,s.jsxs)("div",{className:"flex items-center",children:[M?(0,s.jsx)(g,{className:"text-red-500 text-xl mr-3"}):(0,s.jsx)(u.FileTextOutlined,{className:"text-blue-500 text-xl mr-3"}),(0,s.jsxs)("div",{children:[(0,s.jsx)(d.Typography.Text,{strong:!0,className:M?"text-red-800":"text-blue-800",children:E.name}),(0,s.jsxs)(d.Typography.Text,{className:`block text-xs ${M?"text-red-600":"text-blue-600"}`,children:[(E.size/1024).toFixed(1)," KB • ",new Date().toLocaleDateString()]})]})]}),(0,s.jsxs)(l.Button,{size:"xs",variant:"secondary",onClick:()=>{P(null),I([]),V(null),O(null),F(null)},className:"flex items-center",children:[(0,s.jsx)(x.DeleteOutlined,{className:"mr-1"})," Remove"]})]}),M?(0,s.jsxs)("div",{className:"mt-3 text-red-600 text-sm flex items-start",children:[(0,s.jsx)(m.WarningOutlined,{className:"mr-2 mt-0.5"}),(0,s.jsx)("span",{children:M})]}):!B&&(0,s.jsxs)("div",{className:"mt-3 flex items-center",children:[(0,s.jsx)("div",{className:"w-full bg-gray-200 rounded-full h-1.5",children:(0,s.jsx)("div",{className:"bg-blue-500 h-1.5 rounded-full w-full animate-pulse"})}),(0,s.jsx)("span",{className:"ml-2 text-xs text-blue-600",children:"Processing..."})]})]}):(0,s.jsx)(n.Upload,{beforeUpload:e=>((V(null),O(null),F(null),P(e),"text/csv"===e.type||e.name.endsWith(".csv"))?e.size>5242880?F(`File is too large (${(e.size/1048576).toFixed(1)} MB). Please upload a CSV file smaller than 5MB.`):v.default.parse(e,{complete:e=>{if(!e.data||0===e.data.length){O("The CSV file appears to be empty. Please upload a file with data."),I([]);return}if(1===e.data.length){O("The CSV file only contains headers but no user data. Please add user data to your CSV."),I([]);return}let s=e.data[0];if(0===s.length||1===s.length&&""===s[0]){O("The CSV file doesn't contain any column headers. Please make sure your CSV has headers."),I([]);return}let t=["user_email","user_role"].filter(e=>!s.includes(e));if(t.length>0){O(`Your CSV is missing these required columns: ${t.join(", ")}. Please add these columns to your CSV file.`),I([]);return}try{let t=e.data.slice(1).map((e,t)=>{if(0===e.length||1===e.length&&""===e[0])return null;if(e.length=parseFloat(l.max_budget.toString())&&a.push("Max budget must be greater than 0")),l.budget_duration&&!l.budget_duration.match(/^\d+[dhmwy]$|^\d+mo$/)&&a.push(`Invalid budget duration format "${l.budget_duration}". Use format like "30d", "1mo", "2w", "6h"`),l.teams&&"string"==typeof l.teams&&h&&h.length>0){let e=h.map(e=>e.team_id),s=l.teams.split(",").map(e=>e.trim()).filter(s=>!e.includes(s));s.length>0&&a.push(`Unknown team(s): ${s.join(", ")}`)}return a.length>0&&(l.isValid=!1,l.error=a.join(", ")),l}).filter(Boolean),l=t.filter(e=>e.isValid);I(t),0===t.length?O("No valid data rows found in the CSV file. Please check your file format."):0===l.length?V("No valid users found in the CSV. Please check the errors below and fix your CSV file."):l.length{V(`Failed to parse CSV file: ${e.message}`),I([])},header:!1}):(F(`Invalid file type: ${e.name}. Please upload a CSV file (.csv extension).`),_.default.fromBackend("Invalid file type. Please upload a CSV file.")),!1),accept:".csv",maxCount:1,showUploadList:!1,children:(0,s.jsxs)("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-blue-500 transition-colors cursor-pointer",children:[(0,s.jsx)(o.UploadOutlined,{className:"text-3xl text-gray-400 mb-2"}),(0,s.jsx)("p",{className:"mb-1",children:"Drag and drop your CSV file here"}),(0,s.jsx)("p",{className:"text-sm text-gray-500 mb-3",children:"or"}),(0,s.jsx)(l.Button,{size:"sm",children:"Browse files"}),(0,s.jsx)("p",{className:"text-xs text-gray-500 mt-4",children:"Only CSV files (.csv) are supported"})]})}),B&&(0,s.jsx)("div",{className:"mb-4 p-4 bg-yellow-50 border border-yellow-200 rounded-md",children:(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)(w,{className:"h-5 w-5 text-yellow-500 mr-2 mt-0.5"}),(0,s.jsxs)("div",{children:[(0,s.jsx)(d.Typography.Text,{strong:!0,className:"text-yellow-800",children:"CSV Structure Error"}),(0,s.jsx)(d.Typography.Paragraph,{className:"text-yellow-700 mt-1 mb-0",children:B}),(0,s.jsx)(d.Typography.Paragraph,{className:"text-yellow-700 mt-2 mb-0",children:"Please download our template and ensure your CSV follows the required format."})]})]})})]})]}):(0,s.jsxs)("div",{className:"mb-6",children:[(0,s.jsxs)("div",{className:"flex items-center mb-4",children:[(0,s.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"3"}),(0,s.jsx)("h3",{className:"text-lg font-medium",children:k.some(e=>"success"===e.status||"failed"===e.status)?"User Creation Results":"Review and create users"})]}),L&&(0,s.jsx)("div",{className:"ml-11 mb-4 p-4 bg-red-50 border border-red-200 rounded-md",children:(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)(m.WarningOutlined,{className:"text-red-500 mr-2 mt-1"}),(0,s.jsxs)("div",{children:[(0,s.jsx)(a.Text,{className:"text-red-600 font-medium",children:L}),k.some(e=>!e.isValid)&&(0,s.jsxs)("ul",{className:"mt-2 list-disc list-inside text-red-600 text-sm",children:[(0,s.jsx)("li",{children:"Check the table below for specific errors in each row"}),(0,s.jsx)("li",{children:"Common issues include invalid email formats, missing required fields, or incorrect role values"}),(0,s.jsx)("li",{children:"Fix these issues in your CSV file and upload again"})]})]})]})}),(0,s.jsxs)("div",{className:"ml-11",children:[(0,s.jsxs)("div",{className:"flex justify-between items-center mb-3",children:[(0,s.jsx)("div",{className:"flex items-center",children:k.some(e=>"success"===e.status||"failed"===e.status)?(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(a.Text,{className:"text-lg font-medium mr-3",children:"Creation Summary"}),(0,s.jsxs)(a.Text,{className:"text-sm bg-green-100 text-green-800 px-2 py-1 rounded mr-2",children:[k.filter(e=>"success"===e.status).length," Successful"]}),k.some(e=>"failed"===e.status)&&(0,s.jsxs)(a.Text,{className:"text-sm bg-red-100 text-red-800 px-2 py-1 rounded",children:[k.filter(e=>"failed"===e.status).length," Failed"]})]}):(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(a.Text,{className:"text-lg font-medium mr-3",children:"User Preview"}),(0,s.jsxs)(a.Text,{className:"text-sm bg-blue-100 text-blue-800 px-2 py-1 rounded",children:[k.filter(e=>e.isValid).length," of ",k.length," users valid"]})]})}),!k.some(e=>"success"===e.status||"failed"===e.status)&&(0,s.jsxs)("div",{className:"flex space-x-3",children:[(0,s.jsx)(l.Button,{onClick:()=>{I([]),V(null)},variant:"secondary",children:"Back"}),(0,s.jsx)(l.Button,{onClick:z,disabled:0===k.filter(e=>e.isValid).length||U,children:U?"Creating...":`Create ${k.filter(e=>e.isValid).length} Users`})]})]}),k.some(e=>"success"===e.status)&&(0,s.jsx)("div",{className:"mb-4 p-4 bg-blue-50 border border-blue-200 rounded-md",children:(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"mr-3 mt-1",children:(0,s.jsx)(b.CheckCircleIcon,{className:"h-5 w-5 text-blue-500"})}),(0,s.jsxs)("div",{children:[(0,s.jsx)(a.Text,{className:"font-medium text-blue-800",children:"User creation complete"}),(0,s.jsxs)(a.Text,{className:"block text-sm text-blue-700 mt-1",children:[(0,s.jsx)("span",{className:"font-medium",children:"Next step:"})," Download the credentials file containing Virtual Keys and invitation links. Users will need these Virtual Keys to make LLM requests through LiteLLM."]})]})]})}),(0,s.jsx)(i.Table,{dataSource:k,columns:W,size:"small",pagination:{pageSize:5},scroll:{y:300},rowClassName:e=>e.isValid?"":"bg-red-50"}),!k.some(e=>"success"===e.status||"failed"===e.status)&&(0,s.jsxs)("div",{className:"flex justify-end mt-4",children:[(0,s.jsx)(l.Button,{onClick:()=>{I([]),V(null)},variant:"secondary",className:"mr-3",children:"Back"}),(0,s.jsx)(l.Button,{onClick:z,disabled:0===k.filter(e=>e.isValid).length||U,children:U?"Creating...":`Create ${k.filter(e=>e.isValid).length} Users`})]}),k.some(e=>"success"===e.status||"failed"===e.status)&&(0,s.jsxs)("div",{className:"flex justify-end mt-4",children:[(0,s.jsx)(l.Button,{onClick:()=>{I([]),V(null)},variant:"secondary",className:"mr-3",children:"Start New Bulk Import"}),(0,s.jsxs)(l.Button,{onClick:()=>{let e=k.map(e=>({user_email:e.user_email,user_role:e.user_role,status:e.status,key:e.key||"",invitation_link:e.invitation_link||"",error:e.error||""})),s=new Blob([v.default.unparse(e)],{type:"text/csv"}),t=window.URL.createObjectURL(s),l=document.createElement("a");l.href=t,l.download="bulk_users_results.csv",document.body.appendChild(l),l.click(),document.body.removeChild(l),window.URL.revokeObjectURL(t)},variant:"primary",className:"flex items-center",children:[(0,s.jsx)(c.DownloadOutlined,{className:"mr-2"})," Download User Credentials"]})]})]})]})})})]})}],447082)},371455,172372,e=>{"use strict";var s=e.i(843476),t=e.i(827252),l=e.i(213205),a=e.i(912598),r=e.i(677667),i=e.i(130643),n=e.i(898667),d=e.i(994388),o=e.i(35983),c=e.i(779241),m=e.i(560445),u=e.i(464571),x=e.i(808613),h=e.i(311451),f=e.i(212931),p=e.i(199133),g=e.i(770914),j=e.i(592968),v=e.i(898586),b=e.i(271645),y=e.i(447082),w=e.i(663435),N=e.i(355619),_=e.i(727749),C=e.i(764205),S=e.i(237016),k=e.i(599724);function I({isInvitationLinkModalVisible:e,setIsInvitationLinkModalVisible:t,baseUrl:l,invitationLinkData:a,modalType:r="invitation"}){let{Title:i,Paragraph:n}=v.Typography,o=()=>{if(!l)return"";let e=new URL(l).pathname,s=e&&"/"!==e?`${e}/ui`:"ui";if(a?.has_user_setup_sso)return new URL(s,l).toString();let t=`${s}?invitation_id=${a?.id}`;return"resetPassword"===r&&(t+="&action=reset_password"),new URL(t,l).toString()};return(0,s.jsxs)(f.Modal,{title:"invitation"===r?"Invitation Link":"Reset Password Link",open:e,width:800,footer:null,onOk:()=>{t(!1)},onCancel:()=>{t(!1)},children:[(0,s.jsx)(n,{children:"invitation"===r?"Copy and send the generated link to onboard this user to the proxy.":"Copy and send the generated link to the user to reset their password."}),(0,s.jsxs)("div",{className:"flex justify-between pt-5 pb-2",children:[(0,s.jsx)(k.Text,{className:"text-base",children:"User ID"}),(0,s.jsx)(k.Text,{children:a?.user_id})]}),(0,s.jsxs)("div",{className:"flex justify-between pt-5 pb-2",children:[(0,s.jsx)(k.Text,{children:"invitation"===r?"Invitation Link":"Reset Password Link"}),(0,s.jsx)(k.Text,{children:(0,s.jsx)(k.Text,{children:o()})})]}),(0,s.jsx)("div",{className:"flex justify-end mt-5",children:(0,s.jsx)(S.CopyToClipboard,{text:o(),onCopy:()=>_.default.success("Copied!"),children:(0,s.jsx)(d.Button,{variant:"primary",children:"invitation"===r?"Copy invitation link":"Copy password reset link"})})})]})}e.s(["default",()=>I],172372);let{Option:U}=p.Select,{Text:T,Link:L,Title:V}=v.Typography;e.s(["CreateUserButton",0,({userID:e,accessToken:v,teams:S,possibleUIRoles:k,onUserCreated:U,isEmbedded:V=!1})=>{let B=(0,a.useQueryClient)(),[O,M]=(0,b.useState)(null),[F]=x.Form.useForm(),[E,P]=(0,b.useState)(!1),[R,A]=(0,b.useState)(!1),[D,$]=(0,b.useState)([]),[z,W]=(0,b.useState)(!1),[K,q]=(0,b.useState)(null),[H,G]=(0,b.useState)(null);(0,b.useEffect)(()=>{let s=async()=>{try{let s=await (0,C.modelAvailableCall)(v,e,"any"),t=[];for(let e=0;e{try{_.default.info("Making API Call"),V||P(!0),s.models&&0!==s.models.length||"proxy_admin"===s.user_role||(s.models=["no-default-models"]);let t=await (0,C.userCreateCall)(v,null,s);await B.invalidateQueries({queryKey:["userList"]}),A(!0);let l=t.data?.user_id||t.user_id;if(U&&V){U(l),F.resetFields();return}if(O?.SSO_ENABLED){let s={id:"u">typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){let s=16*Math.random()|0;return("x"==e?s:3&s|8).toString(16)}),user_id:l,is_accepted:!1,accepted_at:null,expires_at:new Date(Date.now()+6048e5),created_at:new Date,created_by:e,updated_at:new Date,updated_by:e,has_user_setup_sso:!0};q(s),W(!0)}else(0,C.invitationCreateCall)(v,l).then(e=>{e.has_user_setup_sso=!1,q(e),W(!0)});_.default.success("API user Created"),F.resetFields(),localStorage.removeItem("userData"+e)}catch(s){let e=s.response?.data?.detail||s?.message||"Error creating the user";_.default.fromBackend(e),console.error("Error creating the user:",s)}};return V?(0,s.jsxs)(x.Form,{form:F,onFinish:J,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,s.jsx)(m.Alert,{message:"Email invitations",description:(0,s.jsxs)(s.Fragment,{children:["New users receive an email invite only when an email integration (SMTP, Resend, or SendGrid) is configured."," ",(0,s.jsx)(L,{href:"https://docs.litellm.ai/docs/proxy/email",target:"_blank",children:"Learn how to set up email notifications"})]}),type:"info",showIcon:!0,className:"mb-4"}),(0,s.jsx)(x.Form.Item,{label:"User Email",name:"user_email",children:(0,s.jsx)(c.TextInput,{placeholder:""})}),(0,s.jsx)(x.Form.Item,{label:"User Role",name:"user_role",children:(0,s.jsx)(p.Select,{children:k&&Object.entries(k).map(([e,{ui_label:t,description:l}])=>(0,s.jsx)(o.SelectItem,{value:e,title:t,children:(0,s.jsxs)("div",{className:"flex",children:[t," ",(0,s.jsx)(T,{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:l})]})},e))})}),(0,s.jsx)(x.Form.Item,{label:"Team",name:"team_id",children:(0,s.jsx)(p.Select,{placeholder:"Select Team",style:{width:"100%"},children:(0,s.jsx)(w.default,{teams:S})})}),(0,s.jsx)(x.Form.Item,{label:"Metadata",name:"metadata",children:(0,s.jsx)(h.Input.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,s.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,s.jsx)(u.Button,{htmlType:"submit",children:"Create User"})})]}):(0,s.jsxs)("div",{className:"flex gap-2",children:[(0,s.jsx)(d.Button,{className:"mb-0",onClick:()=>P(!0),children:"+ Invite User"}),(0,s.jsx)(y.default,{accessToken:v,teams:S,possibleUIRoles:k}),(0,s.jsxs)(f.Modal,{title:"Invite User",open:E,width:800,footer:null,onOk:()=>{P(!1),F.resetFields()},onCancel:()=>{P(!1),A(!1),F.resetFields()},children:[(0,s.jsxs)(g.Space,{direction:"vertical",size:"middle",children:[(0,s.jsx)(T,{className:"mb-1",children:"Create a User who can own keys"}),(0,s.jsx)(m.Alert,{message:"Email invitations",description:(0,s.jsxs)(s.Fragment,{children:["New users receive an email invite only when an email integration (SMTP, Resend, or SendGrid) is configured."," ",(0,s.jsx)(L,{href:"https://docs.litellm.ai/docs/proxy/email",target:"_blank",children:"Learn how to set up email notifications"})]}),type:"info",showIcon:!0,className:"mb-4"})]}),(0,s.jsxs)(x.Form,{form:F,onFinish:J,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,s.jsx)(x.Form.Item,{label:"User Email",name:"user_email",children:(0,s.jsx)(h.Input,{})}),(0,s.jsx)(x.Form.Item,{label:(0,s.jsxs)("span",{children:["Global Proxy Role"," ",(0,s.jsx)(j.Tooltip,{title:"This role is independent of any team/org specific roles. Configure Team / Organization Admins in the Settings",children:(0,s.jsx)(t.InfoCircleOutlined,{})})]}),name:"user_role",children:(0,s.jsx)(p.Select,{children:k&&Object.entries(k).map(([e,{ui_label:t,description:l}])=>(0,s.jsxs)(o.SelectItem,{value:e,title:t,children:[(0,s.jsx)(T,{children:t}),(0,s.jsxs)(T,{type:"secondary",children:[" - ",l]})]},e))})}),(0,s.jsx)(x.Form.Item,{label:"Team",className:"gap-2",name:"team_id",help:"If selected, user will be added as a 'user' role to the team.",children:(0,s.jsx)(w.default,{teams:S})}),(0,s.jsx)(x.Form.Item,{label:"Metadata",name:"metadata",children:(0,s.jsx)(h.Input.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,s.jsxs)(r.Accordion,{children:[(0,s.jsx)(n.AccordionHeader,{children:(0,s.jsx)(T,{strong:!0,children:"Personal Key Creation"})}),(0,s.jsx)(i.AccordionBody,{children:(0,s.jsx)(x.Form.Item,{className:"gap-2",label:(0,s.jsxs)("span",{children:["Models"," ",(0,s.jsx)(j.Tooltip,{title:"Models user has access to, outside of team scope.",children:(0,s.jsx)(t.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"models",help:"Models user has access to, outside of team scope.",children:(0,s.jsxs)(p.Select,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[(0,s.jsx)(p.Select.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),(0,s.jsx)(p.Select.Option,{value:"no-default-models",children:"No Default Models"},"no-default-models"),D.map(e=>(0,s.jsx)(p.Select.Option,{value:e,children:(0,N.getModelDisplayName)(e)},e))]})})})]}),(0,s.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,s.jsx)(u.Button,{type:"primary",icon:(0,s.jsx)(l.UserAddOutlined,{}),htmlType:"submit",children:"Invite User"})})]})]}),R&&(0,s.jsx)(I,{isInvitationLinkModalVisible:z,setIsInvitationLinkModalVisible:W,baseUrl:H||"",invitationLinkData:K})]})}],371455)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/1b424ce64213980f.js b/litellm/proxy/_experimental/out/_next/static/chunks/1b424ce64213980f.js new file mode 100644 index 00000000000..5ea6f73f346 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/1b424ce64213980f.js @@ -0,0 +1 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,510674,e=>{"use strict";var t=e.i(266027),s=e.i(243652),a=e.i(764205),l=e.i(708347),r=e.i(135214);let i=(0,s.createQueryKeys)("projects"),n=async e=>{let t=(0,a.getProxyBaseUrl)(),s=`${t}/project/list`,l=await fetch(s,{method:"GET",headers:{[(0,a.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!l.ok){let e=await l.json(),t=(0,a.deriveErrorMessage)(e);throw(0,a.handleError)(t),Error(t)}return l.json()};e.s(["projectKeys",0,i,"useProjects",0,()=>{let{accessToken:e,userRole:s}=(0,r.default)();return(0,t.useQuery)({queryKey:i.list({}),queryFn:async()=>n(e),enabled:!!e&&l.all_admin_roles.includes(s||"")})}])},557662,e=>{"use strict";let t="../ui/assets/logos/",s=[{id:"arize",displayName:"Arize",logo:`${t}arize.png`,supports_key_team_logging:!0,dynamic_params:{arize_api_key:"password",arize_space_id:"password"},description:"Arize Logging Integration"},{id:"braintrust",displayName:"Braintrust",logo:`${t}braintrust.png`,supports_key_team_logging:!1,dynamic_params:{braintrust_api_key:"password",braintrust_project_name:"text"},description:"Braintrust Logging Integration"},{id:"custom_callback_api",displayName:"Custom Callback API",logo:`${t}custom.svg`,supports_key_team_logging:!0,dynamic_params:{custom_callback_api_url:"text",custom_callback_api_headers:"text"},description:"Custom Callback API Logging Integration"},{id:"datadog",displayName:"Datadog",logo:`${t}datadog.png`,supports_key_team_logging:!1,dynamic_params:{dd_api_key:"password",dd_site:"text"},description:"Datadog Logging Integration"},{id:"lago",displayName:"Lago",logo:`${t}lago.svg`,supports_key_team_logging:!1,dynamic_params:{lago_api_url:"text",lago_api_key:"password"},description:"Lago Billing Logging Integration"},{id:"langfuse",displayName:"Langfuse",logo:`${t}langfuse.png`,supports_key_team_logging:!0,dynamic_params:{langfuse_public_key:"text",langfuse_secret_key:"password",langfuse_host:"text"},description:"Langfuse v2 Logging Integration"},{id:"langfuse_otel",displayName:"Langfuse OTEL",logo:`${t}langfuse.png`,supports_key_team_logging:!0,dynamic_params:{langfuse_public_key:"text",langfuse_secret_key:"password",langfuse_host:"text"},description:"Langfuse v3 OTEL Logging Integration"},{id:"langsmith",displayName:"LangSmith",logo:`${t}langsmith.png`,supports_key_team_logging:!0,dynamic_params:{langsmith_api_key:"password",langsmith_project:"text",langsmith_base_url:"text",langsmith_sampling_rate:"number"},description:"Langsmith Logging Integration"},{id:"openmeter",displayName:"OpenMeter",logo:`${t}openmeter.png`,supports_key_team_logging:!1,dynamic_params:{openmeter_api_key:"password",openmeter_base_url:"text"},description:"OpenMeter Logging Integration"},{id:"otel",displayName:"Open Telemetry",logo:`${t}otel.png`,supports_key_team_logging:!1,dynamic_params:{otel_endpoint:"text",otel_headers:"text"},description:"OpenTelemetry Logging Integration"},{id:"s3",displayName:"S3",logo:`${t}aws.svg`,supports_key_team_logging:!1,dynamic_params:{s3_bucket_name:"text",aws_access_key_id:"password",aws_secret_access_key:"password",aws_region:"text"},description:"S3 Bucket (AWS) Logging Integration"},{id:"SQS",displayName:"SQS",logo:`${t}aws.svg`,supports_key_team_logging:!1,dynamic_params:{sqs_queue_url:"text",aws_access_key_id:"password",aws_secret_access_key:"password",aws_region:"text"},description:"SQS Queue (AWS) Logging Integration"}],a=s.reduce((e,t)=>(e[t.displayName]=t,e),{}),l=s.reduce((e,t)=>(e[t.displayName]=t.id,e),{}),r=s.reduce((e,t)=>(e[t.id]=t.displayName,e),{});e.s(["callbackInfo",0,a,"callback_map",0,l,"mapDisplayToInternalNames",0,e=>e.map(e=>l[e]||e),"mapInternalToDisplayNames",0,e=>e.map(e=>r[e]||e),"reverse_callback_map",0,r])},810757,477386,e=>{"use strict";var t=e.i(271645);let s=t.forwardRef(function(e,s){return t.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:s},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}))});e.s(["CogIcon",0,s],810757);let a=t.forwardRef(function(e,s){return t.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:s},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"}))});e.s(["BanIcon",0,a],477386)},207082,e=>{"use strict";var t=e.i(619273),s=e.i(266027),a=e.i(243652),l=e.i(764205),r=e.i(135214);let i=(0,a.createQueryKeys)("keys"),n=async(e,t,s,a={})=>{try{let r=(0,l.getProxyBaseUrl)(),i=new URLSearchParams(Object.entries({team_id:a.teamID,project_id:a.projectID,organization_id:a.organizationID,key_alias:a.selectedKeyAlias,key_hash:a.keyHash,user_id:a.userID,page:t,size:s,sort_by:a.sortBy,sort_order:a.sortOrder,expand:a.expand,status:a.status,return_full_object:"true",include_team_keys:"true",include_created_by_keys:"true"}).filter(([,e])=>null!=e).map(([e,t])=>[e,String(t)])),n=`${r?`${r}/key/list`:"/key/list"}?${i}`,o=await fetch(n,{method:"GET",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!o.ok){let e=await o.json(),t=(0,l.deriveErrorMessage)(e);throw(0,l.handleError)(t),Error(t)}let c=await o.json();return console.log("/key/list API Response:",c),c}catch(e){throw console.error("Failed to list keys:",e),e}},o=(0,a.createQueryKeys)("deletedKeys");e.s(["keyKeys",0,i,"useDeletedKeys",0,(e,a,l={})=>{let{accessToken:i}=(0,r.default)();return(0,s.useQuery)({queryKey:o.list({page:e,limit:a,...l}),queryFn:async()=>await n(i,e,a,{...l,status:"deleted"}),enabled:!!i,staleTime:3e4,placeholderData:t.keepPreviousData})},"useKeys",0,(e,a,l={})=>{let{accessToken:o}=(0,r.default)();return(0,s.useQuery)({queryKey:i.list({page:e,limit:a,...l}),queryFn:async()=>await n(o,e,a,l),enabled:!!o,staleTime:3e4,placeholderData:t.keepPreviousData})}])},552130,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(199133),l=e.i(764205);e.s(["default",0,({onChange:e,value:r,className:i,accessToken:n,placeholder:o="Select agents",disabled:c=!1})=>{let[d,u]=(0,s.useState)([]),[m,p]=(0,s.useState)([]),[g,h]=(0,s.useState)(!1);(0,s.useEffect)(()=>{(async()=>{if(n){h(!0);try{let e=await (0,l.getAgentsList)(n),t=e?.agents||[];u(t);let s=new Set;t.forEach(e=>{let t=e.agent_access_groups;t&&Array.isArray(t)&&t.forEach(e=>s.add(e))}),p(Array.from(s))}catch(e){console.error("Error fetching agents:",e)}finally{h(!1)}}})()},[n]);let x=[...m.map(e=>({label:e,value:`group:${e}`,isAccessGroup:!0,searchText:`${e} Access Group`})),...d.map(e=>({label:`${e.agent_name||e.agent_id}`,value:e.agent_id,isAccessGroup:!1,searchText:`${e.agent_name||e.agent_id} ${e.agent_id} Agent`}))],y=[...r?.agents||[],...(r?.accessGroups||[]).map(e=>`group:${e}`)];return(0,t.jsx)("div",{children:(0,t.jsx)(a.Select,{mode:"multiple",placeholder:o,onChange:t=>{e({agents:t.filter(e=>!e.startsWith("group:")),accessGroups:t.filter(e=>e.startsWith("group:")).map(e=>e.replace("group:",""))})},value:y,loading:g,className:i,allowClear:!0,showSearch:!0,style:{width:"100%"},disabled:c,filterOption:(e,t)=>(x.find(e=>e.value===t?.value)?.searchText||"").toLowerCase().includes(e.toLowerCase()),children:x.map(e=>(0,t.jsx)(a.Select.Option,{value:e.value,label:e.label,children:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[(0,t.jsx)("span",{style:{display:"inline-block",width:8,height:8,borderRadius:"50%",background:e.isAccessGroup?"#52c41a":"#722ed1",flexShrink:0}}),(0,t.jsx)("span",{style:{flex:1},children:e.label}),(0,t.jsx)("span",{style:{color:e.isAccessGroup?"#52c41a":"#722ed1",fontSize:"12px",fontWeight:500,opacity:.8},children:e.isAccessGroup?"Access Group":"Agent"})]})},e.value))})})}])},9314,263147,e=>{"use strict";var t=e.i(843476),s=e.i(199133),a=e.i(981339),l=e.i(645526),r=e.i(599724),i=e.i(266027),n=e.i(243652),o=e.i(764205),c=e.i(708347),d=e.i(135214);let u=(0,n.createQueryKeys)("accessGroups"),m=async e=>{let t=(0,o.getProxyBaseUrl)(),s=`${t}/v1/access_group`,a=await fetch(s,{method:"GET",headers:{[(0,o.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!a.ok){let e=await a.json(),t=(0,o.deriveErrorMessage)(e);throw(0,o.handleError)(t),Error(t)}return a.json()},p=()=>{let{accessToken:e,userRole:t}=(0,d.default)();return(0,i.useQuery)({queryKey:u.list({}),queryFn:async()=>m(e),enabled:!!e&&c.all_admin_roles.includes(t||"")})};e.s(["accessGroupKeys",0,u,"useAccessGroups",0,p],263147),e.s(["default",0,({value:e,onChange:i,placeholder:n="Select access groups",disabled:o=!1,style:c,className:d,showLabel:u=!1,labelText:m="Access Group",allowClear:g=!0})=>{let{data:h,isLoading:x,isError:y}=p();if(x)return(0,t.jsxs)("div",{children:[u&&(0,t.jsxs)(r.Text,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,t.jsx)(l.TeamOutlined,{className:"mr-2"})," ",m]}),(0,t.jsx)(a.Skeleton.Input,{active:!0,block:!0,style:{height:32,...c}})]});let f=(h??[]).map(e=>({label:(0,t.jsxs)("span",{children:[(0,t.jsx)("span",{className:"font-medium",children:e.access_group_name})," ",(0,t.jsxs)("span",{className:"text-gray-400 text-xs",children:["(",e.access_group_id,")"]})]}),value:e.access_group_id,selectedLabel:e.access_group_name,searchText:`${e.access_group_name} ${e.access_group_id}`}));return(0,t.jsxs)("div",{children:[u&&(0,t.jsxs)(r.Text,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,t.jsx)(l.TeamOutlined,{className:"mr-2"})," ",m]}),(0,t.jsx)(s.Select,{mode:"multiple",value:e,placeholder:n,onChange:i,disabled:o,allowClear:g,showSearch:!0,style:{width:"100%",...c},className:`rounded-md ${d??""}`,notFoundContent:y?(0,t.jsx)("span",{className:"text-red-500",children:"Failed to load access groups"}):"No access groups found",filterOption:(e,t)=>(f.find(e=>e.value===t?.value)?.searchText??"").toLowerCase().includes(e.toLowerCase()),optionLabelProp:"selectedLabel",options:f.map(e=>({label:e.label,value:e.value,selectedLabel:e.selectedLabel}))})]})}],9314)},392110,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(199133),l=e.i(592968),r=e.i(312361),i=e.i(790848),n=e.i(536916),o=e.i(827252),c=e.i(779241);let{Option:d}=a.Select;e.s(["default",0,({form:e,autoRotationEnabled:u,onAutoRotationChange:m,rotationInterval:p,onRotationIntervalChange:g,isCreateMode:h=!1,neverExpire:x=!1,onNeverExpireChange:y})=>{let f=p&&!["7d","30d","90d","180d","365d"].includes(p),[_,j]=(0,s.useState)(f),[b,v]=(0,s.useState)(f?p:""),[w,N]=(0,s.useState)(e?.getFieldValue?.("duration")||"");return(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Key Expiry Settings"}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,t.jsx)("span",{children:"Expire Key"}),(0,t.jsx)(l.Tooltip,{title:"Set when this key should expire. Format: 30s (seconds), 30m (minutes), 30h (hours), 30d (days). Leave empty to keep the current expiry unchanged.",children:(0,t.jsx)(o.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})}),!h&&y&&(0,t.jsx)(n.Checkbox,{checked:x,onChange:t=>{let s=t.target.checked;y(s),s&&(N(""),e&&"function"==typeof e.setFieldValue?e.setFieldValue("duration",""):e&&"function"==typeof e.setFieldsValue&&e.setFieldsValue({duration:""}))},className:"ml-2 text-sm font-normal text-gray-600",children:"Never Expire"})]}),(0,t.jsx)(c.TextInput,{name:"duration",placeholder:h?"e.g., 30d or leave empty to never expire":"e.g., 30d",className:"w-full",value:w,onValueChange:t=>{N(t),e&&"function"==typeof e.setFieldValue?e.setFieldValue("duration",t):e&&"function"==typeof e.setFieldsValue&&e.setFieldsValue({duration:t})},disabled:!h&&x})]})]}),(0,t.jsx)(r.Divider,{}),(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Auto-Rotation Settings"}),(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,t.jsx)("span",{children:"Enable Auto-Rotation"}),(0,t.jsx)(l.Tooltip,{title:"Key will automatically regenerate at the specified interval for enhanced security.",children:(0,t.jsx)(o.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})})]}),(0,t.jsx)(i.Switch,{checked:u,onChange:m,size:"default",className:u?"":"bg-gray-400"})]}),u&&(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,t.jsx)("span",{children:"Rotation Interval"}),(0,t.jsx)(l.Tooltip,{title:"How often the key should be automatically rotated. Choose the interval that best fits your security requirements.",children:(0,t.jsx)(o.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)(a.Select,{value:_?"custom":p,onChange:e=>{"custom"===e?j(!0):(j(!1),v(""),g(e))},className:"w-full",placeholder:"Select interval",children:[(0,t.jsx)(d,{value:"7d",children:"7 days"}),(0,t.jsx)(d,{value:"30d",children:"30 days"}),(0,t.jsx)(d,{value:"90d",children:"90 days"}),(0,t.jsx)(d,{value:"180d",children:"180 days"}),(0,t.jsx)(d,{value:"365d",children:"365 days"}),(0,t.jsx)(d,{value:"custom",children:"Custom interval"})]}),_&&(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(c.TextInput,{value:b,onChange:e=>{let t=e.target.value;v(t),g(t)},placeholder:"e.g., 1s, 5m, 2h, 14d"}),(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"Supported formats: seconds (s), minutes (m), hours (h), days (d)"})]})]})]})]}),u&&(0,t.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."})]})]})}])},844565,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(199133),l=e.i(764205);e.s(["default",0,({onChange:e,value:r,className:i,accessToken:n,placeholder:o="Select pass through routes",disabled:c=!1,teamId:d})=>{let[u,m]=(0,s.useState)([]),[p,g]=(0,s.useState)(!1);return(0,s.useEffect)(()=>{(async()=>{if(n){g(!0);try{let e=await (0,l.getPassThroughEndpointsCall)(n,d);if(e.endpoints){let t=e.endpoints.flatMap(e=>{let t=e.path,s=e.methods;return s&&s.length>0?s.map(e=>({label:`${e} ${t}`,value:t})):[{label:t,value:t}]});m(t)}}catch(e){console.error("Error fetching pass through routes:",e)}finally{g(!1)}}})()},[n,d]),(0,t.jsx)(a.Select,{mode:"tags",placeholder:o,onChange:e,value:r,loading:p,className:i,allowClear:!0,options:u,optionFilterProp:"label",showSearch:!0,style:{width:"100%"},disabled:c})}])},939510,e=>{"use strict";var t=e.i(843476),s=e.i(808613),a=e.i(199133),l=e.i(592968),r=e.i(827252);let{Option:i}=a.Select;e.s(["default",0,({type:e,name:n,showDetailedDescriptions:o=!0,className:c="",initialValue:d=null,form:u,onChange:m})=>{let p=e.toUpperCase(),g=e.toLowerCase(),h=`Select 'guaranteed_throughput' to prevent overallocating ${p} limit when the key belongs to a Team with specific ${p} limits.`;return(0,t.jsx)(s.Form.Item,{label:(0,t.jsxs)("span",{children:[p," Rate Limit Type"," ",(0,t.jsx)(l.Tooltip,{title:h,children:(0,t.jsx)(r.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:n,initialValue:d,className:c,children:(0,t.jsx)(a.Select,{defaultValue:o?"default":void 0,placeholder:"Select rate limit type",style:{width:"100%"},optionLabelProp:o?"label":void 0,onChange:e=>{u&&u.setFieldValue(n,e),m&&m(e)},children:o?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(i,{value:"best_effort_throughput",label:"Default",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Default"}),(0,t.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["Best effort throughput - no error if we're overallocating ",g," (Team/Key Limits checked at runtime)."]})]})}),(0,t.jsx)(i,{value:"guaranteed_throughput",label:"Guaranteed throughput",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Guaranteed throughput"}),(0,t.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["Guaranteed throughput - raise an error if we're overallocating ",g," (also checks model-specific limits)"]})]})}),(0,t.jsx)(i,{value:"dynamic",label:"Dynamic",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Dynamic"}),(0,t.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["If the key has a set ",p," (e.g. 2 ",p,") and there are no 429 errors, it can dynamically exceed the limit when the model being called is not erroring."]})]})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(i,{value:"best_effort_throughput",children:"Best effort throughput"}),(0,t.jsx)(i,{value:"guaranteed_throughput",children:"Guaranteed throughput"}),(0,t.jsx)(i,{value:"dynamic",children:"Dynamic"})]})})})}])},75921,e=>{"use strict";var t=e.i(843476),s=e.i(266027),a=e.i(243652),l=e.i(764205),r=e.i(135214);let i=(0,a.createQueryKeys)("mcpAccessGroups");var n=e.i(500727),o=e.i(199133);e.s(["default",0,({onChange:e,value:a,className:c,accessToken:d,placeholder:u="Select MCP servers",disabled:m=!1,teamId:p})=>{let{data:g=[],isLoading:h}=(0,n.useMCPServers)(p),{data:x=[],isLoading:y}=(()=>{let{accessToken:e}=(0,r.default)();return(0,s.useQuery)({queryKey:i.list({}),queryFn:async()=>await (0,l.fetchMCPAccessGroups)(e),enabled:!!e})})(),f=[...x.map(e=>({label:e,value:e,isAccessGroup:!0,searchText:`${e} Access Group`})),...g.map(e=>({label:`${e.server_name||e.server_id} (${e.server_id})`,value:e.server_id,isAccessGroup:!1,searchText:`${e.server_name||e.server_id} ${e.server_id} MCP Server`}))],_=[...a?.servers||[],...a?.accessGroups||[]];return(0,t.jsx)("div",{children:(0,t.jsx)(o.Select,{mode:"multiple",placeholder:u,onChange:t=>{e({servers:t.filter(e=>!x.includes(e)),accessGroups:t.filter(e=>x.includes(e))})},value:_,loading:h||y,className:c,allowClear:!0,showSearch:!0,style:{width:"100%"},disabled:m,filterOption:(e,t)=>(f.find(e=>e.value===t?.value)?.searchText||"").toLowerCase().includes(e.toLowerCase()),children:f.map(e=>(0,t.jsx)(o.Select.Option,{value:e.value,label:e.label,children:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[(0,t.jsx)("span",{style:{display:"inline-block",width:8,height:8,borderRadius:"50%",background:e.isAccessGroup?"#52c41a":"#1890ff",flexShrink:0}}),(0,t.jsx)("span",{style:{flex:1},children:e.label}),(0,t.jsx)("span",{style:{color:e.isAccessGroup?"#52c41a":"#1890ff",fontSize:"12px",fontWeight:500,opacity:.8},children:e.isAccessGroup?"Access Group":"MCP Server"})]})},e.value))})})}],75921)},390605,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(764205),l=e.i(599724),r=e.i(482725),i=e.i(91739),n=e.i(500727),o=e.i(531516),c=e.i(696609);e.s(["default",0,({accessToken:e,selectedServers:d,toolPermissions:u,onChange:m,disabled:p=!1})=>{let{data:g=[]}=(0,n.useMCPServers)(),[h,x]=(0,s.useState)({}),[y,f]=(0,s.useState)({}),[_,j]=(0,s.useState)({}),[b,v]=(0,s.useState)({}),w=(0,s.useRef)(u);(0,s.useEffect)(()=>{w.current=u},[u]);let N=(0,s.useMemo)(()=>0===d.length?[]:g.filter(e=>d.includes(e.server_id)),[g,d]),k=async(e,t)=>{f(t=>({...t,[e]:!0})),j(t=>({...t,[e]:""}));try{let s=await (0,a.listMCPTools)(t,e);if(s.error)j(t=>({...t,[e]:s.message||"Failed to fetch tools"})),x(t=>({...t,[e]:[]}));else{let t=s.tools||[];x(s=>({...s,[e]:t}));let a=w.current;if(!a[e]&&t.length>0){let s=t.filter(e=>"delete"!==(0,c.classifyToolOp)(e.name,e.description||"")).map(e=>e.name);m({...a,[e]:s})}}}catch(t){console.error(`Error fetching tools for server ${e}:`,t),j(t=>({...t,[e]:"Failed to fetch tools"})),x(t=>({...t,[e]:[]}))}finally{f(t=>({...t,[e]:!1}))}};(0,s.useEffect)(()=>{N.forEach(t=>{h[t.server_id]||y[t.server_id]||k(t.server_id,e)})},[N,e]);let S=(e,t)=>{m({...u,[e]:t})};return 0===d.length?null:(0,t.jsx)("div",{className:"space-y-4",children:N.map(e=>{let s=e.server_name||e.alias||e.server_id,a=h[e.server_id]||[],n=u[e.server_id]||[],c=y[e.server_id],d=_[e.server_id],g=b[e.server_id]??"crud";return(0,t.jsxs)("div",{className:"border rounded-lg bg-gray-50",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between p-4 border-b bg-white rounded-t-lg",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(l.Text,{className:"font-semibold text-gray-900",children:s}),e.description&&(0,t.jsx)(l.Text,{className:"text-sm text-gray-500",children:e.description})]}),(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[!p&&a.length>0&&(0,t.jsx)(i.Radio.Group,{value:g,onChange:t=>v(s=>({...s,[e.server_id]:t.target.value})),size:"small",optionType:"button",buttonStyle:"solid",options:[{label:"Risk Groups",value:"crud"},{label:"Flat List",value:"flat"}]}),!p&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("button",{type:"button",className:"text-sm text-blue-600 hover:text-blue-700 font-medium",onClick:()=>{var t;let s;return s=h[t=e.server_id]||[],void m({...u,[t]:s.map(e=>e.name)})},disabled:c,children:"Select All"}),(0,t.jsx)("button",{type:"button",className:"text-sm text-blue-600 hover:text-blue-700 font-medium",onClick:()=>{var t;return t=e.server_id,void m({...u,[t]:[]})},disabled:c,children:"Deselect All"})]})]})]}),(0,t.jsxs)("div",{className:"p-4",children:[c&&(0,t.jsxs)("div",{className:"flex items-center justify-center py-8",children:[(0,t.jsx)(r.Spin,{size:"large"}),(0,t.jsx)(l.Text,{className:"ml-3 text-gray-500",children:"Loading tools..."})]}),d&&!c&&(0,t.jsxs)("div",{className:"p-4 bg-red-50 border border-red-200 rounded-lg text-center",children:[(0,t.jsx)(l.Text,{className:"text-red-600 font-medium",children:"Unable to load tools"}),(0,t.jsx)(l.Text,{className:"text-sm text-red-500 mt-1",children:d})]}),!c&&!d&&a.length>0&&"crud"===g&&(0,t.jsx)(o.default,{tools:a,value:u[e.server_id]?n:void 0,onChange:t=>S(e.server_id,t),readOnly:p}),!c&&!d&&a.length>0&&"flat"===g&&(0,t.jsx)("div",{className:"space-y-2",children:a.map(s=>{let a=n.includes(s.name);return(0,t.jsxs)("div",{className:"flex items-start gap-2",children:[(0,t.jsx)("input",{type:"checkbox",checked:a,onChange:()=>{if(p)return;let t=a?n.filter(e=>e!==s.name):[...n,s.name];S(e.server_id,t)},disabled:p,className:"mt-0.5"}),(0,t.jsx)("div",{className:"flex-1 min-w-0",children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(l.Text,{className:"font-medium text-gray-900",children:s.name}),(0,t.jsxs)(l.Text,{className:"text-sm text-gray-500",children:["- ",s.description||"No description"]})]})})]},s.name)})}),!c&&!d&&0===a.length&&(0,t.jsx)("div",{className:"text-center py-6",children:(0,t.jsx)(l.Text,{className:"text-gray-500",children:"No tools available"})})]})]},e.server_id)})})}])},533882,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(250980),l=e.i(797672),r=e.i(68155),i=e.i(304967),n=e.i(629569),o=e.i(599724),c=e.i(269200),d=e.i(427612),u=e.i(64848),m=e.i(942232),p=e.i(496020),g=e.i(977572),h=e.i(992619),x=e.i(727749);e.s(["default",0,({accessToken:e,initialModelAliases:y={},onAliasUpdate:f,showExampleConfig:_=!0})=>{let[j,b]=(0,s.useState)([]),[v,w]=(0,s.useState)({aliasName:"",targetModel:""}),[N,k]=(0,s.useState)(null);(0,s.useEffect)(()=>{b(Object.entries(y).map(([e,t],s)=>({id:`${s}-${e}`,aliasName:e,targetModel:t})))},[y]);let S=()=>{if(!N)return;if(!N.aliasName||!N.targetModel)return void x.default.fromBackend("Please provide both alias name and target model");if(j.some(e=>e.id!==N.id&&e.aliasName===N.aliasName))return void x.default.fromBackend("An alias with this name already exists");let e=j.map(e=>e.id===N.id?N:e);b(e),k(null);let t={};e.forEach(e=>{t[e.aliasName]=e.targetModel}),f&&f(t),x.default.success("Alias updated successfully")},C=()=>{k(null)},T=j.reduce((e,t)=>(e[t.aliasName]=t.targetModel,e),{});return(0,t.jsxs)("div",{className:"mt-4",children:[(0,t.jsxs)("div",{className:"mb-6",children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium text-gray-700 mb-2",children:"Add New Alias"}),(0,t.jsxs)("div",{className:"grid grid-cols-3 gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-xs text-gray-500 mb-1",children:"Alias Name"}),(0,t.jsx)("input",{type:"text",value:v.aliasName,onChange:e=>w({...v,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,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-xs text-gray-500 mb-1",children:"Target Model"}),(0,t.jsx)(h.default,{accessToken:e,value:v.targetModel,placeholder:"Select target model",onChange:e=>w({...v,targetModel:e}),showLabel:!1})]}),(0,t.jsx)("div",{className:"flex items-end",children:(0,t.jsxs)("button",{onClick:()=>{if(!v.aliasName||!v.targetModel)return void x.default.fromBackend("Please provide both alias name and target model");if(j.some(e=>e.aliasName===v.aliasName))return void x.default.fromBackend("An alias with this name already exists");let e=[...j,{id:`${Date.now()}-${v.aliasName}`,aliasName:v.aliasName,targetModel:v.targetModel}];b(e),w({aliasName:"",targetModel:""});let t={};e.forEach(e=>{t[e.aliasName]=e.targetModel}),f&&f(t),x.default.success("Alias added successfully")},disabled:!v.aliasName||!v.targetModel,className:`flex items-center px-4 py-2 rounded-md text-sm ${!v.aliasName||!v.targetModel?"bg-gray-300 text-gray-500 cursor-not-allowed":"bg-green-600 text-white hover:bg-green-700"}`,children:[(0,t.jsx)(a.PlusCircleIcon,{className:"w-4 h-4 mr-1"}),"Add Alias"]})})]})]}),(0,t.jsx)(o.Text,{className:"text-sm font-medium text-gray-700 mb-2",children:"Manage Existing Aliases"}),(0,t.jsx)("div",{className:"rounded-lg custom-border relative mb-6",children:(0,t.jsx)("div",{className:"overflow-x-auto",children:(0,t.jsxs)(c.Table,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,t.jsx)(d.TableHead,{children:(0,t.jsxs)(p.TableRow,{children:[(0,t.jsx)(u.TableHeaderCell,{className:"py-1 h-8",children:"Alias Name"}),(0,t.jsx)(u.TableHeaderCell,{className:"py-1 h-8",children:"Target Model"}),(0,t.jsx)(u.TableHeaderCell,{className:"py-1 h-8",children:"Actions"})]})}),(0,t.jsxs)(m.TableBody,{children:[j.map(s=>(0,t.jsx)(p.TableRow,{className:"h-8",children:N&&N.id===s.id?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(g.TableCell,{className:"py-0.5",children:(0,t.jsx)("input",{type:"text",value:N.aliasName,onChange:e=>k({...N,aliasName:e.target.value}),className:"w-full px-2 py-1 border border-gray-300 rounded-md text-sm"})}),(0,t.jsx)(g.TableCell,{className:"py-0.5",children:(0,t.jsx)(h.default,{accessToken:e,value:N.targetModel,onChange:e=>k({...N,targetModel:e}),showLabel:!1,style:{height:"32px"}})}),(0,t.jsx)(g.TableCell,{className:"py-0.5 whitespace-nowrap",children:(0,t.jsxs)("div",{className:"flex space-x-2",children:[(0,t.jsx)("button",{onClick:S,className:"text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded hover:bg-blue-100",children:"Save"}),(0,t.jsx)("button",{onClick:C,className:"text-xs bg-gray-50 text-gray-600 px-2 py-1 rounded hover:bg-gray-100",children:"Cancel"})]})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(g.TableCell,{className:"py-0.5 text-sm text-gray-900",children:s.aliasName}),(0,t.jsx)(g.TableCell,{className:"py-0.5 text-sm text-gray-500",children:s.targetModel}),(0,t.jsx)(g.TableCell,{className:"py-0.5 whitespace-nowrap",children:(0,t.jsxs)("div",{className:"flex space-x-2",children:[(0,t.jsx)("button",{onClick:()=>{k({...s})},className:"text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded hover:bg-blue-100",children:(0,t.jsx)(l.PencilIcon,{className:"w-3 h-3"})}),(0,t.jsx)("button",{onClick:()=>{var e;let t,a;return e=s.id,b(t=j.filter(t=>t.id!==e)),a={},void(t.forEach(e=>{a[e.aliasName]=e.targetModel}),f&&f(a),x.default.success("Alias deleted successfully"))},className:"text-xs bg-red-50 text-red-600 px-2 py-1 rounded hover:bg-red-100",children:(0,t.jsx)(r.TrashIcon,{className:"w-3 h-3"})})]})})]})},s.id)),0===j.length&&(0,t.jsx)(p.TableRow,{children:(0,t.jsx)(g.TableCell,{colSpan:3,className:"py-0.5 text-sm text-gray-500 text-center",children:"No aliases added yet. Add a new alias above."})})]})]})})}),_&&(0,t.jsxs)(i.Card,{children:[(0,t.jsx)(n.Title,{className:"mb-4",children:"Configuration Example"}),(0,t.jsx)(o.Text,{className:"text-gray-600 mb-4",children:"Here's how your current aliases would look in the config:"}),(0,t.jsx)("div",{className:"bg-gray-100 rounded-lg p-4 font-mono text-sm",children:(0,t.jsxs)("div",{className:"text-gray-700",children:["model_aliases:",0===Object.keys(T).length?(0,t.jsxs)("span",{className:"text-gray-500",children:[(0,t.jsx)("br",{}),"  # No aliases configured yet"]}):Object.entries(T).map(([e,s])=>(0,t.jsxs)("span",{children:[(0,t.jsx)("br",{}),'  "',e,'": "',s,'"']},e))]})})]})]})}])},266484,e=>{"use strict";var t=e.i(843476),s=e.i(199133),a=e.i(592968),l=e.i(312361),r=e.i(827252),i=e.i(994388),n=e.i(304967),o=e.i(779241),c=e.i(988297),d=e.i(68155),u=e.i(810757),m=e.i(477386),p=e.i(557662),g=e.i(435451);let{Option:h}=s.Select;e.s(["default",0,({value:e=[],onChange:x,disabledCallbacks:y=[],onDisabledCallbacksChange:f})=>{let _=Object.entries(p.callbackInfo).filter(([e,t])=>t.supports_key_team_logging).map(([e,t])=>e),j=Object.keys(p.callbackInfo),b=e=>{x?.(e)},v=(t,s,a)=>{let l=[...e];if("callback_name"===s){let e=p.callback_map[a]||a;l[t]={...l[t],[s]:e,callback_vars:{}}}else l[t]={...l[t],[s]:a};b(l)},w=(t,s,a)=>{let l=[...e];l[t]={...l[t],callback_vars:{...l[t].callback_vars,[s]:a}},b(l)};return(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)(m.BanIcon,{className:"w-5 h-5 text-red-500"}),(0,t.jsx)("span",{className:"text-base font-semibold text-gray-800",children:"Disabled Callbacks"}),(0,t.jsx)(a.Tooltip,{title:"Select callbacks to disable for this key. Disabled callbacks will not receive any logging data.",children:(0,t.jsx)(r.InfoCircleOutlined,{className:"text-gray-400 cursor-help"})})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{className:"text-sm font-medium text-gray-700",children:"Disabled Callbacks"}),(0,t.jsx)(s.Select,{mode:"multiple",placeholder:"Select callbacks to disable",value:y,onChange:e=>{let t=(0,p.mapDisplayToInternalNames)(e);f?.(t)},style:{width:"100%"},optionLabelProp:"label",children:j.map(e=>{let s=p.callbackInfo[e]?.logo,l=p.callbackInfo[e]?.description;return(0,t.jsx)(h,{value:e,label:e,children:(0,t.jsx)(a.Tooltip,{title:l,placement:"right",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[s&&(0,t.jsx)("img",{src:s,alt:e,className:"w-4 h-4 object-contain",onError:t=>{let s=t.target,a=s.parentElement;if(a){let t=document.createElement("div");t.className="w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",t.textContent=e.charAt(0),a.replaceChild(t,s)}}}),(0,t.jsx)("span",{children:e})]})})},e)})}),(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"Select callbacks that should be disabled for this key. These callbacks will not receive any logging data."})]})]}),(0,t.jsx)(l.Divider,{}),(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)(u.CogIcon,{className:"w-5 h-5 text-blue-500"}),(0,t.jsx)("span",{className:"text-base font-semibold text-gray-800",children:"Logging Integrations"}),(0,t.jsx)(a.Tooltip,{title:"Configure callback logging integrations for this team.",children:(0,t.jsx)(r.InfoCircleOutlined,{className:"text-gray-400 cursor-help"})})]}),(0,t.jsx)(i.Button,{variant:"secondary",onClick:()=>{b([...e,{callback_name:"",callback_type:"success",callback_vars:{}}])},icon:c.PlusIcon,size:"sm",className:"hover:border-blue-400 hover:text-blue-500",type:"button",children:"Add Integration"})]}),(0,t.jsx)("div",{className:"space-y-4",children:e.map((l,c)=>{let u=l.callback_name?Object.entries(p.callback_map).find(([e,t])=>t===l.callback_name)?.[0]:void 0,m=u?p.callbackInfo[u]?.logo:null;return(0,t.jsxs)(n.Card,{className:"border border-gray-200 shadow-sm hover:shadow-md transition-shadow duration-200",decoration:"top",decorationColor:"blue",children:[(0,t.jsxs)("div",{className:"flex justify-between items-start mb-4",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[m&&(0,t.jsx)("img",{src:m,alt:u,className:"w-5 h-5 object-contain"}),(0,t.jsxs)("span",{className:"text-sm font-medium",children:[u||"New Integration"," Configuration"]})]}),(0,t.jsx)(i.Button,{variant:"light",onClick:()=>{b(e.filter((e,t)=>t!==c))},icon:d.TrashIcon,size:"xs",color:"red",className:"hover:bg-red-50",type:"button",children:"Remove"})]}),(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{className:"text-sm font-medium text-gray-700",children:"Integration Type"}),(0,t.jsx)(s.Select,{value:u,placeholder:"Select integration",onChange:e=>v(c,"callback_name",e),className:"w-full",optionLabelProp:"label",children:_.map(e=>{let s=p.callbackInfo[e]?.logo,l=p.callbackInfo[e]?.description;return(0,t.jsx)(h,{value:e,label:e,children:(0,t.jsx)(a.Tooltip,{title:l,placement:"right",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[s&&(0,t.jsx)("img",{src:s,alt:e,className:"w-4 h-4 object-contain",onError:t=>{let s=t.target,a=s.parentElement;if(a){let t=document.createElement("div");t.className="w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",t.textContent=e.charAt(0),a.replaceChild(t,s)}}}),(0,t.jsx)("span",{children:e})]})})},e)})})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{className:"text-sm font-medium text-gray-700",children:"Event Type"}),(0,t.jsxs)(s.Select,{value:l.callback_type,onChange:e=>v(c,"callback_type",e),className:"w-full",children:[(0,t.jsx)(h,{value:"success",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-green-500 rounded-full"}),(0,t.jsx)("span",{children:"Success Only"})]})}),(0,t.jsx)(h,{value:"failure",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-red-500 rounded-full"}),(0,t.jsx)("span",{children:"Failure Only"})]})}),(0,t.jsx)(h,{value:"success_and_failure",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)("span",{children:"Success & Failure"})]})})]})]})]}),((e,s)=>{if(!e.callback_name)return null;let l=Object.entries(p.callback_map).find(([t,s])=>s===e.callback_name)?.[0];if(!l)return null;let i=p.callbackInfo[l]?.dynamic_params||{};return 0===Object.keys(i).length?null:(0,t.jsxs)("div",{className:"mt-6 pt-4 border-t border-gray-100",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2 mb-4",children:[(0,t.jsx)("div",{className:"w-3 h-3 bg-blue-100 rounded-full flex items-center justify-center",children:(0,t.jsx)("div",{className:"w-1.5 h-1.5 bg-blue-500 rounded-full"})}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Integration Parameters"})]}),(0,t.jsx)("div",{className:"grid grid-cols-1 gap-4",children:Object.entries(i).map(([l,i])=>(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 capitalize flex items-center space-x-1",children:[(0,t.jsx)("span",{children:l.replace(/_/g," ")}),(0,t.jsx)(a.Tooltip,{title:`Environment variable reference recommended: os.environ/${l.toUpperCase()}`,children:(0,t.jsx)(r.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})}),"password"===i&&(0,t.jsx)("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-800",children:"Sensitive"}),"number"===i&&(0,t.jsx)("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-800",children:"Number"})]}),"number"===i&&(0,t.jsx)("span",{className:"text-xs text-gray-500",children:"Value must be between 0 and 1"}),"number"===i?(0,t.jsx)(g.default,{step:.01,width:400,placeholder:`os.environ/${l.toUpperCase()}`,value:e.callback_vars[l]||"",onChange:e=>w(s,l,e.target.value)}):(0,t.jsx)(o.TextInput,{type:"password"===i?"password":"text",placeholder:`os.environ/${l.toUpperCase()}`,value:e.callback_vars[l]||"",onChange:e=>w(s,l,e.target.value)})]},l))})]})})(l,c)]})]},c)})}),0===e.length&&(0,t.jsxs)("div",{className:"text-center py-12 text-gray-500 border-2 border-dashed border-gray-200 rounded-lg bg-gray-50/50",children:[(0,t.jsx)(u.CogIcon,{className:"w-12 h-12 text-gray-300 mb-3 mx-auto"}),(0,t.jsx)("div",{className:"text-base font-medium mb-1",children:"No logging integrations configured"}),(0,t.jsx)("div",{className:"text-sm text-gray-400",children:'Click "Add Integration" to configure logging for this team'})]})]})}])},651904,e=>{"use strict";var t=e.i(843476),s=e.i(599724),a=e.i(266484);e.s(["default",0,function({value:e,onChange:l,premiumUser:r=!1,disabledCallbacks:i=[],onDisabledCallbacksChange:n}){return r?(0,t.jsx)(a.default,{value:e,onChange:l,disabledCallbacks:i,onDisabledCallbacksChange:n}):(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex flex-wrap gap-2 mb-3",children:[(0,t.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,t.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,t.jsx)("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-lg",children:(0,t.jsxs)(s.Text,{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,t.jsx)("a",{href:"https://www.litellm.ai/#pricing",target:"_blank",rel:"noopener noreferrer",className:"underline",children:"here"}),"."]})})]})}])},460285,575260,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(404206),l=e.i(723731),r=e.i(653824),i=e.i(881073),n=e.i(197647),o=e.i(764205),c=e.i(158392),d=e.i(419470),u=e.i(689020);let m=(0,s.forwardRef)(({accessToken:e,value:m,onChange:p,modelData:g},h)=>{let[x,y]=(0,s.useState)({routerSettings:{},selectedStrategy:null,enableTagFiltering:!1}),[f,_]=(0,s.useState)([]),[j,b]=(0,s.useState)([]),[v,w]=(0,s.useState)([]),[N,k]=(0,s.useState)([]),[S,C]=(0,s.useState)({}),[T,I]=(0,s.useState)({}),A=(0,s.useRef)(!1),L=(0,s.useRef)(null);(0,s.useEffect)(()=>{let e=m?.router_settings?JSON.stringify({routing_strategy:m.router_settings.routing_strategy,fallbacks:m.router_settings.fallbacks,enable_tag_filtering:m.router_settings.enable_tag_filtering}):null;if(A.current&&e===L.current){A.current=!1;return}if(A.current&&e!==L.current&&(A.current=!1),e!==L.current)if(L.current=e,m?.router_settings){let e=m.router_settings,{fallbacks:t,...s}=e;y({routerSettings:s,selectedStrategy:e.routing_strategy||null,enableTagFiltering:e.enable_tag_filtering??!1});let a=e.fallbacks||[];_(a),b(a&&0!==a.length?a.map((e,t)=>{let[s,a]=Object.entries(e)[0];return{id:(t+1).toString(),primaryModel:s||null,fallbackModels:a||[]}}):[{id:"1",primaryModel:null,fallbackModels:[]}])}else y({routerSettings:{},selectedStrategy:null,enableTagFiltering:!1}),_([]),b([{id:"1",primaryModel:null,fallbackModels:[]}])},[m]),(0,s.useEffect)(()=>{e&&(0,o.getRouterSettingsCall)(e).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}}),C(t);let s=e.fields.find(e=>"routing_strategy"===e.field_name);s?.options&&k(s.options),e.routing_strategy_descriptions&&I(e.routing_strategy_descriptions)}})},[e]),(0,s.useEffect)(()=>{e&&(async()=>{try{let t=await (0,u.fetchAvailableModels)(e);w(t)}catch(e){console.error("Error fetching model info for fallbacks:",e)}})()},[e]);let F=()=>{let e=new Set(["allowed_fails","cooldown_time","num_retries","timeout","retry_after"]),t=new Set(["model_group_alias","retry_policy"]),s=Object.fromEntries(Object.entries({...x.routerSettings,enable_tag_filtering:x.enableTagFiltering,routing_strategy:x.selectedStrategy,fallbacks:f.length>0?f:null}).map(([s,a])=>{if("routing_strategy_args"!==s&&"routing_strategy"!==s&&"enable_tag_filtering"!==s&&"fallbacks"!==s){let l=document.querySelector(`input[name="${s}"]`);if(l&&void 0!==l.value&&""!==l.value){let r=((s,a,l)=>{if(null==a)return l;let r=String(a).trim();if(""===r||"null"===r.toLowerCase())return null;if(e.has(s)){let e=Number(r);return Number.isNaN(e)?l:e}if(t.has(s)){if(""===r)return null;try{return JSON.parse(r)}catch{return l}}return"true"===r.toLowerCase()||"false"!==r.toLowerCase()&&r})(s,l.value,a);return[s,r]}}else if("routing_strategy"===s)return[s,x.selectedStrategy];else if("enable_tag_filtering"===s)return[s,x.enableTagFiltering];else if("fallbacks"===s)return[s,f.length>0?f:null];else if("routing_strategy_args"===s&&"latency-based-routing"===x.selectedStrategy){let e=document.querySelector('input[name="lowest_latency_buffer"]'),t=document.querySelector('input[name="ttl"]'),s={};return e?.value&&(s.lowest_latency_buffer=Number(e.value)),t?.value&&(s.ttl=Number(t.value)),["routing_strategy_args",Object.keys(s).length>0?s:null]}return[s,a]}).filter(e=>null!=e)),a=(e,t=!1)=>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:f.length>0?f: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:x.enableTagFiltering,routing_strategy_args:a(s.routing_strategy_args)}};(0,s.useEffect)(()=>{if(!p)return;let e=setTimeout(()=>{A.current=!0,p({router_settings:F()})},100);return()=>clearTimeout(e)},[x,f]);let M=Array.from(new Set(v.map(e=>e.model_group))).sort();return((0,s.useImperativeHandle)(h,()=>({getValue:()=>({router_settings:F()})})),e)?(0,t.jsx)("div",{className:"w-full",children:(0,t.jsxs)(r.TabGroup,{className:"w-full",children:[(0,t.jsxs)(i.TabList,{variant:"line",defaultValue:"1",className:"px-8 pt-4",children:[(0,t.jsx)(n.Tab,{value:"1",children:"Loadbalancing"}),(0,t.jsx)(n.Tab,{value:"2",children:"Fallbacks"})]}),(0,t.jsxs)(l.TabPanels,{className:"px-8 py-6",children:[(0,t.jsx)(a.TabPanel,{children:(0,t.jsx)(c.default,{value:x,onChange:y,routerFieldsMetadata:S,availableRoutingStrategies:N,routingStrategyDescriptions:T})}),(0,t.jsx)(a.TabPanel,{children:(0,t.jsx)(d.FallbackSelectionForm,{groups:j,onGroupsChange:e=>{b(e),_(e.filter(e=>e.primaryModel&&e.fallbackModels.length>0).map(e=>({[e.primaryModel]:e.fallbackModels})))},availableModels:M,maxGroups:5})})]})]})}):null});m.displayName="RouterSettingsAccordion",e.s(["default",0,m],460285);var p=e.i(199133),g=e.i(482725),h=e.i(56456);e.s(["default",0,({projects:e,value:s,onChange:a,disabled:l,loading:r,teamId:i})=>{let n=i?e?.filter(e=>e.team_id===i):e;return(0,t.jsx)(p.Select,{showSearch:!0,placeholder:"Search or select a project",value:s,onChange:a,disabled:l,loading:r,allowClear:!0,notFoundContent:r?(0,t.jsx)(g.Spin,{indicator:(0,t.jsx)(h.LoadingOutlined,{spin:!0}),size:"small"}):void 0,filterOption:(e,t)=>{if(!t)return!1;let s=n?.find(e=>e.project_id===t.key);if(!s)return!1;let a=e.toLowerCase().trim(),l=(s.project_alias||"").toLowerCase(),r=(s.project_id||"").toLowerCase();return l.includes(a)||r.includes(a)},optionFilterProp:"children",children:!r&&n?.map(e=>(0,t.jsxs)(p.Select.Option,{value:e.project_id,children:[(0,t.jsx)("span",{className:"font-medium",children:e.project_alias||e.project_id})," ",(0,t.jsxs)("span",{className:"text-gray-500",children:["(",e.project_id,")"]})]},e.project_id))})}],575260)},702597,364769,e=>{"use strict";var t=e.i(843476),s=e.i(207082),a=e.i(510674),l=e.i(292639),r=e.i(135214),i=e.i(500330),n=e.i(827252),o=e.i(912598),c=e.i(677667),d=e.i(130643),u=e.i(898667),m=e.i(994388),p=e.i(309426),g=e.i(350967),h=e.i(599724),x=e.i(779241),y=e.i(629569),f=e.i(464571),_=e.i(808613),j=e.i(311451),b=e.i(212931),v=e.i(91739),w=e.i(199133),N=e.i(790848),k=e.i(262218),S=e.i(592968),C=e.i(374009),T=e.i(271645),I=e.i(708347),A=e.i(552130),L=e.i(557662),F=e.i(9314),M=e.i(860585),O=e.i(82946),P=e.i(392110),E=e.i(533882),$=e.i(844565),V=e.i(651904),B=e.i(939510),G=e.i(460285),R=e.i(663435),D=e.i(575260),K=e.i(371455),U=e.i(355619),q=e.i(75921),z=e.i(390605),W=e.i(727749),H=e.i(764205),Q=e.i(237016),J=e.i(998573);let Y=({apiKey:e})=>{let[s,a]=(0,T.useState)(!1);return(0,t.jsxs)("div",{children:[(0,t.jsxs)("p",{className:"mb-2",children:["Please save this secret key somewhere safe and accessible. For security reasons,"," ",(0,t.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,t.jsx)("p",{className:"text-sm text-gray-600 mt-3 mb-1",children:"Virtual Key:"}),(0,t.jsx)("div",{style:{background:"#f8f8f8",padding:"10px",borderRadius:"5px",marginBottom:"10px"},children:(0,t.jsx)("pre",{style:{wordWrap:"break-word",whiteSpace:"normal",margin:0},children:e})}),(0,t.jsx)(Q.CopyToClipboard,{text:e,onCopy:()=>{a(!0),J.message.success("Key copied to clipboard"),setTimeout(()=>a(!1),2e3)},children:(0,t.jsx)(f.Button,{type:"primary",style:{marginTop:12},children:s?"Copied!":"Copy Virtual Key"})})]})};e.s(["default",0,Y],364769);var X=e.i(435451),Z=e.i(916940);let{Option:ee}=w.Select,et=async(e,t,s,a)=>{try{if(null===e||null===t)return[];if(null!==s){let l=(await (0,H.modelAvailableCall)(s,e,t,!0,a,!0)).data.map(e=>e.id);return console.log("available_model_names:",l),l}return[]}catch(e){return console.error("Error fetching user models:",e),[]}},es=async(e,t,s,a)=>{try{if(null===e||null===t)return;if(null!==s){let l=(await (0,H.modelAvailableCall)(s,e,t)).data.map(e=>e.id);console.log("available_model_names:",l),a(l)}}catch(e){console.error("Error fetching user models:",e)}};e.s(["default",0,({team:e,teams:Q,data:J,addKey:ea,autoOpenCreate:el,prefillData:er})=>{let{accessToken:ei,userId:en,userRole:eo,premiumUser:ec}=(0,r.default)(),ed=ec||null!=eo&&I.rolesWithWriteAccess.includes(eo),{data:eu,isLoading:em}=(0,a.useProjects)(),{data:ep}=(0,l.useUISettings)(),eg=!!ep?.values?.enable_projects_ui,eh=(0,o.useQueryClient)(),[ex]=_.Form.useForm(),[ey,ef]=(0,T.useState)(!1),[e_,ej]=(0,T.useState)(null),[eb,ev]=(0,T.useState)(null),[ew,eN]=(0,T.useState)([]),[ek,eS]=(0,T.useState)([]),[eC,eT]=(0,T.useState)("you"),[eI,eA]=(0,T.useState)((e=>{let t=[];if(console.log("data:",JSON.stringify(e)),e)for(let s of e)s.metadata&&s.metadata.tags&&t.push(...s.metadata.tags);let s=Array.from(new Set(t)).map(e=>({value:e,label:e}));return console.log("uniqueTags:",s),s})(J)),[eL,eF]=(0,T.useState)(!1),[eM,eO]=(0,T.useState)(null),[eP,eE]=(0,T.useState)([]),[e$,eV]=(0,T.useState)([]),[eB,eG]=(0,T.useState)([]),[eR,eD]=(0,T.useState)([]),[eK,eU]=(0,T.useState)(e),[eq,ez]=(0,T.useState)(null),[eW,eH]=(0,T.useState)(!1),[eQ,eJ]=(0,T.useState)(null),[eY,eX]=(0,T.useState)({}),[eZ,e0]=(0,T.useState)([]),[e1,e2]=(0,T.useState)(!1),[e4,e5]=(0,T.useState)([]),[e3,e6]=(0,T.useState)([]),[e7,e9]=(0,T.useState)("llm_api"),[e8,te]=(0,T.useState)({}),[tt,ts]=(0,T.useState)(!1),[ta,tl]=(0,T.useState)("30d"),[tr,ti]=(0,T.useState)(null),[tn,to]=(0,T.useState)(0),[tc,td]=(0,T.useState)([]),[tu,tm]=(0,T.useState)(null),tp=()=>{ef(!1),ex.resetFields(),eD([]),e6([]),e9("llm_api"),te({}),ts(!1),tl("30d"),ti(null),to(e=>e+1),tm(null),ez(null)},tg=()=>{ef(!1),ej(null),eU(null),ex.resetFields(),eD([]),e6([]),e9("llm_api"),te({}),ts(!1),tl("30d"),ti(null),to(e=>e+1),tm(null),ez(null)};(0,T.useEffect)(()=>{en&&eo&&ei&&es(en,eo,ei,eN)},[ei,en,eo]),(0,T.useEffect)(()=>{ei&&(0,H.getAgentsList)(ei).then(e=>td(e?.agents||[])).catch(()=>td([]))},[ei]),(0,T.useEffect)(()=>{let e=async()=>{try{let e=(await (0,H.getPoliciesList)(ei)).policies.map(e=>e.policy_name);eV(e)}catch(e){console.error("Failed to fetch policies:",e)}},t=async()=>{try{let e=await (0,H.getPromptsList)(ei);eG(e.prompts.map(e=>e.prompt_id))}catch(e){console.error("Failed to fetch prompts:",e)}};(async()=>{try{let e=(await (0,H.getGuardrailsList)(ei)).guardrails.map(e=>e.guardrail_name);eE(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})(),e(),t()},[ei]),(0,T.useEffect)(()=>{(async()=>{try{if(ei){let e=sessionStorage.getItem("possibleUserRoles");if(e)eX(JSON.parse(e));else{let e=await (0,H.getPossibleUserRoles)(ei);sessionStorage.setItem("possibleUserRoles",JSON.stringify(e)),eX(e)}}}catch(e){console.error("Error fetching possible user roles:",e)}})()},[ei]),(0,T.useEffect)(()=>{if(el&&!eL&&Q&&eo&&I.rolesWithWriteAccess.includes(eo)&&(ef(!0),eF(!0),er)){if(er.owned_by&&("another_user"===er.owned_by&&"Admin"!==eo?eT("you"):eT(er.owned_by)),er.team_id){let e=Q?.find(e=>e.team_id===er.team_id)||null;e&&(eU(e),ex.setFieldsValue({team_id:er.team_id}))}er.key_alias&&ex.setFieldsValue({key_alias:er.key_alias}),er.models&&er.models.length>0&&eO(er.models),er.key_type&&(e9(er.key_type),ex.setFieldsValue({key_type:er.key_type}))}},[el,er,Q,eL,ex,eo]);let th=ek.includes("no-default-models")&&!eK,tx=async e=>{try{let t,a=e?.key_alias??"",l=e?.team_id??null;if((J?.filter(e=>e.team_id===l).map(e=>e.key_alias)??[]).includes(a))throw Error(`Key alias ${a} already exists for team with ID ${l}, please provide another key alias`);if(W.default.info("Making API Call"),ef(!0),"you"===eC)e.user_id=en;else if("agent"===eC){if(!tu)return void W.default.fromBackend("Please select an agent");e.agent_id=tu}let r={};try{r=JSON.parse(e.metadata||"{}")}catch(e){console.error("Error parsing metadata:",e)}if("service_account"===eC&&(r.service_account_id=e.key_alias),eR.length>0&&(r={...r,logging:eR.filter(e=>e.callback_name)}),e3.length>0){let e=(0,L.mapDisplayToInternalNames)(e3);r={...r,litellm_disabled_callbacks:e}}if(tt&&(e.auto_rotate=!0,e.rotation_interval=ta),e.duration&&""!==e.duration.trim()||(e.duration=null),e.metadata=JSON.stringify(r),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&&(e.allowed_mcp_servers_and_groups.servers?.length>0||e.allowed_mcp_servers_and_groups.accessGroups?.length>0)){e.object_permission||(e.object_permission={});let{servers:t,accessGroups:s}=e.allowed_mcp_servers_and_groups;t&&t.length>0&&(e.object_permission.mcp_servers=t),s&&s.length>0&&(e.object_permission.mcp_access_groups=s),delete e.allowed_mcp_servers_and_groups}let i=e.mcp_tool_permissions||{};if(Object.keys(i).length>0&&(e.object_permission||(e.object_permission={}),e.object_permission.mcp_tool_permissions=i),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&&(e.allowed_agents_and_groups.agents?.length>0||e.allowed_agents_and_groups.accessGroups?.length>0)){e.object_permission||(e.object_permission={});let{agents:t,accessGroups:s}=e.allowed_agents_and_groups;t&&t.length>0&&(e.object_permission.agents=t),s&&s.length>0&&(e.object_permission.agent_access_groups=s),delete e.allowed_agents_and_groups}Object.keys(e8).length>0&&(e.aliases=JSON.stringify(e8)),tr?.router_settings&&Object.values(tr.router_settings).some(e=>null!=e&&""!==e)&&(e.router_settings=tr.router_settings),t="service_account"===eC?await (0,H.keyCreateServiceAccountCall)(ei,e):await (0,H.keyCreateCall)(ei,en,e),console.log("key create Response:",t),ea(t),eh.invalidateQueries({queryKey:s.keyKeys.lists()}),ej(t.key),ev(t.soft_budget),W.default.success("Virtual Key Created"),ex.resetFields(),localStorage.removeItem("userData"+en)}catch(t){console.log("error in create key:",t);let e=(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: ${e}`;let s=t;try{if(!e||"object"!=typeof e||e instanceof Error){let e=t.match(/\{[\s\S]*\}/);if(e){let t=JSON.parse(e[0]),a=t?.error||t;a?.message&&(s=a.message)}}else{let t=e?.error||e;t?.message&&(s=t.message)}}catch(e){}return t.includes("team_member_permission_error")||s.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: ${e}`})(t);W.default.fromBackend(e)}};(0,T.useEffect)(()=>{if(eq){let e=eu?.find(e=>e.project_id===eq);eS(e?.models??[]),ex.setFieldValue("models",[]);return}en&&eo&&ei&&et(en,eo,ei,eK?.team_id??null).then(e=>{eS(Array.from(new Set([...eK?.models??[],...e])))}),eM||ex.setFieldValue("models",[]),ex.setFieldValue("allowed_mcp_servers_and_groups",{servers:[],accessGroups:[]})},[eK,eq,ei,en,eo,ex]),(0,T.useEffect)(()=>{if(!eM||0===eM.length||!ek||0===ek.length)return;let e=eM.filter(e=>ek.includes(e));e.length>0&&ex.setFieldsValue({models:e}),eO(null)},[eM,ek,ex]),(0,T.useEffect)(()=>{if(!eq||!Q)return;let e=eu?.find(e=>e.project_id===eq);if(!e?.team_id||eK?.team_id===e.team_id)return;let t=Q.find(t=>t.team_id===e.team_id)||null;t&&(eU(t),ex.setFieldValue("team_id",t.team_id))},[Q,eq,eu]);let ty=async e=>{if(!e)return void e0([]);e2(!0);try{let t=new URLSearchParams;if(t.append("user_email",e),null==ei)return;let s=(await (0,H.userFilterUICall)(ei,t)).map(e=>({label:`${e.user_email} (${e.user_id})`,value:e.user_id,user:e}));e0(s)}catch(e){console.error("Error fetching users:",e),W.default.fromBackend("Failed to search for users")}finally{e2(!1)}},tf=(0,T.useCallback)((0,C.default)(e=>ty(e),300),[ei]);return(0,t.jsxs)("div",{children:[eo&&I.rolesWithWriteAccess.includes(eo)&&(0,t.jsx)(m.Button,{className:"mx-auto",onClick:()=>ef(!0),children:"+ Create New Key"}),(0,t.jsx)(b.Modal,{open:ey,width:1e3,footer:null,onOk:tp,onCancel:tg,children:(0,t.jsxs)(_.Form,{form:ex,onFinish:tx,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,t.jsxs)("div",{className:"mb-8",children:[(0,t.jsx)(y.Title,{className:"mb-4",children:"Key Ownership"}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Owned By"," ",(0,t.jsx)(S.Tooltip,{title:"Select who will own this Virtual Key",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),className:"mb-4",children:(0,t.jsxs)(v.Radio.Group,{onChange:e=>eT(e.target.value),value:eC,children:[(0,t.jsx)(v.Radio,{value:"you",children:"You"}),(0,t.jsx)(v.Radio,{value:"service_account",children:"Service Account"}),"Admin"===eo&&(0,t.jsx)(v.Radio,{value:"another_user",children:"Another User"}),(0,t.jsxs)(v.Radio,{value:"agent",children:["Agent ",(0,t.jsx)(k.Tag,{color:"purple",children:"New"})]})]})}),"another_user"===eC&&(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["User ID"," ",(0,t.jsx)(S.Tooltip,{title:"The user who will own this key and be responsible for its usage",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"user_id",className:"mt-4",rules:[{required:"another_user"===eC,message:"Please input the user ID of the user you are assigning the key to"}],children:(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{style:{display:"flex",marginBottom:"8px"},children:[(0,t.jsx)(w.Select,{showSearch:!0,placeholder:"Type email to search for users",filterOption:!1,onSearch:e=>{tf(e)},onSelect:(e,t)=>{let s;return s=t.user,void ex.setFieldsValue({user_id:s.user_id})},options:eZ,loading:e1,allowClear:!0,style:{width:"100%"},notFoundContent:e1?"Searching...":"No users found"}),(0,t.jsx)(f.Button,{onClick:()=>eH(!0),style:{marginLeft:"8px"},children:"Create User"})]}),(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"Search by email to find users"})]})}),"agent"===eC&&(0,t.jsxs)("div",{className:"mt-4 p-4 bg-purple-50 border border-purple-200 rounded-md",children:[(0,t.jsx)("div",{className:"mb-3",children:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700",children:["Select Agent ",(0,t.jsx)("span",{className:"text-red-500",children:"*"})]})}),(0,t.jsx)(w.Select,{showSearch:!0,placeholder:"Select an agent",style:{width:"100%"},value:tu,onChange:e=>tm(e),filterOption:(e,t)=>t?.label?.toLowerCase().includes(e.toLowerCase()),options:tc.map(e=>({label:e.agent_name||e.agent_id,value:e.agent_id}))}),(0,t.jsx)("div",{className:"text-xs text-gray-500 mt-2",children:"This key will be used by the selected agent to make requests to LiteLLM"})]}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Team"," ",(0,t.jsx)(S.Tooltip,{title:"The team this key belongs to, which determines available models and budget limits",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"team_id",initialValue:e?e.team_id:null,className:"mt-4",rules:[{required:"service_account"===eC,message:"Please select a team for the service account"}],help:"service_account"===eC?"required":"",children:(0,t.jsx)(R.default,{teams:Q,disabled:null!==eq,loading:!Q,onChange:e=>{eU(Q?.find(t=>t.team_id===e)||null),ez(null),ex.setFieldValue("project_id",void 0)}})}),eg&&(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Project"," ",(0,t.jsx)(S.Tooltip,{title:"Assign this key to a project. Selecting a project will lock the team to the project's team.",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"project_id",className:"mt-4",children:(0,t.jsx)(D.default,{projects:eu,teamId:eK?.team_id,loading:em||!Q,onChange:e=>{if(!e){ez(null),eU(null),ex.setFieldValue("team_id",void 0);return}ez(e)}})})]}),th&&(0,t.jsx)("div",{className:"mb-8 p-4 bg-blue-50 border border-blue-200 rounded-md",children:(0,t.jsx)(h.Text,{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."})}),!th&&(0,t.jsxs)("div",{className:"mb-8",children:[(0,t.jsx)(y.Title,{className:"mb-4",children:"Key Details"}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["you"===eC||"another_user"===eC?"Key Name":"Service Account ID"," ",(0,t.jsx)(S.Tooltip,{title:"you"===eC||"another_user"===eC?"A descriptive name to identify this key":"Unique identifier for this service account",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"key_alias",rules:[{required:!0,message:`Please input a ${"you"===eC?"key name":"service account ID"}`}],help:"required",children:(0,t.jsx)(x.TextInput,{placeholder:""})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Models"," ",(0,t.jsx)(S.Tooltip,{title:"Select which models this key can access. Choose 'All Team Models' to grant access to all models available to the team. Leave empty to allow access to all models.",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"models",rules:[],help:"management"===e7||"read_only"===e7?"Models field is disabled for this key type":"optional - leave empty to allow access to all models",className:"mt-4",children:(0,t.jsxs)(w.Select,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},disabled:"management"===e7||"read_only"===e7,onChange:e=>{e.includes("all-team-models")&&ex.setFieldsValue({models:["all-team-models"]})},children:[!eq&&(0,t.jsx)(ee,{value:"all-team-models",children:"All Team Models"},"all-team-models"),ek.map(e=>(0,t.jsx)(ee,{value:e,children:(0,U.getModelDisplayName)(e)},e))]})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Key Type"," ",(0,t.jsx)(S.Tooltip,{title:"Select the type of key to determine what routes and operations this key can access",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"key_type",initialValue:"llm_api",className:"mt-4",children:(0,t.jsxs)(w.Select,{defaultValue:"llm_api",placeholder:"Select key type",style:{width:"100%"},optionLabelProp:"label",onChange:e=>{e9(e),("management"===e||"read_only"===e)&&ex.setFieldsValue({models:[]})},children:[(0,t.jsx)(ee,{value:"default",label:"Default",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Default"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call AI APIs + Management routes"})]})}),(0,t.jsx)(ee,{value:"llm_api",label:"AI APIs",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"AI APIs"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call only AI API routes (chat/completions, embeddings, etc.)"})]})}),(0,t.jsx)(ee,{value:"management",label:"Management",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Management"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call only management routes (user/team/key management)"})]})})]})})]}),!th&&(0,t.jsx)("div",{className:"mb-8",children:(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)(y.Title,{className:"m-0",children:"Optional Settings"})}),(0,t.jsxs)(d.AccordionBody,{children:[(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Max Budget (USD)"," ",(0,t.jsx)(S.Tooltip,{title:"Maximum amount in USD this key can spend. When reached, the key will be blocked from making further requests",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"max_budget",help:`Budget cannot exceed team max budget: $${e?.max_budget!==null&&e?.max_budget!==void 0?e?.max_budget:"unlimited"}`,rules:[{validator:async(t,s)=>{if(s&&e&&null!==e.max_budget&&s>e.max_budget)throw Error(`Budget cannot exceed team max budget: $${(0,i.formatNumberWithCommas)(e.max_budget,4)}`)}}],children:(0,t.jsx)(X.default,{step:.01,precision:2,width:200})}),(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Reset Budget"," ",(0,t.jsx)(S.Tooltip,{title:"How often the budget should reset. For example, setting 'daily' will reset the budget every 24 hours",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"budget_duration",help:`Team Reset Budget: ${e?.budget_duration!==null&&e?.budget_duration!==void 0?e?.budget_duration:"None"}`,children:(0,t.jsx)(M.default,{onChange:e=>ex.setFieldValue("budget_duration",e)})}),(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Tokens per minute Limit (TPM)"," ",(0,t.jsx)(S.Tooltip,{title:"Maximum number of tokens this key can process per minute. Helps control usage and costs",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"tpm_limit",help:`TPM cannot exceed team TPM limit: ${e?.tpm_limit!==null&&e?.tpm_limit!==void 0?e?.tpm_limit:"unlimited"}`,rules:[{validator:async(t,s)=>{if(s&&e&&null!==e.tpm_limit&&s>e.tpm_limit)throw Error(`TPM limit cannot exceed team TPM limit: ${e.tpm_limit}`)}}],children:(0,t.jsx)(X.default,{step:1,width:400})}),(0,t.jsx)(B.default,{type:"tpm",name:"tpm_limit_type",className:"mt-4",initialValue:null,form:ex,showDetailedDescriptions:!0}),(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Requests per minute Limit (RPM)"," ",(0,t.jsx)(S.Tooltip,{title:"Maximum number of API requests this key can make per minute. Helps prevent abuse and manage load",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"rpm_limit",help:`RPM cannot exceed team RPM limit: ${e?.rpm_limit!==null&&e?.rpm_limit!==void 0?e?.rpm_limit:"unlimited"}`,rules:[{validator:async(t,s)=>{if(s&&e&&null!==e.rpm_limit&&s>e.rpm_limit)throw Error(`RPM limit cannot exceed team RPM limit: ${e.rpm_limit}`)}}],children:(0,t.jsx)(X.default,{step:1,width:400})}),(0,t.jsx)(B.default,{type:"rpm",name:"rpm_limit_type",className:"mt-4",initialValue:null,form:ex,showDetailedDescriptions:!0}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Guardrails"," ",(0,t.jsx)(S.Tooltip,{title:"Apply safety guardrails to this key to filter content or enforce policies",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",className:"mt-4",help:ed?"Select existing guardrails or enter new ones":"Premium feature - Upgrade to set guardrails by key",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},disabled:!ed,placeholder:ed?"Select or enter guardrails":"Premium feature - Upgrade to set guardrails by key",options:eP.map(e=>({value:e,label:e}))})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Disable Global Guardrails"," ",(0,t.jsx)(S.Tooltip,{title:"When enabled, this key will bypass any guardrails configured to run on every request (global guardrails)",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"disable_global_guardrails",className:"mt-4",valuePropName:"checked",help:ed?"Bypass global guardrails for this key":"Premium feature - Upgrade to disable global guardrails by key",children:(0,t.jsx)(N.Switch,{disabled:!ed,checkedChildren:"Yes",unCheckedChildren:"No"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Policies"," ",(0,t.jsx)(S.Tooltip,{title:"Apply policies to this key to control guardrails and other settings",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/guardrail_policies",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"policies",className:"mt-4",help:ec?"Select existing policies or enter new ones":"Premium feature - Upgrade to set policies by key",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},disabled:!ec,placeholder:ec?"Select or enter policies":"Premium feature - Upgrade to set policies by key",options:e$.map(e=>({value:e,label:e}))})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Prompts"," ",(0,t.jsx)(S.Tooltip,{title:"Allow this key to use specific prompt templates",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/prompt_management",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"prompts",className:"mt-4",help:ec?"Select existing prompts or enter new ones":"Premium feature - Upgrade to set prompts by key",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},disabled:!ec,placeholder:ec?"Select or enter prompts":"Premium feature - Upgrade to set prompts by key",options:eB.map(e=>({value:e,label:e}))})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Access Groups"," ",(0,t.jsx)(S.Tooltip,{title:"Assign access groups to this key. Access groups control which models, MCP servers, and agents this key can use",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"access_group_ids",className:"mt-4",help:"Select access groups to assign to this key",children:(0,t.jsx)(F.default,{placeholder:"Select access groups (optional)"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Pass Through Routes"," ",(0,t.jsx)(S.Tooltip,{title:"Allow this key to use specific pass through routes",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/pass_through",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"allowed_passthrough_routes",className:"mt-4",help:ec?"Select existing pass through routes or enter new ones":"Premium feature - Upgrade to set pass through routes by key",children:(0,t.jsx)($.default,{onChange:e=>ex.setFieldValue("allowed_passthrough_routes",e),value:ex.getFieldValue("allowed_passthrough_routes"),accessToken:ei,placeholder:ec?"Select or enter pass through routes":"Premium feature - Upgrade to set pass through routes by key",disabled:!ec,teamId:eK?eK.team_id:null})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Vector Stores"," ",(0,t.jsx)(S.Tooltip,{title:"Select which vector stores this key can access. If none selected, the key will have access to all available vector stores",children:(0,t.jsx)(n.InfoCircleOutlined,{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,t.jsx)(Z.default,{onChange:e=>ex.setFieldValue("allowed_vector_store_ids",e),value:ex.getFieldValue("allowed_vector_store_ids"),accessToken:ei,placeholder:"Select vector stores (optional)"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Metadata"," ",(0,t.jsx)(S.Tooltip,{title:"JSON object with additional information about this key. Used for tracking or custom logic",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"metadata",className:"mt-4",children:(0,t.jsx)(j.Input.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Tags"," ",(0,t.jsx)(S.Tooltip,{title:"Tags for tracking spend and/or doing tag-based routing. Used for analytics and filtering",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"tags",className:"mt-4",help:"Tags for tracking spend and/or doing tag-based routing.",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},placeholder:"Enter tags",tokenSeparators:[","],options:eI})}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"MCP Settings"})}),(0,t.jsxs)(d.AccordionBody,{children:[(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed MCP Servers"," ",(0,t.jsx)(S.Tooltip,{title:"Select which MCP servers or access groups this key can access",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_mcp_servers_and_groups",help:"Select MCP servers or access groups this key can access",children:(0,t.jsx)(q.default,{onChange:e=>ex.setFieldValue("allowed_mcp_servers_and_groups",e),value:ex.getFieldValue("allowed_mcp_servers_and_groups"),accessToken:ei,teamId:eK?.team_id??null,placeholder:"Select MCP servers or access groups (optional)"})}),(0,t.jsx)(_.Form.Item,{name:"mcp_tool_permissions",initialValue:{},hidden:!0,children:(0,t.jsx)(j.Input,{type:"hidden"})}),(0,t.jsx)(_.Form.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:()=>(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(z.default,{accessToken:ei,selectedServers:ex.getFieldValue("allowed_mcp_servers_and_groups")?.servers||[],toolPermissions:ex.getFieldValue("mcp_tool_permissions")||{},onChange:e=>ex.setFieldsValue({mcp_tool_permissions:e})})})})]})]}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Agent Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Agents"," ",(0,t.jsx)(S.Tooltip,{title:"Select which agents or access groups this key can access",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_agents_and_groups",help:"Select agents or access groups this key can access",children:(0,t.jsx)(A.default,{onChange:e=>ex.setFieldValue("allowed_agents_and_groups",e),value:ex.getFieldValue("allowed_agents_and_groups"),accessToken:ei,placeholder:"Select agents or access groups (optional)"})})})]}),ec?(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Logging Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(V.default,{value:eR,onChange:eD,premiumUser:!0,disabledCallbacks:e3,onDisabledCallbacksChange:e6})})})]}):(0,t.jsx)(S.Tooltip,{title:(0,t.jsxs)("span",{children:["Key-level logging settings is an enterprise feature, get in touch -",(0,t.jsx)("a",{href:"https://www.litellm.ai/enterprise",target:"_blank",children:"https://www.litellm.ai/enterprise"})]}),placement:"top",children:(0,t.jsxs)("div",{style:{position:"relative"},children:[(0,t.jsx)("div",{style:{opacity:.5},children:(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Logging Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(V.default,{value:eR,onChange:eD,premiumUser:!1,disabledCallbacks:e3,onDisabledCallbacksChange:e6})})})]})}),(0,t.jsx)("div",{style:{position:"absolute",inset:0,cursor:"not-allowed"}})]})}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Router Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4 w-full",children:(0,t.jsx)(G.default,{accessToken:ei||"",value:tr||void 0,onChange:ti,modelData:ew.length>0?{data:ew.map(e=>({model_name:e}))}:void 0},tn)})})]},`router-settings-accordion-${tn}`),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Model Aliases"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsxs)("div",{className:"mt-4",children:[(0,t.jsx)(h.Text,{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,t.jsx)(E.default,{accessToken:ei,initialModelAliases:e8,onAliasUpdate:te,showExampleConfig:!1})]})})]}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Key Lifecycle"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(P.default,{form:ex,autoRotationEnabled:tt,onAutoRotationChange:ts,rotationInterval:ta,onRotationIntervalChange:tl,isCreateMode:!0})})}),(0,t.jsx)(_.Form.Item,{name:"duration",hidden:!0,initialValue:null,children:(0,t.jsx)(j.Input,{})})]}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("b",{children:"Advanced Settings"}),(0,t.jsx)(S.Tooltip,{title:(0,t.jsxs)("span",{children:["Learn more about advanced settings in our"," ",(0,t.jsx)("a",{href:H.proxyBaseUrl?`${H.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,t.jsx)(n.InfoCircleOutlined,{className:"text-gray-400 hover:text-gray-300 cursor-help"})})]})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)(O.default,{schemaComponent:"GenerateKeyRequest",form:ex,excludedFields:["key_alias","team_id","models","duration","metadata","tags","guardrails","max_budget","budget_duration","tpm_limit","rpm_limit"]})})]})]})]})}),(0,t.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,t.jsx)(f.Button,{htmlType:"submit",disabled:th,style:{opacity:th?.5:1},children:"Create Key"})})]})}),eW&&(0,t.jsx)(b.Modal,{title:"Create New User",open:eW,onCancel:()=>eH(!1),footer:null,width:800,children:(0,t.jsx)(K.CreateUserButton,{userID:en,accessToken:ei,teams:Q,possibleUIRoles:eY,onUserCreated:e=>{eJ(e),ex.setFieldsValue({user_id:e}),eH(!1)},isEmbedded:!0})}),e_&&(0,t.jsx)(b.Modal,{open:ey,onOk:tp,onCancel:tg,footer:null,children:(0,t.jsxs)(g.Grid,{numItems:1,className:"gap-2 w-full",children:[(0,t.jsx)(y.Title,{children:"Save your Key"}),(0,t.jsx)(p.Col,{numColSpan:1,children:null!=e_?(0,t.jsx)(Y,{apiKey:e_}):(0,t.jsx)(h.Text,{children:"Key being created, this might take 30s"})})]})})]})},"fetchTeamModels",0,et,"fetchUserModels",0,es],702597)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/1eccde2dab0b3311.js b/litellm/proxy/_experimental/out/_next/static/chunks/1eccde2dab0b3311.js new file mode 100644 index 00000000000..49b9f1ea72e --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/1eccde2dab0b3311.js @@ -0,0 +1 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,948401,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M928 160H96c-17.7 0-32 14.3-32 32v640c0 17.7 14.3 32 32 32h832c17.7 0 32-14.3 32-32V192c0-17.7-14.3-32-32-32zm-40 110.8V792H136V270.8l-27.6-21.5 39.3-50.5 42.8 33.3h643.1l42.8-33.3 39.3 50.5-27.7 21.5zM833.6 232L512 482 190.4 232l-42.8-33.3-39.3 50.5 27.6 21.5 341.6 265.6a55.99 55.99 0 0068.7 0L888 270.8l27.6-21.5-39.3-50.5-42.7 33.2z"}}]},name:"mail",theme:"outlined"};var o=e.i(9583),l=r.forwardRef(function(e,l){return r.createElement(o.default,(0,t.default)({},e,{ref:l,icon:a}))});e.s(["MailOutlined",0,l],948401)},38243,908286,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),a=e.i(876556);function o(e){return["small","middle","large"].includes(e)}function l(e){return!!e&&"number"==typeof e&&!Number.isNaN(e)}e.s(["isPresetSize",()=>o,"isValidGapNumber",()=>l],908286);var i=e.i(242064),n=e.i(249616),s=e.i(372409),c=e.i(246422);let d=(0,c.genStyleHooks)(["Space","Addon"],e=>[(e=>{let{componentCls:t,borderRadius:r,paddingSM:a,colorBorder:o,paddingXS:l,fontSizeLG:i,fontSizeSM:n,borderRadiusLG:c,borderRadiusSM:d,colorBgContainerDisabled:p,lineWidth:g}=e;return{[t]:[{display:"inline-flex",alignItems:"center",gap:0,paddingInline:a,margin:0,background:p,borderWidth:g,borderStyle:"solid",borderColor:o,borderRadius:r,"&-large":{fontSize:i,borderRadius:c},"&-small":{paddingInline:l,borderRadius:d,fontSize:n},"&-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,s.genCompactItemStyle)(e,{focus:!1})]}})(e)]);var p=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,a=Object.getOwnPropertySymbols(e);ot.indexOf(a[o])&&Object.prototype.propertyIsEnumerable.call(e,a[o])&&(r[a[o]]=e[a[o]]);return r};let g=t.default.forwardRef((e,a)=>{let{className:o,children:l,style:s,prefixCls:c}=e,g=p(e,["className","children","style","prefixCls"]),{getPrefixCls:u,direction:m}=t.default.useContext(i.ConfigContext),A=u("space-addon",c),[f,b,v]=d(A),{compactItemClassnames:h,compactSize:I}=(0,n.useCompactItemContext)(A,m),C=(0,r.default)(A,b,h,v,{[`${A}-${I}`]:I},o);return f(t.default.createElement("div",Object.assign({ref:a,className:C,style:s},g),l))}),u=t.default.createContext({latestIndex:0}),m=u.Provider,A=({className:e,index:r,children:a,split:o,style:l})=>{let{latestIndex:i}=t.useContext(u);return null==a?null:t.createElement(t.Fragment,null,t.createElement("div",{className:e,style:l},a),r{let t=(0,f.mergeToken)(e,{spaceGapSmallSize:e.paddingXS,spaceGapMiddleSize:e.padding,spaceGapLargeSize:e.paddingLG});return[(e=>{let{componentCls:t,antCls:r}=e;return{[t]:{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"}},[`${t}-item:empty`]:{display:"none"},[`${t}-item > ${r}-badge-not-a-wrapper:only-child`]:{display:"block"}}}})(t),(e=>{let{componentCls:t}=e;return{[t]:{"&-gap-row-small":{rowGap:e.spaceGapSmallSize},"&-gap-row-middle":{rowGap:e.spaceGapMiddleSize},"&-gap-row-large":{rowGap:e.spaceGapLargeSize},"&-gap-col-small":{columnGap:e.spaceGapSmallSize},"&-gap-col-middle":{columnGap:e.spaceGapMiddleSize},"&-gap-col-large":{columnGap:e.spaceGapLargeSize}}}})(t)]},()=>({}),{resetStyle:!1});var v=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,a=Object.getOwnPropertySymbols(e);ot.indexOf(a[o])&&Object.prototype.propertyIsEnumerable.call(e,a[o])&&(r[a[o]]=e[a[o]]);return r};let h=t.forwardRef((e,n)=>{var s;let{getPrefixCls:c,direction:d,size:p,className:g,style:u,classNames:f,styles:h}=(0,i.useComponentConfig)("space"),{size:I=null!=p?p:"small",align:C,className:O,rootClassName:$,children:E,direction:y="horizontal",prefixCls:S,split:T,style:x,wrap:_=!1,classNames:k,styles:L}=e,w=v(e,["size","align","className","rootClassName","children","direction","prefixCls","split","style","wrap","classNames","styles"]),[M,N]=Array.isArray(I)?I:[I,I],R=o(N),P=o(M),z=l(N),B=l(M),G=(0,a.default)(E,{keepEmpty:!0}),D=void 0===C&&"horizontal"===y?"center":C,j=c("space",S),[H,V,F]=b(j),W=(0,r.default)(j,g,V,`${j}-${y}`,{[`${j}-rtl`]:"rtl"===d,[`${j}-align-${D}`]:D,[`${j}-gap-row-${N}`]:R,[`${j}-gap-col-${M}`]:P},O,$,F),U=(0,r.default)(`${j}-item`,null!=(s=null==k?void 0:k.item)?s:f.item),X=Object.assign(Object.assign({},h.item),null==L?void 0:L.item),K=G.map((e,r)=>{let a=(null==e?void 0:e.key)||`${U}-${r}`;return t.createElement(A,{className:U,key:a,index:r,split:T,style:X},e)}),q=t.useMemo(()=>({latestIndex:G.reduce((e,t,r)=>null!=t?r:e,0)}),[G]);if(0===G.length)return null;let Y={};return _&&(Y.flexWrap="wrap"),!P&&B&&(Y.columnGap=M),!R&&z&&(Y.rowGap=N),H(t.createElement("div",Object.assign({ref:n,className:W,style:Object.assign(Object.assign(Object.assign({},Y),u),x)},w),t.createElement(m,{value:q},K)))});h.Compact=n.default,h.Addon=g,e.s(["default",0,h],38243)},770914,e=>{"use strict";var t=e.i(38243);e.s(["Space",()=>t.default])},262218,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),a=e.i(529681),o=e.i(702779),l=e.i(563113),i=e.i(763731),n=e.i(121872),s=e.i(242064);e.i(296059);var c=e.i(915654);e.i(262370);var d=e.i(135551),p=e.i(183293),g=e.i(246422),u=e.i(838378);let m=e=>{let{lineWidth:t,fontSizeIcon:r,calc:a}=e,o=e.fontSizeSM;return(0,u.mergeToken)(e,{tagFontSize:o,tagLineHeight:(0,c.unit)(a(e.lineHeightSM).mul(o).equal()),tagIconSize:a(r).sub(a(t).mul(2)).equal(),tagPaddingHorizontal:8,tagBorderlessBg:e.defaultBg})},A=e=>({defaultBg:new d.FastColor(e.colorFillQuaternary).onBackground(e.colorBgContainer).toHexString(),defaultColor:e.colorText}),f=(0,g.genStyleHooks)("Tag",e=>(e=>{let{paddingXXS:t,lineWidth:r,tagPaddingHorizontal:a,componentCls:o,calc:l}=e,i=l(a).sub(r).equal(),n=l(t).sub(r).equal();return{[o]:Object.assign(Object.assign({},(0,p.resetComponent)(e)),{display:"inline-block",height:"auto",marginInlineEnd:e.marginXS,paddingInline:i,fontSize:e.tagFontSize,lineHeight:e.tagLineHeight,whiteSpace:"nowrap",background:e.defaultBg,border:`${(0,c.unit)(e.lineWidth)} ${e.lineType} ${e.colorBorder}`,borderRadius:e.borderRadiusSM,opacity:1,transition:`all ${e.motionDurationMid}`,textAlign:"start",position:"relative",[`&${o}-rtl`]:{direction:"rtl"},"&, a, a:hover":{color:e.defaultColor},[`${o}-close-icon`]:{marginInlineStart:n,fontSize:e.tagIconSize,color:e.colorIcon,cursor:"pointer",transition:`all ${e.motionDurationMid}`,"&:hover":{color:e.colorTextHeading}},[`&${o}-has-color`]:{borderColor:"transparent",[`&, a, a:hover, ${e.iconCls}-close, ${e.iconCls}-close:hover`]:{color:e.colorTextLightSolid}},"&-checkable":{backgroundColor:"transparent",borderColor:"transparent",cursor:"pointer",[`&:not(${o}-checkable-checked):hover`]:{color:e.colorPrimary,backgroundColor:e.colorFillSecondary},"&:active, &-checked":{color:e.colorTextLightSolid},"&-checked":{backgroundColor:e.colorPrimary,"&:hover":{backgroundColor:e.colorPrimaryHover}},"&:active":{backgroundColor:e.colorPrimaryActive}},"&-hidden":{display:"none"},[`> ${e.iconCls} + span, > span + ${e.iconCls}`]:{marginInlineStart:i}}),[`${o}-borderless`]:{borderColor:"transparent",background:e.tagBorderlessBg}}})(m(e)),A);var b=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,a=Object.getOwnPropertySymbols(e);ot.indexOf(a[o])&&Object.prototype.propertyIsEnumerable.call(e,a[o])&&(r[a[o]]=e[a[o]]);return r};let v=t.forwardRef((e,a)=>{let{prefixCls:o,style:l,className:i,checked:n,children:c,icon:d,onChange:p,onClick:g}=e,u=b(e,["prefixCls","style","className","checked","children","icon","onChange","onClick"]),{getPrefixCls:m,tag:A}=t.useContext(s.ConfigContext),v=m("tag",o),[h,I,C]=f(v),O=(0,r.default)(v,`${v}-checkable`,{[`${v}-checkable-checked`]:n},null==A?void 0:A.className,i,I,C);return h(t.createElement("span",Object.assign({},u,{ref:a,style:Object.assign(Object.assign({},l),null==A?void 0:A.style),className:O,onClick:e=>{null==p||p(!n),null==g||g(e)}}),d,t.createElement("span",null,c)))});var h=e.i(403541);let I=(0,g.genSubStyleComponent)(["Tag","preset"],e=>{let t;return t=m(e),(0,h.genPresetColor)(t,(e,{textColor:r,lightBorderColor:a,lightColor:o,darkColor:l})=>({[`${t.componentCls}${t.componentCls}-${e}`]:{color:r,background:o,borderColor:a,"&-inverse":{color:t.colorTextLightSolid,background:l,borderColor:l},[`&${t.componentCls}-borderless`]:{borderColor:"transparent"}}}))},A),C=(e,t,r)=>{let a="string"!=typeof r?r:r.charAt(0).toUpperCase()+r.slice(1);return{[`${e.componentCls}${e.componentCls}-${t}`]:{color:e[`color${r}`],background:e[`color${a}Bg`],borderColor:e[`color${a}Border`],[`&${e.componentCls}-borderless`]:{borderColor:"transparent"}}}},O=(0,g.genSubStyleComponent)(["Tag","status"],e=>{let t=m(e);return[C(t,"success","Success"),C(t,"processing","Info"),C(t,"error","Error"),C(t,"warning","Warning")]},A);var $=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,a=Object.getOwnPropertySymbols(e);ot.indexOf(a[o])&&Object.prototype.propertyIsEnumerable.call(e,a[o])&&(r[a[o]]=e[a[o]]);return r};let E=t.forwardRef((e,c)=>{let{prefixCls:d,className:p,rootClassName:g,style:u,children:m,icon:A,color:b,onClose:v,bordered:h=!0,visible:C}=e,E=$(e,["prefixCls","className","rootClassName","style","children","icon","color","onClose","bordered","visible"]),{getPrefixCls:y,direction:S,tag:T}=t.useContext(s.ConfigContext),[x,_]=t.useState(!0),k=(0,a.default)(E,["closeIcon","closable"]);t.useEffect(()=>{void 0!==C&&_(C)},[C]);let L=(0,o.isPresetColor)(b),w=(0,o.isPresetStatusColor)(b),M=L||w,N=Object.assign(Object.assign({backgroundColor:b&&!M?b:void 0},null==T?void 0:T.style),u),R=y("tag",d),[P,z,B]=f(R),G=(0,r.default)(R,null==T?void 0:T.className,{[`${R}-${b}`]:M,[`${R}-has-color`]:b&&!M,[`${R}-hidden`]:!x,[`${R}-rtl`]:"rtl"===S,[`${R}-borderless`]:!h},p,g,z,B),D=e=>{e.stopPropagation(),null==v||v(e),e.defaultPrevented||_(!1)},[,j]=(0,l.useClosable)((0,l.pickClosable)(e),(0,l.pickClosable)(T),{closable:!1,closeIconRender:e=>{let a=t.createElement("span",{className:`${R}-close-icon`,onClick:D},e);return(0,i.replaceElement)(e,a,e=>({onClick:t=>{var r;null==(r=null==e?void 0:e.onClick)||r.call(e,t),D(t)},className:(0,r.default)(null==e?void 0:e.className,`${R}-close-icon`)}))}}),H="function"==typeof E.onClick||m&&"a"===m.type,V=A||null,F=V?t.createElement(t.Fragment,null,V,m&&t.createElement("span",null,m)):m,W=t.createElement("span",Object.assign({},k,{ref:c,className:G,style:N}),F,j,L&&t.createElement(I,{key:"preset",prefixCls:R}),w&&t.createElement(O,{key:"status",prefixCls:R}));return P(H?t.createElement(n.default,{component:"Tag"},W):W)});E.CheckableTag=v,e.s(["Tag",0,E],262218)},801312,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M724 218.3V141c0-6.7-7.7-10.4-12.9-6.3L260.3 486.8a31.86 31.86 0 000 50.3l450.8 352.1c5.3 4.1 12.9.4 12.9-6.3v-77.3c0-4.9-2.3-9.6-6.1-12.6l-360-281 360-281.1c3.8-3 6.1-7.7 6.1-12.6z"}}]},name:"left",theme:"outlined"};var o=e.i(9583),l=r.forwardRef(function(e,l){return r.createElement(o.default,(0,t.default)({},e,{ref:l,icon:a}))});e.s(["default",0,l],801312)},475254,e=>{"use strict";var t=e.i(271645);let r=e=>{let t=e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,r)=>r?r.toUpperCase():t.toLowerCase());return t.charAt(0).toUpperCase()+t.slice(1)},a=(...e)=>e.filter((e,t,r)=>!!e&&""!==e.trim()&&r.indexOf(e)===t).join(" ").trim();var o={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 l=(0,t.forwardRef)(({color:e="currentColor",size:r=24,strokeWidth:l=2,absoluteStrokeWidth:i,className:n="",children:s,iconNode:c,...d},p)=>(0,t.createElement)("svg",{ref:p,...o,width:r,height:r,stroke:e,strokeWidth:i?24*Number(l)/Number(r):l,className:a("lucide",n),...!s&&!(e=>{for(let t in e)if(t.startsWith("aria-")||"role"===t||"title"===t)return!0})(d)&&{"aria-hidden":"true"},...d},[...c.map(([e,r])=>(0,t.createElement)(e,r)),...Array.isArray(s)?s:[s]])),i=(e,o)=>{let i=(0,t.forwardRef)(({className:i,...n},s)=>(0,t.createElement)(l,{ref:s,iconNode:o,className:a(`lucide-${r(e).replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,`lucide-${e}`,i),...n}));return i.displayName=r(e),i};e.s(["default",()=>i],475254)},312361,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),a=e.i(242064),o=e.i(517455);e.i(296059);var l=e.i(915654),i=e.i(183293),n=e.i(246422),s=e.i(838378);let c=(0,n.genStyleHooks)("Divider",e=>{let t=(0,s.mergeToken)(e,{dividerHorizontalWithTextGutterMargin:e.margin,sizePaddingEdgeHorizontal:0});return[(e=>{let{componentCls:t,sizePaddingEdgeHorizontal:r,colorSplit:a,lineWidth:o,textPaddingInline:n,orientationMargin:s,verticalMarginInline:c}=e;return{[t]:Object.assign(Object.assign({},(0,i.resetComponent)(e)),{borderBlockStart:`${(0,l.unit)(o)} solid ${a}`,"&-vertical":{position:"relative",top:"-0.06em",display:"inline-block",height:"0.9em",marginInline:c,marginBlock:0,verticalAlign:"middle",borderTop:0,borderInlineStart:`${(0,l.unit)(o)} solid ${a}`},"&-horizontal":{display:"flex",clear:"both",width:"100%",minWidth:"100%",margin:`${(0,l.unit)(e.marginLG)} 0`},[`&-horizontal${t}-with-text`]:{display:"flex",alignItems:"center",margin:`${(0,l.unit)(e.dividerHorizontalWithTextGutterMargin)} 0`,color:e.colorTextHeading,fontWeight:500,fontSize:e.fontSizeLG,whiteSpace:"nowrap",textAlign:"center",borderBlockStart:`0 ${a}`,"&::before, &::after":{position:"relative",width:"50%",borderBlockStart:`${(0,l.unit)(o)} solid transparent`,borderBlockStartColor:"inherit",borderBlockEnd:0,transform:"translateY(50%)",content:"''"}},[`&-horizontal${t}-with-text-start`]:{"&::before":{width:`calc(${s} * 100%)`},"&::after":{width:`calc(100% - ${s} * 100%)`}},[`&-horizontal${t}-with-text-end`]:{"&::before":{width:`calc(100% - ${s} * 100%)`},"&::after":{width:`calc(${s} * 100%)`}},[`${t}-inner-text`]:{display:"inline-block",paddingBlock:0,paddingInline:n},"&-dashed":{background:"none",borderColor:a,borderStyle:"dashed",borderWidth:`${(0,l.unit)(o)} 0 0`},[`&-horizontal${t}-with-text${t}-dashed`]:{"&::before, &::after":{borderStyle:"dashed none none"}},[`&-vertical${t}-dashed`]:{borderInlineStartWidth:o,borderInlineEnd:0,borderBlockStart:0,borderBlockEnd:0},"&-dotted":{background:"none",borderColor:a,borderStyle:"dotted",borderWidth:`${(0,l.unit)(o)} 0 0`},[`&-horizontal${t}-with-text${t}-dotted`]:{"&::before, &::after":{borderStyle:"dotted none none"}},[`&-vertical${t}-dotted`]:{borderInlineStartWidth:o,borderInlineEnd:0,borderBlockStart:0,borderBlockEnd:0},[`&-plain${t}-with-text`]:{color:e.colorText,fontWeight:"normal",fontSize:e.fontSize},[`&-horizontal${t}-with-text-start${t}-no-default-orientation-margin-start`]:{"&::before":{width:0},"&::after":{width:"100%"},[`${t}-inner-text`]:{paddingInlineStart:r}},[`&-horizontal${t}-with-text-end${t}-no-default-orientation-margin-end`]:{"&::before":{width:"100%"},"&::after":{width:0},[`${t}-inner-text`]:{paddingInlineEnd:r}}})}})(t),(e=>{let{componentCls:t}=e;return{[t]:{"&-horizontal":{[`&${t}`]:{"&-sm":{marginBlock:e.marginXS},"&-md":{marginBlock:e.margin}}}}}})(t)]},e=>({textPaddingInline:"1em",orientationMargin:.05,verticalMarginInline:e.marginXS}),{unitless:{orientationMargin:!0}});var d=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,a=Object.getOwnPropertySymbols(e);ot.indexOf(a[o])&&Object.prototype.propertyIsEnumerable.call(e,a[o])&&(r[a[o]]=e[a[o]]);return r};let p={small:"sm",middle:"md"};e.s(["Divider",0,e=>{let{getPrefixCls:l,direction:i,className:n,style:s}=(0,a.useComponentConfig)("divider"),{prefixCls:g,type:u="horizontal",orientation:m="center",orientationMargin:A,className:f,rootClassName:b,children:v,dashed:h,variant:I="solid",plain:C,style:O,size:$}=e,E=d(e,["prefixCls","type","orientation","orientationMargin","className","rootClassName","children","dashed","variant","plain","style","size"]),y=l("divider",g),[S,T,x]=c(y),_=p[(0,o.default)($)],k=!!v,L=t.useMemo(()=>"left"===m?"rtl"===i?"end":"start":"right"===m?"rtl"===i?"start":"end":m,[i,m]),w="start"===L&&null!=A,M="end"===L&&null!=A,N=(0,r.default)(y,n,T,x,`${y}-${u}`,{[`${y}-with-text`]:k,[`${y}-with-text-${L}`]:k,[`${y}-dashed`]:!!h,[`${y}-${I}`]:"solid"!==I,[`${y}-plain`]:!!C,[`${y}-rtl`]:"rtl"===i,[`${y}-no-default-orientation-margin-start`]:w,[`${y}-no-default-orientation-margin-end`]:M,[`${y}-${_}`]:!!_},f,b),R=t.useMemo(()=>"number"==typeof A?A:/^\d+$/.test(A)?Number(A):A,[A]);return S(t.createElement("div",Object.assign({className:N,style:Object.assign(Object.assign({},s),O)},E,{role:"separator"}),v&&"vertical"!==u&&t.createElement("span",{className:`${y}-inner-text`,style:{marginInlineStart:w?R:void 0,marginInlineEnd:M?R:void 0}},v)))}],312361)},653496,e=>{"use strict";var t=e.i(721369);e.s(["Tabs",()=>t.default])},56456,e=>{"use strict";var t=e.i(739295);e.s(["LoadingOutlined",()=>t.default])},771674,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M858.5 763.6a374 374 0 00-80.6-119.5 375.63 375.63 0 00-119.5-80.6c-.4-.2-.8-.3-1.2-.5C719.5 518 760 444.7 760 362c0-137-111-248-248-248S264 225 264 362c0 82.7 40.5 156 102.8 201.1-.4.2-.8.3-1.2.5-44.8 18.9-85 46-119.5 80.6a375.63 375.63 0 00-80.6 119.5A371.7 371.7 0 00136 901.8a8 8 0 008 8.2h60c4.4 0 7.9-3.5 8-7.8 2-77.2 33-149.5 87.8-204.3 56.7-56.7 132-87.9 212.2-87.9s155.5 31.2 212.2 87.9C779 752.7 810 825 812 902.2c.1 4.4 3.6 7.8 8 7.8h60a8 8 0 008-8.2c-1-47.8-10.9-94.3-29.5-138.2zM512 534c-45.9 0-89.1-17.9-121.6-50.4S340 407.9 340 362c0-45.9 17.9-89.1 50.4-121.6S466.1 190 512 190s89.1 17.9 121.6 50.4S684 316.1 684 362c0 45.9-17.9 89.1-50.4 121.6S557.9 534 512 534z"}}]},name:"user",theme:"outlined"};var o=e.i(9583),l=r.forwardRef(function(e,l){return r.createElement(o.default,(0,t.default)({},e,{ref:l,icon:a}))});e.s(["UserOutlined",0,l],771674)},755151,e=>{"use strict";var t=e.i(247153);e.s(["DownOutlined",()=>t.default])},916925,e=>{"use strict";var t,r=((t={}).A2A_Agent="A2A Agent",t.AI21="Ai21",t.AI21_CHAT="Ai21 Chat",t.AIML="AI/ML API",t.AIOHTTP_OPENAI="Aiohttp Openai",t.Anthropic="Anthropic",t.ANTHROPIC_TEXT="Anthropic Text",t.AssemblyAI="AssemblyAI",t.AUTO_ROUTER="Auto Router",t.Bedrock="Amazon Bedrock",t.BedrockMantle="Amazon Bedrock Mantle",t.SageMaker="AWS SageMaker",t.Azure="Azure",t.Azure_AI_Studio="Azure AI Foundry (Studio)",t.AZURE_TEXT="Azure Text",t.BASETEN="Baseten",t.BYTEZ="Bytez",t.Cerebras="Cerebras",t.CLARIFAI="Clarifai",t.CLOUDFLARE="Cloudflare",t.CODESTRAL="Codestral",t.Cohere="Cohere",t.COHERE_CHAT="Cohere Chat",t.COMETAPI="Cometapi",t.COMPACTIFAI="Compactifai",t.Cursor="Cursor",t.Dashscope="Dashscope",t.Databricks="Databricks (Qwen API)",t.DATAROBOT="Datarobot",t.DeepInfra="DeepInfra",t.Deepgram="Deepgram",t.Deepseek="Deepseek",t.DOCKER_MODEL_RUNNER="Docker Model Runner",t.DOTPROMPT="Dotprompt",t.ElevenLabs="ElevenLabs",t.EMPOWER="Empower",t.FalAI="Fal AI",t.FEATHERLESS_AI="Featherless Ai",t.FireworksAI="Fireworks AI",t.FRIENDLIAI="Friendliai",t.GALADRIEL="Galadriel",t.GITHUB_COPILOT="Github Copilot",t.Google_AI_Studio="Google AI Studio",t.GradientAI="GradientAI",t.Groq="Groq",t.HEROKU="Heroku",t.Hosted_Vllm="vllm",t.HUGGINGFACE="Huggingface",t.HYPERBOLIC="Hyperbolic",t.Infinity="Infinity",t.JinaAI="Jina AI",t.LAMBDA_AI="Lambda Ai",t.LEMONADE="Lemonade",t.LLAMAFILE="Llamafile",t.LM_STUDIO="Lm Studio",t.LLAMA="Meta Llama",t.MARITALK="Maritalk",t.MiniMax="MiniMax",t.MistralAI="Mistral AI",t.MOONSHOT="Moonshot",t.MORPH="Morph",t.NEBIUS="Nebius",t.NLP_CLOUD="Nlp Cloud",t.NOVITA="Novita",t.NSCALE="Nscale",t.NVIDIA_NIM="Nvidia Nim",t.Ollama="Ollama",t.OLLAMA_CHAT="Ollama Chat",t.OOBABOOGA="Oobabooga",t.OpenAI="OpenAI",t.OPENAI_LIKE="Openai Like",t.OpenAI_Compatible="OpenAI-Compatible Endpoints (Together AI, etc.)",t.OpenAI_Text="OpenAI Text Completion",t.OpenAI_Text_Compatible="OpenAI-Compatible Text Completion Models (Together AI, etc.)",t.Openrouter="Openrouter",t.Oracle="Oracle Cloud Infrastructure (OCI)",t.OVHCLOUD="Ovhcloud",t.Perplexity="Perplexity",t.PETALS="Petals",t.PG_VECTOR="Pg Vector",t.PREDIBASE="Predibase",t.RECRAFT="Recraft",t.REPLICATE="Replicate",t.RunwayML="RunwayML",t.SAGEMAKER_LEGACY="Sagemaker",t.Sambanova="Sambanova",t.SAP="SAP Generative AI Hub",t.Snowflake="Snowflake",t.TEXT_COMPLETION_CODESTRAL="Text-Completion-Codestral",t.TogetherAI="TogetherAI",t.TOPAZ="Topaz",t.Triton="Triton",t.V0="V0",t.VERCEL_AI_GATEWAY="Vercel Ai Gateway",t.Vertex_AI="Vertex AI (Anthropic, Gemini, etc.)",t.VERTEX_AI_BETA="Vertex Ai Beta",t.VLLM="Vllm",t.VolcEngine="VolcEngine",t.Voyage="Voyage AI",t.WANDB="Wandb",t.WATSONX="Watsonx",t.WATSONX_TEXT="Watsonx Text",t.xAI="xAI",t.XINFERENCE="Xinference",t);let a={A2A_Agent:"a2a_agent",AI21:"ai21",AI21_CHAT:"ai21_chat",AIML:"aiml",AIOHTTP_OPENAI:"aiohttp_openai",Anthropic:"anthropic",ANTHROPIC_TEXT:"anthropic_text",AssemblyAI:"assemblyai",AUTO_ROUTER:"auto_router",Azure:"azure",Azure_AI_Studio:"azure_ai",AZURE_TEXT:"azure_text",BASETEN:"baseten",Bedrock:"bedrock",BedrockMantle:"bedrock_mantle",BYTEZ:"bytez",Cerebras:"cerebras",CLARIFAI:"clarifai",CLOUDFLARE:"cloudflare",CODESTRAL:"codestral",Cohere:"cohere",COHERE_CHAT:"cohere_chat",COMETAPI:"cometapi",COMPACTIFAI:"compactifai",Cursor:"cursor",Dashscope:"dashscope",Databricks:"databricks",DATAROBOT:"datarobot",DeepInfra:"deepinfra",Deepgram:"deepgram",Deepseek:"deepseek",DOCKER_MODEL_RUNNER:"docker_model_runner",DOTPROMPT:"dotprompt",ElevenLabs:"elevenlabs",EMPOWER:"empower",FalAI:"fal_ai",FEATHERLESS_AI:"featherless_ai",FireworksAI:"fireworks_ai",FRIENDLIAI:"friendliai",GALADRIEL:"galadriel",GITHUB_COPILOT:"github_copilot",Google_AI_Studio:"gemini",GradientAI:"gradient_ai",Groq:"groq",HEROKU:"heroku",Hosted_Vllm:"hosted_vllm",HUGGINGFACE:"huggingface",HYPERBOLIC:"hyperbolic",Infinity:"infinity",JinaAI:"jina_ai",LAMBDA_AI:"lambda_ai",LEMONADE:"lemonade",LLAMAFILE:"llamafile",LLAMA:"meta_llama",LM_STUDIO:"lm_studio",MARITALK:"maritalk",MiniMax:"minimax",MistralAI:"mistral",MOONSHOT:"moonshot",MORPH:"morph",NEBIUS:"nebius",NLP_CLOUD:"nlp_cloud",NOVITA:"novita",NSCALE:"nscale",NVIDIA_NIM:"nvidia_nim",Ollama:"ollama",OLLAMA_CHAT:"ollama_chat",OOBABOOGA:"oobabooga",OpenAI:"openai",OPENAI_LIKE:"openai_like",OpenAI_Compatible:"openai",OpenAI_Text:"text-completion-openai",OpenAI_Text_Compatible:"text-completion-openai",Openrouter:"openrouter",Oracle:"oci",OVHCLOUD:"ovhcloud",Perplexity:"perplexity",PETALS:"petals",PG_VECTOR:"pg_vector",PREDIBASE:"predibase",RECRAFT:"recraft",REPLICATE:"replicate",RunwayML:"runwayml",SAGEMAKER_LEGACY:"sagemaker",SageMaker:"sagemaker_chat",Sambanova:"sambanova",SAP:"sap",Snowflake:"snowflake",TEXT_COMPLETION_CODESTRAL:"text-completion-codestral",TogetherAI:"together_ai",TOPAZ:"topaz",Triton:"triton",V0:"v0",VERCEL_AI_GATEWAY:"vercel_ai_gateway",Vertex_AI:"vertex_ai",VERTEX_AI_BETA:"vertex_ai_beta",VLLM:"vllm",VolcEngine:"volcengine",Voyage:"voyage",WANDB:"wandb",WATSONX:"watsonx",WATSONX_TEXT:"watsonx_text",xAI:"xai",XINFERENCE:"xinference"},o="../ui/assets/logos/",l={"A2A Agent":`${o}a2a_agent.png`,Ai21:`${o}ai21.svg`,"Ai21 Chat":`${o}ai21.svg`,"AI/ML API":`${o}aiml_api.svg`,"Aiohttp Openai":`${o}openai_small.svg`,Anthropic:`${o}anthropic.svg`,"Anthropic Text":`${o}anthropic.svg`,AssemblyAI:`${o}assemblyai_small.png`,Azure:`${o}microsoft_azure.svg`,"Azure AI Foundry (Studio)":`${o}microsoft_azure.svg`,"Azure Text":`${o}microsoft_azure.svg`,Baseten:`${o}baseten.svg`,"Amazon Bedrock":`${o}bedrock.svg`,"Amazon Bedrock Mantle":`${o}bedrock.svg`,"AWS SageMaker":`${o}bedrock.svg`,Cerebras:`${o}cerebras.svg`,Cloudflare:`${o}cloudflare.svg`,Codestral:`${o}mistral.svg`,Cohere:`${o}cohere.svg`,"Cohere Chat":`${o}cohere.svg`,Cometapi:`${o}cometapi.svg`,Cursor:`${o}cursor.svg`,"Databricks (Qwen API)":`${o}databricks.svg`,Dashscope:`${o}dashscope.svg`,Deepseek:`${o}deepseek.svg`,Deepgram:`${o}deepgram.png`,DeepInfra:`${o}deepinfra.png`,ElevenLabs:`${o}elevenlabs.png`,"Fal AI":`${o}fal_ai.jpg`,"Featherless Ai":`${o}featherless.svg`,"Fireworks AI":`${o}fireworks.svg`,Friendliai:`${o}friendli.svg`,"Github Copilot":`${o}github_copilot.svg`,"Google AI Studio":`${o}google.svg`,GradientAI:`${o}gradientai.svg`,Groq:`${o}groq.svg`,vllm:`${o}vllm.png`,Huggingface:`${o}huggingface.svg`,Hyperbolic:`${o}hyperbolic.svg`,Infinity:`${o}infinity.png`,"Jina AI":`${o}jina.png`,"Lambda Ai":`${o}lambda.svg`,"Lm Studio":`${o}lmstudio.svg`,"Meta Llama":`${o}meta_llama.svg`,MiniMax:`${o}minimax.svg`,"Mistral AI":`${o}mistral.svg`,Moonshot:`${o}moonshot.svg`,Morph:`${o}morph.svg`,Nebius:`${o}nebius.svg`,Novita:`${o}novita.svg`,"Nvidia Nim":`${o}nvidia_nim.svg`,Ollama:`${o}ollama.svg`,"Ollama Chat":`${o}ollama.svg`,Oobabooga:`${o}openai_small.svg`,OpenAI:`${o}openai_small.svg`,"Openai Like":`${o}openai_small.svg`,"OpenAI Text Completion":`${o}openai_small.svg`,"OpenAI-Compatible Text Completion Models (Together AI, etc.)":`${o}openai_small.svg`,"OpenAI-Compatible Endpoints (Together AI, etc.)":`${o}openai_small.svg`,Openrouter:`${o}openrouter.svg`,"Oracle Cloud Infrastructure (OCI)":`${o}oracle.svg`,Perplexity:`${o}perplexity-ai.svg`,Recraft:`${o}recraft.svg`,Replicate:`${o}replicate.svg`,RunwayML:`${o}runwayml.png`,Sagemaker:`${o}bedrock.svg`,Sambanova:`${o}sambanova.svg`,"SAP Generative AI Hub":`${o}sap.png`,Snowflake:`${o}snowflake.svg`,"Text-Completion-Codestral":`${o}mistral.svg`,TogetherAI:`${o}togetherai.svg`,Topaz:`${o}topaz.svg`,Triton:`${o}nvidia_triton.png`,V0:`${o}v0.svg`,"Vercel Ai Gateway":`${o}vercel.svg`,"Vertex AI (Anthropic, Gemini, etc.)":`${o}google.svg`,"Vertex Ai Beta":`${o}google.svg`,Vllm:`${o}vllm.png`,VolcEngine:`${o}volcengine.png`,"Voyage AI":`${o}voyage.webp`,Watsonx:`${o}watsonx.svg`,"Watsonx Text":`${o}watsonx.svg`,xAI:`${o}xai.svg`,Xinference:`${o}xinference.svg`};e.s(["Providers",()=>r,"getPlaceholder",0,e=>{if("AI/ML API"===e)return"aiml/flux-pro/v1.1";if("Vertex AI (Anthropic, Gemini, etc.)"===e)return"gemini-pro";if("Anthropic"==e)return"claude-3-opus";if("Amazon Bedrock"==e)return"claude-3-opus";if("AWS SageMaker"==e)return"sagemaker/jumpstart-dft-meta-textgeneration-llama-2-7b";else if("Google AI Studio"==e)return"gemini-pro";else if("Azure AI Foundry (Studio)"==e)return"azure_ai/command-r-plus";else if("Azure"==e)return"my-deployment";else if("Oracle Cloud Infrastructure (OCI)"==e)return"oci/xai.grok-4";else if("Snowflake"==e)return"snowflake/mistral-7b";else if("Voyage AI"==e)return"voyage/";else if("Jina AI"==e)return"jina_ai/";else if("VolcEngine"==e)return"volcengine/";else if("DeepInfra"==e)return"deepinfra/";else if("Fal AI"==e)return"fal_ai/fal-ai/flux-pro/v1.1-ultra";else if("RunwayML"==e)return"runwayml/gen4_turbo";else if("Watsonx"===e)return"watsonx/ibm/granite-3-3-8b-instruct";else if("Cursor"===e)return"cursor/claude-4-sonnet";else return"gpt-3.5-turbo"},"getProviderLogoAndName",0,e=>{if(!e)return{logo:"",displayName:"-"};if("gemini"===e.toLowerCase()){let e="Google AI Studio";return{logo:l[e],displayName:e}}let t=Object.keys(a).find(t=>a[t].toLowerCase()===e.toLowerCase());if(!t)return{logo:"",displayName:e};let o=r[t];return{logo:l[o],displayName:o}},"getProviderModels",0,(e,t)=>{console.log(`Provider key: ${e}`);let r=a[e];console.log(`Provider mapped to: ${r}`);let o=[];return e&&"object"==typeof t&&(Object.entries(t).forEach(([e,t])=>{if(null!==t&&"object"==typeof t&&"litellm_provider"in t){let a=t.litellm_provider;(a===r||"string"==typeof a&&a.includes(r))&&o.push(e)}}),"Cohere"==e&&(console.log("Adding cohere chat models"),Object.entries(t).forEach(([e,t])=>{null!==t&&"object"==typeof t&&"litellm_provider"in t&&"cohere_chat"===t.litellm_provider&&o.push(e)})),"AWS SageMaker"==e&&(console.log("Adding sagemaker chat models"),Object.entries(t).forEach(([e,t])=>{null!==t&&"object"==typeof t&&"litellm_provider"in t&&"sagemaker_chat"===t.litellm_provider&&o.push(e)}))),o},"providerLogoMap",0,l,"provider_map",0,a])}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/1f58814a2409d571.js b/litellm/proxy/_experimental/out/_next/static/chunks/1f58814a2409d571.js new file mode 100644 index 00000000000..cb25c33cb8d --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/1f58814a2409d571.js @@ -0,0 +1 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,213205,e=>{"use strict";e.i(247167);var s=e.i(931067),t=e.i(271645);let l={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M678.3 642.4c24.2-13 51.9-20.4 81.4-20.4h.1c3 0 4.4-3.6 2.2-5.6a371.67 371.67 0 00-103.7-65.8c-.4-.2-.8-.3-1.2-.5C719.2 505 759.6 431.7 759.6 349c0-137-110.8-248-247.5-248S264.7 212 264.7 349c0 82.7 40.4 156 102.6 201.1-.4.2-.8.3-1.2.5-44.7 18.9-84.8 46-119.3 80.6a373.42 373.42 0 00-80.4 119.5A373.6 373.6 0 00137 888.8a8 8 0 008 8.2h59.9c4.3 0 7.9-3.5 8-7.8 2-77.2 32.9-149.5 87.6-204.3C357 628.2 432.2 597 512.2 597c56.7 0 111.1 15.7 158 45.1a8.1 8.1 0 008.1.3zM512.2 521c-45.8 0-88.9-17.9-121.4-50.4A171.2 171.2 0 01340.5 349c0-45.9 17.9-89.1 50.3-121.6S466.3 177 512.2 177s88.9 17.9 121.4 50.4A171.2 171.2 0 01683.9 349c0 45.9-17.9 89.1-50.3 121.6C601.1 503.1 558 521 512.2 521zM880 759h-84v-84c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v84h-84c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h84v84c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8v-84h84c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8z"}}]},name:"user-add",theme:"outlined"};var a=e.i(9583),r=t.forwardRef(function(e,r){return t.createElement(a.default,(0,s.default)({},e,{ref:r,icon:l}))});e.s(["UserAddOutlined",0,r],213205)},355619,e=>{"use strict";var s=e.i(764205);let t=async(e,t,l)=>{try{if(null===e||null===t)return;if(null!==l){let a=(await (0,s.modelAvailableCall)(l,e,t,!0,null,!0)).data.map(e=>e.id),r=[],i=[];return a.forEach(e=>{e.endsWith("/*")?r.push(e):i.push(e)}),[...r,...i]}}catch(e){console.error("Error fetching user models:",e)}};e.s(["fetchAvailableModelsForTeamOrKey",0,t,"getModelDisplayName",0,e=>{if("all-proxy-models"===e)return"All Proxy Models";if(e.endsWith("/*")){let s=e.replace("/*","");return`All ${s} models`}return e},"unfurlWildcardModelsInList",0,(e,s)=>{let t=[],l=[];return console.log("teamModels",e),console.log("allModels",s),e.forEach(e=>{if(e.endsWith("/*")){let a=e.replace("/*",""),r=s.filter(e=>e.startsWith(a+"/"));l.push(...r),t.push(e)}else l.push(e)}),[...t,...l].filter((e,s,t)=>t.indexOf(e)===s)}])},860585,e=>{"use strict";var s=e.i(843476),t=e.i(199133);let{Option:l}=t.Select;e.s(["default",0,({value:e,onChange:a,className:r="",style:i={}})=>(0,s.jsxs)(t.Select,{style:{width:"100%",...i},value:e||void 0,onChange:a,className:r,placeholder:"n/a",allowClear:!0,children:[(0,s.jsx)(l,{value:"24h",children:"daily"}),(0,s.jsx)(l,{value:"7d",children:"weekly"}),(0,s.jsx)(l,{value:"30d",children:"monthly"})]}),"getBudgetDurationLabel",0,e=>e?({"24h":"daily","7d":"weekly","30d":"monthly"})[e]||e:"Not set"])},663435,e=>{"use strict";var s=e.i(843476),t=e.i(199133);e.s(["default",0,({teams:e,value:l,onChange:a,disabled:r,loading:i})=>(0,s.jsx)(t.Select,{showSearch:!0,placeholder:"Search or select a team",value:l,onChange:a,disabled:r,loading:i,allowClear:!0,filterOption:(s,t)=>{if(!t)return!1;let l=e?.find(e=>e.team_id===t.key);if(!l)return!1;let a=s.toLowerCase().trim(),r=(l.team_alias||"").toLowerCase(),i=(l.team_id||"").toLowerCase();return r.includes(a)||i.includes(a)},optionFilterProp:"children",children:e?.map(e=>(0,s.jsxs)(t.Select.Option,{value:e.team_id,children:[(0,s.jsx)("span",{className:"font-medium",children:e.team_alias})," ",(0,s.jsxs)("span",{className:"text-gray-500",children:["(",e.team_id,")"]})]},e.team_id))})])},285027,e=>{"use strict";e.i(247167);var s=e.i(931067),t=e.i(271645);let l={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"};var a=e.i(9583),r=t.forwardRef(function(e,r){return t.createElement(a.default,(0,s.default)({},e,{ref:r,icon:l}))});e.s(["WarningOutlined",0,r],285027)},447082,e=>{"use strict";var s=e.i(843476),t=e.i(271645),l=e.i(599724),a=e.i(464571),r=e.i(212931),i=e.i(291542),n=e.i(515831),d=e.i(898586),o=e.i(519756),c=e.i(737434),m=e.i(285027),u=e.i(993914),x=e.i(955135);e.i(247167);var h=e.i(931067);let p={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"};var f=e.i(9583),g=t.forwardRef(function(e,s){return t.createElement(f.default,(0,h.default)({},e,{ref:s,icon:p}))}),j=e.i(764205),y=e.i(59935),v=e.i(220508),b=e.i(964306);let w=t.forwardRef(function(e,s){return t.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:s},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"}))});var N=e.i(237016),_=e.i(727749);e.s(["default",0,({accessToken:e,teams:h,possibleUIRoles:p,onUsersCreated:f})=>{let[C,S]=(0,t.useState)(!1),[k,I]=(0,t.useState)([]),[T,U]=(0,t.useState)(!1),[V,O]=(0,t.useState)(null),[B,L]=(0,t.useState)(null),[M,F]=(0,t.useState)(null),[z,E]=(0,t.useState)(null),[P,A]=(0,t.useState)(null),[R,D]=(0,t.useState)("http://localhost:4000");(0,t.useEffect)(()=>{(async()=>{try{let s=await (0,j.getProxyUISettings)(e);A(s)}catch(e){console.error("Error fetching UI settings:",e)}})(),D(new URL("/",window.location.href).toString())},[e]);let $=async()=>{U(!0);let s=k.map(e=>({...e,status:"pending"}));I(s);let t=!1;for(let l=0;le.trim()).filter(Boolean),0===s.teams.length&&delete s.teams),a.models&&"string"==typeof a.models&&""!==a.models.trim()&&(s.models=a.models.split(",").map(e=>e.trim()).filter(Boolean),0===s.models.length&&delete s.models),a.max_budget&&""!==a.max_budget.toString().trim()){let e=parseFloat(a.max_budget.toString());!isNaN(e)&&e>0&&(s.max_budget=e)}a.budget_duration&&""!==a.budget_duration.trim()&&(s.budget_duration=a.budget_duration.trim()),a.metadata&&"string"==typeof a.metadata&&""!==a.metadata.trim()&&(s.metadata=a.metadata.trim()),console.log("Sending user data:",s);let r=await (0,j.userCreateCall)(e,null,s);if(console.log("Full response:",r),r&&(r.key||r.user_id)){t=!0,console.log("Success case triggered");let s=r.data?.user_id||r.user_id;try{if(P?.SSO_ENABLED){let e=new URL("/ui",R).toString();I(s=>s.map((s,t)=>t===l?{...s,status:"success",key:r.key||r.user_id,invitation_link:e}:s))}else{let t=await (0,j.invitationCreateCall)(e,s),a=new URL(`/ui?invitation_id=${t.id}`,R).toString();I(e=>e.map((e,s)=>s===l?{...e,status:"success",key:r.key||r.user_id,invitation_link:a}:e))}}catch(e){console.error("Error creating invitation:",e),I(e=>e.map((e,s)=>s===l?{...e,status:"success",key:r.key||r.user_id,error:"User created but failed to generate invitation link"}:e))}}else{console.log("Error case triggered");let e=r?.error||"Failed to create user";console.log("Error message:",e),I(s=>s.map((s,t)=>t===l?{...s,status:"failed",error:e}:s))}}catch(s){console.error("Caught error:",s);let e=s?.response?.data?.error||s?.message||String(s);I(s=>s.map((s,t)=>t===l?{...s,status:"failed",error:e}:s))}}U(!1),t&&f&&f()},W=[{title:"Row",dataIndex:"rowNumber",key:"rowNumber",width:80},{title:"Email",dataIndex:"user_email",key:"user_email"},{title:"Role",dataIndex:"user_role",key:"user_role"},{title:"Teams",dataIndex:"teams",key:"teams"},{title:"Budget",dataIndex:"max_budget",key:"max_budget"},{title:"Status",key:"status",render:(e,t)=>t.isValid?t.status&&"pending"!==t.status?"success"===t.status?(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(v.CheckCircleIcon,{className:"h-5 w-5 text-green-500 mr-2"}),(0,s.jsx)("span",{className:"text-green-500",children:"Success"})]}),t.invitation_link&&(0,s.jsx)("div",{className:"mt-1",children:(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)("span",{className:"text-xs text-gray-500 truncate max-w-[150px]",children:t.invitation_link}),(0,s.jsx)(N.CopyToClipboard,{text:t.invitation_link,onCopy:()=>_.default.success("Invitation link copied!"),children:(0,s.jsx)("button",{className:"ml-1 text-blue-500 text-xs hover:text-blue-700",children:"Copy"})})]})})]}):(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(b.XCircleIcon,{className:"h-5 w-5 text-red-500 mr-2"}),(0,s.jsx)("span",{className:"text-red-500",children:"Failed"})]}),t.error&&(0,s.jsx)("span",{className:"text-sm text-red-500 ml-7",children:JSON.stringify(t.error)})]}):(0,s.jsx)("span",{className:"text-gray-500",children:"Pending"}):(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(b.XCircleIcon,{className:"h-5 w-5 text-red-500 mr-2"}),(0,s.jsx)("span",{className:"text-red-500",children:"Invalid"})]}),t.error&&(0,s.jsx)("span",{className:"text-sm text-red-500 ml-7",children:t.error})]})}];return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(a.Button,{type:"primary",className:"mb-0",onClick:()=>S(!0),children:"+ Bulk Invite Users"}),(0,s.jsx)(r.Modal,{title:"Bulk Invite Users",open:C,width:800,onCancel:()=>S(!1),bodyStyle:{maxHeight:"70vh",overflow:"auto"},footer:null,children:(0,s.jsx)("div",{className:"flex flex-col",children:0===k.length?(0,s.jsxs)("div",{className:"mb-6",children:[(0,s.jsxs)("div",{className:"flex items-center mb-4",children:[(0,s.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"1"}),(0,s.jsx)("h3",{className:"text-lg font-medium",children:"Download and fill the template"})]}),(0,s.jsxs)("div",{className:"ml-11 mb-6",children:[(0,s.jsx)("p",{className:"mb-4",children:"Add multiple users at once by following these steps:"}),(0,s.jsxs)("ol",{className:"list-decimal list-inside space-y-2 ml-2 mb-4",children:[(0,s.jsx)("li",{children:"Download our CSV template"}),(0,s.jsx)("li",{children:"Add your users' information to the spreadsheet"}),(0,s.jsx)("li",{children:"Save the file and upload it here"}),(0,s.jsx)("li",{children:"After creation, download the results file containing the Virtual Keys for each user"})]}),(0,s.jsxs)("div",{className:"bg-gray-50 p-4 rounded-md border border-gray-200 mb-4",children:[(0,s.jsx)("h4",{className:"font-medium mb-2",children:"Template Column Names"}),(0,s.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-red-500 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"user_email"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:"User's email address (required)"})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-red-500 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"user_role"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'User\'s role (one of: "proxy_admin", "proxy_admin_viewer", "internal_user", "internal_user_viewer")'})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"teams"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'Comma-separated team IDs (e.g., "team-1,team-2")'})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"max_budget"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'Maximum budget as a number (e.g., "100")'})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"budget_duration"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'Budget reset period (e.g., "30d", "1mo")'})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"models"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'Comma-separated allowed models (e.g., "gpt-3.5-turbo,gpt-4")'})]})]})]})]}),(0,s.jsx)(a.Button,{type:"primary",size:"large",className:"w-full md:w-auto",icon:(0,s.jsx)(c.DownloadOutlined,{}),children:"Download CSV Template"})]}),(0,s.jsxs)("div",{className:"flex items-center mb-4",children:[(0,s.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"2"}),(0,s.jsx)("h3",{className:"text-lg font-medium",children:"Upload your completed CSV"})]}),(0,s.jsxs)("div",{className:"ml-11",children:[z?(0,s.jsxs)("div",{className:`mb-4 p-4 rounded-md border ${M?"bg-red-50 border-red-200":"bg-blue-50 border-blue-200"}`,children:[(0,s.jsxs)("div",{className:"flex items-center justify-between",children:[(0,s.jsxs)("div",{className:"flex items-center",children:[M?(0,s.jsx)(g,{className:"text-red-500 text-xl mr-3"}):(0,s.jsx)(u.FileTextOutlined,{className:"text-blue-500 text-xl mr-3"}),(0,s.jsxs)("div",{children:[(0,s.jsx)(d.Typography.Text,{strong:!0,className:M?"text-red-800":"text-blue-800",children:z.name}),(0,s.jsxs)(d.Typography.Text,{className:`block text-xs ${M?"text-red-600":"text-blue-600"}`,children:[(z.size/1024).toFixed(1)," KB • ",new Date().toLocaleDateString()]})]})]}),(0,s.jsx)(a.Button,{size:"small",onClick:()=>{E(null),I([]),O(null),L(null),F(null)},className:"flex items-center",icon:(0,s.jsx)(x.DeleteOutlined,{}),children:"Remove"})]}),M?(0,s.jsxs)("div",{className:"mt-3 text-red-600 text-sm flex items-start",children:[(0,s.jsx)(m.WarningOutlined,{className:"mr-2 mt-0.5"}),(0,s.jsx)("span",{children:M})]}):!B&&(0,s.jsxs)("div",{className:"mt-3 flex items-center",children:[(0,s.jsx)("div",{className:"w-full bg-gray-200 rounded-full h-1.5",children:(0,s.jsx)("div",{className:"bg-blue-500 h-1.5 rounded-full w-full animate-pulse"})}),(0,s.jsx)("span",{className:"ml-2 text-xs text-blue-600",children:"Processing..."})]})]}):(0,s.jsx)(n.Upload,{beforeUpload:e=>((O(null),L(null),F(null),E(e),"text/csv"===e.type||e.name.endsWith(".csv"))?e.size>5242880?F(`File is too large (${(e.size/1048576).toFixed(1)} MB). Please upload a CSV file smaller than 5MB.`):y.default.parse(e,{complete:e=>{if(!e.data||0===e.data.length){L("The CSV file appears to be empty. Please upload a file with data."),I([]);return}if(1===e.data.length){L("The CSV file only contains headers but no user data. Please add user data to your CSV."),I([]);return}let s=e.data[0];if(0===s.length||1===s.length&&""===s[0]){L("The CSV file doesn't contain any column headers. Please make sure your CSV has headers."),I([]);return}let t=["user_email","user_role"].filter(e=>!s.includes(e));if(t.length>0){L(`Your CSV is missing these required columns: ${t.join(", ")}. Please add these columns to your CSV file.`),I([]);return}try{let t=e.data.slice(1).map((e,t)=>{if(0===e.length||1===e.length&&""===e[0])return null;if(e.length=parseFloat(l.max_budget.toString())&&a.push("Max budget must be greater than 0")),l.budget_duration&&!l.budget_duration.match(/^\d+[dhmwy]$|^\d+mo$/)&&a.push(`Invalid budget duration format "${l.budget_duration}". Use format like "30d", "1mo", "2w", "6h"`),l.teams&&"string"==typeof l.teams&&h&&h.length>0){let e=h.map(e=>e.team_id),s=l.teams.split(",").map(e=>e.trim()).filter(s=>!e.includes(s));s.length>0&&a.push(`Unknown team(s): ${s.join(", ")}`)}return a.length>0&&(l.isValid=!1,l.error=a.join(", ")),l}).filter(Boolean),l=t.filter(e=>e.isValid);I(t),0===t.length?L("No valid data rows found in the CSV file. Please check your file format."):0===l.length?O("No valid users found in the CSV. Please check the errors below and fix your CSV file."):l.length{O(`Failed to parse CSV file: ${e.message}`),I([])},header:!1}):(F(`Invalid file type: ${e.name}. Please upload a CSV file (.csv extension).`),_.default.fromBackend("Invalid file type. Please upload a CSV file.")),!1),accept:".csv",maxCount:1,showUploadList:!1,children:(0,s.jsxs)("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-blue-500 transition-colors cursor-pointer",children:[(0,s.jsx)(o.UploadOutlined,{className:"text-3xl text-gray-400 mb-2"}),(0,s.jsx)("p",{className:"mb-1",children:"Drag and drop your CSV file here"}),(0,s.jsx)("p",{className:"text-sm text-gray-500 mb-3",children:"or"}),(0,s.jsx)(a.Button,{size:"small",children:"Browse files"}),(0,s.jsx)("p",{className:"text-xs text-gray-500 mt-4",children:"Only CSV files (.csv) are supported"})]})}),B&&(0,s.jsx)("div",{className:"mb-4 p-4 bg-yellow-50 border border-yellow-200 rounded-md",children:(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)(w,{className:"h-5 w-5 text-yellow-500 mr-2 mt-0.5"}),(0,s.jsxs)("div",{children:[(0,s.jsx)(d.Typography.Text,{strong:!0,className:"text-yellow-800",children:"CSV Structure Error"}),(0,s.jsx)(d.Typography.Paragraph,{className:"text-yellow-700 mt-1 mb-0",children:B}),(0,s.jsx)(d.Typography.Paragraph,{className:"text-yellow-700 mt-2 mb-0",children:"Please download our template and ensure your CSV follows the required format."})]})]})})]})]}):(0,s.jsxs)("div",{className:"mb-6",children:[(0,s.jsxs)("div",{className:"flex items-center mb-4",children:[(0,s.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"3"}),(0,s.jsx)("h3",{className:"text-lg font-medium",children:k.some(e=>"success"===e.status||"failed"===e.status)?"User Creation Results":"Review and create users"})]}),V&&(0,s.jsx)("div",{className:"ml-11 mb-4 p-4 bg-red-50 border border-red-200 rounded-md",children:(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)(m.WarningOutlined,{className:"text-red-500 mr-2 mt-1"}),(0,s.jsxs)("div",{children:[(0,s.jsx)(l.Text,{className:"text-red-600 font-medium",children:V}),k.some(e=>!e.isValid)&&(0,s.jsxs)("ul",{className:"mt-2 list-disc list-inside text-red-600 text-sm",children:[(0,s.jsx)("li",{children:"Check the table below for specific errors in each row"}),(0,s.jsx)("li",{children:"Common issues include invalid email formats, missing required fields, or incorrect role values"}),(0,s.jsx)("li",{children:"Fix these issues in your CSV file and upload again"})]})]})]})}),(0,s.jsxs)("div",{className:"ml-11",children:[(0,s.jsxs)("div",{className:"flex justify-between items-center mb-3",children:[(0,s.jsx)("div",{className:"flex items-center",children:k.some(e=>"success"===e.status||"failed"===e.status)?(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(l.Text,{className:"text-lg font-medium mr-3",children:"Creation Summary"}),(0,s.jsxs)(l.Text,{className:"text-sm bg-green-100 text-green-800 px-2 py-1 rounded mr-2",children:[k.filter(e=>"success"===e.status).length," Successful"]}),k.some(e=>"failed"===e.status)&&(0,s.jsxs)(l.Text,{className:"text-sm bg-red-100 text-red-800 px-2 py-1 rounded",children:[k.filter(e=>"failed"===e.status).length," Failed"]})]}):(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(l.Text,{className:"text-lg font-medium mr-3",children:"User Preview"}),(0,s.jsxs)(l.Text,{className:"text-sm bg-blue-100 text-blue-800 px-2 py-1 rounded",children:[k.filter(e=>e.isValid).length," of ",k.length," users valid"]})]})}),!k.some(e=>"success"===e.status||"failed"===e.status)&&(0,s.jsxs)("div",{className:"flex space-x-3",children:[(0,s.jsx)(a.Button,{onClick:()=>{I([]),O(null)},children:"Back"}),(0,s.jsx)(a.Button,{type:"primary",onClick:$,disabled:0===k.filter(e=>e.isValid).length||T,children:T?"Creating...":`Create ${k.filter(e=>e.isValid).length} Users`})]})]}),k.some(e=>"success"===e.status)&&(0,s.jsx)("div",{className:"mb-4 p-4 bg-blue-50 border border-blue-200 rounded-md",children:(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"mr-3 mt-1",children:(0,s.jsx)(v.CheckCircleIcon,{className:"h-5 w-5 text-blue-500"})}),(0,s.jsxs)("div",{children:[(0,s.jsx)(l.Text,{className:"font-medium text-blue-800",children:"User creation complete"}),(0,s.jsxs)(l.Text,{className:"block text-sm text-blue-700 mt-1",children:[(0,s.jsx)("span",{className:"font-medium",children:"Next step:"})," Download the credentials file containing Virtual Keys and invitation links. Users will need these Virtual Keys to make LLM requests through LiteLLM."]})]})]})}),(0,s.jsx)(i.Table,{dataSource:k,columns:W,size:"small",pagination:{pageSize:5},scroll:{y:300},rowClassName:e=>e.isValid?"":"bg-red-50"}),!k.some(e=>"success"===e.status||"failed"===e.status)&&(0,s.jsxs)("div",{className:"flex justify-end mt-4",children:[(0,s.jsx)(a.Button,{onClick:()=>{I([]),O(null)},className:"mr-3",children:"Back"}),(0,s.jsx)(a.Button,{type:"primary",onClick:$,disabled:0===k.filter(e=>e.isValid).length||T,children:T?"Creating...":`Create ${k.filter(e=>e.isValid).length} Users`})]}),k.some(e=>"success"===e.status||"failed"===e.status)&&(0,s.jsxs)("div",{className:"flex justify-end mt-4",children:[(0,s.jsx)(a.Button,{onClick:()=>{I([]),O(null)},className:"mr-3",children:"Start New Bulk Import"}),(0,s.jsx)(a.Button,{type:"primary",onClick:()=>{let e=k.map(e=>({user_email:e.user_email,user_role:e.user_role,status:e.status,key:e.key||"",invitation_link:e.invitation_link||"",error:e.error||""})),s=new Blob([y.default.unparse(e)],{type:"text/csv"}),t=window.URL.createObjectURL(s),l=document.createElement("a");l.href=t,l.download="bulk_users_results.csv",document.body.appendChild(l),l.click(),document.body.removeChild(l),window.URL.revokeObjectURL(t)},icon:(0,s.jsx)(c.DownloadOutlined,{}),children:"Download User Credentials"})]})]})]})})})]})}],447082)},371455,172372,e=>{"use strict";var s=e.i(843476),t=e.i(827252),l=e.i(213205),a=e.i(912598),r=e.i(109799),i=e.i(677667),n=e.i(130643),d=e.i(898667),o=e.i(35983),c=e.i(779241),m=e.i(560445),u=e.i(464571),x=e.i(808613),h=e.i(311451),p=e.i(212931),f=e.i(199133),g=e.i(770914),j=e.i(592968),y=e.i(898586),v=e.i(271645),b=e.i(447082),w=e.i(663435),N=e.i(355619),_=e.i(727749),C=e.i(764205),S=e.i(237016),k=e.i(599724);function I({isInvitationLinkModalVisible:e,setIsInvitationLinkModalVisible:t,baseUrl:l,invitationLinkData:a,modalType:r="invitation"}){let{Title:i,Paragraph:n}=y.Typography,d=()=>{if(!l)return"";let e=new URL(l).pathname,s=e&&"/"!==e?`${e}/ui`:"ui";if(a?.has_user_setup_sso)return new URL(s,l).toString();let t=`${s}?invitation_id=${a?.id}`;return"resetPassword"===r&&(t+="&action=reset_password"),new URL(t,l).toString()};return(0,s.jsxs)(p.Modal,{title:"invitation"===r?"Invitation Link":"Reset Password Link",open:e,width:800,footer:null,onOk:()=>{t(!1)},onCancel:()=>{t(!1)},children:[(0,s.jsx)(n,{children:"invitation"===r?"Copy and send the generated link to onboard this user to the proxy.":"Copy and send the generated link to the user to reset their password."}),(0,s.jsxs)("div",{className:"flex justify-between pt-5 pb-2",children:[(0,s.jsx)(k.Text,{className:"text-base",children:"User ID"}),(0,s.jsx)(k.Text,{children:a?.user_id})]}),(0,s.jsxs)("div",{className:"flex justify-between pt-5 pb-2",children:[(0,s.jsx)(k.Text,{children:"invitation"===r?"Invitation Link":"Reset Password Link"}),(0,s.jsx)(k.Text,{children:(0,s.jsx)(k.Text,{children:d()})})]}),(0,s.jsx)("div",{className:"flex justify-end mt-5",children:(0,s.jsx)(S.CopyToClipboard,{text:d(),onCopy:()=>_.default.success("Copied!"),children:(0,s.jsx)(u.Button,{type:"primary",children:"invitation"===r?"Copy invitation link":"Copy password reset link"})})})]})}e.s(["default",()=>I],172372);let{Option:T}=f.Select,{Text:U,Link:V,Title:O}=y.Typography;e.s(["CreateUserButton",0,({userID:e,accessToken:y,teams:S,possibleUIRoles:k,onUserCreated:O,isEmbedded:B=!1})=>{let L=(0,a.useQueryClient)(),[M,F]=(0,v.useState)(null),[z]=x.Form.useForm(),[E,P]=(0,v.useState)(!1),[A,R]=(0,v.useState)(!1),[D,$]=(0,v.useState)([]),[W,K]=(0,v.useState)(!1),[q,H]=(0,v.useState)(null),[G,J]=(0,v.useState)(null),{data:Q=[]}=(0,r.useOrganizations)(),X=(0,v.useMemo)(()=>{let e=Q.flatMap(e=>e.teams||[]);return e.length>0?e:S||[]},[Q,S]);(0,v.useEffect)(()=>{let s=async()=>{try{let s=await (0,C.modelAvailableCall)(y,e,"any"),t=[];for(let e=0;e{try{_.default.info("Making API Call"),B||P(!0),s.models&&0!==s.models.length||"proxy_admin"===s.user_role||(s.models=["no-default-models"]),s.organization_ids&&(s.organizations=s.organization_ids,delete s.organization_ids);let t=await (0,C.userCreateCall)(y,null,s);await L.invalidateQueries({queryKey:["userList"]}),R(!0);let l=t.data?.user_id||t.user_id;if(O&&B){O(l),z.resetFields();return}if(M?.SSO_ENABLED){let s={id:"u">typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){let s=16*Math.random()|0;return("x"==e?s:3&s|8).toString(16)}),user_id:l,is_accepted:!1,accepted_at:null,expires_at:new Date(Date.now()+6048e5),created_at:new Date,created_by:e,updated_at:new Date,updated_by:e,has_user_setup_sso:!0};H(s),K(!0)}else(0,C.invitationCreateCall)(y,l).then(e=>{e.has_user_setup_sso=!1,H(e),K(!0)});_.default.success("API user Created"),z.resetFields(),localStorage.removeItem("userData"+e)}catch(s){let e=s.response?.data?.detail||s?.message||"Error creating the user";_.default.fromBackend(e),console.error("Error creating the user:",s)}};return B?(0,s.jsxs)(x.Form,{form:z,onFinish:Y,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,s.jsx)(m.Alert,{message:"Email invitations",description:(0,s.jsxs)(s.Fragment,{children:["New users receive an email invite only when an email integration (SMTP, Resend, or SendGrid) is configured."," ",(0,s.jsx)(V,{href:"https://docs.litellm.ai/docs/proxy/email",target:"_blank",children:"Learn how to set up email notifications"})]}),type:"info",showIcon:!0,className:"mb-4"}),(0,s.jsx)(x.Form.Item,{label:"User Email",name:"user_email",children:(0,s.jsx)(c.TextInput,{placeholder:""})}),(0,s.jsx)(x.Form.Item,{label:"User Role",name:"user_role",children:(0,s.jsx)(f.Select,{children:k&&Object.entries(k).map(([e,{ui_label:t,description:l}])=>(0,s.jsx)(o.SelectItem,{value:e,title:t,children:(0,s.jsxs)("div",{className:"flex",children:[t," ",(0,s.jsx)(U,{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:l})]})},e))})}),(0,s.jsx)(x.Form.Item,{label:"Team",name:"team_id",children:(0,s.jsx)(f.Select,{placeholder:"Select Team",style:{width:"100%"},children:(0,s.jsx)(w.default,{teams:X})})}),(0,s.jsx)(x.Form.Item,{label:"Metadata",name:"metadata",children:(0,s.jsx)(h.Input.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,s.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,s.jsx)(u.Button,{htmlType:"submit",children:"Create User"})})]}):(0,s.jsxs)("div",{className:"flex gap-2",children:[(0,s.jsx)(u.Button,{type:"primary",className:"mb-0",onClick:()=>P(!0),children:"+ Invite User"}),(0,s.jsx)(b.default,{accessToken:y,teams:S,possibleUIRoles:k}),(0,s.jsxs)(p.Modal,{title:"Invite User",open:E,width:800,footer:null,onOk:()=>{P(!1),z.resetFields()},onCancel:()=>{P(!1),R(!1),z.resetFields()},children:[(0,s.jsxs)(g.Space,{direction:"vertical",size:"middle",children:[(0,s.jsx)(U,{className:"mb-1",children:"Create a User who can own keys"}),(0,s.jsx)(m.Alert,{message:"Email invitations",description:(0,s.jsxs)(s.Fragment,{children:["New users receive an email invite only when an email integration (SMTP, Resend, or SendGrid) is configured."," ",(0,s.jsx)(V,{href:"https://docs.litellm.ai/docs/proxy/email",target:"_blank",children:"Learn how to set up email notifications"})]}),type:"info",showIcon:!0,className:"mb-4"})]}),(0,s.jsxs)(x.Form,{form:z,onFinish:Y,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,s.jsx)(x.Form.Item,{label:"User Email",name:"user_email",children:(0,s.jsx)(h.Input,{})}),(0,s.jsx)(x.Form.Item,{label:(0,s.jsxs)("span",{children:["Global Proxy Role"," ",(0,s.jsx)(j.Tooltip,{title:"This role is independent of any team/org specific roles. Configure Team / Organization Admins in the Settings",children:(0,s.jsx)(t.InfoCircleOutlined,{})})]}),name:"user_role",children:(0,s.jsx)(f.Select,{children:k&&Object.entries(k).map(([e,{ui_label:t,description:l}])=>(0,s.jsxs)(o.SelectItem,{value:e,title:t,children:[(0,s.jsx)(U,{children:t}),(0,s.jsxs)(U,{type:"secondary",children:[" - ",l]})]},e))})}),(0,s.jsx)(x.Form.Item,{label:"Team",className:"gap-2",name:"team_id",help:"If selected, user will be added as a 'user' role to the team.",children:(0,s.jsx)(w.default,{teams:X})}),(0,s.jsx)(x.Form.Item,{label:"Organization",name:"organization_ids",help:"The user will be added to the selected organization(s).",children:(0,s.jsx)(f.Select,{mode:"multiple",placeholder:"Select Organization",style:{width:"100%"},children:Q.map(e=>(0,s.jsxs)(T,{value:e.organization_id,children:[e.organization_alias," (",e.organization_id,")"]},e.organization_id))})}),(0,s.jsx)(x.Form.Item,{label:"Metadata",name:"metadata",children:(0,s.jsx)(h.Input.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,s.jsxs)(i.Accordion,{children:[(0,s.jsx)(d.AccordionHeader,{children:(0,s.jsx)(U,{strong:!0,children:"Personal Key Creation"})}),(0,s.jsx)(n.AccordionBody,{children:(0,s.jsx)(x.Form.Item,{className:"gap-2",label:(0,s.jsxs)("span",{children:["Models"," ",(0,s.jsx)(j.Tooltip,{title:"Models user has access to, outside of team scope.",children:(0,s.jsx)(t.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"models",help:"Models user has access to, outside of team scope.",children:(0,s.jsxs)(f.Select,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[(0,s.jsx)(f.Select.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),(0,s.jsx)(f.Select.Option,{value:"no-default-models",children:"No Default Models"},"no-default-models"),D.map(e=>(0,s.jsx)(f.Select.Option,{value:e,children:(0,N.getModelDisplayName)(e)},e))]})})})]}),(0,s.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,s.jsx)(u.Button,{type:"primary",icon:(0,s.jsx)(l.UserAddOutlined,{}),htmlType:"submit",children:"Invite User"})})]})]}),A&&(0,s.jsx)(I,{isInvitationLinkModalVisible:W,setIsInvitationLinkModalVisible:K,baseUrl:G||"",invitationLinkData:q})]})}],371455)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/3330260a2a6da847.js b/litellm/proxy/_experimental/out/_next/static/chunks/1f6df7977860dc7b.js similarity index 51% rename from litellm/proxy/_experimental/out/_next/static/chunks/3330260a2a6da847.js rename to litellm/proxy/_experimental/out/_next/static/chunks/1f6df7977860dc7b.js index be4bf02092d..f10573a30cb 100644 --- a/litellm/proxy/_experimental/out/_next/static/chunks/3330260a2a6da847.js +++ b/litellm/proxy/_experimental/out/_next/static/chunks/1f6df7977860dc7b.js @@ -1 +1 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,349356,e=>{e.v({AElig:"Æ",AMP:"&",Aacute:"Á",Acirc:"Â",Agrave:"À",Aring:"Å",Atilde:"Ã",Auml:"Ä",COPY:"©",Ccedil:"Ç",ETH:"Ð",Eacute:"É",Ecirc:"Ê",Egrave:"È",Euml:"Ë",GT:">",Iacute:"Í",Icirc:"Î",Igrave:"Ì",Iuml:"Ï",LT:"<",Ntilde:"Ñ",Oacute:"Ó",Ocirc:"Ô",Ograve:"Ò",Oslash:"Ø",Otilde:"Õ",Ouml:"Ö",QUOT:'"',REG:"®",THORN:"Þ",Uacute:"Ú",Ucirc:"Û",Ugrave:"Ù",Uuml:"Ü",Yacute:"Ý",aacute:"á",acirc:"â",acute:"´",aelig:"æ",agrave:"à",amp:"&",aring:"å",atilde:"ã",auml:"ä",brvbar:"¦",ccedil:"ç",cedil:"¸",cent:"¢",copy:"©",curren:"¤",deg:"°",divide:"÷",eacute:"é",ecirc:"ê",egrave:"è",eth:"ð",euml:"ë",frac12:"½",frac14:"¼",frac34:"¾",gt:">",iacute:"í",icirc:"î",iexcl:"¡",igrave:"ì",iquest:"¿",iuml:"ï",laquo:"«",lt:"<",macr:"¯",micro:"µ",middot:"·",nbsp:" ",not:"¬",ntilde:"ñ",oacute:"ó",ocirc:"ô",ograve:"ò",ordf:"ª",ordm:"º",oslash:"ø",otilde:"õ",ouml:"ö",para:"¶",plusmn:"±",pound:"£",quot:'"',raquo:"»",reg:"®",sect:"§",shy:"­",sup1:"¹",sup2:"²",sup3:"³",szlig:"ß",thorn:"þ",times:"×",uacute:"ú",ucirc:"û",ugrave:"ù",uml:"¨",uuml:"ü",yacute:"ý",yen:"¥",yuml:"ÿ"})},137429,e=>{e.v({0:"�",128:"€",130:"‚",131:"ƒ",132:"„",133:"…",134:"†",135:"‡",136:"ˆ",137:"‰",138:"Š",139:"‹",140:"Œ",142:"Ž",145:"‘",146:"’",147:"“",148:"”",149:"•",150:"–",151:"—",152:"˜",153:"™",154:"š",155:"›",156:"œ",158:"ž",159:"Ÿ"})},166406,e=>{"use strict";var t=e.i(190144);e.s(["CopyOutlined",()=>t.default])},916925,e=>{"use strict";var t,a=((t={}).A2A_Agent="A2A Agent",t.AI21="Ai21",t.AI21_CHAT="Ai21 Chat",t.AIML="AI/ML API",t.AIOHTTP_OPENAI="Aiohttp Openai",t.Anthropic="Anthropic",t.ANTHROPIC_TEXT="Anthropic Text",t.AssemblyAI="AssemblyAI",t.AUTO_ROUTER="Auto Router",t.Bedrock="Amazon Bedrock",t.BedrockMantle="Amazon Bedrock Mantle",t.SageMaker="AWS SageMaker",t.Azure="Azure",t.Azure_AI_Studio="Azure AI Foundry (Studio)",t.AZURE_TEXT="Azure Text",t.BASETEN="Baseten",t.BYTEZ="Bytez",t.Cerebras="Cerebras",t.CLARIFAI="Clarifai",t.CLOUDFLARE="Cloudflare",t.CODESTRAL="Codestral",t.Cohere="Cohere",t.COHERE_CHAT="Cohere Chat",t.COMETAPI="Cometapi",t.COMPACTIFAI="Compactifai",t.Cursor="Cursor",t.Dashscope="Dashscope",t.Databricks="Databricks (Qwen API)",t.DATAROBOT="Datarobot",t.DeepInfra="DeepInfra",t.Deepgram="Deepgram",t.Deepseek="Deepseek",t.DOCKER_MODEL_RUNNER="Docker Model Runner",t.DOTPROMPT="Dotprompt",t.ElevenLabs="ElevenLabs",t.EMPOWER="Empower",t.FalAI="Fal AI",t.FEATHERLESS_AI="Featherless Ai",t.FireworksAI="Fireworks AI",t.FRIENDLIAI="Friendliai",t.GALADRIEL="Galadriel",t.GITHUB_COPILOT="Github Copilot",t.Google_AI_Studio="Google AI Studio",t.GradientAI="GradientAI",t.Groq="Groq",t.HEROKU="Heroku",t.Hosted_Vllm="vllm",t.HUGGINGFACE="Huggingface",t.HYPERBOLIC="Hyperbolic",t.Infinity="Infinity",t.JinaAI="Jina AI",t.LAMBDA_AI="Lambda Ai",t.LEMONADE="Lemonade",t.LLAMAFILE="Llamafile",t.LM_STUDIO="Lm Studio",t.LLAMA="Meta Llama",t.MARITALK="Maritalk",t.MiniMax="MiniMax",t.MistralAI="Mistral AI",t.MOONSHOT="Moonshot",t.MORPH="Morph",t.NEBIUS="Nebius",t.NLP_CLOUD="Nlp Cloud",t.NOVITA="Novita",t.NSCALE="Nscale",t.NVIDIA_NIM="Nvidia Nim",t.Ollama="Ollama",t.OLLAMA_CHAT="Ollama Chat",t.OOBABOOGA="Oobabooga",t.OpenAI="OpenAI",t.OPENAI_LIKE="Openai Like",t.OpenAI_Compatible="OpenAI-Compatible Endpoints (Together AI, etc.)",t.OpenAI_Text="OpenAI Text Completion",t.OpenAI_Text_Compatible="OpenAI-Compatible Text Completion Models (Together AI, etc.)",t.Openrouter="Openrouter",t.Oracle="Oracle Cloud Infrastructure (OCI)",t.OVHCLOUD="Ovhcloud",t.Perplexity="Perplexity",t.PETALS="Petals",t.PG_VECTOR="Pg Vector",t.PREDIBASE="Predibase",t.RECRAFT="Recraft",t.REPLICATE="Replicate",t.RunwayML="RunwayML",t.SAGEMAKER_LEGACY="Sagemaker",t.Sambanova="Sambanova",t.SAP="SAP Generative AI Hub",t.Snowflake="Snowflake",t.TEXT_COMPLETION_CODESTRAL="Text-Completion-Codestral",t.TogetherAI="TogetherAI",t.TOPAZ="Topaz",t.Triton="Triton",t.V0="V0",t.VERCEL_AI_GATEWAY="Vercel Ai Gateway",t.Vertex_AI="Vertex AI (Anthropic, Gemini, etc.)",t.VERTEX_AI_BETA="Vertex Ai Beta",t.VLLM="Vllm",t.VolcEngine="VolcEngine",t.Voyage="Voyage AI",t.WANDB="Wandb",t.WATSONX="Watsonx",t.WATSONX_TEXT="Watsonx Text",t.xAI="xAI",t.XINFERENCE="Xinference",t);let r={A2A_Agent:"a2a_agent",AI21:"ai21",AI21_CHAT:"ai21_chat",AIML:"aiml",AIOHTTP_OPENAI:"aiohttp_openai",Anthropic:"anthropic",ANTHROPIC_TEXT:"anthropic_text",AssemblyAI:"assemblyai",AUTO_ROUTER:"auto_router",Azure:"azure",Azure_AI_Studio:"azure_ai",AZURE_TEXT:"azure_text",BASETEN:"baseten",Bedrock:"bedrock",BedrockMantle:"bedrock_mantle",BYTEZ:"bytez",Cerebras:"cerebras",CLARIFAI:"clarifai",CLOUDFLARE:"cloudflare",CODESTRAL:"codestral",Cohere:"cohere",COHERE_CHAT:"cohere_chat",COMETAPI:"cometapi",COMPACTIFAI:"compactifai",Cursor:"cursor",Dashscope:"dashscope",Databricks:"databricks",DATAROBOT:"datarobot",DeepInfra:"deepinfra",Deepgram:"deepgram",Deepseek:"deepseek",DOCKER_MODEL_RUNNER:"docker_model_runner",DOTPROMPT:"dotprompt",ElevenLabs:"elevenlabs",EMPOWER:"empower",FalAI:"fal_ai",FEATHERLESS_AI:"featherless_ai",FireworksAI:"fireworks_ai",FRIENDLIAI:"friendliai",GALADRIEL:"galadriel",GITHUB_COPILOT:"github_copilot",Google_AI_Studio:"gemini",GradientAI:"gradient_ai",Groq:"groq",HEROKU:"heroku",Hosted_Vllm:"hosted_vllm",HUGGINGFACE:"huggingface",HYPERBOLIC:"hyperbolic",Infinity:"infinity",JinaAI:"jina_ai",LAMBDA_AI:"lambda_ai",LEMONADE:"lemonade",LLAMAFILE:"llamafile",LLAMA:"meta_llama",LM_STUDIO:"lm_studio",MARITALK:"maritalk",MiniMax:"minimax",MistralAI:"mistral",MOONSHOT:"moonshot",MORPH:"morph",NEBIUS:"nebius",NLP_CLOUD:"nlp_cloud",NOVITA:"novita",NSCALE:"nscale",NVIDIA_NIM:"nvidia_nim",Ollama:"ollama",OLLAMA_CHAT:"ollama_chat",OOBABOOGA:"oobabooga",OpenAI:"openai",OPENAI_LIKE:"openai_like",OpenAI_Compatible:"openai",OpenAI_Text:"text-completion-openai",OpenAI_Text_Compatible:"text-completion-openai",Openrouter:"openrouter",Oracle:"oci",OVHCLOUD:"ovhcloud",Perplexity:"perplexity",PETALS:"petals",PG_VECTOR:"pg_vector",PREDIBASE:"predibase",RECRAFT:"recraft",REPLICATE:"replicate",RunwayML:"runwayml",SAGEMAKER_LEGACY:"sagemaker",SageMaker:"sagemaker_chat",Sambanova:"sambanova",SAP:"sap",Snowflake:"snowflake",TEXT_COMPLETION_CODESTRAL:"text-completion-codestral",TogetherAI:"together_ai",TOPAZ:"topaz",Triton:"triton",V0:"v0",VERCEL_AI_GATEWAY:"vercel_ai_gateway",Vertex_AI:"vertex_ai",VERTEX_AI_BETA:"vertex_ai_beta",VLLM:"vllm",VolcEngine:"volcengine",Voyage:"voyage",WANDB:"wandb",WATSONX:"watsonx",WATSONX_TEXT:"watsonx_text",xAI:"xai",XINFERENCE:"xinference"},o="../ui/assets/logos/",n={"A2A Agent":`${o}a2a_agent.png`,Ai21:`${o}ai21.svg`,"Ai21 Chat":`${o}ai21.svg`,"AI/ML API":`${o}aiml_api.svg`,"Aiohttp Openai":`${o}openai_small.svg`,Anthropic:`${o}anthropic.svg`,"Anthropic Text":`${o}anthropic.svg`,AssemblyAI:`${o}assemblyai_small.png`,Azure:`${o}microsoft_azure.svg`,"Azure AI Foundry (Studio)":`${o}microsoft_azure.svg`,"Azure Text":`${o}microsoft_azure.svg`,Baseten:`${o}baseten.svg`,"Amazon Bedrock":`${o}bedrock.svg`,"Amazon Bedrock Mantle":`${o}bedrock.svg`,"AWS SageMaker":`${o}bedrock.svg`,Cerebras:`${o}cerebras.svg`,Cloudflare:`${o}cloudflare.svg`,Codestral:`${o}mistral.svg`,Cohere:`${o}cohere.svg`,"Cohere Chat":`${o}cohere.svg`,Cometapi:`${o}cometapi.svg`,Cursor:`${o}cursor.svg`,"Databricks (Qwen API)":`${o}databricks.svg`,Dashscope:`${o}dashscope.svg`,Deepseek:`${o}deepseek.svg`,Deepgram:`${o}deepgram.png`,DeepInfra:`${o}deepinfra.png`,ElevenLabs:`${o}elevenlabs.png`,"Fal AI":`${o}fal_ai.jpg`,"Featherless Ai":`${o}featherless.svg`,"Fireworks AI":`${o}fireworks.svg`,Friendliai:`${o}friendli.svg`,"Github Copilot":`${o}github_copilot.svg`,"Google AI Studio":`${o}google.svg`,GradientAI:`${o}gradientai.svg`,Groq:`${o}groq.svg`,vllm:`${o}vllm.png`,Huggingface:`${o}huggingface.svg`,Hyperbolic:`${o}hyperbolic.svg`,Infinity:`${o}infinity.png`,"Jina AI":`${o}jina.png`,"Lambda Ai":`${o}lambda.svg`,"Lm Studio":`${o}lmstudio.svg`,"Meta Llama":`${o}meta_llama.svg`,MiniMax:`${o}minimax.svg`,"Mistral AI":`${o}mistral.svg`,Moonshot:`${o}moonshot.svg`,Morph:`${o}morph.svg`,Nebius:`${o}nebius.svg`,Novita:`${o}novita.svg`,"Nvidia Nim":`${o}nvidia_nim.svg`,Ollama:`${o}ollama.svg`,"Ollama Chat":`${o}ollama.svg`,Oobabooga:`${o}openai_small.svg`,OpenAI:`${o}openai_small.svg`,"Openai Like":`${o}openai_small.svg`,"OpenAI Text Completion":`${o}openai_small.svg`,"OpenAI-Compatible Text Completion Models (Together AI, etc.)":`${o}openai_small.svg`,"OpenAI-Compatible Endpoints (Together AI, etc.)":`${o}openai_small.svg`,Openrouter:`${o}openrouter.svg`,"Oracle Cloud Infrastructure (OCI)":`${o}oracle.svg`,Perplexity:`${o}perplexity-ai.svg`,Recraft:`${o}recraft.svg`,Replicate:`${o}replicate.svg`,RunwayML:`${o}runwayml.png`,Sagemaker:`${o}bedrock.svg`,Sambanova:`${o}sambanova.svg`,"SAP Generative AI Hub":`${o}sap.png`,Snowflake:`${o}snowflake.svg`,"Text-Completion-Codestral":`${o}mistral.svg`,TogetherAI:`${o}togetherai.svg`,Topaz:`${o}topaz.svg`,Triton:`${o}nvidia_triton.png`,V0:`${o}v0.svg`,"Vercel Ai Gateway":`${o}vercel.svg`,"Vertex AI (Anthropic, Gemini, etc.)":`${o}google.svg`,"Vertex Ai Beta":`${o}google.svg`,Vllm:`${o}vllm.png`,VolcEngine:`${o}volcengine.png`,"Voyage AI":`${o}voyage.webp`,Watsonx:`${o}watsonx.svg`,"Watsonx Text":`${o}watsonx.svg`,xAI:`${o}xai.svg`,Xinference:`${o}xinference.svg`};e.s(["Providers",()=>a,"getPlaceholder",0,e=>{if("AI/ML API"===e)return"aiml/flux-pro/v1.1";if("Vertex AI (Anthropic, Gemini, etc.)"===e)return"gemini-pro";if("Anthropic"==e)return"claude-3-opus";if("Amazon Bedrock"==e)return"claude-3-opus";if("AWS SageMaker"==e)return"sagemaker/jumpstart-dft-meta-textgeneration-llama-2-7b";else if("Google AI Studio"==e)return"gemini-pro";else if("Azure AI Foundry (Studio)"==e)return"azure_ai/command-r-plus";else if("Azure"==e)return"my-deployment";else if("Oracle Cloud Infrastructure (OCI)"==e)return"oci/xai.grok-4";else if("Snowflake"==e)return"snowflake/mistral-7b";else if("Voyage AI"==e)return"voyage/";else if("Jina AI"==e)return"jina_ai/";else if("VolcEngine"==e)return"volcengine/";else if("DeepInfra"==e)return"deepinfra/";else if("Fal AI"==e)return"fal_ai/fal-ai/flux-pro/v1.1-ultra";else if("RunwayML"==e)return"runwayml/gen4_turbo";else if("Watsonx"===e)return"watsonx/ibm/granite-3-3-8b-instruct";else if("Cursor"===e)return"cursor/claude-4-sonnet";else return"gpt-3.5-turbo"},"getProviderLogoAndName",0,e=>{if(!e)return{logo:"",displayName:"-"};if("gemini"===e.toLowerCase()){let e="Google AI Studio";return{logo:n[e],displayName:e}}let t=Object.keys(r).find(t=>r[t].toLowerCase()===e.toLowerCase());if(!t)return{logo:"",displayName:e};let o=a[t];return{logo:n[o],displayName:o}},"getProviderModels",0,(e,t)=>{console.log(`Provider key: ${e}`);let a=r[e];console.log(`Provider mapped to: ${a}`);let o=[];return e&&"object"==typeof t&&(Object.entries(t).forEach(([e,t])=>{if(null!==t&&"object"==typeof t&&"litellm_provider"in t){let r=t.litellm_provider;(r===a||"string"==typeof r&&r.includes(a))&&o.push(e)}}),"Cohere"==e&&(console.log("Adding cohere chat models"),Object.entries(t).forEach(([e,t])=>{null!==t&&"object"==typeof t&&"litellm_provider"in t&&"cohere_chat"===t.litellm_provider&&o.push(e)})),"AWS SageMaker"==e&&(console.log("Adding sagemaker chat models"),Object.entries(t).forEach(([e,t])=>{null!==t&&"object"==typeof t&&"litellm_provider"in t&&"sagemaker_chat"===t.litellm_provider&&o.push(e)}))),o},"providerLogoMap",0,n,"provider_map",0,r])},637235,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let r={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 372z"}},{tag:"path",attrs:{d:"M686.7 638.6L544.1 535.5V288c0-4.4-3.6-8-8-8H488c-4.4 0-8 3.6-8 8v275.4c0 2.6 1.2 5 3.3 6.5l165.4 120.6c3.6 2.6 8.6 1.8 11.2-1.7l28.6-39c2.6-3.7 1.8-8.7-1.8-11.2z"}}]},name:"clock-circle",theme:"outlined"};var o=e.i(9583),n=a.forwardRef(function(e,n){return a.createElement(o.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["ClockCircleOutlined",0,n],637235)},519756,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let r={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"};var o=e.i(9583),n=a.forwardRef(function(e,n){return a.createElement(o.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["UploadOutlined",0,n],519756)},530212,e=>{"use strict";var t=e.i(271645);let a=t.forwardRef(function(e,a){return t.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:a},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10 19l-7-7m0 0l7-7m-7 7h18"}))});e.s(["ArrowLeftIcon",0,a],530212)},500330,e=>{"use strict";var t=e.i(727749);function a(e,t){let a=structuredClone(e);for(let[e,r]of Object.entries(t))e in a&&(a[e]=r);return a}let r=(e,t=0,a=!1,r=!0)=>{if(null==e||!Number.isFinite(e)||0===e&&!r)return"-";let o={minimumFractionDigits:t,maximumFractionDigits:t};if(!a)return e.toLocaleString("en-US",o);let n=e<0?"-":"",i=Math.abs(e),l=i,s="";return i>=1e6?(l=i/1e6,s="M"):i>=1e3&&(l=i/1e3,s="K"),`${n}${l.toLocaleString("en-US",o)}${s}`},o=async(e,a="Copied to clipboard")=>{if(!e)return!1;if(!navigator||!navigator.clipboard||!navigator.clipboard.writeText)return n(e,a);try{return await navigator.clipboard.writeText(e),t.default.success(a),!0}catch(t){return console.error("Clipboard API failed: ",t),n(e,a)}},n=(e,a)=>{try{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",r.setAttribute("readonly",""),document.body.appendChild(r),r.focus(),r.select();let o=document.execCommand("copy");if(document.body.removeChild(r),o)return t.default.success(a),!0;throw Error("execCommand failed")}catch(e){return t.default.fromBackend("Failed to copy to clipboard"),console.error("Failed to copy: ",e),!1}};e.s(["copyToClipboard",0,o,"formatNumberWithCommas",0,r,"getSpendString",0,(e,t=6)=>{if(null==e||!Number.isFinite(e)||0===e)return"-";let a=r(e,t,!1,!1);if(0===Number(a.replace(/,/g,""))){let e=(1/10**t).toFixed(t);return`< $${e}`}return`$${a}`},"updateExistingKeys",()=>a])},603908,e=>{"use strict";let t=(0,e.i(475254).default)("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);e.s(["default",()=>t])},689020,e=>{"use strict";var t=e.i(764205);let a=async e=>{try{let a=await (0,t.modelHubCall)(e);if(console.log("model_info:",a),a?.data.length>0){let e=a.data.map(e=>({model_group:e.model_group,mode:e?.mode}));return e.sort((e,t)=>e.model_group.localeCompare(t.model_group)),e}return[]}catch(e){throw console.error("Error fetching model info:",e),e}};e.s(["fetchAvailableModels",0,a])},599724,936325,e=>{"use strict";var t=e.i(95779),a=e.i(444755),r=e.i(673706),o=e.i(271645);let n=o.default.forwardRef((e,n)=>{let{color:i,className:l,children:s}=e;return o.default.createElement("p",{ref:n,className:(0,a.tremorTwMerge)("text-tremor-default",i?(0,r.getColorClassNames)(i,t.colorPalette.text).textColor:(0,a.tremorTwMerge)("text-tremor-content","dark:text-dark-tremor-content"),l)},s)});n.displayName="Text",e.s(["default",()=>n],936325),e.s(["Text",()=>n],599724)},994388,e=>{"use strict";var t=e.i(290571),a=e.i(829087),r=e.i(271645);let o=["preEnter","entering","entered","preExit","exiting","exited","unmounted"],n=e=>({_s:e,status:o[e],isEnter:e<3,isMounted:6!==e,isResolved:2===e||e>4}),i=e=>e?6:5,l=(e,t,a,r,o)=>{clearTimeout(r.current);let i=n(e);t(i),a.current=i,o&&o({current:i})};var s=e.i(480731),c=e.i(444755),d=e.i(673706);let u=e=>{var a=(0,t.__rest)(e,[]);return r.default.createElement("svg",Object.assign({},a,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"}),r.default.createElement("path",{fill:"none",d:"M0 0h24v24H0z"}),r.default.createElement("path",{d:"M18.364 5.636L16.95 7.05A7 7 0 1 0 19 12h2a9 9 0 1 1-2.636-6.364z"}))};var m=e.i(95779);let p={xs:{height:"h-4",width:"w-4"},sm:{height:"h-5",width:"w-5"},md:{height:"h-5",width:"w-5"},lg:{height:"h-6",width:"w-6"},xl:{height:"h-6",width:"w-6"}},g=(e,t)=>{switch(e){case"primary":return{textColor:t?(0,d.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",hoverTextColor:t?(0,d.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",bgColor:t?(0,d.getColorClassNames)(t,m.colorPalette.background).bgColor:"bg-tremor-brand dark:bg-dark-tremor-brand",hoverBgColor:t?(0,d.getColorClassNames)(t,m.colorPalette.darkBackground).hoverBgColor:"hover:bg-tremor-brand-emphasis dark:hover:bg-dark-tremor-brand-emphasis",borderColor:t?(0,d.getColorClassNames)(t,m.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",hoverBorderColor:t?(0,d.getColorClassNames)(t,m.colorPalette.darkBorder).hoverBorderColor:"hover:border-tremor-brand-emphasis dark:hover:border-dark-tremor-brand-emphasis"};case"secondary":return{textColor:t?(0,d.getColorClassNames)(t,m.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,d.getColorClassNames)(t,m.colorPalette.text).textColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,d.getColorClassNames)("transparent").bgColor,hoverBgColor:t?(0,c.tremorTwMerge)((0,d.getColorClassNames)(t,m.colorPalette.background).hoverBgColor,"hover:bg-opacity-20 dark:hover:bg-opacity-20"):"hover:bg-tremor-brand-faint dark:hover:bg-dark-tremor-brand-faint",borderColor:t?(0,d.getColorClassNames)(t,m.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand"};case"light":return{textColor:t?(0,d.getColorClassNames)(t,m.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,d.getColorClassNames)(t,m.colorPalette.darkText).hoverTextColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,d.getColorClassNames)("transparent").bgColor,borderColor:"",hoverBorderColor:""}}},f=(0,d.makeClassName)("Button"),h=({loading:e,iconSize:t,iconPosition:a,Icon:o,needMargin:n,transitionStatus:i})=>{let l=n?a===s.HorizontalPositions.Left?(0,c.tremorTwMerge)("-ml-1","mr-1.5"):(0,c.tremorTwMerge)("-mr-1","ml-1.5"):"",d=(0,c.tremorTwMerge)("w-0 h-0"),m={default:d,entering:d,entered:t,exiting:t,exited:d};return e?r.default.createElement(u,{className:(0,c.tremorTwMerge)(f("icon"),"animate-spin shrink-0",l,m.default,m[i]),style:{transition:"width 150ms"}}):r.default.createElement(o,{className:(0,c.tremorTwMerge)(f("icon"),"shrink-0",t,l)})},v=r.default.forwardRef((e,o)=>{let{icon:u,iconPosition:m=s.HorizontalPositions.Left,size:v=s.Sizes.SM,color:b,variant:x="primary",disabled:y,loading:C=!1,loadingText:$,children:k,tooltip:O,className:w}=e,A=(0,t.__rest)(e,["icon","iconPosition","size","color","variant","disabled","loading","loadingText","children","tooltip","className"]),E=C||y,S=void 0!==u||C,I=C&&$,T=!(!k&&!I),N=(0,c.tremorTwMerge)(p[v].height,p[v].width),M="light"!==x?(0,c.tremorTwMerge)("rounded-tremor-default border","shadow-tremor-input","dark:shadow-dark-tremor-input"):"",z=g(x,b),L=("light"!==x?{xs:{paddingX:"px-2.5",paddingY:"py-1.5",fontSize:"text-xs"},sm:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-sm"},md:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-md"},lg:{paddingX:"px-4",paddingY:"py-2.5",fontSize:"text-lg"},xl:{paddingX:"px-4",paddingY:"py-3",fontSize:"text-xl"}}:{xs:{paddingX:"",paddingY:"",fontSize:"text-xs"},sm:{paddingX:"",paddingY:"",fontSize:"text-sm"},md:{paddingX:"",paddingY:"",fontSize:"text-md"},lg:{paddingX:"",paddingY:"",fontSize:"text-lg"},xl:{paddingX:"",paddingY:"",fontSize:"text-xl"}})[v],{tooltipProps:_,getReferenceProps:j}=(0,a.useTooltip)(300),[R,P]=(({enter:e=!0,exit:t=!0,preEnter:a,preExit:o,timeout:s,initialEntered:c,mountOnEnter:d,unmountOnExit:u,onStateChange:m}={})=>{let[p,g]=(0,r.useState)(()=>n(c?2:i(d))),f=(0,r.useRef)(p),h=(0,r.useRef)(0),[v,b]="object"==typeof s?[s.enter,s.exit]:[s,s],x=(0,r.useCallback)(()=>{let e=((e,t)=>{switch(e){case 1:case 0:return 2;case 4:case 3:return i(t)}})(f.current._s,u);e&&l(e,g,f,h,m)},[m,u]);return[p,(0,r.useCallback)(r=>{let n=e=>{switch(l(e,g,f,h,m),e){case 1:v>=0&&(h.current=((...e)=>setTimeout(...e))(x,v));break;case 4:b>=0&&(h.current=((...e)=>setTimeout(...e))(x,b));break;case 0:case 3:h.current=((...e)=>setTimeout(...e))(()=>{isNaN(document.body.offsetTop)||n(e+1)},0)}},s=f.current.isEnter;"boolean"!=typeof r&&(r=!s),r?s||n(e?+!a:2):s&&n(t?o?3:4:i(u))},[x,m,e,t,a,o,v,b,u]),x]})({timeout:50});return(0,r.useEffect)(()=>{P(C)},[C]),r.default.createElement("button",Object.assign({ref:(0,d.mergeRefs)([o,_.refs.setReference]),className:(0,c.tremorTwMerge)(f("root"),"shrink-0 inline-flex justify-center items-center group font-medium outline-none",M,L.paddingX,L.paddingY,L.fontSize,z.textColor,z.bgColor,z.borderColor,z.hoverBorderColor,E?"opacity-50 cursor-not-allowed":(0,c.tremorTwMerge)(g(x,b).hoverTextColor,g(x,b).hoverBgColor,g(x,b).hoverBorderColor),w),disabled:E},j,A),r.default.createElement(a.default,Object.assign({text:O},_)),S&&m!==s.HorizontalPositions.Right?r.default.createElement(h,{loading:C,iconSize:N,iconPosition:m,Icon:u,transitionStatus:R.status,needMargin:T}):null,I||k?r.default.createElement("span",{className:(0,c.tremorTwMerge)(f("text"),"text-tremor-default whitespace-nowrap")},I?$:k):null,S&&m===s.HorizontalPositions.Right?r.default.createElement(h,{loading:C,iconSize:N,iconPosition:m,Icon:u,transitionStatus:R.status,needMargin:T}):null)});v.displayName="Button",e.s(["Button",()=>v],994388)},304967,e=>{"use strict";var t=e.i(290571),a=e.i(271645),r=e.i(480731),o=e.i(95779),n=e.i(444755),i=e.i(673706);let l=(0,i.makeClassName)("Card"),s=a.default.forwardRef((e,s)=>{let{decoration:c="",decorationColor:d,children:u,className:m}=e,p=(0,t.__rest)(e,["decoration","decorationColor","children","className"]);return a.default.createElement("div",Object.assign({ref:s,className:(0,n.tremorTwMerge)(l("root"),"relative w-full text-left ring-1 rounded-tremor-default p-6","bg-tremor-background ring-tremor-ring shadow-tremor-card","dark:bg-dark-tremor-background dark:ring-dark-tremor-ring dark:shadow-dark-tremor-card",d?(0,i.getColorClassNames)(d,o.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",(e=>{if(!e)return"";switch(e){case r.HorizontalPositions.Left:return"border-l-4";case r.VerticalPositions.Top:return"border-t-4";case r.HorizontalPositions.Right:return"border-r-4";case r.VerticalPositions.Bottom:return"border-b-4";default:return""}})(c),m)},p),u)});s.displayName="Card",e.s(["Card",()=>s],304967)},629569,e=>{"use strict";var t=e.i(290571),a=e.i(95779),r=e.i(444755),o=e.i(673706),n=e.i(271645);let i=n.default.forwardRef((e,i)=>{let{color:l,children:s,className:c}=e,d=(0,t.__rest)(e,["color","children","className"]);return n.default.createElement("p",Object.assign({ref:i,className:(0,r.tremorTwMerge)("font-medium text-tremor-title",l?(0,o.getColorClassNames)(l,a.colorPalette.darkText).textColor:"text-tremor-content-strong dark:text-dark-tremor-content-strong",c)},d),s)});i.displayName="Title",e.s(["Title",()=>i],629569)},244451,e=>{"use strict";let t;e.i(247167);var a=e.i(271645),r=e.i(343794),o=e.i(242064),n=e.i(763731),i=e.i(174428);let l=80*Math.PI,s=e=>{let{dotClassName:t,style:o,hasCircleCls:n}=e;return a.createElement("circle",{className:(0,r.default)(`${t}-circle`,{[`${t}-circle-bg`]:n}),r:40,cx:50,cy:50,strokeWidth:20,style:o})},c=({percent:e,prefixCls:t})=>{let o=`${t}-dot`,n=`${o}-holder`,c=`${n}-hidden`,[d,u]=a.useState(!1);(0,i.default)(()=>{0!==e&&u(!0)},[0!==e]);let m=Math.max(Math.min(e,100),0);if(!d)return null;let p={strokeDashoffset:`${l/4}`,strokeDasharray:`${l*m/100} ${l*(100-m)/100}`};return a.createElement("span",{className:(0,r.default)(n,`${o}-progress`,m<=0&&c)},a.createElement("svg",{viewBox:"0 0 100 100",role:"progressbar","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":m},a.createElement(s,{dotClassName:o,hasCircleCls:!0}),a.createElement(s,{dotClassName:o,style:p})))};function d(e){let{prefixCls:t,percent:o=0}=e,n=`${t}-dot`,i=`${n}-holder`,l=`${i}-hidden`;return a.createElement(a.Fragment,null,a.createElement("span",{className:(0,r.default)(i,o>0&&l)},a.createElement("span",{className:(0,r.default)(n,`${t}-dot-spin`)},[1,2,3,4].map(e=>a.createElement("i",{className:`${t}-dot-item`,key:e})))),a.createElement(c,{prefixCls:t,percent:o}))}function u(e){var t;let{prefixCls:o,indicator:i,percent:l}=e,s=`${o}-dot`;return i&&a.isValidElement(i)?(0,n.cloneElement)(i,{className:(0,r.default)(null==(t=i.props)?void 0:t.className,s),percent:l}):a.createElement(d,{prefixCls:o,percent:l})}e.i(296059);var m=e.i(694758),p=e.i(183293),g=e.i(246422),f=e.i(838378);let h=new m.Keyframes("antSpinMove",{to:{opacity:1}}),v=new m.Keyframes("antRotate",{to:{transform:"rotate(405deg)"}}),b=(0,g.genStyleHooks)("Spin",e=>(e=>{let{componentCls:t,calc:a}=e;return{[t]:Object.assign(Object.assign({},(0,p.resetComponent)(e)),{position:"absolute",display:"none",color:e.colorPrimary,fontSize:0,textAlign:"center",verticalAlign:"middle",opacity:0,transition:`transform ${e.motionDurationSlow} ${e.motionEaseInOutCirc}`,"&-spinning":{position:"relative",display:"inline-block",opacity:1},[`${t}-text`]:{fontSize:e.fontSize,paddingTop:a(a(e.dotSize).sub(e.fontSize)).div(2).add(2).equal()},"&-fullscreen":{position:"fixed",width:"100vw",height:"100vh",backgroundColor:e.colorBgMask,zIndex:e.zIndexPopupBase,inset:0,display:"flex",alignItems:"center",flexDirection:"column",justifyContent:"center",opacity:0,visibility:"hidden",transition:`all ${e.motionDurationMid}`,"&-show":{opacity:1,visibility:"visible"},[t]:{[`${t}-dot-holder`]:{color:e.colorWhite},[`${t}-text`]:{color:e.colorTextLightSolid}}},"&-nested-loading":{position:"relative",[`> div > ${t}`]:{position:"absolute",top:0,insetInlineStart:0,zIndex:4,display:"block",width:"100%",height:"100%",maxHeight:e.contentHeight,[`${t}-dot`]:{position:"absolute",top:"50%",insetInlineStart:"50%",margin:a(e.dotSize).mul(-1).div(2).equal()},[`${t}-text`]:{position:"absolute",top:"50%",width:"100%",textShadow:`0 1px 2px ${e.colorBgContainer}`},[`&${t}-show-text ${t}-dot`]:{marginTop:a(e.dotSize).div(2).mul(-1).sub(10).equal()},"&-sm":{[`${t}-dot`]:{margin:a(e.dotSizeSM).mul(-1).div(2).equal()},[`${t}-text`]:{paddingTop:a(a(e.dotSizeSM).sub(e.fontSize)).div(2).add(2).equal()},[`&${t}-show-text ${t}-dot`]:{marginTop:a(e.dotSizeSM).div(2).mul(-1).sub(10).equal()}},"&-lg":{[`${t}-dot`]:{margin:a(e.dotSizeLG).mul(-1).div(2).equal()},[`${t}-text`]:{paddingTop:a(a(e.dotSizeLG).sub(e.fontSize)).div(2).add(2).equal()},[`&${t}-show-text ${t}-dot`]:{marginTop:a(e.dotSizeLG).div(2).mul(-1).sub(10).equal()}}},[`${t}-container`]:{position:"relative",transition:`opacity ${e.motionDurationSlow}`,"&::after":{position:"absolute",top:0,insetInlineEnd:0,bottom:0,insetInlineStart:0,zIndex:10,width:"100%",height:"100%",background:e.colorBgContainer,opacity:0,transition:`all ${e.motionDurationSlow}`,content:'""',pointerEvents:"none"}},[`${t}-blur`]:{clear:"both",opacity:.5,userSelect:"none",pointerEvents:"none","&::after":{opacity:.4,pointerEvents:"auto"}}},"&-tip":{color:e.spinDotDefault},[`${t}-dot-holder`]:{width:"1em",height:"1em",fontSize:e.dotSize,display:"inline-block",transition:`transform ${e.motionDurationSlow} ease, opacity ${e.motionDurationSlow} ease`,transformOrigin:"50% 50%",lineHeight:1,color:e.colorPrimary,"&-hidden":{transform:"scale(0.3)",opacity:0}},[`${t}-dot-progress`]:{position:"absolute",inset:0},[`${t}-dot`]:{position:"relative",display:"inline-block",fontSize:e.dotSize,width:"1em",height:"1em","&-item":{position:"absolute",display:"block",width:a(e.dotSize).sub(a(e.marginXXS).div(2)).div(2).equal(),height:a(e.dotSize).sub(a(e.marginXXS).div(2)).div(2).equal(),background:"currentColor",borderRadius:"100%",transform:"scale(0.75)",transformOrigin:"50% 50%",opacity:.3,animationName:h,animationDuration:"1s",animationIterationCount:"infinite",animationTimingFunction:"linear",animationDirection:"alternate","&:nth-child(1)":{top:0,insetInlineStart:0,animationDelay:"0s"},"&:nth-child(2)":{top:0,insetInlineEnd:0,animationDelay:"0.4s"},"&:nth-child(3)":{insetInlineEnd:0,bottom:0,animationDelay:"0.8s"},"&:nth-child(4)":{bottom:0,insetInlineStart:0,animationDelay:"1.2s"}},"&-spin":{transform:"rotate(45deg)",animationName:v,animationDuration:"1.2s",animationIterationCount:"infinite",animationTimingFunction:"linear"},"&-circle":{strokeLinecap:"round",transition:["stroke-dashoffset","stroke-dasharray","stroke","stroke-width","opacity"].map(t=>`${t} ${e.motionDurationSlow} ease`).join(","),fillOpacity:0,stroke:"currentcolor"},"&-circle-bg":{stroke:e.colorFillSecondary}},[`&-sm ${t}-dot`]:{"&, &-holder":{fontSize:e.dotSizeSM}},[`&-sm ${t}-dot-holder`]:{i:{width:a(a(e.dotSizeSM).sub(a(e.marginXXS).div(2))).div(2).equal(),height:a(a(e.dotSizeSM).sub(a(e.marginXXS).div(2))).div(2).equal()}},[`&-lg ${t}-dot`]:{"&, &-holder":{fontSize:e.dotSizeLG}},[`&-lg ${t}-dot-holder`]:{i:{width:a(a(e.dotSizeLG).sub(e.marginXXS)).div(2).equal(),height:a(a(e.dotSizeLG).sub(e.marginXXS)).div(2).equal()}},[`&${t}-show-text ${t}-text`]:{display:"block"}})}})((0,f.mergeToken)(e,{spinDotDefault:e.colorTextDescription})),e=>{let{controlHeightLG:t,controlHeight:a}=e;return{contentHeight:400,dotSize:t/2,dotSizeSM:.35*t,dotSizeLG:a}}),x=[[30,.05],[70,.03],[96,.01]];var y=function(e,t){var a={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(a[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);ot.indexOf(r[o])&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(a[r[o]]=e[r[o]]);return a};let C=e=>{var n;let{prefixCls:i,spinning:l=!0,delay:s=0,className:c,rootClassName:d,size:m="default",tip:p,wrapperClassName:g,style:f,children:h,fullscreen:v=!1,indicator:C,percent:$}=e,k=y(e,["prefixCls","spinning","delay","className","rootClassName","size","tip","wrapperClassName","style","children","fullscreen","indicator","percent"]),{getPrefixCls:O,direction:w,className:A,style:E,indicator:S}=(0,o.useComponentConfig)("spin"),I=O("spin",i),[T,N,M]=b(I),[z,L]=a.useState(()=>l&&(!l||!s||!!Number.isNaN(Number(s)))),_=function(e,t){let[r,o]=a.useState(0),n=a.useRef(null),i="auto"===t;return a.useEffect(()=>(i&&e&&(o(0),n.current=setInterval(()=>{o(e=>{let t=100-e;for(let a=0;a{n.current&&(clearInterval(n.current),n.current=null)}),[i,e]),i?r:t}(z,$);a.useEffect(()=>{if(l){let e=function(e,t,a){var r,o=a||{},n=o.noTrailing,i=void 0!==n&&n,l=o.noLeading,s=void 0!==l&&l,c=o.debounceMode,d=void 0===c?void 0:c,u=!1,m=0;function p(){r&&clearTimeout(r)}function g(){for(var a=arguments.length,o=Array(a),n=0;ne?s?(m=Date.now(),i||(r=setTimeout(d?f:g,e))):g():!0!==i&&(r=setTimeout(d?f:g,void 0===d?e-c:e)))}return g.cancel=function(e){var t=(e||{}).upcomingOnly;p(),u=!(void 0!==t&&t)},g}(s,()=>{L(!0)},{debounceMode:false});return e(),()=>{var t;null==(t=null==e?void 0:e.cancel)||t.call(e)}}L(!1)},[s,l]);let j=a.useMemo(()=>void 0!==h&&!v,[h,v]),R=(0,r.default)(I,A,{[`${I}-sm`]:"small"===m,[`${I}-lg`]:"large"===m,[`${I}-spinning`]:z,[`${I}-show-text`]:!!p,[`${I}-rtl`]:"rtl"===w},c,!v&&d,N,M),P=(0,r.default)(`${I}-container`,{[`${I}-blur`]:z}),D=null!=(n=null!=C?C:S)?n:t,B=Object.assign(Object.assign({},E),f),H=a.createElement("div",Object.assign({},k,{style:B,className:R,"aria-live":"polite","aria-busy":z}),a.createElement(u,{prefixCls:I,indicator:D,percent:_}),p&&(j||v)?a.createElement("div",{className:`${I}-text`},p):null);return T(j?a.createElement("div",Object.assign({},k,{className:(0,r.default)(`${I}-nested-loading`,g,N,M)}),z&&a.createElement("div",{key:"loading"},H),a.createElement("div",{className:P,key:"container"},h)):v?a.createElement("div",{className:(0,r.default)(`${I}-fullscreen`,{[`${I}-fullscreen-show`]:z},d,N,M)},H):H)};C.setDefaultIndicator=e=>{t=e},e.s(["default",0,C],244451)},482725,e=>{"use strict";var t=e.i(244451);e.s(["Spin",()=>t.default])},597440,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let r={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M360 184h-8c4.4 0 8-3.6 8-8v8h304v-8c0 4.4 3.6 8 8 8h-8v72h72v-80c0-35.3-28.7-64-64-64H352c-35.3 0-64 28.7-64 64v80h72v-72zm504 72H160c-17.7 0-32 14.3-32 32v32c0 4.4 3.6 8 8 8h60.4l24.7 523c1.6 34.1 29.8 61 63.9 61h454c34.2 0 62.3-26.8 63.9-61l24.7-523H888c4.4 0 8-3.6 8-8v-32c0-17.7-14.3-32-32-32zM731.3 840H292.7l-24.2-512h487l-24.2 512z"}}]},name:"delete",theme:"outlined"};var o=e.i(9583),n=a.forwardRef(function(e,n){return a.createElement(o.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["default",0,n],597440)},797672,e=>{"use strict";var t=e.i(271645);let a=t.forwardRef(function(e,a){return t.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:a},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"}))});e.s(["PencilIcon",0,a],797672)},981339,e=>{"use strict";var t=e.i(185793);e.s(["Skeleton",()=>t.default])},653496,e=>{"use strict";var t=e.i(721369);e.s(["Tabs",()=>t.default])},983561,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let r={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"};var o=e.i(9583),n=a.forwardRef(function(e,n){return a.createElement(o.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["RobotOutlined",0,n],983561)},992619,e=>{"use strict";var t=e.i(843476),a=e.i(271645),r=e.i(779241),o=e.i(599724),n=e.i(199133),i=e.i(983561),l=e.i(689020);e.s(["default",0,({accessToken:e,value:s,placeholder:c="Select a Model",onChange:d,disabled:u=!1,style:m,className:p,showLabel:g=!0,labelText:f="Select Model"})=>{let[h,v]=(0,a.useState)(s),[b,x]=(0,a.useState)(!1),[y,C]=(0,a.useState)([]),$=(0,a.useRef)(null);return(0,a.useEffect)(()=>{v(s)},[s]),(0,a.useEffect)(()=>{e&&(async()=>{try{let t=await (0,l.fetchAvailableModels)(e);console.log("Fetched models for selector:",t),t.length>0&&C(t)}catch(e){console.error("Error fetching model info:",e)}})()},[e]),(0,t.jsxs)("div",{children:[g&&(0,t.jsxs)(o.Text,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,t.jsx)(i.RobotOutlined,{className:"mr-2"})," ",f]}),(0,t.jsx)(n.Select,{value:h,placeholder:c,onChange:e=>{"custom"===e?(x(!0),v(void 0)):(x(!1),v(e),d&&d(e))},options:[...Array.from(new Set(y.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%",...m},showSearch:!0,className:`rounded-md ${p||""}`,disabled:u}),b&&(0,t.jsx)(r.TextInput,{className:"mt-2",placeholder:"Enter custom model name",onValueChange:e=>{$.current&&clearTimeout($.current),$.current=setTimeout(()=>{v(e),d&&d(e)},500)},disabled:u})]})}])},829672,836938,310730,e=>{"use strict";e.i(247167);var t=e.i(271645),a=e.i(343794),r=e.i(914949),o=e.i(404948);let n=e=>e?"function"==typeof e?e():e:null;e.s(["getRenderPropValue",0,n],836938);var i=e.i(613541),l=e.i(763731),s=e.i(242064),c=e.i(491816);e.i(793154);var d=e.i(880476),u=e.i(183293),m=e.i(717356),p=e.i(320560),g=e.i(307358),f=e.i(246422),h=e.i(838378),v=e.i(617933);let b=(0,f.genStyleHooks)("Popover",e=>{let{colorBgElevated:t,colorText:a}=e,r=(0,h.mergeToken)(e,{popoverBg:t,popoverColor:a});return[(e=>{let{componentCls:t,popoverColor:a,titleMinWidth:r,fontWeightStrong:o,innerPadding:n,boxShadowSecondary:i,colorTextHeading:l,borderRadiusLG:s,zIndexPopup:c,titleMarginBottom:d,colorBgElevated:m,popoverBg:g,titleBorderBottom:f,innerContentPadding:h,titlePadding:v}=e;return[{[t]:Object.assign(Object.assign({},(0,u.resetComponent)(e)),{position:"absolute",top:0,left:{_skip_check_:!0,value:0},zIndex:c,fontWeight:"normal",whiteSpace:"normal",textAlign:"start",cursor:"auto",userSelect:"text","--valid-offset-x":"var(--arrow-offset-horizontal, var(--arrow-x))",transformOrigin:"var(--valid-offset-x, 50%) var(--arrow-y, 50%)","--antd-arrow-background-color":m,width:"max-content",maxWidth:"100vw","&-rtl":{direction:"rtl"},"&-hidden":{display:"none"},[`${t}-content`]:{position:"relative"},[`${t}-inner`]:{backgroundColor:g,backgroundClip:"padding-box",borderRadius:s,boxShadow:i,padding:n},[`${t}-title`]:{minWidth:r,marginBottom:d,color:l,fontWeight:o,borderBottom:f,padding:v},[`${t}-inner-content`]:{color:a,padding:h}})},(0,p.default)(e,"var(--antd-arrow-background-color)"),{[`${t}-pure`]:{position:"relative",maxWidth:"none",margin:e.sizePopupArrow,display:"inline-block",[`${t}-content`]:{display:"inline-block"}}}]})(r),(e=>{let{componentCls:t}=e;return{[t]:v.PresetColors.map(a=>{let r=e[`${a}6`];return{[`&${t}-${a}`]:{"--antd-arrow-background-color":r,[`${t}-inner`]:{backgroundColor:r},[`${t}-arrow`]:{background:"transparent"}}}})}})(r),(0,m.initZoomMotion)(r,"zoom-big")]},e=>{let{lineWidth:t,controlHeight:a,fontHeight:r,padding:o,wireframe:n,zIndexPopupBase:i,borderRadiusLG:l,marginXS:s,lineType:c,colorSplit:d,paddingSM:u}=e,m=a-r;return Object.assign(Object.assign(Object.assign({titleMinWidth:177,zIndexPopup:i+30},(0,g.getArrowToken)(e)),(0,p.getArrowOffsetToken)({contentRadius:l,limitVerticalRadius:!0})),{innerPadding:12*!n,titleMarginBottom:n?0:s,titlePadding:n?`${m/2}px ${o}px ${m/2-t}px`:0,titleBorderBottom:n?`${t}px ${c} ${d}`:"none",innerContentPadding:n?`${u}px ${o}px`:0})},{resetStyle:!1,deprecatedTokens:[["width","titleMinWidth"],["minWidth","titleMinWidth"]]});var x=function(e,t){var a={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(a[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);ot.indexOf(r[o])&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(a[r[o]]=e[r[o]]);return a};let y=({title:e,content:a,prefixCls:r})=>e||a?t.createElement(t.Fragment,null,e&&t.createElement("div",{className:`${r}-title`},e),a&&t.createElement("div",{className:`${r}-inner-content`},a)):null,C=e=>{let{hashId:r,prefixCls:o,className:i,style:l,placement:s="top",title:c,content:u,children:m}=e,p=n(c),g=n(u),f=(0,a.default)(r,o,`${o}-pure`,`${o}-placement-${s}`,i);return t.createElement("div",{className:f,style:l},t.createElement("div",{className:`${o}-arrow`}),t.createElement(d.Popup,Object.assign({},e,{className:r,prefixCls:o}),m||t.createElement(y,{prefixCls:o,title:p,content:g})))},$=e=>{let{prefixCls:r,className:o}=e,n=x(e,["prefixCls","className"]),{getPrefixCls:i}=t.useContext(s.ConfigContext),l=i("popover",r),[c,d,u]=b(l);return c(t.createElement(C,Object.assign({},n,{prefixCls:l,hashId:d,className:(0,a.default)(o,u)})))};e.s(["Overlay",0,y,"default",0,$],310730);var k=function(e,t){var a={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(a[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);ot.indexOf(r[o])&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(a[r[o]]=e[r[o]]);return a};let O=t.forwardRef((e,d)=>{var u,m;let{prefixCls:p,title:g,content:f,overlayClassName:h,placement:v="top",trigger:x="hover",children:C,mouseEnterDelay:$=.1,mouseLeaveDelay:O=.1,onOpenChange:w,overlayStyle:A={},styles:E,classNames:S}=e,I=k(e,["prefixCls","title","content","overlayClassName","placement","trigger","children","mouseEnterDelay","mouseLeaveDelay","onOpenChange","overlayStyle","styles","classNames"]),{getPrefixCls:T,className:N,style:M,classNames:z,styles:L}=(0,s.useComponentConfig)("popover"),_=T("popover",p),[j,R,P]=b(_),D=T(),B=(0,a.default)(h,R,P,N,z.root,null==S?void 0:S.root),H=(0,a.default)(z.body,null==S?void 0:S.body),[V,W]=(0,r.default)(!1,{value:null!=(u=e.open)?u:e.visible,defaultValue:null!=(m=e.defaultOpen)?m:e.defaultVisible}),F=(e,t)=>{W(e,!0),null==w||w(e,t)},G=n(g),X=n(f);return j(t.createElement(c.default,Object.assign({placement:v,trigger:x,mouseEnterDelay:$,mouseLeaveDelay:O},I,{prefixCls:_,classNames:{root:B,body:H},styles:{root:Object.assign(Object.assign(Object.assign(Object.assign({},L.root),M),A),null==E?void 0:E.root),body:Object.assign(Object.assign({},L.body),null==E?void 0:E.body)},ref:d,open:V,onOpenChange:e=>{F(e)},overlay:G||X?t.createElement(y,{prefixCls:_,title:G,content:X}):null,transitionName:(0,i.getTransitionName)(D,"zoom-big",I.transitionName),"data-popover-inject":!0}),(0,l.cloneElement)(C,{onKeyDown:e=>{var a,r;(0,t.isValidElement)(C)&&(null==(r=null==C?void 0:(a=C.props).onKeyDown)||r.call(a,e)),e.keyCode===o.default.ESC&&F(!1,e)}})))});O._InternalPanelDoNotUseOrYouWillBeFired=$,e.s(["default",0,O],829672)},282786,e=>{"use strict";var t=e.i(829672);e.s(["Popover",()=>t.default])},751904,e=>{"use strict";var t=e.i(401361);e.s(["EditOutlined",()=>t.default])},94629,e=>{"use strict";var t=e.i(271645);let a=t.forwardRef(function(e,a){return t.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:a},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4"}))});e.s(["SwitchVerticalIcon",0,a],94629)},991124,e=>{"use strict";let t=(0,e.i(475254).default)("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"}]]);e.s(["default",()=>t])},678784,678745,e=>{"use strict";let t=(0,e.i(475254).default)("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);e.s(["default",()=>t],678745),e.s(["CheckIcon",()=>t],678784)},118366,e=>{"use strict";var t=e.i(991124);e.s(["CopyIcon",()=>t.default])},211576,e=>{"use strict";var t=e.i(131757);e.s(["Col",()=>t.default])},837007,e=>{"use strict";var t=e.i(603908);e.s(["PlusIcon",()=>t.default])},573421,e=>{"use strict";e.i(247167);var t=e.i(8211),a=e.i(271645),r=e.i(343794),o=e.i(887719),n=e.i(908206),i=e.i(242064),l=e.i(721132),s=e.i(517455),c=e.i(264042),d=e.i(150073),u=e.i(165370),m=e.i(244451);let p=a.default.createContext({});p.Consumer;var g=e.i(763731),f=e.i(211576),h=function(e,t){var a={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(a[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);ot.indexOf(r[o])&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(a[r[o]]=e[r[o]]);return a};let v=a.default.forwardRef((e,t)=>{let o,{prefixCls:n,children:l,actions:s,extra:c,styles:d,className:u,classNames:m,colStyle:v}=e,b=h(e,["prefixCls","children","actions","extra","styles","className","classNames","colStyle"]),{grid:x,itemLayout:y}=(0,a.useContext)(p),{getPrefixCls:C,list:$}=(0,a.useContext)(i.ConfigContext),k=e=>{var t,a;return(0,r.default)(null==(a=null==(t=null==$?void 0:$.item)?void 0:t.classNames)?void 0:a[e],null==m?void 0:m[e])},O=e=>{var t,a;return Object.assign(Object.assign({},null==(a=null==(t=null==$?void 0:$.item)?void 0:t.styles)?void 0:a[e]),null==d?void 0:d[e])},w=C("list",n),A=s&&s.length>0&&a.default.createElement("ul",{className:(0,r.default)(`${w}-item-action`,k("actions")),key:"actions",style:O("actions")},s.map((e,t)=>a.default.createElement("li",{key:`${w}-item-action-${t}`},e,t!==s.length-1&&a.default.createElement("em",{className:`${w}-item-action-split`})))),E=a.default.createElement(x?"div":"li",Object.assign({},b,x?{}:{ref:t},{className:(0,r.default)(`${w}-item`,{[`${w}-item-no-flex`]:!("vertical"===y?!!c:(o=!1,a.Children.forEach(l,e=>{"string"==typeof e&&(o=!0)}),!(o&&a.Children.count(l)>1)))},u)}),"vertical"===y&&c?[a.default.createElement("div",{className:`${w}-item-main`,key:"content"},l,A),a.default.createElement("div",{className:(0,r.default)(`${w}-item-extra`,k("extra")),key:"extra",style:O("extra")},c)]:[l,A,(0,g.cloneElement)(c,{key:"extra"})]);return x?a.default.createElement(f.Col,{ref:t,flex:1,style:v},E):E});v.Meta=e=>{var{prefixCls:t,className:o,avatar:n,title:l,description:s}=e,c=h(e,["prefixCls","className","avatar","title","description"]);let{getPrefixCls:d}=(0,a.useContext)(i.ConfigContext),u=d("list",t),m=(0,r.default)(`${u}-item-meta`,o),p=a.default.createElement("div",{className:`${u}-item-meta-content`},l&&a.default.createElement("h4",{className:`${u}-item-meta-title`},l),s&&a.default.createElement("div",{className:`${u}-item-meta-description`},s));return a.default.createElement("div",Object.assign({},c,{className:m}),n&&a.default.createElement("div",{className:`${u}-item-meta-avatar`},n),(l||s)&&p)},e.i(296059);var b=e.i(915654),x=e.i(183293),y=e.i(246422),C=e.i(838378);let $=(0,y.genStyleHooks)("List",e=>{let t=(0,C.mergeToken)(e,{listBorderedCls:`${e.componentCls}-bordered`,minHeight:e.controlHeightLG});return[(e=>{let{componentCls:t,antCls:a,controlHeight:r,minHeight:o,paddingSM:n,marginLG:i,padding:l,itemPadding:s,colorPrimary:c,itemPaddingSM:d,itemPaddingLG:u,paddingXS:m,margin:p,colorText:g,colorTextDescription:f,motionDurationSlow:h,lineWidth:v,headerBg:y,footerBg:C,emptyTextPadding:$,metaMarginBottom:k,avatarMarginRight:O,titleMarginBottom:w,descriptionFontSize:A}=e;return{[t]:Object.assign(Object.assign({},(0,x.resetComponent)(e)),{position:"relative","--rc-virtual-list-scrollbar-bg":e.colorSplit,"*":{outline:"none"},[`${t}-header`]:{background:y},[`${t}-footer`]:{background:C},[`${t}-header, ${t}-footer`]:{paddingBlock:n},[`${t}-pagination`]:{marginBlockStart:i,[`${a}-pagination-options`]:{textAlign:"start"}},[`${t}-spin`]:{minHeight:o,textAlign:"center"},[`${t}-items`]:{margin:0,padding:0,listStyle:"none"},[`${t}-item`]:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:s,color:g,[`${t}-item-meta`]:{display:"flex",flex:1,alignItems:"flex-start",maxWidth:"100%",[`${t}-item-meta-avatar`]:{marginInlineEnd:O},[`${t}-item-meta-content`]:{flex:"1 0",width:0,color:g},[`${t}-item-meta-title`]:{margin:`0 0 ${(0,b.unit)(e.marginXXS)} 0`,color:g,fontSize:e.fontSize,lineHeight:e.lineHeight,"> a":{color:g,transition:`all ${h}`,"&:hover":{color:c}}},[`${t}-item-meta-description`]:{color:f,fontSize:A,lineHeight:e.lineHeight}},[`${t}-item-action`]:{flex:"0 0 auto",marginInlineStart:e.marginXXL,padding:0,fontSize:0,listStyle:"none","& > li":{position:"relative",display:"inline-block",padding:`0 ${(0,b.unit)(m)}`,color:f,fontSize:e.fontSize,lineHeight:e.lineHeight,textAlign:"center","&:first-child":{paddingInlineStart:0}},[`${t}-item-action-split`]:{position:"absolute",insetBlockStart:"50%",insetInlineEnd:0,width:v,height:e.calc(e.fontHeight).sub(e.calc(e.marginXXS).mul(2)).equal(),transform:"translateY(-50%)",backgroundColor:e.colorSplit}}},[`${t}-empty`]:{padding:`${(0,b.unit)(l)} 0`,color:f,fontSize:e.fontSizeSM,textAlign:"center"},[`${t}-empty-text`]:{padding:$,color:e.colorTextDisabled,fontSize:e.fontSize,textAlign:"center"},[`${t}-item-no-flex`]:{display:"block"}}),[`${t}-grid ${a}-col > ${t}-item`]:{display:"block",maxWidth:"100%",marginBlockEnd:p,paddingBlock:0,borderBlockEnd:"none"},[`${t}-vertical ${t}-item`]:{alignItems:"initial",[`${t}-item-main`]:{display:"block",flex:1},[`${t}-item-extra`]:{marginInlineStart:i},[`${t}-item-meta`]:{marginBlockEnd:k,[`${t}-item-meta-title`]:{marginBlockStart:0,marginBlockEnd:w,color:g,fontSize:e.fontSizeLG,lineHeight:e.lineHeightLG}},[`${t}-item-action`]:{marginBlockStart:l,marginInlineStart:"auto","> li":{padding:`0 ${(0,b.unit)(l)}`,"&:first-child":{paddingInlineStart:0}}}},[`${t}-split ${t}-item`]:{borderBlockEnd:`${(0,b.unit)(e.lineWidth)} ${e.lineType} ${e.colorSplit}`,"&:last-child":{borderBlockEnd:"none"}},[`${t}-split ${t}-header`]:{borderBlockEnd:`${(0,b.unit)(e.lineWidth)} ${e.lineType} ${e.colorSplit}`},[`${t}-split${t}-empty ${t}-footer`]:{borderTop:`${(0,b.unit)(e.lineWidth)} ${e.lineType} ${e.colorSplit}`},[`${t}-loading ${t}-spin-nested-loading`]:{minHeight:r},[`${t}-split${t}-something-after-last-item ${a}-spin-container > ${t}-items > ${t}-item:last-child`]:{borderBlockEnd:`${(0,b.unit)(e.lineWidth)} ${e.lineType} ${e.colorSplit}`},[`${t}-lg ${t}-item`]:{padding:u},[`${t}-sm ${t}-item`]:{padding:d},[`${t}:not(${t}-vertical)`]:{[`${t}-item-no-flex`]:{[`${t}-item-action`]:{float:"right"}}}}})(t),(e=>{let{listBorderedCls:t,componentCls:a,paddingLG:r,margin:o,itemPaddingSM:n,itemPaddingLG:i,marginLG:l,borderRadiusLG:s}=e,c=(0,b.unit)(e.calc(s).sub(e.lineWidth).equal());return{[t]:{border:`${(0,b.unit)(e.lineWidth)} ${e.lineType} ${e.colorBorder}`,borderRadius:s,[`${a}-header`]:{borderRadius:`${c} ${c} 0 0`},[`${a}-footer`]:{borderRadius:`0 0 ${c} ${c}`},[`${a}-header,${a}-footer,${a}-item`]:{paddingInline:r},[`${a}-pagination`]:{margin:`${(0,b.unit)(o)} ${(0,b.unit)(l)}`}},[`${t}${a}-sm`]:{[`${a}-item,${a}-header,${a}-footer`]:{padding:n}},[`${t}${a}-lg`]:{[`${a}-item,${a}-header,${a}-footer`]:{padding:i}}}})(t),(e=>{let{componentCls:t,screenSM:a,screenMD:r,marginLG:o,marginSM:n,margin:i}=e;return{[`@media screen and (max-width:${r}px)`]:{[t]:{[`${t}-item`]:{[`${t}-item-action`]:{marginInlineStart:o}}},[`${t}-vertical`]:{[`${t}-item`]:{[`${t}-item-extra`]:{marginInlineStart:o}}}},[`@media screen and (max-width: ${a}px)`]:{[t]:{[`${t}-item`]:{flexWrap:"wrap",[`${t}-action`]:{marginInlineStart:n}}},[`${t}-vertical`]:{[`${t}-item`]:{flexWrap:"wrap-reverse",[`${t}-item-main`]:{minWidth:e.contentWidth},[`${t}-item-extra`]:{margin:`auto auto ${(0,b.unit)(i)}`}}}}}})(t)]},e=>({contentWidth:220,itemPadding:`${(0,b.unit)(e.paddingContentVertical)} 0`,itemPaddingSM:`${(0,b.unit)(e.paddingContentVerticalSM)} ${(0,b.unit)(e.paddingContentHorizontal)}`,itemPaddingLG:`${(0,b.unit)(e.paddingContentVerticalLG)} ${(0,b.unit)(e.paddingContentHorizontalLG)}`,headerBg:"transparent",footerBg:"transparent",emptyTextPadding:e.padding,metaMarginBottom:e.padding,avatarMarginRight:e.padding,titleMarginBottom:e.paddingSM,descriptionFontSize:e.fontSize}));var k=function(e,t){var a={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(a[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);ot.indexOf(r[o])&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(a[r[o]]=e[r[o]]);return a};let O=a.forwardRef(function(e,g){let{pagination:f=!1,prefixCls:h,bordered:v=!1,split:b=!0,className:x,rootClassName:y,style:C,children:O,itemLayout:w,loadMore:A,grid:E,dataSource:S=[],size:I,header:T,footer:N,loading:M=!1,rowKey:z,renderItem:L,locale:_}=e,j=k(e,["pagination","prefixCls","bordered","split","className","rootClassName","style","children","itemLayout","loadMore","grid","dataSource","size","header","footer","loading","rowKey","renderItem","locale"]),R=f&&"object"==typeof f?f:{},[P,D]=a.useState(R.defaultCurrent||1),[B,H]=a.useState(R.defaultPageSize||10),{getPrefixCls:V,direction:W,className:F,style:G}=(0,i.useComponentConfig)("list"),{renderEmpty:X}=a.useContext(i.ConfigContext),U=e=>(t,a)=>{var r;D(t),H(a),f&&(null==(r=null==f?void 0:f[e])||r.call(f,t,a))},q=U("onChange"),K=U("onShowSizeChange"),Y=!!(A||f||N),Z=V("list",h),[J,Q,ee]=$(Z),et=M;"boolean"==typeof et&&(et={spinning:et});let ea=!!(null==et?void 0:et.spinning),er=(0,s.default)(I),eo="";switch(er){case"large":eo="lg";break;case"small":eo="sm"}let en=(0,r.default)(Z,{[`${Z}-vertical`]:"vertical"===w,[`${Z}-${eo}`]:eo,[`${Z}-split`]:b,[`${Z}-bordered`]:v,[`${Z}-loading`]:ea,[`${Z}-grid`]:!!E,[`${Z}-something-after-last-item`]:Y,[`${Z}-rtl`]:"rtl"===W},F,x,y,Q,ee),ei=(0,o.default)({current:1,total:0,position:"bottom"},{total:S.length,current:P,pageSize:B},f||{}),el=Math.ceil(ei.total/ei.pageSize);ei.current=Math.min(ei.current,el);let es=f&&a.createElement("div",{className:(0,r.default)(`${Z}-pagination`)},a.createElement(u.default,Object.assign({align:"end"},ei,{onChange:q,onShowSizeChange:K}))),ec=(0,t.default)(S);f&&S.length>(ei.current-1)*ei.pageSize&&(ec=(0,t.default)(S).splice((ei.current-1)*ei.pageSize,ei.pageSize));let ed=Object.keys(E||{}).some(e=>["xs","sm","md","lg","xl","xxl"].includes(e)),eu=(0,d.default)(ed),em=a.useMemo(()=>{for(let e=0;e{if(!E)return;let e=em&&E[em]?E[em]:E.column;if(e)return{width:`${100/e}%`,maxWidth:`${100/e}%`}},[JSON.stringify(E),em]),eg=ea&&a.createElement("div",{style:{minHeight:53}});if(ec.length>0){let e=ec.map((e,t)=>{let r;return L?((r="function"==typeof z?z(e):z?e[z]:e.key)||(r=`list-item-${t}`),a.createElement(a.Fragment,{key:r},L(e,t))):null});eg=E?a.createElement(c.Row,{gutter:E.gutter},a.Children.map(e,e=>a.createElement("div",{key:null==e?void 0:e.key,style:ep},e))):a.createElement("ul",{className:`${Z}-items`},e)}else O||ea||(eg=a.createElement("div",{className:`${Z}-empty-text`},(null==_?void 0:_.emptyText)||(null==X?void 0:X("List"))||a.createElement(l.default,{componentName:"List"})));let ef=ei.position,eh=a.useMemo(()=>({grid:E,itemLayout:w}),[JSON.stringify(E),w]);return J(a.createElement(p.Provider,{value:eh},a.createElement("div",Object.assign({ref:g,style:Object.assign(Object.assign({},G),C),className:en},j),("top"===ef||"both"===ef)&&es,T&&a.createElement("div",{className:`${Z}-header`},T),a.createElement(m.default,Object.assign({},et),eg,O),N&&a.createElement("div",{className:`${Z}-footer`},N),A||("bottom"===ef||"both"===ef)&&es)))});O.Item=v,e.s(["List",0,O],573421)},219470,812618,e=>{"use strict";e.s(["coy",0,{'code[class*="language-"]':{color:"black",background:"none",fontFamily:"Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace",fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",maxHeight:"inherit",height:"inherit",padding:"0 1em",display:"block",overflow:"auto"},'pre[class*="language-"]':{color:"black",background:"none",fontFamily:"Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace",fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",position:"relative",margin:".5em 0",overflow:"visible",padding:"1px",backgroundColor:"#fdfdfd",WebkitBoxSizing:"border-box",MozBoxSizing:"border-box",boxSizing:"border-box",marginBottom:"1em"},'pre[class*="language-"] > code':{position:"relative",zIndex:"1",borderLeft:"10px solid #358ccb",boxShadow:"-1px 0px 0px 0px #358ccb, 0px 0px 0px 1px #dfdfdf",backgroundColor:"#fdfdfd",backgroundImage:"linear-gradient(transparent 50%, rgba(69, 142, 209, 0.04) 50%)",backgroundSize:"3em 3em",backgroundOrigin:"content-box",backgroundAttachment:"local"},':not(pre) > code[class*="language-"]':{backgroundColor:"#fdfdfd",WebkitBoxSizing:"border-box",MozBoxSizing:"border-box",boxSizing:"border-box",marginBottom:"1em",position:"relative",padding:".2em",borderRadius:"0.3em",color:"#c92c2c",border:"1px solid rgba(0, 0, 0, 0.1)",display:"inline",whiteSpace:"normal"},'pre[class*="language-"]:before':{content:"''",display:"block",position:"absolute",bottom:"0.75em",left:"0.18em",width:"40%",height:"20%",maxHeight:"13em",boxShadow:"0px 13px 8px #979797",WebkitTransform:"rotate(-2deg)",MozTransform:"rotate(-2deg)",msTransform:"rotate(-2deg)",OTransform:"rotate(-2deg)",transform:"rotate(-2deg)"},'pre[class*="language-"]:after':{content:"''",display:"block",position:"absolute",bottom:"0.75em",left:"auto",width:"40%",height:"20%",maxHeight:"13em",boxShadow:"0px 13px 8px #979797",WebkitTransform:"rotate(2deg)",MozTransform:"rotate(2deg)",msTransform:"rotate(2deg)",OTransform:"rotate(2deg)",transform:"rotate(2deg)",right:"0.75em"},comment:{color:"#7D8B99"},"block-comment":{color:"#7D8B99"},prolog:{color:"#7D8B99"},doctype:{color:"#7D8B99"},cdata:{color:"#7D8B99"},punctuation:{color:"#5F6364"},property:{color:"#c92c2c"},tag:{color:"#c92c2c"},boolean:{color:"#c92c2c"},number:{color:"#c92c2c"},"function-name":{color:"#c92c2c"},constant:{color:"#c92c2c"},symbol:{color:"#c92c2c"},deleted:{color:"#c92c2c"},selector:{color:"#2f9c0a"},"attr-name":{color:"#2f9c0a"},string:{color:"#2f9c0a"},char:{color:"#2f9c0a"},function:{color:"#2f9c0a"},builtin:{color:"#2f9c0a"},inserted:{color:"#2f9c0a"},operator:{color:"#a67f59",background:"rgba(255, 255, 255, 0.5)"},entity:{color:"#a67f59",background:"rgba(255, 255, 255, 0.5)",cursor:"help"},url:{color:"#a67f59",background:"rgba(255, 255, 255, 0.5)"},variable:{color:"#a67f59",background:"rgba(255, 255, 255, 0.5)"},atrule:{color:"#1990b8"},"attr-value":{color:"#1990b8"},keyword:{color:"#1990b8"},"class-name":{color:"#1990b8"},regex:{color:"#e90"},important:{color:"#e90",fontWeight:"normal"},".language-css .token.string":{color:"#a67f59",background:"rgba(255, 255, 255, 0.5)"},".style .token.string":{color:"#a67f59",background:"rgba(255, 255, 255, 0.5)"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},namespace:{Opacity:".7"},'pre[class*="language-"].line-numbers.line-numbers':{paddingLeft:"0"},'pre[class*="language-"].line-numbers.line-numbers code':{paddingLeft:"3.8em"},'pre[class*="language-"].line-numbers.line-numbers .line-numbers-rows':{left:"0"},'pre[class*="language-"][data-line]':{paddingTop:"0",paddingBottom:"0",paddingLeft:"0"},"pre[data-line] code":{position:"relative",paddingLeft:"4em"},"pre .line-highlight":{marginTop:"0"}}],219470),e.i(247167);var t=e.i(931067),a=e.i(271645);let r={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M632 888H392c-4.4 0-8 3.6-8 8v32c0 17.7 14.3 32 32 32h192c17.7 0 32-14.3 32-32v-32c0-4.4-3.6-8-8-8zM512 64c-181.1 0-328 146.9-328 328 0 121.4 66 227.4 164 284.1V792c0 17.7 14.3 32 32 32h264c17.7 0 32-14.3 32-32V676.1c98-56.7 164-162.7 164-284.1 0-181.1-146.9-328-328-328zm127.9 549.8L604 634.6V752H420V634.6l-35.9-20.8C305.4 568.3 256 484.5 256 392c0-141.4 114.6-256 256-256s256 114.6 256 256c0 92.5-49.4 176.3-128.1 221.8z"}}]},name:"bulb",theme:"outlined"};var o=e.i(9583),n=a.forwardRef(function(e,n){return a.createElement(o.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["BulbOutlined",0,n],812618)},458505,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let r={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"};var o=e.i(9583),n=a.forwardRef(function(e,n){return a.createElement(o.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["DollarOutlined",0,n],458505)},245094,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let r={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M516 673c0 4.4 3.4 8 7.5 8h185c4.1 0 7.5-3.6 7.5-8v-48c0-4.4-3.4-8-7.5-8h-185c-4.1 0-7.5 3.6-7.5 8v48zm-194.9 6.1l192-161c3.8-3.2 3.8-9.1 0-12.3l-192-160.9A7.95 7.95 0 00308 351v62.7c0 2.4 1 4.6 2.9 6.1L420.7 512l-109.8 92.2a8.1 8.1 0 00-2.9 6.1V673c0 6.8 7.9 10.5 13.1 6.1zM880 112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32zm-40 728H184V184h656v656z"}}]},name:"code",theme:"outlined"};var o=e.i(9583),n=a.forwardRef(function(e,n){return a.createElement(o.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["CodeOutlined",0,n],245094)},872934,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let r={icon:{tag:"svg",attrs:{"fill-rule":"evenodd",viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M880 912H144c-17.7 0-32-14.3-32-32V144c0-17.7 14.3-32 32-32h360c4.4 0 8 3.6 8 8v56c0 4.4-3.6 8-8 8H184v656h656V520c0-4.4 3.6-8 8-8h56c4.4 0 8 3.6 8 8v360c0 17.7-14.3 32-32 32zM770.87 199.13l-52.2-52.2a8.01 8.01 0 014.7-13.6l179.4-21c5.1-.6 9.5 3.7 8.9 8.9l-21 179.4c-.8 6.6-8.9 9.4-13.6 4.7l-52.4-52.4-256.2 256.2a8.03 8.03 0 01-11.3 0l-42.4-42.4a8.03 8.03 0 010-11.3l256.1-256.3z"}}]},name:"export",theme:"outlined"};var o=e.i(9583),n=a.forwardRef(function(e,n){return a.createElement(o.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["ExportOutlined",0,n],872934)},447593,989022,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645),r={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"defs",attrs:{},children:[{tag:"style",attrs:{}}]},{tag:"path",attrs:{d:"M899.1 869.6l-53-305.6H864c14.4 0 26-11.6 26-26V346c0-14.4-11.6-26-26-26H618V138c0-14.4-11.6-26-26-26H432c-14.4 0-26 11.6-26 26v182H160c-14.4 0-26 11.6-26 26v192c0 14.4 11.6 26 26 26h17.9l-53 305.6a25.95 25.95 0 0025.6 30.4h723c1.5 0 3-.1 4.4-.4a25.88 25.88 0 0021.2-30zM204 390h272V182h72v208h272v104H204V390zm468 440V674c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v156H416V674c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v156H202.8l45.1-260H776l45.1 260H672z"}}]},name:"clear",theme:"outlined"},o=e.i(9583),n=a.forwardRef(function(e,n){return a.createElement(o.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["ClearOutlined",0,n],447593);var i=e.i(843476),l=e.i(592968),s=e.i(637235);let c={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M872 394c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8H708V152c0-4.4-3.6-8-8-8h-64c-4.4 0-8 3.6-8 8v166H400V152c0-4.4-3.6-8-8-8h-64c-4.4 0-8 3.6-8 8v166H152c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h168v236H152c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h168v166c0 4.4 3.6 8 8 8h64c4.4 0 8-3.6 8-8V706h228v166c0 4.4 3.6 8 8 8h64c4.4 0 8-3.6 8-8V706h164c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8H708V394h164zM628 630H400V394h228v236z"}}]},name:"number",theme:"outlined"};var d=a.forwardRef(function(e,r){return a.createElement(o.default,(0,t.default)({},e,{ref:r,icon:c}))});let u={icon:{tag:"svg",attrs:{"fill-rule":"evenodd",viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M880 912H144c-17.7 0-32-14.3-32-32V144c0-17.7 14.3-32 32-32h360c4.4 0 8 3.6 8 8v56c0 4.4-3.6 8-8 8H184v656h656V520c0-4.4 3.6-8 8-8h56c4.4 0 8 3.6 8 8v360c0 17.7-14.3 32-32 32zM653.3 424.6l52.2 52.2a8.01 8.01 0 01-4.7 13.6l-179.4 21c-5.1.6-9.5-3.7-8.9-8.9l21-179.4c.8-6.6 8.9-9.4 13.6-4.7l52.4 52.4 256.2-256.2c3.1-3.1 8.2-3.1 11.3 0l42.4 42.4c3.1 3.1 3.1 8.2 0 11.3L653.3 424.6z"}}]},name:"import",theme:"outlined"};var m=a.forwardRef(function(e,r){return a.createElement(o.default,(0,t.default)({},e,{ref:r,icon:u}))}),p=e.i(872934),g=e.i(812618),f=e.i(366308),h=e.i(458505);e.s(["default",0,({timeToFirstToken:e,totalLatency:t,usage:a,toolName:r})=>e||t||a?(0,i.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!==e&&(0,i.jsx)(l.Tooltip,{title:"Time to first token",children:(0,i.jsxs)("div",{className:"flex items-center",children:[(0,i.jsx)(s.ClockCircleOutlined,{className:"mr-1"}),(0,i.jsxs)("span",{children:["TTFT: ",(e/1e3).toFixed(2),"s"]})]})}),void 0!==t&&(0,i.jsx)(l.Tooltip,{title:"Total latency",children:(0,i.jsxs)("div",{className:"flex items-center",children:[(0,i.jsx)(s.ClockCircleOutlined,{className:"mr-1"}),(0,i.jsxs)("span",{children:["Total Latency: ",(t/1e3).toFixed(2),"s"]})]})}),a?.promptTokens!==void 0&&(0,i.jsx)(l.Tooltip,{title:"Prompt tokens",children:(0,i.jsxs)("div",{className:"flex items-center",children:[(0,i.jsx)(m,{className:"mr-1"}),(0,i.jsxs)("span",{children:["In: ",a.promptTokens]})]})}),a?.completionTokens!==void 0&&(0,i.jsx)(l.Tooltip,{title:"Completion tokens",children:(0,i.jsxs)("div",{className:"flex items-center",children:[(0,i.jsx)(p.ExportOutlined,{className:"mr-1"}),(0,i.jsxs)("span",{children:["Out: ",a.completionTokens]})]})}),a?.reasoningTokens!==void 0&&(0,i.jsx)(l.Tooltip,{title:"Reasoning tokens",children:(0,i.jsxs)("div",{className:"flex items-center",children:[(0,i.jsx)(g.BulbOutlined,{className:"mr-1"}),(0,i.jsxs)("span",{children:["Reasoning: ",a.reasoningTokens]})]})}),a?.totalTokens!==void 0&&(0,i.jsx)(l.Tooltip,{title:"Total tokens",children:(0,i.jsxs)("div",{className:"flex items-center",children:[(0,i.jsx)(d,{className:"mr-1"}),(0,i.jsxs)("span",{children:["Total: ",a.totalTokens]})]})}),a?.cost!==void 0&&(0,i.jsx)(l.Tooltip,{title:"Cost",children:(0,i.jsxs)("div",{className:"flex items-center",children:[(0,i.jsx)(h.DollarOutlined,{className:"mr-1"}),(0,i.jsxs)("span",{children:["$",a.cost.toFixed(6)]})]})}),r&&(0,i.jsx)(l.Tooltip,{title:"Tool used",children:(0,i.jsxs)("div",{className:"flex items-center",children:[(0,i.jsx)(f.ToolOutlined,{className:"mr-1"}),(0,i.jsxs)("span",{children:["Tool: ",r]})]})})]}):null],989022)},132104,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let r={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M868 545.5L536.1 163a31.96 31.96 0 00-48.3 0L156 545.5a7.97 7.97 0 006 13.2h81c4.6 0 9-2 12.1-5.5L474 300.9V864c0 4.4 3.6 8 8 8h60c4.4 0 8-3.6 8-8V300.9l218.9 252.3c3 3.5 7.4 5.5 12.1 5.5h81c6.8 0 10.5-8 6-13.2z"}}]},name:"arrow-up",theme:"outlined"};var o=e.i(9583),n=a.forwardRef(function(e,n){return a.createElement(o.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["ArrowUpOutlined",0,n],132104)},903446,e=>{"use strict";let t=(0,e.i(475254).default)("settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);e.s(["default",()=>t])},608856,e=>{"use strict";e.i(247167);var t=e.i(271645),a=e.i(343794),r=e.i(209428),o=e.i(392221),n=e.i(951160),i=e.i(174428),l=t.createContext(null),s=t.createContext({}),c=e.i(211577),d=e.i(931067),u=e.i(361275),m=e.i(404948),p=e.i(244009),g=e.i(703923),f=e.i(611935),h=["prefixCls","className","containerRef"];let v=function(e){var r=e.prefixCls,o=e.className,n=e.containerRef,i=(0,g.default)(e,h),l=t.useContext(s).panel,c=(0,f.useComposeRef)(l,n);return t.createElement("div",(0,d.default)({className:(0,a.default)("".concat(r,"-content"),o),role:"dialog",ref:c},(0,p.default)(e,{aria:!0}),{"aria-modal":"true"},i))};var b=e.i(883110);function x(e){return"string"==typeof e&&String(Number(e))===e?((0,b.default)(!1,"Invalid value type of `width` or `height` which should be number type instead."),Number(e)):e}e.i(654310);var y={width:0,height:0,overflow:"hidden",outline:"none",position:"absolute"},C=t.forwardRef(function(e,n){var i,s,g,f=e.prefixCls,h=e.open,b=e.placement,C=e.inline,$=e.push,k=e.forceRender,O=e.autoFocus,w=e.keyboard,A=e.classNames,E=e.rootClassName,S=e.rootStyle,I=e.zIndex,T=e.className,N=e.id,M=e.style,z=e.motion,L=e.width,_=e.height,j=e.children,R=e.mask,P=e.maskClosable,D=e.maskMotion,B=e.maskClassName,H=e.maskStyle,V=e.afterOpenChange,W=e.onClose,F=e.onMouseEnter,G=e.onMouseOver,X=e.onMouseLeave,U=e.onClick,q=e.onKeyDown,K=e.onKeyUp,Y=e.styles,Z=e.drawerRender,J=t.useRef(),Q=t.useRef(),ee=t.useRef();t.useImperativeHandle(n,function(){return J.current}),t.useEffect(function(){if(h&&O){var e;null==(e=J.current)||e.focus({preventScroll:!0})}},[h]);var et=t.useState(!1),ea=(0,o.default)(et,2),er=ea[0],eo=ea[1],en=t.useContext(l),ei=null!=(i=null!=(s=null==(g="boolean"==typeof $?$?{}:{distance:0}:$||{})?void 0:g.distance)?s:null==en?void 0:en.pushDistance)?i:180,el=t.useMemo(function(){return{pushDistance:ei,push:function(){eo(!0)},pull:function(){eo(!1)}}},[ei]);t.useEffect(function(){var e,t;h?null==en||null==(e=en.push)||e.call(en):null==en||null==(t=en.pull)||t.call(en)},[h]),t.useEffect(function(){return function(){var e;null==en||null==(e=en.pull)||e.call(en)}},[]);var es=t.createElement(u.default,(0,d.default)({key:"mask"},D,{visible:R&&h}),function(e,o){var n=e.className,i=e.style;return t.createElement("div",{className:(0,a.default)("".concat(f,"-mask"),n,null==A?void 0:A.mask,B),style:(0,r.default)((0,r.default)((0,r.default)({},i),H),null==Y?void 0:Y.mask),onClick:P&&h?W:void 0,ref:o})}),ec="function"==typeof z?z(b):z,ed={};if(er&&ei)switch(b){case"top":ed.transform="translateY(".concat(ei,"px)");break;case"bottom":ed.transform="translateY(".concat(-ei,"px)");break;case"left":ed.transform="translateX(".concat(ei,"px)");break;default:ed.transform="translateX(".concat(-ei,"px)")}"left"===b||"right"===b?ed.width=x(L):ed.height=x(_);var eu={onMouseEnter:F,onMouseOver:G,onMouseLeave:X,onClick:U,onKeyDown:q,onKeyUp:K},em=t.createElement(u.default,(0,d.default)({key:"panel"},ec,{visible:h,forceRender:k,onVisibleChanged:function(e){null==V||V(e)},removeOnLeave:!1,leavedClassName:"".concat(f,"-content-wrapper-hidden")}),function(o,n){var i=o.className,l=o.style,s=t.createElement(v,(0,d.default)({id:N,containerRef:n,prefixCls:f,className:(0,a.default)(T,null==A?void 0:A.content),style:(0,r.default)((0,r.default)({},M),null==Y?void 0:Y.content)},(0,p.default)(e,{aria:!0}),eu),j);return t.createElement("div",(0,d.default)({className:(0,a.default)("".concat(f,"-content-wrapper"),null==A?void 0:A.wrapper,i),style:(0,r.default)((0,r.default)((0,r.default)({},ed),l),null==Y?void 0:Y.wrapper)},(0,p.default)(e,{data:!0})),Z?Z(s):s)}),ep=(0,r.default)({},S);return I&&(ep.zIndex=I),t.createElement(l.Provider,{value:el},t.createElement("div",{className:(0,a.default)(f,"".concat(f,"-").concat(b),E,(0,c.default)((0,c.default)({},"".concat(f,"-open"),h),"".concat(f,"-inline"),C)),style:ep,tabIndex:-1,ref:J,onKeyDown:function(e){var t,a,r=e.keyCode,o=e.shiftKey;switch(r){case m.default.TAB:r===m.default.TAB&&(o||document.activeElement!==ee.current?o&&document.activeElement===Q.current&&(null==(a=ee.current)||a.focus({preventScroll:!0})):null==(t=Q.current)||t.focus({preventScroll:!0}));break;case m.default.ESC:W&&w&&(e.stopPropagation(),W(e))}}},es,t.createElement("div",{tabIndex:0,ref:Q,style:y,"aria-hidden":"true","data-sentinel":"start"}),em,t.createElement("div",{tabIndex:0,ref:ee,style:y,"aria-hidden":"true","data-sentinel":"end"})))});let $=function(e){var a=e.open,l=e.prefixCls,c=e.placement,d=e.autoFocus,u=e.keyboard,m=e.width,p=e.mask,g=void 0===p||p,f=e.maskClosable,h=e.getContainer,v=e.forceRender,b=e.afterOpenChange,x=e.destroyOnClose,y=e.onMouseEnter,$=e.onMouseOver,k=e.onMouseLeave,O=e.onClick,w=e.onKeyDown,A=e.onKeyUp,E=e.panelRef,S=t.useState(!1),I=(0,o.default)(S,2),T=I[0],N=I[1],M=t.useState(!1),z=(0,o.default)(M,2),L=z[0],_=z[1];(0,i.default)(function(){_(!0)},[]);var j=!!L&&void 0!==a&&a,R=t.useRef(),P=t.useRef();(0,i.default)(function(){j&&(P.current=document.activeElement)},[j]);var D=t.useMemo(function(){return{panel:E}},[E]);if(!v&&!T&&!j&&x)return null;var B=(0,r.default)((0,r.default)({},e),{},{open:j,prefixCls:void 0===l?"rc-drawer":l,placement:void 0===c?"right":c,autoFocus:void 0===d||d,keyboard:void 0===u||u,width:void 0===m?378:m,mask:g,maskClosable:void 0===f||f,inline:!1===h,afterOpenChange:function(e){var t,a;N(e),null==b||b(e),e||!P.current||null!=(t=R.current)&&t.contains(P.current)||null==(a=P.current)||a.focus({preventScroll:!0})},ref:R},{onMouseEnter:y,onMouseOver:$,onMouseLeave:k,onClick:O,onKeyDown:w,onKeyUp:A});return t.createElement(s.Provider,{value:D},t.createElement(n.default,{open:j||v||T,autoDestroy:!1,getContainer:h,autoLock:g&&(j||T)},t.createElement(C,B)))};var k=e.i(981444),O=e.i(617206),w=e.i(122767),A=e.i(613541),E=e.i(340010),S=e.i(242064),I=e.i(922611),T=e.i(563113),N=e.i(185793);let M=e=>{var r,o,n,i;let l,{prefixCls:s,ariaId:c,title:d,footer:u,extra:m,closable:p,loading:g,onClose:f,headerStyle:h,bodyStyle:v,footerStyle:b,children:x,classNames:y,styles:C}=e,$=(0,S.useComponentConfig)("drawer");l=!1===p?void 0:void 0===p||!0===p?"start":(null==p?void 0:p.placement)==="end"?"end":"start";let k=t.useCallback(e=>t.createElement("button",{type:"button",onClick:f,className:(0,a.default)(`${s}-close`,{[`${s}-close-${l}`]:"end"===l})},e),[f,s,l]),[O,w]=(0,T.useClosable)((0,T.pickClosable)(e),(0,T.pickClosable)($),{closable:!0,closeIconRender:k});return t.createElement(t.Fragment,null,d||O?t.createElement("div",{style:Object.assign(Object.assign(Object.assign({},null==(n=$.styles)?void 0:n.header),h),null==C?void 0:C.header),className:(0,a.default)(`${s}-header`,{[`${s}-header-close-only`]:O&&!d&&!m},null==(i=$.classNames)?void 0:i.header,null==y?void 0:y.header)},t.createElement("div",{className:`${s}-header-title`},"start"===l&&w,d&&t.createElement("div",{className:`${s}-title`,id:c},d)),m&&t.createElement("div",{className:`${s}-extra`},m),"end"===l&&w):null,t.createElement("div",{className:(0,a.default)(`${s}-body`,null==y?void 0:y.body,null==(r=$.classNames)?void 0:r.body),style:Object.assign(Object.assign(Object.assign({},null==(o=$.styles)?void 0:o.body),v),null==C?void 0:C.body)},g?t.createElement(N.default,{active:!0,title:!1,paragraph:{rows:5},className:`${s}-body-skeleton`}):x),(()=>{var e,r;if(!u)return null;let o=`${s}-footer`;return t.createElement("div",{className:(0,a.default)(o,null==(e=$.classNames)?void 0:e.footer,null==y?void 0:y.footer),style:Object.assign(Object.assign(Object.assign({},null==(r=$.styles)?void 0:r.footer),b),null==C?void 0:C.footer)},u)})())};e.i(296059);var z=e.i(915654),L=e.i(183293),_=e.i(246422),j=e.i(838378);let R=(e,t)=>({"&-enter, &-appear":Object.assign(Object.assign({},e),{"&-active":t}),"&-leave":Object.assign(Object.assign({},t),{"&-active":e})}),P=(e,t)=>Object.assign({"&-enter, &-appear, &-leave":{"&-start":{transition:"none"},"&-active":{transition:`all ${t}`}}},R({opacity:e},{opacity:1})),D=(0,_.genStyleHooks)("Drawer",e=>{let t=(0,j.mergeToken)(e,{});return[(e=>{let{borderRadiusSM:t,componentCls:a,zIndexPopup:r,colorBgMask:o,colorBgElevated:n,motionDurationSlow:i,motionDurationMid:l,paddingXS:s,padding:c,paddingLG:d,fontSizeLG:u,lineHeightLG:m,lineWidth:p,lineType:g,colorSplit:f,marginXS:h,colorIcon:v,colorIconHover:b,colorBgTextHover:x,colorBgTextActive:y,colorText:C,fontWeightStrong:$,footerPaddingBlock:k,footerPaddingInline:O,calc:w}=e,A=`${a}-content-wrapper`;return{[a]:{position:"fixed",inset:0,zIndex:r,pointerEvents:"none",color:C,"&-pure":{position:"relative",background:n,display:"flex",flexDirection:"column",[`&${a}-left`]:{boxShadow:e.boxShadowDrawerLeft},[`&${a}-right`]:{boxShadow:e.boxShadowDrawerRight},[`&${a}-top`]:{boxShadow:e.boxShadowDrawerUp},[`&${a}-bottom`]:{boxShadow:e.boxShadowDrawerDown}},"&-inline":{position:"absolute"},[`${a}-mask`]:{position:"absolute",inset:0,zIndex:r,background:o,pointerEvents:"auto"},[A]:{position:"absolute",zIndex:r,maxWidth:"100vw",transition:`all ${i}`,"&-hidden":{display:"none"}},[`&-left > ${A}`]:{top:0,bottom:0,left:{_skip_check_:!0,value:0},boxShadow:e.boxShadowDrawerLeft},[`&-right > ${A}`]:{top:0,right:{_skip_check_:!0,value:0},bottom:0,boxShadow:e.boxShadowDrawerRight},[`&-top > ${A}`]:{top:0,insetInline:0,boxShadow:e.boxShadowDrawerUp},[`&-bottom > ${A}`]:{bottom:0,insetInline:0,boxShadow:e.boxShadowDrawerDown},[`${a}-content`]:{display:"flex",flexDirection:"column",width:"100%",height:"100%",overflow:"auto",background:n,pointerEvents:"auto"},[`${a}-header`]:{display:"flex",flex:0,alignItems:"center",padding:`${(0,z.unit)(c)} ${(0,z.unit)(d)}`,fontSize:u,lineHeight:m,borderBottom:`${(0,z.unit)(p)} ${g} ${f}`,"&-title":{display:"flex",flex:1,alignItems:"center",minWidth:0,minHeight:0}},[`${a}-extra`]:{flex:"none"},[`${a}-close`]:Object.assign({display:"inline-flex",width:w(u).add(s).equal(),height:w(u).add(s).equal(),borderRadius:t,justifyContent:"center",alignItems:"center",color:v,fontWeight:$,fontSize:u,fontStyle:"normal",lineHeight:1,textAlign:"center",textTransform:"none",textDecoration:"none",background:"transparent",border:0,cursor:"pointer",transition:`all ${l}`,textRendering:"auto",[`&${a}-close-end`]:{marginInlineStart:h},[`&:not(${a}-close-end)`]:{marginInlineEnd:h},"&:hover":{color:b,backgroundColor:x,textDecoration:"none"},"&:active":{backgroundColor:y}},(0,L.genFocusStyle)(e)),[`${a}-title`]:{flex:1,margin:0,fontWeight:e.fontWeightStrong,fontSize:u,lineHeight:m},[`${a}-body`]:{flex:1,minWidth:0,minHeight:0,padding:d,overflow:"auto",[`${a}-body-skeleton`]:{width:"100%",height:"100%",display:"flex",justifyContent:"center"}},[`${a}-footer`]:{flexShrink:0,padding:`${(0,z.unit)(k)} ${(0,z.unit)(O)}`,borderTop:`${(0,z.unit)(p)} ${g} ${f}`},"&-rtl":{direction:"rtl"}}}})(t),(e=>{let{componentCls:t,motionDurationSlow:a}=e;return{[t]:{[`${t}-mask-motion`]:P(0,a),[`${t}-panel-motion`]:["left","right","top","bottom"].reduce((e,t)=>{let r;return Object.assign(Object.assign({},e),{[`&-${t}`]:[P(.7,a),R({transform:(r="100%",({left:`translateX(-${r})`,right:`translateX(${r})`,top:`translateY(-${r})`,bottom:`translateY(${r})`})[t])},{transform:"none"})]})},{})}}})(t)]},e=>({zIndexPopup:e.zIndexPopupBase,footerPaddingBlock:e.paddingXS,footerPaddingInline:e.padding}));var B=function(e,t){var a={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(a[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);ot.indexOf(r[o])&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(a[r[o]]=e[r[o]]);return a};let H={distance:180},V=e=>{let{rootClassName:r,width:o,height:n,size:i="default",mask:l=!0,push:s=H,open:c,afterOpenChange:d,onClose:u,prefixCls:m,getContainer:p,panelRef:g=null,style:h,className:v,"aria-labelledby":b,visible:x,afterVisibleChange:y,maskStyle:C,drawerStyle:T,contentWrapperStyle:N,destroyOnClose:z,destroyOnHidden:L}=e,_=B(e,["rootClassName","width","height","size","mask","push","open","afterOpenChange","onClose","prefixCls","getContainer","panelRef","style","className","aria-labelledby","visible","afterVisibleChange","maskStyle","drawerStyle","contentWrapperStyle","destroyOnClose","destroyOnHidden"]),j=(0,k.default)(),R=_.title?j:void 0,{getPopupContainer:P,getPrefixCls:V,direction:W,className:F,style:G,classNames:X,styles:U}=(0,S.useComponentConfig)("drawer"),q=V("drawer",m),[K,Y,Z]=D(q),J=void 0===p&&P?()=>P(document.body):p,Q=(0,a.default)({"no-mask":!l,[`${q}-rtl`]:"rtl"===W},r,Y,Z),ee=t.useMemo(()=>null!=o?o:"large"===i?736:378,[o,i]),et=t.useMemo(()=>null!=n?n:"large"===i?736:378,[n,i]),ea={motionName:(0,A.getTransitionName)(q,"mask-motion"),motionAppear:!0,motionEnter:!0,motionLeave:!0,motionDeadline:500},er=(0,I.usePanelRef)(),eo=(0,f.composeRef)(g,er),[en,ei]=(0,w.useZIndex)("Drawer",_.zIndex),{classNames:el={},styles:es={}}=_;return K(t.createElement(O.default,{form:!0,space:!0},t.createElement(E.default.Provider,{value:ei},t.createElement($,Object.assign({prefixCls:q,onClose:u,maskMotion:ea,motion:e=>({motionName:(0,A.getTransitionName)(q,`panel-motion-${e}`),motionAppear:!0,motionEnter:!0,motionLeave:!0,motionDeadline:500})},_,{classNames:{mask:(0,a.default)(el.mask,X.mask),content:(0,a.default)(el.content,X.content),wrapper:(0,a.default)(el.wrapper,X.wrapper)},styles:{mask:Object.assign(Object.assign(Object.assign({},es.mask),C),U.mask),content:Object.assign(Object.assign(Object.assign({},es.content),T),U.content),wrapper:Object.assign(Object.assign(Object.assign({},es.wrapper),N),U.wrapper)},open:null!=c?c:x,mask:l,push:s,width:ee,height:et,style:Object.assign(Object.assign({},G),h),className:(0,a.default)(F,v),rootClassName:Q,getContainer:J,afterOpenChange:null!=d?d:y,panelRef:eo,zIndex:en,"aria-labelledby":null!=b?b:R,destroyOnClose:null!=L?L:z}),t.createElement(M,Object.assign({prefixCls:q},_,{ariaId:R,onClose:u}))))))};V._InternalPanelDoNotUseOrYouWillBeFired=e=>{let{prefixCls:r,style:o,className:n,placement:i="right"}=e,l=B(e,["prefixCls","style","className","placement"]),{getPrefixCls:s}=t.useContext(S.ConfigContext),c=s("drawer",r),[d,u,m]=D(c),p=(0,a.default)(c,`${c}-pure`,`${c}-${i}`,u,m,n);return d(t.createElement("div",{className:p,style:o},t.createElement(M,Object.assign({prefixCls:c},l))))},e.s(["Drawer",0,V],608856)},675879,e=>{"use strict";var t=e.i(843476),a=e.i(191403),r=e.i(135214);e.s(["default",0,()=>{let{accessToken:e}=(0,r.default)();return(0,t.jsx)(a.default,{accessToken:e})}])}]); \ No newline at end of file +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,349356,e=>{e.v({AElig:"Æ",AMP:"&",Aacute:"Á",Acirc:"Â",Agrave:"À",Aring:"Å",Atilde:"Ã",Auml:"Ä",COPY:"©",Ccedil:"Ç",ETH:"Ð",Eacute:"É",Ecirc:"Ê",Egrave:"È",Euml:"Ë",GT:">",Iacute:"Í",Icirc:"Î",Igrave:"Ì",Iuml:"Ï",LT:"<",Ntilde:"Ñ",Oacute:"Ó",Ocirc:"Ô",Ograve:"Ò",Oslash:"Ø",Otilde:"Õ",Ouml:"Ö",QUOT:'"',REG:"®",THORN:"Þ",Uacute:"Ú",Ucirc:"Û",Ugrave:"Ù",Uuml:"Ü",Yacute:"Ý",aacute:"á",acirc:"â",acute:"´",aelig:"æ",agrave:"à",amp:"&",aring:"å",atilde:"ã",auml:"ä",brvbar:"¦",ccedil:"ç",cedil:"¸",cent:"¢",copy:"©",curren:"¤",deg:"°",divide:"÷",eacute:"é",ecirc:"ê",egrave:"è",eth:"ð",euml:"ë",frac12:"½",frac14:"¼",frac34:"¾",gt:">",iacute:"í",icirc:"î",iexcl:"¡",igrave:"ì",iquest:"¿",iuml:"ï",laquo:"«",lt:"<",macr:"¯",micro:"µ",middot:"·",nbsp:" ",not:"¬",ntilde:"ñ",oacute:"ó",ocirc:"ô",ograve:"ò",ordf:"ª",ordm:"º",oslash:"ø",otilde:"õ",ouml:"ö",para:"¶",plusmn:"±",pound:"£",quot:'"',raquo:"»",reg:"®",sect:"§",shy:"­",sup1:"¹",sup2:"²",sup3:"³",szlig:"ß",thorn:"þ",times:"×",uacute:"ú",ucirc:"û",ugrave:"ù",uml:"¨",uuml:"ü",yacute:"ý",yen:"¥",yuml:"ÿ"})},137429,e=>{e.v({0:"�",128:"€",130:"‚",131:"ƒ",132:"„",133:"…",134:"†",135:"‡",136:"ˆ",137:"‰",138:"Š",139:"‹",140:"Œ",142:"Ž",145:"‘",146:"’",147:"“",148:"”",149:"•",150:"–",151:"—",152:"˜",153:"™",154:"š",155:"›",156:"œ",158:"ž",159:"Ÿ"})},166406,e=>{"use strict";var t=e.i(190144);e.s(["CopyOutlined",()=>t.default])},916925,e=>{"use strict";var t,a=((t={}).A2A_Agent="A2A Agent",t.AI21="Ai21",t.AI21_CHAT="Ai21 Chat",t.AIML="AI/ML API",t.AIOHTTP_OPENAI="Aiohttp Openai",t.Anthropic="Anthropic",t.ANTHROPIC_TEXT="Anthropic Text",t.AssemblyAI="AssemblyAI",t.AUTO_ROUTER="Auto Router",t.Bedrock="Amazon Bedrock",t.BedrockMantle="Amazon Bedrock Mantle",t.SageMaker="AWS SageMaker",t.Azure="Azure",t.Azure_AI_Studio="Azure AI Foundry (Studio)",t.AZURE_TEXT="Azure Text",t.BASETEN="Baseten",t.BYTEZ="Bytez",t.Cerebras="Cerebras",t.CLARIFAI="Clarifai",t.CLOUDFLARE="Cloudflare",t.CODESTRAL="Codestral",t.Cohere="Cohere",t.COHERE_CHAT="Cohere Chat",t.COMETAPI="Cometapi",t.COMPACTIFAI="Compactifai",t.Cursor="Cursor",t.Dashscope="Dashscope",t.Databricks="Databricks (Qwen API)",t.DATAROBOT="Datarobot",t.DeepInfra="DeepInfra",t.Deepgram="Deepgram",t.Deepseek="Deepseek",t.DOCKER_MODEL_RUNNER="Docker Model Runner",t.DOTPROMPT="Dotprompt",t.ElevenLabs="ElevenLabs",t.EMPOWER="Empower",t.FalAI="Fal AI",t.FEATHERLESS_AI="Featherless Ai",t.FireworksAI="Fireworks AI",t.FRIENDLIAI="Friendliai",t.GALADRIEL="Galadriel",t.GITHUB_COPILOT="Github Copilot",t.Google_AI_Studio="Google AI Studio",t.GradientAI="GradientAI",t.Groq="Groq",t.HEROKU="Heroku",t.Hosted_Vllm="vllm",t.HUGGINGFACE="Huggingface",t.HYPERBOLIC="Hyperbolic",t.Infinity="Infinity",t.JinaAI="Jina AI",t.LAMBDA_AI="Lambda Ai",t.LEMONADE="Lemonade",t.LLAMAFILE="Llamafile",t.LM_STUDIO="Lm Studio",t.LLAMA="Meta Llama",t.MARITALK="Maritalk",t.MiniMax="MiniMax",t.MistralAI="Mistral AI",t.MOONSHOT="Moonshot",t.MORPH="Morph",t.NEBIUS="Nebius",t.NLP_CLOUD="Nlp Cloud",t.NOVITA="Novita",t.NSCALE="Nscale",t.NVIDIA_NIM="Nvidia Nim",t.Ollama="Ollama",t.OLLAMA_CHAT="Ollama Chat",t.OOBABOOGA="Oobabooga",t.OpenAI="OpenAI",t.OPENAI_LIKE="Openai Like",t.OpenAI_Compatible="OpenAI-Compatible Endpoints (Together AI, etc.)",t.OpenAI_Text="OpenAI Text Completion",t.OpenAI_Text_Compatible="OpenAI-Compatible Text Completion Models (Together AI, etc.)",t.Openrouter="Openrouter",t.Oracle="Oracle Cloud Infrastructure (OCI)",t.OVHCLOUD="Ovhcloud",t.Perplexity="Perplexity",t.PETALS="Petals",t.PG_VECTOR="Pg Vector",t.PREDIBASE="Predibase",t.RECRAFT="Recraft",t.REPLICATE="Replicate",t.RunwayML="RunwayML",t.SAGEMAKER_LEGACY="Sagemaker",t.Sambanova="Sambanova",t.SAP="SAP Generative AI Hub",t.Snowflake="Snowflake",t.TEXT_COMPLETION_CODESTRAL="Text-Completion-Codestral",t.TogetherAI="TogetherAI",t.TOPAZ="Topaz",t.Triton="Triton",t.V0="V0",t.VERCEL_AI_GATEWAY="Vercel Ai Gateway",t.Vertex_AI="Vertex AI (Anthropic, Gemini, etc.)",t.VERTEX_AI_BETA="Vertex Ai Beta",t.VLLM="Vllm",t.VolcEngine="VolcEngine",t.Voyage="Voyage AI",t.WANDB="Wandb",t.WATSONX="Watsonx",t.WATSONX_TEXT="Watsonx Text",t.xAI="xAI",t.XINFERENCE="Xinference",t);let r={A2A_Agent:"a2a_agent",AI21:"ai21",AI21_CHAT:"ai21_chat",AIML:"aiml",AIOHTTP_OPENAI:"aiohttp_openai",Anthropic:"anthropic",ANTHROPIC_TEXT:"anthropic_text",AssemblyAI:"assemblyai",AUTO_ROUTER:"auto_router",Azure:"azure",Azure_AI_Studio:"azure_ai",AZURE_TEXT:"azure_text",BASETEN:"baseten",Bedrock:"bedrock",BedrockMantle:"bedrock_mantle",BYTEZ:"bytez",Cerebras:"cerebras",CLARIFAI:"clarifai",CLOUDFLARE:"cloudflare",CODESTRAL:"codestral",Cohere:"cohere",COHERE_CHAT:"cohere_chat",COMETAPI:"cometapi",COMPACTIFAI:"compactifai",Cursor:"cursor",Dashscope:"dashscope",Databricks:"databricks",DATAROBOT:"datarobot",DeepInfra:"deepinfra",Deepgram:"deepgram",Deepseek:"deepseek",DOCKER_MODEL_RUNNER:"docker_model_runner",DOTPROMPT:"dotprompt",ElevenLabs:"elevenlabs",EMPOWER:"empower",FalAI:"fal_ai",FEATHERLESS_AI:"featherless_ai",FireworksAI:"fireworks_ai",FRIENDLIAI:"friendliai",GALADRIEL:"galadriel",GITHUB_COPILOT:"github_copilot",Google_AI_Studio:"gemini",GradientAI:"gradient_ai",Groq:"groq",HEROKU:"heroku",Hosted_Vllm:"hosted_vllm",HUGGINGFACE:"huggingface",HYPERBOLIC:"hyperbolic",Infinity:"infinity",JinaAI:"jina_ai",LAMBDA_AI:"lambda_ai",LEMONADE:"lemonade",LLAMAFILE:"llamafile",LLAMA:"meta_llama",LM_STUDIO:"lm_studio",MARITALK:"maritalk",MiniMax:"minimax",MistralAI:"mistral",MOONSHOT:"moonshot",MORPH:"morph",NEBIUS:"nebius",NLP_CLOUD:"nlp_cloud",NOVITA:"novita",NSCALE:"nscale",NVIDIA_NIM:"nvidia_nim",Ollama:"ollama",OLLAMA_CHAT:"ollama_chat",OOBABOOGA:"oobabooga",OpenAI:"openai",OPENAI_LIKE:"openai_like",OpenAI_Compatible:"openai",OpenAI_Text:"text-completion-openai",OpenAI_Text_Compatible:"text-completion-openai",Openrouter:"openrouter",Oracle:"oci",OVHCLOUD:"ovhcloud",Perplexity:"perplexity",PETALS:"petals",PG_VECTOR:"pg_vector",PREDIBASE:"predibase",RECRAFT:"recraft",REPLICATE:"replicate",RunwayML:"runwayml",SAGEMAKER_LEGACY:"sagemaker",SageMaker:"sagemaker_chat",Sambanova:"sambanova",SAP:"sap",Snowflake:"snowflake",TEXT_COMPLETION_CODESTRAL:"text-completion-codestral",TogetherAI:"together_ai",TOPAZ:"topaz",Triton:"triton",V0:"v0",VERCEL_AI_GATEWAY:"vercel_ai_gateway",Vertex_AI:"vertex_ai",VERTEX_AI_BETA:"vertex_ai_beta",VLLM:"vllm",VolcEngine:"volcengine",Voyage:"voyage",WANDB:"wandb",WATSONX:"watsonx",WATSONX_TEXT:"watsonx_text",xAI:"xai",XINFERENCE:"xinference"},o="../ui/assets/logos/",n={"A2A Agent":`${o}a2a_agent.png`,Ai21:`${o}ai21.svg`,"Ai21 Chat":`${o}ai21.svg`,"AI/ML API":`${o}aiml_api.svg`,"Aiohttp Openai":`${o}openai_small.svg`,Anthropic:`${o}anthropic.svg`,"Anthropic Text":`${o}anthropic.svg`,AssemblyAI:`${o}assemblyai_small.png`,Azure:`${o}microsoft_azure.svg`,"Azure AI Foundry (Studio)":`${o}microsoft_azure.svg`,"Azure Text":`${o}microsoft_azure.svg`,Baseten:`${o}baseten.svg`,"Amazon Bedrock":`${o}bedrock.svg`,"Amazon Bedrock Mantle":`${o}bedrock.svg`,"AWS SageMaker":`${o}bedrock.svg`,Cerebras:`${o}cerebras.svg`,Cloudflare:`${o}cloudflare.svg`,Codestral:`${o}mistral.svg`,Cohere:`${o}cohere.svg`,"Cohere Chat":`${o}cohere.svg`,Cometapi:`${o}cometapi.svg`,Cursor:`${o}cursor.svg`,"Databricks (Qwen API)":`${o}databricks.svg`,Dashscope:`${o}dashscope.svg`,Deepseek:`${o}deepseek.svg`,Deepgram:`${o}deepgram.png`,DeepInfra:`${o}deepinfra.png`,ElevenLabs:`${o}elevenlabs.png`,"Fal AI":`${o}fal_ai.jpg`,"Featherless Ai":`${o}featherless.svg`,"Fireworks AI":`${o}fireworks.svg`,Friendliai:`${o}friendli.svg`,"Github Copilot":`${o}github_copilot.svg`,"Google AI Studio":`${o}google.svg`,GradientAI:`${o}gradientai.svg`,Groq:`${o}groq.svg`,vllm:`${o}vllm.png`,Huggingface:`${o}huggingface.svg`,Hyperbolic:`${o}hyperbolic.svg`,Infinity:`${o}infinity.png`,"Jina AI":`${o}jina.png`,"Lambda Ai":`${o}lambda.svg`,"Lm Studio":`${o}lmstudio.svg`,"Meta Llama":`${o}meta_llama.svg`,MiniMax:`${o}minimax.svg`,"Mistral AI":`${o}mistral.svg`,Moonshot:`${o}moonshot.svg`,Morph:`${o}morph.svg`,Nebius:`${o}nebius.svg`,Novita:`${o}novita.svg`,"Nvidia Nim":`${o}nvidia_nim.svg`,Ollama:`${o}ollama.svg`,"Ollama Chat":`${o}ollama.svg`,Oobabooga:`${o}openai_small.svg`,OpenAI:`${o}openai_small.svg`,"Openai Like":`${o}openai_small.svg`,"OpenAI Text Completion":`${o}openai_small.svg`,"OpenAI-Compatible Text Completion Models (Together AI, etc.)":`${o}openai_small.svg`,"OpenAI-Compatible Endpoints (Together AI, etc.)":`${o}openai_small.svg`,Openrouter:`${o}openrouter.svg`,"Oracle Cloud Infrastructure (OCI)":`${o}oracle.svg`,Perplexity:`${o}perplexity-ai.svg`,Recraft:`${o}recraft.svg`,Replicate:`${o}replicate.svg`,RunwayML:`${o}runwayml.png`,Sagemaker:`${o}bedrock.svg`,Sambanova:`${o}sambanova.svg`,"SAP Generative AI Hub":`${o}sap.png`,Snowflake:`${o}snowflake.svg`,"Text-Completion-Codestral":`${o}mistral.svg`,TogetherAI:`${o}togetherai.svg`,Topaz:`${o}topaz.svg`,Triton:`${o}nvidia_triton.png`,V0:`${o}v0.svg`,"Vercel Ai Gateway":`${o}vercel.svg`,"Vertex AI (Anthropic, Gemini, etc.)":`${o}google.svg`,"Vertex Ai Beta":`${o}google.svg`,Vllm:`${o}vllm.png`,VolcEngine:`${o}volcengine.png`,"Voyage AI":`${o}voyage.webp`,Watsonx:`${o}watsonx.svg`,"Watsonx Text":`${o}watsonx.svg`,xAI:`${o}xai.svg`,Xinference:`${o}xinference.svg`};e.s(["Providers",()=>a,"getPlaceholder",0,e=>{if("AI/ML API"===e)return"aiml/flux-pro/v1.1";if("Vertex AI (Anthropic, Gemini, etc.)"===e)return"gemini-pro";if("Anthropic"==e)return"claude-3-opus";if("Amazon Bedrock"==e)return"claude-3-opus";if("AWS SageMaker"==e)return"sagemaker/jumpstart-dft-meta-textgeneration-llama-2-7b";else if("Google AI Studio"==e)return"gemini-pro";else if("Azure AI Foundry (Studio)"==e)return"azure_ai/command-r-plus";else if("Azure"==e)return"my-deployment";else if("Oracle Cloud Infrastructure (OCI)"==e)return"oci/xai.grok-4";else if("Snowflake"==e)return"snowflake/mistral-7b";else if("Voyage AI"==e)return"voyage/";else if("Jina AI"==e)return"jina_ai/";else if("VolcEngine"==e)return"volcengine/";else if("DeepInfra"==e)return"deepinfra/";else if("Fal AI"==e)return"fal_ai/fal-ai/flux-pro/v1.1-ultra";else if("RunwayML"==e)return"runwayml/gen4_turbo";else if("Watsonx"===e)return"watsonx/ibm/granite-3-3-8b-instruct";else if("Cursor"===e)return"cursor/claude-4-sonnet";else return"gpt-3.5-turbo"},"getProviderLogoAndName",0,e=>{if(!e)return{logo:"",displayName:"-"};if("gemini"===e.toLowerCase()){let e="Google AI Studio";return{logo:n[e],displayName:e}}let t=Object.keys(r).find(t=>r[t].toLowerCase()===e.toLowerCase());if(!t)return{logo:"",displayName:e};let o=a[t];return{logo:n[o],displayName:o}},"getProviderModels",0,(e,t)=>{console.log(`Provider key: ${e}`);let a=r[e];console.log(`Provider mapped to: ${a}`);let o=[];return e&&"object"==typeof t&&(Object.entries(t).forEach(([e,t])=>{if(null!==t&&"object"==typeof t&&"litellm_provider"in t){let r=t.litellm_provider;(r===a||"string"==typeof r&&r.includes(a))&&o.push(e)}}),"Cohere"==e&&(console.log("Adding cohere chat models"),Object.entries(t).forEach(([e,t])=>{null!==t&&"object"==typeof t&&"litellm_provider"in t&&"cohere_chat"===t.litellm_provider&&o.push(e)})),"AWS SageMaker"==e&&(console.log("Adding sagemaker chat models"),Object.entries(t).forEach(([e,t])=>{null!==t&&"object"==typeof t&&"litellm_provider"in t&&"sagemaker_chat"===t.litellm_provider&&o.push(e)}))),o},"providerLogoMap",0,n,"provider_map",0,r])},637235,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let r={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 372z"}},{tag:"path",attrs:{d:"M686.7 638.6L544.1 535.5V288c0-4.4-3.6-8-8-8H488c-4.4 0-8 3.6-8 8v275.4c0 2.6 1.2 5 3.3 6.5l165.4 120.6c3.6 2.6 8.6 1.8 11.2-1.7l28.6-39c2.6-3.7 1.8-8.7-1.8-11.2z"}}]},name:"clock-circle",theme:"outlined"};var o=e.i(9583),n=a.forwardRef(function(e,n){return a.createElement(o.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["ClockCircleOutlined",0,n],637235)},519756,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let r={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"};var o=e.i(9583),n=a.forwardRef(function(e,n){return a.createElement(o.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["UploadOutlined",0,n],519756)},530212,e=>{"use strict";var t=e.i(271645);let a=t.forwardRef(function(e,a){return t.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:a},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10 19l-7-7m0 0l7-7m-7 7h18"}))});e.s(["ArrowLeftIcon",0,a],530212)},500330,e=>{"use strict";var t=e.i(727749);function a(e,t){let a=structuredClone(e);for(let[e,r]of Object.entries(t))e in a&&(a[e]=r);return a}let r=(e,t=0,a=!1,r=!0)=>{if(null==e||!Number.isFinite(e)||0===e&&!r)return"-";let o={minimumFractionDigits:t,maximumFractionDigits:t};if(!a)return e.toLocaleString("en-US",o);let n=e<0?"-":"",i=Math.abs(e),l=i,s="";return i>=1e6?(l=i/1e6,s="M"):i>=1e3&&(l=i/1e3,s="K"),`${n}${l.toLocaleString("en-US",o)}${s}`},o=async(e,a="Copied to clipboard")=>{if(!e)return!1;if(!navigator||!navigator.clipboard||!navigator.clipboard.writeText)return n(e,a);try{return await navigator.clipboard.writeText(e),t.default.success(a),!0}catch(t){return console.error("Clipboard API failed: ",t),n(e,a)}},n=(e,a)=>{try{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",r.setAttribute("readonly",""),document.body.appendChild(r),r.focus(),r.select();let o=document.execCommand("copy");if(document.body.removeChild(r),o)return t.default.success(a),!0;throw Error("execCommand failed")}catch(e){return t.default.fromBackend("Failed to copy to clipboard"),console.error("Failed to copy: ",e),!1}};e.s(["copyToClipboard",0,o,"formatNumberWithCommas",0,r,"getSpendString",0,(e,t=6)=>{if(null==e||!Number.isFinite(e)||0===e)return"-";let a=r(e,t,!1,!1);if(0===Number(a.replace(/,/g,""))){let e=(1/10**t).toFixed(t);return`< $${e}`}return`$${a}`},"updateExistingKeys",()=>a])},603908,e=>{"use strict";let t=(0,e.i(475254).default)("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);e.s(["default",()=>t])},689020,e=>{"use strict";var t=e.i(764205);let a=async e=>{try{let a=await (0,t.modelHubCall)(e);if(console.log("model_info:",a),a?.data.length>0){let e=a.data.map(e=>({model_group:e.model_group,mode:e?.mode}));return e.sort((e,t)=>e.model_group.localeCompare(t.model_group)),e}return[]}catch(e){throw console.error("Error fetching model info:",e),e}};e.s(["fetchAvailableModels",0,a])},599724,936325,e=>{"use strict";var t=e.i(95779),a=e.i(444755),r=e.i(673706),o=e.i(271645);let n=o.default.forwardRef((e,n)=>{let{color:i,className:l,children:s}=e;return o.default.createElement("p",{ref:n,className:(0,a.tremorTwMerge)("text-tremor-default",i?(0,r.getColorClassNames)(i,t.colorPalette.text).textColor:(0,a.tremorTwMerge)("text-tremor-content","dark:text-dark-tremor-content"),l)},s)});n.displayName="Text",e.s(["default",()=>n],936325),e.s(["Text",()=>n],599724)},994388,e=>{"use strict";var t=e.i(290571),a=e.i(829087),r=e.i(271645);let o=["preEnter","entering","entered","preExit","exiting","exited","unmounted"],n=e=>({_s:e,status:o[e],isEnter:e<3,isMounted:6!==e,isResolved:2===e||e>4}),i=e=>e?6:5,l=(e,t,a,r,o)=>{clearTimeout(r.current);let i=n(e);t(i),a.current=i,o&&o({current:i})};var s=e.i(480731),c=e.i(444755),d=e.i(673706);let u=e=>{var a=(0,t.__rest)(e,[]);return r.default.createElement("svg",Object.assign({},a,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"}),r.default.createElement("path",{fill:"none",d:"M0 0h24v24H0z"}),r.default.createElement("path",{d:"M18.364 5.636L16.95 7.05A7 7 0 1 0 19 12h2a9 9 0 1 1-2.636-6.364z"}))};var m=e.i(95779);let p={xs:{height:"h-4",width:"w-4"},sm:{height:"h-5",width:"w-5"},md:{height:"h-5",width:"w-5"},lg:{height:"h-6",width:"w-6"},xl:{height:"h-6",width:"w-6"}},g=(e,t)=>{switch(e){case"primary":return{textColor:t?(0,d.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",hoverTextColor:t?(0,d.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",bgColor:t?(0,d.getColorClassNames)(t,m.colorPalette.background).bgColor:"bg-tremor-brand dark:bg-dark-tremor-brand",hoverBgColor:t?(0,d.getColorClassNames)(t,m.colorPalette.darkBackground).hoverBgColor:"hover:bg-tremor-brand-emphasis dark:hover:bg-dark-tremor-brand-emphasis",borderColor:t?(0,d.getColorClassNames)(t,m.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",hoverBorderColor:t?(0,d.getColorClassNames)(t,m.colorPalette.darkBorder).hoverBorderColor:"hover:border-tremor-brand-emphasis dark:hover:border-dark-tremor-brand-emphasis"};case"secondary":return{textColor:t?(0,d.getColorClassNames)(t,m.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,d.getColorClassNames)(t,m.colorPalette.text).textColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,d.getColorClassNames)("transparent").bgColor,hoverBgColor:t?(0,c.tremorTwMerge)((0,d.getColorClassNames)(t,m.colorPalette.background).hoverBgColor,"hover:bg-opacity-20 dark:hover:bg-opacity-20"):"hover:bg-tremor-brand-faint dark:hover:bg-dark-tremor-brand-faint",borderColor:t?(0,d.getColorClassNames)(t,m.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand"};case"light":return{textColor:t?(0,d.getColorClassNames)(t,m.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,d.getColorClassNames)(t,m.colorPalette.darkText).hoverTextColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,d.getColorClassNames)("transparent").bgColor,borderColor:"",hoverBorderColor:""}}},f=(0,d.makeClassName)("Button"),h=({loading:e,iconSize:t,iconPosition:a,Icon:o,needMargin:n,transitionStatus:i})=>{let l=n?a===s.HorizontalPositions.Left?(0,c.tremorTwMerge)("-ml-1","mr-1.5"):(0,c.tremorTwMerge)("-mr-1","ml-1.5"):"",d=(0,c.tremorTwMerge)("w-0 h-0"),m={default:d,entering:d,entered:t,exiting:t,exited:d};return e?r.default.createElement(u,{className:(0,c.tremorTwMerge)(f("icon"),"animate-spin shrink-0",l,m.default,m[i]),style:{transition:"width 150ms"}}):r.default.createElement(o,{className:(0,c.tremorTwMerge)(f("icon"),"shrink-0",t,l)})},v=r.default.forwardRef((e,o)=>{let{icon:u,iconPosition:m=s.HorizontalPositions.Left,size:v=s.Sizes.SM,color:b,variant:x="primary",disabled:y,loading:C=!1,loadingText:$,children:k,tooltip:O,className:w}=e,A=(0,t.__rest)(e,["icon","iconPosition","size","color","variant","disabled","loading","loadingText","children","tooltip","className"]),E=C||y,S=void 0!==u||C,I=C&&$,T=!(!k&&!I),N=(0,c.tremorTwMerge)(p[v].height,p[v].width),M="light"!==x?(0,c.tremorTwMerge)("rounded-tremor-default border","shadow-tremor-input","dark:shadow-dark-tremor-input"):"",z=g(x,b),L=("light"!==x?{xs:{paddingX:"px-2.5",paddingY:"py-1.5",fontSize:"text-xs"},sm:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-sm"},md:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-md"},lg:{paddingX:"px-4",paddingY:"py-2.5",fontSize:"text-lg"},xl:{paddingX:"px-4",paddingY:"py-3",fontSize:"text-xl"}}:{xs:{paddingX:"",paddingY:"",fontSize:"text-xs"},sm:{paddingX:"",paddingY:"",fontSize:"text-sm"},md:{paddingX:"",paddingY:"",fontSize:"text-md"},lg:{paddingX:"",paddingY:"",fontSize:"text-lg"},xl:{paddingX:"",paddingY:"",fontSize:"text-xl"}})[v],{tooltipProps:_,getReferenceProps:j}=(0,a.useTooltip)(300),[R,P]=(({enter:e=!0,exit:t=!0,preEnter:a,preExit:o,timeout:s,initialEntered:c,mountOnEnter:d,unmountOnExit:u,onStateChange:m}={})=>{let[p,g]=(0,r.useState)(()=>n(c?2:i(d))),f=(0,r.useRef)(p),h=(0,r.useRef)(0),[v,b]="object"==typeof s?[s.enter,s.exit]:[s,s],x=(0,r.useCallback)(()=>{let e=((e,t)=>{switch(e){case 1:case 0:return 2;case 4:case 3:return i(t)}})(f.current._s,u);e&&l(e,g,f,h,m)},[m,u]);return[p,(0,r.useCallback)(r=>{let n=e=>{switch(l(e,g,f,h,m),e){case 1:v>=0&&(h.current=((...e)=>setTimeout(...e))(x,v));break;case 4:b>=0&&(h.current=((...e)=>setTimeout(...e))(x,b));break;case 0:case 3:h.current=((...e)=>setTimeout(...e))(()=>{isNaN(document.body.offsetTop)||n(e+1)},0)}},s=f.current.isEnter;"boolean"!=typeof r&&(r=!s),r?s||n(e?+!a:2):s&&n(t?o?3:4:i(u))},[x,m,e,t,a,o,v,b,u]),x]})({timeout:50});return(0,r.useEffect)(()=>{P(C)},[C]),r.default.createElement("button",Object.assign({ref:(0,d.mergeRefs)([o,_.refs.setReference]),className:(0,c.tremorTwMerge)(f("root"),"shrink-0 inline-flex justify-center items-center group font-medium outline-none",M,L.paddingX,L.paddingY,L.fontSize,z.textColor,z.bgColor,z.borderColor,z.hoverBorderColor,E?"opacity-50 cursor-not-allowed":(0,c.tremorTwMerge)(g(x,b).hoverTextColor,g(x,b).hoverBgColor,g(x,b).hoverBorderColor),w),disabled:E},j,A),r.default.createElement(a.default,Object.assign({text:O},_)),S&&m!==s.HorizontalPositions.Right?r.default.createElement(h,{loading:C,iconSize:N,iconPosition:m,Icon:u,transitionStatus:R.status,needMargin:T}):null,I||k?r.default.createElement("span",{className:(0,c.tremorTwMerge)(f("text"),"text-tremor-default whitespace-nowrap")},I?$:k):null,S&&m===s.HorizontalPositions.Right?r.default.createElement(h,{loading:C,iconSize:N,iconPosition:m,Icon:u,transitionStatus:R.status,needMargin:T}):null)});v.displayName="Button",e.s(["Button",()=>v],994388)},304967,e=>{"use strict";var t=e.i(290571),a=e.i(271645),r=e.i(480731),o=e.i(95779),n=e.i(444755),i=e.i(673706);let l=(0,i.makeClassName)("Card"),s=a.default.forwardRef((e,s)=>{let{decoration:c="",decorationColor:d,children:u,className:m}=e,p=(0,t.__rest)(e,["decoration","decorationColor","children","className"]);return a.default.createElement("div",Object.assign({ref:s,className:(0,n.tremorTwMerge)(l("root"),"relative w-full text-left ring-1 rounded-tremor-default p-6","bg-tremor-background ring-tremor-ring shadow-tremor-card","dark:bg-dark-tremor-background dark:ring-dark-tremor-ring dark:shadow-dark-tremor-card",d?(0,i.getColorClassNames)(d,o.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",(e=>{if(!e)return"";switch(e){case r.HorizontalPositions.Left:return"border-l-4";case r.VerticalPositions.Top:return"border-t-4";case r.HorizontalPositions.Right:return"border-r-4";case r.VerticalPositions.Bottom:return"border-b-4";default:return""}})(c),m)},p),u)});s.displayName="Card",e.s(["Card",()=>s],304967)},629569,e=>{"use strict";var t=e.i(290571),a=e.i(95779),r=e.i(444755),o=e.i(673706),n=e.i(271645);let i=n.default.forwardRef((e,i)=>{let{color:l,children:s,className:c}=e,d=(0,t.__rest)(e,["color","children","className"]);return n.default.createElement("p",Object.assign({ref:i,className:(0,r.tremorTwMerge)("font-medium text-tremor-title",l?(0,o.getColorClassNames)(l,a.colorPalette.darkText).textColor:"text-tremor-content-strong dark:text-dark-tremor-content-strong",c)},d),s)});i.displayName="Title",e.s(["Title",()=>i],629569)},244451,e=>{"use strict";let t;e.i(247167);var a=e.i(271645),r=e.i(343794),o=e.i(242064),n=e.i(763731),i=e.i(174428);let l=80*Math.PI,s=e=>{let{dotClassName:t,style:o,hasCircleCls:n}=e;return a.createElement("circle",{className:(0,r.default)(`${t}-circle`,{[`${t}-circle-bg`]:n}),r:40,cx:50,cy:50,strokeWidth:20,style:o})},c=({percent:e,prefixCls:t})=>{let o=`${t}-dot`,n=`${o}-holder`,c=`${n}-hidden`,[d,u]=a.useState(!1);(0,i.default)(()=>{0!==e&&u(!0)},[0!==e]);let m=Math.max(Math.min(e,100),0);if(!d)return null;let p={strokeDashoffset:`${l/4}`,strokeDasharray:`${l*m/100} ${l*(100-m)/100}`};return a.createElement("span",{className:(0,r.default)(n,`${o}-progress`,m<=0&&c)},a.createElement("svg",{viewBox:"0 0 100 100",role:"progressbar","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":m},a.createElement(s,{dotClassName:o,hasCircleCls:!0}),a.createElement(s,{dotClassName:o,style:p})))};function d(e){let{prefixCls:t,percent:o=0}=e,n=`${t}-dot`,i=`${n}-holder`,l=`${i}-hidden`;return a.createElement(a.Fragment,null,a.createElement("span",{className:(0,r.default)(i,o>0&&l)},a.createElement("span",{className:(0,r.default)(n,`${t}-dot-spin`)},[1,2,3,4].map(e=>a.createElement("i",{className:`${t}-dot-item`,key:e})))),a.createElement(c,{prefixCls:t,percent:o}))}function u(e){var t;let{prefixCls:o,indicator:i,percent:l}=e,s=`${o}-dot`;return i&&a.isValidElement(i)?(0,n.cloneElement)(i,{className:(0,r.default)(null==(t=i.props)?void 0:t.className,s),percent:l}):a.createElement(d,{prefixCls:o,percent:l})}e.i(296059);var m=e.i(694758),p=e.i(183293),g=e.i(246422),f=e.i(838378);let h=new m.Keyframes("antSpinMove",{to:{opacity:1}}),v=new m.Keyframes("antRotate",{to:{transform:"rotate(405deg)"}}),b=(0,g.genStyleHooks)("Spin",e=>(e=>{let{componentCls:t,calc:a}=e;return{[t]:Object.assign(Object.assign({},(0,p.resetComponent)(e)),{position:"absolute",display:"none",color:e.colorPrimary,fontSize:0,textAlign:"center",verticalAlign:"middle",opacity:0,transition:`transform ${e.motionDurationSlow} ${e.motionEaseInOutCirc}`,"&-spinning":{position:"relative",display:"inline-block",opacity:1},[`${t}-text`]:{fontSize:e.fontSize,paddingTop:a(a(e.dotSize).sub(e.fontSize)).div(2).add(2).equal()},"&-fullscreen":{position:"fixed",width:"100vw",height:"100vh",backgroundColor:e.colorBgMask,zIndex:e.zIndexPopupBase,inset:0,display:"flex",alignItems:"center",flexDirection:"column",justifyContent:"center",opacity:0,visibility:"hidden",transition:`all ${e.motionDurationMid}`,"&-show":{opacity:1,visibility:"visible"},[t]:{[`${t}-dot-holder`]:{color:e.colorWhite},[`${t}-text`]:{color:e.colorTextLightSolid}}},"&-nested-loading":{position:"relative",[`> div > ${t}`]:{position:"absolute",top:0,insetInlineStart:0,zIndex:4,display:"block",width:"100%",height:"100%",maxHeight:e.contentHeight,[`${t}-dot`]:{position:"absolute",top:"50%",insetInlineStart:"50%",margin:a(e.dotSize).mul(-1).div(2).equal()},[`${t}-text`]:{position:"absolute",top:"50%",width:"100%",textShadow:`0 1px 2px ${e.colorBgContainer}`},[`&${t}-show-text ${t}-dot`]:{marginTop:a(e.dotSize).div(2).mul(-1).sub(10).equal()},"&-sm":{[`${t}-dot`]:{margin:a(e.dotSizeSM).mul(-1).div(2).equal()},[`${t}-text`]:{paddingTop:a(a(e.dotSizeSM).sub(e.fontSize)).div(2).add(2).equal()},[`&${t}-show-text ${t}-dot`]:{marginTop:a(e.dotSizeSM).div(2).mul(-1).sub(10).equal()}},"&-lg":{[`${t}-dot`]:{margin:a(e.dotSizeLG).mul(-1).div(2).equal()},[`${t}-text`]:{paddingTop:a(a(e.dotSizeLG).sub(e.fontSize)).div(2).add(2).equal()},[`&${t}-show-text ${t}-dot`]:{marginTop:a(e.dotSizeLG).div(2).mul(-1).sub(10).equal()}}},[`${t}-container`]:{position:"relative",transition:`opacity ${e.motionDurationSlow}`,"&::after":{position:"absolute",top:0,insetInlineEnd:0,bottom:0,insetInlineStart:0,zIndex:10,width:"100%",height:"100%",background:e.colorBgContainer,opacity:0,transition:`all ${e.motionDurationSlow}`,content:'""',pointerEvents:"none"}},[`${t}-blur`]:{clear:"both",opacity:.5,userSelect:"none",pointerEvents:"none","&::after":{opacity:.4,pointerEvents:"auto"}}},"&-tip":{color:e.spinDotDefault},[`${t}-dot-holder`]:{width:"1em",height:"1em",fontSize:e.dotSize,display:"inline-block",transition:`transform ${e.motionDurationSlow} ease, opacity ${e.motionDurationSlow} ease`,transformOrigin:"50% 50%",lineHeight:1,color:e.colorPrimary,"&-hidden":{transform:"scale(0.3)",opacity:0}},[`${t}-dot-progress`]:{position:"absolute",inset:0},[`${t}-dot`]:{position:"relative",display:"inline-block",fontSize:e.dotSize,width:"1em",height:"1em","&-item":{position:"absolute",display:"block",width:a(e.dotSize).sub(a(e.marginXXS).div(2)).div(2).equal(),height:a(e.dotSize).sub(a(e.marginXXS).div(2)).div(2).equal(),background:"currentColor",borderRadius:"100%",transform:"scale(0.75)",transformOrigin:"50% 50%",opacity:.3,animationName:h,animationDuration:"1s",animationIterationCount:"infinite",animationTimingFunction:"linear",animationDirection:"alternate","&:nth-child(1)":{top:0,insetInlineStart:0,animationDelay:"0s"},"&:nth-child(2)":{top:0,insetInlineEnd:0,animationDelay:"0.4s"},"&:nth-child(3)":{insetInlineEnd:0,bottom:0,animationDelay:"0.8s"},"&:nth-child(4)":{bottom:0,insetInlineStart:0,animationDelay:"1.2s"}},"&-spin":{transform:"rotate(45deg)",animationName:v,animationDuration:"1.2s",animationIterationCount:"infinite",animationTimingFunction:"linear"},"&-circle":{strokeLinecap:"round",transition:["stroke-dashoffset","stroke-dasharray","stroke","stroke-width","opacity"].map(t=>`${t} ${e.motionDurationSlow} ease`).join(","),fillOpacity:0,stroke:"currentcolor"},"&-circle-bg":{stroke:e.colorFillSecondary}},[`&-sm ${t}-dot`]:{"&, &-holder":{fontSize:e.dotSizeSM}},[`&-sm ${t}-dot-holder`]:{i:{width:a(a(e.dotSizeSM).sub(a(e.marginXXS).div(2))).div(2).equal(),height:a(a(e.dotSizeSM).sub(a(e.marginXXS).div(2))).div(2).equal()}},[`&-lg ${t}-dot`]:{"&, &-holder":{fontSize:e.dotSizeLG}},[`&-lg ${t}-dot-holder`]:{i:{width:a(a(e.dotSizeLG).sub(e.marginXXS)).div(2).equal(),height:a(a(e.dotSizeLG).sub(e.marginXXS)).div(2).equal()}},[`&${t}-show-text ${t}-text`]:{display:"block"}})}})((0,f.mergeToken)(e,{spinDotDefault:e.colorTextDescription})),e=>{let{controlHeightLG:t,controlHeight:a}=e;return{contentHeight:400,dotSize:t/2,dotSizeSM:.35*t,dotSizeLG:a}}),x=[[30,.05],[70,.03],[96,.01]];var y=function(e,t){var a={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(a[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);ot.indexOf(r[o])&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(a[r[o]]=e[r[o]]);return a};let C=e=>{var n;let{prefixCls:i,spinning:l=!0,delay:s=0,className:c,rootClassName:d,size:m="default",tip:p,wrapperClassName:g,style:f,children:h,fullscreen:v=!1,indicator:C,percent:$}=e,k=y(e,["prefixCls","spinning","delay","className","rootClassName","size","tip","wrapperClassName","style","children","fullscreen","indicator","percent"]),{getPrefixCls:O,direction:w,className:A,style:E,indicator:S}=(0,o.useComponentConfig)("spin"),I=O("spin",i),[T,N,M]=b(I),[z,L]=a.useState(()=>l&&(!l||!s||!!Number.isNaN(Number(s)))),_=function(e,t){let[r,o]=a.useState(0),n=a.useRef(null),i="auto"===t;return a.useEffect(()=>(i&&e&&(o(0),n.current=setInterval(()=>{o(e=>{let t=100-e;for(let a=0;a{n.current&&(clearInterval(n.current),n.current=null)}),[i,e]),i?r:t}(z,$);a.useEffect(()=>{if(l){let e=function(e,t,a){var r,o=a||{},n=o.noTrailing,i=void 0!==n&&n,l=o.noLeading,s=void 0!==l&&l,c=o.debounceMode,d=void 0===c?void 0:c,u=!1,m=0;function p(){r&&clearTimeout(r)}function g(){for(var a=arguments.length,o=Array(a),n=0;ne?s?(m=Date.now(),i||(r=setTimeout(d?f:g,e))):g():!0!==i&&(r=setTimeout(d?f:g,void 0===d?e-c:e)))}return g.cancel=function(e){var t=(e||{}).upcomingOnly;p(),u=!(void 0!==t&&t)},g}(s,()=>{L(!0)},{debounceMode:false});return e(),()=>{var t;null==(t=null==e?void 0:e.cancel)||t.call(e)}}L(!1)},[s,l]);let j=a.useMemo(()=>void 0!==h&&!v,[h,v]),R=(0,r.default)(I,A,{[`${I}-sm`]:"small"===m,[`${I}-lg`]:"large"===m,[`${I}-spinning`]:z,[`${I}-show-text`]:!!p,[`${I}-rtl`]:"rtl"===w},c,!v&&d,N,M),P=(0,r.default)(`${I}-container`,{[`${I}-blur`]:z}),D=null!=(n=null!=C?C:S)?n:t,B=Object.assign(Object.assign({},E),f),H=a.createElement("div",Object.assign({},k,{style:B,className:R,"aria-live":"polite","aria-busy":z}),a.createElement(u,{prefixCls:I,indicator:D,percent:_}),p&&(j||v)?a.createElement("div",{className:`${I}-text`},p):null);return T(j?a.createElement("div",Object.assign({},k,{className:(0,r.default)(`${I}-nested-loading`,g,N,M)}),z&&a.createElement("div",{key:"loading"},H),a.createElement("div",{className:P,key:"container"},h)):v?a.createElement("div",{className:(0,r.default)(`${I}-fullscreen`,{[`${I}-fullscreen-show`]:z},d,N,M)},H):H)};C.setDefaultIndicator=e=>{t=e},e.s(["default",0,C],244451)},482725,e=>{"use strict";var t=e.i(244451);e.s(["Spin",()=>t.default])},597440,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let r={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M360 184h-8c4.4 0 8-3.6 8-8v8h304v-8c0 4.4 3.6 8 8 8h-8v72h72v-80c0-35.3-28.7-64-64-64H352c-35.3 0-64 28.7-64 64v80h72v-72zm504 72H160c-17.7 0-32 14.3-32 32v32c0 4.4 3.6 8 8 8h60.4l24.7 523c1.6 34.1 29.8 61 63.9 61h454c34.2 0 62.3-26.8 63.9-61l24.7-523H888c4.4 0 8-3.6 8-8v-32c0-17.7-14.3-32-32-32zM731.3 840H292.7l-24.2-512h487l-24.2 512z"}}]},name:"delete",theme:"outlined"};var o=e.i(9583),n=a.forwardRef(function(e,n){return a.createElement(o.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["default",0,n],597440)},797672,e=>{"use strict";var t=e.i(271645);let a=t.forwardRef(function(e,a){return t.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:a},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"}))});e.s(["PencilIcon",0,a],797672)},981339,e=>{"use strict";var t=e.i(185793);e.s(["Skeleton",()=>t.default])},653496,e=>{"use strict";var t=e.i(721369);e.s(["Tabs",()=>t.default])},983561,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let r={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"};var o=e.i(9583),n=a.forwardRef(function(e,n){return a.createElement(o.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["RobotOutlined",0,n],983561)},992619,e=>{"use strict";var t=e.i(843476),a=e.i(271645),r=e.i(779241),o=e.i(599724),n=e.i(199133),i=e.i(983561),l=e.i(689020);e.s(["default",0,({accessToken:e,value:s,placeholder:c="Select a Model",onChange:d,disabled:u=!1,style:m,className:p,showLabel:g=!0,labelText:f="Select Model"})=>{let[h,v]=(0,a.useState)(s),[b,x]=(0,a.useState)(!1),[y,C]=(0,a.useState)([]),$=(0,a.useRef)(null);return(0,a.useEffect)(()=>{v(s)},[s]),(0,a.useEffect)(()=>{e&&(async()=>{try{let t=await (0,l.fetchAvailableModels)(e);console.log("Fetched models for selector:",t),t.length>0&&C(t)}catch(e){console.error("Error fetching model info:",e)}})()},[e]),(0,t.jsxs)("div",{children:[g&&(0,t.jsxs)(o.Text,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,t.jsx)(i.RobotOutlined,{className:"mr-2"})," ",f]}),(0,t.jsx)(n.Select,{value:h,placeholder:c,onChange:e=>{"custom"===e?(x(!0),v(void 0)):(x(!1),v(e),d&&d(e))},options:[...Array.from(new Set(y.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%",...m},showSearch:!0,className:`rounded-md ${p||""}`,disabled:u}),b&&(0,t.jsx)(r.TextInput,{className:"mt-2",placeholder:"Enter custom model name",onValueChange:e=>{$.current&&clearTimeout($.current),$.current=setTimeout(()=>{v(e),d&&d(e)},500)},disabled:u})]})}])},829672,836938,310730,e=>{"use strict";e.i(247167);var t=e.i(271645),a=e.i(343794),r=e.i(914949),o=e.i(404948);let n=e=>e?"function"==typeof e?e():e:null;e.s(["getRenderPropValue",0,n],836938);var i=e.i(613541),l=e.i(763731),s=e.i(242064),c=e.i(491816);e.i(793154);var d=e.i(880476),u=e.i(183293),m=e.i(717356),p=e.i(320560),g=e.i(307358),f=e.i(246422),h=e.i(838378),v=e.i(617933);let b=(0,f.genStyleHooks)("Popover",e=>{let{colorBgElevated:t,colorText:a}=e,r=(0,h.mergeToken)(e,{popoverBg:t,popoverColor:a});return[(e=>{let{componentCls:t,popoverColor:a,titleMinWidth:r,fontWeightStrong:o,innerPadding:n,boxShadowSecondary:i,colorTextHeading:l,borderRadiusLG:s,zIndexPopup:c,titleMarginBottom:d,colorBgElevated:m,popoverBg:g,titleBorderBottom:f,innerContentPadding:h,titlePadding:v}=e;return[{[t]:Object.assign(Object.assign({},(0,u.resetComponent)(e)),{position:"absolute",top:0,left:{_skip_check_:!0,value:0},zIndex:c,fontWeight:"normal",whiteSpace:"normal",textAlign:"start",cursor:"auto",userSelect:"text","--valid-offset-x":"var(--arrow-offset-horizontal, var(--arrow-x))",transformOrigin:"var(--valid-offset-x, 50%) var(--arrow-y, 50%)","--antd-arrow-background-color":m,width:"max-content",maxWidth:"100vw","&-rtl":{direction:"rtl"},"&-hidden":{display:"none"},[`${t}-content`]:{position:"relative"},[`${t}-inner`]:{backgroundColor:g,backgroundClip:"padding-box",borderRadius:s,boxShadow:i,padding:n},[`${t}-title`]:{minWidth:r,marginBottom:d,color:l,fontWeight:o,borderBottom:f,padding:v},[`${t}-inner-content`]:{color:a,padding:h}})},(0,p.default)(e,"var(--antd-arrow-background-color)"),{[`${t}-pure`]:{position:"relative",maxWidth:"none",margin:e.sizePopupArrow,display:"inline-block",[`${t}-content`]:{display:"inline-block"}}}]})(r),(e=>{let{componentCls:t}=e;return{[t]:v.PresetColors.map(a=>{let r=e[`${a}6`];return{[`&${t}-${a}`]:{"--antd-arrow-background-color":r,[`${t}-inner`]:{backgroundColor:r},[`${t}-arrow`]:{background:"transparent"}}}})}})(r),(0,m.initZoomMotion)(r,"zoom-big")]},e=>{let{lineWidth:t,controlHeight:a,fontHeight:r,padding:o,wireframe:n,zIndexPopupBase:i,borderRadiusLG:l,marginXS:s,lineType:c,colorSplit:d,paddingSM:u}=e,m=a-r;return Object.assign(Object.assign(Object.assign({titleMinWidth:177,zIndexPopup:i+30},(0,g.getArrowToken)(e)),(0,p.getArrowOffsetToken)({contentRadius:l,limitVerticalRadius:!0})),{innerPadding:12*!n,titleMarginBottom:n?0:s,titlePadding:n?`${m/2}px ${o}px ${m/2-t}px`:0,titleBorderBottom:n?`${t}px ${c} ${d}`:"none",innerContentPadding:n?`${u}px ${o}px`:0})},{resetStyle:!1,deprecatedTokens:[["width","titleMinWidth"],["minWidth","titleMinWidth"]]});var x=function(e,t){var a={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(a[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);ot.indexOf(r[o])&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(a[r[o]]=e[r[o]]);return a};let y=({title:e,content:a,prefixCls:r})=>e||a?t.createElement(t.Fragment,null,e&&t.createElement("div",{className:`${r}-title`},e),a&&t.createElement("div",{className:`${r}-inner-content`},a)):null,C=e=>{let{hashId:r,prefixCls:o,className:i,style:l,placement:s="top",title:c,content:u,children:m}=e,p=n(c),g=n(u),f=(0,a.default)(r,o,`${o}-pure`,`${o}-placement-${s}`,i);return t.createElement("div",{className:f,style:l},t.createElement("div",{className:`${o}-arrow`}),t.createElement(d.Popup,Object.assign({},e,{className:r,prefixCls:o}),m||t.createElement(y,{prefixCls:o,title:p,content:g})))},$=e=>{let{prefixCls:r,className:o}=e,n=x(e,["prefixCls","className"]),{getPrefixCls:i}=t.useContext(s.ConfigContext),l=i("popover",r),[c,d,u]=b(l);return c(t.createElement(C,Object.assign({},n,{prefixCls:l,hashId:d,className:(0,a.default)(o,u)})))};e.s(["Overlay",0,y,"default",0,$],310730);var k=function(e,t){var a={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(a[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);ot.indexOf(r[o])&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(a[r[o]]=e[r[o]]);return a};let O=t.forwardRef((e,d)=>{var u,m;let{prefixCls:p,title:g,content:f,overlayClassName:h,placement:v="top",trigger:x="hover",children:C,mouseEnterDelay:$=.1,mouseLeaveDelay:O=.1,onOpenChange:w,overlayStyle:A={},styles:E,classNames:S}=e,I=k(e,["prefixCls","title","content","overlayClassName","placement","trigger","children","mouseEnterDelay","mouseLeaveDelay","onOpenChange","overlayStyle","styles","classNames"]),{getPrefixCls:T,className:N,style:M,classNames:z,styles:L}=(0,s.useComponentConfig)("popover"),_=T("popover",p),[j,R,P]=b(_),D=T(),B=(0,a.default)(h,R,P,N,z.root,null==S?void 0:S.root),H=(0,a.default)(z.body,null==S?void 0:S.body),[V,W]=(0,r.default)(!1,{value:null!=(u=e.open)?u:e.visible,defaultValue:null!=(m=e.defaultOpen)?m:e.defaultVisible}),F=(e,t)=>{W(e,!0),null==w||w(e,t)},G=n(g),X=n(f);return j(t.createElement(c.default,Object.assign({placement:v,trigger:x,mouseEnterDelay:$,mouseLeaveDelay:O},I,{prefixCls:_,classNames:{root:B,body:H},styles:{root:Object.assign(Object.assign(Object.assign(Object.assign({},L.root),M),A),null==E?void 0:E.root),body:Object.assign(Object.assign({},L.body),null==E?void 0:E.body)},ref:d,open:V,onOpenChange:e=>{F(e)},overlay:G||X?t.createElement(y,{prefixCls:_,title:G,content:X}):null,transitionName:(0,i.getTransitionName)(D,"zoom-big",I.transitionName),"data-popover-inject":!0}),(0,l.cloneElement)(C,{onKeyDown:e=>{var a,r;(0,t.isValidElement)(C)&&(null==(r=null==C?void 0:(a=C.props).onKeyDown)||r.call(a,e)),e.keyCode===o.default.ESC&&F(!1,e)}})))});O._InternalPanelDoNotUseOrYouWillBeFired=$,e.s(["default",0,O],829672)},282786,e=>{"use strict";var t=e.i(829672);e.s(["Popover",()=>t.default])},751904,e=>{"use strict";var t=e.i(401361);e.s(["EditOutlined",()=>t.default])},440987,e=>{"use strict";var t=e.i(903446);e.s(["SettingsIcon",()=>t.default])},94629,e=>{"use strict";var t=e.i(271645);let a=t.forwardRef(function(e,a){return t.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:a},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4"}))});e.s(["SwitchVerticalIcon",0,a],94629)},991124,e=>{"use strict";let t=(0,e.i(475254).default)("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"}]]);e.s(["default",()=>t])},678784,678745,e=>{"use strict";let t=(0,e.i(475254).default)("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);e.s(["default",()=>t],678745),e.s(["CheckIcon",()=>t],678784)},118366,e=>{"use strict";var t=e.i(991124);e.s(["CopyIcon",()=>t.default])},211576,e=>{"use strict";var t=e.i(131757);e.s(["Col",()=>t.default])},837007,e=>{"use strict";var t=e.i(603908);e.s(["PlusIcon",()=>t.default])},573421,e=>{"use strict";e.i(247167);var t=e.i(8211),a=e.i(271645),r=e.i(343794),o=e.i(887719),n=e.i(908206),i=e.i(242064),l=e.i(721132),s=e.i(517455),c=e.i(264042),d=e.i(150073),u=e.i(165370),m=e.i(244451);let p=a.default.createContext({});p.Consumer;var g=e.i(763731),f=e.i(211576),h=function(e,t){var a={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(a[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);ot.indexOf(r[o])&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(a[r[o]]=e[r[o]]);return a};let v=a.default.forwardRef((e,t)=>{let o,{prefixCls:n,children:l,actions:s,extra:c,styles:d,className:u,classNames:m,colStyle:v}=e,b=h(e,["prefixCls","children","actions","extra","styles","className","classNames","colStyle"]),{grid:x,itemLayout:y}=(0,a.useContext)(p),{getPrefixCls:C,list:$}=(0,a.useContext)(i.ConfigContext),k=e=>{var t,a;return(0,r.default)(null==(a=null==(t=null==$?void 0:$.item)?void 0:t.classNames)?void 0:a[e],null==m?void 0:m[e])},O=e=>{var t,a;return Object.assign(Object.assign({},null==(a=null==(t=null==$?void 0:$.item)?void 0:t.styles)?void 0:a[e]),null==d?void 0:d[e])},w=C("list",n),A=s&&s.length>0&&a.default.createElement("ul",{className:(0,r.default)(`${w}-item-action`,k("actions")),key:"actions",style:O("actions")},s.map((e,t)=>a.default.createElement("li",{key:`${w}-item-action-${t}`},e,t!==s.length-1&&a.default.createElement("em",{className:`${w}-item-action-split`})))),E=a.default.createElement(x?"div":"li",Object.assign({},b,x?{}:{ref:t},{className:(0,r.default)(`${w}-item`,{[`${w}-item-no-flex`]:!("vertical"===y?!!c:(o=!1,a.Children.forEach(l,e=>{"string"==typeof e&&(o=!0)}),!(o&&a.Children.count(l)>1)))},u)}),"vertical"===y&&c?[a.default.createElement("div",{className:`${w}-item-main`,key:"content"},l,A),a.default.createElement("div",{className:(0,r.default)(`${w}-item-extra`,k("extra")),key:"extra",style:O("extra")},c)]:[l,A,(0,g.cloneElement)(c,{key:"extra"})]);return x?a.default.createElement(f.Col,{ref:t,flex:1,style:v},E):E});v.Meta=e=>{var{prefixCls:t,className:o,avatar:n,title:l,description:s}=e,c=h(e,["prefixCls","className","avatar","title","description"]);let{getPrefixCls:d}=(0,a.useContext)(i.ConfigContext),u=d("list",t),m=(0,r.default)(`${u}-item-meta`,o),p=a.default.createElement("div",{className:`${u}-item-meta-content`},l&&a.default.createElement("h4",{className:`${u}-item-meta-title`},l),s&&a.default.createElement("div",{className:`${u}-item-meta-description`},s));return a.default.createElement("div",Object.assign({},c,{className:m}),n&&a.default.createElement("div",{className:`${u}-item-meta-avatar`},n),(l||s)&&p)},e.i(296059);var b=e.i(915654),x=e.i(183293),y=e.i(246422),C=e.i(838378);let $=(0,y.genStyleHooks)("List",e=>{let t=(0,C.mergeToken)(e,{listBorderedCls:`${e.componentCls}-bordered`,minHeight:e.controlHeightLG});return[(e=>{let{componentCls:t,antCls:a,controlHeight:r,minHeight:o,paddingSM:n,marginLG:i,padding:l,itemPadding:s,colorPrimary:c,itemPaddingSM:d,itemPaddingLG:u,paddingXS:m,margin:p,colorText:g,colorTextDescription:f,motionDurationSlow:h,lineWidth:v,headerBg:y,footerBg:C,emptyTextPadding:$,metaMarginBottom:k,avatarMarginRight:O,titleMarginBottom:w,descriptionFontSize:A}=e;return{[t]:Object.assign(Object.assign({},(0,x.resetComponent)(e)),{position:"relative","--rc-virtual-list-scrollbar-bg":e.colorSplit,"*":{outline:"none"},[`${t}-header`]:{background:y},[`${t}-footer`]:{background:C},[`${t}-header, ${t}-footer`]:{paddingBlock:n},[`${t}-pagination`]:{marginBlockStart:i,[`${a}-pagination-options`]:{textAlign:"start"}},[`${t}-spin`]:{minHeight:o,textAlign:"center"},[`${t}-items`]:{margin:0,padding:0,listStyle:"none"},[`${t}-item`]:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:s,color:g,[`${t}-item-meta`]:{display:"flex",flex:1,alignItems:"flex-start",maxWidth:"100%",[`${t}-item-meta-avatar`]:{marginInlineEnd:O},[`${t}-item-meta-content`]:{flex:"1 0",width:0,color:g},[`${t}-item-meta-title`]:{margin:`0 0 ${(0,b.unit)(e.marginXXS)} 0`,color:g,fontSize:e.fontSize,lineHeight:e.lineHeight,"> a":{color:g,transition:`all ${h}`,"&:hover":{color:c}}},[`${t}-item-meta-description`]:{color:f,fontSize:A,lineHeight:e.lineHeight}},[`${t}-item-action`]:{flex:"0 0 auto",marginInlineStart:e.marginXXL,padding:0,fontSize:0,listStyle:"none","& > li":{position:"relative",display:"inline-block",padding:`0 ${(0,b.unit)(m)}`,color:f,fontSize:e.fontSize,lineHeight:e.lineHeight,textAlign:"center","&:first-child":{paddingInlineStart:0}},[`${t}-item-action-split`]:{position:"absolute",insetBlockStart:"50%",insetInlineEnd:0,width:v,height:e.calc(e.fontHeight).sub(e.calc(e.marginXXS).mul(2)).equal(),transform:"translateY(-50%)",backgroundColor:e.colorSplit}}},[`${t}-empty`]:{padding:`${(0,b.unit)(l)} 0`,color:f,fontSize:e.fontSizeSM,textAlign:"center"},[`${t}-empty-text`]:{padding:$,color:e.colorTextDisabled,fontSize:e.fontSize,textAlign:"center"},[`${t}-item-no-flex`]:{display:"block"}}),[`${t}-grid ${a}-col > ${t}-item`]:{display:"block",maxWidth:"100%",marginBlockEnd:p,paddingBlock:0,borderBlockEnd:"none"},[`${t}-vertical ${t}-item`]:{alignItems:"initial",[`${t}-item-main`]:{display:"block",flex:1},[`${t}-item-extra`]:{marginInlineStart:i},[`${t}-item-meta`]:{marginBlockEnd:k,[`${t}-item-meta-title`]:{marginBlockStart:0,marginBlockEnd:w,color:g,fontSize:e.fontSizeLG,lineHeight:e.lineHeightLG}},[`${t}-item-action`]:{marginBlockStart:l,marginInlineStart:"auto","> li":{padding:`0 ${(0,b.unit)(l)}`,"&:first-child":{paddingInlineStart:0}}}},[`${t}-split ${t}-item`]:{borderBlockEnd:`${(0,b.unit)(e.lineWidth)} ${e.lineType} ${e.colorSplit}`,"&:last-child":{borderBlockEnd:"none"}},[`${t}-split ${t}-header`]:{borderBlockEnd:`${(0,b.unit)(e.lineWidth)} ${e.lineType} ${e.colorSplit}`},[`${t}-split${t}-empty ${t}-footer`]:{borderTop:`${(0,b.unit)(e.lineWidth)} ${e.lineType} ${e.colorSplit}`},[`${t}-loading ${t}-spin-nested-loading`]:{minHeight:r},[`${t}-split${t}-something-after-last-item ${a}-spin-container > ${t}-items > ${t}-item:last-child`]:{borderBlockEnd:`${(0,b.unit)(e.lineWidth)} ${e.lineType} ${e.colorSplit}`},[`${t}-lg ${t}-item`]:{padding:u},[`${t}-sm ${t}-item`]:{padding:d},[`${t}:not(${t}-vertical)`]:{[`${t}-item-no-flex`]:{[`${t}-item-action`]:{float:"right"}}}}})(t),(e=>{let{listBorderedCls:t,componentCls:a,paddingLG:r,margin:o,itemPaddingSM:n,itemPaddingLG:i,marginLG:l,borderRadiusLG:s}=e,c=(0,b.unit)(e.calc(s).sub(e.lineWidth).equal());return{[t]:{border:`${(0,b.unit)(e.lineWidth)} ${e.lineType} ${e.colorBorder}`,borderRadius:s,[`${a}-header`]:{borderRadius:`${c} ${c} 0 0`},[`${a}-footer`]:{borderRadius:`0 0 ${c} ${c}`},[`${a}-header,${a}-footer,${a}-item`]:{paddingInline:r},[`${a}-pagination`]:{margin:`${(0,b.unit)(o)} ${(0,b.unit)(l)}`}},[`${t}${a}-sm`]:{[`${a}-item,${a}-header,${a}-footer`]:{padding:n}},[`${t}${a}-lg`]:{[`${a}-item,${a}-header,${a}-footer`]:{padding:i}}}})(t),(e=>{let{componentCls:t,screenSM:a,screenMD:r,marginLG:o,marginSM:n,margin:i}=e;return{[`@media screen and (max-width:${r}px)`]:{[t]:{[`${t}-item`]:{[`${t}-item-action`]:{marginInlineStart:o}}},[`${t}-vertical`]:{[`${t}-item`]:{[`${t}-item-extra`]:{marginInlineStart:o}}}},[`@media screen and (max-width: ${a}px)`]:{[t]:{[`${t}-item`]:{flexWrap:"wrap",[`${t}-action`]:{marginInlineStart:n}}},[`${t}-vertical`]:{[`${t}-item`]:{flexWrap:"wrap-reverse",[`${t}-item-main`]:{minWidth:e.contentWidth},[`${t}-item-extra`]:{margin:`auto auto ${(0,b.unit)(i)}`}}}}}})(t)]},e=>({contentWidth:220,itemPadding:`${(0,b.unit)(e.paddingContentVertical)} 0`,itemPaddingSM:`${(0,b.unit)(e.paddingContentVerticalSM)} ${(0,b.unit)(e.paddingContentHorizontal)}`,itemPaddingLG:`${(0,b.unit)(e.paddingContentVerticalLG)} ${(0,b.unit)(e.paddingContentHorizontalLG)}`,headerBg:"transparent",footerBg:"transparent",emptyTextPadding:e.padding,metaMarginBottom:e.padding,avatarMarginRight:e.padding,titleMarginBottom:e.paddingSM,descriptionFontSize:e.fontSize}));var k=function(e,t){var a={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(a[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);ot.indexOf(r[o])&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(a[r[o]]=e[r[o]]);return a};let O=a.forwardRef(function(e,g){let{pagination:f=!1,prefixCls:h,bordered:v=!1,split:b=!0,className:x,rootClassName:y,style:C,children:O,itemLayout:w,loadMore:A,grid:E,dataSource:S=[],size:I,header:T,footer:N,loading:M=!1,rowKey:z,renderItem:L,locale:_}=e,j=k(e,["pagination","prefixCls","bordered","split","className","rootClassName","style","children","itemLayout","loadMore","grid","dataSource","size","header","footer","loading","rowKey","renderItem","locale"]),R=f&&"object"==typeof f?f:{},[P,D]=a.useState(R.defaultCurrent||1),[B,H]=a.useState(R.defaultPageSize||10),{getPrefixCls:V,direction:W,className:F,style:G}=(0,i.useComponentConfig)("list"),{renderEmpty:X}=a.useContext(i.ConfigContext),U=e=>(t,a)=>{var r;D(t),H(a),f&&(null==(r=null==f?void 0:f[e])||r.call(f,t,a))},q=U("onChange"),K=U("onShowSizeChange"),Y=!!(A||f||N),Z=V("list",h),[J,Q,ee]=$(Z),et=M;"boolean"==typeof et&&(et={spinning:et});let ea=!!(null==et?void 0:et.spinning),er=(0,s.default)(I),eo="";switch(er){case"large":eo="lg";break;case"small":eo="sm"}let en=(0,r.default)(Z,{[`${Z}-vertical`]:"vertical"===w,[`${Z}-${eo}`]:eo,[`${Z}-split`]:b,[`${Z}-bordered`]:v,[`${Z}-loading`]:ea,[`${Z}-grid`]:!!E,[`${Z}-something-after-last-item`]:Y,[`${Z}-rtl`]:"rtl"===W},F,x,y,Q,ee),ei=(0,o.default)({current:1,total:0,position:"bottom"},{total:S.length,current:P,pageSize:B},f||{}),el=Math.ceil(ei.total/ei.pageSize);ei.current=Math.min(ei.current,el);let es=f&&a.createElement("div",{className:(0,r.default)(`${Z}-pagination`)},a.createElement(u.default,Object.assign({align:"end"},ei,{onChange:q,onShowSizeChange:K}))),ec=(0,t.default)(S);f&&S.length>(ei.current-1)*ei.pageSize&&(ec=(0,t.default)(S).splice((ei.current-1)*ei.pageSize,ei.pageSize));let ed=Object.keys(E||{}).some(e=>["xs","sm","md","lg","xl","xxl"].includes(e)),eu=(0,d.default)(ed),em=a.useMemo(()=>{for(let e=0;e{if(!E)return;let e=em&&E[em]?E[em]:E.column;if(e)return{width:`${100/e}%`,maxWidth:`${100/e}%`}},[JSON.stringify(E),em]),eg=ea&&a.createElement("div",{style:{minHeight:53}});if(ec.length>0){let e=ec.map((e,t)=>{let r;return L?((r="function"==typeof z?z(e):z?e[z]:e.key)||(r=`list-item-${t}`),a.createElement(a.Fragment,{key:r},L(e,t))):null});eg=E?a.createElement(c.Row,{gutter:E.gutter},a.Children.map(e,e=>a.createElement("div",{key:null==e?void 0:e.key,style:ep},e))):a.createElement("ul",{className:`${Z}-items`},e)}else O||ea||(eg=a.createElement("div",{className:`${Z}-empty-text`},(null==_?void 0:_.emptyText)||(null==X?void 0:X("List"))||a.createElement(l.default,{componentName:"List"})));let ef=ei.position,eh=a.useMemo(()=>({grid:E,itemLayout:w}),[JSON.stringify(E),w]);return J(a.createElement(p.Provider,{value:eh},a.createElement("div",Object.assign({ref:g,style:Object.assign(Object.assign({},G),C),className:en},j),("top"===ef||"both"===ef)&&es,T&&a.createElement("div",{className:`${Z}-header`},T),a.createElement(m.default,Object.assign({},et),eg,O),N&&a.createElement("div",{className:`${Z}-footer`},N),A||("bottom"===ef||"both"===ef)&&es)))});O.Item=v,e.s(["List",0,O],573421)},903446,e=>{"use strict";let t=(0,e.i(475254).default)("settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);e.s(["default",()=>t])},219470,812618,e=>{"use strict";e.s(["coy",0,{'code[class*="language-"]':{color:"black",background:"none",fontFamily:"Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace",fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",maxHeight:"inherit",height:"inherit",padding:"0 1em",display:"block",overflow:"auto"},'pre[class*="language-"]':{color:"black",background:"none",fontFamily:"Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace",fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",position:"relative",margin:".5em 0",overflow:"visible",padding:"1px",backgroundColor:"#fdfdfd",WebkitBoxSizing:"border-box",MozBoxSizing:"border-box",boxSizing:"border-box",marginBottom:"1em"},'pre[class*="language-"] > code':{position:"relative",zIndex:"1",borderLeft:"10px solid #358ccb",boxShadow:"-1px 0px 0px 0px #358ccb, 0px 0px 0px 1px #dfdfdf",backgroundColor:"#fdfdfd",backgroundImage:"linear-gradient(transparent 50%, rgba(69, 142, 209, 0.04) 50%)",backgroundSize:"3em 3em",backgroundOrigin:"content-box",backgroundAttachment:"local"},':not(pre) > code[class*="language-"]':{backgroundColor:"#fdfdfd",WebkitBoxSizing:"border-box",MozBoxSizing:"border-box",boxSizing:"border-box",marginBottom:"1em",position:"relative",padding:".2em",borderRadius:"0.3em",color:"#c92c2c",border:"1px solid rgba(0, 0, 0, 0.1)",display:"inline",whiteSpace:"normal"},'pre[class*="language-"]:before':{content:"''",display:"block",position:"absolute",bottom:"0.75em",left:"0.18em",width:"40%",height:"20%",maxHeight:"13em",boxShadow:"0px 13px 8px #979797",WebkitTransform:"rotate(-2deg)",MozTransform:"rotate(-2deg)",msTransform:"rotate(-2deg)",OTransform:"rotate(-2deg)",transform:"rotate(-2deg)"},'pre[class*="language-"]:after':{content:"''",display:"block",position:"absolute",bottom:"0.75em",left:"auto",width:"40%",height:"20%",maxHeight:"13em",boxShadow:"0px 13px 8px #979797",WebkitTransform:"rotate(2deg)",MozTransform:"rotate(2deg)",msTransform:"rotate(2deg)",OTransform:"rotate(2deg)",transform:"rotate(2deg)",right:"0.75em"},comment:{color:"#7D8B99"},"block-comment":{color:"#7D8B99"},prolog:{color:"#7D8B99"},doctype:{color:"#7D8B99"},cdata:{color:"#7D8B99"},punctuation:{color:"#5F6364"},property:{color:"#c92c2c"},tag:{color:"#c92c2c"},boolean:{color:"#c92c2c"},number:{color:"#c92c2c"},"function-name":{color:"#c92c2c"},constant:{color:"#c92c2c"},symbol:{color:"#c92c2c"},deleted:{color:"#c92c2c"},selector:{color:"#2f9c0a"},"attr-name":{color:"#2f9c0a"},string:{color:"#2f9c0a"},char:{color:"#2f9c0a"},function:{color:"#2f9c0a"},builtin:{color:"#2f9c0a"},inserted:{color:"#2f9c0a"},operator:{color:"#a67f59",background:"rgba(255, 255, 255, 0.5)"},entity:{color:"#a67f59",background:"rgba(255, 255, 255, 0.5)",cursor:"help"},url:{color:"#a67f59",background:"rgba(255, 255, 255, 0.5)"},variable:{color:"#a67f59",background:"rgba(255, 255, 255, 0.5)"},atrule:{color:"#1990b8"},"attr-value":{color:"#1990b8"},keyword:{color:"#1990b8"},"class-name":{color:"#1990b8"},regex:{color:"#e90"},important:{color:"#e90",fontWeight:"normal"},".language-css .token.string":{color:"#a67f59",background:"rgba(255, 255, 255, 0.5)"},".style .token.string":{color:"#a67f59",background:"rgba(255, 255, 255, 0.5)"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},namespace:{Opacity:".7"},'pre[class*="language-"].line-numbers.line-numbers':{paddingLeft:"0"},'pre[class*="language-"].line-numbers.line-numbers code':{paddingLeft:"3.8em"},'pre[class*="language-"].line-numbers.line-numbers .line-numbers-rows':{left:"0"},'pre[class*="language-"][data-line]':{paddingTop:"0",paddingBottom:"0",paddingLeft:"0"},"pre[data-line] code":{position:"relative",paddingLeft:"4em"},"pre .line-highlight":{marginTop:"0"}}],219470),e.i(247167);var t=e.i(931067),a=e.i(271645);let r={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M632 888H392c-4.4 0-8 3.6-8 8v32c0 17.7 14.3 32 32 32h192c17.7 0 32-14.3 32-32v-32c0-4.4-3.6-8-8-8zM512 64c-181.1 0-328 146.9-328 328 0 121.4 66 227.4 164 284.1V792c0 17.7 14.3 32 32 32h264c17.7 0 32-14.3 32-32V676.1c98-56.7 164-162.7 164-284.1 0-181.1-146.9-328-328-328zm127.9 549.8L604 634.6V752H420V634.6l-35.9-20.8C305.4 568.3 256 484.5 256 392c0-141.4 114.6-256 256-256s256 114.6 256 256c0 92.5-49.4 176.3-128.1 221.8z"}}]},name:"bulb",theme:"outlined"};var o=e.i(9583),n=a.forwardRef(function(e,n){return a.createElement(o.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["BulbOutlined",0,n],812618)},458505,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let r={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"};var o=e.i(9583),n=a.forwardRef(function(e,n){return a.createElement(o.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["DollarOutlined",0,n],458505)},245094,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let r={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M516 673c0 4.4 3.4 8 7.5 8h185c4.1 0 7.5-3.6 7.5-8v-48c0-4.4-3.4-8-7.5-8h-185c-4.1 0-7.5 3.6-7.5 8v48zm-194.9 6.1l192-161c3.8-3.2 3.8-9.1 0-12.3l-192-160.9A7.95 7.95 0 00308 351v62.7c0 2.4 1 4.6 2.9 6.1L420.7 512l-109.8 92.2a8.1 8.1 0 00-2.9 6.1V673c0 6.8 7.9 10.5 13.1 6.1zM880 112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32zm-40 728H184V184h656v656z"}}]},name:"code",theme:"outlined"};var o=e.i(9583),n=a.forwardRef(function(e,n){return a.createElement(o.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["CodeOutlined",0,n],245094)},872934,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let r={icon:{tag:"svg",attrs:{"fill-rule":"evenodd",viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M880 912H144c-17.7 0-32-14.3-32-32V144c0-17.7 14.3-32 32-32h360c4.4 0 8 3.6 8 8v56c0 4.4-3.6 8-8 8H184v656h656V520c0-4.4 3.6-8 8-8h56c4.4 0 8 3.6 8 8v360c0 17.7-14.3 32-32 32zM770.87 199.13l-52.2-52.2a8.01 8.01 0 014.7-13.6l179.4-21c5.1-.6 9.5 3.7 8.9 8.9l-21 179.4c-.8 6.6-8.9 9.4-13.6 4.7l-52.4-52.4-256.2 256.2a8.03 8.03 0 01-11.3 0l-42.4-42.4a8.03 8.03 0 010-11.3l256.1-256.3z"}}]},name:"export",theme:"outlined"};var o=e.i(9583),n=a.forwardRef(function(e,n){return a.createElement(o.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["ExportOutlined",0,n],872934)},447593,989022,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645),r={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"defs",attrs:{},children:[{tag:"style",attrs:{}}]},{tag:"path",attrs:{d:"M899.1 869.6l-53-305.6H864c14.4 0 26-11.6 26-26V346c0-14.4-11.6-26-26-26H618V138c0-14.4-11.6-26-26-26H432c-14.4 0-26 11.6-26 26v182H160c-14.4 0-26 11.6-26 26v192c0 14.4 11.6 26 26 26h17.9l-53 305.6a25.95 25.95 0 0025.6 30.4h723c1.5 0 3-.1 4.4-.4a25.88 25.88 0 0021.2-30zM204 390h272V182h72v208h272v104H204V390zm468 440V674c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v156H416V674c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v156H202.8l45.1-260H776l45.1 260H672z"}}]},name:"clear",theme:"outlined"},o=e.i(9583),n=a.forwardRef(function(e,n){return a.createElement(o.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["ClearOutlined",0,n],447593);var i=e.i(843476),l=e.i(592968),s=e.i(637235);let c={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M872 394c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8H708V152c0-4.4-3.6-8-8-8h-64c-4.4 0-8 3.6-8 8v166H400V152c0-4.4-3.6-8-8-8h-64c-4.4 0-8 3.6-8 8v166H152c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h168v236H152c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h168v166c0 4.4 3.6 8 8 8h64c4.4 0 8-3.6 8-8V706h228v166c0 4.4 3.6 8 8 8h64c4.4 0 8-3.6 8-8V706h164c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8H708V394h164zM628 630H400V394h228v236z"}}]},name:"number",theme:"outlined"};var d=a.forwardRef(function(e,r){return a.createElement(o.default,(0,t.default)({},e,{ref:r,icon:c}))});let u={icon:{tag:"svg",attrs:{"fill-rule":"evenodd",viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M880 912H144c-17.7 0-32-14.3-32-32V144c0-17.7 14.3-32 32-32h360c4.4 0 8 3.6 8 8v56c0 4.4-3.6 8-8 8H184v656h656V520c0-4.4 3.6-8 8-8h56c4.4 0 8 3.6 8 8v360c0 17.7-14.3 32-32 32zM653.3 424.6l52.2 52.2a8.01 8.01 0 01-4.7 13.6l-179.4 21c-5.1.6-9.5-3.7-8.9-8.9l21-179.4c.8-6.6 8.9-9.4 13.6-4.7l52.4 52.4 256.2-256.2c3.1-3.1 8.2-3.1 11.3 0l42.4 42.4c3.1 3.1 3.1 8.2 0 11.3L653.3 424.6z"}}]},name:"import",theme:"outlined"};var m=a.forwardRef(function(e,r){return a.createElement(o.default,(0,t.default)({},e,{ref:r,icon:u}))}),p=e.i(872934),g=e.i(812618),f=e.i(366308),h=e.i(458505);e.s(["default",0,({timeToFirstToken:e,totalLatency:t,usage:a,toolName:r})=>e||t||a?(0,i.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!==e&&(0,i.jsx)(l.Tooltip,{title:"Time to first token",children:(0,i.jsxs)("div",{className:"flex items-center",children:[(0,i.jsx)(s.ClockCircleOutlined,{className:"mr-1"}),(0,i.jsxs)("span",{children:["TTFT: ",(e/1e3).toFixed(2),"s"]})]})}),void 0!==t&&(0,i.jsx)(l.Tooltip,{title:"Total latency",children:(0,i.jsxs)("div",{className:"flex items-center",children:[(0,i.jsx)(s.ClockCircleOutlined,{className:"mr-1"}),(0,i.jsxs)("span",{children:["Total Latency: ",(t/1e3).toFixed(2),"s"]})]})}),a?.promptTokens!==void 0&&(0,i.jsx)(l.Tooltip,{title:"Prompt tokens",children:(0,i.jsxs)("div",{className:"flex items-center",children:[(0,i.jsx)(m,{className:"mr-1"}),(0,i.jsxs)("span",{children:["In: ",a.promptTokens]})]})}),a?.completionTokens!==void 0&&(0,i.jsx)(l.Tooltip,{title:"Completion tokens",children:(0,i.jsxs)("div",{className:"flex items-center",children:[(0,i.jsx)(p.ExportOutlined,{className:"mr-1"}),(0,i.jsxs)("span",{children:["Out: ",a.completionTokens]})]})}),a?.reasoningTokens!==void 0&&(0,i.jsx)(l.Tooltip,{title:"Reasoning tokens",children:(0,i.jsxs)("div",{className:"flex items-center",children:[(0,i.jsx)(g.BulbOutlined,{className:"mr-1"}),(0,i.jsxs)("span",{children:["Reasoning: ",a.reasoningTokens]})]})}),a?.totalTokens!==void 0&&(0,i.jsx)(l.Tooltip,{title:"Total tokens",children:(0,i.jsxs)("div",{className:"flex items-center",children:[(0,i.jsx)(d,{className:"mr-1"}),(0,i.jsxs)("span",{children:["Total: ",a.totalTokens]})]})}),a?.cost!==void 0&&(0,i.jsx)(l.Tooltip,{title:"Cost",children:(0,i.jsxs)("div",{className:"flex items-center",children:[(0,i.jsx)(h.DollarOutlined,{className:"mr-1"}),(0,i.jsxs)("span",{children:["$",a.cost.toFixed(6)]})]})}),r&&(0,i.jsx)(l.Tooltip,{title:"Tool used",children:(0,i.jsxs)("div",{className:"flex items-center",children:[(0,i.jsx)(f.ToolOutlined,{className:"mr-1"}),(0,i.jsxs)("span",{children:["Tool: ",r]})]})})]}):null],989022)},132104,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let r={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M868 545.5L536.1 163a31.96 31.96 0 00-48.3 0L156 545.5a7.97 7.97 0 006 13.2h81c4.6 0 9-2 12.1-5.5L474 300.9V864c0 4.4 3.6 8 8 8h60c4.4 0 8-3.6 8-8V300.9l218.9 252.3c3 3.5 7.4 5.5 12.1 5.5h81c6.8 0 10.5-8 6-13.2z"}}]},name:"arrow-up",theme:"outlined"};var o=e.i(9583),n=a.forwardRef(function(e,n){return a.createElement(o.default,(0,t.default)({},e,{ref:n,icon:r}))});e.s(["ArrowUpOutlined",0,n],132104)},608856,e=>{"use strict";e.i(247167);var t=e.i(271645),a=e.i(343794),r=e.i(209428),o=e.i(392221),n=e.i(951160),i=e.i(174428),l=t.createContext(null),s=t.createContext({}),c=e.i(211577),d=e.i(931067),u=e.i(361275),m=e.i(404948),p=e.i(244009),g=e.i(703923),f=e.i(611935),h=["prefixCls","className","containerRef"];let v=function(e){var r=e.prefixCls,o=e.className,n=e.containerRef,i=(0,g.default)(e,h),l=t.useContext(s).panel,c=(0,f.useComposeRef)(l,n);return t.createElement("div",(0,d.default)({className:(0,a.default)("".concat(r,"-content"),o),role:"dialog",ref:c},(0,p.default)(e,{aria:!0}),{"aria-modal":"true"},i))};var b=e.i(883110);function x(e){return"string"==typeof e&&String(Number(e))===e?((0,b.default)(!1,"Invalid value type of `width` or `height` which should be number type instead."),Number(e)):e}e.i(654310);var y={width:0,height:0,overflow:"hidden",outline:"none",position:"absolute"},C=t.forwardRef(function(e,n){var i,s,g,f=e.prefixCls,h=e.open,b=e.placement,C=e.inline,$=e.push,k=e.forceRender,O=e.autoFocus,w=e.keyboard,A=e.classNames,E=e.rootClassName,S=e.rootStyle,I=e.zIndex,T=e.className,N=e.id,M=e.style,z=e.motion,L=e.width,_=e.height,j=e.children,R=e.mask,P=e.maskClosable,D=e.maskMotion,B=e.maskClassName,H=e.maskStyle,V=e.afterOpenChange,W=e.onClose,F=e.onMouseEnter,G=e.onMouseOver,X=e.onMouseLeave,U=e.onClick,q=e.onKeyDown,K=e.onKeyUp,Y=e.styles,Z=e.drawerRender,J=t.useRef(),Q=t.useRef(),ee=t.useRef();t.useImperativeHandle(n,function(){return J.current}),t.useEffect(function(){if(h&&O){var e;null==(e=J.current)||e.focus({preventScroll:!0})}},[h]);var et=t.useState(!1),ea=(0,o.default)(et,2),er=ea[0],eo=ea[1],en=t.useContext(l),ei=null!=(i=null!=(s=null==(g="boolean"==typeof $?$?{}:{distance:0}:$||{})?void 0:g.distance)?s:null==en?void 0:en.pushDistance)?i:180,el=t.useMemo(function(){return{pushDistance:ei,push:function(){eo(!0)},pull:function(){eo(!1)}}},[ei]);t.useEffect(function(){var e,t;h?null==en||null==(e=en.push)||e.call(en):null==en||null==(t=en.pull)||t.call(en)},[h]),t.useEffect(function(){return function(){var e;null==en||null==(e=en.pull)||e.call(en)}},[]);var es=t.createElement(u.default,(0,d.default)({key:"mask"},D,{visible:R&&h}),function(e,o){var n=e.className,i=e.style;return t.createElement("div",{className:(0,a.default)("".concat(f,"-mask"),n,null==A?void 0:A.mask,B),style:(0,r.default)((0,r.default)((0,r.default)({},i),H),null==Y?void 0:Y.mask),onClick:P&&h?W:void 0,ref:o})}),ec="function"==typeof z?z(b):z,ed={};if(er&&ei)switch(b){case"top":ed.transform="translateY(".concat(ei,"px)");break;case"bottom":ed.transform="translateY(".concat(-ei,"px)");break;case"left":ed.transform="translateX(".concat(ei,"px)");break;default:ed.transform="translateX(".concat(-ei,"px)")}"left"===b||"right"===b?ed.width=x(L):ed.height=x(_);var eu={onMouseEnter:F,onMouseOver:G,onMouseLeave:X,onClick:U,onKeyDown:q,onKeyUp:K},em=t.createElement(u.default,(0,d.default)({key:"panel"},ec,{visible:h,forceRender:k,onVisibleChanged:function(e){null==V||V(e)},removeOnLeave:!1,leavedClassName:"".concat(f,"-content-wrapper-hidden")}),function(o,n){var i=o.className,l=o.style,s=t.createElement(v,(0,d.default)({id:N,containerRef:n,prefixCls:f,className:(0,a.default)(T,null==A?void 0:A.content),style:(0,r.default)((0,r.default)({},M),null==Y?void 0:Y.content)},(0,p.default)(e,{aria:!0}),eu),j);return t.createElement("div",(0,d.default)({className:(0,a.default)("".concat(f,"-content-wrapper"),null==A?void 0:A.wrapper,i),style:(0,r.default)((0,r.default)((0,r.default)({},ed),l),null==Y?void 0:Y.wrapper)},(0,p.default)(e,{data:!0})),Z?Z(s):s)}),ep=(0,r.default)({},S);return I&&(ep.zIndex=I),t.createElement(l.Provider,{value:el},t.createElement("div",{className:(0,a.default)(f,"".concat(f,"-").concat(b),E,(0,c.default)((0,c.default)({},"".concat(f,"-open"),h),"".concat(f,"-inline"),C)),style:ep,tabIndex:-1,ref:J,onKeyDown:function(e){var t,a,r=e.keyCode,o=e.shiftKey;switch(r){case m.default.TAB:r===m.default.TAB&&(o||document.activeElement!==ee.current?o&&document.activeElement===Q.current&&(null==(a=ee.current)||a.focus({preventScroll:!0})):null==(t=Q.current)||t.focus({preventScroll:!0}));break;case m.default.ESC:W&&w&&(e.stopPropagation(),W(e))}}},es,t.createElement("div",{tabIndex:0,ref:Q,style:y,"aria-hidden":"true","data-sentinel":"start"}),em,t.createElement("div",{tabIndex:0,ref:ee,style:y,"aria-hidden":"true","data-sentinel":"end"})))});let $=function(e){var a=e.open,l=e.prefixCls,c=e.placement,d=e.autoFocus,u=e.keyboard,m=e.width,p=e.mask,g=void 0===p||p,f=e.maskClosable,h=e.getContainer,v=e.forceRender,b=e.afterOpenChange,x=e.destroyOnClose,y=e.onMouseEnter,$=e.onMouseOver,k=e.onMouseLeave,O=e.onClick,w=e.onKeyDown,A=e.onKeyUp,E=e.panelRef,S=t.useState(!1),I=(0,o.default)(S,2),T=I[0],N=I[1],M=t.useState(!1),z=(0,o.default)(M,2),L=z[0],_=z[1];(0,i.default)(function(){_(!0)},[]);var j=!!L&&void 0!==a&&a,R=t.useRef(),P=t.useRef();(0,i.default)(function(){j&&(P.current=document.activeElement)},[j]);var D=t.useMemo(function(){return{panel:E}},[E]);if(!v&&!T&&!j&&x)return null;var B=(0,r.default)((0,r.default)({},e),{},{open:j,prefixCls:void 0===l?"rc-drawer":l,placement:void 0===c?"right":c,autoFocus:void 0===d||d,keyboard:void 0===u||u,width:void 0===m?378:m,mask:g,maskClosable:void 0===f||f,inline:!1===h,afterOpenChange:function(e){var t,a;N(e),null==b||b(e),e||!P.current||null!=(t=R.current)&&t.contains(P.current)||null==(a=P.current)||a.focus({preventScroll:!0})},ref:R},{onMouseEnter:y,onMouseOver:$,onMouseLeave:k,onClick:O,onKeyDown:w,onKeyUp:A});return t.createElement(s.Provider,{value:D},t.createElement(n.default,{open:j||v||T,autoDestroy:!1,getContainer:h,autoLock:g&&(j||T)},t.createElement(C,B)))};var k=e.i(981444),O=e.i(617206),w=e.i(122767),A=e.i(613541),E=e.i(340010),S=e.i(242064),I=e.i(922611),T=e.i(563113),N=e.i(185793);let M=e=>{var r,o,n,i;let l,{prefixCls:s,ariaId:c,title:d,footer:u,extra:m,closable:p,loading:g,onClose:f,headerStyle:h,bodyStyle:v,footerStyle:b,children:x,classNames:y,styles:C}=e,$=(0,S.useComponentConfig)("drawer");l=!1===p?void 0:void 0===p||!0===p?"start":(null==p?void 0:p.placement)==="end"?"end":"start";let k=t.useCallback(e=>t.createElement("button",{type:"button",onClick:f,className:(0,a.default)(`${s}-close`,{[`${s}-close-${l}`]:"end"===l})},e),[f,s,l]),[O,w]=(0,T.useClosable)((0,T.pickClosable)(e),(0,T.pickClosable)($),{closable:!0,closeIconRender:k});return t.createElement(t.Fragment,null,d||O?t.createElement("div",{style:Object.assign(Object.assign(Object.assign({},null==(n=$.styles)?void 0:n.header),h),null==C?void 0:C.header),className:(0,a.default)(`${s}-header`,{[`${s}-header-close-only`]:O&&!d&&!m},null==(i=$.classNames)?void 0:i.header,null==y?void 0:y.header)},t.createElement("div",{className:`${s}-header-title`},"start"===l&&w,d&&t.createElement("div",{className:`${s}-title`,id:c},d)),m&&t.createElement("div",{className:`${s}-extra`},m),"end"===l&&w):null,t.createElement("div",{className:(0,a.default)(`${s}-body`,null==y?void 0:y.body,null==(r=$.classNames)?void 0:r.body),style:Object.assign(Object.assign(Object.assign({},null==(o=$.styles)?void 0:o.body),v),null==C?void 0:C.body)},g?t.createElement(N.default,{active:!0,title:!1,paragraph:{rows:5},className:`${s}-body-skeleton`}):x),(()=>{var e,r;if(!u)return null;let o=`${s}-footer`;return t.createElement("div",{className:(0,a.default)(o,null==(e=$.classNames)?void 0:e.footer,null==y?void 0:y.footer),style:Object.assign(Object.assign(Object.assign({},null==(r=$.styles)?void 0:r.footer),b),null==C?void 0:C.footer)},u)})())};e.i(296059);var z=e.i(915654),L=e.i(183293),_=e.i(246422),j=e.i(838378);let R=(e,t)=>({"&-enter, &-appear":Object.assign(Object.assign({},e),{"&-active":t}),"&-leave":Object.assign(Object.assign({},t),{"&-active":e})}),P=(e,t)=>Object.assign({"&-enter, &-appear, &-leave":{"&-start":{transition:"none"},"&-active":{transition:`all ${t}`}}},R({opacity:e},{opacity:1})),D=(0,_.genStyleHooks)("Drawer",e=>{let t=(0,j.mergeToken)(e,{});return[(e=>{let{borderRadiusSM:t,componentCls:a,zIndexPopup:r,colorBgMask:o,colorBgElevated:n,motionDurationSlow:i,motionDurationMid:l,paddingXS:s,padding:c,paddingLG:d,fontSizeLG:u,lineHeightLG:m,lineWidth:p,lineType:g,colorSplit:f,marginXS:h,colorIcon:v,colorIconHover:b,colorBgTextHover:x,colorBgTextActive:y,colorText:C,fontWeightStrong:$,footerPaddingBlock:k,footerPaddingInline:O,calc:w}=e,A=`${a}-content-wrapper`;return{[a]:{position:"fixed",inset:0,zIndex:r,pointerEvents:"none",color:C,"&-pure":{position:"relative",background:n,display:"flex",flexDirection:"column",[`&${a}-left`]:{boxShadow:e.boxShadowDrawerLeft},[`&${a}-right`]:{boxShadow:e.boxShadowDrawerRight},[`&${a}-top`]:{boxShadow:e.boxShadowDrawerUp},[`&${a}-bottom`]:{boxShadow:e.boxShadowDrawerDown}},"&-inline":{position:"absolute"},[`${a}-mask`]:{position:"absolute",inset:0,zIndex:r,background:o,pointerEvents:"auto"},[A]:{position:"absolute",zIndex:r,maxWidth:"100vw",transition:`all ${i}`,"&-hidden":{display:"none"}},[`&-left > ${A}`]:{top:0,bottom:0,left:{_skip_check_:!0,value:0},boxShadow:e.boxShadowDrawerLeft},[`&-right > ${A}`]:{top:0,right:{_skip_check_:!0,value:0},bottom:0,boxShadow:e.boxShadowDrawerRight},[`&-top > ${A}`]:{top:0,insetInline:0,boxShadow:e.boxShadowDrawerUp},[`&-bottom > ${A}`]:{bottom:0,insetInline:0,boxShadow:e.boxShadowDrawerDown},[`${a}-content`]:{display:"flex",flexDirection:"column",width:"100%",height:"100%",overflow:"auto",background:n,pointerEvents:"auto"},[`${a}-header`]:{display:"flex",flex:0,alignItems:"center",padding:`${(0,z.unit)(c)} ${(0,z.unit)(d)}`,fontSize:u,lineHeight:m,borderBottom:`${(0,z.unit)(p)} ${g} ${f}`,"&-title":{display:"flex",flex:1,alignItems:"center",minWidth:0,minHeight:0}},[`${a}-extra`]:{flex:"none"},[`${a}-close`]:Object.assign({display:"inline-flex",width:w(u).add(s).equal(),height:w(u).add(s).equal(),borderRadius:t,justifyContent:"center",alignItems:"center",color:v,fontWeight:$,fontSize:u,fontStyle:"normal",lineHeight:1,textAlign:"center",textTransform:"none",textDecoration:"none",background:"transparent",border:0,cursor:"pointer",transition:`all ${l}`,textRendering:"auto",[`&${a}-close-end`]:{marginInlineStart:h},[`&:not(${a}-close-end)`]:{marginInlineEnd:h},"&:hover":{color:b,backgroundColor:x,textDecoration:"none"},"&:active":{backgroundColor:y}},(0,L.genFocusStyle)(e)),[`${a}-title`]:{flex:1,margin:0,fontWeight:e.fontWeightStrong,fontSize:u,lineHeight:m},[`${a}-body`]:{flex:1,minWidth:0,minHeight:0,padding:d,overflow:"auto",[`${a}-body-skeleton`]:{width:"100%",height:"100%",display:"flex",justifyContent:"center"}},[`${a}-footer`]:{flexShrink:0,padding:`${(0,z.unit)(k)} ${(0,z.unit)(O)}`,borderTop:`${(0,z.unit)(p)} ${g} ${f}`},"&-rtl":{direction:"rtl"}}}})(t),(e=>{let{componentCls:t,motionDurationSlow:a}=e;return{[t]:{[`${t}-mask-motion`]:P(0,a),[`${t}-panel-motion`]:["left","right","top","bottom"].reduce((e,t)=>{let r;return Object.assign(Object.assign({},e),{[`&-${t}`]:[P(.7,a),R({transform:(r="100%",({left:`translateX(-${r})`,right:`translateX(${r})`,top:`translateY(-${r})`,bottom:`translateY(${r})`})[t])},{transform:"none"})]})},{})}}})(t)]},e=>({zIndexPopup:e.zIndexPopupBase,footerPaddingBlock:e.paddingXS,footerPaddingInline:e.padding}));var B=function(e,t){var a={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&0>t.indexOf(r)&&(a[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);ot.indexOf(r[o])&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(a[r[o]]=e[r[o]]);return a};let H={distance:180},V=e=>{let{rootClassName:r,width:o,height:n,size:i="default",mask:l=!0,push:s=H,open:c,afterOpenChange:d,onClose:u,prefixCls:m,getContainer:p,panelRef:g=null,style:h,className:v,"aria-labelledby":b,visible:x,afterVisibleChange:y,maskStyle:C,drawerStyle:T,contentWrapperStyle:N,destroyOnClose:z,destroyOnHidden:L}=e,_=B(e,["rootClassName","width","height","size","mask","push","open","afterOpenChange","onClose","prefixCls","getContainer","panelRef","style","className","aria-labelledby","visible","afterVisibleChange","maskStyle","drawerStyle","contentWrapperStyle","destroyOnClose","destroyOnHidden"]),j=(0,k.default)(),R=_.title?j:void 0,{getPopupContainer:P,getPrefixCls:V,direction:W,className:F,style:G,classNames:X,styles:U}=(0,S.useComponentConfig)("drawer"),q=V("drawer",m),[K,Y,Z]=D(q),J=void 0===p&&P?()=>P(document.body):p,Q=(0,a.default)({"no-mask":!l,[`${q}-rtl`]:"rtl"===W},r,Y,Z),ee=t.useMemo(()=>null!=o?o:"large"===i?736:378,[o,i]),et=t.useMemo(()=>null!=n?n:"large"===i?736:378,[n,i]),ea={motionName:(0,A.getTransitionName)(q,"mask-motion"),motionAppear:!0,motionEnter:!0,motionLeave:!0,motionDeadline:500},er=(0,I.usePanelRef)(),eo=(0,f.composeRef)(g,er),[en,ei]=(0,w.useZIndex)("Drawer",_.zIndex),{classNames:el={},styles:es={}}=_;return K(t.createElement(O.default,{form:!0,space:!0},t.createElement(E.default.Provider,{value:ei},t.createElement($,Object.assign({prefixCls:q,onClose:u,maskMotion:ea,motion:e=>({motionName:(0,A.getTransitionName)(q,`panel-motion-${e}`),motionAppear:!0,motionEnter:!0,motionLeave:!0,motionDeadline:500})},_,{classNames:{mask:(0,a.default)(el.mask,X.mask),content:(0,a.default)(el.content,X.content),wrapper:(0,a.default)(el.wrapper,X.wrapper)},styles:{mask:Object.assign(Object.assign(Object.assign({},es.mask),C),U.mask),content:Object.assign(Object.assign(Object.assign({},es.content),T),U.content),wrapper:Object.assign(Object.assign(Object.assign({},es.wrapper),N),U.wrapper)},open:null!=c?c:x,mask:l,push:s,width:ee,height:et,style:Object.assign(Object.assign({},G),h),className:(0,a.default)(F,v),rootClassName:Q,getContainer:J,afterOpenChange:null!=d?d:y,panelRef:eo,zIndex:en,"aria-labelledby":null!=b?b:R,destroyOnClose:null!=L?L:z}),t.createElement(M,Object.assign({prefixCls:q},_,{ariaId:R,onClose:u}))))))};V._InternalPanelDoNotUseOrYouWillBeFired=e=>{let{prefixCls:r,style:o,className:n,placement:i="right"}=e,l=B(e,["prefixCls","style","className","placement"]),{getPrefixCls:s}=t.useContext(S.ConfigContext),c=s("drawer",r),[d,u,m]=D(c),p=(0,a.default)(c,`${c}-pure`,`${c}-${i}`,u,m,n);return d(t.createElement("div",{className:p,style:o},t.createElement(M,Object.assign({prefixCls:c},l))))},e.s(["Drawer",0,V],608856)},675879,e=>{"use strict";var t=e.i(843476),a=e.i(191403),r=e.i(135214);e.s(["default",0,()=>{let{accessToken:e}=(0,r.default)();return(0,t.jsx)(a.default,{accessToken:e})}])}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/1fcff413509b2e1f.js b/litellm/proxy/_experimental/out/_next/static/chunks/1fcff413509b2e1f.js new file mode 100644 index 00000000000..cc6116dad9a --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/1fcff413509b2e1f.js @@ -0,0 +1,7 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,91739,e=>{"use strict";var t=e.i(544195);e.s(["Radio",()=>t.default])},841947,e=>{"use strict";let t=(0,e.i(475254).default)("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);e.s(["default",()=>t])},361653,e=>{"use strict";let t=(0,e.i(475254).default)("circle-alert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);e.s(["default",()=>t])},409797,e=>{"use strict";var t=e.i(631171);e.s(["ChevronDownIcon",()=>t.default])},500727,696609,531516,e=>{"use strict";var t=e.i(266027),r=e.i(243652),o=e.i(764205),a=e.i(135214);let l=(0,r.createQueryKeys)("mcpServers");e.s(["useMCPServers",0,e=>{let{accessToken:r}=(0,a.default)();return(0,t.useQuery)({queryKey:l.list(e?{filters:{teamId:e}}:void 0),queryFn:async()=>await (0,o.fetchMCPServers)(r,e),enabled:!!r})}],500727);var n=e.i(843476),i=e.i(271645),s=e.i(536916),d=e.i(599724),c=e.i(409797),u=e.i(246349),u=u;let m=/\b(delete|remove|destroy|purge|drop|erase|unlink)\b/i,f=/\b(create|add|insert|new|post|submit|register|make|generate|write|upload)\b/i,g=/\b(update|edit|modify|change|patch|put|set|rename|move|transform)\b/i,p=/\b(get|read|list|fetch|search|find|query|retrieve|show|view|check|describe|info)\b/i;function b(e,t=""){let r=e.toLowerCase();if(p.test(r))return"read";if(m.test(r))return"delete";if(g.test(r))return"update";if(f.test(r))return"create";if(t){let e=t.toLowerCase();if(p.test(e))return"read";if(m.test(e))return"delete";if(g.test(e))return"update";if(f.test(e))return"create"}return"unknown"}function h(e){let t={read:[],create:[],update:[],delete:[],unknown:[]};for(let r of e)t[b(r.name,r.description)].push(r);return t}let x={read:{label:"Read",description:"Safe operations — fetch, list, search. No side effects.",risk:"low"},create:{label:"Create",description:"Add new resources — insert, upload, register.",risk:"medium"},update:{label:"Update",description:"Modify existing resources — edit, patch, rename.",risk:"medium"},delete:{label:"Delete",description:"Destructive operations — remove, purge, destroy.",risk:"high"},unknown:{label:"Other",description:"Operations that could not be automatically classified.",risk:"unknown"}};e.s(["CRUD_GROUP_META",0,x,"classifyToolOp",()=>b,"groupToolsByCrud",()=>h],696609);let v=["read","create","update","delete","unknown"],C={low:"bg-green-100 text-green-800",medium:"bg-yellow-100 text-yellow-800",high:"bg-red-100 text-red-800 font-semibold",unknown:"bg-gray-100 text-gray-700"},y={read:"border-green-200",create:"border-blue-200",update:"border-yellow-200",delete:"border-red-300",unknown:"border-gray-200"},k={read:"bg-green-50",create:"bg-blue-50",update:"bg-yellow-50",delete:"bg-red-50",unknown:"bg-gray-50"};e.s(["default",0,({tools:e,value:t,onChange:r,readOnly:o=!1,searchFilter:a=""})=>{let[l,m]=(0,i.useState)({read:!1,create:!1,update:!1,delete:!1,unknown:!0}),f=(0,i.useMemo)(()=>h(e),[e]),g=(0,i.useMemo)(()=>new Set(void 0===t?e.map(e=>e.name):t),[t,e]),p=e=>{if(o)return;let t=new Set(g);t.has(e)?t.delete(e):t.add(e),r(Array.from(t))};return 0===e.length?null:(0,n.jsx)("div",{className:"space-y-3",children:v.map(e=>{let t,i=f[e];if(0===i.length)return null;if(a){let e=a.toLowerCase();if(!i.some(t=>t.name.toLowerCase().includes(e)||(t.description??"").toLowerCase().includes(e)))return null}let b=x[e],h=(t=f[e]).length>0&&t.every(e=>g.has(e.name)),v=(e=>{let t=f[e];if(0===t.length)return!1;let r=t.filter(e=>g.has(e.name)).length;return r>0&&r{m(t=>({...t,[e]:!t[e]}))},children:[w?(0,n.jsx)(u.default,{className:"w-4 h-4 text-gray-500 flex-shrink-0"}):(0,n.jsx)(c.ChevronDownIcon,{className:"w-4 h-4 text-gray-500 flex-shrink-0"}),(0,n.jsx)("span",{className:"font-semibold text-gray-900 text-sm",children:b.label}),(0,n.jsx)("span",{className:`text-xs px-2 py-0.5 rounded-full ${C[b.risk]}`,children:"high"===b.risk?"High Risk":"medium"===b.risk?"Medium Risk":"low"===b.risk?"Safe":"Unclassified"}),(0,n.jsxs)("span",{className:"text-xs text-gray-500 ml-1",children:[i.filter(e=>g.has(e.name)).length,"/",i.length," allowed"]})]}),!o&&(0,n.jsxs)("div",{className:"flex items-center gap-2 ml-4",children:[(0,n.jsx)(d.Text,{className:"text-xs text-gray-500",children:h?"All on":v?"Partial":"All off"}),(0,n.jsx)(s.Checkbox,{checked:h,indeterminate:v,onChange:t=>((e,t)=>{if(o)return;let a=new Set(g);for(let r of f[e])t?a.add(r.name):a.delete(r.name);r(Array.from(a))})(e,t.target.checked),onClick:e=>e.stopPropagation()})]})]}),!w&&(0,n.jsx)("div",{className:"px-4 pt-2 pb-1 text-xs text-gray-500 bg-white border-b border-gray-100",children:b.description}),!w&&(0,n.jsx)("div",{className:"bg-white divide-y divide-gray-50",children:i.filter(e=>!a||e.name.toLowerCase().includes(a.toLowerCase())||(e.description??"").toLowerCase().includes(a.toLowerCase())).map(e=>{let t,r=(t=e.name,g.has(t));return(0,n.jsxs)("div",{className:`flex items-start gap-3 px-4 py-2.5 transition-colors hover:bg-gray-50 ${!o?"cursor-pointer":""} ${r?"":"opacity-60"}`,onClick:()=>p(e.name),children:[(0,n.jsx)(s.Checkbox,{checked:r,onChange:()=>p(e.name),disabled:o,onClick:e=>e.stopPropagation()}),(0,n.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,n.jsx)(d.Text,{className:"font-medium text-gray-900 text-sm",children:e.name}),e.description&&(0,n.jsx)(d.Text,{className:"text-xs text-gray-500 mt-0.5 leading-snug",children:e.description})]}),(0,n.jsx)("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${r?"bg-green-100 text-green-700":"bg-gray-100 text-gray-500"}`,children:r?"on":"off"})]},e.name)})})]},e)})})}],531516)},992619,e=>{"use strict";var t=e.i(843476),r=e.i(271645),o=e.i(779241),a=e.i(599724),l=e.i(199133),n=e.i(983561),i=e.i(689020);e.s(["default",0,({accessToken:e,value:s,placeholder:d="Select a Model",onChange:c,disabled:u=!1,style:m,className:f,showLabel:g=!0,labelText:p="Select Model"})=>{let[b,h]=(0,r.useState)(s),[x,v]=(0,r.useState)(!1),[C,y]=(0,r.useState)([]),k=(0,r.useRef)(null);return(0,r.useEffect)(()=>{h(s)},[s]),(0,r.useEffect)(()=>{e&&(async()=>{try{let t=await (0,i.fetchAvailableModels)(e);console.log("Fetched models for selector:",t),t.length>0&&y(t)}catch(e){console.error("Error fetching model info:",e)}})()},[e]),(0,t.jsxs)("div",{children:[g&&(0,t.jsxs)(a.Text,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,t.jsx)(n.RobotOutlined,{className:"mr-2"})," ",p]}),(0,t.jsx)(l.Select,{value:b,placeholder:d,onChange:e=>{"custom"===e?(v(!0),h(void 0)):(v(!1),h(e),c&&c(e))},options:[...Array.from(new Set(C.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%",...m},showSearch:!0,className:`rounded-md ${f||""}`,disabled:u}),x&&(0,t.jsx)(o.TextInput,{className:"mt-2",placeholder:"Enter custom model name",onValueChange:e=>{k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{h(e),c&&c(e)},500)},disabled:u})]})}])},689020,e=>{"use strict";var t=e.i(764205);let r=async e=>{try{let r=await (0,t.modelHubCall)(e);if(console.log("model_info:",r),r?.data.length>0){let e=r.data.map(e=>({model_group:e.model_group,mode:e?.mode}));return e.sort((e,t)=>e.model_group.localeCompare(t.model_group)),e}return[]}catch(e){throw console.error("Error fetching model info:",e),e}};e.s(["fetchAvailableModels",0,r])},983561,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let o={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"};var a=e.i(9583),l=r.forwardRef(function(e,l){return r.createElement(a.default,(0,t.default)({},e,{ref:l,icon:o}))});e.s(["RobotOutlined",0,l],983561)},981339,e=>{"use strict";var t=e.i(185793);e.s(["Skeleton",()=>t.default])},500330,e=>{"use strict";var t=e.i(727749);function r(e,t){let r=structuredClone(e);for(let[e,o]of Object.entries(t))e in r&&(r[e]=o);return r}let o=(e,t=0,r=!1,o=!0)=>{if(null==e||!Number.isFinite(e)||0===e&&!o)return"-";let a={minimumFractionDigits:t,maximumFractionDigits:t};if(!r)return e.toLocaleString("en-US",a);let l=e<0?"-":"",n=Math.abs(e),i=n,s="";return n>=1e6?(i=n/1e6,s="M"):n>=1e3&&(i=n/1e3,s="K"),`${l}${i.toLocaleString("en-US",a)}${s}`},a=async(e,r="Copied to clipboard")=>{if(!e)return!1;if(!navigator||!navigator.clipboard||!navigator.clipboard.writeText)return l(e,r);try{return await navigator.clipboard.writeText(e),t.default.success(r),!0}catch(t){return console.error("Clipboard API failed: ",t),l(e,r)}},l=(e,r)=>{try{let o=document.createElement("textarea");o.value=e,o.style.position="fixed",o.style.left="-999999px",o.style.top="-999999px",o.setAttribute("readonly",""),document.body.appendChild(o),o.focus(),o.select();let a=document.execCommand("copy");if(document.body.removeChild(o),a)return t.default.success(r),!0;throw Error("execCommand failed")}catch(e){return t.default.fromBackend("Failed to copy to clipboard"),console.error("Failed to copy: ",e),!1}};e.s(["copyToClipboard",0,a,"formatNumberWithCommas",0,o,"getSpendString",0,(e,t=6)=>{if(null==e||!Number.isFinite(e)||0===e)return"-";let r=o(e,t,!1,!1);if(0===Number(r.replace(/,/g,""))){let e=(1/10**t).toFixed(t);return`< $${e}`}return`$${r}`},"updateExistingKeys",()=>r])},653496,e=>{"use strict";var t=e.i(721369);e.s(["Tabs",()=>t.default])},599724,936325,e=>{"use strict";var t=e.i(95779),r=e.i(444755),o=e.i(673706),a=e.i(271645);let l=a.default.forwardRef((e,l)=>{let{color:n,className:i,children:s}=e;return a.default.createElement("p",{ref:l,className:(0,r.tremorTwMerge)("text-tremor-default",n?(0,o.getColorClassNames)(n,t.colorPalette.text).textColor:(0,r.tremorTwMerge)("text-tremor-content","dark:text-dark-tremor-content"),i)},s)});l.displayName="Text",e.s(["default",()=>l],936325),e.s(["Text",()=>l],599724)},994388,e=>{"use strict";var t=e.i(290571),r=e.i(829087),o=e.i(271645);let a=["preEnter","entering","entered","preExit","exiting","exited","unmounted"],l=e=>({_s:e,status:a[e],isEnter:e<3,isMounted:6!==e,isResolved:2===e||e>4}),n=e=>e?6:5,i=(e,t,r,o,a)=>{clearTimeout(o.current);let n=l(e);t(n),r.current=n,a&&a({current:n})};var s=e.i(480731),d=e.i(444755),c=e.i(673706);let u=e=>{var r=(0,t.__rest)(e,[]);return o.default.createElement("svg",Object.assign({},r,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"}),o.default.createElement("path",{fill:"none",d:"M0 0h24v24H0z"}),o.default.createElement("path",{d:"M18.364 5.636L16.95 7.05A7 7 0 1 0 19 12h2a9 9 0 1 1-2.636-6.364z"}))};var m=e.i(95779);let f={xs:{height:"h-4",width:"w-4"},sm:{height:"h-5",width:"w-5"},md:{height:"h-5",width:"w-5"},lg:{height:"h-6",width:"w-6"},xl:{height:"h-6",width:"w-6"}},g=(e,t)=>{switch(e){case"primary":return{textColor:t?(0,c.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",hoverTextColor:t?(0,c.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",bgColor:t?(0,c.getColorClassNames)(t,m.colorPalette.background).bgColor:"bg-tremor-brand dark:bg-dark-tremor-brand",hoverBgColor:t?(0,c.getColorClassNames)(t,m.colorPalette.darkBackground).hoverBgColor:"hover:bg-tremor-brand-emphasis dark:hover:bg-dark-tremor-brand-emphasis",borderColor:t?(0,c.getColorClassNames)(t,m.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",hoverBorderColor:t?(0,c.getColorClassNames)(t,m.colorPalette.darkBorder).hoverBorderColor:"hover:border-tremor-brand-emphasis dark:hover:border-dark-tremor-brand-emphasis"};case"secondary":return{textColor:t?(0,c.getColorClassNames)(t,m.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,c.getColorClassNames)(t,m.colorPalette.text).textColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,c.getColorClassNames)("transparent").bgColor,hoverBgColor:t?(0,d.tremorTwMerge)((0,c.getColorClassNames)(t,m.colorPalette.background).hoverBgColor,"hover:bg-opacity-20 dark:hover:bg-opacity-20"):"hover:bg-tremor-brand-faint dark:hover:bg-dark-tremor-brand-faint",borderColor:t?(0,c.getColorClassNames)(t,m.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand"};case"light":return{textColor:t?(0,c.getColorClassNames)(t,m.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,c.getColorClassNames)(t,m.colorPalette.darkText).hoverTextColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,c.getColorClassNames)("transparent").bgColor,borderColor:"",hoverBorderColor:""}}},p=(0,c.makeClassName)("Button"),b=({loading:e,iconSize:t,iconPosition:r,Icon:a,needMargin:l,transitionStatus:n})=>{let i=l?r===s.HorizontalPositions.Left?(0,d.tremorTwMerge)("-ml-1","mr-1.5"):(0,d.tremorTwMerge)("-mr-1","ml-1.5"):"",c=(0,d.tremorTwMerge)("w-0 h-0"),m={default:c,entering:c,entered:t,exiting:t,exited:c};return e?o.default.createElement(u,{className:(0,d.tremorTwMerge)(p("icon"),"animate-spin shrink-0",i,m.default,m[n]),style:{transition:"width 150ms"}}):o.default.createElement(a,{className:(0,d.tremorTwMerge)(p("icon"),"shrink-0",t,i)})},h=o.default.forwardRef((e,a)=>{let{icon:u,iconPosition:m=s.HorizontalPositions.Left,size:h=s.Sizes.SM,color:x,variant:v="primary",disabled:C,loading:y=!1,loadingText:k,children:w,tooltip:N,className:S}=e,$=(0,t.__rest)(e,["icon","iconPosition","size","color","variant","disabled","loading","loadingText","children","tooltip","className"]),T=y||C,E=void 0!==u||y,P=y&&k,j=!(!w&&!P),M=(0,d.tremorTwMerge)(f[h].height,f[h].width),O="light"!==v?(0,d.tremorTwMerge)("rounded-tremor-default border","shadow-tremor-input","dark:shadow-dark-tremor-input"):"",z=g(v,x),R=("light"!==v?{xs:{paddingX:"px-2.5",paddingY:"py-1.5",fontSize:"text-xs"},sm:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-sm"},md:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-md"},lg:{paddingX:"px-4",paddingY:"py-2.5",fontSize:"text-lg"},xl:{paddingX:"px-4",paddingY:"py-3",fontSize:"text-xl"}}:{xs:{paddingX:"",paddingY:"",fontSize:"text-xs"},sm:{paddingX:"",paddingY:"",fontSize:"text-sm"},md:{paddingX:"",paddingY:"",fontSize:"text-md"},lg:{paddingX:"",paddingY:"",fontSize:"text-lg"},xl:{paddingX:"",paddingY:"",fontSize:"text-xl"}})[h],{tooltipProps:B,getReferenceProps:I}=(0,r.useTooltip)(300),[_,H]=(({enter:e=!0,exit:t=!0,preEnter:r,preExit:a,timeout:s,initialEntered:d,mountOnEnter:c,unmountOnExit:u,onStateChange:m}={})=>{let[f,g]=(0,o.useState)(()=>l(d?2:n(c))),p=(0,o.useRef)(f),b=(0,o.useRef)(0),[h,x]="object"==typeof s?[s.enter,s.exit]:[s,s],v=(0,o.useCallback)(()=>{let e=((e,t)=>{switch(e){case 1:case 0:return 2;case 4:case 3:return n(t)}})(p.current._s,u);e&&i(e,g,p,b,m)},[m,u]);return[f,(0,o.useCallback)(o=>{let l=e=>{switch(i(e,g,p,b,m),e){case 1:h>=0&&(b.current=((...e)=>setTimeout(...e))(v,h));break;case 4:x>=0&&(b.current=((...e)=>setTimeout(...e))(v,x));break;case 0:case 3:b.current=((...e)=>setTimeout(...e))(()=>{isNaN(document.body.offsetTop)||l(e+1)},0)}},s=p.current.isEnter;"boolean"!=typeof o&&(o=!s),o?s||l(e?+!r:2):s&&l(t?a?3:4:n(u))},[v,m,e,t,r,a,h,x,u]),v]})({timeout:50});return(0,o.useEffect)(()=>{H(y)},[y]),o.default.createElement("button",Object.assign({ref:(0,c.mergeRefs)([a,B.refs.setReference]),className:(0,d.tremorTwMerge)(p("root"),"shrink-0 inline-flex justify-center items-center group font-medium outline-none",O,R.paddingX,R.paddingY,R.fontSize,z.textColor,z.bgColor,z.borderColor,z.hoverBorderColor,T?"opacity-50 cursor-not-allowed":(0,d.tremorTwMerge)(g(v,x).hoverTextColor,g(v,x).hoverBgColor,g(v,x).hoverBorderColor),S),disabled:T},I,$),o.default.createElement(r.default,Object.assign({text:N},B)),E&&m!==s.HorizontalPositions.Right?o.default.createElement(b,{loading:y,iconSize:M,iconPosition:m,Icon:u,transitionStatus:_.status,needMargin:j}):null,P||w?o.default.createElement("span",{className:(0,d.tremorTwMerge)(p("text"),"text-tremor-default whitespace-nowrap")},P?k:w):null,E&&m===s.HorizontalPositions.Right?o.default.createElement(b,{loading:y,iconSize:M,iconPosition:m,Icon:u,transitionStatus:_.status,needMargin:j}):null)});h.displayName="Button",e.s(["Button",()=>h],994388)},304967,e=>{"use strict";var t=e.i(290571),r=e.i(271645),o=e.i(480731),a=e.i(95779),l=e.i(444755),n=e.i(673706);let i=(0,n.makeClassName)("Card"),s=r.default.forwardRef((e,s)=>{let{decoration:d="",decorationColor:c,children:u,className:m}=e,f=(0,t.__rest)(e,["decoration","decorationColor","children","className"]);return r.default.createElement("div",Object.assign({ref:s,className:(0,l.tremorTwMerge)(i("root"),"relative w-full text-left ring-1 rounded-tremor-default p-6","bg-tremor-background ring-tremor-ring shadow-tremor-card","dark:bg-dark-tremor-background dark:ring-dark-tremor-ring dark:shadow-dark-tremor-card",c?(0,n.getColorClassNames)(c,a.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",(e=>{if(!e)return"";switch(e){case o.HorizontalPositions.Left:return"border-l-4";case o.VerticalPositions.Top:return"border-t-4";case o.HorizontalPositions.Right:return"border-r-4";case o.VerticalPositions.Bottom:return"border-b-4";default:return""}})(d),m)},f),u)});s.displayName="Card",e.s(["Card",()=>s],304967)},629569,e=>{"use strict";var t=e.i(290571),r=e.i(95779),o=e.i(444755),a=e.i(673706),l=e.i(271645);let n=l.default.forwardRef((e,n)=>{let{color:i,children:s,className:d}=e,c=(0,t.__rest)(e,["color","children","className"]);return l.default.createElement("p",Object.assign({ref:n,className:(0,o.tremorTwMerge)("font-medium text-tremor-title",i?(0,a.getColorClassNames)(i,r.colorPalette.darkText).textColor:"text-tremor-content-strong dark:text-dark-tremor-content-strong",d)},c),s)});n.displayName="Title",e.s(["Title",()=>n],629569)},91874,e=>{"use strict";var t=e.i(931067),r=e.i(209428),o=e.i(211577),a=e.i(392221),l=e.i(703923),n=e.i(343794),i=e.i(914949),s=e.i(271645),d=["prefixCls","className","style","checked","disabled","defaultChecked","type","title","onChange"],c=(0,s.forwardRef)(function(e,c){var u=e.prefixCls,m=void 0===u?"rc-checkbox":u,f=e.className,g=e.style,p=e.checked,b=e.disabled,h=e.defaultChecked,x=e.type,v=void 0===x?"checkbox":x,C=e.title,y=e.onChange,k=(0,l.default)(e,d),w=(0,s.useRef)(null),N=(0,s.useRef)(null),S=(0,i.default)(void 0!==h&&h,{value:p}),$=(0,a.default)(S,2),T=$[0],E=$[1];(0,s.useImperativeHandle)(c,function(){return{focus:function(e){var t;null==(t=w.current)||t.focus(e)},blur:function(){var e;null==(e=w.current)||e.blur()},input:w.current,nativeElement:N.current}});var P=(0,n.default)(m,f,(0,o.default)((0,o.default)({},"".concat(m,"-checked"),T),"".concat(m,"-disabled"),b));return s.createElement("span",{className:P,title:C,style:g,ref:N},s.createElement("input",(0,t.default)({},k,{className:"".concat(m,"-input"),ref:w,onChange:function(t){b||("checked"in e||E(t.target.checked),null==y||y({target:(0,r.default)((0,r.default)({},e),{},{type:v,checked:t.target.checked}),stopPropagation:function(){t.stopPropagation()},preventDefault:function(){t.preventDefault()},nativeEvent:t.nativeEvent}))},disabled:b,checked:!!T,type:v})),s.createElement("span",{className:"".concat(m,"-inner")}))});e.s(["default",0,c])},421512,236836,e=>{"use strict";let t=e.i(271645).default.createContext(null);e.s(["default",0,t],421512),e.i(296059);var r=e.i(915654),o=e.i(183293),a=e.i(246422),l=e.i(838378);function n(e,t){return(e=>{let{checkboxCls:t}=e,a=`${t}-wrapper`;return[{[`${t}-group`]:Object.assign(Object.assign({},(0,o.resetComponent)(e)),{display:"inline-flex",flexWrap:"wrap",columnGap:e.marginXS,[`> ${e.antCls}-row`]:{flex:1}}),[a]:Object.assign(Object.assign({},(0,o.resetComponent)(e)),{display:"inline-flex",alignItems:"baseline",cursor:"pointer","&:after":{display:"inline-block",width:0,overflow:"hidden",content:"'\\a0'"},[`& + ${a}`]:{marginInlineStart:0},[`&${a}-in-form-item`]:{'input[type="checkbox"]':{width:14,height:14}}}),[t]:Object.assign(Object.assign({},(0,o.resetComponent)(e)),{position:"relative",whiteSpace:"nowrap",lineHeight:1,cursor:"pointer",borderRadius:e.borderRadiusSM,alignSelf:"center",[`${t}-input`]:{position:"absolute",inset:0,zIndex:1,cursor:"pointer",opacity:0,margin:0,[`&:focus-visible + ${t}-inner`]:(0,o.genFocusOutline)(e)},[`${t}-inner`]:{boxSizing:"border-box",display:"block",width:e.checkboxSize,height:e.checkboxSize,direction:"ltr",backgroundColor:e.colorBgContainer,border:`${(0,r.unit)(e.lineWidth)} ${e.lineType} ${e.colorBorder}`,borderRadius:e.borderRadiusSM,borderCollapse:"separate",transition:`all ${e.motionDurationSlow}`,"&:after":{boxSizing:"border-box",position:"absolute",top:"50%",insetInlineStart:"25%",display:"table",width:e.calc(e.checkboxSize).div(14).mul(5).equal(),height:e.calc(e.checkboxSize).div(14).mul(8).equal(),border:`${(0,r.unit)(e.lineWidthBold)} solid ${e.colorWhite}`,borderTop:0,borderInlineStart:0,transform:"rotate(45deg) scale(0) translate(-50%,-50%)",opacity:0,content:'""',transition:`all ${e.motionDurationFast} ${e.motionEaseInBack}, opacity ${e.motionDurationFast}`}},"& + span":{paddingInlineStart:e.paddingXS,paddingInlineEnd:e.paddingXS}})},{[` + ${a}:not(${a}-disabled), + ${t}:not(${t}-disabled) + `]:{[`&:hover ${t}-inner`]:{borderColor:e.colorPrimary}},[`${a}:not(${a}-disabled)`]:{[`&:hover ${t}-checked:not(${t}-disabled) ${t}-inner`]:{backgroundColor:e.colorPrimaryHover,borderColor:"transparent"},[`&:hover ${t}-checked:not(${t}-disabled):after`]:{borderColor:e.colorPrimaryHover}}},{[`${t}-checked`]:{[`${t}-inner`]:{backgroundColor:e.colorPrimary,borderColor:e.colorPrimary,"&:after":{opacity:1,transform:"rotate(45deg) scale(1) translate(-50%,-50%)",transition:`all ${e.motionDurationMid} ${e.motionEaseOutBack} ${e.motionDurationFast}`}}},[` + ${a}-checked:not(${a}-disabled), + ${t}-checked:not(${t}-disabled) + `]:{[`&:hover ${t}-inner`]:{backgroundColor:e.colorPrimaryHover,borderColor:"transparent"}}},{[t]:{"&-indeterminate":{"&":{[`${t}-inner`]:{backgroundColor:`${e.colorBgContainer}`,borderColor:`${e.colorBorder}`,"&:after":{top:"50%",insetInlineStart:"50%",width:e.calc(e.fontSizeLG).div(2).equal(),height:e.calc(e.fontSizeLG).div(2).equal(),backgroundColor:e.colorPrimary,border:0,transform:"translate(-50%, -50%) scale(1)",opacity:1,content:'""'}},[`&:hover ${t}-inner`]:{backgroundColor:`${e.colorBgContainer}`,borderColor:`${e.colorPrimary}`}}}}},{[`${a}-disabled`]:{cursor:"not-allowed"},[`${t}-disabled`]:{[`&, ${t}-input`]:{cursor:"not-allowed",pointerEvents:"none"},[`${t}-inner`]:{background:e.colorBgContainerDisabled,borderColor:e.colorBorder,"&:after":{borderColor:e.colorTextDisabled}},"&:after":{display:"none"},"& + span":{color:e.colorTextDisabled},[`&${t}-indeterminate ${t}-inner::after`]:{background:e.colorTextDisabled}}}]})((0,l.mergeToken)(t,{checkboxCls:`.${e}`,checkboxSize:t.controlInteractiveSize}))}let i=(0,a.genStyleHooks)("Checkbox",(e,{prefixCls:t})=>[n(t,e)]);e.s(["default",0,i,"getStyle",()=>n],236836)},681216,e=>{"use strict";var t=e.i(271645),r=e.i(963188);function o(e){let o=t.default.useRef(null),a=()=>{r.default.cancel(o.current),o.current=null};return[()=>{a(),o.current=(0,r.default)(()=>{o.current=null})},t=>{o.current&&(t.stopPropagation(),a()),null==e||e(t)}]}e.s(["default",()=>o])},374276,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),o=e.i(91874),a=e.i(611935),l=e.i(121872),n=e.i(26905),i=e.i(242064),s=e.i(937328),d=e.i(321883),c=e.i(62139),u=e.i(421512),m=e.i(236836),f=e.i(681216),g=function(e,t){var r={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&0>t.indexOf(o)&&(r[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var a=0,o=Object.getOwnPropertySymbols(e);at.indexOf(o[a])&&Object.prototype.propertyIsEnumerable.call(e,o[a])&&(r[o[a]]=e[o[a]]);return r};let p=t.forwardRef((e,p)=>{var b;let{prefixCls:h,className:x,rootClassName:v,children:C,indeterminate:y=!1,style:k,onMouseEnter:w,onMouseLeave:N,skipGroup:S=!1,disabled:$}=e,T=g(e,["prefixCls","className","rootClassName","children","indeterminate","style","onMouseEnter","onMouseLeave","skipGroup","disabled"]),{getPrefixCls:E,direction:P,checkbox:j}=t.useContext(i.ConfigContext),M=t.useContext(u.default),{isFormItemInput:O}=t.useContext(c.FormItemInputContext),z=t.useContext(s.default),R=null!=(b=(null==M?void 0:M.disabled)||$)?b:z,B=t.useRef(T.value),I=t.useRef(null),_=(0,a.composeRef)(p,I);t.useEffect(()=>{null==M||M.registerValue(T.value)},[]),t.useEffect(()=>{if(!S)return T.value!==B.current&&(null==M||M.cancelValue(B.current),null==M||M.registerValue(T.value),B.current=T.value),()=>null==M?void 0:M.cancelValue(T.value)},[T.value]),t.useEffect(()=>{var e;(null==(e=I.current)?void 0:e.input)&&(I.current.input.indeterminate=y)},[y]);let H=E("checkbox",h),L=(0,d.default)(H),[D,A,X]=(0,m.default)(H,L),F=Object.assign({},T);M&&!S&&(F.onChange=(...e)=>{T.onChange&&T.onChange.apply(T,e),M.toggleOption&&M.toggleOption({label:C,value:T.value})},F.name=M.name,F.checked=M.value.includes(T.value));let q=(0,r.default)(`${H}-wrapper`,{[`${H}-rtl`]:"rtl"===P,[`${H}-wrapper-checked`]:F.checked,[`${H}-wrapper-disabled`]:R,[`${H}-wrapper-in-form-item`]:O},null==j?void 0:j.className,x,v,X,L,A),Y=(0,r.default)({[`${H}-indeterminate`]:y},n.TARGET_CLS,A),[V,U]=(0,f.default)(F.onClick);return D(t.createElement(l.default,{component:"Checkbox",disabled:R},t.createElement("label",{className:q,style:Object.assign(Object.assign({},null==j?void 0:j.style),k),onMouseEnter:w,onMouseLeave:N,onClick:V},t.createElement(o.default,Object.assign({},F,{onClick:U,prefixCls:H,className:Y,disabled:R,ref:_})),null!=C&&t.createElement("span",{className:`${H}-label`},C))))});var b=e.i(8211),h=e.i(529681),x=function(e,t){var r={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&0>t.indexOf(o)&&(r[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var a=0,o=Object.getOwnPropertySymbols(e);at.indexOf(o[a])&&Object.prototype.propertyIsEnumerable.call(e,o[a])&&(r[o[a]]=e[o[a]]);return r};let v=t.forwardRef((e,o)=>{let{defaultValue:a,children:l,options:n=[],prefixCls:s,className:c,rootClassName:f,style:g,onChange:v}=e,C=x(e,["defaultValue","children","options","prefixCls","className","rootClassName","style","onChange"]),{getPrefixCls:y,direction:k}=t.useContext(i.ConfigContext),[w,N]=t.useState(C.value||a||[]),[S,$]=t.useState([]);t.useEffect(()=>{"value"in C&&N(C.value||[])},[C.value]);let T=t.useMemo(()=>n.map(e=>"string"==typeof e||"number"==typeof e?{label:e,value:e}:e),[n]),E=e=>{$(t=>t.filter(t=>t!==e))},P=e=>{$(t=>[].concat((0,b.default)(t),[e]))},j=e=>{let t=w.indexOf(e.value),r=(0,b.default)(w);-1===t?r.push(e.value):r.splice(t,1),"value"in C||N(r),null==v||v(r.filter(e=>S.includes(e)).sort((e,t)=>T.findIndex(t=>t.value===e)-T.findIndex(e=>e.value===t)))},M=y("checkbox",s),O=`${M}-group`,z=(0,d.default)(M),[R,B,I]=(0,m.default)(M,z),_=(0,h.default)(C,["value","disabled"]),H=n.length?T.map(e=>t.createElement(p,{prefixCls:M,key:e.value.toString(),disabled:"disabled"in e?e.disabled:C.disabled,value:e.value,checked:w.includes(e.value),onChange:e.onChange,className:(0,r.default)(`${O}-item`,e.className),style:e.style,title:e.title,id:e.id,required:e.required},e.label)):l,L=t.useMemo(()=>({toggleOption:j,value:w,disabled:C.disabled,name:C.name,registerValue:P,cancelValue:E}),[j,w,C.disabled,C.name,P,E]),D=(0,r.default)(O,{[`${O}-rtl`]:"rtl"===k},c,f,I,z,B);return R(t.createElement("div",Object.assign({className:D,style:g},_,{ref:o}),t.createElement(u.default.Provider,{value:L},H)))});p.Group=v,p.__ANT_CHECKBOX=!0,e.s(["default",0,p],374276)},536916,e=>{"use strict";var t=e.i(374276);e.s(["Checkbox",()=>t.default])},246349,e=>{"use strict";let t=(0,e.i(475254).default)("chevron-right",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);e.s(["default",()=>t])}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/22970a12064ba16b.js b/litellm/proxy/_experimental/out/_next/static/chunks/22970a12064ba16b.js new file mode 100644 index 00000000000..836cd30e918 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/22970a12064ba16b.js @@ -0,0 +1,231 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,952683,e=>{"use strict";var t=e.i(843476),s=e.i(794357),a=e.i(111672),l=e.i(764205),r=e.i(135214),i=e.i(271645);let n=({setPage:e,defaultSelectedKey:s,sidebarCollapsed:n})=>{let{accessToken:o}=(0,r.default)(),[d,c]=(0,i.useState)(null),[m,u]=(0,i.useState)(!1),[x,p]=(0,i.useState)(!1),[h,g]=(0,i.useState)(!1),[y,j]=(0,i.useState)(!1),[f,b]=(0,i.useState)(!1);return(0,i.useEffect)(()=>{(async()=>{if(!o)return console.log("[SidebarProvider] No access token, skipping UI settings fetch");try{console.log("[SidebarProvider] Fetching UI settings from /get/ui_settings");let e=await (0,l.getUISettings)(o);console.log("[SidebarProvider] UI settings response:",e),e?.values?.enabled_ui_pages_internal_users!==void 0?(console.log("[SidebarProvider] Setting enabled pages:",e.values.enabled_ui_pages_internal_users),c(e.values.enabled_ui_pages_internal_users)):console.log("[SidebarProvider] No enabled_ui_pages_internal_users in response (all pages visible by default)"),e?.values?.enable_projects_ui!==void 0&&u(!!e.values.enable_projects_ui),e?.values?.disable_agents_for_internal_users!==void 0&&p(!!e.values.disable_agents_for_internal_users),e?.values?.allow_agents_for_team_admins!==void 0&&g(!!e.values.allow_agents_for_team_admins),e?.values?.disable_vector_stores_for_internal_users!==void 0&&j(!!e.values.disable_vector_stores_for_internal_users),e?.values?.allow_vector_stores_for_team_admins!==void 0&&b(!!e.values.allow_vector_stores_for_team_admins)}catch(e){console.error("[SidebarProvider] Failed to fetch UI settings:",e)}})()},[o]),(0,t.jsx)(a.default,{setPage:e,defaultSelectedKey:s,collapsed:n,enabledPagesInternalUsers:d,enableProjectsUI:m,disableAgentsForInternalUsers:x,allowAgentsForTeamAdmins:h,disableVectorStoresForInternalUsers:y,allowVectorStoresForTeamAdmins:f})};var o=e.i(161059),d=e.i(213970),c=e.i(105278),m=e.i(994388),u=e.i(304967),x=e.i(269200),p=e.i(942232),h=e.i(977572),g=e.i(427612),y=e.i(64848),j=e.i(496020),f=e.i(389083),b=e.i(599724),_=e.i(212931),v=e.i(560445),N=e.i(592968),w=e.i(981339),k=e.i(790848),C=e.i(245704),S=e.i(808613),T=e.i(998573),I=e.i(199133),F=e.i(311451),P=e.i(280898),L=e.i(91739),A=e.i(262218),M=e.i(312361),D=e.i(28651),E=e.i(826910),O=e.i(438957),R=e.i(983561),z=e.i(477189),B=e.i(827252),q=e.i(364769),$=e.i(355619),U=e.i(663435),H=e.i(362024),V=e.i(770914),G=e.i(464571),K=e.i(646563),W=e.i(564897);let Q={basic:{key:"basic",title:"Basic Information",defaultExpanded:!0,fields:[{name:"name",label:"Display Name",type:"text",required:!0,placeholder:"e.g., Customer Support Agent"},{name:"description",label:"Description",type:"textarea",required:!0,placeholder:"Describe what this agent does...",rows:3},{name:"url",label:"URL",type:"url",required:!1,placeholder:"http://localhost:9999/",tooltip:"Base URL where the agent is hosted (optional)"},{name:"version",label:"Version",type:"text",placeholder:"1.0.0",defaultValue:"1.0.0"},{name:"protocolVersion",label:"Protocol Version",type:"text",placeholder:"1.0",defaultValue:"1.0"}]},skills:{key:"skills",title:"Skills",fields:[{name:"skills",label:"Skills",type:"list",defaultValue:[]}]},capabilities:{key:"capabilities",title:"Capabilities",fields:[{name:"streaming",label:"Streaming",type:"switch",defaultValue:!1},{name:"pushNotifications",label:"Push Notifications",type:"switch"},{name:"stateTransitionHistory",label:"State Transition History",type:"switch"}]},optional:{key:"optional",title:"Optional Settings",fields:[{name:"iconUrl",label:"Icon URL",type:"url",placeholder:"https://example.com/icon.png"},{name:"documentationUrl",label:"Documentation URL",type:"url",placeholder:"https://docs.example.com"},{name:"supportsAuthenticatedExtendedCard",label:"Supports Authenticated Extended Card",type:"switch"}]},litellm:{key:"litellm",title:"LiteLLM Parameters",fields:[{name:"model",label:"Model (Optional)",type:"text"},{name:"make_public",label:"Make Public",type:"switch"}]},cost:{key:"cost",title:"Cost Configuration",fields:[{name:"cost_per_query",label:"Cost Per Query ($)",type:"text",placeholder:"0.0",tooltip:"Fixed cost per query"},{name:"input_cost_per_token",label:"Input Cost Per Token ($)",type:"text",placeholder:"0.000001",tooltip:"Cost per input token"},{name:"output_cost_per_token",label:"Output Cost Per Token ($)",type:"text",placeholder:"0.000002",tooltip:"Cost per output token"}]},tracing:{key:"tracing",title:"Tracing",fields:[{name:"enable_tracing",label:"Enable Tracing",type:"switch",defaultValue:!1,tooltip:"Enable request tracing for this agent"}]}},Y="Skill ID",J=!0,X="e.g., hello_world",Z="Skill Name",ee=!0,et="e.g., Returns hello world",es="Description",ea=!0,el="What this skill does",er=2,ei="Tags (comma-separated)",en=!0,eo="e.g., hello world, greeting",ed="Examples (comma-separated)",ec="e.g., hi, hello world",em=(e,t)=>{let s={agent_name:e.agent_name,agent_card_params:{protocolVersion:e.protocolVersion||"1.0",name:e.name||e.agent_name,description:e.description||"",url:e.url||"",version:e.version||"1.0.0",defaultInputModes:t?.agent_card_params?.defaultInputModes||["text"],defaultOutputModes:t?.agent_card_params?.defaultOutputModes||["text"],capabilities:{streaming:!0===e.streaming,...void 0!==e.pushNotifications&&{pushNotifications:e.pushNotifications},...void 0!==e.stateTransitionHistory&&{stateTransitionHistory:e.stateTransitionHistory}},skills:e.skills||[],...e.iconUrl&&{iconUrl:e.iconUrl},...e.documentationUrl&&{documentationUrl:e.documentationUrl},...void 0!==e.supportsAuthenticatedExtendedCard&&{supportsAuthenticatedExtendedCard:e.supportsAuthenticatedExtendedCard}}},a={};if(e.model&&(a.model=e.model),void 0!==e.make_public&&(a.make_public=e.make_public),e.cost_per_query&&(a.cost_per_query=parseFloat(e.cost_per_query)),e.input_cost_per_token&&(a.input_cost_per_token=parseFloat(e.input_cost_per_token)),e.output_cost_per_token&&(a.output_cost_per_token=parseFloat(e.output_cost_per_token)),Object.keys(a).length>0&&(s.litellm_params=a),null!=e.tpm_limit&&(s.tpm_limit=e.tpm_limit),null!=e.rpm_limit&&(s.rpm_limit=e.rpm_limit),null!=e.session_tpm_limit&&(s.session_tpm_limit=e.session_tpm_limit),null!=e.session_rpm_limit&&(s.session_rpm_limit=e.session_rpm_limit),Array.isArray(e.static_headers)&&e.static_headers.length>0){let t={};e.static_headers.forEach(e=>{let s=e?.header?.trim();s&&(t[s]=e?.value??"")}),Object.keys(t).length>0&&(s.static_headers=t)}return Array.isArray(e.extra_headers)&&e.extra_headers.length>0&&(s.extra_headers=e.extra_headers),s},eu=e=>{let t=e.agent_card_params?.skills?.map(e=>({...e,tags:e.tags,examples:e.examples||[]}))||[];return{agent_name:e.agent_name,name:e.agent_card_params?.name,description:e.agent_card_params?.description,url:e.agent_card_params?.url,version:e.agent_card_params?.version,protocolVersion:e.agent_card_params?.protocolVersion,streaming:e.agent_card_params?.capabilities?.streaming,pushNotifications:e.agent_card_params?.capabilities?.pushNotifications,stateTransitionHistory:e.agent_card_params?.capabilities?.stateTransitionHistory,skills:t,iconUrl:e.agent_card_params?.iconUrl,documentationUrl:e.agent_card_params?.documentationUrl,supportsAuthenticatedExtendedCard:e.agent_card_params?.supportsAuthenticatedExtendedCard,model:e.litellm_params?.model,make_public:e.litellm_params?.make_public,cost_per_query:e.litellm_params?.cost_per_query,input_cost_per_token:e.litellm_params?.input_cost_per_token,output_cost_per_token:e.litellm_params?.output_cost_per_token,tpm_limit:e.tpm_limit,rpm_limit:e.rpm_limit,session_tpm_limit:e.session_tpm_limit,session_rpm_limit:e.session_rpm_limit,static_headers:e.static_headers?Object.entries(e.static_headers).map(([e,t])=>({header:e,value:t})):[],extra_headers:e.extra_headers??[]}},ex=()=>(0,t.jsx)(t.Fragment,{children:Q.cost.fields.map(e=>(0,t.jsx)(S.Form.Item,{label:e.label,name:e.name,tooltip:e.tooltip,children:(0,t.jsx)(F.Input,{placeholder:e.placeholder,type:"number",step:"0.000001"})},e.name))}),{Panel:ep}=H.Collapse,eh=({showAgentName:e=!0,visiblePanels:s})=>{let a=e=>!s||s.includes(e);return(0,t.jsxs)(t.Fragment,{children:[e&&(0,t.jsx)(S.Form.Item,{label:"Agent Name",name:"agent_name",rules:[{required:!0,message:"Please enter a unique agent name"}],tooltip:"Unique identifier for the agent",children:(0,t.jsx)(F.Input,{placeholder:"e.g., customer-support-agent"})}),(0,t.jsxs)(H.Collapse,{defaultActiveKey:["basic"],style:{marginBottom:16},children:[a(Q.basic.key)&&(0,t.jsx)(ep,{header:`${Q.basic.title} (Required)`,children:Q.basic.fields.map(e=>(0,t.jsx)(S.Form.Item,{label:e.label,name:e.name,rules:e.required?[{required:!0,message:`Please enter ${e.label.toLowerCase()}`}]:void 0,tooltip:e.tooltip,children:"textarea"===e.type?(0,t.jsx)(F.Input.TextArea,{rows:e.rows,placeholder:e.placeholder}):(0,t.jsx)(F.Input,{placeholder:e.placeholder})},e.name))},Q.basic.key),a(Q.skills.key)&&(0,t.jsx)(ep,{header:`${Q.skills.title} (Required)`,children:(0,t.jsx)(S.Form.List,{name:"skills",children:(e,{add:s,remove:a})=>(0,t.jsxs)(t.Fragment,{children:[e.map(e=>(0,t.jsxs)("div",{style:{marginBottom:16,padding:16,border:"1px solid #d9d9d9",borderRadius:4},children:[(0,t.jsx)(S.Form.Item,{...e,label:Y,name:[e.name,"id"],rules:[{required:J,message:"Required"}],children:(0,t.jsx)(F.Input,{placeholder:X})}),(0,t.jsx)(S.Form.Item,{...e,label:Z,name:[e.name,"name"],rules:[{required:ee,message:"Required"}],children:(0,t.jsx)(F.Input,{placeholder:et})}),(0,t.jsx)(S.Form.Item,{...e,label:es,name:[e.name,"description"],rules:[{required:ea,message:"Required"}],children:(0,t.jsx)(F.Input.TextArea,{rows:er,placeholder:el})}),(0,t.jsx)(S.Form.Item,{...e,label:ei,name:[e.name,"tags"],rules:[{required:en,message:"Required"}],getValueFromEvent:e=>e.target.value.split(",").map(e=>e.trim()),getValueProps:e=>({value:Array.isArray(e)?e.join(", "):e}),children:(0,t.jsx)(F.Input,{placeholder:eo})}),(0,t.jsx)(S.Form.Item,{...e,label:ed,name:[e.name,"examples"],getValueFromEvent:e=>e.target.value.split(",").map(e=>e.trim()).filter(e=>e),getValueProps:e=>({value:Array.isArray(e)?e.join(", "):""}),children:(0,t.jsx)(F.Input,{placeholder:ec})}),(0,t.jsx)(G.Button,{type:"link",danger:!0,onClick:()=>a(e.name),icon:(0,t.jsx)(W.MinusCircleOutlined,{}),children:"Remove Skill"})]},e.key)),(0,t.jsx)(G.Button,{type:"dashed",onClick:()=>s(),icon:(0,t.jsx)(K.PlusOutlined,{}),style:{width:"100%"},children:"Add Skill"})]})})},Q.skills.key),a(Q.capabilities.key)&&(0,t.jsx)(ep,{header:Q.capabilities.title,children:Q.capabilities.fields.map(e=>(0,t.jsx)(S.Form.Item,{label:e.label,name:e.name,valuePropName:"checked",children:(0,t.jsx)(k.Switch,{})},e.name))},Q.capabilities.key),a(Q.optional.key)&&(0,t.jsx)(ep,{header:Q.optional.title,children:Q.optional.fields.map(e=>(0,t.jsx)(S.Form.Item,{label:e.label,name:e.name,valuePropName:"switch"===e.type?"checked":void 0,children:"switch"===e.type?(0,t.jsx)(k.Switch,{}):(0,t.jsx)(F.Input,{placeholder:e.placeholder})},e.name))},Q.optional.key),a(Q.cost.key)&&(0,t.jsx)(ep,{header:Q.cost.title,children:(0,t.jsx)(ex,{})},Q.cost.key),a(Q.litellm.key)&&(0,t.jsx)(ep,{header:Q.litellm.title,children:Q.litellm.fields.map(e=>(0,t.jsx)(S.Form.Item,{label:e.label,name:e.name,valuePropName:"switch"===e.type?"checked":void 0,children:"switch"===e.type?(0,t.jsx)(k.Switch,{}):(0,t.jsx)(F.Input,{placeholder:e.placeholder})},e.name))},Q.litellm.key),a("auth_headers")&&(0,t.jsxs)(ep,{header:"Authentication Headers",children:[(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{children:["Static Headers"," ",(0,t.jsx)(N.Tooltip,{title:"Headers always sent to the backend agent, regardless of the client request. Admin-configured, static wins on conflict.",children:(0,t.jsx)(B.InfoCircleOutlined,{style:{color:"#8c8c8c"}})})]}),children:(0,t.jsx)(S.Form.List,{name:"static_headers",children:(e,{add:s,remove:a})=>(0,t.jsxs)(t.Fragment,{children:[e.map(({key:e,name:s,...l})=>(0,t.jsxs)(V.Space,{style:{display:"flex",marginBottom:8},align:"baseline",children:[(0,t.jsx)(S.Form.Item,{...l,name:[s,"header"],rules:[{required:!0,message:"Header name required"}],children:(0,t.jsx)(F.Input,{placeholder:"Header name (e.g. Authorization)",style:{width:220}})}),(0,t.jsx)(S.Form.Item,{...l,name:[s,"value"],rules:[{required:!0,message:"Value required"}],children:(0,t.jsx)(F.Input,{placeholder:"Value (e.g. Bearer token123)",style:{width:260}})}),(0,t.jsx)(W.MinusCircleOutlined,{onClick:()=>a(s),style:{color:"#ff4d4f"}})]},e)),(0,t.jsx)(G.Button,{type:"dashed",onClick:()=>s(),icon:(0,t.jsx)(K.PlusOutlined,{}),style:{width:"100%"},children:"Add Static Header"})]})})}),(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{children:["Forward Client Headers"," ",(0,t.jsx)(N.Tooltip,{title:"Header names to extract from the client's request and forward to the agent. Type a name and press Enter.",children:(0,t.jsx)(B.InfoCircleOutlined,{style:{color:"#8c8c8c"}})})]}),name:"extra_headers",children:(0,t.jsx)(I.Select,{mode:"tags",style:{width:"100%"},placeholder:"e.g. x-api-key, Authorization",tokenSeparators:[","]})})]},"auth_headers")]})]})},{Panel:eg}=H.Collapse,ey=(e,t)=>{let s={...t.litellm_params_template||{}};for(let a of t.credential_fields){let t=e[a.key];t&&!1!==a.include_in_litellm_params&&(s[a.key]=t)}if(e.cost_per_query&&(s.cost_per_query=parseFloat(e.cost_per_query)),e.input_cost_per_token&&(s.input_cost_per_token=parseFloat(e.input_cost_per_token)),e.output_cost_per_token&&(s.output_cost_per_token=parseFloat(e.output_cost_per_token)),t.model_template){let a=t.model_template;for(let s of t.credential_fields){let t=`{${s.key}}`;a.includes(t)&&e[s.key]&&(a=a.replace(t,e[s.key]))}s.model=a}let a={agent_name:e.agent_name,agent_card_params:{protocolVersion:"1.0",name:e.display_name||e.agent_name,description:e.description||`${t.agent_type_display_name} agent`,url:e.api_base||"",version:"1.0.0",defaultInputModes:["text"],defaultOutputModes:["text"],capabilities:{streaming:!0},skills:[{id:"chat",name:"Chat",description:"General chat capability",tags:["chat","conversation"]}]},litellm_params:s};return null!=e.tpm_limit&&(a.tpm_limit=e.tpm_limit),null!=e.rpm_limit&&(a.rpm_limit=e.rpm_limit),null!=e.session_tpm_limit&&(a.session_tpm_limit=e.session_tpm_limit),null!=e.session_rpm_limit&&(a.session_rpm_limit=e.session_rpm_limit),a},ej=({agentTypeInfo:e})=>(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(S.Form.Item,{label:"Agent Name",name:"agent_name",rules:[{required:!0,message:"Please enter a unique agent name"}],tooltip:"Unique identifier for the agent",children:(0,t.jsx)(F.Input,{placeholder:"e.g., my-langgraph-agent"})}),(0,t.jsx)(S.Form.Item,{label:"Description",name:"description",tooltip:"Brief description of what this agent does",children:(0,t.jsx)(F.Input.TextArea,{rows:2,placeholder:"Describe what this agent does..."})}),e.credential_fields.map(e=>(0,t.jsx)(S.Form.Item,{label:e.label,name:e.key,rules:e.required?[{required:!0,message:`Please enter ${e.label}`}]:void 0,tooltip:e.tooltip,initialValue:e.default_value,children:"password"===e.field_type?(0,t.jsx)(F.Input.Password,{placeholder:e.placeholder||""}):"textarea"===e.field_type?(0,t.jsx)(F.Input.TextArea,{rows:3,placeholder:e.placeholder||""}):"select"===e.field_type&&e.options?(0,t.jsx)(I.Select,{placeholder:e.placeholder||"",children:e.options.map(e=>(0,t.jsx)(I.Select.Option,{value:e,children:e},e))}):(0,t.jsx)(F.Input,{placeholder:e.placeholder||""})},e.key)),(0,t.jsx)(H.Collapse,{style:{marginBottom:16},children:(0,t.jsx)(eg,{header:Q.cost.title,children:(0,t.jsx)(ex,{})},Q.cost.key)})]});var ef=e.i(75921),eb=e.i(390605),e_=e.i(891547);let{Step:ev}=P.Steps,eN="custom",ew=({visible:e,onClose:s,accessToken:a,onSuccess:n,teams:o})=>{let d,c,{userId:u,userRole:x}=(0,r.default)(),[p]=S.Form.useForm(),[h,g]=(0,i.useState)(0),[y,j]=(0,i.useState)(!1),[f,b]=(0,i.useState)("a2a"),[v,N]=(0,i.useState)([]),[w,C]=(0,i.useState)(!1),[H,V]=(0,i.useState)("create_new"),[G,K]=(0,i.useState)(""),[W,Y]=(0,i.useState)([]),[J,X]=(0,i.useState)([]),[Z,ee]=(0,i.useState)(null),[et,es]=(0,i.useState)(!1),[ea,el]=(0,i.useState)([]),[er,ei]=(0,i.useState)(!1),[en,eo]=(0,i.useState)([]),[ed,ec]=(0,i.useState)(!1),[eu,ex]=(0,i.useState)(""),[ep,eg]=(0,i.useState)(null),[ew,ek]=(0,i.useState)(null),[eC,eS]=(0,i.useState)(!1),[eT,eI]=(0,i.useState)(!1),[eF,eP]=(0,i.useState)(null),[eL,eA]=(0,i.useState)(null);(0,i.useEffect)(()=>{(async()=>{C(!0);try{let e=await (0,l.getAgentCreateMetadata)();N(e)}catch(e){console.error("Error fetching agent metadata:",e)}finally{C(!1)}})()},[]),(0,i.useEffect)(()=>{3===h&&a&&0===J.length&&(async()=>{es(!0);try{let e=await (0,l.keyListCall)(a,null,null,null,null,null,1,100);X(e?.keys||[])}catch(e){console.error("Error fetching keys:",e)}finally{es(!1)}})()},[h,a]),(0,i.useEffect)(()=>{if(1!==h&&3!==h||!a||!u||!x)return;let e=!1;return ei(!0),(0,l.modelAvailableCall)(a,u,x).then(t=>{e||el((t?.data??(Array.isArray(t)?t:[])).map(e=>e.id??e.model_name).filter(Boolean))}).catch(t=>{e||console.error("Error fetching models:",t)}).finally(()=>{e||ei(!1)}),()=>{e=!0}},[h,a,u,x]),(0,i.useEffect)(()=>{if(1!==h||!a)return;let e=!1;return ec(!0),(0,l.getAgentsList)(a).then(t=>{e||eo((t?.agents??[]).map(e=>({agent_id:e.agent_id,agent_name:e.agent_name})))}).catch(t=>{e||console.error("Error fetching agents:",t)}).finally(()=>{e||ec(!1)}),()=>{e=!0}},[h,a]);let eM=v.find(e=>e.agent_type===f),eD=async()=>{try{if(0===h){await p.validateFields(["agent_name"]);let e=p.getFieldValue("agent_name");e&&!G&&K(`${e}-key`)}g(e=>e+1)}catch{}},eE=async()=>{if(!a)return void T.message.error("No access token available");j(!0);try{await p.validateFields();let e={...p.getFieldsValue(!0)},t=(e=>{if(f===eN)return{agent_name:e.agent_name,agent_card_params:{protocolVersion:"1.0",name:e.agent_name,description:e.description||"",url:"",version:"1.0.0",defaultInputModes:["text"],defaultOutputModes:["text"],capabilities:{streaming:!1},skills:[]}};if("a2a"===f)return em(e);if(eM?.use_a2a_form_fields){let t=em(e);for(let s of(eM.litellm_params_template&&(t.litellm_params={...t.litellm_params,...eM.litellm_params_template}),eM.credential_fields)){let a=e[s.key];a&&!1!==s.include_in_litellm_params&&(t.litellm_params[s.key]=a)}return t}return eM?ey(e,eM):null})(e);if(!t){T.message.error("Failed to build agent data"),j(!1);return}let s=e.allowed_mcp_servers_and_groups,r=e.mcp_tool_permissions||{},i=e.entitlement_models||[],o=e.entitlement_agents||[];(s?.servers?.length>0||s?.accessGroups?.length>0||Object.keys(r).length>0||i.length>0||o.length>0)&&(t.object_permission={},s?.servers?.length>0&&(t.object_permission.mcp_servers=s.servers),s?.accessGroups?.length>0&&(t.object_permission.mcp_access_groups=s.accessGroups),Object.keys(r).length>0&&(t.object_permission.mcp_tool_permissions=r),i.length>0&&(t.object_permission.models=i),o.length>0&&(t.object_permission.agents=o)),(eC||eT)&&(t.litellm_params||(t.litellm_params={}),eC&&(t.litellm_params.require_trace_id_on_calls_to_agent=!0),eT&&(t.litellm_params.require_trace_id_on_calls_by_agent=!0,eF&&(t.litellm_params.max_iterations=eF),eL&&(t.litellm_params.max_budget_per_session=eL)));let d=e.guardrails||[];d.length>0&&(t.litellm_params||(t.litellm_params={}),t.litellm_params.guardrails=d);let c=e.team_id||null;c&&(t.team_id=c);let m=await (0,l.createAgentCall)(a,t),u=m.agent_id,x=m.agent_name||e.agent_name||u;if(ex(x),"create_new"===H&&G){let e=await (0,l.keyCreateForAgentCall)(a,u,G,W,void 0,c);eg(e.key||null)}else if("existing_key"===H){if(!Z){T.message.error("Please select an existing key to assign"),j(!1);return}await (0,l.keyUpdateCall)(a,{key:Z,agent_id:u});let e=J.find(e=>e.token===Z);ek(e?.key_alias||Z.slice(0,12)+"…")}g(4),n()}catch(t){console.error("Error creating agent:",t);let e=t instanceof Error?t.message:String(t);T.message.error(e?`Failed to create agent: ${e}`:"Failed to create agent")}finally{j(!1)}},eO=()=>{p.resetFields(),b("a2a"),g(0),V("create_new"),K(""),Y([]),ee(null),ex(""),eg(null),ek(null),eS(!1),eI(!1),eP(null),eA(null),s()},eR=e=>{b(e),p.resetFields()},ez=f===eN?null:eM?.logo_url||v.find(e=>"a2a"===e.agent_type)?.logo_url;return(0,t.jsx)(_.Modal,{title:(0,t.jsxs)("div",{className:"flex items-center space-x-3 pb-4 border-b border-gray-100",children:[ez&&h<1&&(0,t.jsx)("img",{src:ez,alt:"Agent",className:"w-6 h-6 object-contain"}),(0,t.jsx)("h2",{className:"text-xl font-semibold text-gray-900",children:"Add New Agent"})]}),open:e,onCancel:eO,footer:null,width:900,className:"top-8",styles:{body:{padding:"24px"},header:{padding:"24px 24px 0 24px",border:"none"}},children:(0,t.jsxs)("div",{className:"mt-4",children:[(0,t.jsxs)(P.Steps,{current:h,size:"small",className:"mb-8",children:[(0,t.jsx)(ev,{title:"Configure"}),(0,t.jsx)(ev,{title:"Entitlements"}),(0,t.jsx)(ev,{title:"Governance"}),(0,t.jsx)(ev,{title:"Agent Management"}),(0,t.jsx)(ev,{title:"Ready"})]}),(0,t.jsxs)(S.Form,{form:p,layout:"vertical",initialValues:"a2a"===f?{...(d={defaultInputModes:["text"],defaultOutputModes:["text"]},Object.values(Q).forEach(e=>{e.fields.forEach(e=>{void 0!==e.defaultValue&&(d[e.name]=e.defaultValue)})}),d),allowed_mcp_servers_and_groups:{servers:[],accessGroups:[]},mcp_tool_permissions:{},entitlement_models:[],entitlement_agents:[],guardrails:[]}:{allowed_mcp_servers_and_groups:{servers:[],accessGroups:[]},mcp_tool_permissions:{},entitlement_models:[],entitlement_agents:[],guardrails:[]},className:"space-y-4",children:[0===h&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(S.Form.Item,{label:(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Agent Type"}),required:!0,tooltip:"Select the type of agent you want to create",children:(0,t.jsx)(I.Select,{value:f,onChange:eR,size:"large",style:{width:"100%"},optionLabelProp:"label",dropdownRender:e=>(0,t.jsxs)(t.Fragment,{children:[e,(0,t.jsx)(M.Divider,{style:{margin:"4px 0"}}),(0,t.jsxs)("div",{className:"px-2 py-1",children:[(0,t.jsx)("div",{className:"text-xs text-gray-400 font-medium mb-1 uppercase tracking-wide px-2",children:"Not listed?"}),(0,t.jsxs)("div",{className:`flex items-center gap-3 px-2 py-2 rounded cursor-pointer transition-colors ${f===eN?"bg-amber-50":"hover:bg-amber-50"}`,onClick:()=>eR(eN),children:[(0,t.jsx)(z.AppstoreOutlined,{className:"text-amber-600 text-lg"}),(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:"font-medium text-amber-700",children:"Custom / Other"}),(0,t.jsx)(A.Tag,{color:"orange",style:{fontSize:10,padding:"0 4px"},children:"GENERIC"})]}),(0,t.jsx)("div",{className:"text-xs text-amber-600",children:"For agents that don't follow a standard protocol — just needs a virtual key"})]})]})]})]}),children:v.map(e=>(0,t.jsx)(I.Select.Option,{value:e.agent_type,label:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("img",{src:e.logo_url||"",alt:"",className:"w-4 h-4 object-contain"}),(0,t.jsx)("span",{children:e.agent_type_display_name})]}),children:(0,t.jsxs)("div",{className:"flex items-center gap-3 py-1",children:[(0,t.jsx)("img",{src:e.logo_url||"",alt:e.agent_type_display_name,className:"w-5 h-5 object-contain"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"font-medium",children:e.agent_type_display_name}),e.description&&(0,t.jsx)("div",{className:"text-xs text-gray-500",children:e.description})]})]})},e.agent_type))})}),(0,t.jsx)("div",{className:"mt-4",children:f===eN?(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)(S.Form.Item,{label:"Agent Name",name:"agent_name",rules:[{required:!0,message:"Please enter an agent name"}],children:(0,t.jsx)(F.Input,{placeholder:"e.g. my-custom-agent"})}),(0,t.jsx)(S.Form.Item,{label:"Description",name:"description",children:(0,t.jsx)(F.Input.TextArea,{placeholder:"Describe what this agent does…",rows:3})})]}):"a2a"===f?(0,t.jsx)(eh,{showAgentName:!0}):eM?.use_a2a_form_fields?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(eh,{showAgentName:!0}),eM.credential_fields.length>0&&(0,t.jsxs)("div",{className:"mt-4 p-4 border border-gray-200 rounded-lg",children:[(0,t.jsxs)("h4",{className:"text-sm font-medium text-gray-700 mb-3",children:[eM.agent_type_display_name," Settings"]}),eM.credential_fields.map(e=>(0,t.jsx)(S.Form.Item,{label:e.label,name:e.key,rules:e.required?[{required:!0,message:`Please enter ${e.label}`}]:void 0,tooltip:e.tooltip,initialValue:e.default_value,children:"password"===e.field_type?(0,t.jsx)(F.Input.Password,{placeholder:e.placeholder||""}):(0,t.jsx)(F.Input,{placeholder:e.placeholder||""})},e.key))]})]}):eM?(0,t.jsx)(ej,{agentTypeInfo:eM}):null})]}),1===h&&(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("p",{className:"text-sm text-gray-600",children:"Configure which models, agents, and MCP tools this agent is allowed to use. Leave fields empty to allow all (subject to key/team permissions)."}),(0,t.jsx)(S.Form.Item,{label:(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Allowed Models"}),name:"entitlement_models",tooltip:"Restrict which models this agent can call. Leave empty to allow all.",children:(0,t.jsx)(I.Select,{mode:"tags",style:{width:"100%"},placeholder:er?"Loading models...":"Select models (leave empty for all)",tokenSeparators:[","],loading:er,showSearch:!0,options:ea.map(e=>({label:(0,$.getModelDisplayName)(e),value:e}))})}),(0,t.jsx)(S.Form.Item,{label:(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Allowed Agents (Sub-Agents)"}),name:"entitlement_agents",tooltip:"Restrict which other agents this agent can invoke as sub-agents. Leave empty to allow all.",children:(0,t.jsx)(I.Select,{mode:"multiple",style:{width:"100%"},placeholder:ed?"Loading agents...":"Select agents (leave empty for all)",loading:ed,showSearch:!0,filterOption:(e,t)=>(t?.label??"").toLowerCase().includes(e.toLowerCase()),options:en.map(e=>({label:e.agent_name,value:e.agent_id}))})}),(0,t.jsx)(M.Divider,{className:"my-2"}),(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed MCP Servers"," ",(0,t.jsx)(B.InfoCircleOutlined,{title:"Select which MCP servers or access groups this agent can access",style:{marginLeft:"4px"}})]}),name:"allowed_mcp_servers_and_groups",initialValue:{servers:[],accessGroups:[]},children:(0,t.jsx)(ef.default,{onChange:e=>p.setFieldValue("allowed_mcp_servers_and_groups",e),value:p.getFieldValue("allowed_mcp_servers_and_groups")||{servers:[],accessGroups:[]},accessToken:a??"",placeholder:"Select MCP servers or access groups (optional)"})}),(0,t.jsx)(S.Form.Item,{name:"mcp_tool_permissions",initialValue:{},hidden:!0,children:(0,t.jsx)(F.Input,{type:"hidden"})}),(0,t.jsx)(S.Form.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:()=>(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(eb.default,{accessToken:a??"",selectedServers:p.getFieldValue("allowed_mcp_servers_and_groups")?.servers??[],toolPermissions:p.getFieldValue("mcp_tool_permissions")??{},onChange:e=>p.setFieldsValue({mcp_tool_permissions:e})})})})]}),2===h&&(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h4",{className:"text-sm font-medium text-gray-700 mb-3",children:"Tracing"}),(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Require x-litellm-trace-id on calls TO this agent"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Only accept this agent being invoked with a trace-id (e.g. when used as a sub-agent)."})]}),(0,t.jsx)(k.Switch,{checked:eC,onChange:eS})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Require x-litellm-trace-id on calls BY this agent"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Requires LLM/MCP calls made by this agent to include x-litellm-trace-id for session tracking."})]}),(0,t.jsx)(k.Switch,{checked:eT,onChange:e=>{eI(e),e||(eP(null),eA(null))}})]})]})]}),(0,t.jsx)(M.Divider,{className:"my-0"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("h4",{className:"text-sm font-medium text-gray-700 mb-3",children:"Budgets & Rate Limits"}),(0,t.jsxs)("div",{className:"space-y-4",children:[!eT&&(0,t.jsx)("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-lg text-sm text-yellow-800",children:'Enable "Require x-litellm-trace-id on calls BY this agent" in Tracing to configure budgets and rate limits.'}),(0,t.jsx)("div",{className:"text-sm font-medium text-gray-700",children:"Session Budgets"}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm text-gray-600 block mb-1",children:"Max Iterations"}),(0,t.jsx)(D.InputNumber,{className:"w-full",min:1,placeholder:"e.g. 25",disabled:!eT,value:eF,onChange:e=>eP(e)}),(0,t.jsx)("p",{className:"text-xs text-gray-400 mt-1",children:"Hard cap on LLM calls per session"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm text-gray-600 block mb-1",children:"Max Budget Per Session ($)"}),(0,t.jsx)(D.InputNumber,{className:"w-full",min:.01,step:.5,placeholder:"e.g. 5.00",disabled:!eT,value:eL,onChange:e=>eA(e)}),(0,t.jsx)("p",{className:"text-xs text-gray-400 mt-1",children:"Max spend per trace before returning 429"})]})]}),(0,t.jsx)(M.Divider,{className:"my-2"}),(0,t.jsx)("div",{className:"text-sm font-medium text-gray-700",children:"Agent Rate Limits"}),(0,t.jsx)("p",{className:"text-xs text-gray-500",children:"Global rate limits applied across all callers of this agent."}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-4",children:[(0,t.jsx)(S.Form.Item,{label:"TPM Limit",name:"tpm_limit",className:"mb-0",children:(0,t.jsx)(D.InputNumber,{className:"w-full",min:0,placeholder:"e.g. 100000",disabled:!eT})}),(0,t.jsx)(S.Form.Item,{label:"RPM Limit",name:"rpm_limit",className:"mb-0",children:(0,t.jsx)(D.InputNumber,{className:"w-full",min:0,placeholder:"e.g. 100",disabled:!eT})})]}),(0,t.jsx)("div",{className:"text-sm font-medium text-gray-700 mt-4",children:"Per-Session Rate Limits"}),(0,t.jsx)("p",{className:"text-xs text-gray-500",children:"Rate limits per session (x-litellm-trace-id). Each session gets its own counters."}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-4",children:[(0,t.jsx)(S.Form.Item,{label:"Session TPM Limit",name:"session_tpm_limit",className:"mb-0",children:(0,t.jsx)(D.InputNumber,{className:"w-full",min:0,placeholder:"e.g. 10000",disabled:!eT})}),(0,t.jsx)(S.Form.Item,{label:"Session RPM Limit",name:"session_rpm_limit",className:"mb-0",children:(0,t.jsx)(D.InputNumber,{className:"w-full",min:0,placeholder:"e.g. 20",disabled:!eT})})]})]})]}),(0,t.jsx)(M.Divider,{className:"my-0"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("h4",{className:"text-sm font-medium text-gray-700 mb-3",children:"Guardrails"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mb-3",children:"Apply guardrails to this agent. Selected guardrails will run on all calls made by this agent."}),(0,t.jsx)(S.Form.Item,{name:"guardrails",initialValue:[],children:(0,t.jsx)(e_.default,{accessToken:a??"",value:p.getFieldValue("guardrails")??[],onChange:e=>p.setFieldsValue({guardrails:e})})})]})]}),3===h&&(c=p.getFieldValue("agent_name")||"your-agent",(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"flex justify-center mb-6",children:(0,t.jsx)(A.Tag,{icon:(0,t.jsx)(R.RobotOutlined,{}),color:"purple",className:"px-3 py-1 text-sm",children:c})}),(0,t.jsx)(S.Form.Item,{label:(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Assign to Team"}),name:"team_id",tooltip:"Optionally assign this agent to a team. The agent and its key will belong to the selected team.",children:(0,t.jsx)(U.default,{teams:o,loading:!o})}),(0,t.jsx)(M.Divider,{className:"my-4"}),(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsx)("div",{className:`p-4 border-2 rounded-lg cursor-pointer transition-colors ${"create_new"===H?"border-indigo-600 bg-indigo-50":"border-gray-200 bg-white hover:border-gray-300"}`,onClick:()=>V("create_new"),children:(0,t.jsxs)("div",{className:"flex items-start justify-between",children:[(0,t.jsxs)("div",{className:"flex items-start gap-3 flex-1",children:[(0,t.jsx)(L.Radio,{value:"create_new",checked:"create_new"===H,onChange:()=>V("create_new")}),(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(O.KeyOutlined,{className:"text-indigo-600"}),(0,t.jsx)("span",{className:"font-medium text-gray-900",children:"Create a new key for this agent"})]}),(0,t.jsx)("p",{className:"text-sm text-gray-500 mt-1",children:"A dedicated key scoped to this agent."}),"create_new"===H&&(0,t.jsx)("div",{className:"mt-3 space-y-3",onClick:e=>e.stopPropagation(),children:(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm text-gray-600 block mb-1",children:"Key Name"}),(0,t.jsx)(F.Input,{value:G,onChange:e=>K(e.target.value),placeholder:"e.g. my-agent-key"})]})})]})]}),(0,t.jsx)(A.Tag,{color:"green",children:"Recommended"})]})}),(0,t.jsx)("div",{className:`p-4 border-2 rounded-lg cursor-pointer transition-colors ${"existing_key"===H?"border-indigo-600 bg-indigo-50":"border-gray-200 bg-white hover:border-gray-300"}`,onClick:()=>V("existing_key"),children:(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)(L.Radio,{value:"existing_key",checked:"existing_key"===H,onChange:()=>V("existing_key")}),(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(O.KeyOutlined,{className:"text-gray-500"}),(0,t.jsx)("span",{className:"font-medium text-gray-900",children:"Assign an existing key"})]}),(0,t.jsx)("p",{className:"text-sm text-gray-500 mt-1",children:"Re-assign a key you already have to this agent."}),"existing_key"===H&&(0,t.jsx)("div",{className:"mt-3",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(I.Select,{showSearch:!0,style:{width:"100%"},placeholder:"Search by key name…",loading:et,value:Z,onChange:e=>ee(e),filterOption:(e,t)=>(t?.label??"").toLowerCase().includes(e.toLowerCase()),options:J.map(e=>({label:e.key_alias||e.token?.slice(0,12)+"…",value:e.token}))})})]})]})})]}),(0,t.jsx)("div",{className:"text-center mt-4",children:(0,t.jsx)("button",{type:"button",className:"text-sm text-gray-500 underline hover:text-gray-700",onClick:()=>V("skip"),children:"Skip for now — I'll assign a key later"})})]})),4===h&&(0,t.jsxs)("div",{className:"text-center py-6",children:[(0,t.jsx)(E.CheckCircleFilled,{className:"text-5xl text-green-500 mb-4",style:{fontSize:48}}),(0,t.jsx)("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"Agent Created!"}),(0,t.jsx)("div",{className:"flex justify-center mb-4",children:(0,t.jsx)(A.Tag,{icon:(0,t.jsx)(R.RobotOutlined,{}),color:"purple",className:"px-3 py-1 text-sm",children:eu})}),ep&&(0,t.jsx)("div",{className:"mt-4 text-left max-w-md mx-auto",children:(0,t.jsx)(q.default,{apiKey:ep})}),ew&&(0,t.jsxs)("p",{className:"text-sm text-gray-600 mt-2",children:["Key ",(0,t.jsx)("span",{className:"font-medium",children:ew})," has been assigned to this agent."]}),!ep&&!ew&&"skip"===H&&(0,t.jsx)("p",{className:"text-sm text-gray-500 mt-2",children:"No key assigned. You can create one from the Virtual Keys page."})]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between pt-6 border-t border-gray-100 mt-6",children:[(0,t.jsx)("div",{children:h>0&&h<4&&(0,t.jsx)("button",{type:"button",onClick:()=>{g(e=>Math.max(0,e-1))},className:"text-sm text-gray-600 border border-gray-300 rounded px-4 py-2 hover:bg-gray-50",children:"← Back"})}),(0,t.jsxs)("div",{className:"flex gap-3",children:[h<4&&(0,t.jsx)(m.Button,{variant:"secondary",onClick:eO,children:"Cancel"}),0===h&&(0,t.jsx)(m.Button,{variant:"primary",onClick:eD,children:"Next →"}),1===h&&(0,t.jsx)(m.Button,{variant:"primary",onClick:eD,children:"Next →"}),2===h&&(0,t.jsx)(m.Button,{variant:"primary",onClick:eD,children:"Next →"}),3===h&&(0,t.jsx)(m.Button,{variant:"primary",loading:y,onClick:eE,children:y?"Creating...":"Create Agent →"}),4===h&&(0,t.jsx)(m.Button,{variant:"primary",onClick:eO,children:"Done"})]})]})]})})};var ek=e.i(708347),eC=e.i(629569),eS=e.i(197647),eT=e.i(653824),eI=e.i(881073),eF=e.i(404206),eP=e.i(723731),eL=e.i(482725),eA=e.i(869216),eM=e.i(530212);let eD=({agent:e})=>{let s=e.litellm_params;return s?.cost_per_query===void 0&&s?.input_cost_per_token===void 0&&s?.output_cost_per_token===void 0?null:(0,t.jsxs)("div",{style:{marginTop:24},children:[(0,t.jsx)(eC.Title,{children:"Cost Configuration"}),(0,t.jsxs)(eA.Descriptions,{bordered:!0,column:1,style:{marginTop:16},children:[void 0!==s.cost_per_query&&(0,t.jsxs)(eA.Descriptions.Item,{label:"Cost Per Query",children:["$",s.cost_per_query]}),void 0!==s.input_cost_per_token&&(0,t.jsxs)(eA.Descriptions.Item,{label:"Input Cost Per Token",children:["$",s.input_cost_per_token]}),void 0!==s.output_cost_per_token&&(0,t.jsxs)(eA.Descriptions.Item,{label:"Output Cost Per Token",children:["$",s.output_cost_per_token]})]})]})},eE=e=>{let t=e.litellm_params?.model||"",s=e.litellm_params?.custom_llm_provider;return"langgraph"===s?"langgraph":"azure_ai"===s?"azure_ai_foundry":"bedrock"===s?"bedrock_agentcore":t.startsWith("langgraph/")?"langgraph":t.startsWith("azure_ai/agents/")?"azure_ai_foundry":t.startsWith("bedrock/agentcore/")?"bedrock_agentcore":"a2a"},eO=(e,t)=>{let s={agent_name:e.agent_name,description:e.agent_card_params?.description||""};for(let a of t.credential_fields)if(!1!==a.include_in_litellm_params)s[a.key]=e.litellm_params?.[a.key]||a.default_value||"";else if(t.model_template&&e.litellm_params?.model){let l=e.litellm_params.model,r=t.model_template.split("/"),i=l.split("/");r.forEach((e,t)=>{e===`{${a.key}}`&&i[t]&&(s[a.key]=i[t])})}return s.cost_per_query=e.litellm_params?.cost_per_query,s.input_cost_per_token=e.litellm_params?.input_cost_per_token,s.output_cost_per_token=e.litellm_params?.output_cost_per_token,s},eR=({agentId:e,onClose:s,accessToken:a,isAdmin:r})=>{let[n,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(!0),[x,p]=(0,i.useState)(!1),[h,g]=(0,i.useState)(!1),[y]=S.Form.useForm(),[j,f]=(0,i.useState)([]),[_,v]=(0,i.useState)("a2a");(0,i.useEffect)(()=>{(async()=>{try{let e=await (0,l.getAgentCreateMetadata)();f(e)}catch(e){console.error("Error fetching agent metadata:",e)}})()},[]),(0,i.useEffect)(()=>{N()},[e,a]);let N=async()=>{if(a){c(!0);try{let t=await (0,l.getAgentInfo)(a,e);o(t);let s=eE(t);if(v(s),"a2a"===s)y.setFieldsValue(eu(t));else{let e=j.find(e=>e.agent_type===s);e?y.setFieldsValue(eO(t,e)):y.setFieldsValue(eu(t))}}catch(e){console.error("Error fetching agent info:",e),T.message.error("Failed to load agent information")}finally{c(!1)}}};(0,i.useEffect)(()=>{if(n&&j.length>0){let e=eE(n);if("a2a"!==e){let t=j.find(t=>t.agent_type===e);t&&y.setFieldsValue(eO(n,t))}}},[j,n]);let w=j.find(e=>e.agent_type===_),k=async t=>{if(a&&n){g(!0);try{let s;"a2a"===_?s=em(t,n):w?(s=ey(t,w)).agent_name=t.agent_name:s=em(t,n),await (0,l.patchAgentCall)(a,e,s),T.message.success("Agent updated successfully"),p(!1),N()}catch(e){console.error("Error updating agent:",e),T.message.error("Failed to update agent")}finally{g(!1)}}};if(d)return(0,t.jsx)("div",{className:"p-4",children:(0,t.jsx)("div",{className:"flex justify-center items-center h-64",children:(0,t.jsx)(eL.Spin,{size:"large"})})});if(!n)return(0,t.jsxs)("div",{className:"p-4",children:[(0,t.jsx)("div",{className:"text-center",children:"Agent not found"}),(0,t.jsx)(m.Button,{onClick:s,className:"mt-4",children:"Back to Agents List"})]});let C=e=>e?new Date(e).toLocaleString():"-";return(0,t.jsxs)("div",{className:"p-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(m.Button,{icon:eM.ArrowLeftIcon,variant:"light",onClick:s,className:"mb-4",children:"Back to Agents"}),(0,t.jsx)(eC.Title,{children:n.agent_name||"Unnamed Agent"}),(0,t.jsx)(b.Text,{className:"text-gray-500 font-mono",children:n.agent_id})]}),(0,t.jsxs)(eT.TabGroup,{children:[(0,t.jsxs)(eI.TabList,{className:"mb-4",children:[(0,t.jsx)(eS.Tab,{children:"Overview"},"overview"),r?(0,t.jsx)(eS.Tab,{children:"Settings"},"settings"):(0,t.jsx)(t.Fragment,{})]}),(0,t.jsxs)(eP.TabPanels,{children:[(0,t.jsxs)(eF.TabPanel,{children:[(0,t.jsxs)(eA.Descriptions,{bordered:!0,column:1,children:[(0,t.jsx)(eA.Descriptions.Item,{label:"Agent ID",children:n.agent_id}),(0,t.jsx)(eA.Descriptions.Item,{label:"Agent Name",children:n.agent_name}),(0,t.jsx)(eA.Descriptions.Item,{label:"Display Name",children:n.agent_card_params?.name||"-"}),(0,t.jsx)(eA.Descriptions.Item,{label:"Description",children:n.agent_card_params?.description||"-"}),(0,t.jsx)(eA.Descriptions.Item,{label:"URL",children:n.agent_card_params?.url||"-"}),(0,t.jsx)(eA.Descriptions.Item,{label:"Version",children:n.agent_card_params?.version||"-"}),(0,t.jsx)(eA.Descriptions.Item,{label:"Protocol Version",children:n.agent_card_params?.protocolVersion||"-"}),(0,t.jsx)(eA.Descriptions.Item,{label:"Streaming",children:n.agent_card_params?.capabilities?.streaming?"Yes":"No"}),n.agent_card_params?.capabilities?.pushNotifications&&(0,t.jsx)(eA.Descriptions.Item,{label:"Push Notifications",children:"Yes"}),n.agent_card_params?.capabilities?.stateTransitionHistory&&(0,t.jsx)(eA.Descriptions.Item,{label:"State Transition History",children:"Yes"}),(0,t.jsxs)(eA.Descriptions.Item,{label:"Skills",children:[n.agent_card_params?.skills?.length||0," configured"]}),n.litellm_params?.model&&(0,t.jsx)(eA.Descriptions.Item,{label:"Model",children:n.litellm_params.model}),n.litellm_params?.make_public!==void 0&&(0,t.jsx)(eA.Descriptions.Item,{label:"Make Public",children:n.litellm_params.make_public?"Yes":"No"}),n.agent_card_params?.iconUrl&&(0,t.jsx)(eA.Descriptions.Item,{label:"Icon URL",children:n.agent_card_params.iconUrl}),n.agent_card_params?.documentationUrl&&(0,t.jsx)(eA.Descriptions.Item,{label:"Documentation URL",children:n.agent_card_params.documentationUrl}),(0,t.jsx)(eA.Descriptions.Item,{label:"TPM Limit",children:n.tpm_limit??"Unlimited"}),(0,t.jsx)(eA.Descriptions.Item,{label:"RPM Limit",children:n.rpm_limit??"Unlimited"}),(0,t.jsx)(eA.Descriptions.Item,{label:"Session TPM Limit",children:n.session_tpm_limit??"Unlimited"}),(0,t.jsx)(eA.Descriptions.Item,{label:"Session RPM Limit",children:n.session_rpm_limit??"Unlimited"}),(0,t.jsx)(eA.Descriptions.Item,{label:"Created At",children:C(n.created_at)}),(0,t.jsx)(eA.Descriptions.Item,{label:"Updated At",children:C(n.updated_at)})]}),n.object_permission&&(n.object_permission.mcp_servers?.length||n.object_permission.mcp_access_groups?.length||n.object_permission.mcp_tool_permissions&&Object.keys(n.object_permission.mcp_tool_permissions).length>0)&&(0,t.jsxs)("div",{style:{marginTop:24},children:[(0,t.jsx)(eC.Title,{children:"MCP Tool Permissions"}),(0,t.jsxs)(eA.Descriptions,{bordered:!0,column:1,style:{marginTop:16},children:[n.object_permission.mcp_servers&&n.object_permission.mcp_servers.length>0&&(0,t.jsx)(eA.Descriptions.Item,{label:"MCP Servers",children:n.object_permission.mcp_servers.join(", ")}),n.object_permission.mcp_access_groups&&n.object_permission.mcp_access_groups.length>0&&(0,t.jsx)(eA.Descriptions.Item,{label:"MCP Access Groups",children:n.object_permission.mcp_access_groups.join(", ")}),n.object_permission.mcp_tool_permissions&&Object.keys(n.object_permission.mcp_tool_permissions).length>0&&(0,t.jsx)(eA.Descriptions.Item,{label:"Tool permissions per server",children:(0,t.jsx)("div",{className:"space-y-1",children:Object.entries(n.object_permission.mcp_tool_permissions).map(([e,s])=>(0,t.jsxs)("div",{children:[(0,t.jsxs)("span",{className:"font-medium",children:[e,":"]})," ",Array.isArray(s)?s.join(", "):String(s)]},e))})})]})]}),(0,t.jsx)(eD,{agent:n}),n.agent_card_params?.skills&&n.agent_card_params.skills.length>0&&(0,t.jsxs)("div",{style:{marginTop:24},children:[(0,t.jsx)(eC.Title,{children:"Skills"}),(0,t.jsx)(eA.Descriptions,{bordered:!0,column:1,style:{marginTop:16},children:n.agent_card_params.skills.map((e,s)=>(0,t.jsx)(eA.Descriptions.Item,{label:e.name||`Skill ${s+1}`,children:(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("strong",{children:"ID:"})," ",e.id]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("strong",{children:"Description:"})," ",e.description]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("strong",{children:"Tags:"})," ",Array.isArray(e.tags)?e.tags.join(", "):e.tags]}),e.examples&&e.examples.length>0&&(0,t.jsxs)("div",{children:[(0,t.jsx)("strong",{children:"Examples:"})," ",Array.isArray(e.examples)?e.examples.join(", "):e.examples]})]})},s))})]})]}),r&&(0,t.jsx)(eF.TabPanel,{children:(0,t.jsxs)(u.Card,{children:[(0,t.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,t.jsx)(eC.Title,{children:"Agent Settings"}),!x&&(0,t.jsx)(m.Button,{onClick:()=>p(!0),children:"Edit Settings"})]}),x?(0,t.jsxs)(S.Form,{form:y,layout:"vertical",onFinish:k,children:[(0,t.jsx)(S.Form.Item,{label:"Agent ID",children:(0,t.jsx)(F.Input,{value:n.agent_id,disabled:!0})}),"a2a"===_?(0,t.jsx)(eh,{showAgentName:!0}):w?(0,t.jsx)(ej,{agentTypeInfo:w}):(0,t.jsx)(eh,{showAgentName:!0}),(0,t.jsx)(M.Divider,{}),(0,t.jsx)(eC.Title,{className:"mb-4",children:"Rate Limits"}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-4",children:[(0,t.jsx)(S.Form.Item,{label:"TPM Limit",name:"tpm_limit",children:(0,t.jsx)(D.InputNumber,{className:"w-full",min:0,placeholder:"Unlimited"})}),(0,t.jsx)(S.Form.Item,{label:"RPM Limit",name:"rpm_limit",children:(0,t.jsx)(D.InputNumber,{className:"w-full",min:0,placeholder:"Unlimited"})})]}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-4",children:[(0,t.jsx)(S.Form.Item,{label:"Session TPM Limit",name:"session_tpm_limit",children:(0,t.jsx)(D.InputNumber,{className:"w-full",min:0,placeholder:"Unlimited"})}),(0,t.jsx)(S.Form.Item,{label:"Session RPM Limit",name:"session_rpm_limit",children:(0,t.jsx)(D.InputNumber,{className:"w-full",min:0,placeholder:"Unlimited"})})]}),(0,t.jsxs)("div",{className:"flex justify-end gap-2 mt-6",children:[(0,t.jsx)(G.Button,{onClick:()=>{p(!1),N()},children:"Cancel"}),(0,t.jsx)(m.Button,{loading:h,children:"Save Changes"})]})]}):(0,t.jsx)(b.Text,{children:'Click "Edit Settings" to modify agent configuration.'})]})})]})]})]})};var ez=e.i(727749),eB=e.i(500330),eq=e.i(902555);let e$=({accessToken:e,userRole:s,teams:a})=>{let[r,n]=(0,i.useState)([]),[o,d]=(0,i.useState)({}),[c,S]=(0,i.useState)(!1),[T,I]=(0,i.useState)(!1),[F,P]=(0,i.useState)(!1),[L,A]=(0,i.useState)(null),[M,D]=(0,i.useState)(null),[E,O]=(0,i.useState)(!1),R=!!s&&(0,ek.isAdminRole)(s),z=async t=>{if(e){I(!0);try{let s=await (0,l.getAgentsList)(e,t??E);n(s.agents||[])}catch(e){console.error("Error fetching agents:",e)}finally{I(!1)}}},B=async()=>{if(e)try{let{keys:t=[]}=await (0,l.keyListCall)(e,null,null,null,null,null,1,500),s={};for(let e of t){let t=e.agent_id;t&&!s[t]&&(s[t]={has_key:!0,key_alias:e.key_alias,token_prefix:e.token?`${e.token.slice(0,8)}…`:void 0})}d(s)}catch(e){console.error("Error fetching keys for agents:",e)}};(0,i.useEffect)(()=>{z()},[e]),(0,i.useEffect)(()=>{e&&r.length>0?B():0===r.length&&d({})},[e,r.length]);let q=async()=>{if(L&&e){P(!0);try{await (0,l.deleteAgentCall)(e,L.id),ez.default.success(`Agent "${L.name}" deleted successfully`),z()}catch(e){console.error("Error deleting agent:",e),ez.default.fromBackend("Failed to delete agent")}finally{P(!1),A(null)}}},$=[...r].sort((e,t)=>{let s=e.created_at?new Date(e.created_at).getTime():0;return(t.created_at?new Date(t.created_at).getTime():0)-s}),U=R?7:6;return(0,t.jsxs)("div",{className:"w-full mx-auto flex-auto overflow-y-auto m-8 p-2",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-2 mb-4",children:[(0,t.jsx)("h1",{className:"text-2xl font-bold",children:"Agents"}),(0,t.jsx)("p",{className:"text-sm text-gray-600",children:"List of A2A-spec agents that are available to be used in your organization. Go to AI Hub, to make agents public."}),(0,t.jsx)(v.Alert,{message:"Why do agents need keys?",description:"Keys scope access to an agent and allow it to call MCP tools. Assign a key when creating an agent or from the Virtual Keys page.",type:"info",showIcon:!0,className:"mb-3"}),(0,t.jsxs)("div",{className:"mt-2 flex items-center gap-4",children:[R&&(0,t.jsx)(m.Button,{onClick:()=>{M&&D(null),S(!0)},disabled:!e,children:"+ Add New Agent"}),(0,t.jsx)(N.Tooltip,{title:"When enabled, only agents with reachable URLs are shown",children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(C.CheckCircleOutlined,{className:E?"text-green-500":"text-gray-400"}),(0,t.jsx)("span",{className:"text-sm text-gray-600",children:"Health Check"}),(0,t.jsx)(k.Switch,{size:"small",checked:E,onChange:e=>{O(e),z(e)},loading:T&&E})]})})]})]}),M?(0,t.jsx)(eR,{agentId:M,onClose:()=>D(null),accessToken:e,isAdmin:R}):(0,t.jsx)(u.Card,{children:T?(0,t.jsx)(w.Skeleton,{active:!0,paragraph:{rows:3}}):(0,t.jsxs)(x.Table,{children:[(0,t.jsx)(g.TableHead,{children:(0,t.jsxs)(j.TableRow,{children:[(0,t.jsx)(y.TableHeaderCell,{children:"Agent Name"}),(0,t.jsx)(y.TableHeaderCell,{children:"Agent ID"}),(0,t.jsx)(y.TableHeaderCell,{children:"Spend (USD)"}),(0,t.jsx)(y.TableHeaderCell,{children:"Model"}),(0,t.jsx)(y.TableHeaderCell,{children:"Created"}),(0,t.jsx)(y.TableHeaderCell,{children:"Status"}),R&&(0,t.jsx)(y.TableHeaderCell,{children:"Actions"})]})}),(0,t.jsx)(p.TableBody,{children:0===$.length?(0,t.jsx)(j.TableRow,{children:(0,t.jsx)(h.TableCell,{colSpan:U,children:(0,t.jsx)(b.Text,{className:"text-center",children:'No agents found. Click "+ Add New Agent" to create one.'})})}):$.map(e=>(0,t.jsxs)(j.TableRow,{children:[(0,t.jsx)(h.TableCell,{children:(0,t.jsx)(b.Text,{children:e.agent_name})}),(0,t.jsx)(h.TableCell,{children:(0,t.jsx)(N.Tooltip,{title:e.agent_id,children:(0,t.jsxs)(m.Button,{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:()=>D(e.agent_id),children:[e.agent_id.slice(0,7),"..."]})})}),(0,t.jsx)(h.TableCell,{children:(0,t.jsx)(b.Text,{children:(0,eB.formatNumberWithCommas)(e.spend,4)})}),(0,t.jsx)(h.TableCell,{children:(0,t.jsx)(f.Badge,{size:"xs",color:"blue",children:e.litellm_params?.model||"N/A"})}),(0,t.jsx)(h.TableCell,{children:(0,t.jsx)(b.Text,{children:e.created_at?new Date(e.created_at).toLocaleDateString():"N/A"})}),(0,t.jsx)(h.TableCell,{children:o[e.agent_id]?.has_key?(0,t.jsx)(f.Badge,{color:"green",children:"Active"}):(0,t.jsx)(f.Badge,{color:"yellow",children:"Needs Setup"})}),R&&(0,t.jsx)(h.TableCell,{children:(0,t.jsx)(eq.default,{variant:"Delete",onClick:()=>{A({id:e.agent_id,name:e.agent_name})}})})]},e.agent_id))})]})}),(0,t.jsx)(ew,{visible:c,onClose:()=>{S(!1)},accessToken:e,onSuccess:()=>{z()},teams:a}),L&&(0,t.jsxs)(_.Modal,{title:"Delete Agent",open:null!==L,onOk:q,onCancel:()=>{A(null)},confirmLoading:F,okText:"Delete",okButtonProps:{danger:!0},children:[(0,t.jsxs)("p",{children:["Are you sure you want to delete agent: ",L.name,"?"]}),(0,t.jsx)("p",{children:"This action cannot be undone."})]})]})};var eU=e.i(646050),eH=e.i(559061),eV=e.i(704308),eG=e.i(584578),eK=e.i(936578),eW=e.i(677667),eQ=e.i(898667),eY=e.i(130643),eJ=e.i(779241),eX=e.i(752978),eZ=e.i(68155),e0=e.i(591935);let e1=i.forwardRef(function(e,t){return i.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:t},e),i.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"}))});var e2=e.i(836991);function e4({data:e,columns:s,isLoading:a=!1,loadingMessage:l="Loading...",emptyMessage:r="No data",getRowKey:i}){return(0,t.jsxs)(x.Table,{children:[(0,t.jsx)(g.TableHead,{children:(0,t.jsx)(j.TableRow,{children:s.map((e,s)=>(0,t.jsx)(y.TableHeaderCell,{style:{width:e.width},children:e.header},s))})}),(0,t.jsx)(p.TableBody,{children:a?(0,t.jsx)(j.TableRow,{children:(0,t.jsx)(h.TableCell,{colSpan:s.length,className:"text-center",children:(0,t.jsx)(b.Text,{className:"text-gray-500",children:l})})}):e.length>0?e.map((e,a)=>(0,t.jsx)(j.TableRow,{children:s.map((s,a)=>(0,t.jsx)(h.TableCell,{children:s.cell?s.cell(e):String(e[s.accessor]??"")},a))},i?i(e,a):a)):(0,t.jsx)(j.TableRow,{children:(0,t.jsx)(h.TableCell,{colSpan:s.length,className:"text-center",children:(0,t.jsx)(b.Text,{className:"text-gray-500",children:r})})})})]})}var e5=e.i(916925);let e6=e=>{let t=Object.keys(e5.provider_map).find(t=>e5.provider_map[t]===e);if(t){let e=e5.Providers[t],s=e5.providerLogoMap[e];return{displayName:e,logo:s,enumKey:t}}return{displayName:e,logo:"",enumKey:null}},e3=e=>e5.provider_map[e]||null,e8=(e,t)=>{let s=e.target,a=s.parentElement;if(a){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),a.replaceChild(e,s)}},e7=({discountConfig:e,onDiscountChange:s,onRemoveProvider:a})=>{let[l,r]=(0,i.useState)(null),[n,o]=(0,i.useState)(""),d=e=>{let t=parseFloat(n);!isNaN(t)&&t>=0&&t<=100&&s(e,(t/100).toString()),r(null),o("")},c=()=>{r(null),o("")},m=Object.entries(e).map(([e,t])=>({provider:e,discount:t})).sort((e,t)=>{let s=e6(e.provider).displayName,a=e6(t.provider).displayName;return s.localeCompare(a)});return(0,t.jsx)(e4,{data:m,columns:[{header:"Provider",cell:e=>{let{displayName:s,logo:a}=e6(e.provider);return(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[a&&(0,t.jsx)("img",{src:a,alt:`${s} logo`,className:"w-5 h-5",onError:e=>e8(e,s)}),(0,t.jsx)("span",{className:"font-medium",children:s})]})}},{header:"Discount Percentage",cell:e=>(0,t.jsx)("div",{className:"flex items-center gap-2",children:l===e.provider?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(eJ.TextInput,{value:n,onValueChange:o,onKeyDown:t=>{var s;return s=e.provider,void("Enter"===t.key?d(s):"Escape"===t.key&&c())},placeholder:"5",className:"w-20",autoFocus:!0}),(0,t.jsx)("span",{className:"text-gray-600",children:"%"}),(0,t.jsx)(eX.Icon,{icon:e1,size:"sm",onClick:()=>d(e.provider),className:"cursor-pointer text-green-600 hover:text-green-700"}),(0,t.jsx)(eX.Icon,{icon:e2.XIcon,size:"sm",onClick:c,className:"cursor-pointer text-gray-600 hover:text-gray-700"})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(b.Text,{className:"font-medium",children:[(100*e.discount).toFixed(1),"%"]}),(0,t.jsx)(eX.Icon,{icon:e0.PencilAltIcon,size:"sm",onClick:()=>{var t,s;return t=e.provider,s=e.discount,void(r(t),o((100*s).toString()))},className:"cursor-pointer text-blue-600 hover:text-blue-700"})]})}),width:"250px"},{header:"Actions",cell:e=>{let{displayName:s}=e6(e.provider);return(0,t.jsx)(eX.Icon,{icon:eZ.TrashIcon,size:"sm",onClick:()=>a(e.provider,s),className:"cursor-pointer hover:text-red-600"})},width:"80px"}],getRowKey:e=>e.provider,emptyMessage:"No provider discounts configured"})},e9=({discountConfig:e,selectedProvider:s,newDiscount:a,onProviderChange:l,onDiscountChange:r,onAddProvider:i})=>(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Provider",(0,t.jsx)(N.Tooltip,{title:"Select the LLM provider you want to configure a discount for",children:(0,t.jsx)(B.InfoCircleOutlined,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),rules:[{required:!0,message:"Please select a provider"}],children:(0,t.jsx)(I.Select,{showSearch:!0,placeholder:"Select provider",value:s,onChange:l,style:{width:"100%"},size:"large",optionFilterProp:"children",filterOption:(e,t)=>String(t?.label??"").toLowerCase().includes(e.toLowerCase()),children:Object.entries(e5.Providers).map(([s,a])=>{let l=e5.provider_map[s];return l&&e[l]?null:(0,t.jsx)(I.Select.Option,{value:s,label:a,children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("img",{src:e5.providerLogoMap[a],alt:`${s} logo`,className:"w-5 h-5",onError:e=>e8(e,a)}),(0,t.jsx)("span",{children:a})]})},s)})})}),(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Discount Percentage",(0,t.jsx)(N.Tooltip,{title:"Enter a percentage value (e.g., 5 for 5% discount)",children:(0,t.jsx)(B.InfoCircleOutlined,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),rules:[{required:!0,message:"Please enter a discount percentage"}],children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(eJ.TextInput,{placeholder:"5",value:a,onValueChange:r,className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500 flex-1"}),(0,t.jsx)("span",{className:"text-gray-600",children:"%"})]})}),(0,t.jsx)("div",{className:"flex items-center justify-end space-x-3 pt-6 border-t border-gray-100",children:(0,t.jsx)(m.Button,{variant:"primary",onClick:i,disabled:!s||!a,children:"Add Provider Discount"})})]}),te=({marginConfig:e,onMarginChange:s,onRemoveProvider:a})=>{let[l,r]=(0,i.useState)(null),[n,o]=(0,i.useState)(""),[d,c]=(0,i.useState)(""),m=()=>{r(null),o(""),c("")},u=Object.entries(e).map(([e,t])=>({provider:e,margin:t})).sort((e,t)=>{if("global"===e.provider)return -1;if("global"===t.provider)return 1;let s=e6(e.provider).displayName,a=e6(t.provider).displayName;return s.localeCompare(a)});return(0,t.jsx)(e4,{data:u,columns:[{header:"Provider",cell:e=>{if("global"===e.provider)return(0,t.jsx)("div",{className:"flex items-center space-x-2",children:(0,t.jsx)("span",{className:"font-medium",children:"Global (All Providers)"})});let{displayName:s,logo:a}=e6(e.provider);return(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[a&&(0,t.jsx)("img",{src:a,alt:`${s} logo`,className:"w-5 h-5",onError:e=>e8(e,s)}),(0,t.jsx)("span",{className:"font-medium",children:s})]})}},{header:"Margin",cell:e=>(0,t.jsx)("div",{className:"flex items-center gap-2",children:l===e.provider?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(eJ.TextInput,{value:n,onValueChange:o,placeholder:"10",className:"w-20",autoFocus:!0}),(0,t.jsx)("span",{className:"text-gray-600",children:"%"}),(0,t.jsx)("span",{className:"text-gray-400",children:"+"}),(0,t.jsx)("span",{className:"text-gray-600",children:"$"}),(0,t.jsx)(eJ.TextInput,{value:d,onValueChange:c,placeholder:"0.001",className:"w-24"})]}),(0,t.jsx)(eX.Icon,{icon:e1,size:"sm",onClick:()=>{var t;let a,l;return t=e.provider,a=n?parseFloat(n):void 0,l=d?parseFloat(d):void 0,void(void 0!==a&&!isNaN(a)&&a>=0&&a<=1e3?void 0!==l&&!isNaN(l)&&l>=0?s(t,{percentage:a/100,fixed_amount:l}):s(t,a/100):void 0!==l&&!isNaN(l)&&l>=0&&s(t,{fixed_amount:l}),r(null),o(""),c(""))},className:"cursor-pointer text-green-600 hover:text-green-700"}),(0,t.jsx)(eX.Icon,{icon:e2.XIcon,size:"sm",onClick:m,className:"cursor-pointer text-gray-600 hover:text-gray-700"})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(b.Text,{className:"font-medium",children:(e=>{if("number"==typeof e)return`${(100*e).toFixed(1)}%`;let t=[];return void 0!==e.percentage&&t.push(`${(100*e.percentage).toFixed(1)}%`),void 0!==e.fixed_amount&&t.push(`$${e.fixed_amount.toFixed(6)}`),t.join(" + ")||"0%"})(e.margin)}),(0,t.jsx)(eX.Icon,{icon:e0.PencilAltIcon,size:"sm",onClick:()=>{var t,s;return t=e.provider,s=e.margin,void(r(t),"number"==typeof s?(o((100*s).toString()),c("")):(o(s.percentage?(100*s.percentage).toString():""),c(s.fixed_amount?s.fixed_amount.toString():"")))},className:"cursor-pointer text-blue-600 hover:text-blue-700"})]})}),width:"350px"},{header:"Actions",cell:e=>{let s="global"===e.provider?"Global":e6(e.provider).displayName;return(0,t.jsx)(eX.Icon,{icon:eZ.TrashIcon,size:"sm",onClick:()=>a(e.provider,s),className:"cursor-pointer hover:text-red-600"})},width:"80px"}],getRowKey:e=>e.provider,emptyMessage:"No provider margins configured"})},tt=({marginConfig:e,selectedProvider:s,marginType:a,percentageValue:l,fixedAmountValue:r,onProviderChange:i,onMarginTypeChange:n,onPercentageChange:o,onFixedAmountChange:d,onAddProvider:c})=>(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Provider",(0,t.jsx)(N.Tooltip,{title:"Select 'Global' to apply margin to all providers, or select a specific provider",children:(0,t.jsx)(B.InfoCircleOutlined,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),rules:[{required:!0,message:"Please select a provider"}],children:(0,t.jsxs)(I.Select,{showSearch:!0,placeholder:"Select provider or 'Global'",value:s,onChange:i,style:{width:"100%"},size:"large",optionFilterProp:"children",filterOption:(e,t)=>String(t?.label??"").toLowerCase().includes(e.toLowerCase()),children:[(0,t.jsx)(I.Select.Option,{value:"global",label:"Global (All Providers)",children:(0,t.jsx)("div",{className:"flex items-center space-x-2",children:(0,t.jsx)("span",{className:"font-medium",children:"Global (All Providers)"})})},"global"),Object.entries(e5.Providers).map(([s,a])=>{let l=e5.provider_map[s];return l&&e[l]?null:(0,t.jsx)(I.Select.Option,{value:s,label:a,children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("img",{src:e5.providerLogoMap[a],alt:`${s} logo`,className:"w-5 h-5",onError:e=>e8(e,a)}),(0,t.jsx)("span",{children:a})]})},s)})]})}),(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Margin Type",(0,t.jsx)(N.Tooltip,{title:"Choose how to apply the margin: percentage-based or fixed amount",children:(0,t.jsx)(B.InfoCircleOutlined,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),rules:[{required:!0,message:"Please select a margin type"}],children:(0,t.jsxs)(L.Radio.Group,{value:a,onChange:e=>n(e.target.value),className:"w-full",children:[(0,t.jsx)(L.Radio,{value:"percentage",children:"Percentage-based"}),(0,t.jsx)(L.Radio,{value:"fixed",children:"Fixed Amount"})]})}),"percentage"===a&&(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Margin Percentage",(0,t.jsx)(N.Tooltip,{title:"Enter a percentage value (e.g., 10 for 10% margin)",children:(0,t.jsx)(B.InfoCircleOutlined,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),rules:[{required:!0,message:"Please enter a margin percentage"},{validator:(e,t)=>{if(!t)return Promise.reject(Error("Please enter a margin percentage"));let s=parseFloat(t);return isNaN(s)||s<0||s>1e3?Promise.reject(Error("Percentage must be between 0 and 1000")):Promise.resolve()}}],children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(eJ.TextInput,{placeholder:"10",value:l,onValueChange:o,className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500 flex-1"}),(0,t.jsx)("span",{className:"text-gray-600",children:"%"})]})}),"fixed"===a&&(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Fixed Margin Amount",(0,t.jsx)(N.Tooltip,{title:"Enter a fixed amount in USD (e.g., 0.001 for $0.001 per request)",children:(0,t.jsx)(B.InfoCircleOutlined,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),rules:[{required:!0,message:"Please enter a fixed amount"},{validator:(e,t)=>{if(!t)return Promise.reject(Error("Please enter a fixed amount"));let s=parseFloat(t);return isNaN(s)||s<0?Promise.reject(Error("Fixed amount must be non-negative")):Promise.resolve()}}],children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:"text-gray-600",children:"$"}),(0,t.jsx)(eJ.TextInput,{placeholder:"0.001",value:r,onValueChange:d,className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500 flex-1"})]})}),(0,t.jsx)("div",{className:"flex items-center justify-end space-x-3 pt-6 border-t border-gray-100",children:(0,t.jsx)(m.Button,{variant:"primary",onClick:c,disabled:!s||"percentage"===a&&!l||"fixed"===a&&!r,children:"Add Provider Margin"})})]});var ts=e.i(291542),ta=e.i(955135),tl=e.i(175712);e.i(247167),e.i(62664);var tr=e.i(697539),ti=e.i(963188),tn=e.i(763731),to=e.i(343794),td=e.i(244009),tc=e.i(242064),tm=e.i(185793);let tu=e=>{let t,{value:s,formatter:a,precision:l,decimalSeparator:r,groupSeparator:n="",prefixCls:o}=e;if("function"==typeof a)t=a(s);else{let e=String(s),a=e.match(/^(-?)(\d*)(\.(\d+))?$/);if(a&&"-"!==e){let e=a[1],s=a[2]||"0",d=a[4]||"";s=s.replace(/\B(?=(\d{3})+(?!\d))/g,n),"number"==typeof l&&(d=d.padEnd(l,"0").slice(0,l>0?l:0)),d&&(d=`${r}${d}`),t=[i.createElement("span",{key:"int",className:`${o}-content-value-int`},e,s),d&&i.createElement("span",{key:"decimal",className:`${o}-content-value-decimal`},d)]}else t=e}return i.createElement("span",{className:`${o}-content-value`},t)};var tx=e.i(183293),tp=e.i(246422),th=e.i(838378);let tg=(0,tp.genStyleHooks)("Statistic",e=>(e=>{let{componentCls:t,marginXXS:s,padding:a,colorTextDescription:l,titleFontSize:r,colorTextHeading:i,contentFontSize:n,fontFamily:o}=e;return{[t]:Object.assign(Object.assign({},(0,tx.resetComponent)(e)),{[`${t}-title`]:{marginBottom:s,color:l,fontSize:r},[`${t}-skeleton`]:{paddingTop:a},[`${t}-content`]:{color:i,fontSize:n,fontFamily:o,[`${t}-content-value`]:{display:"inline-block",direction:"ltr"},[`${t}-content-prefix, ${t}-content-suffix`]:{display:"inline-block"},[`${t}-content-prefix`]:{marginInlineEnd:s},[`${t}-content-suffix`]:{marginInlineStart:s}}})}})((0,th.mergeToken)(e,{})),e=>{let{fontSizeHeading3:t,fontSize:s}=e;return{titleFontSize:s,contentFontSize:t}});var ty=function(e,t){var s={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(s[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var l=0,a=Object.getOwnPropertySymbols(e);lt.indexOf(a[l])&&Object.prototype.propertyIsEnumerable.call(e,a[l])&&(s[a[l]]=e[a[l]]);return s};let tj=i.forwardRef((e,t)=>{let{prefixCls:s,className:a,rootClassName:l,style:r,valueStyle:n,value:o=0,title:d,valueRender:c,prefix:m,suffix:u,loading:x=!1,formatter:p,precision:h,decimalSeparator:g=".",groupSeparator:y=",",onMouseEnter:j,onMouseLeave:f}=e,b=ty(e,["prefixCls","className","rootClassName","style","valueStyle","value","title","valueRender","prefix","suffix","loading","formatter","precision","decimalSeparator","groupSeparator","onMouseEnter","onMouseLeave"]),{getPrefixCls:_,direction:v,className:N,style:w}=(0,tc.useComponentConfig)("statistic"),k=_("statistic",s),[C,S,T]=tg(k),I=i.createElement(tu,{decimalSeparator:g,groupSeparator:y,prefixCls:k,formatter:p,precision:h,value:o}),F=(0,to.default)(k,{[`${k}-rtl`]:"rtl"===v},N,a,l,S,T),P=i.useRef(null);i.useImperativeHandle(t,()=>({nativeElement:P.current}));let L=(0,td.default)(b,{aria:!0,data:!0});return C(i.createElement("div",Object.assign({},L,{ref:P,className:F,style:Object.assign(Object.assign({},w),r),onMouseEnter:j,onMouseLeave:f}),d&&i.createElement("div",{className:`${k}-title`},d),i.createElement(tm.default,{paragraph:!1,loading:x,className:`${k}-skeleton`,active:!0},i.createElement("div",{style:n,className:`${k}-content`},m&&i.createElement("span",{className:`${k}-content-prefix`},m),c?c(I):I,u&&i.createElement("span",{className:`${k}-content-suffix`},u)))))}),tf=[["Y",31536e6],["M",2592e6],["D",864e5],["H",36e5],["m",6e4],["s",1e3],["S",1]];var tb=function(e,t){var s={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(s[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var l=0,a=Object.getOwnPropertySymbols(e);lt.indexOf(a[l])&&Object.prototype.propertyIsEnumerable.call(e,a[l])&&(s[a[l]]=e[a[l]]);return s};let t_=e=>{let{value:t,format:s="HH:mm:ss",onChange:a,onFinish:l,type:r}=e,n=tb(e,["value","format","onChange","onFinish","type"]),o="countdown"===r,[d,c]=i.useState(null),m=(0,tr.useEvent)(()=>{let e=Date.now(),s=new Date(t).getTime();return c({}),null==a||a(o?s-e:e-s),!o||!(s{let e,t=()=>{e=(0,ti.default)(()=>{m()&&t()})};return t(),()=>ti.default.cancel(e)},[t,o]),i.useEffect(()=>{c({})},[]),i.createElement(tj,Object.assign({},n,{value:t,valueRender:e=>(0,tn.cloneElement)(e,{title:void 0}),formatter:(e,t)=>d?function(e,t,s){let a,l,r,i,n,o,{format:d=""}=t,c=new Date(e).getTime(),m=Date.now();return a=s?Math.max(c-m,0):Math.max(m-c,0),l=/\[[^\]]*]/g,r=(d.match(l)||[]).map(e=>e.slice(1,-1)),i=d.replace(l,"[]"),n=tf.reduce((e,[t,s])=>{if(e.includes(t)){let l=Math.floor(a/s);return a-=l*s,e.replace(RegExp(`${t}+`,"g"),e=>{let t=e.length;return l.toString().padStart(t,"0")})}return e},i),o=0,n.replace(l,()=>{let e=r[o];return o+=1,e})}(e,Object.assign(Object.assign({},t),{format:s}),o):"-"}))},tv=i.memo(e=>i.createElement(t_,Object.assign({},e,{type:"countdown"})));tj.Timer=t_,tj.Countdown=tv;var tN=e.i(621192),tw=e.i(178654),tk=e.i(56456),tC=e.i(755151),tS=e.i(240647),tT=e.i(737434),tI=e.i(91500),tF=e.i(931067);let tP={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 42h216v494zM514.1 580.1l-61.8-102.4c-2.2-3.6-6.1-5.8-10.3-5.8h-38.4c-2.3 0-4.5.6-6.4 1.9-5.6 3.5-7.3 10.9-3.7 16.6l82.3 130.4-83.4 132.8a12.04 12.04 0 0010.2 18.4h34.5c4.2 0 8-2.2 10.2-5.7L510 664.8l62.3 101.4c2.2 3.6 6.1 5.7 10.2 5.7H620c2.3 0 4.5-.7 6.5-1.9 5.6-3.6 7.2-11 3.6-16.6l-84-130.4 85.3-132.5a12.04 12.04 0 00-10.1-18.5h-35.7c-4.2 0-8.1 2.2-10.3 5.8l-61.2 102.3z"}}]},name:"file-excel",theme:"outlined"};var tL=e.i(9583),tA=i.forwardRef(function(e,t){return i.createElement(tL.default,(0,tF.default)({},e,{ref:t,icon:tP}))});let tM=e=>null==e?"-":0===e?"$0.00":e<.01?`$${e.toFixed(6)}`:e<1?`$${e.toFixed(4)}`:`$${(0,eB.formatNumberWithCommas)(e,2)}`,tD=e=>null==e?"-":(0,eB.formatNumberWithCommas)(e,0),tE=({multiResult:e})=>{let[s,a]=(0,i.useState)(!1),l=(0,i.useRef)(null),r=e.entries.some(e=>null!==e.result);return((0,i.useEffect)(()=>{let e=e=>{l.current&&!l.current.contains(e.target)&&a(!1)};return s&&document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}},[s]),r)?(0,t.jsxs)("div",{className:"relative inline-block",ref:l,children:[(0,t.jsx)(m.Button,{size:"xs",variant:"secondary",icon:tT.DownloadOutlined,onClick:()=>a(!s),children:"Export"}),s&&(0,t.jsxs)("div",{className:"absolute right-0 mt-1 w-44 bg-white rounded-lg shadow-lg border border-gray-200 py-1 z-50",children:[(0,t.jsxs)("button",{className:"flex items-center w-full px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-colors",onClick:()=>{(e=>{let t=window.open("","_blank");if(!t)return alert("Please allow popups to export PDF");let s=e.entries.filter(e=>null!==e.result),a=s.length,l=` + + + + Multi-Model Cost Estimate Report + + + +

LLM Cost Estimate Report

+

${a} model${1!==a?"s":""} configured

+ +
+

Combined Totals

+
+
+
Total Per Request
+
${tM(e.totals.cost_per_request)}
+
+
+
Total Daily
+
${tM(e.totals.daily_cost)}
+
+
+
Total Monthly
+
${tM(e.totals.monthly_cost)}
+
+
+ ${e.totals.margin_per_request>0?` +
+
+
Margin/Request
+
${tM(e.totals.margin_per_request)}
+
+
+
Daily Margin
+
${tM(e.totals.daily_margin)}
+
+
+
Monthly Margin
+
${tM(e.totals.monthly_margin)}
+
+
+ `:""} +
+ +

Model Breakdown

+ ${s.map(e=>{let t;return t=e.result,` +
+

${t.model} ${t.provider?`(${t.provider})`:""}

+ +
+

Input Tokens per Request: ${tD(t.input_tokens)}

+

Output Tokens per Request: ${tD(t.output_tokens)}

+ ${t.num_requests_per_day?`

Requests per Day: ${tD(t.num_requests_per_day)}

`:""} + ${t.num_requests_per_month?`

Requests per Month: ${tD(t.num_requests_per_month)}

`:""} +
+ + + + + + ${null!==t.daily_cost?"":""} + ${null!==t.monthly_cost?"":""} + + + + + ${null!==t.daily_cost?``:""} + ${null!==t.monthly_cost?``:""} + + + + + ${null!==t.daily_cost?``:""} + ${null!==t.monthly_cost?``:""} + + + + + ${null!==t.daily_cost?``:""} + ${null!==t.monthly_cost?``:""} + + + + + ${null!==t.daily_cost?``:""} + ${null!==t.monthly_cost?``:""} + +
Cost TypePer RequestDailyMonthly
Input Cost${tM(t.input_cost_per_request)}${tM(t.daily_input_cost)}${tM(t.monthly_input_cost)}
Output Cost${tM(t.output_cost_per_request)}${tM(t.daily_output_cost)}${tM(t.monthly_output_cost)}
Margin/Fee${tM(t.margin_cost_per_request)}${tM(t.daily_margin_cost)}${tM(t.monthly_margin_cost)}
Total${tM(t.cost_per_request)}${tM(t.daily_cost)}${tM(t.monthly_cost)}
+
+ `}).join("")} + + + + + `;t.document.write(l),t.document.close(),t.onload=()=>{t.print()}})(e),a(!1)},children:[(0,t.jsx)(tI.FilePdfOutlined,{className:"mr-3 text-red-500"}),"Export as PDF"]}),(0,t.jsxs)("button",{className:"flex items-center w-full px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-colors",onClick:()=>{(e=>{let t=e.entries.filter(e=>null!==e.result),s=[["LLM Multi-Model Cost Estimate Report"],["Generated",new Date().toLocaleString()],[""]];for(let a of(s.push(["COMBINED TOTALS"],["Total Per Request",e.totals.cost_per_request.toString()],["Total Daily",e.totals.daily_cost?.toString()||"-"],["Total Monthly",e.totals.monthly_cost?.toString()||"-"],["Margin Per Request",e.totals.margin_per_request.toString()],["Daily Margin",e.totals.daily_margin?.toString()||"-"],["Monthly Margin",e.totals.monthly_margin?.toString()||"-"],[""]),s.push(["Model","Provider","Input Tokens","Output Tokens","Requests/Day","Requests/Month","Cost/Request","Daily Cost","Monthly Cost","Input Cost/Req","Output Cost/Req","Margin/Req"]),t)){let e=a.result;s.push([e.model,e.provider||"-",e.input_tokens.toString(),e.output_tokens.toString(),e.num_requests_per_day?.toString()||"-",e.num_requests_per_month?.toString()||"-",e.cost_per_request.toString(),e.daily_cost?.toString()||"-",e.monthly_cost?.toString()||"-",e.input_cost_per_request.toString(),e.output_cost_per_request.toString(),e.margin_cost_per_request.toString()])}let a=new Blob([s.map(e=>e.map(e=>`"${e}"`).join(",")).join("\n")],{type:"text/csv;charset=utf-8;"}),l=window.URL.createObjectURL(a),r=document.createElement("a");r.href=l,r.download=`cost_estimate_multi_model_${new Date().toISOString().split("T")[0]}.csv`,document.body.appendChild(r),r.click(),document.body.removeChild(r),window.URL.revokeObjectURL(l)})(e),a(!1)},children:[(0,t.jsx)(tA,{className:"mr-3 text-green-600"}),"Export as CSV"]})]})]}):null},tO=e=>null==e?"-":0===e?"$0":e<1e-4?`$${e.toExponential(2)}`:e<1?`$${e.toFixed(4)}`:`$${(0,eB.formatNumberWithCommas)(e,2,!0)}`,tR=({result:e,loading:s,timePeriod:a})=>{let l="day"===a?"Daily":"Monthly",r="day"===a?e.daily_cost:e.monthly_cost,i="day"===a?e.daily_input_cost:e.monthly_input_cost,n="day"===a?e.daily_output_cost:e.monthly_output_cost,o="day"===a?e.daily_margin_cost:e.monthly_margin_cost,d="day"===a?e.num_requests_per_day:e.num_requests_per_month;return(0,t.jsxs)("div",{className:"space-y-3 bg-gray-50 p-4 rounded-lg",children:[s&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-gray-500 text-sm",children:[(0,t.jsx)(eL.Spin,{indicator:(0,t.jsx)(tk.LoadingOutlined,{spin:!0}),size:"small"}),(0,t.jsx)("span",{children:"Updating..."})]}),(0,t.jsxs)("div",{className:"grid grid-cols-4 gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(b.Text,{className:"text-xs text-gray-500 block",children:"Total/Request"}),(0,t.jsx)(b.Text,{className:"text-base font-semibold text-blue-600",children:tO(e.cost_per_request)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(b.Text,{className:"text-xs text-gray-500 block",children:"Input Cost"}),(0,t.jsx)(b.Text,{className:"text-sm",children:tO(e.input_cost_per_request)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(b.Text,{className:"text-xs text-gray-500 block",children:"Output Cost"}),(0,t.jsx)(b.Text,{className:"text-sm",children:tO(e.output_cost_per_request)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(b.Text,{className:"text-xs text-gray-500 block",children:"Margin Fee"}),(0,t.jsx)(b.Text,{className:`text-sm ${e.margin_cost_per_request>0?"text-amber-600":""}`,children:tO(e.margin_cost_per_request)})]})]}),null!==r&&(0,t.jsxs)("div",{className:"grid grid-cols-4 gap-4 pt-2 border-t border-gray-200",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)(b.Text,{className:"text-xs text-gray-500 block",children:[l," Total (",null==d?"-":(0,eB.formatNumberWithCommas)(d,0,!0)," req)"]}),(0,t.jsx)(b.Text,{className:`text-base font-semibold ${"day"===a?"text-green-600":"text-purple-600"}`,children:tO(r)})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)(b.Text,{className:"text-xs text-gray-500 block",children:[l," Input"]}),(0,t.jsx)(b.Text,{className:"text-sm",children:tO(i)})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)(b.Text,{className:"text-xs text-gray-500 block",children:[l," Output"]}),(0,t.jsx)(b.Text,{className:"text-sm",children:tO(n)})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)(b.Text,{className:"text-xs text-gray-500 block",children:[l," Margin Fee"]}),(0,t.jsx)(b.Text,{className:`text-sm ${(o??0)>0?"text-amber-600":""}`,children:tO(o)})]})]}),(e.input_cost_per_token||e.output_cost_per_token)&&(0,t.jsxs)("div",{className:"text-xs text-gray-400 pt-2 border-t border-gray-200",children:["Token Pricing: "," ",e.input_cost_per_token&&(0,t.jsxs)("span",{children:["Input $",(0,eB.formatNumberWithCommas)(1e6*e.input_cost_per_token,2),"/1M"]}),e.input_cost_per_token&&e.output_cost_per_token&&" | ",e.output_cost_per_token&&(0,t.jsxs)("span",{children:["Output $",(0,eB.formatNumberWithCommas)(1e6*e.output_cost_per_token,2),"/1M"]})]})]})},tz=({multiResult:e,timePeriod:s})=>{let[a,l]=(0,i.useState)(new Set),r=e.entries.filter(e=>null!==e.result),n=e.entries.filter(e=>e.loading),o=e.entries.filter(e=>null!==e.error),d=r.length>0,c=n.length>0,u=o.length>0;if(!d&&!c&&!u)return(0,t.jsx)("div",{className:"py-6 text-center border border-dashed border-gray-300 rounded-lg bg-gray-50",children:(0,t.jsx)(b.Text,{className:"text-gray-500",children:"Select models above to see cost estimates"})});if(!d&&c&&!u)return(0,t.jsxs)("div",{className:"py-6 text-center",children:[(0,t.jsx)(eL.Spin,{indicator:(0,t.jsx)(tk.LoadingOutlined,{spin:!0})}),(0,t.jsx)(b.Text,{className:"text-gray-500 block mt-2",children:"Calculating costs..."})]});if(!d&&u)return(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)(M.Divider,{className:"my-4"}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)(b.Text,{className:"text-base font-semibold text-gray-900",children:"Cost Estimates"}),c&&(0,t.jsx)(eL.Spin,{indicator:(0,t.jsx)(tk.LoadingOutlined,{spin:!0}),size:"small"})]}),o.map(e=>(0,t.jsxs)("div",{className:"text-sm text-red-600 bg-red-50 p-3 rounded-lg border border-red-200",children:[(0,t.jsxs)("span",{className:"font-medium",children:[e.entry.model||"Unknown model",": "]}),e.error]},e.entry.id))]});let x=e.totals.margin_per_request>0,p="day"===s?"Daily":"Monthly",h=[{title:"Model",dataIndex:"model",key:"model",render:(e,s)=>(0,t.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:"font-medium text-sm",children:e}),s.provider&&(0,t.jsx)(A.Tag,{color:"blue",className:"text-xs",children:s.provider}),s.loading&&(0,t.jsx)(eL.Spin,{indicator:(0,t.jsx)(tk.LoadingOutlined,{spin:!0}),size:"small"})]}),s.error&&(0,t.jsxs)("div",{className:"text-xs text-red-600 bg-red-50 px-2 py-1 rounded",children:["⚠️ ",s.error]}),s.hasZeroCost&&!s.error&&(0,t.jsx)("div",{className:"text-xs text-amber-600 bg-amber-50 px-2 py-1 rounded",children:"⚠️ No pricing data found for this model. Set base_model in config."})]})},{title:"Per Request",dataIndex:"cost_per_request",key:"cost_per_request",align:"right",render:(e,s)=>s.error?(0,t.jsx)("span",{className:"text-gray-400",children:"-"}):(0,t.jsx)("span",{className:"font-mono text-sm",children:tO(e)})},{title:"Margin Fee",dataIndex:"margin_cost_per_request",key:"margin_cost_per_request",align:"right",render:(e,s)=>s.error?(0,t.jsx)("span",{className:"text-gray-400",children:"-"}):(0,t.jsx)("span",{className:`font-mono text-sm ${(e??0)>0?"text-amber-600":"text-gray-400"}`,children:tO(e)})},{title:p,dataIndex:"day"===s?"daily_cost":"monthly_cost",key:"period_cost",align:"right",render:(e,s)=>s.error?(0,t.jsx)("span",{className:"text-gray-400",children:"-"}):(0,t.jsx)("span",{className:"font-mono text-sm",children:tO(e)})},{title:"",key:"expand",width:40,render:(e,s)=>s.error?null:(0,t.jsx)(m.Button,{size:"xs",variant:"light",onClick:()=>{var e;return e=s.id,void l(t=>{let s=new Set(t);return s.has(e)?s.delete(e):s.add(e),s})},className:"text-gray-400 hover:text-gray-600",children:a.has(s.id)?(0,t.jsx)(tC.DownOutlined,{}):(0,t.jsx)(tS.RightOutlined,{})})}],g=e.entries.filter(e=>e.entry.model).map(e=>({key:e.entry.id,id:e.entry.id,model:e.result?.model||e.entry.model,provider:e.result?.provider,cost_per_request:e.result?.cost_per_request??null,margin_cost_per_request:e.result?.margin_cost_per_request??null,daily_cost:e.result?.daily_cost??null,monthly_cost:e.result?.monthly_cost??null,error:e.error,loading:e.loading,hasZeroCost:e.result&&0===e.result.cost_per_request}));return(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)(M.Divider,{className:"my-4"}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)(b.Text,{className:"text-base font-semibold text-gray-900",children:"Cost Estimates"}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[c&&(0,t.jsx)(eL.Spin,{indicator:(0,t.jsx)(tk.LoadingOutlined,{spin:!0}),size:"small"}),(0,t.jsx)(tE,{multiResult:e})]})]}),(0,t.jsxs)(tl.Card,{size:"small",className:"bg-gradient-to-r from-slate-50 to-blue-50 border-slate-200",children:[(0,t.jsxs)(tN.Row,{gutter:[16,8],children:[(0,t.jsx)(tw.Col,{xs:24,sm:12,children:(0,t.jsx)(tj,{title:(0,t.jsx)("span",{className:"text-xs",children:"Total Per Request"}),value:tO(e.totals.cost_per_request),valueStyle:{color:"#1890ff",fontSize:"18px",fontFamily:"monospace"}})}),(0,t.jsx)(tw.Col,{xs:24,sm:12,children:(0,t.jsx)(tj,{title:(0,t.jsxs)("span",{className:"text-xs",children:["Total ",p]}),value:tO("day"===s?e.totals.daily_cost:e.totals.monthly_cost),valueStyle:{color:"day"===s?"#52c41a":"#722ed1",fontSize:"18px",fontFamily:"monospace"}})})]}),x&&(0,t.jsxs)(tN.Row,{gutter:[16,8],className:"mt-3 pt-3 border-t border-slate-200",children:[(0,t.jsxs)(tw.Col,{xs:24,sm:12,children:[(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"Margin Fee/Request"}),(0,t.jsx)("div",{className:"text-sm font-mono text-amber-600",children:tO(e.totals.margin_per_request)})]}),(0,t.jsxs)(tw.Col,{xs:24,sm:12,children:[(0,t.jsxs)("div",{className:"text-xs text-gray-500",children:[p," Margin Fee"]}),(0,t.jsx)("div",{className:"text-sm font-mono text-amber-600",children:tO("day"===s?e.totals.daily_margin:e.totals.monthly_margin)})]})]})]}),g.length>0&&(0,t.jsx)(ts.Table,{columns:h,dataSource:g,pagination:!1,size:"small",className:"border border-gray-200 rounded-lg",expandable:{expandedRowKeys:Array.from(a),expandedRowRender:e=>{let a=r.find(t=>t.entry.id===e.id);return a?.result?(0,t.jsx)("div",{className:"py-2",children:(0,t.jsx)(tR,{result:a.result,loading:a.loading,timePeriod:s})}):null},showExpandColumn:!1}})]})},tB=()=>({id:`entry-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,model:"",input_tokens:1e3,output_tokens:500,num_requests_per_day:void 0,num_requests_per_month:void 0}),tq=({accessToken:e,models:s})=>{let[a,r]=(0,i.useState)([tB()]),[n,o]=(0,i.useState)("month"),{debouncedFetchForEntry:d,removeEntry:c,getMultiModelResult:m}=function(e){let[t,s]=(0,i.useState)(new Map),a=(0,i.useRef)(new Map),r=(0,i.useCallback)(async t=>{if(!e||!t.model)return void s(e=>{let s=new Map(e);return s.set(t.id,{entry:t,result:null,loading:!1,error:null}),s});s(e=>{let s=new Map(e),a=s.get(t.id);return s.set(t.id,{entry:t,result:a?.result??null,loading:!0,error:null}),s});try{let a=(0,l.getProxyBaseUrl)(),r=a?`${a}/cost/estimate`:"/cost/estimate",i={model:t.model,input_tokens:t.input_tokens||0,output_tokens:t.output_tokens||0,num_requests_per_day:t.num_requests_per_day||null,num_requests_per_month:t.num_requests_per_month||null},n=await fetch(r,{method:"POST",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i)});if(n.ok){let e=await n.json();s(s=>{let a=new Map(s);return a.set(t.id,{entry:t,result:e,loading:!1,error:null}),a})}else{let e=await n.json(),a=e.detail?.error||e.detail||"Failed to estimate cost";s(e=>{let s=new Map(e);return s.set(t.id,{entry:t,result:null,loading:!1,error:a}),s})}}catch(e){console.error("Error estimating cost:",e),s(e=>{let s=new Map(e);return s.set(t.id,{entry:t,result:null,loading:!1,error:"Network error"}),s})}},[e]),n=(0,i.useCallback)(e=>{let t=a.current.get(e.id);t&&clearTimeout(t);let s=setTimeout(()=>{r(e)},500);a.current.set(e.id,s)},[r]),o=(0,i.useCallback)(e=>{let t=a.current.get(e);t&&(clearTimeout(t),a.current.delete(e)),s(t=>{let s=new Map(t);return s.delete(e),s})},[]);return(0,i.useEffect)(()=>{let e=a.current;return()=>{e.forEach(e=>clearTimeout(e)),e.clear()}},[]),{debouncedFetchForEntry:n,removeEntry:o,getMultiModelResult:(0,i.useCallback)(e=>{let s=e.map(e=>{let s=t.get(e.id);return{entry:e,result:s?.result??null,loading:s?.loading??!1,error:s?.error??null}}),a=0,l=null,r=null,i=0,n=null,o=null;for(let e of s)e.result&&(a+=e.result.cost_per_request,i+=e.result.margin_cost_per_request,null!==e.result.daily_cost&&(l=(l??0)+e.result.daily_cost),null!==e.result.daily_margin_cost&&(n=(n??0)+e.result.daily_margin_cost),null!==e.result.monthly_cost&&(r=(r??0)+e.result.monthly_cost),null!==e.result.monthly_margin_cost&&(o=(o??0)+e.result.monthly_margin_cost));return{entries:s,totals:{cost_per_request:a,daily_cost:l,monthly_cost:r,margin_per_request:i,daily_margin:n,monthly_margin:o}}},[t])}}(e),u=(0,i.useCallback)((e,t,s)=>{r(a=>{let l=a.map(a=>a.id===e?{...a,[t]:s}:a),r=l.find(t=>t.id===e);return r&&r.model&&d(r),l})},[d]),x=(0,i.useCallback)(e=>{o(e),r(t=>t.map(t=>({...t,num_requests_per_day:"day"===e?t.num_requests_per_day:void 0,num_requests_per_month:"month"===e?t.num_requests_per_month:void 0})))},[]),p=(0,i.useCallback)(()=>{r(e=>[...e,tB()])},[]),h=(0,i.useCallback)(e=>{r(t=>t.filter(t=>t.id!==e)),c(e)},[c]),g=m(a),y=[{title:"Model",dataIndex:"model",key:"model",width:"35%",render:(e,a)=>(0,t.jsx)(I.Select,{showSearch:!0,placeholder:"Select a model",value:a.model||void 0,onChange:e=>u(a.id,"model",e),optionFilterProp:"label",filterOption:(e,t)=>String(t?.label??"").toLowerCase().includes(e.toLowerCase()),options:s.map(e=>({value:e,label:e})),style:{width:"100%"},size:"small"})},{title:"Input Tokens",dataIndex:"input_tokens",key:"input_tokens",width:"18%",render:(e,s)=>(0,t.jsx)(D.InputNumber,{min:0,value:s.input_tokens,onChange:e=>u(s.id,"input_tokens",e??0),style:{width:"100%"},size:"small",formatter:e=>`${e}`.replace(/\B(?=(\d{3})+(?!\d))/g,",")})},{title:"Output Tokens",dataIndex:"output_tokens",key:"output_tokens",width:"18%",render:(e,s)=>(0,t.jsx)(D.InputNumber,{min:0,value:s.output_tokens,onChange:e=>u(s.id,"output_tokens",e??0),style:{width:"100%"},size:"small",formatter:e=>`${e}`.replace(/\B(?=(\d{3})+(?!\d))/g,",")})},{title:`Requests/${"day"===n?"Day":"Month"}`,dataIndex:"day"===n?"num_requests_per_day":"num_requests_per_month",key:"num_requests",width:"20%",render:(e,s)=>(0,t.jsx)(D.InputNumber,{min:0,value:"day"===n?s.num_requests_per_day:s.num_requests_per_month,onChange:e=>u(s.id,"day"===n?"num_requests_per_day":"num_requests_per_month",e??void 0),style:{width:"100%"},size:"small",placeholder:"-",formatter:e=>e?`${e}`.replace(/\B(?=(\d{3})+(?!\d))/g,","):""})},{title:"",key:"actions",width:50,render:(e,s)=>(0,t.jsx)(G.Button,{type:"text",icon:(0,t.jsx)(ta.DeleteOutlined,{}),onClick:()=>h(s.id),disabled:1===a.length,danger:!0,size:"small"})}];return(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("div",{className:"flex items-center justify-end mb-2",children:(0,t.jsxs)(L.Radio.Group,{value:n,onChange:e=>x(e.target.value),size:"small",optionType:"button",buttonStyle:"solid",children:[(0,t.jsx)(L.Radio.Button,{value:"day",children:"Per Day"}),(0,t.jsx)(L.Radio.Button,{value:"month",children:"Per Month"})]})}),(0,t.jsx)(ts.Table,{columns:y,dataSource:a,rowKey:"id",pagination:!1,size:"small",footer:()=>(0,t.jsx)(G.Button,{type:"dashed",onClick:p,icon:(0,t.jsx)(K.PlusOutlined,{}),className:"w-full",children:"Add Another Model"})}),(0,t.jsx)(tz,{multiResult:g,timePeriod:n})]})};var t$=e.i(270377),tU=e.i(778917),tH=e.i(664659);let tV=({items:e,children:s="Docs",className:a=""})=>{let[l,r]=(0,i.useState)(!1),n=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=e=>{n.current&&!n.current.contains(e.target)&&r(!1)};return l&&document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}},[l]),(0,t.jsxs)("div",{className:`relative inline-block ${a}`,ref:n,children:[(0,t.jsxs)("button",{type:"button",onClick:()=>r(!l),className:"inline-flex items-center gap-1 text-gray-500 hover:text-gray-700 text-xs transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1 rounded px-2 py-1","aria-expanded":l,"aria-haspopup":"true",children:[(0,t.jsx)("span",{children:s}),(0,t.jsx)(tH.ChevronDown,{className:`h-3 w-3 transition-transform ${l?"rotate-180":""}`,"aria-hidden":"true"})]}),l&&(0,t.jsx)("div",{className:"absolute right-0 mt-1 w-56 bg-white rounded-lg shadow-lg border border-gray-200 py-1 z-50",children:e.map((e,s)=>(0,t.jsxs)("a",{href:e.href,target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-between px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-colors",onClick:()=>r(!1),children:[(0,t.jsx)("span",{children:e.label}),(0,t.jsx)(tU.ExternalLink,{className:"h-3.5 w-3.5 text-gray-400 flex-shrink-0 ml-2","aria-hidden":"true"})]},s))})]})};var tG=e.i(673709);let tK=()=>{let[e,s]=(0,i.useState)(""),[a,l]=(0,i.useState)(""),r=(0,i.useMemo)(()=>{let t=parseFloat(e),s=parseFloat(a);if(isNaN(t)||isNaN(s)||0===t||0===s)return null;let l=t+s,r=s/l*100;return{originalCost:l.toFixed(10),finalCost:t.toFixed(10),discountAmount:s.toFixed(10),discountPercentage:r.toFixed(2)}},[e,a]);return(0,t.jsxs)("div",{className:"space-y-4 pt-2",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(b.Text,{className:"font-medium text-gray-900 text-sm mb-1",children:"Cost Calculation"}),(0,t.jsxs)(b.Text,{className:"text-xs text-gray-600",children:["Discounts are applied to provider costs: ",(0,t.jsx)("code",{className:"bg-gray-100 px-1.5 py-0.5 rounded text-xs",children:"final_cost = base_cost × (1 - discount%/100)"})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(b.Text,{className:"font-medium text-gray-900 text-sm mb-1",children:"Example"}),(0,t.jsx)(b.Text,{className:"text-xs text-gray-600",children:"A 5% discount on a $10.00 request results in: $10.00 × (1 - 0.05) = $9.50"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(b.Text,{className:"font-medium text-gray-900 text-sm mb-1",children:"Valid Range"}),(0,t.jsx)(b.Text,{className:"text-xs text-gray-600",children:"Discount percentages must be between 0% and 100%"})]}),(0,t.jsxs)("div",{className:"pt-4 border-t border-gray-200",children:[(0,t.jsx)(b.Text,{className:"font-medium text-gray-900 text-sm mb-2",children:"Validating Discounts"}),(0,t.jsx)(b.Text,{className:"text-xs text-gray-600 mb-3",children:"Make a test request and check the response headers to verify discounts are applied:"}),(0,t.jsx)(tG.default,{language:"bash",code:`curl -X POST -i http://your-proxy:4000/chat/completions \\ + -H "Content-Type: application/json" \\ + -H "Authorization: Bearer sk-1234" \\ + -d '{ + "model": "gemini/gemini-2.5-pro", + "messages": [{"role": "user", "content": "Hello"}] + }'`}),(0,t.jsx)(b.Text,{className:"text-xs text-gray-600 mt-3 mb-2",children:"Look for these headers in the response:"}),(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)("code",{className:"bg-gray-100 px-2 py-1 rounded text-xs font-mono text-gray-800 whitespace-nowrap",children:"x-litellm-response-cost"}),(0,t.jsx)(b.Text,{className:"text-xs text-gray-600",children:"Final cost after discount"})]}),(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)("code",{className:"bg-gray-100 px-2 py-1 rounded text-xs font-mono text-gray-800 whitespace-nowrap",children:"x-litellm-response-cost-original"}),(0,t.jsx)(b.Text,{className:"text-xs text-gray-600",children:"Original cost before discount"})]}),(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)("code",{className:"bg-gray-100 px-2 py-1 rounded text-xs font-mono text-gray-800 whitespace-nowrap",children:"x-litellm-response-cost-discount-amount"}),(0,t.jsx)(b.Text,{className:"text-xs text-gray-600",children:"Amount discounted"})]})]})]}),(0,t.jsxs)("div",{className:"pt-4 border-t border-gray-200",children:[(0,t.jsx)(b.Text,{className:"font-medium text-gray-900 text-sm mb-3",children:"Discount Calculator"}),(0,t.jsx)(b.Text,{className:"text-xs text-gray-600 mb-3",children:"Enter values from your response headers to verify the discount:"}),(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mb-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-xs font-medium text-gray-700 mb-1",children:"Response Cost (x-litellm-response-cost)"}),(0,t.jsx)(eJ.TextInput,{placeholder:"0.0171938125",value:e,onValueChange:s,className:"text-sm"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-xs font-medium text-gray-700 mb-1",children:"Discount Amount (x-litellm-response-cost-discount-amount)"}),(0,t.jsx)(eJ.TextInput,{placeholder:"0.0009049375",value:a,onValueChange:l,className:"text-sm"})]})]}),r&&(0,t.jsxs)("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4",children:[(0,t.jsx)(b.Text,{className:"text-sm font-medium text-blue-900 mb-2",children:"Calculated Results"}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)(b.Text,{className:"text-xs text-blue-800",children:"Original Cost:"}),(0,t.jsxs)("code",{className:"text-xs font-mono text-blue-900",children:["$",r.originalCost]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)(b.Text,{className:"text-xs text-blue-800",children:"Final Cost:"}),(0,t.jsxs)("code",{className:"text-xs font-mono text-blue-900",children:["$",r.finalCost]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)(b.Text,{className:"text-xs text-blue-800",children:"Discount Amount:"}),(0,t.jsxs)("code",{className:"text-xs font-mono text-blue-900",children:["$",r.discountAmount]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between pt-2 border-t border-blue-300",children:[(0,t.jsx)(b.Text,{className:"text-xs font-semibold text-blue-900",children:"Discount Applied:"}),(0,t.jsxs)(b.Text,{className:"text-sm font-bold text-blue-900",children:[r.discountPercentage,"%"]})]})]})]})]})]})};var tW=e.i(689020);let tQ=[{label:"Custom pricing for models",href:"https://docs.litellm.ai/docs/proxy/custom_pricing"},{label:"Spend tracking",href:"https://docs.litellm.ai/docs/proxy/cost_tracking"}],tY=({userID:e,userRole:s,accessToken:a})=>{let[r,n]=(0,i.useState)(void 0),[o,d]=(0,i.useState)(""),[c,u]=(0,i.useState)(!0),[x,p]=(0,i.useState)(!1),[h,g]=(0,i.useState)(!1),[y,j]=(0,i.useState)(void 0),[f,v]=(0,i.useState)("percentage"),[N,w]=(0,i.useState)(""),[k,C]=(0,i.useState)(""),[T,I]=(0,i.useState)([]),[F]=S.Form.useForm(),[P]=S.Form.useForm(),[L,A]=_.Modal.useModal(),M="proxy_admin"===s||"Admin"===s,{discountConfig:D,fetchDiscountConfig:E,handleAddProvider:O,handleRemoveProvider:R,handleDiscountChange:z}=function({accessToken:e}){let[t,s]=(0,i.useState)({}),a=(0,i.useCallback)(async()=>{try{let t=(0,l.getProxyBaseUrl)(),a=t?`${t}/config/cost_discount_config`:"/config/cost_discount_config",r=await fetch(a,{method:"GET",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(r.ok){let e=await r.json();s(e.values||{})}else console.error("Failed to fetch discount config")}catch(e){console.error("Error fetching discount config:",e),ez.default.fromBackend("Failed to fetch discount configuration")}},[e]),r=(0,i.useCallback)(async t=>{try{let s=(0,l.getProxyBaseUrl)(),r=s?`${s}/config/cost_discount_config`:"/config/cost_discount_config",i=await fetch(r,{method:"PATCH",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(i.ok)ez.default.success("Discount configuration updated successfully"),await a();else{let e=await i.json(),t=e.detail?.error||e.detail||"Failed to update settings";ez.default.fromBackend(t)}}catch(e){console.error("Error updating discount config:",e),ez.default.fromBackend("Failed to update discount configuration")}},[e,a]),n=(0,i.useCallback)(async(e,a)=>{if(!e||!a)return ez.default.fromBackend("Please select a provider and enter discount percentage"),!1;let l=parseFloat(a);if(isNaN(l)||l<0||l>100)return ez.default.fromBackend("Discount must be between 0% and 100%"),!1;let i=e3(e);if(!i)return ez.default.fromBackend("Invalid provider selected"),!1;if(t[i])return ez.default.fromBackend(`Discount for ${e5.Providers[e]} already exists. Edit it in the table above.`),!1;let n={...t,[i]:l/100};return s(n),await r(n),!0},[t,r]),o=(0,i.useCallback)(async e=>{let a={...t};delete a[e],s(a),await r(a)},[t,r]),d=(0,i.useCallback)(async(e,a)=>{let l=parseFloat(a);if(!isNaN(l)&&l>=0&&l<=1){let a={...t,[e]:l};s(a),await r(a)}},[t,r]);return{discountConfig:t,setDiscountConfig:s,fetchDiscountConfig:a,saveDiscountConfig:r,handleAddProvider:n,handleRemoveProvider:o,handleDiscountChange:d}}({accessToken:a}),{marginConfig:B,fetchMarginConfig:q,handleAddMargin:$,handleRemoveMargin:U,handleMarginChange:H}=function({accessToken:e}){let[t,s]=(0,i.useState)({}),a=(0,i.useCallback)(async()=>{try{let t=(0,l.getProxyBaseUrl)(),a=t?`${t}/config/cost_margin_config`:"/config/cost_margin_config",r=await fetch(a,{method:"GET",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(r.ok){let e=await r.json();s(e.values||{})}else console.error("Failed to fetch margin config")}catch(e){console.error("Error fetching margin config:",e),ez.default.fromBackend("Failed to fetch margin configuration")}},[e]),r=(0,i.useCallback)(async t=>{try{let s=(0,l.getProxyBaseUrl)(),r=s?`${s}/config/cost_margin_config`:"/config/cost_margin_config",i=await fetch(r,{method:"PATCH",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(i.ok)ez.default.success("Margin configuration updated successfully"),await a();else{let e=await i.json(),t=e.detail?.error||e.detail||"Failed to update settings";ez.default.fromBackend(t)}}catch(e){console.error("Error updating margin config:",e),ez.default.fromBackend("Failed to update margin configuration")}},[e,a]),n=(0,i.useCallback)(async e=>{let a,l,{selectedProvider:i,marginType:n,percentageValue:o,fixedAmountValue:d}=e;if(!i)return ez.default.fromBackend("Please select a provider"),!1;if("global"===i)a="global";else{let e=e3(i);if(!e)return ez.default.fromBackend("Invalid provider selected"),!1;a=e}if(t[a]){let e="global"===a?"Global":e5.Providers[i];return ez.default.fromBackend(`Margin for ${e} already exists. Edit it in the table above.`),!1}if("percentage"===n){let e=parseFloat(o);if(isNaN(e)||e<0||e>1e3)return ez.default.fromBackend("Percentage must be between 0% and 1000%"),!1;l=e/100}else{let e=parseFloat(d);if(isNaN(e)||e<0)return ez.default.fromBackend("Fixed amount must be non-negative"),!1;l={fixed_amount:e}}let c={...t,[a]:l};return s(c),await r(c),!0},[t,r]),o=(0,i.useCallback)(async e=>{let a={...t};delete a[e],s(a),await r(a)},[t,r]),d=(0,i.useCallback)(async(e,a)=>{let l={...t,[e]:a};s(l),await r(l)},[t,r]);return{marginConfig:t,setMarginConfig:s,fetchMarginConfig:a,saveMarginConfig:r,handleAddMargin:n,handleRemoveMargin:o,handleMarginChange:d}}({accessToken:a});(0,i.useEffect)(()=>{a&&(Promise.all([E(),q()]).finally(()=>{u(!1)}),(async()=>{try{let e=await (0,tW.fetchAvailableModels)(a);I(e.map(e=>e.model_group))}catch(e){console.error("Error fetching models:",e)}})())},[a,E,q]);let V=async()=>{await O(r,o)&&(n(void 0),d(""),p(!1))},G=async(e,s)=>{L.confirm({title:"Remove Provider Discount",icon:(0,t.jsx)(t$.ExclamationCircleOutlined,{}),content:`Are you sure you want to remove the discount for ${s}?`,okText:"Remove",okType:"danger",cancelText:"Cancel",onOk:()=>R(e)})},K=async()=>{await $({selectedProvider:y,marginType:f,percentageValue:N,fixedAmountValue:k})&&(j(void 0),w(""),C(""),v("percentage"),g(!1))},W=async(e,s)=>{L.confirm({title:"Remove Provider Margin",icon:(0,t.jsx)(t$.ExclamationCircleOutlined,{}),content:`Are you sure you want to remove the margin for ${s}?`,okText:"Remove",okType:"danger",cancelText:"Cancel",onOk:()=>U(e)})};return a?(0,t.jsxs)("div",{className:"w-full p-8",children:[A,(0,t.jsx)("div",{className:"flex flex-col md:flex-row items-start md:items-center justify-between mb-6",children:(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(eC.Title,{children:"Cost Tracking Settings"}),(0,t.jsx)(tV,{items:tQ})]}),(0,t.jsx)(b.Text,{className:"text-gray-500 mt-1",children:"Configure cost discounts and margins for different LLM providers. Changes are saved automatically."})]})}),(0,t.jsxs)("div",{className:"bg-white rounded-lg shadow w-full max-w-full space-y-4",children:[M&&(0,t.jsxs)(eW.Accordion,{children:[(0,t.jsx)(eQ.AccordionHeader,{className:"px-6 py-4",children:(0,t.jsxs)("div",{className:"flex flex-col items-start w-full",children:[(0,t.jsx)(b.Text,{className:"text-lg font-semibold text-gray-900",children:"Provider Discounts"}),(0,t.jsx)(b.Text,{className:"text-sm text-gray-500 mt-1",children:"Apply percentage-based discounts to reduce costs for specific providers"})]})}),(0,t.jsx)(eY.AccordionBody,{className:"px-0",children:(0,t.jsxs)(eT.TabGroup,{children:[(0,t.jsxs)(eI.TabList,{className:"px-6 pt-4",children:[(0,t.jsx)(eS.Tab,{children:"Discounts"}),(0,t.jsx)(eS.Tab,{children:"Test It"})]}),(0,t.jsxs)(eP.TabPanels,{children:[(0,t.jsx)(eF.TabPanel,{children:(0,t.jsxs)("div",{className:"p-6",children:[(0,t.jsx)("div",{className:"flex justify-end mb-4",children:(0,t.jsx)(m.Button,{onClick:()=>p(!0),children:"+ Add Provider Discount"})}),c?(0,t.jsx)("div",{className:"py-12 text-center",children:(0,t.jsx)(b.Text,{className:"text-gray-500",children:"Loading configuration..."})}):Object.keys(D).length>0?(0,t.jsx)(e7,{discountConfig:D,onDiscountChange:z,onRemoveProvider:G}):(0,t.jsxs)("div",{className:"py-16 px-6 text-center",children:[(0,t.jsx)("svg",{className:"mx-auto h-12 w-12 text-gray-400 mb-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,t.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),(0,t.jsx)(b.Text,{className:"text-gray-700 font-medium mb-2",children:"No provider discounts configured"}),(0,t.jsx)(b.Text,{className:"text-gray-500 text-sm",children:'Click "Add Provider Discount" to get started'})]})]})}),(0,t.jsx)(eF.TabPanel,{children:(0,t.jsx)("div",{className:"px-6 pb-4",children:(0,t.jsx)(tK,{})})})]})]})})]}),M&&(0,t.jsxs)(eW.Accordion,{children:[(0,t.jsx)(eQ.AccordionHeader,{className:"px-6 py-4",children:(0,t.jsxs)("div",{className:"flex flex-col items-start w-full",children:[(0,t.jsx)(b.Text,{className:"text-lg font-semibold text-gray-900",children:"Fee/Price Margin"}),(0,t.jsx)(b.Text,{className:"text-sm text-gray-500 mt-1",children:"Add fees or margins to LLM costs for internal billing and cost recovery"})]})}),(0,t.jsx)(eY.AccordionBody,{className:"px-0",children:(0,t.jsxs)("div",{className:"p-6",children:[(0,t.jsx)("div",{className:"flex justify-end mb-4",children:(0,t.jsx)(m.Button,{onClick:()=>g(!0),children:"+ Add Provider Margin"})}),c?(0,t.jsx)("div",{className:"py-12 text-center",children:(0,t.jsx)(b.Text,{className:"text-gray-500",children:"Loading configuration..."})}):Object.keys(B).length>0?(0,t.jsx)(te,{marginConfig:B,onMarginChange:H,onRemoveProvider:W}):(0,t.jsxs)("div",{className:"py-16 px-6 text-center",children:[(0,t.jsx)("svg",{className:"mx-auto h-12 w-12 text-gray-400 mb-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,t.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),(0,t.jsx)(b.Text,{className:"text-gray-700 font-medium mb-2",children:"No provider margins configured"}),(0,t.jsx)(b.Text,{className:"text-gray-500 text-sm",children:'Click "Add Provider Margin" to get started'})]})]})})]}),(0,t.jsxs)(eW.Accordion,{defaultOpen:!0,children:[(0,t.jsx)(eQ.AccordionHeader,{className:"px-6 py-4",children:(0,t.jsxs)("div",{className:"flex flex-col items-start w-full",children:[(0,t.jsx)(b.Text,{className:"text-lg font-semibold text-gray-900",children:"Pricing Calculator"}),(0,t.jsx)(b.Text,{className:"text-sm text-gray-500 mt-1",children:"Estimate LLM costs based on expected token usage and request volume"})]})}),(0,t.jsx)(eY.AccordionBody,{className:"px-0",children:(0,t.jsx)("div",{className:"p-6",children:(0,t.jsx)(tq,{accessToken:a,models:T})})})]})]}),(0,t.jsx)(_.Modal,{title:(0,t.jsx)("div",{className:"flex items-center space-x-3 pb-4 border-b border-gray-100",children:(0,t.jsx)("h2",{className:"text-xl font-semibold text-gray-900",children:"Add Provider Discount"})}),open:x,width:1e3,onCancel:()=>{p(!1),F.resetFields(),n(void 0),d("")},footer:null,className:"top-8",styles:{body:{padding:"24px"},header:{padding:"24px 24px 0 24px",border:"none"}},children:(0,t.jsxs)("div",{className:"mt-6",children:[(0,t.jsx)(b.Text,{className:"text-sm text-gray-600 mb-6",children:"Select a provider and set its discount percentage. Enter a value between 0% and 100% (e.g., 5 for a 5% discount)."}),(0,t.jsx)(S.Form,{form:F,onFinish:()=>{V()},layout:"vertical",className:"space-y-6",children:(0,t.jsx)(e9,{discountConfig:D,selectedProvider:r,newDiscount:o,onProviderChange:n,onDiscountChange:d,onAddProvider:V})})]})}),(0,t.jsx)(_.Modal,{title:(0,t.jsx)("div",{className:"flex items-center space-x-3 pb-4 border-b border-gray-100",children:(0,t.jsx)("h2",{className:"text-xl font-semibold text-gray-900",children:"Add Provider Margin"})}),open:h,width:1e3,onCancel:()=>{g(!1),P.resetFields(),j(void 0),w(""),C(""),v("percentage")},footer:null,className:"top-8",styles:{body:{padding:"24px"},header:{padding:"24px 24px 0 24px",border:"none"}},children:(0,t.jsxs)("div",{className:"mt-6",children:[(0,t.jsx)(b.Text,{className:"text-sm text-gray-600 mb-6",children:'Select a provider (or "Global" for all providers) and configure the margin. You can use percentage-based or fixed amount.'}),(0,t.jsx)(S.Form,{form:P,layout:"vertical",className:"space-y-6",children:(0,t.jsx)(tt,{marginConfig:B,selectedProvider:y,marginType:f,percentageValue:N,fixedAmountValue:k,onProviderChange:j,onMarginTypeChange:v,onPercentageChange:w,onFixedAmountChange:C,onAddProvider:K})})]})})]}):null};var tJ=e.i(226898),tX=e.i(973706),tZ=e.i(447566),t0=e.i(602073),t1=e.i(313603),t2=e.i(285027),t4=e.i(266027),t5=e.i(309426),t6=e.i(350967),t3=e.i(653496),t8=e.i(149192),t7=e.i(788191);let t9=`Evaluate whether this guardrail's decision was correct. +Analyze the user input, the guardrail action taken, and determine if it was appropriate. + +Consider: +— Was the user's intent genuinely harmful or policy-violating? +— Was the guardrail's action (block / flag / pass) appropriate? +— Could this be a false positive or false negative? + +Return a structured verdict with confidence and justification.`,se=`{ + "verdict": "correct" | "false_positive" | "false_negative", + "confidence": 0.0, + "justification": "string", + "risk_category": "string", + "suggested_action": "keep" | "adjust threshold" | "add allowlist" +} +`;function st({open:e,onClose:s,guardrailName:a,accessToken:l,onRunEvaluation:r}){let[n,o]=(0,i.useState)(t9),[d,c]=(0,i.useState)(se),[m,u]=(0,i.useState)(null),[x,p]=(0,i.useState)([]),[h,g]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(!e||!l)return void p([]);let t=!1;return g(!0),(0,tW.fetchAvailableModels)(l).then(e=>{t||p(e)}).catch(()=>{t||p([])}).finally(()=>{t||g(!1)}),()=>{t=!0}},[e,l]);let y=x.map(e=>({value:e.model_group,label:e.model_group}));return(0,t.jsxs)(_.Modal,{title:"Evaluation Settings",open:e,onCancel:s,width:640,footer:null,closeIcon:(0,t.jsx)(t8.CloseOutlined,{}),destroyOnClose:!0,children:[(0,t.jsx)("p",{className:"text-sm text-gray-500 mb-4",children:a?`Configure AI evaluation for ${a}`:"Configure AI evaluation for re-running on logs"}),(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-1.5",children:[(0,t.jsx)("label",{className:"text-sm font-medium text-gray-700",children:"Evaluation Prompt"}),(0,t.jsx)("button",{type:"button",onClick:()=>o(t9),className:"text-xs text-indigo-600 hover:text-indigo-700",children:"Reset to default"})]}),(0,t.jsx)(F.Input.TextArea,{value:n,onChange:e=>o(e.target.value),rows:6,className:"font-mono text-sm"}),(0,t.jsx)("p",{className:"text-xs text-gray-400 mt-1",children:"System prompt sent to the evaluation model. Output is structured via response_format."})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1.5",children:"Response Schema"}),(0,t.jsx)("p",{className:"text-xs text-gray-400 mb-1",children:"response_format: json_schema"}),(0,t.jsx)(F.Input.TextArea,{value:d,onChange:e=>c(e.target.value),rows:6,className:"font-mono text-sm"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1.5",children:"Model"}),(0,t.jsx)(I.Select,{placeholder:h?"Loading models…":"Select a model",value:m??void 0,onChange:u,options:y,style:{width:"100%"},showSearch:!0,optionFilterProp:"label",loading:h,notFoundContent:l?"No models available":"Sign in to see models"})]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-end gap-2 mt-6 pt-4 border-t border-gray-100",children:[(0,t.jsx)(G.Button,{onClick:s,children:"Cancel"}),(0,t.jsx)(G.Button,{type:"primary",icon:(0,t.jsx)(t7.PlayCircleOutlined,{}),onClick:()=>{m&&(r?.({prompt:n,schema:d,model:m}),s())},disabled:!m,children:"Run Evaluation"})]})]})}var ss=e.i(166540);e.i(3565);var sa=e.i(502626);let sl={blocked:{icon:t8.CloseOutlined,color:"text-red-600",bg:"bg-red-50",border:"border-red-200",label:"Blocked"},passed:{icon:C.CheckCircleOutlined,color:"text-green-600",bg:"bg-green-50",border:"border-green-200",label:"Passed"},flagged:{icon:t2.WarningOutlined,color:"text-amber-600",bg:"bg-amber-50",border:"border-amber-200",label:"Flagged"}};function sr({guardrailName:e,filterAction:s="all",logs:a=[],logsLoading:r=!1,totalLogs:n,accessToken:o=null,startDate:d="",endDate:c=""}){let[m,u]=(0,i.useState)(10),[x,p]=(0,i.useState)(s),[h,g]=(0,i.useState)(null),[y,j]=(0,i.useState)(!1),f=a.filter(e=>"all"===x||e.action===x).slice(0,m),b=n??a.length,_=d?(0,ss.default)(d).utc().format("YYYY-MM-DD HH:mm:ss"):(0,ss.default)().subtract(24,"hours").utc().format("YYYY-MM-DD HH:mm:ss"),v=c?(0,ss.default)(c).utc().endOf("day").format("YYYY-MM-DD HH:mm:ss"):(0,ss.default)().utc().format("YYYY-MM-DD HH:mm:ss"),{data:N}=(0,t4.useQuery)({queryKey:["spend-log-by-request",h,_,v],queryFn:async()=>o&&h?await (0,l.uiSpendLogsCall)({accessToken:o,start_date:_,end_date:v,page:1,page_size:10,params:{request_id:h}}):null,enabled:!!(o&&h&&y)}),w=N?.data?.[0]??null;return(0,t.jsxs)("div",{className:"bg-white border border-gray-200 rounded-lg",children:[(0,t.jsx)("div",{className:"p-4 border-b border-gray-200",children:(0,t.jsxs)("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h3",{className:"text-base font-semibold text-gray-900",children:e?`Logs — ${e}`:"Request Logs"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:r?"Loading…":a.length>0?`Showing ${f.length} of ${b} entries`:"No logs for this period. Select a guardrail and date range."})]}),a.length>0&&(0,t.jsxs)("div",{className:"flex items-center gap-4",children:[(0,t.jsx)("div",{className:"flex items-center gap-1",children:["all","blocked","flagged","passed"].map(e=>(0,t.jsx)(G.Button,{type:x===e?"primary":"default",size:"small",onClick:()=>p(e),children:e.charAt(0).toUpperCase()+e.slice(1)},e))}),(0,t.jsx)("div",{className:"h-4 w-px bg-gray-200"}),(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,t.jsx)("span",{className:"text-xs text-gray-500 mr-1",children:"Sample:"}),[10,50,100].map(e=>(0,t.jsx)(G.Button,{type:m===e?"primary":"default",size:"small",onClick:()=>u(e),children:e},e))]})]})]})}),r&&(0,t.jsx)("div",{className:"flex items-center justify-center py-12",children:(0,t.jsx)(eL.Spin,{})}),!r&&0===f.length&&(0,t.jsx)("div",{className:"py-12 text-center text-sm text-gray-500",children:"No logs to display. Adjust filters or date range."}),!r&&f.length>0&&(0,t.jsx)("div",{className:"divide-y divide-gray-100",children:f.map(e=>{let s=sl[e.action],a=s.icon;return(0,t.jsxs)("button",{type:"button",onClick:()=>{g(e.id),j(!0)},className:"w-full text-left px-4 py-3 hover:bg-gray-50 transition-colors flex items-start gap-3",children:[(0,t.jsx)(a,{className:`w-4 h-4 mt-0.5 flex-shrink-0 ${s.color}`}),(0,t.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[(0,t.jsx)("span",{className:`inline-flex items-center px-2 py-0.5 text-xs font-medium rounded border ${s.bg} ${s.color} ${s.border}`,children:s.label}),(0,t.jsx)("span",{className:"text-xs text-gray-400",children:e.timestamp}),(0,t.jsx)("span",{className:"text-xs text-gray-400",children:"·"}),e.model&&(0,t.jsx)("span",{className:"text-xs text-gray-500",children:e.model})]}),(0,t.jsx)("p",{className:"text-sm text-gray-800 truncate",children:e.input_snippet??e.input??"—"})]}),(0,t.jsx)(tC.DownOutlined,{className:"w-4 h-4 text-gray-400 flex-shrink-0 mt-1"})]},e.id)})}),(0,t.jsx)(sa.LogDetailsDrawer,{open:y,onClose:()=>{j(!1),g(null)},logEntry:w,accessToken:o,allLogs:w?[w]:[],startTime:_})]})}function si({label:e,value:s,valueColor:a="text-gray-900",icon:l,subtitle:r}){return(0,t.jsxs)("div",{className:"h-full bg-white border border-gray-200 rounded-lg p-5 flex flex-col",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,t.jsx)("span",{className:"text-sm font-medium text-gray-600",children:e}),l&&(0,t.jsx)("span",{className:"text-gray-400",children:l})]}),(0,t.jsx)("div",{className:`text-3xl font-semibold ${a} tracking-tight`,children:s}),r&&(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:r})]})}let sn={healthy:{bg:"bg-green-50",text:"text-green-700",dot:"bg-green-500"},warning:{bg:"bg-amber-50",text:"text-amber-700",dot:"bg-amber-500"},critical:{bg:"bg-red-50",text:"text-red-700",dot:"bg-red-500"}};function so({guardrailId:e,onBack:s,accessToken:a=null,startDate:r,endDate:n}){let[o,d]=(0,i.useState)("overview"),[c,m]=(0,i.useState)(!1),[u,x]=(0,i.useState)(1),{data:p,isLoading:h,error:g}=(0,t4.useQuery)({queryKey:["guardrails-usage-detail",e,r,n],queryFn:()=>(0,l.getGuardrailsUsageDetail)(a,e,r,n),enabled:!!a&&!!e}),{data:y,isLoading:j}=(0,t4.useQuery)({queryKey:["guardrails-usage-logs",e,u,50],queryFn:()=>(0,l.getGuardrailsUsageLogs)(a,{guardrailId:e,page:u,pageSize:50,startDate:r,endDate:n}),enabled:!!a&&!!e}),f=(0,i.useMemo)(()=>(y?.logs??[]).map(e=>({id:e.id,timestamp:e.timestamp,action:e.action,score:e.score,model:e.model,input_snippet:e.input_snippet,output_snippet:e.output_snippet,reason:e.reason})),[y?.logs]),b=p?{name:p.guardrail_name,description:p.description??"",status:p.status,provider:p.provider,type:p.type,requestsEvaluated:p.requestsEvaluated,failRate:p.failRate,avgScore:p.avgScore,avgLatency:p.avgLatency}:{name:e,description:"",status:"healthy",provider:"—",type:"—",requestsEvaluated:0,failRate:0,avgScore:void 0,avgLatency:void 0},_=sn[b.status]??sn.healthy;return h&&!p?(0,t.jsx)("div",{className:"flex items-center justify-center py-12",children:(0,t.jsx)(eL.Spin,{size:"large"})}):g&&!p?(0,t.jsxs)("div",{children:[(0,t.jsx)(G.Button,{type:"link",icon:(0,t.jsx)(tZ.ArrowLeftOutlined,{}),onClick:s,className:"pl-0 mb-4",children:"Back to Overview"}),(0,t.jsx)("p",{className:"text-red-600",children:"Failed to load guardrail details."})]}):(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"mb-6",children:[(0,t.jsx)(G.Button,{type:"link",icon:(0,t.jsx)(tZ.ArrowLeftOutlined,{}),onClick:s,className:"pl-0 mb-4",children:"Back to Overview"}),(0,t.jsxs)("div",{className:"flex items-start justify-between",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center gap-3 mb-1",children:[(0,t.jsx)(t0.SafetyOutlined,{className:"text-xl text-gray-400"}),(0,t.jsx)("h1",{className:"text-xl font-semibold text-gray-900",children:b.name}),(0,t.jsxs)("span",{className:`inline-flex items-center gap-1.5 px-2.5 py-0.5 text-xs font-medium rounded-full ${_.bg} ${_.text}`,children:[(0,t.jsx)("span",{className:`w-1.5 h-1.5 rounded-full ${_.dot}`}),b.status.charAt(0).toUpperCase()+b.status.slice(1)]})]}),(0,t.jsx)("p",{className:"text-sm text-gray-500 ml-8",children:b.description})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:"inline-flex items-center px-2.5 py-1 text-xs font-medium rounded-md bg-indigo-50 text-indigo-700 border border-indigo-200",children:b.provider}),(0,t.jsx)(G.Button,{type:"default",icon:(0,t.jsx)(t1.SettingOutlined,{}),onClick:()=>m(!0),title:"Evaluation settings"})]})]})]}),(0,t.jsx)(t3.Tabs,{activeKey:o,onChange:d,items:[{key:"overview",label:"Overview"},{key:"logs",label:"Logs"}]}),"overview"===o&&(0,t.jsxs)("div",{className:"space-y-6 mt-4",children:[(0,t.jsxs)(t6.Grid,{numItems:2,numItemsMd:5,className:"gap-4",children:[(0,t.jsx)(t5.Col,{children:(0,t.jsx)(si,{label:"Requests Evaluated",value:b.requestsEvaluated.toLocaleString()})}),(0,t.jsx)(t5.Col,{children:(0,t.jsx)(si,{label:"Fail Rate",value:`${b.failRate}%`,valueColor:b.failRate>15?"text-red-600":b.failRate>5?"text-amber-600":"text-green-600",subtitle:`${Math.round(b.requestsEvaluated*b.failRate/100).toLocaleString()} blocked`,icon:b.failRate>15?(0,t.jsx)(t2.WarningOutlined,{className:"text-red-400"}):void 0})}),(0,t.jsx)(t5.Col,{children:(0,t.jsx)(si,{label:"Avg. latency added",value:null!=b.avgLatency?`${Math.round(b.avgLatency)}ms`:"—",valueColor:null!=b.avgLatency?b.avgLatency>150?"text-red-600":b.avgLatency>50?"text-amber-600":"text-green-600":"text-gray-500",subtitle:null!=b.avgLatency?"Per request (avg)":"No data"})})]}),(0,t.jsx)(sr,{guardrailName:b.name,filterAction:"all",logs:f,logsLoading:j,totalLogs:y?.total??0,accessToken:a,startDate:r,endDate:n})]}),"logs"===o&&(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(sr,{guardrailName:b.name,logs:f,logsLoading:j,totalLogs:y?.total??0,accessToken:a,startDate:r,endDate:n})}),(0,t.jsx)(st,{open:c,onClose:()=>m(!1),guardrailName:b.name,accessToken:a})]})}let sd={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M917 211.1l-199.2 24c-6.6.8-9.4 8.9-4.7 13.6l59.3 59.3-226 226-101.8-101.7c-6.3-6.3-16.4-6.2-22.6 0L100.3 754.1a8.03 8.03 0 000 11.3l45 45.2c3.1 3.1 8.2 3.1 11.3 0L433.3 534 535 635.7c6.3 6.2 16.4 6.2 22.6 0L829 364.5l59.3 59.3a8.01 8.01 0 0013.6-4.7l24-199.2c.7-5.1-3.7-9.5-8.9-8.8z"}}]},name:"rise",theme:"outlined"};var sc=i.forwardRef(function(e,t){return i.createElement(tL.default,(0,tF.default)({},e,{ref:t,icon:sd}))}),sm=e.i(584935);function su({data:e}){let s=e&&e.length>0?e:[];return(0,t.jsxs)(u.Card,{className:"bg-white border border-gray-200",children:[(0,t.jsx)(eC.Title,{className:"text-base font-semibold text-gray-900 mb-4",children:"Request Outcomes Over Time"}),(0,t.jsx)("div",{className:"h-80 min-h-[280px]",children:s.length>0?(0,t.jsx)(sm.BarChart,{data:s,index:"date",categories:["passed","blocked"],colors:["green","red"],valueFormatter:e=>e.toLocaleString(),yAxisWidth:48,showLegend:!0,stack:!0}):(0,t.jsx)("div",{className:"flex items-center justify-center h-full text-sm text-gray-500",children:"No chart data for this period"})})]})}let sx={Bedrock:"bg-orange-100 text-orange-700 border-orange-200","Google Cloud":"bg-sky-100 text-sky-700 border-sky-200",LiteLLM:"bg-indigo-100 text-indigo-700 border-indigo-200",Custom:"bg-gray-100 text-gray-600 border-gray-200"};function sp({accessToken:e=null,startDate:s,endDate:a,onSelectGuardrail:r}){let[n,o]=(0,i.useState)("failRate"),[d,c]=(0,i.useState)("desc"),[m,x]=(0,i.useState)(!1),{data:p,isLoading:h,error:g}=(0,t4.useQuery)({queryKey:["guardrails-usage-overview",s,a],queryFn:()=>(0,l.getGuardrailsUsageOverview)(e,s,a),enabled:!!e}),y=p?.rows??[],j=(0,i.useMemo)(()=>{let e,t,s,a;return p?{totalRequests:p.totalRequests??0,totalBlocked:p.totalBlocked??0,passRate:String(p.passRate??0),avgLatency:y.length?Math.round(y.reduce((e,t)=>e+(t.avgLatency??0),0)/y.length):0,count:y.length}:(e=y.reduce((e,t)=>e+t.requestsEvaluated,0),t=y.reduce((e,t)=>e+Math.round(t.requestsEvaluated*t.failRate/100),0),s=e>0?((1-t/e)*100).toFixed(1):"0",{totalRequests:e,totalBlocked:t,passRate:s,avgLatency:(a=y.filter(e=>null!=e.avgLatency)).length>0?Math.round(a.reduce((e,t)=>e+(t.avgLatency??0),0)/a.length):0,count:y.length})},[p,y]),f=p?.chart,b=(0,i.useMemo)(()=>[...y].sort((e,t)=>{let s="desc"===d?-1:1,a=e[n]??0,l=t[n]??0;return(Number(a)-Number(l))*s}),[y,n,d]),_=[{title:"Guardrail",dataIndex:"name",key:"name",render:(e,s)=>(0,t.jsx)("button",{type:"button",className:"text-sm font-medium text-gray-900 hover:text-indigo-600 text-left",onClick:()=>r(s.id),children:e})},{title:"Provider",dataIndex:"provider",key:"provider",render:e=>(0,t.jsx)("span",{className:`inline-flex items-center px-2 py-0.5 text-xs font-medium rounded border ${sx[e]??sx.Custom}`,children:e})},{title:"Requests",dataIndex:"requestsEvaluated",key:"requestsEvaluated",align:"right",sorter:!0,sortOrder:"requestsEvaluated"===n?"desc"===d?"descend":"ascend":null,render:e=>e.toLocaleString()},{title:"Fail Rate",dataIndex:"failRate",key:"failRate",align:"right",sorter:!0,sortOrder:"failRate"===n?"desc"===d?"descend":"ascend":null,render:(e,s)=>(0,t.jsxs)("span",{className:e>15?"text-red-600":e>5?"text-amber-600":"text-green-600",children:[e,"%","up"===s.trend&&(0,t.jsx)("span",{className:"ml-1 text-xs text-red-400",children:"↑"}),"down"===s.trend&&(0,t.jsx)("span",{className:"ml-1 text-xs text-green-400",children:"↓"})]})},{title:"Avg. latency added",dataIndex:"avgLatency",key:"avgLatency",align:"right",sorter:!0,sortOrder:"avgLatency"===n?"desc"===d?"descend":"ascend":null,render:e=>(0,t.jsx)("span",{className:null==e?"text-gray-400":e>150?"text-red-600":e>50?"text-amber-600":"text-green-600",children:null!=e?`${e}ms`:"—"})},{title:"Status",dataIndex:"status",key:"status",align:"center",render:e=>(0,t.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,t.jsx)("span",{className:`w-2 h-2 rounded-full ${"healthy"===e?"bg-green-500":"warning"===e?"bg-amber-500":"bg-red-500"}`}),(0,t.jsx)("span",{className:"text-xs text-gray-600 capitalize",children:e})]})}],v=["failRate","requestsEvaluated","avgLatency"];return(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-start justify-between mb-5",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 mb-1",children:[(0,t.jsx)(t0.SafetyOutlined,{className:"text-lg text-indigo-500"}),(0,t.jsx)("h1",{className:"text-xl font-semibold text-gray-900",children:"Guardrails Monitor"})]}),(0,t.jsx)("p",{className:"text-sm text-gray-500",children:"Monitor guardrail performance across all requests"})]}),(0,t.jsx)("div",{className:"flex items-center gap-3",children:(0,t.jsx)(G.Button,{type:"default",icon:(0,t.jsx)(tT.DownloadOutlined,{}),title:"Coming soon",children:"Export Data"})})]}),(0,t.jsxs)(t6.Grid,{numItems:2,numItemsLg:5,className:"gap-4 mb-6 items-stretch",children:[(0,t.jsx)(t5.Col,{className:"flex flex-col",children:(0,t.jsx)(si,{label:"Total Evaluations",value:j.totalRequests.toLocaleString()})}),(0,t.jsx)(t5.Col,{className:"flex flex-col",children:(0,t.jsx)(si,{label:"Blocked Requests",value:j.totalBlocked.toLocaleString(),valueColor:"text-red-600",icon:(0,t.jsx)(t2.WarningOutlined,{className:"text-red-400"})})}),(0,t.jsx)(t5.Col,{className:"flex flex-col",children:(0,t.jsx)(si,{label:"Pass Rate",value:`${j.passRate}%`,valueColor:"text-green-600",icon:(0,t.jsx)(sc,{className:"text-green-400"})})}),(0,t.jsx)(t5.Col,{className:"flex flex-col",children:(0,t.jsx)(si,{label:"Avg. latency added",value:`${j.avgLatency}ms`,valueColor:j.avgLatency>150?"text-red-600":j.avgLatency>50?"text-amber-600":"text-green-600"})}),(0,t.jsx)(t5.Col,{className:"flex flex-col",children:(0,t.jsx)(si,{label:"Active Guardrails",value:j.count})})]}),(0,t.jsx)("div",{className:"mb-6",children:(0,t.jsx)(su,{data:f})}),(0,t.jsxs)(u.Card,{className:"bg-white border border-gray-200 rounded-lg",children:[(h||g)&&(0,t.jsxs)("div",{className:"px-6 py-4 border-b border-gray-200 flex items-center gap-2",children:[h&&(0,t.jsx)(eL.Spin,{size:"small"}),g&&(0,t.jsx)("span",{className:"text-sm text-red-600",children:"Failed to load data. Try again."})]}),(0,t.jsxs)("div",{className:"px-6 py-4 border-b border-gray-200 flex items-start justify-between gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(eC.Title,{className:"text-base font-semibold text-gray-900",children:"Guardrail Performance"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:"Click a guardrail to view details, logs, and configuration"})]}),(0,t.jsx)("div",{className:"flex items-center gap-2",children:(0,t.jsx)(G.Button,{type:"default",icon:(0,t.jsx)(t1.SettingOutlined,{}),onClick:()=>x(!0),title:"Evaluation settings"})})]}),(0,t.jsx)(ts.Table,{columns:_,dataSource:b,rowKey:"id",pagination:!1,loading:h,onChange:(e,t,s)=>{s?.field&&v.includes(s.field)&&(o(s.field),c("ascend"===s.order?"asc":"desc"))},locale:0!==y.length||h?void 0:{emptyText:"No data for this period"},onRow:e=>({onClick:()=>r(e.id),style:{cursor:"pointer"}})})]}),(0,t.jsx)(st,{open:m,onClose:()=>x(!1),accessToken:e})]})}let sh=new Date,sg=new Date;function sy({accessToken:e=null}){let[s,a]=(0,i.useState)({type:"overview"}),r=(0,i.useMemo)(()=>new Date(sg),[]),n=(0,i.useMemo)(()=>new Date(sh),[]),[o,d]=(0,i.useState)({from:r,to:n}),c=o.from?(0,l.formatDate)(o.from):"",m=o.to?(0,l.formatDate)(o.to):"",u=(0,i.useCallback)(e=>{d(e)},[]);return(0,t.jsxs)("div",{className:"p-6 w-full min-w-0 flex-1",children:[(0,t.jsx)("div",{className:"flex items-center justify-end mb-4",children:(0,t.jsx)(tX.default,{value:o,onValueChange:u,label:"",showTimeRange:!1})}),"overview"===s.type?(0,t.jsx)(sp,{accessToken:e,startDate:c,endDate:m,onSelectGuardrail:e=>{a({type:"detail",guardrailId:e})}}):(0,t.jsx)(so,{guardrailId:s.guardrailId,onBack:()=>{a({type:"overview"})},accessToken:e,startDate:c,endDate:m})]})}sg.setDate(sg.getDate()-7);var sj=e.i(487304),sf=e.i(760221);e.i(111790);var sb=e.i(280881),s_=e.i(934879),sv=e.i(402874),sN=e.i(797305),sw=e.i(109799),sk=e.i(747871),sC=e.i(56567),sS=e.i(468133),sT=e.i(871943),sI=e.i(502547),sF=e.i(278587),sP=e.i(655913),sL=e.i(38419),sA=e.i(78334),sM=e.i(555436),sD=e.i(284614),sE=e.i(206929),sO=e.i(35983),sR=e.i(898586),sz=e.i(9314),sB=e.i(552130),sq=e.i(533882),s$=e.i(651904),sU=e.i(460285),sH=e.i(435451),sV=e.i(916940),sG=e.i(127952),sK=e.i(162386);let sW=(e,t,s)=>"Admin"===e||!!s&&!!t&&s.some(e=>e.members?.some(e=>e.user_id===t&&"org_admin"===e.user_role)),sQ=(e,t,s)=>"Admin"===e?s||[]:s&&t?s.filter(e=>e.members?.some(e=>e.user_id===t&&"org_admin"===e.user_role)):[],sY=({teams:e,searchParams:s,accessToken:a,setTeams:r,userID:n,userRole:o,organizations:d,premiumUser:c=!1})=>{let v,w,C,T;console.log(`organizations: ${JSON.stringify(d)}`);let{data:P}=(0,sw.useOrganizations)(),[L,A]=(0,i.useState)(""),[M,D]=(0,i.useState)(null),[E,O]=(0,i.useState)(null),[R,z]=(0,i.useState)(!1),[q,U]=(0,i.useState)({team_id:"",team_alias:"",organization_id:"",sort_by:"created_at",sort_order:"desc"});(0,i.useEffect)(()=>{console.log(`inside useeffect - ${L}`),a&&(0,eG.fetchTeams)(a,n,o,M,r),e7()},[L]);let[H]=S.Form.useForm(),[V]=S.Form.useForm(),{Title:K,Paragraph:W}=sR.Typography,[Q,Y]=(0,i.useState)(""),[J,X]=(0,i.useState)(!1),[Z,ee]=(0,i.useState)(null),[et,es]=(0,i.useState)(null),[ea,el]=(0,i.useState)(!1),[er,ei]=(0,i.useState)(!1),[en,eo]=(0,i.useState)(!1),[ed,ec]=(0,i.useState)(!1),[em,eu]=(0,i.useState)([]),[ex,ep]=(0,i.useState)(!1),[eh,eg]=(0,i.useState)(null),[ey,ej]=(0,i.useState)([]),[e_,ev]=(0,i.useState)({}),[eN,ew]=(0,i.useState)(!1),[eC,eL]=(0,i.useState)([]),[eA,eM]=(0,i.useState)([]),[eD,eE]=(0,i.useState)({}),[eO,eR]=(0,i.useState)([]),[e$,eU]=(0,i.useState)([]),[eH,eV]=(0,i.useState)(!1),[eK,eZ]=(0,i.useState)({}),[e0,e1]=(0,i.useState)(null),[e2,e4]=(0,i.useState)(0);(0,i.useEffect)(()=>{let e;console.log(`currentOrgForCreateTeam: ${E}`);let t=(e=[],E&&E.models.length>0?(console.log(`organization.models: ${E.models}`),e=E.models):e=em,(0,$.unfurlWildcardModelsInList)(e,em));console.log(`models: ${t}`),ej(t),H.setFieldValue("models",[])},[E,em]),(0,i.useEffect)(()=>{if(er){let e=sQ(o,n,d);if(1===e.length){let t=e[0];H.setFieldValue("organization_id",t.organization_id),O(t)}else H.setFieldValue("organization_id",M?.organization_id||null),O(M)}},[er,o,n,d,M]),(0,i.useEffect)(()=>{let e=async()=>{try{if(null==a)return;let e=(await (0,l.getPoliciesList)(a)).policies.map(e=>e.policy_name);eM(e)}catch(e){console.error("Failed to fetch policies:",e)}};(async()=>{try{if(null==a)return;let e=(await (0,l.getGuardrailsList)(a)).guardrails.map(e=>e.guardrail_name);eL(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})(),e()},[a]);let e5=async()=>{try{if(null==a)return;let e=await (0,l.fetchMCPAccessGroups)(a);eU(e)}catch(e){console.error("Failed to fetch MCP access groups:",e)}};(0,i.useEffect)(()=>{e5()},[a]),(0,i.useEffect)(()=>{e&&ev(e.reduce((e,t)=>(e[t.team_id]={keys:t.keys||[],team_info:{members_with_roles:t.members_with_roles||[]}},e),{}))},[e]);let e6=async e=>{eg(e),ep(!0)},e3=async()=>{if(null!=eh&&null!=e&&null!=a)try{ew(!0),await (0,l.teamDeleteCall)(a,eh.team_id),await (0,eG.fetchTeams)(a,n,o,M,r),ez.default.success("Team deleted successfully")}catch(e){ez.default.fromBackend("Error deleting the team: "+e)}finally{ew(!1),ep(!1),eg(null)}};(0,i.useEffect)(()=>{(async()=>{try{if(null===n||null===o||null===a)return;let e=await (0,$.fetchAvailableModelsForTeamOrKey)(n,o,a);e&&eu(e)}catch(e){console.error("Error fetching user models:",e)}})()},[a,n,o,e]);let e8=async t=>{try{if(console.log(`formValues: ${JSON.stringify(t)}`),null!=a){let s=t?.team_alias,i=e?.map(e=>e.team_alias)??[],n=t?.organization_id||M?.organization_id;if(""===n||"string"!=typeof n?t.organization_id=null:t.organization_id=n.trim(),i.includes(s))throw Error(`Team alias ${s} already exists, please pick another alias`);if(ez.default.info("Creating Team"),eO.length>0){let e={};if(t.metadata)try{e=JSON.parse(t.metadata)}catch(e){console.warn("Invalid JSON in metadata field, starting with empty object")}e={...e,logging:eO.filter(e=>e.callback_name)},t.metadata=JSON.stringify(e)}if(t.secret_manager_settings&&"string"==typeof t.secret_manager_settings)if(""===t.secret_manager_settings.trim())delete t.secret_manager_settings;else try{t.secret_manager_settings=JSON.parse(t.secret_manager_settings)}catch(e){throw Error("Failed to parse secret manager settings: "+e)}if(t.allowed_vector_store_ids&&t.allowed_vector_store_ids.length>0||t.allowed_mcp_servers_and_groups&&(t.allowed_mcp_servers_and_groups.servers?.length>0||t.allowed_mcp_servers_and_groups.accessGroups?.length>0||t.allowed_mcp_servers_and_groups.toolPermissions)){if(t.object_permission={},t.allowed_vector_store_ids&&t.allowed_vector_store_ids.length>0&&(t.object_permission.vector_stores=t.allowed_vector_store_ids,delete t.allowed_vector_store_ids),t.allowed_mcp_servers_and_groups){let{servers:e,accessGroups:s}=t.allowed_mcp_servers_and_groups;e&&e.length>0&&(t.object_permission.mcp_servers=e),s&&s.length>0&&(t.object_permission.mcp_access_groups=s),delete t.allowed_mcp_servers_and_groups}t.mcp_tool_permissions&&Object.keys(t.mcp_tool_permissions).length>0&&(t.object_permission||(t.object_permission={}),t.object_permission.mcp_tool_permissions=t.mcp_tool_permissions,delete t.mcp_tool_permissions)}if(t.allowed_mcp_access_groups&&t.allowed_mcp_access_groups.length>0&&(t.object_permission||(t.object_permission={}),t.object_permission.mcp_access_groups=t.allowed_mcp_access_groups,delete t.allowed_mcp_access_groups),t.allowed_agents_and_groups){let{agents:e,accessGroups:s}=t.allowed_agents_and_groups;t.object_permission||(t.object_permission={}),e&&e.length>0&&(t.object_permission.agents=e),s&&s.length>0&&(t.object_permission.agent_access_groups=s),delete t.allowed_agents_and_groups}Object.keys(eK).length>0&&(t.model_aliases=eK),e0?.router_settings&&Object.values(e0.router_settings).some(e=>null!=e&&""!==e)&&(t.router_settings=e0.router_settings);let o=await (0,l.teamCreateCall)(a,t);null!==e?r([...e,o]):r([o]),console.log(`response for team create call: ${o}`),ez.default.success("Team created"),H.resetFields(),eR([]),eZ({}),e1(null),e4(e=>e+1),ei(!1)}}catch(e){console.error("Error creating the team:",e),ez.default.fromBackend("Error creating the team: "+e)}},e7=()=>{A(new Date().toLocaleString())},e9=(e,t)=>{let s={...q,[e]:t};U(s),a&&(0,l.v2TeamListCall)(a,s.organization_id||null,null,s.team_id||null,s.team_alias||null).then(e=>{e&&e.teams&&r(e.teams)}).catch(e=>{console.error("Error fetching teams:",e)})};return(0,t.jsx)("div",{className:"w-full mx-4 h-[75vh]",children:(0,t.jsx)(t6.Grid,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:(0,t.jsxs)(t5.Col,{numColSpan:1,className:"flex flex-col gap-2",children:[sW(o,n,d)&&(0,t.jsx)(m.Button,{className:"w-fit",onClick:()=>ei(!0),children:"+ Create New Team"}),et?(0,t.jsx)(sC.default,{teamId:et,onUpdate:e=>{r(t=>{if(null==t)return t;let s=t.map(t=>e.team_id===t.team_id?(0,eB.updateExistingKeys)(t,e):t);return a&&(0,eG.fetchTeams)(a,n,o,M,r),s})},onClose:()=>{es(null),el(!1)},accessToken:a,is_team_admin:(e=>{if(null==e||null==e.members_with_roles)return!1;for(let t=0;te.team_id===et)),is_proxy_admin:"Admin"==o,userModels:em,editTeam:ea,premiumUser:c}):(0,t.jsxs)(eT.TabGroup,{className:"gap-2 h-[75vh] w-full",children:[(0,t.jsxs)(eI.TabList,{className:"flex justify-between mt-2 w-full items-center",children:[(0,t.jsxs)("div",{className:"flex",children:[(0,t.jsx)(eS.Tab,{children:"Your Teams"}),(0,t.jsx)(eS.Tab,{children:"Available Teams"}),(0,ek.isProxyAdminRole)(o||"")&&(0,t.jsx)(eS.Tab,{children:"Default Team Settings"})]}),(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[L&&(0,t.jsxs)(b.Text,{children:["Last Refreshed: ",L]}),(0,t.jsx)(eX.Icon,{icon:sF.RefreshIcon,variant:"shadow",size:"xs",className:"self-center",onClick:e7})]})]}),(0,t.jsxs)(eP.TabPanels,{children:[(0,t.jsxs)(eF.TabPanel,{children:[(0,t.jsxs)(b.Text,{children:["Click on “Team ID” to view team details ",(0,t.jsx)("b",{children:"and"})," manage team members."]}),(0,t.jsx)(t6.Grid,{numItems:1,className:"gap-2 pt-2 pb-2 h-[75vh] w-full mt-2",children:(0,t.jsx)(t5.Col,{numColSpan:1,children:(0,t.jsxs)(u.Card,{className:"w-full mx-auto flex-auto overflow-hidden overflow-y-auto max-h-[50vh]",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)(sP.FilterInput,{placeholder:"Search by Team Name...",value:q.team_alias,onChange:e=>e9("team_alias",e),icon:sM.Search}),(0,t.jsx)(sL.FiltersButton,{onClick:()=>z(!R),active:R,hasActiveFilters:!!(q.team_id||q.team_alias||q.organization_id)}),(0,t.jsx)(sA.ResetFiltersButton,{onClick:()=>{U({team_id:"",team_alias:"",organization_id:"",sort_by:"created_at",sort_order:"desc"}),a&&(0,l.v2TeamListCall)(a,null,n||null,null,null).then(e=>{e&&e.teams&&r(e.teams)}).catch(e=>{console.error("Error fetching teams:",e)})}})]}),R&&(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-3 mt-3",children:[(0,t.jsx)(sP.FilterInput,{placeholder:"Enter Team ID",value:q.team_id,onChange:e=>e9("team_id",e),icon:sD.User}),(0,t.jsx)("div",{className:"w-64",children:(0,t.jsx)(sE.Select,{value:q.organization_id||"",onValueChange:e=>e9("organization_id",e),placeholder:"Select Organization",children:d?.map(e=>(0,t.jsx)(sO.SelectItem,{value:e.organization_id||"",children:e.organization_alias||e.organization_id},e.organization_id))})})]})]})}),(0,t.jsxs)(x.Table,{children:[(0,t.jsx)(g.TableHead,{children:(0,t.jsxs)(j.TableRow,{children:[(0,t.jsx)(y.TableHeaderCell,{children:"Team Name"}),(0,t.jsx)(y.TableHeaderCell,{children:"Team ID"}),(0,t.jsx)(y.TableHeaderCell,{children:"Created"}),(0,t.jsx)(y.TableHeaderCell,{children:"Spend (USD)"}),(0,t.jsx)(y.TableHeaderCell,{children:"Budget (USD)"}),(0,t.jsx)(y.TableHeaderCell,{children:"Models"}),(0,t.jsx)(y.TableHeaderCell,{children:"Organization"}),(0,t.jsx)(y.TableHeaderCell,{children:"Info"}),(0,t.jsx)(y.TableHeaderCell,{children:"Actions"})]})}),(0,t.jsx)(p.TableBody,{children:e&&e.length>0?e.filter(e=>!M||e.organization_id===M.organization_id).sort((e,t)=>new Date(t.created_at).getTime()-new Date(e.created_at).getTime()).map(e=>(0,t.jsxs)(j.TableRow,{children:[(0,t.jsx)(h.TableCell,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:e.team_alias}),(0,t.jsx)(h.TableCell,{children:(0,t.jsx)("div",{className:"overflow-hidden",children:(0,t.jsx)(N.Tooltip,{title:e.team_id,children:(0,t.jsxs)(m.Button,{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:()=>{es(e.team_id)},children:[e.team_id.slice(0,7),"..."]})})})}),(0,t.jsx)(h.TableCell,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:e.created_at?new Date(e.created_at).toLocaleDateString():"N/A"}),(0,t.jsx)(h.TableCell,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:(0,eB.formatNumberWithCommas)(e.spend,4)}),(0,t.jsx)(h.TableCell,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:null!==e.max_budget&&void 0!==e.max_budget?e.max_budget:"No limit"}),(0,t.jsx)(h.TableCell,{style:{maxWidth:"8-x",whiteSpace:"pre-wrap",overflow:"hidden"},className:e.models.length>3?"px-0":"",children:(0,t.jsx)("div",{className:"flex flex-col",children:Array.isArray(e.models)?(0,t.jsx)("div",{className:"flex flex-col",children:0===e.models.length?(0,t.jsx)(f.Badge,{size:"xs",className:"mb-1",color:"red",children:(0,t.jsx)(b.Text,{children:"All Proxy Models"})}):(0,t.jsx)(t.Fragment,{children:(0,t.jsxs)("div",{className:"flex items-start",children:[e.models.length>3&&(0,t.jsx)("div",{children:(0,t.jsx)(eX.Icon,{icon:eD[e.team_id]?sT.ChevronDownIcon:sI.ChevronRightIcon,className:"cursor-pointer",size:"xs",onClick:()=>{eE(t=>({...t,[e.team_id]:!t[e.team_id]}))}})}),(0,t.jsxs)("div",{className:"flex flex-wrap gap-1",children:[e.models.slice(0,3).map((e,s)=>"all-proxy-models"===e?(0,t.jsx)(f.Badge,{size:"xs",color:"red",children:(0,t.jsx)(b.Text,{children:"All Proxy Models"})},s):(0,t.jsx)(f.Badge,{size:"xs",color:"blue",children:(0,t.jsx)(b.Text,{children:e.length>30?`${(0,$.getModelDisplayName)(e).slice(0,30)}...`:(0,$.getModelDisplayName)(e)})},s)),e.models.length>3&&!eD[e.team_id]&&(0,t.jsx)(f.Badge,{size:"xs",color:"gray",className:"cursor-pointer",children:(0,t.jsxs)(b.Text,{children:["+",e.models.length-3," ",e.models.length-3==1?"more model":"more models"]})}),eD[e.team_id]&&(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:e.models.slice(3).map((e,s)=>"all-proxy-models"===e?(0,t.jsx)(f.Badge,{size:"xs",color:"red",children:(0,t.jsx)(b.Text,{children:"All Proxy Models"})},s+3):(0,t.jsx)(f.Badge,{size:"xs",color:"blue",children:(0,t.jsx)(b.Text,{children:e.length>30?`${(0,$.getModelDisplayName)(e).slice(0,30)}...`:(0,$.getModelDisplayName)(e)})},s+3))})]})]})})}):null})}),(0,t.jsx)(h.TableCell,{children:((e,t)=>{if(!e||!t)return e||"N/A";let s=t.find(t=>t.organization_id===e);return s?.organization_alias||e})(e.organization_id,P||d)}),(0,t.jsxs)(h.TableCell,{children:[(0,t.jsxs)(b.Text,{children:[e_&&e.team_id&&e_[e.team_id]&&e_[e.team_id].keys&&e_[e.team_id].keys.length," ","Keys"]}),(0,t.jsxs)(b.Text,{children:[e_&&e.team_id&&e_[e.team_id]&&e_[e.team_id].team_info&&e_[e.team_id].team_info.members_with_roles&&e_[e.team_id].team_info.members_with_roles.length," ","Members"]})]}),(0,t.jsx)(h.TableCell,{children:"Admin"==o?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(eq.default,{variant:"Edit",onClick:()=>{es(e.team_id),el(!0)},dataTestId:"edit-team-button",tooltipText:"Edit team"}),(0,t.jsx)(eq.default,{variant:"Delete",onClick:()=>e6(e),dataTestId:"delete-team-button",tooltipText:"Delete team"})]}):null})]},e.team_id)):(0,t.jsx)(j.TableRow,{children:(0,t.jsx)(h.TableCell,{colSpan:9,className:"text-center",children:(0,t.jsxs)("div",{className:"flex flex-col items-center justify-center py-4",children:[(0,t.jsx)(b.Text,{className:"text-lg font-medium mb-2",children:"No teams found"}),(0,t.jsx)(b.Text,{className:"text-sm",children:"Adjust your filters or create a new team"})]})})})})]}),(0,t.jsx)(sG.default,{isOpen:ex,title:"Delete Team?",alertMessage:eh?.keys?.length===0?void 0:`Warning: This team has ${eh?.keys?.length} keys associated with it. Deleting the team will also delete all associated keys. This action is irreversible.`,message:"Are you sure you want to delete this team and all its keys? This action cannot be undone.",resourceInformationTitle:"Team Information",resourceInformation:[{label:"Team ID",value:eh?.team_id,code:!0},{label:"Team Name",value:eh?.team_alias},{label:"Keys",value:eh?.keys?.length},{label:"Members",value:eh?.members_with_roles?.length}],requiredConfirmation:eh?.team_alias,onCancel:()=>{ep(!1),eg(null)},onOk:e3,confirmLoading:eN})]})})})]}),(0,t.jsx)(eF.TabPanel,{children:(0,t.jsx)(sk.default,{accessToken:a,userID:n})}),(0,ek.isProxyAdminRole)(o||"")&&(0,t.jsx)(eF.TabPanel,{children:(0,t.jsx)(sS.default,{accessToken:a,userID:n||"",userRole:o||""})})]})]}),sW(o,n,d)&&(0,t.jsx)(_.Modal,{title:"Create Team",open:er,width:1e3,footer:null,onOk:()=>{ei(!1),H.resetFields(),eR([]),eZ({}),e1(null),e4(e=>e+1)},onCancel:()=>{ei(!1),H.resetFields(),eR([]),eZ({}),e1(null),e4(e=>e+1)},children:(0,t.jsxs)(S.Form,{form:H,onFinish:e8,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(S.Form.Item,{label:"Team Name",name:"team_alias",rules:[{required:!0,message:"Please input a team name"}],children:(0,t.jsx)(eJ.TextInput,{placeholder:""})}),(v=sQ(o,n,d),w="Admin"!==o,C=1===v.length,T=0===v.length,(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{children:["Organization"," ",(0,t.jsx)(N.Tooltip,{title:(0,t.jsxs)("span",{children:["Organizations can have multiple teams. Learn more about"," ",(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/user_management_heirarchy",target:"_blank",rel:"noopener noreferrer",style:{color:"#1890ff",textDecoration:"underline"},onClick:e=>e.stopPropagation(),children:"user management hierarchy"})]}),children:(0,t.jsx)(B.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"organization_id",initialValue:M?M.organization_id:null,className:"mt-8",rules:w?[{required:!0,message:"Please select an organization"}]:[],help:C?"You can only create teams within this organization":w?"required":"",children:(0,t.jsx)(I.Select,{showSearch:!0,allowClear:!w,disabled:C,placeholder:T?"No organizations available":"Search or select an Organization",onChange:e=>{H.setFieldValue("organization_id",e),O(v?.find(t=>t.organization_id===e)||null)},filterOption:(e,t)=>!!t&&(t.children?.toString()||"").toLowerCase().includes(e.toLowerCase()),optionFilterProp:"children",children:v?.map(e=>(0,t.jsxs)(I.Select.Option,{value:e.organization_id,children:[(0,t.jsx)("span",{className:"font-medium",children:e.organization_alias})," ",(0,t.jsxs)("span",{className:"text-gray-500",children:["(",e.organization_id,")"]})]},e.organization_id))})}),w&&!C&&v.length>1&&(0,t.jsx)("div",{className:"mb-8 p-4 bg-blue-50 border border-blue-200 rounded-md",children:(0,t.jsx)(b.Text,{className:"text-blue-800 text-sm",children:"Please select an organization to create a team for. You can only create teams within organizations where you are an admin."})})]})),(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{children:["Models"," ",(0,t.jsx)(N.Tooltip,{title:"These are the models that your selected team has access to",children:(0,t.jsx)(B.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),rules:[{required:!0,message:"Please select at least one model"}],name:"models",children:(0,t.jsx)(sK.ModelSelect,{value:H.getFieldValue("models")||[],onChange:e=>H.setFieldValue("models",e),organizationID:H.getFieldValue("organization_id"),options:{includeSpecialOptions:!0,showAllProxyModelsOverride:!H.getFieldValue("organization_id")},context:"team",dataTestId:"create-team-models-select"})}),(0,t.jsx)(S.Form.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,t.jsx)(sH.default,{step:.01,precision:2,width:200})}),(0,t.jsx)(S.Form.Item,{className:"mt-8",label:"Reset Budget",name:"budget_duration",children:(0,t.jsxs)(I.Select,{defaultValue:null,placeholder:"n/a",children:[(0,t.jsx)(I.Select.Option,{value:"24h",children:"daily"}),(0,t.jsx)(I.Select.Option,{value:"7d",children:"weekly"}),(0,t.jsx)(I.Select.Option,{value:"30d",children:"monthly"})]})}),(0,t.jsx)(S.Form.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,t.jsx)(sH.default,{step:1,width:400})}),(0,t.jsx)(S.Form.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,t.jsx)(sH.default,{step:1,width:400})}),(0,t.jsxs)(eW.Accordion,{className:"mt-20 mb-8",onClick:()=>{eH||(e5(),eV(!0))},children:[(0,t.jsx)(eQ.AccordionHeader,{children:(0,t.jsx)("b",{children:"Additional Settings"})}),(0,t.jsxs)(eY.AccordionBody,{children:[(0,t.jsx)(S.Form.Item,{label:"Team ID",name:"team_id",help:"ID of the team you want to create. If not provided, it will be generated automatically.",children:(0,t.jsx)(eJ.TextInput,{onChange:e=>{e.target.value=e.target.value.trim()}})}),(0,t.jsx)(S.Form.Item,{label:"Team Member Budget (USD)",name:"team_member_budget",normalize:e=>e?Number(e):void 0,tooltip:"This is the individual budget for a user in the team.",children:(0,t.jsx)(sH.default,{step:.01,precision:2,width:200})}),(0,t.jsx)(S.Form.Item,{label:"Team Member Key Duration (eg: 1d, 1mo)",name:"team_member_key_duration",tooltip:"Set a limit to the duration of a team member's key. Format: 30s (seconds), 30m (minutes), 30h (hours), 30d (days), 1mo (month)",children:(0,t.jsx)(eJ.TextInput,{placeholder:"e.g., 30d"})}),(0,t.jsx)(S.Form.Item,{label:"Team Member RPM Limit",name:"team_member_rpm_limit",tooltip:"The RPM (Requests Per Minute) limit for individual team members",children:(0,t.jsx)(sH.default,{step:1,width:400})}),(0,t.jsx)(S.Form.Item,{label:"Team Member TPM Limit",name:"team_member_tpm_limit",tooltip:"The TPM (Tokens Per Minute) limit for individual team members",children:(0,t.jsx)(sH.default,{step:1,width:400})}),(0,t.jsx)(S.Form.Item,{label:"Metadata",name:"metadata",help:"Additional team metadata. Enter metadata as JSON object.",children:(0,t.jsx)(F.Input.TextArea,{rows:4})}),(0,t.jsx)(S.Form.Item,{label:"Secret Manager Settings",name:"secret_manager_settings",help:c?"Enter secret manager configuration as a JSON object.":"Premium feature - Upgrade to manage secret manager settings.",rules:[{validator:async(e,t)=>{if(!t)return Promise.resolve();try{return JSON.parse(t),Promise.resolve()}catch(e){return Promise.reject(Error("Please enter valid JSON"))}}}],children:(0,t.jsx)(F.Input.TextArea,{rows:4,placeholder:'{"namespace": "admin", "mount": "secret", "path_prefix": "litellm"}',disabled:!c})}),(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{children:["Guardrails"," ",(0,t.jsx)(N.Tooltip,{title:"Setup your first guardrail",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(B.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",className:"mt-8",help:"Select existing guardrails or enter new ones",children:(0,t.jsx)(I.Select,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter guardrails",options:eC.map(e=>({value:e,label:e}))})}),(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{children:["Disable Global Guardrails"," ",(0,t.jsx)(N.Tooltip,{title:"When enabled, this team will bypass any guardrails configured to run on every request (global guardrails)",children:(0,t.jsx)(B.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"disable_global_guardrails",className:"mt-4",valuePropName:"checked",help:"Bypass global guardrails for this team",children:(0,t.jsx)(k.Switch,{disabled:!c,checkedChildren:c?"Yes":"Premium feature - Upgrade to disable global guardrails by team",unCheckedChildren:c?"No":"Premium feature - Upgrade to disable global guardrails by team"})}),(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{children:["Policies"," ",(0,t.jsx)(N.Tooltip,{title:"Apply policies to this team to control guardrails and other settings",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/guardrail_policies",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(B.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"policies",className:"mt-8",help:"Select existing policies or enter new ones",children:(0,t.jsx)(I.Select,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter policies",options:eA.map(e=>({value:e,label:e}))})}),(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{children:["Access Groups"," ",(0,t.jsx)(N.Tooltip,{title:"Assign access groups to this team. Access groups control which models, MCP servers, and agents this team can use",children:(0,t.jsx)(B.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"access_group_ids",className:"mt-8",help:"Select access groups to assign to this team",children:(0,t.jsx)(sz.default,{placeholder:"Select access groups (optional)"})}),(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Vector Stores"," ",(0,t.jsx)(N.Tooltip,{title:"Select which vector stores this team can access by default. Leave empty for access to all vector stores",children:(0,t.jsx)(B.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_vector_store_ids",className:"mt-8",help:"Select vector stores this team can access. Leave empty for access to all vector stores",children:(0,t.jsx)(sV.default,{onChange:e=>H.setFieldValue("allowed_vector_store_ids",e),value:H.getFieldValue("allowed_vector_store_ids"),accessToken:a||"",placeholder:"Select vector stores (optional)"})})]})]}),(0,t.jsxs)(eW.Accordion,{className:"mt-8 mb-8",children:[(0,t.jsx)(eQ.AccordionHeader,{children:(0,t.jsx)("b",{children:"MCP Settings"})}),(0,t.jsxs)(eY.AccordionBody,{children:[(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed MCP Servers"," ",(0,t.jsx)(N.Tooltip,{title:"Select which MCP servers or access groups this team can access",children:(0,t.jsx)(B.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_mcp_servers_and_groups",className:"mt-4",help:"Select MCP servers or access groups this team can access",children:(0,t.jsx)(ef.default,{onChange:e=>H.setFieldValue("allowed_mcp_servers_and_groups",e),value:H.getFieldValue("allowed_mcp_servers_and_groups"),accessToken:a||"",placeholder:"Select MCP servers or access groups (optional)"})}),(0,t.jsx)(S.Form.Item,{name:"mcp_tool_permissions",initialValue:{},hidden:!0,children:(0,t.jsx)(F.Input,{type:"hidden"})}),(0,t.jsx)(S.Form.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:()=>(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(eb.default,{accessToken:a||"",selectedServers:H.getFieldValue("allowed_mcp_servers_and_groups")?.servers||[],toolPermissions:H.getFieldValue("mcp_tool_permissions")||{},onChange:e=>H.setFieldsValue({mcp_tool_permissions:e})})})})]})]}),(0,t.jsxs)(eW.Accordion,{className:"mt-8 mb-8",children:[(0,t.jsx)(eQ.AccordionHeader,{children:(0,t.jsx)("b",{children:"Agent Settings"})}),(0,t.jsx)(eY.AccordionBody,{children:(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Agents"," ",(0,t.jsx)(N.Tooltip,{title:"Select which agents or access groups this team can access",children:(0,t.jsx)(B.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_agents_and_groups",className:"mt-4",help:"Select agents or access groups this team can access",children:(0,t.jsx)(sB.default,{onChange:e=>H.setFieldValue("allowed_agents_and_groups",e),value:H.getFieldValue("allowed_agents_and_groups"),accessToken:a||"",placeholder:"Select agents or access groups (optional)"})})})]}),(0,t.jsxs)(eW.Accordion,{className:"mt-8 mb-8",children:[(0,t.jsx)(eQ.AccordionHeader,{children:(0,t.jsx)("b",{children:"Logging Settings"})}),(0,t.jsx)(eY.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(s$.default,{value:eO,onChange:eR,premiumUser:c})})})]}),(0,t.jsxs)(eW.Accordion,{className:"mt-8 mb-8",children:[(0,t.jsx)(eQ.AccordionHeader,{children:(0,t.jsx)("b",{children:"Router Settings"})}),(0,t.jsx)(eY.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4 w-full",children:(0,t.jsx)(sU.default,{accessToken:a||"",value:e0||void 0,onChange:e1,modelData:em.length>0?{data:em.map(e=>({model_name:e}))}:void 0},e2)})})]},`router-settings-accordion-${e2}`),(0,t.jsxs)(eW.Accordion,{className:"mt-8 mb-8",children:[(0,t.jsx)(eQ.AccordionHeader,{children:(0,t.jsx)("b",{children:"Model Aliases"})}),(0,t.jsx)(eY.AccordionBody,{children:(0,t.jsxs)("div",{className:"mt-4",children:[(0,t.jsx)(b.Text,{className:"text-sm text-gray-600 mb-4",children:"Create custom aliases for models that can be used by team members in API calls. This allows you to create shortcuts for specific models."}),(0,t.jsx)(sq.default,{accessToken:a||"",initialModelAliases:eK,onAliasUpdate:eZ,showExampleConfig:!1})]})})]})]}),(0,t.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,t.jsx)(G.Button,{htmlType:"submit",children:"Create Team"})})]})})]})})})};var sJ=e.i(702597),sX=e.i(846835),sZ=e.i(147612),s0=e.i(191403),s1=e.i(976883),s2=e.i(657688),s4=e.i(437902);let{Text:s5}=sR.Typography,s6=({litellmParams:e,accessToken:s,onTestComplete:a})=>{let[r,n]=(0,i.useState)(!0),[o,d]=(0,i.useState)(null),[c,m]=(0,i.useState)(!1);(0,i.useEffect)(()=>{(async()=>{n(!0);try{let t=await (0,l.testSearchToolConnection)(s,e);d(t),"success"===t.status&&ez.default.success("Connection test successful!")}catch(e){d({status:"error",message:e instanceof Error?e.message:"Unknown error occurred",error_type:"NetworkError"})}finally{n(!1),a&&a()}})()},[s,e,a]);let u=o?.message?(e=>{if(!e)return"Unknown error";let t=e.split("stack trace:")[0].trim().replace(/^litellm\.(.*?)Error:\s*/,"").replace(/^AuthenticationError:\s*/,"");if(t.includes("")||t.includes("(.*?)<\/title>/);return e?e[1]:t.includes("401")||t.includes("Authorization Required")?"Authentication failed: Invalid API key or credentials":"Authentication error - please check your API key"}return t.length>200?t.substring(0,200)+"...":t})(o.message):"Unknown error";return r?(0,t.jsx)("div",{style:{padding:"24px",borderRadius:"8px",backgroundColor:"#fff"},children:(0,t.jsxs)("div",{style:{textAlign:"center",padding:"32px 20px"},className:"jsx-dc9a0e2d897fe63b",children:[(0,t.jsx)("div",{style:{marginBottom:"16px"},className:"jsx-dc9a0e2d897fe63b loading-spinner",children:(0,t.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,t.jsxs)(s5,{style:{fontSize:"16px"},children:["Testing connection to ",e.search_provider||"search provider","..."]}),(0,t.jsx)(s4.default,{id:"dc9a0e2d897fe63b",children:"@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}"})]})}):o?(0,t.jsxs)("div",{style:{padding:"24px",borderRadius:"8px",backgroundColor:"#fff"},children:["success"===o.status?(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"32px 20px"},children:[(0,t.jsx)("div",{style:{color:"#52c41a",fontSize:"24px",display:"flex",alignItems:"center"},children:(0,t.jsx)("svg",{viewBox:"64 64 896 896",focusable:"false","data-icon":"check-circle",width:"1em",height:"1em",fill:"currentColor","aria-hidden":"true",children:(0,t.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,t.jsxs)("div",{style:{marginLeft:"12px"},children:[(0,t.jsxs)(s5,{type:"success",style:{fontSize:"18px",fontWeight:500,display:"block"},children:["Connection to ",e.search_provider," successful!"]}),o.test_query&&(0,t.jsxs)(s5,{style:{fontSize:"14px",color:"#666",marginTop:"8px",display:"block"},children:["Test query: ",(0,t.jsx)("code",{style:{backgroundColor:"#f0f0f0",padding:"2px 6px",borderRadius:"4px"},children:o.test_query})]}),void 0!==o.results_count&&(0,t.jsxs)(s5,{style:{fontSize:"14px",color:"#666",display:"block"},children:["Results retrieved: ",o.results_count]})]})]}):(0,t.jsx)(t.Fragment,{children:(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",marginBottom:"20px"},children:[(0,t.jsx)(t2.WarningOutlined,{style:{color:"#ff4d4f",fontSize:"24px",marginRight:"12px"}}),(0,t.jsxs)(s5,{type:"danger",style:{fontSize:"18px",fontWeight:500},children:["Connection to ",e.search_provider||"search provider"," failed"]})]}),(0,t.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,t.jsxs)(s5,{strong:!0,style:{display:"block",marginBottom:"8px"},children:["Error:"," "]}),(0,t.jsx)(s5,{type:"danger",style:{fontSize:"14px",lineHeight:"1.5"},children:u}),o.error_type&&(0,t.jsx)("div",{style:{marginTop:"8px"},children:(0,t.jsxs)(s5,{style:{fontSize:"13px",color:"#666"},children:["Error type:"," ",(0,t.jsx)("code",{style:{backgroundColor:"#ffebee",padding:"2px 6px",borderRadius:"4px",color:"#d32f2f"},children:o.error_type})]})}),o.message&&(0,t.jsx)("div",{style:{marginTop:"12px"},children:(0,t.jsx)(G.Button,{type:"link",onClick:()=>m(!c),style:{paddingLeft:0,height:"auto"},children:c?"Hide Details":"Show Details"})})]}),c&&(0,t.jsxs)("div",{style:{marginBottom:"20px"},children:[(0,t.jsx)(s5,{strong:!0,style:{display:"block",marginBottom:"8px",fontSize:"15px"},children:"Full Error Details"}),(0,t.jsx)("pre",{style:{backgroundColor:"#f5f5f5",padding:"16px",borderRadius:"8px",fontSize:"13px",maxHeight:"200px",overflow:"auto",border:"1px solid #e8e8e8",lineHeight:"1.5",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:o.message})]}),(0,t.jsxs)("div",{style:{backgroundColor:"#fffbf0",border:"1px solid #ffe58f",borderLeft:"4px solid #faad14",borderRadius:"8px",padding:"16px"},children:[(0,t.jsx)(s5,{strong:!0,style:{display:"block",marginBottom:"8px",color:"#d48806"},children:"Troubleshooting tips:"}),(0,t.jsxs)("ul",{style:{margin:"8px 0",paddingLeft:"20px",color:"#ad6800"},children:[(0,t.jsx)("li",{style:{marginBottom:"6px"},children:"Verify your API key is correct and active"}),(0,t.jsx)("li",{style:{marginBottom:"6px"},children:"Check if the search provider service is operational"}),(0,t.jsx)("li",{style:{marginBottom:"6px"},children:"Ensure you have sufficient credits/quota with the provider"}),(0,t.jsx)("li",{style:{marginBottom:"6px"},children:"Review the provider's documentation for any additional requirements"})]})]})]})}),(0,t.jsx)(M.Divider,{style:{margin:"24px 0 16px"}}),(0,t.jsx)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:(0,t.jsx)(G.Button,{type:"link",href:"https://docs.litellm.ai/docs/search",target:"_blank",icon:(0,t.jsx)(B.InfoCircleOutlined,{}),children:"View Search Documentation"})})]}):null},{TextArea:s3}=F.Input,s8=({providerName:e,displayName:s})=>(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center"},children:[(0,t.jsx)(s2.default,{src:`../ui/assets/logos/${e}.png`,alt:"",width:20,height:20,style:{marginRight:"8px",objectFit:"contain"},onError:e=>{e.currentTarget.style.display="none"}}),(0,t.jsx)("span",{children:s})]}),s7=({userRole:e,accessToken:s,onCreateSuccess:a,isModalVisible:r,setModalVisible:n})=>{let[o]=S.Form.useForm(),[d,c]=(0,i.useState)(!1),[u,x]=(0,i.useState)({}),[p,h]=(0,i.useState)(!1),[g,y]=(0,i.useState)(!1),[j,f]=(0,i.useState)(""),{data:b,isLoading:v}=(0,t4.useQuery)({queryKey:["searchProviders"],queryFn:()=>{if(!s)throw Error("Access Token required");return(0,l.fetchAvailableSearchProviders)(s)},enabled:!!s&&r}),w=b?.providers||[],k=async e=>{c(!0);try{let t={search_tool_name:e.search_tool_name,litellm_params:{search_provider:e.search_provider,api_key:e.api_key,api_base:e.api_base,timeout:e.timeout?parseFloat(e.timeout):void 0,max_retries:e.max_retries?parseInt(e.max_retries):void 0},search_tool_info:e.description?{description:e.description}:void 0};if(console.log("Creating search tool with payload:",t),null!=s){let e=await (0,l.createSearchTool)(s,t);ez.default.success("Search tool created successfully"),o.resetFields(),x({}),n(!1),a(e)}}catch(e){ez.default.error("Error creating search tool: "+e)}finally{c(!1)}},C=async()=>{try{await o.validateFields(["search_provider","api_key"]),y(!0),f(`test-${Date.now()}`),h(!0)}catch(e){ez.default.error("Please fill in Search Provider and API Key before testing")}};return(i.default.useEffect(()=>{r||x({})},[r]),(0,ek.isAdminRole)(e))?(0,t.jsxs)(_.Modal,{title:(0,t.jsxs)("div",{className:"flex items-center space-x-3 pb-4 border-b border-gray-100",children:[(0,t.jsx)("span",{className:"text-2xl",children:"🔍"}),(0,t.jsx)("h2",{className:"text-xl font-semibold text-gray-900",children:"Add New Search Tool"})]}),open:r,width:800,onCancel:()=>{o.resetFields(),x({}),n(!1)},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)(S.Form,{form:o,onFinish:k,onValuesChange:(e,t)=>x(t),layout:"vertical",className:"space-y-6",children:[(0,t.jsxs)("div",{className:"grid grid-cols-1 gap-6",children:[(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Search Tool Name",(0,t.jsx)(N.Tooltip,{title:"A unique name to identify this search tool configuration (e.g., 'perplexity-search', 'tavily-news-search').",children:(0,t.jsx)(B.InfoCircleOutlined,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:"search_tool_name",rules:[{required:!0,message:"Please enter a search tool name"},{pattern:/^[a-zA-Z0-9_-]+$/,message:"Name can only contain letters, numbers, hyphens, and underscores"}],children:(0,t.jsx)(eJ.TextInput,{placeholder:"e.g., perplexity-search, my-tavily-tool",className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"})}),(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Search Provider",(0,t.jsx)(N.Tooltip,{title:"Select the search provider you want to use. Each provider has different capabilities and pricing.",children:(0,t.jsx)(B.InfoCircleOutlined,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:"search_provider",rules:[{required:!0,message:"Please select a search provider"}],children:(0,t.jsx)(I.Select,{placeholder:"Select a search provider",className:"rounded-lg",size:"large",loading:v,showSearch:!0,optionFilterProp:"children",optionLabelProp:"label",children:w.map(e=>(0,t.jsx)(I.Select.Option,{value:e.provider_name,label:(0,t.jsx)(s8,{providerName:e.provider_name,displayName:e.ui_friendly_name}),children:(0,t.jsx)(s8,{providerName:e.provider_name,displayName:e.ui_friendly_name})},e.provider_name))})}),(0,t.jsx)(S.Form.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["API Key",(0,t.jsx)(N.Tooltip,{title:"The API key for authenticating with the search provider. This will be securely stored.",children:(0,t.jsx)(B.InfoCircleOutlined,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:"api_key",rules:[{required:!1,message:"Please enter an API key"}],children:(0,t.jsx)(eJ.TextInput,{type:"password",placeholder:"Enter your API key",className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"})}),(0,t.jsx)(S.Form.Item,{label:(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Description (Optional)"}),name:"description",children:(0,t.jsx)(s3,{rows:3,placeholder:"Brief description of this search tool's purpose",className:"rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"})})]}),(0,t.jsxs)("div",{className:"flex justify-between items-center pt-6 border-t border-gray-100",children:[(0,t.jsx)(N.Tooltip,{title:"Get help on our github",children:(0,t.jsx)(sR.Typography.Link,{href:"https://github.com/BerriAI/litellm/issues",target:"_blank",children:"Need Help?"})}),(0,t.jsxs)("div",{className:"space-x-2",children:[(0,t.jsx)(m.Button,{onClick:C,loading:g,children:"Test Connection"}),(0,t.jsx)(m.Button,{loading:d,type:"submit",children:"Add Search Tool"})]})]})]})}),(0,t.jsx)(_.Modal,{title:"Connection Test Results",open:p,onCancel:()=>{h(!1),y(!1)},footer:[(0,t.jsx)(m.Button,{onClick:()=>{h(!1),y(!1)},children:"Close"},"close")],width:700,children:p&&s&&(0,t.jsx)(s6,{litellmParams:{search_provider:u.search_provider,api_key:u.api_key,api_base:u.api_base},accessToken:s,onTestComplete:()=>y(!1)},j)})]}):null};var s9=e.i(678784),ae=e.i(118366),at=e.i(928685);let{Text:as}=sR.Typography,aa=({searchToolName:e,accessToken:s,className:a=""})=>{let[r,n]=(0,i.useState)(""),[o,d]=(0,i.useState)(!1),[c,m]=(0,i.useState)([]),[x,p]=(0,i.useState)({}),[h,g]=(0,i.useState)(!1),y=async()=>{if(!r.trim())return void T.message.warning("Please enter a search query");d(!0);let t=performance.now();try{let a=await (0,l.searchToolQueryCall)(s,e,r),i=performance.now(),n=Math.round(i-t),o={query:r,response:a,timestamp:Date.now(),latency:n};m(e=>[o,...e])}catch(e){console.error("Error querying search tool:",e),ez.default.fromBackend("Failed to query search tool")}finally{d(!1)}},j=e=>new Date(e).toLocaleString(),f=(0,t.jsx)(tk.LoadingOutlined,{style:{fontSize:24},spin:!0}),b=c.length>0?c[0]:null;return(0,t.jsxs)(u.Card,{className:"mt-6",children:[(0,t.jsx)("div",{className:"mb-6",children:(0,t.jsx)(eC.Title,{children:"Test Search Tool"})}),(0,t.jsxs)("div",{className:"flex flex-col",style:{minHeight:"600px"},children:[(0,t.jsx)("div",{className:"mb-6",children:(0,t.jsxs)("div",{className:"flex items-stretch gap-3",children:[(0,t.jsxs)("div",{className:"flex items-center flex-1 bg-white rounded-lg px-4 transition-all duration-200",style:{border:h?"2px solid #3b82f6":"2px solid #e5e7eb",boxShadow:h?"0 0 0 3px rgba(59, 130, 246, 0.1)":"0 1px 2px 0 rgba(0, 0, 0, 0.05)",height:"48px"},children:[(0,t.jsx)(at.SearchOutlined,{className:"text-gray-400 mr-3",style:{fontSize:"18px"}}),(0,t.jsx)(F.Input,{value:r,onChange:e=>n(e.target.value),onFocus:()=>g(!0),onBlur:()=>g(!1),onPressEnter:e=>{e.shiftKey||(e.preventDefault(),y())},placeholder:"Enter your search query...",disabled:o,bordered:!1,style:{fontSize:"15px",padding:0,height:"100%",boxShadow:"none"}})]}),(0,t.jsx)(G.Button,{type:"primary",onClick:y,disabled:o||!r.trim(),icon:(0,t.jsx)(at.SearchOutlined,{}),loading:o,style:{height:"48px",paddingLeft:"24px",paddingRight:"24px",borderRadius:"8px",fontWeight:500,fontSize:"15px",backgroundColor:o||!r.trim()?void 0:"#1890ff",borderColor:o||!r.trim()?void 0:"#1890ff",boxShadow:"0 1px 2px 0 rgba(0, 0, 0, 0.05)"},children:"Search"})]})}),(0,t.jsx)("div",{className:"flex-1",children:b||o?(0,t.jsxs)("div",{children:[o&&(0,t.jsxs)("div",{className:"flex flex-col justify-center items-center py-16",children:[(0,t.jsx)(eL.Spin,{indicator:f}),(0,t.jsx)(as,{className:"mt-4 text-gray-600 font-medium",children:"Searching..."})]}),b&&!o&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:"mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg",style:{boxShadow:"0 1px 2px 0 rgba(0, 0, 0, 0.05)"},children:(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsx)(as,{className:"text-xs font-semibold text-gray-500 uppercase tracking-wide",children:"Search Query"}),(0,t.jsx)("div",{className:"text-base font-semibold text-gray-900 mt-1.5",children:b.query})]}),(0,t.jsxs)("div",{className:"text-right ml-4",children:[(0,t.jsx)(as,{className:"text-xs text-gray-500",children:j(b.timestamp)}),(0,t.jsxs)("div",{className:"flex items-center gap-3 mt-1",children:[(0,t.jsxs)("div",{className:"text-sm font-semibold text-blue-600",children:[b.response?.results?.length||0," ",b.response?.results?.length===1?"result":"results"]}),void 0!==b.latency&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-gray-400",children:"•"}),(0,t.jsxs)("div",{className:"text-sm font-semibold text-green-600",children:[b.latency,"ms"]})]})]})]})]})}),b.response&&b.response.results&&b.response.results.length>0?(0,t.jsx)("div",{className:"space-y-3",children:b.response.results.map((e,s)=>{let a=x[`0-${s}`]||!1;return(0,t.jsx)("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden transition-all duration-200",style:{boxShadow:"0 1px 2px 0 rgba(0, 0, 0, 0.05)"},onMouseEnter:e=>{e.currentTarget.style.boxShadow="0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",e.currentTarget.style.borderColor="#e0e7ff"},onMouseLeave:e=>{e.currentTarget.style.boxShadow="0 1px 2px 0 rgba(0, 0, 0, 0.05)",e.currentTarget.style.borderColor="#e5e7eb"},children:(0,t.jsxs)("div",{className:"p-5",children:[(0,t.jsxs)("div",{className:"flex items-start justify-between gap-3 mb-2",children:[(0,t.jsx)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",className:"text-lg font-semibold text-blue-600 hover:text-blue-700 flex-1 leading-snug",style:{textDecoration:"none"},onMouseEnter:e=>e.currentTarget.style.textDecoration="underline",onMouseLeave:e=>e.currentTarget.style.textDecoration="none",children:e.title}),(0,t.jsx)(G.Button,{type:"text",size:"small",className:"flex-shrink-0",icon:(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:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})}),onClick:()=>window.open(e.url,"_blank"),style:{color:"#6b7280"}})]}),(0,t.jsx)("div",{className:"text-sm text-green-700 mb-3 truncate font-medium",children:e.url}),(0,t.jsx)("div",{className:"text-sm text-gray-700 leading-relaxed",children:a?e.snippet:`${e.snippet.substring(0,200)}${e.snippet.length>200?"...":""}`}),e.snippet.length>200&&(0,t.jsx)(G.Button,{type:"link",size:"small",className:"mt-3 p-0 h-auto",onClick:()=>{let e;return e=`0-${s}`,void p(t=>({...t,[e]:!t[e]}))},style:{fontSize:"13px",fontWeight:500,color:"#3b82f6"},children:a?"Show less":"Show more"})]})},s)})}):(0,t.jsxs)("div",{className:"text-center py-12 bg-gray-50 border border-gray-200 rounded-lg",children:[(0,t.jsx)("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mx-auto mb-4",children:(0,t.jsx)(at.SearchOutlined,{style:{fontSize:"24px",color:"#9ca3af"}})}),(0,t.jsx)(as,{className:"text-gray-600 font-medium",children:"No results found"}),(0,t.jsx)(as,{className:"text-sm text-gray-500 mt-1",children:"Try a different search query"})]})]}),c.length>1&&(0,t.jsxs)("div",{className:"mt-8 pt-6 border-t border-gray-200",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-4",children:[(0,t.jsx)(as,{className:"text-sm font-semibold text-gray-700",children:"Previous Searches"}),(0,t.jsx)(G.Button,{onClick:()=>{m([]),p({}),ez.default.success("Search history cleared")},size:"small",type:"link",style:{fontSize:"13px",fontWeight:500},children:"Clear All"})]}),(0,t.jsx)("div",{className:"space-y-2",children:c.slice(1,6).map((e,s)=>(0,t.jsxs)("div",{className:"p-3 bg-gray-50 border border-gray-200 rounded-lg cursor-pointer transition-all duration-200 hover:bg-gray-100 hover:border-gray-300",onClick:()=>{n(e.query)},children:[(0,t.jsx)("div",{className:"text-sm font-medium text-gray-800 truncate",children:e.query}),(0,t.jsxs)("div",{className:"text-xs text-gray-500 mt-1.5 flex items-center gap-2",children:[(0,t.jsxs)("span",{className:"font-medium text-blue-600",children:[e.response?.results?.length||0," ",e.response?.results?.length===1?"result":"results"]}),void 0!==e.latency&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{children:"•"}),(0,t.jsxs)("span",{className:"font-medium text-green-600",children:[e.latency,"ms"]})]}),(0,t.jsx)("span",{children:"•"}),(0,t.jsx)("span",{children:j(e.timestamp)})]})]},s+1))})]})]}):(0,t.jsxs)("div",{className:"h-full flex flex-col items-center justify-center p-8",children:[(0,t.jsx)("div",{className:"flex items-center justify-center w-24 h-24 rounded-full bg-gray-100 mb-6",children:(0,t.jsx)(at.SearchOutlined,{style:{fontSize:"48px",color:"#9ca3af"}})}),(0,t.jsx)(as,{className:"text-lg text-gray-600 font-medium",children:"Test your search tool"}),(0,t.jsx)(as,{className:"text-sm text-gray-500 mt-2",children:"Enter a query above to see search results"})]})})]})]})},al=({searchTool:e,onBack:s,isEditing:a,accessToken:l,availableProviders:r})=>{var n;let o,[d,c]=(0,i.useState)({}),x=async(e,t)=>{await (0,eB.copyToClipboard)(e)&&(c(e=>({...e,[t]:!0})),setTimeout(()=>{c(e=>({...e,[t]:!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)(m.Button,{icon:eM.ArrowLeftIcon,variant:"light",className:"mb-4",onClick:s,children:"Back to All Search Tools"}),(0,t.jsxs)("div",{className:"flex items-center cursor-pointer",children:[(0,t.jsx)(eC.Title,{children:e.search_tool_name}),(0,t.jsx)(G.Button,{type:"text",size:"small",icon:d["search-tool-name"]?(0,t.jsx)(s9.CheckIcon,{size:12}):(0,t.jsx)(ae.CopyIcon,{size:12}),onClick:()=>x(e.search_tool_name,"search-tool-name"),className:`left-2 z-10 transition-all duration-200 ${d["search-tool-name"]?"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)(b.Text,{className:"text-gray-500 font-mono",children:e.search_tool_id}),(0,t.jsx)(G.Button,{type:"text",size:"small",icon:d["search-tool-id"]?(0,t.jsx)(s9.CheckIcon,{size:12}):(0,t.jsx)(ae.CopyIcon,{size:12}),onClick:()=>x(e.search_tool_id,"search-tool-id"),className:`left-2 z-10 transition-all duration-200 ${d["search-tool-id"]?"text-green-600 bg-green-50 border-green-200":"text-gray-500 hover:text-gray-700 hover:bg-gray-100"}`})]})]})}),(0,t.jsxs)(t6.Grid,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,t.jsxs)(u.Card,{children:[(0,t.jsx)(b.Text,{children:"Provider"}),(0,t.jsx)("div",{className:"mt-2",children:(0,t.jsx)(eC.Title,{children:(n=e.litellm_params.search_provider,o=r.find(e=>e.provider_name===n),o?.ui_friendly_name||n)})})]}),(0,t.jsxs)(u.Card,{children:[(0,t.jsx)(b.Text,{children:"API Key"}),(0,t.jsx)("div",{className:"mt-2",children:(0,t.jsx)(b.Text,{children:e.litellm_params.api_key?"****":"Not set"})})]}),(0,t.jsxs)(u.Card,{children:[(0,t.jsx)(b.Text,{children:"Created At"}),(0,t.jsx)("div",{className:"mt-2",children:(0,t.jsx)(b.Text,{children:e.created_at?new Date(e.created_at).toLocaleString():"Unknown"})})]})]}),e.search_tool_info?.description&&(0,t.jsxs)(u.Card,{className:"mt-6",children:[(0,t.jsx)(b.Text,{children:"Description"}),(0,t.jsx)("div",{className:"mt-2",children:(0,t.jsx)(b.Text,{children:e.search_tool_info.description})})]}),(0,t.jsx)("div",{className:"mt-6",children:l&&(0,t.jsx)(aa,{searchToolName:e.search_tool_name,accessToken:l})})]})},ar=({accessToken:e,userRole:s,userID:a})=>{let{data:r,isLoading:n,refetch:o}=(0,t4.useQuery)({queryKey:["searchTools"],queryFn:()=>{if(!e)throw Error("Access Token required");return(0,l.fetchSearchTools)(e).then(e=>e.search_tools||[])},enabled:!!e}),{data:d,isLoading:c}=(0,t4.useQuery)({queryKey:["searchProviders"],queryFn:()=>{if(!e)throw Error("Access Token required");return(0,l.fetchAvailableSearchProviders)(e)},enabled:!!e}),u=d?.providers||[],[x,p]=(0,i.useState)(null),[h,g]=(0,i.useState)(!1),[y,j]=(0,i.useState)(!1),[f,v]=(0,i.useState)(null),[N,w]=(0,i.useState)(!1),[k,C]=(0,i.useState)(!1),[T,P]=(0,i.useState)(!1),[L]=S.Form.useForm(),M=i.default.useMemo(()=>{let e,s,a;return e=e=>{v(e),w(!1)},s=e=>{let t=r?.find(t=>t.search_tool_id===e);t&&(L.setFieldsValue({search_tool_name:t.search_tool_name,search_provider:t.litellm_params.search_provider,api_key:t.litellm_params.api_key,api_base:t.litellm_params.api_base,timeout:t.litellm_params.timeout,max_retries:t.litellm_params.max_retries,description:t.search_tool_info?.description}),v(e),P(!0))},a=D,[{title:"Search Tool ID",dataIndex:"search_tool_id",key:"search_tool_id",render:(s,a)=>a.is_from_config?(0,t.jsx)("span",{className:"text-xs",children:"-"}):(0,t.jsx)("button",{onClick:()=>e(a.search_tool_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 cursor-pointer max-w-40",children:(0,t.jsx)("span",{className:"truncate block",children:a.search_tool_id})})},{title:"Name",dataIndex:"search_tool_name",key:"search_tool_name",render:e=>(0,t.jsx)("span",{className:"font-medium",children:e})},{title:"Provider",key:"provider",render:(e,s)=>{let a=s.litellm_params.search_provider,l=u.find(e=>e.provider_name===a),r=l?.ui_friendly_name||a;return(0,t.jsx)("span",{className:"text-sm",children:r})}},{title:"Created At",dataIndex:"created_at",key:"created_at",render:(e,s)=>(0,t.jsx)("span",{className:"text-xs",children:s.created_at?new Date(s.created_at).toLocaleDateString():"-"})},{title:"Updated At",dataIndex:"updated_at",key:"updated_at",render:(e,s)=>(0,t.jsx)("span",{className:"text-xs",children:s.updated_at?new Date(s.updated_at).toLocaleDateString():"-"})},{title:"Source",key:"source",render:(e,s)=>{let a=s.is_from_config??!1;return(0,t.jsx)(A.Tag,{color:a?"default":"blue",children:a?"Config":"DB"})}},{title:"Actions",key:"actions",render:(e,l)=>{let r=l.search_tool_id,i=l.is_from_config??!1;return(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(eq.default,{variant:"Edit",tooltipText:"Edit search tool",disabled:i,disabledTooltipText:"Config search tool cannot be edited on the dashboard. Please edit it from the config file.",onClick:()=>{r&&!i&&s(r)}}),(0,t.jsx)(eq.default,{variant:"Delete",tooltipText:"Delete search tool",disabled:i,disabledTooltipText:"Config search tool cannot be deleted on the dashboard. Please delete it from the config file.",onClick:()=>{r&&!i&&a(r)}})]})}}]},[u,r,L]);function D(e){p(e),g(!0)}let E=async()=>{if(null!=x&&null!=e){j(!0);try{await (0,l.deleteSearchTool)(e,x),ez.default.success("Deleted search tool successfully"),g(!1),p(null),o()}catch(e){console.error("Error deleting the search tool:",e),ez.default.error("Failed to delete search tool")}finally{j(!1)}}},O=r?.find(e=>e.search_tool_id===x),R=O?u.find(e=>e.provider_name===O.litellm_params.search_provider):null,z=async()=>{if(e&&f)try{let t=await L.validateFields(),s={search_tool_name:t.search_tool_name,litellm_params:{search_provider:t.search_provider,api_key:t.api_key,api_base:t.api_base,timeout:t.timeout?parseFloat(t.timeout):void 0,max_retries:t.max_retries?parseInt(t.max_retries):void 0},search_tool_info:t.description?{description:t.description}:void 0};await (0,l.updateSearchTool)(e,f,s),ez.default.success("Search tool updated successfully"),P(!1),L.resetFields(),v(null),o()}catch(e){console.error("Failed to update search tool:",e),ez.default.error("Failed to update search tool")}};return e&&s&&a?(0,t.jsxs)("div",{className:"w-full h-full p-6",children:[(0,t.jsx)(sG.default,{isOpen:h,title:"Delete Search Tool",message:"Are you sure you want to delete this search tool? This action cannot be undone.",resourceInformationTitle:"Search Tool Information",resourceInformation:O?[{label:"Name",value:O.search_tool_name},{label:"ID",value:O.search_tool_id,code:!0},{label:"Provider",value:R?.ui_friendly_name||O.litellm_params.search_provider},{label:"Description",value:O.search_tool_info?.description||"-"}]:[],onCancel:()=>{g(!1),p(null)},onOk:E,confirmLoading:y}),(0,t.jsx)(s7,{userRole:s,accessToken:e,onCreateSuccess:e=>{C(!1),o()},isModalVisible:k,setModalVisible:C}),(0,t.jsx)(_.Modal,{title:"Edit Search Tool",open:T,onOk:z,onCancel:()=>{P(!1),L.resetFields(),v(null)},width:600,children:(0,t.jsxs)(S.Form,{form:L,layout:"vertical",children:[(0,t.jsx)(S.Form.Item,{name:"search_tool_name",label:"Search Tool Name",rules:[{required:!0,message:"Please enter a search tool name"}],children:(0,t.jsx)(F.Input,{placeholder:"e.g., my-perplexity-search"})}),(0,t.jsx)(S.Form.Item,{name:"search_provider",label:"Search Provider",rules:[{required:!0,message:"Please select a search provider"}],children:(0,t.jsx)(I.Select,{placeholder:"Select a search provider",loading:c,children:u.map(e=>(0,t.jsx)(I.Select.Option,{value:e.provider_name,children:e.ui_friendly_name},e.provider_name))})}),(0,t.jsx)(S.Form.Item,{name:"api_key",label:"API Key",extra:"API key for the search provider",children:(0,t.jsx)(F.Input.Password,{placeholder:"Enter API key"})}),(0,t.jsx)(S.Form.Item,{name:"description",label:"Description",children:(0,t.jsx)(F.Input.TextArea,{rows:3,placeholder:"Description of this search tool"})})]})}),(0,t.jsx)(eC.Title,{children:"Search Tools"}),(0,t.jsx)(b.Text,{className:"text-tremor-content mt-2",children:"Configure and manage your search providers"}),(0,ek.isAdminRole)(s)&&(0,t.jsx)(m.Button,{className:"mt-4 mb-4",onClick:()=>C(!0),children:"+ Add New Search Tool"}),(0,t.jsx)(()=>f?(0,t.jsx)(al,{searchTool:r?.find(e=>e.search_tool_id===f)||{search_tool_id:"",search_tool_name:"",litellm_params:{search_provider:""}},onBack:()=>{w(!1),v(null),o()},isEditing:N,accessToken:e,availableProviders:u}):(0,t.jsx)("div",{className:"w-full h-full",children:(0,t.jsx)(eL.Spin,{spinning:n,indicator:(0,t.jsx)(tk.LoadingOutlined,{spin:!0}),size:"large",children:(0,t.jsx)(ts.Table,{bordered:!0,dataSource:r||[],columns:M,rowKey:e=>e.search_tool_id||e.search_tool_name,pagination:!1,locale:{emptyText:"No search tools configured"},size:"small"})})}),{})]}):(console.log("Missing required authentication parameters",{accessToken:e,userRole:s,userID:a}),(0,t.jsx)("div",{className:"p-6 text-center text-gray-500",children:"Missing required authentication parameters."}))};var ai=e.i(700904),an=e.i(686311),ao=e.i(37727),ad=e.i(643531),ac=e.i(636772),am=e.i(115571);function au({onOpen:e,onDismiss:s,isVisible:a,title:l,description:r,buttonText:n,icon:o,accentColor:d,buttonStyle:c}){let m=(0,ac.useDisableShowPrompts)(),[u,x]=(0,i.useState)(100),[p,h]=(0,i.useState)(!1);return((0,i.useEffect)(()=>{if(!a){x(100),h(!1);return}let e=Date.now(),t=setInterval(()=>{let s=Math.max(0,100-(Date.now()-e)/15e3*100);x(s),s<=0&&clearInterval(t)},50);return()=>clearInterval(t)},[a]),(0,i.useEffect)(()=>{if(p){let e=setTimeout(()=>{h(!1),s()},5e3);return()=>clearTimeout(e)}},[p,s]),p)?(0,t.jsx)("div",{className:`fixed bottom-6 right-6 z-40 w-80 bg-white rounded-lg shadow-xl border border-gray-200 overflow-hidden transform transition-all duration-300 ease-out ${a?"translate-y-0 opacity-100 scale-100":"translate-y-4 opacity-0 scale-95"}`,children:(0,t.jsx)("div",{className:"p-4",children:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("div",{className:"flex-shrink-0 w-8 h-8 rounded-full bg-green-100 flex items-center justify-center",children:(0,t.jsx)(ad.Check,{className:"h-5 w-5 text-green-600"})}),(0,t.jsx)("div",{className:"flex-1",children:(0,t.jsx)("p",{className:"text-sm text-gray-700 font-medium",children:"Got it, we will not ask again. Reactivate this at any time in the User Menu."})})]})})}):!a||m?null:(0,t.jsxs)("div",{className:`fixed bottom-6 right-6 z-40 w-80 bg-white rounded-lg shadow-xl border border-gray-200 overflow-hidden transform transition-all duration-300 ease-out ${a?"translate-y-0 opacity-100 scale-100":"translate-y-4 opacity-0 scale-95"}`,children:[(0,t.jsx)("div",{className:"h-1 bg-gray-100 w-full",children:(0,t.jsx)("div",{className:"h-full transition-all duration-100 ease-linear",style:{width:`${u}%`,backgroundColor:d}})}),(0,t.jsxs)("div",{className:"p-4",children:[(0,t.jsxs)("div",{className:"flex items-start justify-between mb-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",style:{color:d},children:[(0,t.jsx)(o,{className:"h-5 w-5"}),(0,t.jsx)("span",{className:"font-semibold text-sm",children:l})]}),(0,t.jsx)("button",{onClick:s,className:"text-gray-400 hover:text-gray-600 transition-colors p-0.5 rounded hover:bg-gray-100",children:(0,t.jsx)(ao.X,{className:"h-4 w-4"})})]}),(0,t.jsx)("p",{className:"text-sm text-gray-600 mb-3",children:r}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(G.Button,{type:"primary",block:!0,onClick:e,style:c,children:n}),(0,t.jsx)(G.Button,{variant:"outlined",danger:!0,block:!0,onClick:()=>{(0,am.setLocalStorageItem)("disableShowPrompts","true"),(0,am.emitLocalStorageChange)("disableShowPrompts"),h(!0)},className:"text-xs",children:"Don't ask me again"})]})]})]})}function ax({onOpen:e,onDismiss:s,isVisible:a}){return(0,t.jsx)(au,{onOpen:e,onDismiss:s,isVisible:a,title:"Quick feedback",description:"Help us improve LiteLLM! Share your experience in 5 quick questions.",buttonText:"Share feedback",icon:an.MessageSquare,accentColor:"#3b82f6"})}var ap=e.i(972520),ah=e.i(180127),ah=ah,ag=e.i(497650),ay=e.i(536916);let aj=[{id:"oss_adoption",label:"OSS Adoption",description:"Stars, contributors, forks, community support"},{id:"ai_integration",label:"AI Integration",description:"LiteLLM had the logging/guardrail integration we needed - Langfuse, OTEL, S3 logging, Azure Content Safety guardrails"},{id:"unified_api",label:"Unified API",description:"LiteLLM had the best OpenAI-compatible API across providers - OpenAI, Anthropic, Gemini, etc."},{id:"breadth_of_models",label:"Breadth of Models/Providers",description:"LiteLLM had the provider + endpoint combinations we needed - /ocr endpoint with Mistral OCR, /batches endppint with Bedrock API, etc."},{id:"other",label:"Other",description:"Something else not listed above"}];function af({isOpen:e,onClose:s,onComplete:a}){let[l,r]=(0,i.useState)(1),[n,o]=(0,i.useState)({usingAtCompany:null,companyName:"",startDate:"",reasons:[],otherReason:"",email:""}),[d,c]=(0,i.useState)(!1),m=!0===n.usingAtCompany?5:4;if(!e)return null;let u=async()=>{c(!0);try{let e={oss_adoption:"OSS Adoption (stars, contributors, forks)",ai_integration:"AI Integration (Langfuse, OTEL, S3, Azure Content Safety)",unified_api:"Unified API (OpenAI-compatible)",breadth_of_models:"Breadth of Models/Providers (/ocr, /batches, Bedrock, Azure OCR)"},t=n.reasons.map(t=>"other"===t&&n.otherReason?`Other: ${n.otherReason}`:e[t]||t),s=new URLSearchParams({"entry.2015264290":n.usingAtCompany?"Yes":"No","entry.1876243786":n.companyName||"","entry.1282591459":n.startDate,"entry.393456108":t.join(", "),"entry.928142208":n.email||""});await fetch("https://feedback.litellm.ai/survey",{method:"POST",mode:"no-cors",body:s})}catch(e){console.error("Failed to submit survey:",e)}c(!1),a()},x=(e,t)=>{o(s=>({...s,[e]:t}))},p=e=>{o(t=>({...t,reasons:t.reasons.includes(e)?t.reasons.filter(t=>t!==e):[...t.reasons,e]}))},h=()=>{if(!1===n.usingAtCompany){if(1===l)return 1;if(3===l)return 2;if(4===l)return 3;if(5===l)return 4}return l},g=5===l;return(0,t.jsxs)("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6",children:[(0,t.jsx)("div",{className:"fixed inset-0 bg-black/40 backdrop-blur-sm",onClick:s}),(0,t.jsxs)("div",{className:"relative w-full max-w-lg bg-white rounded-xl shadow-2xl overflow-hidden flex flex-col max-h-[90vh] transform transition-all duration-300 ease-out",children:[(0,t.jsxs)("div",{className:"px-6 py-4 border-b border-gray-100 flex items-center justify-between bg-gray-50/50",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-blue-600",children:[(0,t.jsx)(an.MessageSquare,{className:"h-5 w-5"}),(0,t.jsx)("span",{className:"font-semibold text-sm tracking-wide uppercase",children:"Quick Feedback"})]}),(0,t.jsx)("button",{onClick:s,className:"text-gray-400 hover:text-gray-600 transition-colors p-1 rounded-full hover:bg-gray-100",children:(0,t.jsx)(ao.X,{className:"h-5 w-5"})})]}),(0,t.jsx)(ag.Progress,{percent:h()/m*100,showInfo:!1,strokeColor:"#2563eb",className:"m-0"}),(0,t.jsx)("div",{className:"p-8 flex-1 overflow-y-auto",children:1===l?(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsx)("h2",{className:"text-2xl font-bold text-gray-900",children:"Are you using LiteLLM at your company?"}),(0,t.jsx)("p",{className:"text-gray-500",children:"Help us understand how our product is being used in professional environments."}),(0,t.jsxs)("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4 pt-4",children:[(0,t.jsxs)("button",{onClick:()=>x("usingAtCompany",!0),className:`p-6 rounded-lg border-2 text-left transition-all ${!0===n.usingAtCompany?"border-blue-600 bg-blue-50 ring-1 ring-blue-600":"border-gray-200 hover:border-blue-300 hover:bg-gray-50"}`,children:[(0,t.jsx)("span",{className:"block text-lg font-semibold text-gray-900 mb-1",children:"Yes"}),(0,t.jsx)("span",{className:"text-sm text-gray-500",children:"We use it for work"})]}),(0,t.jsxs)("button",{onClick:()=>x("usingAtCompany",!1),className:`p-6 rounded-lg border-2 text-left transition-all ${!1===n.usingAtCompany?"border-blue-600 bg-blue-50 ring-1 ring-blue-600":"border-gray-200 hover:border-blue-300 hover:bg-gray-50"}`,children:[(0,t.jsx)("span",{className:"block text-lg font-semibold text-gray-900 mb-1",children:"No"}),(0,t.jsx)("span",{className:"text-sm text-gray-500",children:"Personal project / Hobby"})]})]})]}):2===l&&!0===n.usingAtCompany?(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsx)("h2",{className:"text-2xl font-bold text-gray-900",children:"What company are you using LiteLLM at?"}),(0,t.jsx)("p",{className:"text-gray-500",children:"This helps us understand our user base better."}),(0,t.jsx)(F.Input,{size:"large",placeholder:"Enter your company name",value:n.companyName,onChange:e=>x("companyName",e.target.value),autoFocus:!0})]}):3===l?(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsx)("h2",{className:"text-2xl font-bold text-gray-900",children:"When did you start using LiteLLM?"}),(0,t.jsx)(L.Radio.Group,{value:n.startDate,onChange:e=>x("startDate",e.target.value),className:"w-full",children:(0,t.jsx)(V.Space,{direction:"vertical",className:"w-full",children:["Less than a month ago","1-3 months ago","3-6 months ago","More than 6 months ago"].map(e=>(0,t.jsx)("label",{className:`flex items-center p-4 rounded-lg border cursor-pointer transition-all w-full ${n.startDate===e?"border-blue-600 bg-blue-50 ring-1 ring-blue-600":"border-gray-200 hover:bg-gray-50"}`,children:(0,t.jsx)(L.Radio,{value:e,children:e})},e))})})]}):4===l?(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsx)("h2",{className:"text-2xl font-bold text-gray-900",children:"Why did you pick LiteLLM over other AI Gateways?"}),(0,t.jsx)("p",{className:"text-gray-500",children:"Select all that apply."}),(0,t.jsx)("div",{className:"space-y-3",children:aj.map(e=>{let s=n.reasons.includes(e.id);return(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{role:"button",tabIndex:0,onClick:()=>p(e.id),onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),p(e.id))},className:`flex items-start p-4 rounded-lg border cursor-pointer transition-all ${s?"border-blue-600 bg-blue-50 ring-1 ring-blue-600":"border-gray-200 hover:bg-gray-50"}`,children:[(0,t.jsx)(ay.Checkbox,{checked:s,className:"mt-0.5 pointer-events-none"}),(0,t.jsxs)("div",{className:"ml-3",children:[(0,t.jsx)("span",{className:"block font-medium text-gray-900",children:e.label}),(0,t.jsx)("span",{className:"text-sm text-gray-500",children:e.description})]})]}),"other"===e.id&&s&&(0,t.jsx)(F.Input,{className:"mt-2 ml-7",placeholder:"Please specify...",value:n.otherReason,onChange:e=>x("otherReason",e.target.value),onClick:e=>e.stopPropagation(),autoFocus:!0})]},e.id)})})]}):5===l?(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsx)("h2",{className:"text-2xl font-bold text-gray-900",children:"Want to share more?"}),(0,t.jsx)("p",{className:"text-gray-500",children:"Leave your email and we may reach out to learn more about your experience. This is completely optional."}),(0,t.jsx)(F.Input,{size:"large",type:"email",placeholder:"your@email.com (optional)",value:n.email,onChange:e=>x("email",e.target.value),autoFocus:!0}),(0,t.jsx)("p",{className:"text-xs text-gray-400",children:"We will only use this to follow up on your feedback. No spam, ever."})]}):null}),(0,t.jsxs)("div",{className:"px-6 py-4 bg-gray-50 border-t border-gray-200 flex items-center justify-between",children:[(0,t.jsxs)("div",{className:"text-sm text-gray-500 font-medium",children:["Step ",h()," of ",m]}),(0,t.jsxs)("div",{className:"flex gap-3",children:[l>1&&(0,t.jsx)(G.Button,{onClick:()=>{3===l&&!1===n.usingAtCompany?r(1):r(l-1)},disabled:d,icon:(0,t.jsx)(ah.default,{className:"h-4 w-4"}),children:"Back"}),(0,t.jsxs)(G.Button,{type:"primary",onClick:()=>{1===l&&!1===n.usingAtCompany?r(3):l<5?r(l+1):u()},disabled:!(1===l?null!==n.usingAtCompany:2===l?n.companyName.trim().length>0:3===l?""!==n.startDate:4===l?n.reasons.includes("other")?n.reasons.length>0&&n.otherReason.trim().length>0:n.reasons.length>0:5===l)||d,loading:d,className:"min-w-[100px]",children:[g?"Submit":"Next",!g&&(0,t.jsx)(ap.ArrowRight,{className:"ml-2 h-4 w-4"})]})]})]})]})]})}var ab=e.i(758472);function a_({onOpen:e,onDismiss:s,isVisible:a}){return(0,t.jsx)(au,{onOpen:e,onDismiss:s,isVisible:a,title:"Claude Code Feedback",description:"Help us improve your Claude Code experience with LiteLLM! Share your feedback in 4 quick questions.",buttonText:"Share feedback",icon:ab.Code,accentColor:"#7c3aed",buttonStyle:{backgroundColor:"#7c3aed",borderColor:"#7c3aed"}})}function av({isOpen:e,onClose:s,onComplete:a}){return e?(0,t.jsxs)("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6",children:[(0,t.jsx)("div",{className:"fixed inset-0 bg-black/40 backdrop-blur-sm",onClick:s}),(0,t.jsxs)("div",{className:"relative w-full max-w-md bg-white rounded-xl shadow-2xl overflow-hidden transform transition-all duration-300 ease-out",children:[(0,t.jsxs)("div",{className:"px-6 py-4 border-b border-gray-100 flex items-center justify-between bg-gray-50/50",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-purple-600",children:[(0,t.jsx)(ab.Code,{className:"h-5 w-5"}),(0,t.jsx)("span",{className:"font-semibold text-sm tracking-wide uppercase",children:"Claude Code Feedback"})]}),(0,t.jsx)("button",{onClick:s,className:"text-gray-400 hover:text-gray-600 transition-colors p-1 rounded-full hover:bg-gray-100",children:(0,t.jsx)(ao.X,{className:"h-5 w-5"})})]}),(0,t.jsxs)("div",{className:"p-8",children:[(0,t.jsx)("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Help us improve your experience"}),(0,t.jsx)("p",{className:"text-gray-600 mb-6",children:"We'd love to hear about your experience using LiteLLM with Claude Code. Your feedback helps us improve the product for everyone."}),(0,t.jsx)("p",{className:"text-sm text-gray-500 mb-6",children:"This brief survey takes about 2-3 minutes to complete."}),(0,t.jsx)(G.Button,{type:"primary",size:"large",block:!0,onClick:()=>{window.open("https://forms.gle/LZeJQ3XytBakckYa9","_blank","noopener,noreferrer"),a()},icon:(0,t.jsx)(tU.ExternalLink,{className:"h-4 w-4"}),style:{backgroundColor:"#7c3aed",borderColor:"#7c3aed"},children:"Open Feedback Form"})]})]})]}):null}var aN=e.i(345244),aw=e.i(662316),ak=e.i(208075),aC=e.i(735042),aS=e.i(693569),aT=e.i(263147),aI=e.i(954616),aF=e.i(912598);let aP=async(e,t)=>{let s=(0,l.getProxyBaseUrl)(),a=`${s}/v1/access_group/${encodeURIComponent(t)}`,r=await fetch(a,{method:"DELETE",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!r.ok){let e=await r.json(),t=(0,l.deriveErrorMessage)(e);throw(0,l.handleError)(t),Error(t)}};var aL=e.i(152990),aA=e.i(682830),aM=e.i(525720),aD=e.i(372943),aE=e.i(95684),aO=e.i(368869),aR=e.i(657150),aR=aR,az=e.i(475254);let aB=(0,az.default)("layers",[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]]);var aq=e.i(988846),a$=e.i(302202),aU=e.i(446891);let aH=async(e,t)=>{let s=(0,l.getProxyBaseUrl)(),a=`${s}/v1/access_group/${encodeURIComponent(t)}`,r=await fetch(a,{method:"GET",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!r.ok){let e=await r.json(),t=(0,l.deriveErrorMessage)(e);throw(0,l.handleError)(t),Error(t)}return r.json()};var aV=e.i(21548),aG=e.i(573421),aK=e.i(516430),aR=aR,aW=e.i(823429),aW=aW,aQ=e.i(438100),aY=e.i(98740),aY=aY,aJ=e.i(304911),aX=e.i(289793),aZ=e.i(500727),aR=aR,a0=e.i(168118);let{TextArea:a1}=F.Input;function a2({form:e,isNameDisabled:s=!1}){let{data:a}=(0,aX.useAgents)(),{data:l}=(0,aZ.useMCPServers)(),r=a?.agents??[],i=[{key:"1",label:(0,t.jsxs)(V.Space,{align:"center",size:4,children:[(0,t.jsx)(a0.InfoIcon,{size:16}),"General Info"]}),children:(0,t.jsxs)("div",{style:{paddingTop:16},children:[(0,t.jsx)(S.Form.Item,{name:"name",label:"Group Name",rules:[{required:!0,message:"Please enter the access group name"}],children:(0,t.jsx)(F.Input,{placeholder:"e.g. Engineering Team",disabled:s})}),(0,t.jsx)(S.Form.Item,{name:"description",label:"Description",children:(0,t.jsx)(a1,{rows:4,placeholder:"Describe the purpose of this access group..."})})]})},{key:"2",label:(0,t.jsxs)(V.Space,{align:"center",size:4,children:[(0,t.jsx)(aB,{size:16}),"Models"]}),children:(0,t.jsx)("div",{style:{paddingTop:16},children:(0,t.jsx)(S.Form.Item,{name:"modelIds",label:"Allowed Models",children:(0,t.jsx)(sK.ModelSelect,{context:"global",value:e.getFieldValue("modelIds")??[],onChange:t=>e.setFieldsValue({modelIds:t}),style:{width:"100%"}})})})},{key:"3",label:(0,t.jsxs)(V.Space,{align:"center",size:4,children:[(0,t.jsx)(a$.ServerIcon,{size:16}),"MCP Servers"]}),children:(0,t.jsx)("div",{style:{paddingTop:16},children:(0,t.jsx)(S.Form.Item,{name:"mcpServerIds",label:"Allowed MCP Servers",children:(0,t.jsx)(I.Select,{mode:"multiple",placeholder:"Select MCP servers",style:{width:"100%"},optionFilterProp:"label",allowClear:!0,options:(l??[]).map(e=>({label:e.server_name??e.server_id,value:e.server_id}))})})})},{key:"4",label:(0,t.jsxs)(V.Space,{align:"center",size:4,children:[(0,t.jsx)(aR.default,{size:16}),"Agents"]}),children:(0,t.jsx)("div",{style:{paddingTop:16},children:(0,t.jsx)(S.Form.Item,{name:"agentIds",label:"Allowed Agents",children:(0,t.jsx)(I.Select,{mode:"multiple",placeholder:"Select agents",style:{width:"100%"},optionFilterProp:"label",allowClear:!0,options:r.map(e=>({label:e.agent_name,value:e.agent_id}))})})})}];return(0,t.jsx)(S.Form,{form:e,layout:"vertical",name:"access_group_form",initialValues:{modelIds:[],mcpServerIds:[],agentIds:[]},children:(0,t.jsx)(t3.Tabs,{defaultActiveKey:"1",items:i})})}let a4=async(e,t,s)=>{let a=(0,l.getProxyBaseUrl)(),r=`${a}/v1/access_group/${encodeURIComponent(t)}`,i=await fetch(r,{method:"PUT",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(s)});if(!i.ok){let e=await i.json(),t=(0,l.deriveErrorMessage)(e);throw(0,l.handleError)(t),Error(t)}return i.json()};function a5({visible:e,accessGroup:s,onCancel:a,onSuccess:l}){let[n]=S.Form.useForm(),o=(()=>{let{accessToken:e}=(0,r.default)(),t=(0,aF.useQueryClient)();return(0,aI.useMutation)({mutationFn:async({accessGroupId:t,params:s})=>{if(!e)throw Error("Access token is required");return a4(e,t,s)},onSuccess:(e,{accessGroupId:s})=>{t.invalidateQueries({queryKey:aT.accessGroupKeys.all}),t.invalidateQueries({queryKey:aT.accessGroupKeys.detail(s)})}})})();return(0,i.useEffect)(()=>{e&&s&&n.setFieldsValue({name:s.access_group_name,description:s.description??"",modelIds:s.access_model_names??[],mcpServerIds:s.access_mcp_server_ids??[],agentIds:s.access_agent_ids??[]})},[e,s,n]),(0,t.jsx)(_.Modal,{title:"Edit Access Group",open:e,onOk:()=>{n.validateFields().then(e=>{let t={access_group_name:e.name,description:e.description,access_model_names:e.modelIds,access_mcp_server_ids:e.mcpServerIds,access_agent_ids:e.agentIds};o.mutate({accessGroupId:s.access_group_id,params:t},{onSuccess:()=>{T.message.success("Access group updated successfully"),l?.(),a()}})}).catch(e=>{console.log("Validate Failed:",e)})},onCancel:a,width:700,okText:"Save Changes",cancelText:"Cancel",confirmLoading:o.isPending,destroyOnHidden:!0,children:(0,t.jsx)(a2,{form:n})})}let{Title:a6,Text:a3}=sR.Typography,{Content:a8}=aD.Layout;function a7({accessGroupId:e,onBack:s}){let{data:a,isLoading:l}=(e=>{let{accessToken:t,userRole:s}=(0,r.default)(),a=(0,aF.useQueryClient)();return(0,t4.useQuery)({queryKey:aT.accessGroupKeys.detail(e),queryFn:async()=>aH(t,e),enabled:!!(t&&e)&&ek.all_admin_roles.includes(s||""),initialData:()=>{if(!e)return;let t=a.getQueryData(aT.accessGroupKeys.list({}));return t?.find(t=>t.access_group_id===e)}})})(e),{token:n}=aO.theme.useToken(),[o,d]=(0,i.useState)(!1),[c,m]=(0,i.useState)(!1),[u,x]=(0,i.useState)(!1);if(l)return(0,t.jsx)(a8,{style:{padding:n.paddingLG,paddingInline:2*n.paddingLG},children:(0,t.jsx)(aM.Flex,{justify:"center",align:"center",style:{minHeight:300},children:(0,t.jsx)(eL.Spin,{size:"large"})})});if(!a)return(0,t.jsxs)(a8,{style:{padding:n.paddingLG,paddingInline:2*n.paddingLG},children:[(0,t.jsx)(G.Button,{icon:(0,t.jsx)(aK.ArrowLeftIcon,{size:16}),onClick:s,type:"text",style:{marginBottom:16}}),(0,t.jsx)(aV.Empty,{description:"Access group not found"})]});let p=a.access_model_names??[],h=a.access_mcp_server_ids??[],g=a.access_agent_ids??[],y=a.assigned_key_ids??[],j=a.assigned_team_ids??[],f=c?y:y.slice(0,5),b=u?j:j.slice(0,5),_=[{key:"models",label:(0,t.jsxs)(aM.Flex,{align:"center",gap:8,children:[(0,t.jsx)(aB,{size:16}),"Models",(0,t.jsx)(A.Tag,{style:{marginInlineEnd:0},children:p?.length})]}),children:p?.length>0?(0,t.jsx)(aG.List,{grid:{gutter:16,xs:1,sm:2,md:3,lg:4},dataSource:p,renderItem:e=>(0,t.jsx)(aG.List.Item,{children:(0,t.jsx)(tl.Card,{size:"small",children:(0,t.jsx)(a3,{code:!0,children:e})})})}):(0,t.jsx)(aV.Empty,{description:"No models assigned to this group"})},{key:"mcp",label:(0,t.jsxs)(aM.Flex,{align:"center",gap:8,children:[(0,t.jsx)(a$.ServerIcon,{size:16}),"MCP Servers",(0,t.jsx)(A.Tag,{children:h?.length})]}),children:h?.length>0?(0,t.jsx)(aG.List,{grid:{gutter:16,xs:1,sm:2,md:3,lg:4},dataSource:h,renderItem:e=>(0,t.jsx)(aG.List.Item,{children:(0,t.jsx)(tl.Card,{size:"small",children:(0,t.jsx)(a3,{code:!0,children:e})})})}):(0,t.jsx)(aV.Empty,{description:"No MCP servers assigned to this group"})},{key:"agents",label:(0,t.jsxs)(aM.Flex,{align:"center",gap:8,children:[(0,t.jsx)(aR.default,{size:16}),"Agents",(0,t.jsx)(A.Tag,{children:g?.length})]}),children:g?.length>0?(0,t.jsx)(aG.List,{grid:{gutter:16,xs:1,sm:2,md:3,lg:4},dataSource:g,renderItem:e=>(0,t.jsx)(aG.List.Item,{children:(0,t.jsx)(tl.Card,{size:"small",children:(0,t.jsx)(a3,{code:!0,children:e})})})}):(0,t.jsx)(aV.Empty,{description:"No agents assigned to this group"})}];return(0,t.jsxs)(a8,{style:{padding:n.paddingLG,paddingInline:2*n.paddingLG},children:[(0,t.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:24},children:[(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:16},children:[(0,t.jsx)(G.Button,{icon:(0,t.jsx)(aK.ArrowLeftIcon,{size:16}),onClick:s,type:"text"}),(0,t.jsxs)("div",{children:[(0,t.jsx)(a6,{level:2,style:{margin:0},children:a.access_group_name}),(0,t.jsxs)(a3,{type:"secondary",children:["ID: ",(0,t.jsx)(a3,{copyable:!0,children:a.access_group_id})]})]})]}),(0,t.jsx)(G.Button,{type:"primary",icon:(0,t.jsx)(aW.default,{size:16}),onClick:()=>{d(!0)},children:"Edit Access Group"})]}),(0,t.jsx)(tN.Row,{style:{marginBottom:24},children:(0,t.jsx)(tl.Card,{children:(0,t.jsxs)(eA.Descriptions,{title:"Group Details",column:1,children:[(0,t.jsx)(eA.Descriptions.Item,{label:"Description",children:a.description||"—"}),(0,t.jsxs)(eA.Descriptions.Item,{label:"Created",children:[new Date(a.created_at).toLocaleString(),a.created_by&&(0,t.jsxs)(a3,{children:[" ","by"," ",(0,t.jsx)(aJ.default,{userId:a.created_by})]})]}),(0,t.jsxs)(eA.Descriptions.Item,{label:"Last Updated",children:[new Date(a.updated_at).toLocaleString(),a.updated_by&&(0,t.jsxs)(a3,{children:[" ","by"," ",(0,t.jsx)(aJ.default,{userId:a.updated_by})]})]})]})})}),(0,t.jsxs)(tN.Row,{gutter:[16,16],style:{marginBottom:24},children:[(0,t.jsx)(tw.Col,{xs:24,lg:12,children:(0,t.jsx)(tl.Card,{title:(0,t.jsxs)(aM.Flex,{align:"center",gap:8,children:[(0,t.jsx)(aQ.KeyIcon,{size:16}),"Attached Keys",(0,t.jsx)(A.Tag,{children:y?.length})]}),extra:y?.length>5?(0,t.jsx)(G.Button,{type:"link",onClick:()=>m(!c),children:c?"Show Less":`View All (${y?.length})`}):null,children:y?.length>0?(0,t.jsx)(aM.Flex,{wrap:"wrap",gap:8,children:f.map(e=>(0,t.jsx)(A.Tag,{children:(0,t.jsx)(a3,{code:!0,style:{fontSize:12},children:e.length>20?`${e.slice(0,10)}...${e.slice(-6)}`:e})},e))}):(0,t.jsx)(aV.Empty,{description:"No keys attached",image:aV.Empty.PRESENTED_IMAGE_SIMPLE})})}),(0,t.jsx)(tw.Col,{xs:24,lg:12,children:(0,t.jsx)(tl.Card,{title:(0,t.jsxs)(aM.Flex,{align:"center",gap:8,children:[(0,t.jsx)(aY.default,{size:16}),"Attached Teams",(0,t.jsx)(A.Tag,{children:j?.length})]}),extra:j?.length>5?(0,t.jsx)(G.Button,{type:"link",onClick:()=>x(!u),children:u?"Show Less":`View All (${j?.length})`}):null,children:j?.length>0?(0,t.jsx)(aM.Flex,{wrap:"wrap",gap:8,children:b.map(e=>(0,t.jsx)(A.Tag,{children:(0,t.jsx)(a3,{code:!0,style:{fontSize:12},children:e})},e))}):(0,t.jsx)(aV.Empty,{description:"No teams attached",image:aV.Empty.PRESENTED_IMAGE_SIMPLE})})})]}),(0,t.jsx)(tl.Card,{children:(0,t.jsx)(t3.Tabs,{defaultActiveKey:"models",items:_})}),(0,t.jsx)(a5,{visible:o,accessGroup:a,onCancel:()=>d(!1)})]})}let a9=async(e,t)=>{let s=(0,l.getProxyBaseUrl)(),a=`${s}/v1/access_group`,r=await fetch(a,{method:"POST",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let e=await r.json(),t=(0,l.deriveErrorMessage)(e);throw(0,l.handleError)(t),Error(t)}return r.json()};function le({visible:e,onCancel:s,onSuccess:a}){let[l]=S.Form.useForm(),i=(()=>{let{accessToken:e}=(0,r.default)(),t=(0,aF.useQueryClient)();return(0,aI.useMutation)({mutationFn:async t=>{if(!e)throw Error("Access token is required");return a9(e,t)},onSuccess:()=>{t.invalidateQueries({queryKey:aT.accessGroupKeys.all})}})})();return(0,t.jsx)(_.Modal,{title:"Create Access Group",open:e,onOk:()=>{l.validateFields().then(e=>{let t={access_group_name:e.name,description:e.description,access_model_names:e.modelIds,access_mcp_server_ids:e.mcpServerIds,access_agent_ids:e.agentIds};i.mutate(t,{onSuccess:()=>{T.message.success("Access group created successfully"),l.resetFields(),a?.(),s()}})}).catch(e=>{console.log("Validate Failed:",e)})},onCancel:s,width:700,okText:"Create Group",cancelText:"Cancel",confirmLoading:i.isPending,destroyOnClose:!0,children:(0,t.jsx)(a2,{form:l})})}let{Title:lt,Text:ls}=sR.Typography,{Content:la}=aD.Layout;function ll(e){return{id:e.access_group_id,name:e.access_group_name,description:e.description??"",modelIds:e.access_model_names,mcpServerIds:e.access_mcp_server_ids,agentIds:e.access_agent_ids,keyIds:e.assigned_key_ids,teamIds:e.assigned_team_ids,createdAt:e.created_at,createdBy:e.created_by??"",updatedAt:e.updated_at,updatedBy:e.updated_by??""}}function lr(){let{token:e}=aO.theme.useToken(),{data:s,isLoading:a}=(0,aT.useAccessGroups)(),l=(0,i.useMemo)(()=>(s??[]).map(ll),[s]),[n,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(!1),[m,u]=(0,i.useState)(""),[x,p]=(0,i.useState)(1),[h,g]=(0,i.useState)([]),[y,j]=(0,i.useState)(null),f=(()=>{let{accessToken:e}=(0,r.default)(),t=(0,aF.useQueryClient)();return(0,aI.useMutation)({mutationFn:async t=>{if(!e)throw Error("Access token is required");return aP(e,t)},onSuccess:()=>{t.invalidateQueries({queryKey:aT.accessGroupKeys.all})}})})();(0,i.useEffect)(()=>{p(1)},[m]);let b=(0,i.useMemo)(()=>l.filter(e=>e.name.toLowerCase().includes(m.toLowerCase())||e.id.toLowerCase().includes(m.toLowerCase())||e.description.toLowerCase().includes(m.toLowerCase())),[l,m]),_=(0,i.useMemo)(()=>[{id:"id",accessorKey:"id",header:()=>(0,t.jsx)("span",{children:"ID"}),enableSorting:!1,size:170,cell:({row:e})=>{let s=e.original;return(0,t.jsx)(N.Tooltip,{title:s.id,children:(0,t.jsx)(ls,{ellipsis:!0,className:"text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs cursor-pointer",style:{fontSize:14,padding:"1px 8px"},onClick:()=>o(s.id),children:s.id})})}},{id:"name",accessorKey:"name",header:()=>(0,t.jsx)("span",{children:"Name"}),enableSorting:!0,cell:({getValue:e})=>e()},{id:"resources",header:()=>(0,t.jsx)("span",{children:"Resources"}),enableSorting:!1,cell:({row:e})=>{let s=e.original,a=s.modelIds??[],l=s.mcpServerIds??[],r=s.agentIds??[];return(0,t.jsxs)(aM.Flex,{gap:12,align:"center",children:[(0,t.jsx)(N.Tooltip,{title:`${a?.length} Models`,children:(0,t.jsx)(A.Tag,{color:"blue",style:{fontSize:14,padding:"2px 8px",margin:0},children:(0,t.jsxs)(aM.Flex,{align:"center",gap:6,children:[(0,t.jsx)(aB,{size:14}),a?.length]})})}),(0,t.jsx)(N.Tooltip,{title:`${l?.length} MCP Servers`,children:(0,t.jsx)(A.Tag,{color:"cyan",style:{fontSize:14,padding:"2px 8px",margin:0},children:(0,t.jsxs)(aM.Flex,{align:"center",gap:6,children:[(0,t.jsx)(a$.ServerIcon,{size:14}),l?.length]})})}),(0,t.jsx)(N.Tooltip,{title:`${r?.length} Agents`,children:(0,t.jsx)(A.Tag,{color:"purple",style:{fontSize:14,padding:"2px 8px",margin:0},children:(0,t.jsxs)(aM.Flex,{align:"center",gap:6,children:[(0,t.jsx)(aR.default,{size:14}),r?.length]})})})]})}},{id:"createdAt",accessorKey:"createdAt",header:()=>(0,t.jsx)("span",{children:"Created"}),enableSorting:!0,sortingFn:"datetime",cell:({getValue:e})=>new Date(e()).toLocaleDateString(),meta:{responsive:["lg"]}},{id:"updatedAt",accessorKey:"updatedAt",header:()=>(0,t.jsx)("span",{children:"Updated"}),enableSorting:!1,cell:({getValue:e})=>new Date(e()).toLocaleDateString(),meta:{responsive:["xl"]}},{id:"actions",header:()=>(0,t.jsx)("span",{children:"Actions"}),enableSorting:!1,cell:({row:e})=>(0,t.jsx)(V.Space,{children:(0,t.jsx)(eq.default,{variant:"Delete",tooltipText:"Delete access group",onClick:()=>j(e.original)})})}],[]),v=(0,aL.useReactTable)({data:b,columns:_,state:{sorting:h},onSortingChange:g,getCoreRowModel:(0,aA.getCoreRowModel)(),getSortedRowModel:(0,aA.getSortedRowModel)(),getRowId:e=>e.id}),w=v.getRowModel().rows,k=w.slice((x-1)*10,10*x),C=(0,i.useMemo)(()=>new Map(k.map(e=>[e.original.id,e])),[k]),S=(v.getHeaderGroups()[0]?.headers??[]).map(e=>{let s=e.column.getCanSort(),a=e.column.getIsSorted(),l=e.column.columnDef.meta,r={title:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:4},children:[e.isPlaceholder?null:(0,aL.flexRender)(e.column.columnDef.header,e.getContext()),s&&(0,t.jsx)(aU.TableHeaderSortDropdown,{sortState:!1!==a&&a,onSortChange:t=>{g(!1===t?[]:[{id:e.column.id,desc:"desc"===t}])},columnId:e.column.id})]}),key:e.id,width:e.column.columnDef.size,render:(t,s)=>{let a=C.get(s.id);if(!a)return null;let l=a.getVisibleCells().find(t=>t.column.id===e.id);return l?(0,aL.flexRender)(l.column.columnDef.cell,l.getContext()):null}};return l?.responsive&&(r.responsive=l.responsive),r}),T=k.map(e=>e.original);return n?(0,t.jsx)(a7,{accessGroupId:n,onBack:()=>o(null)}):(0,t.jsxs)(la,{style:{padding:e.paddingLG,paddingInline:2*e.paddingLG},children:[(0,t.jsxs)(aM.Flex,{justify:"space-between",align:"center",style:{marginBottom:16},children:[(0,t.jsxs)(V.Space,{direction:"vertical",size:0,children:[(0,t.jsx)(lt,{level:2,style:{margin:0},children:"Access Groups"}),(0,t.jsx)(ls,{type:"secondary",children:"Manage resource permissions for your organization"})]}),(0,t.jsx)(G.Button,{type:"primary",icon:(0,t.jsx)(K.PlusOutlined,{}),onClick:()=>c(!0),children:"Create Access Group"})]}),(0,t.jsxs)(tl.Card,{styles:{body:{padding:0}},children:[(0,t.jsxs)(aM.Flex,{justify:"space-between",align:"center",style:{padding:"12px 16px"},children:[(0,t.jsx)(F.Input,{prefix:(0,t.jsx)(aq.SearchIcon,{size:16}),placeholder:"Search groups by name, ID, or description...",style:{maxWidth:400},value:m,onChange:e=>u(e.target.value),allowClear:!0}),(0,t.jsx)(aE.Pagination,{current:x,total:w?.length,pageSize:10,onChange:e=>p(e),size:"small",showTotal:e=>`${e} groups`,showSizeChanger:!1})]}),(0,t.jsx)(ts.Table,{columns:S,dataSource:T,rowKey:"id",loading:a,pagination:!1})]}),(0,t.jsx)(le,{visible:d,onCancel:()=>c(!1)}),(0,t.jsx)(sG.default,{isOpen:!!y,title:"Delete Access Group",message:"Are you sure you want to delete this access group? This action cannot be undone.",resourceInformationTitle:"Access Group Information",resourceInformation:[{label:"ID",value:y?.id,code:!0},{label:"Name",value:y?.name},{label:"Description",value:y?.description||"—"}],onCancel:()=>j(null),onOk:()=>{y&&f.mutate(y.id,{onSuccess:()=>{j(null)}})},confirmLoading:f.isPending})]})}var li=e.i(510674),ln=e.i(785242);let lo={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M484 443.1V528h-84.5c-4.1 0-7.5 3.1-7.5 7v42c0 3.8 3.4 7 7.5 7H484v84.9c0 3.9 3.2 7.1 7 7.1h42c3.9 0 7-3.2 7-7.1V584h84.5c4.1 0 7.5-3.2 7.5-7v-42c0-3.9-3.4-7-7.5-7H540v-84.9c0-3.9-3.1-7.1-7-7.1h-42c-3.8 0-7 3.2-7 7.1zm396-144.7H521L403.7 186.2a8.15 8.15 0 00-5.5-2.2H144c-17.7 0-32 14.3-32 32v592c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V330.4c0-17.7-14.3-32-32-32zM840 768H184V256h188.5l119.6 114.4H840V768z"}}]},name:"folder-add",theme:"outlined"};var ld=i.forwardRef(function(e,t){return i.createElement(tL.default,(0,tF.default)({},e,{ref:t,icon:lo}))});let lc=async(e,t)=>{let s=(0,l.getProxyBaseUrl)(),a=`${s}/project/new`,r=await fetch(a,{method:"POST",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let e=await r.json(),t=(0,l.deriveErrorMessage)(e);throw(0,l.handleError)(t),Error(t)}return r.json()};function lm({form:e}){let{accessToken:s,userId:a,userRole:l}=(0,r.default)(),{data:n}=(0,ln.useTeams)(),[o,d]=(0,i.useState)(null),[c,m]=(0,i.useState)([]),u=S.Form.useWatch("team_id",e);return(0,i.useEffect)(()=>{if(u&&n){let e=n.find(e=>e.team_id===u)??null;e&&e.team_id!==o?.team_id&&d(e)}},[u,n,o?.team_id]),(0,i.useEffect)(()=>{a&&l&&s&&o?(0,sJ.fetchTeamModels)(a,l,s,o.team_id).then(e=>{m(Array.from(new Set([...o.models??[],...e])))}):m([])},[o,s,a,l]),(0,t.jsxs)(S.Form,{form:e,layout:"vertical",name:"project_form",initialValues:{isBlocked:!1},style:{marginTop:24},children:[(0,t.jsx)(sR.Typography.Text,{strong:!0,style:{fontSize:13,color:"#374151",textTransform:"uppercase",letterSpacing:"0.05em"},children:"Basic Information"}),(0,t.jsx)(M.Divider,{style:{marginTop:8,marginBottom:16}}),(0,t.jsxs)(tN.Row,{gutter:24,children:[(0,t.jsx)(tw.Col,{span:12,children:(0,t.jsx)(S.Form.Item,{name:"project_alias",label:"Project Name",rules:[{required:!0,message:"Please enter a project name"}],children:(0,t.jsx)(F.Input,{placeholder:"e.g. Customer Support Bot"})})}),(0,t.jsx)(tw.Col,{span:12,children:(0,t.jsx)(S.Form.Item,{name:"team_id",label:"Team",rules:[{required:!0,message:"Please select a team"}],children:(0,t.jsx)(I.Select,{showSearch:!0,placeholder:"Search or select a team",onChange:t=>{d(n?.find(e=>e.team_id===t)??null),e.setFieldValue("models",[])},allowClear:!0,optionLabelProp:"label",filterOption:(e,t)=>{let s=n?.find(e=>e.team_id===t?.value);if(!s)return!1;let a=e.toLowerCase().trim();return(s.team_alias||"").toLowerCase().includes(a)||s.team_id.toLowerCase().includes(a)},children:n?.map(e=>(0,t.jsxs)(I.Select.Option,{value:e.team_id,label:e.team_alias||e.team_id,children:[(0,t.jsx)("span",{style:{fontWeight:500},children:e.team_alias})," ",(0,t.jsxs)("span",{style:{color:"#9ca3af"},children:["(",e.team_id,")"]})]},e.team_id))})})})]}),(0,t.jsx)(tN.Row,{children:(0,t.jsx)(tw.Col,{span:24,children:(0,t.jsx)(S.Form.Item,{name:"description",label:"Description",children:(0,t.jsx)(F.Input.TextArea,{placeholder:"Describe the purpose of this project",rows:3})})})}),(0,t.jsx)(tN.Row,{children:(0,t.jsx)(tw.Col,{span:24,children:(0,t.jsx)(S.Form.Item,{name:"models",label:"Allowed Models (scoped to selected team's models)",help:o?void 0:"Select a team first to see available models",children:(0,t.jsxs)(I.Select,{mode:"multiple",placeholder:o?"Select models":"Select a team first",disabled:!o,allowClear:!0,maxTagCount:"responsive",onChange:t=>{t.includes("all-team-models")&&e.setFieldsValue({models:["all-team-models"]})},children:[(0,t.jsx)(I.Select.Option,{value:"all-team-models",children:"All Team Models"},"all-team-models"),c.map(e=>(0,t.jsx)(I.Select.Option,{value:e,children:(0,$.getModelDisplayName)(e)},e))]})})})}),(0,t.jsx)(tN.Row,{gutter:24,children:(0,t.jsx)(tw.Col,{span:12,children:(0,t.jsx)(S.Form.Item,{name:"max_budget",label:"Max Budget (USD)",children:(0,t.jsx)(D.InputNumber,{prefix:"$",style:{width:"100%"},placeholder:"0.00",min:0,precision:2})})})}),(0,t.jsx)(tN.Row,{children:(0,t.jsx)(tw.Col,{span:24,children:(0,t.jsx)(H.Collapse,{ghost:!0,style:{background:"#f9fafb",borderRadius:8,border:"1px solid #e5e7eb"},items:[{key:"1",label:(0,t.jsx)(sR.Typography.Text,{strong:!0,style:{color:"#374151"},children:"Advanced Settings"}),children:(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(aM.Flex,{align:"center",gap:12,children:[(0,t.jsx)(sR.Typography.Text,{strong:!0,children:"Block Project"}),(0,t.jsx)(S.Form.Item,{name:"isBlocked",valuePropName:"checked",noStyle:!0,children:(0,t.jsx)(k.Switch,{})})]}),(0,t.jsx)(S.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.isBlocked!==t.isBlocked,children:({getFieldValue:e})=>e("isBlocked")?(0,t.jsx)(v.Alert,{banner:!0,type:"warning",showIcon:!0,message:"All API requests using keys under this project will be rejected.",style:{marginTop:12}}):null}),(0,t.jsx)(M.Divider,{}),(0,t.jsx)(sR.Typography.Text,{strong:!0,style:{display:"block",marginBottom:12},children:"Model-Specific Limits"}),(0,t.jsx)(S.Form.List,{name:"modelLimits",children:(s,{add:a,remove:l})=>(0,t.jsxs)(t.Fragment,{children:[s.map(({key:s,name:a,...r})=>(0,t.jsxs)(V.Space,{style:{display:"flex",marginBottom:8},align:"baseline",children:[(0,t.jsx)(S.Form.Item,{...r,name:[a,"model"],rules:[{required:!0,message:"Missing model"},{validator:(t,s)=>s&&(e.getFieldValue("modelLimits")??[]).filter(e=>e?.model===s).length>1?Promise.reject(Error("Duplicate model")):Promise.resolve()}],children:(0,t.jsx)(F.Input,{placeholder:"Model name (e.g. gpt-4)"})}),(0,t.jsx)(S.Form.Item,{...r,name:[a,"tpm"],children:(0,t.jsx)(D.InputNumber,{placeholder:"TPM Limit",min:0})}),(0,t.jsx)(S.Form.Item,{...r,name:[a,"rpm"],children:(0,t.jsx)(D.InputNumber,{placeholder:"RPM Limit",min:0})}),(0,t.jsx)(W.MinusCircleOutlined,{onClick:()=>l(a),style:{color:"#ef4444"}})]},s)),(0,t.jsx)(S.Form.Item,{children:(0,t.jsx)(G.Button,{type:"dashed",onClick:()=>a(),block:!0,icon:(0,t.jsx)(K.PlusOutlined,{}),children:"Add Model Limit"})})]})}),(0,t.jsx)(M.Divider,{}),(0,t.jsx)(sR.Typography.Text,{strong:!0,style:{display:"block",marginBottom:12},children:"Metadata"}),(0,t.jsx)(S.Form.List,{name:"metadata",children:(s,{add:a,remove:l})=>(0,t.jsxs)(t.Fragment,{children:[s.map(({key:s,name:a,...r})=>(0,t.jsxs)(V.Space,{style:{display:"flex",marginBottom:8},align:"baseline",children:[(0,t.jsx)(S.Form.Item,{...r,name:[a,"key"],rules:[{required:!0,message:"Missing key"},{validator:(t,s)=>s&&(e.getFieldValue("metadata")??[]).filter(e=>e?.key===s).length>1?Promise.reject(Error("Duplicate key")):Promise.resolve()}],children:(0,t.jsx)(F.Input,{placeholder:"Key"})}),(0,t.jsx)(S.Form.Item,{...r,name:[a,"value"],rules:[{required:!0,message:"Missing value"}],children:(0,t.jsx)(F.Input,{placeholder:"Value"})}),(0,t.jsx)(W.MinusCircleOutlined,{onClick:()=>l(a),style:{color:"#ef4444"}})]},s)),(0,t.jsx)(S.Form.Item,{children:(0,t.jsx)(G.Button,{type:"dashed",onClick:()=>a(),block:!0,icon:(0,t.jsx)(K.PlusOutlined,{}),children:"Add Key-Value Pair"})})]})})]})}]})})})]})}function lu(e){let t={},s={};for(let a of e.modelLimits??[])a.model&&(null!=a.rpm&&(t[a.model]=a.rpm),null!=a.tpm&&(s[a.model]=a.tpm));let a={};for(let t of e.metadata??[])t.key&&(a[t.key]=t.value);return{project_alias:e.project_alias,description:e.description,models:e.models??[],max_budget:e.max_budget,blocked:e.isBlocked??!1,...Object.keys(t).length>0&&{model_rpm_limit:t},...Object.keys(s).length>0&&{model_tpm_limit:s},...Object.keys(a).length>0&&{metadata:a}}}function lx({isOpen:e,onClose:s}){let[a]=S.Form.useForm(),l=(()=>{let{accessToken:e}=(0,r.default)(),t=(0,aF.useQueryClient)();return(0,aI.useMutation)({mutationFn:async t=>{if(!e)throw Error("Access token is required");return lc(e,t)},onSuccess:()=>{t.invalidateQueries({queryKey:li.projectKeys.all})}})})(),i=async()=>{try{let e=await a.validateFields(),t={...lu(e),team_id:e.team_id};l.mutate(t,{onSuccess:()=>{T.message.success("Project created successfully"),a.resetFields(),s()},onError:e=>{T.message.error(e.message||"Failed to create project")}})}catch(e){console.error("Validation failed:",e)}},n=()=>{a.resetFields(),s()};return(0,t.jsx)(_.Modal,{title:(0,t.jsx)(sR.Typography.Text,{strong:!0,style:{fontSize:18},children:"Create New Project"}),open:e,onCancel:n,width:720,destroyOnHidden:!0,footer:[(0,t.jsx)(G.Button,{onClick:n,children:"Cancel"},"cancel"),(0,t.jsx)(G.Button,{type:"primary",icon:(0,t.jsx)(ld,{}),loading:l.isPending,onClick:i,children:"Create Project"},"submit")],children:(0,t.jsx)(lm,{form:a})})}let lp=async(e,t)=>{let s=(0,l.getProxyBaseUrl)(),a=`${s}/project/info?project_id=${encodeURIComponent(t)}`,r=await fetch(a,{method:"GET",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!r.ok){let e=await r.json(),t=(0,l.deriveErrorMessage)(e);throw(0,l.handleError)(t),Error(t)}return r.json()},lh=(0,az.default)("dollar-sign",[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]]);var aW=aW,aY=aY,lg=e.i(987432);let ly=async(e,t,s)=>{let a=(0,l.getProxyBaseUrl)(),r=`${a}/project/update`,i=await fetch(r,{method:"POST",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({project_id:t,...s})});if(!i.ok){let e=await i.json(),t=(0,l.deriveErrorMessage)(e);throw(0,l.handleError)(t),Error(t)}return i.json()};function lj({isOpen:e,project:s,onClose:a,onSuccess:l}){let[n]=S.Form.useForm(),o=(()=>{let{accessToken:e}=(0,r.default)(),t=(0,aF.useQueryClient)();return(0,aI.useMutation)({mutationFn:async({projectId:t,params:s})=>{if(!e)throw Error("Access token is required");return ly(e,t,s)},onSuccess:()=>{t.invalidateQueries({queryKey:li.projectKeys.all})}})})();(0,i.useEffect)(()=>{if(e&&s){let e=s.metadata??{},t=e.model_rpm_limit??{},a=e.model_tpm_limit??{},l=[];for(let e of new Set([...Object.keys(t),...Object.keys(a)]))l.push({model:e,rpm:t[e],tpm:a[e]});let r=new Set(["model_rpm_limit","model_tpm_limit"]),i=[];for(let[t,s]of Object.entries(e))r.has(t)||i.push({key:t,value:String(s)});n.setFieldsValue({project_alias:s.project_alias??"",team_id:s.team_id??"",description:s.description??"",models:s.models??[],max_budget:s.litellm_budget_table?.max_budget??void 0,isBlocked:s.blocked,modelLimits:l.length>0?l:void 0,metadata:i.length>0?i:void 0})}},[e,s,n]);let d=async()=>{try{let e=await n.validateFields(),t={...lu(e),team_id:e.team_id};o.mutate({projectId:s.project_id,params:t},{onSuccess:()=>{T.message.success("Project updated successfully"),l?.(),a()},onError:e=>{T.message.error(e.message||"Failed to update project")}})}catch(e){console.error("Validation failed:",e)}};return(0,t.jsx)(_.Modal,{title:(0,t.jsx)(sR.Typography.Text,{strong:!0,style:{fontSize:18},children:"Edit Project"}),open:e,onCancel:a,width:720,destroyOnHidden:!0,footer:[(0,t.jsx)(G.Button,{onClick:a,children:"Cancel"},"cancel"),(0,t.jsx)(G.Button,{type:"primary",icon:(0,t.jsx)(lg.SaveOutlined,{}),loading:o.isPending,onClick:d,children:"Save Changes"},"submit")],children:(0,t.jsx)(lm,{form:n})})}let{Title:lf,Text:lb}=sR.Typography,{Content:l_}=aD.Layout;function lv({projectId:e,onBack:s}){let a,l,n,o,{data:d,isLoading:c}=(e=>{let{accessToken:t,userRole:s}=(0,r.default)(),a=(0,aF.useQueryClient)();return(0,t4.useQuery)({queryKey:li.projectKeys.detail(e),queryFn:async()=>lp(t,e),enabled:!!(t&&e)&&ek.all_admin_roles.includes(s||""),initialData:()=>{if(!e)return;let t=a.getQueryData(li.projectKeys.list({}));return t?.find(t=>t.project_id===e)}})})(e),{data:m}=(0,ln.useTeam)(d?.team_id??void 0),u=m?.team_info??m,{token:x}=aO.theme.useToken(),[p,h]=(0,i.useState)(!1),g=d?.spend??0,y=d?.litellm_budget_table?.max_budget??null,j=null!=y&&y>0,f=j?Math.min(g/y*100,100):0,b=(0,i.useMemo)(()=>Object.entries(d?.model_spend??{}).map(([e,t])=>({model:e,spend:t})).sort((e,t)=>t.spend-e.spend),[d?.model_spend]);return c?(0,t.jsx)(l_,{style:{padding:x.paddingLG,paddingInline:2*x.paddingLG},children:(0,t.jsx)(aM.Flex,{justify:"center",align:"center",style:{minHeight:300},children:(0,t.jsx)(eL.Spin,{indicator:(0,t.jsx)(tk.LoadingOutlined,{spin:!0}),size:"large"})})}):d?(0,t.jsxs)(l_,{style:{padding:x.paddingLG,paddingInline:2*x.paddingLG},children:[(0,t.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:24},children:[(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:16},children:[(0,t.jsx)(G.Button,{icon:(0,t.jsx)(aK.ArrowLeftIcon,{size:16}),onClick:s,type:"text"}),(0,t.jsxs)("div",{children:[(0,t.jsxs)(aM.Flex,{align:"center",gap:8,children:[(0,t.jsx)(lf,{level:2,style:{margin:0},children:d.project_alias??d.project_id}),(0,t.jsx)(A.Tag,{color:d.blocked?"red":"green",children:d.blocked?"Blocked":"Active"})]}),(0,t.jsxs)(lb,{type:"secondary",children:["ID: ",(0,t.jsx)(lb,{copyable:!0,children:d.project_id})]})]})]}),(0,t.jsx)(G.Button,{type:"primary",icon:(0,t.jsx)(aW.default,{size:16}),onClick:()=>h(!0),children:"Edit Project"})]}),(0,t.jsx)(tN.Row,{style:{marginBottom:24},children:(0,t.jsx)(tl.Card,{children:(0,t.jsxs)(eA.Descriptions,{title:"Project Details",column:1,children:[(0,t.jsx)(eA.Descriptions.Item,{label:"Description",children:d.description||"—"}),(0,t.jsxs)(eA.Descriptions.Item,{label:"Created",children:[new Date(d.created_at).toLocaleString(),d.created_by&&(0,t.jsxs)(lb,{children:[" ","by"," ",(0,t.jsx)(aJ.default,{userId:d.created_by})]})]}),(0,t.jsxs)(eA.Descriptions.Item,{label:"Last Updated",children:[new Date(d.updated_at).toLocaleString(),d.updated_by&&(0,t.jsxs)(lb,{children:[" ","by"," ",(0,t.jsx)(aJ.default,{userId:d.updated_by})]})]})]})})}),(0,t.jsxs)(tN.Row,{gutter:[16,16],style:{marginBottom:24},children:[(0,t.jsx)(tw.Col,{xs:24,lg:8,children:(0,t.jsx)(tl.Card,{title:(0,t.jsxs)(aM.Flex,{align:"center",gap:8,children:[(0,t.jsx)(lh,{size:16}),"Budget"]}),style:{height:"100%"},children:(0,t.jsxs)(aM.Flex,{vertical:!0,gap:16,children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)(lb,{strong:!0,style:{fontSize:28,lineHeight:1},children:["$",g.toFixed(2)]}),(0,t.jsx)("br",{}),(0,t.jsx)(lb,{type:"secondary",children:j?`of $${y.toFixed(2)} budget`:"No budget limit"})]}),j&&(0,t.jsxs)("div",{children:[(0,t.jsx)(ag.Progress,{percent:Math.round(10*f)/10,strokeColor:f>=90?"#f5222d":f>=70?"#faad14":"#52c41a",showInfo:!1}),(0,t.jsxs)(lb,{type:"secondary",style:{fontSize:12},children:[(Math.round(10*f)/10).toFixed(1),"% utilized"]})]})]})})}),(0,t.jsx)(tw.Col,{xs:24,lg:16,children:(0,t.jsx)(tl.Card,{title:"Spend by Model",style:{height:"100%"},children:b.length>0?(0,t.jsx)(sm.BarChart,{data:b,index:"model",categories:["spend"],colors:["cyan"],layout:"vertical",valueFormatter:e=>`$${e.toFixed(4)}`,yAxisWidth:140,showLegend:!1,style:{height:Math.max(40*b.length,120)}}):(0,t.jsx)(aV.Empty,{description:"No model spend recorded yet",image:aV.Empty.PRESENTED_IMAGE_SIMPLE})})})]}),(0,t.jsxs)(tN.Row,{gutter:[16,16],style:{marginBottom:24},children:[(0,t.jsx)(tw.Col,{xs:24,lg:12,children:(0,t.jsx)(tl.Card,{title:(0,t.jsxs)(aM.Flex,{align:"center",gap:8,children:[(0,t.jsx)(aQ.KeyIcon,{size:16}),"Keys"]}),style:{height:"100%"},children:(0,t.jsx)(aV.Empty,{description:"No keys to display",image:aV.Empty.PRESENTED_IMAGE_SIMPLE})})}),(0,t.jsx)(tw.Col,{xs:24,lg:12,children:(0,t.jsx)(tl.Card,{title:(0,t.jsxs)(aM.Flex,{align:"center",gap:8,children:[(0,t.jsx)(aY.default,{size:16}),"Team"]}),style:{height:"100%"},children:u?(a=u.max_budget??null,l=u.spend??0,o=(n=null!=a&&a>0)?Math.min(l/a*100,100):0,(0,t.jsxs)(aM.Flex,{vertical:!0,gap:12,children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(lb,{strong:!0,style:{fontSize:16},children:u.team_alias||u.team_id}),(0,t.jsx)("br",{}),(0,t.jsxs)(lb,{type:"secondary",style:{fontSize:12},children:["ID:"," ",(0,t.jsx)(lb,{copyable:!0,style:{fontSize:12},children:u.team_id})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(lb,{type:"secondary",style:{fontSize:12,display:"block",marginBottom:4},children:"Models"}),(u.models?.length??0)>0?(0,t.jsx)(aM.Flex,{wrap:"wrap",gap:4,style:{maxHeight:60,overflow:"hidden"},children:u.models?.map(e=>(0,t.jsx)(A.Tag,{style:{margin:0},children:e},e))}):(0,t.jsx)(lb,{type:"secondary",children:"All models"})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)(aM.Flex,{justify:"space-between",align:"center",style:{marginBottom:2},children:[(0,t.jsx)(lb,{type:"secondary",style:{fontSize:12},children:"Spend"}),(0,t.jsxs)(lb,{style:{fontSize:12},children:["$",l.toFixed(2),n?(0,t.jsxs)(lb,{type:"secondary",style:{fontSize:12},children:[" ","/ $",a.toFixed(2)]}):(0,t.jsxs)(lb,{type:"secondary",style:{fontSize:12},children:[" ","(Unlimited)"]})]})]}),n&&(0,t.jsx)(ag.Progress,{percent:Math.round(10*o)/10,strokeColor:o>=90?"#f5222d":o>=70?"#faad14":"#52c41a",size:"small",showInfo:!1})]}),(0,t.jsxs)(aM.Flex,{justify:"space-between",children:[(0,t.jsx)(lb,{type:"secondary",style:{fontSize:12},children:"Members"}),(0,t.jsx)(lb,{style:{fontSize:12},children:u.members_with_roles?.length??0})]})]})):d.team_id?(0,t.jsx)(aM.Flex,{justify:"center",align:"center",style:{padding:16},children:(0,t.jsx)(eL.Spin,{indicator:(0,t.jsx)(tk.LoadingOutlined,{spin:!0}),size:"small"})}):(0,t.jsx)(aV.Empty,{description:"No team assigned",image:aV.Empty.PRESENTED_IMAGE_SIMPLE})})})]}),(0,t.jsx)(lj,{isOpen:p,project:d,onClose:()=>h(!1)})]}):(0,t.jsxs)(l_,{style:{padding:x.paddingLG,paddingInline:2*x.paddingLG},children:[(0,t.jsx)(G.Button,{icon:(0,t.jsx)(aK.ArrowLeftIcon,{size:16}),onClick:s,type:"text",style:{marginBottom:16}}),(0,t.jsx)(aV.Empty,{description:"Project not found"})]})}let{Title:lN,Text:lw}=sR.Typography,{Content:lk}=aD.Layout;function lC(){let{token:e}=aO.theme.useToken(),{data:s,isLoading:a}=(0,li.useProjects)(),{data:l,isLoading:r}=(0,ln.useTeams)(),[n,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(!1),[m,u]=(0,i.useState)(""),[x,p]=(0,i.useState)(1);(0,i.useEffect)(()=>{p(1)},[m]);let h=(0,i.useMemo)(()=>{let e=new Map;for(let t of l??[])e.set(t.team_id,t.team_alias??t.team_id);return e},[l]),g=(0,i.useMemo)(()=>{let e=s??[];if(!m)return e;let t=m.toLowerCase();return e.filter(e=>{let s=h.get(e.team_id??"")??"";return(e.project_alias??"").toLowerCase().includes(t)||e.project_id.toLowerCase().includes(t)||(e.description??"").toLowerCase().includes(t)||s.toLowerCase().includes(t)})},[s,m,h]),y=[{title:"ID",dataIndex:"project_id",key:"project_id",width:170,render:e=>(0,t.jsx)(N.Tooltip,{title:e,children:(0,t.jsx)(lw,{ellipsis:!0,className:"text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs cursor-pointer",style:{fontSize:14,padding:"1px 8px"},onClick:()=>o(e),children:e})})},{title:"Name",dataIndex:"project_alias",key:"project_alias",sorter:(e,t)=>(e.project_alias??"").localeCompare(t.project_alias??""),render:e=>e??"—"},{title:"Team",key:"team",sorter:(e,t)=>{let s=h.get(e.team_id??"")??"",a=h.get(t.team_id??"")??"";return s.localeCompare(a)},render:(e,s)=>{if(!s.team_id)return"—";let a=h.get(s.team_id);return a||(r?(0,t.jsx)(eL.Spin,{indicator:(0,t.jsx)(tk.LoadingOutlined,{spin:!0}),size:"small"}):s.team_id)}},{title:"Models",key:"models",render:(e,s)=>{let a=s.models??[];return(0,t.jsx)(N.Tooltip,{title:a.length>0?a.join(", "):"No models",children:(0,t.jsx)(A.Tag,{color:"blue",style:{fontSize:14,padding:"2px 8px",margin:0},children:(0,t.jsxs)(aM.Flex,{align:"center",gap:6,children:[(0,t.jsx)(aB,{size:14}),a.length]})})})}},{title:"Status",dataIndex:"blocked",key:"status",render:e=>(0,t.jsx)(A.Tag,{color:e?"red":"green",children:e?"Blocked":"Active"})},{title:"Created",dataIndex:"created_at",key:"created_at",sorter:(e,t)=>new Date(e.created_at).getTime()-new Date(t.created_at).getTime(),responsive:["lg"],render:e=>new Date(e).toLocaleDateString()},{title:"Updated",dataIndex:"updated_at",key:"updated_at",responsive:["xl"],render:e=>new Date(e).toLocaleDateString()}];return n?(0,t.jsx)(lv,{projectId:n,onBack:()=>o(null)}):(0,t.jsxs)(lk,{style:{padding:e.paddingLG,paddingInline:2*e.paddingLG},children:[(0,t.jsxs)(aM.Flex,{justify:"space-between",align:"center",style:{marginBottom:16},children:[(0,t.jsxs)(V.Space,{direction:"vertical",size:0,children:[(0,t.jsx)(lN,{level:2,style:{margin:0},children:"Projects"}),(0,t.jsx)(lw,{type:"secondary",children:"Manage projects within your teams"})]}),(0,t.jsx)(G.Button,{type:"primary",icon:(0,t.jsx)(K.PlusOutlined,{}),onClick:()=>c(!0),children:"Create Project"})]}),(0,t.jsxs)(tl.Card,{styles:{body:{padding:0}},children:[(0,t.jsxs)(aM.Flex,{justify:"space-between",align:"center",style:{padding:"12px 16px"},children:[(0,t.jsx)(F.Input,{prefix:(0,t.jsx)(aq.SearchIcon,{size:16}),placeholder:"Search projects by name, ID, description, or team...",style:{maxWidth:400},value:m,onChange:e=>u(e.target.value),allowClear:!0}),(0,t.jsx)(aE.Pagination,{current:x,total:g.length,pageSize:10,onChange:e=>p(e),size:"small",showTotal:e=>`${e} projects`,showSizeChanger:!1})]}),(0,t.jsx)(ts.Table,{columns:y,dataSource:g.slice((x-1)*10,10*x),rowKey:"project_id",loading:a,pagination:!1})]}),(0,t.jsx)(lx,{isOpen:d,onClose:()=>c(!1)})]})}var lS=e.i(241902);let lT={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M536.1 273H488c-4.4 0-8 3.6-8 8v275.3c0 2.6 1.2 5 3.3 6.5l165.3 120.7c3.6 2.6 8.6 1.9 11.2-1.7l28.6-39c2.7-3.7 1.9-8.7-1.7-11.2L544.1 528.5V281c0-4.4-3.6-8-8-8zm219.8 75.2l156.8 38.3c5 1.2 9.9-2.6 9.9-7.7l.8-161.5c0-6.7-7.7-10.5-12.9-6.3L752.9 334.1a8 8 0 003 14.1zm167.7 301.1l-56.7-19.5a8 8 0 00-10.1 4.8c-1.9 5.1-3.9 10.1-6 15.1-17.8 42.1-43.3 80-75.9 112.5a353 353 0 01-112.5 75.9 352.18 352.18 0 01-137.7 27.8c-47.8 0-94.1-9.3-137.7-27.8a353 353 0 01-112.5-75.9c-32.5-32.5-58-70.4-75.9-112.5A353.44 353.44 0 01171 512c0-47.8 9.3-94.2 27.8-137.8 17.8-42.1 43.3-80 75.9-112.5a353 353 0 01112.5-75.9C430.6 167.3 477 158 524.8 158s94.1 9.3 137.7 27.8A353 353 0 01775 261.7c10.2 10.3 19.8 21 28.6 32.3l59.8-46.8C784.7 146.6 662.2 81.9 524.6 82 285 82.1 92.6 276.7 95 516.4 97.4 751.9 288.9 942 524.8 942c185.5 0 343.5-117.6 403.7-282.3 1.5-4.2-.7-8.9-4.9-10.4z"}}]},name:"history",theme:"outlined"};var lI=i.forwardRef(function(e,t){return i.createElement(tL.default,(0,tF.default)({},e,{ref:t,icon:lT}))}),lF=e.i(366308);let lP=[{value:"untrusted",label:"untrusted",color:"#92400e",bg:"#fef3c7",border:"#fcd34d"},{value:"trusted",label:"trusted",color:"#065f46",bg:"#d1fae5",border:"#6ee7b7"},{value:"blocked",label:"blocked",color:"#991b1b",bg:"#fee2e2",border:"#fca5a5"}],lL=[{value:"untrusted",label:"untrusted",color:"#92400e",bg:"#fef3c7",border:"#fcd34d"},{value:"trusted",label:"trusted",color:"#065f46",bg:"#d1fae5",border:"#6ee7b7"}],lA=({value:e,toolName:s,saving:a,onChange:l,policyType:r="input",size:i="small",minWidth:n=110,stopPropagation:o=!0})=>{let d="output"===r?lL:lP,c=lP.find(t=>t.value===e)??lP[0];return(0,t.jsx)(I.Select,{size:i,value:e,disabled:a,loading:a,onChange:e=>l(s,e),onClick:e=>o&&e.stopPropagation(),style:{minWidth:n,fontWeight:500,backgroundColor:c.bg,borderColor:c.border,color:c.color,borderRadius:999,fontSize:"small"===i?11:12},popupMatchSelectWidth:!1,options:d.map(e=>({value:e.value,label:(0,t.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:12,fontWeight:500,color:e.color},children:[(0,t.jsx)("span",{style:{width:8,height:8,borderRadius:"50%",backgroundColor:e.color,display:"inline-block",flexShrink:0}}),e.label]})}))})},lM="tool-detail";function lD({toolName:e,onBack:s,accessToken:a}){let r=(0,aF.useQueryClient)(),[n,o]=(0,i.useState)(!1),[d,c]=(0,i.useState)(!1),[m,u]=(0,i.useState)(!1),[x,p]=(0,i.useState)("team"),[h,g]=(0,i.useState)(null),[y,j]=(0,i.useState)(null),f=(0,i.useMemo)(()=>{let e,t,s;return e=new Date,(t=new Date).setDate(t.getDate()-90),{start:(s=e=>e.toISOString().slice(0,19).replace("T"," "))(t),end:s(e)}},[]),{data:b,isLoading:_,error:v}=(0,t4.useQuery)({queryKey:[lM,e],queryFn:()=>(0,l.fetchToolDetail)(a,e),enabled:!!a&&!!e}),{data:N}=(0,t4.useQuery)({queryKey:["tool-policy-options"],queryFn:()=>(0,l.fetchToolPolicyOptions)(a),enabled:!!a,staleTime:6e4}),{data:w}=(0,t4.useQuery)({queryKey:["teams-list-tool-detail"],queryFn:()=>(0,l.teamListCall)(a,null,null),enabled:!!a}),{data:k}=(0,t4.useQuery)({queryKey:["keys-list-tool-detail"],queryFn:()=>(0,l.keyListCall)(a,null,null,null,null,null,1,100),enabled:!!a}),{data:C,isLoading:S}=(0,t4.useQuery)({queryKey:["tool-usage-logs",e,f.start,f.end],queryFn:()=>(0,l.getToolUsageLogs)(a,e,{page:1,pageSize:50,startDate:f.start,endDate:f.end}),enabled:!!a&&!!e}),T=(0,i.useMemo)(()=>(C?.logs??[]).map(e=>({id:e.id,timestamp:e.timestamp,action:"passed",model:e.model??void 0,input_snippet:e.input_snippet??void 0})),[C?.logs]),F=(0,i.useMemo)(()=>(Array.isArray(w)?w:w?.data??[]).map(e=>({team_id:e.team_id??e.id??"",team_alias:e.team_alias??e.team_id??"",models:[],max_budget:null,budget_duration:null,tpm_limit:null,rpm_limit:null,organization_id:"",created_at:"",keys:[],members_with_roles:[],spend:0})),[w]),P=(0,i.useMemo)(()=>(k?.keys??k?.data??[]).map(e=>({token:e.token??e.api_key??e.key_hash??"",key_alias:e.key_alias??(e.token??e.api_key??e.key_hash)?.toString?.()?.substring?.(0,8)})),[k]),L=(0,i.useCallback)(()=>{r.invalidateQueries({queryKey:[lM,e]})},[r,e]),A=(0,i.useCallback)(async(t,s)=>{if(a){c(!0);try{await (0,l.updateToolPolicy)(a,e,{input_policy:s}),L()}catch(e){alert(`Failed to update input policy: ${e instanceof Error?e.message:String(e)}`)}finally{c(!1)}}},[a,e,L]),M=(0,i.useCallback)(async(t,s)=>{if(a){u(!0);try{await (0,l.updateToolPolicy)(a,e,{output_policy:s}),L()}catch(e){alert(`Failed to update output policy: ${e instanceof Error?e.message:String(e)}`)}finally{u(!1)}}},[a,e,L]),D=(0,i.useCallback)(async()=>{if(!a||!e)return;let t="team"===x;if((!t||h)&&(t||y?.token)){o(!0);try{await (0,l.updateToolPolicy)(a,e,{input_policy:"blocked"},{team_id:t?h:void 0,key_hash:t?void 0:y.token,key_alias:t?void 0:y.key_alias}),L(),g(null),j(null)}catch(e){alert(`Failed to add override: ${e instanceof Error?e.message:String(e)}`)}finally{o(!1)}}},[a,e,x,h,y,L]),E=(0,i.useCallback)(async t=>{if(a&&e){o(!0);try{await (0,l.deleteToolPolicyOverride)(a,e,{team_id:t.team_id??void 0,key_hash:t.key_hash??void 0}),L()}catch(e){alert(`Failed to remove override: ${e instanceof Error?e.message:String(e)}`)}finally{o(!1)}}},[a,e,L]);if(_&&!b)return(0,t.jsx)("div",{className:"flex items-center justify-center py-12",children:(0,t.jsx)(eL.Spin,{size:"large"})});if(v&&!b)return(0,t.jsxs)("div",{children:[(0,t.jsx)(G.Button,{type:"link",icon:(0,t.jsx)(tZ.ArrowLeftOutlined,{}),onClick:s,className:"pl-0 mb-4",children:"Back to Tool Policies"}),(0,t.jsx)("p",{className:"text-red-600",children:"Failed to load tool details."})]});if(!b)return null;let{tool:O,overrides:R}=b,z=N?.input_policies?.find(e=>e.value===O.input_policy)?.description,B=N?.output_policies?.find(e=>e.value===O.output_policy)?.description;return(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"mb-6",children:[(0,t.jsx)(G.Button,{type:"link",icon:(0,t.jsx)(tZ.ArrowLeftOutlined,{}),onClick:s,className:"pl-0 mb-4",children:"Back to Tool Policies"}),(0,t.jsx)("div",{className:"flex items-start justify-between",children:(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center gap-3 mb-1 flex-wrap",children:[(0,t.jsx)(lF.ToolOutlined,{className:"text-xl text-gray-400"}),(0,t.jsx)("h1",{className:"text-xl font-semibold text-gray-900 font-mono",children:O.tool_name}),(0,t.jsx)("span",{className:"inline-flex items-center px-2.5 py-1 text-xs font-medium rounded-md bg-gray-100 text-gray-700 border border-gray-200",children:O.origin??"—"}),(0,t.jsxs)("span",{className:"inline-flex items-center px-2.5 py-1 text-xs font-medium rounded-md bg-indigo-50 text-indigo-700 border border-indigo-200",children:[(O.call_count??0).toLocaleString()," calls"]})]}),(0,t.jsxs)("dl",{className:"mt-3 flex flex-wrap gap-x-6 gap-y-1 text-sm text-gray-600",children:[O.user_agent&&(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,t.jsx)("dt",{className:"font-medium text-gray-500 whitespace-nowrap",children:"User Agent:"}),(0,t.jsx)("dd",{className:"font-mono truncate max-w-[40ch]",title:O.user_agent,children:O.user_agent})]}),O.created_at&&(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,t.jsx)("dt",{className:"font-medium text-gray-500 whitespace-nowrap",children:"First Discovered:"}),(0,t.jsx)("dd",{children:new Date(O.created_at).toLocaleString()})]}),O.last_used_at&&(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,t.jsx)("dt",{className:"font-medium text-gray-500 whitespace-nowrap",children:"Last Used:"}),(0,t.jsx)("dd",{children:new Date(O.last_used_at).toLocaleString()})]})]})]})})]}),(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[(0,t.jsxs)("section",{className:"bg-white rounded-lg border border-gray-200 p-5 shadow-sm",children:[(0,t.jsx)("h2",{className:"text-sm font-semibold text-gray-700 mb-1",children:"Input Policy"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mb-3",children:z??"Controls what data this tool is allowed to accept."}),(0,t.jsx)(lA,{value:O.input_policy,toolName:O.tool_name,saving:d,onChange:A,policyType:"input",size:"middle",minWidth:140,stopPropagation:!1})]}),(0,t.jsxs)("section",{className:"bg-white rounded-lg border border-gray-200 p-5 shadow-sm",children:[(0,t.jsx)("h2",{className:"text-sm font-semibold text-gray-700 mb-1",children:"Output Policy"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mb-3",children:B??"Controls how this tool's output is trusted by downstream tools."}),(0,t.jsx)(lA,{value:O.output_policy,toolName:O.tool_name,saving:m,onChange:M,policyType:"output",size:"middle",minWidth:140,stopPropagation:!1})]})]}),R.length>0&&(0,t.jsxs)("section",{className:"bg-white rounded-lg border border-gray-200 p-5 shadow-sm",children:[(0,t.jsx)("h2",{className:"text-sm font-semibold text-gray-700 mb-3",children:"Blocked for team or key"}),(0,t.jsx)("ul",{className:"border rounded-md divide-y divide-gray-100 bg-red-50/30",children:R.map(e=>(0,t.jsxs)("li",{className:"flex items-center justify-between px-3 py-2.5 text-sm",children:[(0,t.jsxs)("span",{className:"text-gray-700",children:[e.team_id?`Team: ${e.team_id}`:"",e.team_id&&e.key_hash?" · ":"",e.key_hash?`Key: ${e.key_alias||e.key_hash.substring(0,8)}`:"",e.team_id||e.key_hash?"":"—"]}),(0,t.jsx)(G.Button,{type:"link",danger:!0,size:"small",disabled:n,onClick:()=>E(e),children:"Remove"})]},e.override_id))})]}),(0,t.jsxs)("section",{className:"bg-white rounded-lg border border-gray-200 p-5 shadow-sm",children:[(0,t.jsx)("h2",{className:"text-sm font-semibold text-gray-700 mb-3",children:"Block for team or key"}),(0,t.jsxs)("div",{className:"flex flex-col gap-4 max-w-md",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700 block mb-2",children:"Scope"}),(0,t.jsxs)("div",{className:"flex items-center gap-6",children:[(0,t.jsxs)("label",{className:"flex items-center gap-2 cursor-pointer text-sm text-gray-700",children:[(0,t.jsx)("input",{type:"radio",checked:"team"===x,onChange:()=>p("team"),className:"align-middle"}),"Team"]}),(0,t.jsxs)("label",{className:"flex items-center gap-2 cursor-pointer text-sm text-gray-700",children:[(0,t.jsx)("input",{type:"radio",checked:"key"===x,onChange:()=>p("key"),className:"align-middle"}),"Key"]})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700 block mb-2",children:"team"===x?"Team":"Key"}),"team"===x?(0,t.jsx)(U.default,{teams:F,value:h??void 0,onChange:e=>g(e||null)}):(0,t.jsx)(I.Select,{placeholder:"Select key",allowClear:!0,showSearch:!0,optionFilterProp:"label",value:y?y.token:void 0,onChange:e=>{j(P.find(t=>t.token===e)??null)},options:P.map(e=>({value:e.token,label:e.key_alias||e.token?.substring?.(0,12)||e.token})),className:"w-full",style:{minWidth:200}})]}),(0,t.jsxs)(G.Button,{type:"primary",danger:!0,disabled:n||("team"===x?!h:!y?.token),loading:n,onClick:D,children:["Block for ",x]})]})]}),(0,t.jsxs)("section",{className:"bg-white rounded-lg border border-gray-200 p-5 shadow-sm",children:[(0,t.jsxs)("h2",{className:"text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2",children:[(0,t.jsx)(lI,{}),"Recent logs"]}),(0,t.jsx)(sr,{guardrailName:O.tool_name,filterAction:"passed",logs:T,logsLoading:S,totalLogs:C?.total??0,accessToken:a,startDate:f.start,endDate:f.end})]})]})]})}var lE=e.i(307582),lO=e.i(969550);function lR(e){return`${e.getUTCFullYear()}-${String(e.getUTCMonth()+1).padStart(2,"0")}-${String(e.getUTCDate()).padStart(2,"0")}`}function lz(e,t){if(!e)return!1;try{let s=new Date(e);return lR(s)===t}catch{return!1}}function lB(e,t){return e.filter(e=>lz(e.created_at,t)).length}let lq=({accessToken:e,onSelectTool:s})=>{let[a,r]=(0,i.useState)([]),[n,o]=(0,i.useState)(!0),[d,c]=(0,i.useState)(!1),[m,u]=(0,i.useState)(null),[f,b]=(0,i.useState)(null),[_,v]=(0,i.useState)(null),[w,C]=(0,i.useState)(""),[S,T]=(0,i.useState)("created_at"),[I,F]=(0,i.useState)("desc"),[P,L]=(0,i.useState)(1),[A,M]=(0,i.useState)(!0),[D,E]=(0,i.useState)({}),O=(0,i.useDeferredValue)(d),R=d||O,z=(0,i.useCallback)(async()=>{if(e){c(!0),u(null);try{let t=await (0,l.fetchToolsList)(e);r(t)}catch(e){u(e.message??"Failed to load tools")}finally{c(!1),o(!1)}}},[e]);(0,i.useEffect)(()=>{z()},[z]),(0,i.useEffect)(()=>{if(!A)return;let e=setInterval(z,15e3);return()=>clearInterval(e)},[A,z]);let B=async(t,s)=>{if(e){b(t);try{await (0,l.updateToolPolicy)(e,t,{input_policy:s}),r(e=>e.map(e=>e.tool_name===t?{...e,input_policy:s}:e))}catch(e){alert(`Failed to update input policy: ${e.message}`)}finally{b(null)}}},q=async(t,s)=>{if(e){v(t);try{await (0,l.updateToolPolicy)(e,t,{output_policy:s}),r(e=>e.map(e=>e.tool_name===t?{...e,output_policy:s}:e))}catch(e){alert(`Failed to update output policy: ${e.message}`)}finally{v(null)}}},$=Array.from(new Set(a.map(e=>e.team_id).filter(Boolean))).map(e=>({label:e,value:e})),U=Array.from(new Set(a.map(e=>e.key_alias).filter(Boolean))).map(e=>({label:e,value:e})),H=[{name:"Input Policy",label:"Input Policy",options:lP.map(e=>({label:e.label,value:e.value}))},{name:"Output Policy",label:"Output Policy",options:lL.map(e=>({label:e.label,value:e.value}))},{name:"Team Name",label:"Team Name",options:$},{name:"Key Name",label:"Key Name",options:U}],{newToday:V,newYesterday:G,trendSubtitle:K,totalTools:W,blockedCount:Q,activeTeamsCount:Y,needsReviewTools:J}=(0,i.useMemo)(()=>{let e=new Date,t=lR(e),s=new Date(e);s.setUTCDate(s.getUTCDate()-1);let l=lR(s),r=lB(a,t),i=lB(a,l),n=function(e,t){let s=e-t;if(0!==s)return s>0?`+${s} since yesterday`:`${s} since yesterday`}(r,i),o=a.length,d=a.filter(e=>"blocked"===e.input_policy).length;return{newToday:r,newYesterday:i,trendSubtitle:n,totalTools:o,blockedCount:d,activeTeamsCount:new Set(a.map(e=>e.team_id).filter(Boolean)).size,needsReviewTools:a.filter(e=>lz(e.created_at,t)&&"untrusted"===e.input_policy)}},[a]),X=({label:e,field:s})=>(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,t.jsx)("span",{children:e}),(0,t.jsx)(aU.TableHeaderSortDropdown,{sortState:S===s&&I,onSortChange:e=>{!1===e?(T("created_at"),F("desc")):(T(s),F(e)),L(1)}})]}),Z=a.filter(e=>{if(w){let t=w.toLowerCase();if(!(e.tool_name.toLowerCase().includes(t)||(e.team_id??"").toLowerCase().includes(t)||(e.key_alias??"").toLowerCase().includes(t)||(e.key_hash??"").toLowerCase().includes(t)||e.input_policy.toLowerCase().includes(t)||e.output_policy.toLowerCase().includes(t)))return!1}return(!D["Input Policy"]||e.input_policy===D["Input Policy"])&&(!D["Output Policy"]||e.output_policy===D["Output Policy"])&&(!D["Team Name"]||e.team_id===D["Team Name"])&&(!D["Key Name"]||e.key_alias===D["Key Name"])}),ee=[...Z].sort((e,t)=>{let s=e[S]??"",a=t[S]??"";return sa?"desc"===I?-1:1:0}),et=Math.max(1,Math.ceil(ee.length/50)),es=ee.slice((P-1)*50,50*P);return(0,t.jsxs)("div",{className:"w-full",children:[(0,t.jsx)("h1",{className:"text-2xl font-semibold text-gray-900 mb-6",children:"Tool Policies"}),(0,t.jsxs)("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6",children:[(0,t.jsx)(si,{label:"New Today",value:V,valueColor:"text-green-600",subtitle:K,icon:(0,t.jsx)("svg",{className:"w-4 h-4 text-green-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,t.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"})})}),(0,t.jsx)(si,{label:"Total Tools Discovered",value:W}),(0,t.jsx)(si,{label:"Blocked Tools",value:Q,valueColor:Q>0?"text-red-600":void 0}),(0,t.jsx)(si,{label:"Active Teams",value:Y>0?Y:"—"})]}),J.length>0&&(0,t.jsxs)("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-4 mb-6",children:[(0,t.jsx)("h2",{className:"text-sm font-semibold text-amber-900 mb-1",children:"Needs Review"}),(0,t.jsxs)("p",{className:"text-sm text-amber-800 mb-3",children:[J.length," new tool",1!==J.length?"s":""," discovered that require policy decisions."]}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:J.map(e=>(0,t.jsxs)("span",{className:"inline-flex items-center gap-2 px-3 py-1.5 bg-white border border-amber-200 rounded-md text-sm",children:[(0,t.jsx)("span",{className:"font-mono text-amber-900 truncate max-w-[200px]",title:e.tool_name,children:e.tool_name}),(0,t.jsx)("button",{type:"button",onClick:()=>(e=>{let t=ee.findIndex(t=>t.tool_id===e);if(t>=0){let s=Math.floor(t/50)+1;s!==P&&L(s),requestAnimationFrame(()=>{setTimeout(()=>{document.getElementById(`tool-row-${e}`)?.scrollIntoView({behavior:"smooth",block:"center"})},100)})}})(e.tool_id),className:"text-amber-700 hover:text-amber-900 font-medium text-xs whitespace-nowrap",children:"Review"})]},e.tool_id))})]}),(0,t.jsxs)("div",{className:"bg-white rounded-lg shadow w-full max-w-full box-border",children:[(0,t.jsxs)("div",{className:"border-b px-6 py-4 w-full max-w-full box-border",children:[(0,t.jsxs)("div",{className:"flex flex-col md:flex-row items-start md:items-center justify-between space-y-4 md:space-y-0 w-full max-w-full box-border",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,t.jsxs)("div",{className:"relative w-64",children:[(0,t.jsx)("input",{type:"text",placeholder:"Search by Tool Name",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:w,onChange:e=>{C(e.target.value),L(1)}}),(0,t.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,t.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,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:"text-sm font-medium text-gray-900",children:"Live Tail"}),(0,t.jsx)(k.Switch,{checked:A,onChange:M})]}),(0,t.jsxs)("button",{onClick:z,disabled:R,className:"flex items-center gap-1.5 px-3 py-2 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-60",children:[(0,t.jsx)("svg",{className:`w-4 h-4 ${R?"animate-spin":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,t.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"})}),R?"Fetching":"Fetch"]})]}),(0,t.jsxs)("div",{className:"flex items-center gap-4 text-sm text-gray-600 whitespace-nowrap",children:[(0,t.jsxs)("span",{children:["Showing ",0===Z.length?0:(P-1)*50+1," -"," ",Math.min(50*P,Z.length)," of ",Z.length," results"]}),(0,t.jsxs)("span",{children:["Page ",P," of ",et]}),(0,t.jsxs)("div",{className:"flex gap-1",children:[(0,t.jsx)("button",{onClick:()=>L(e=>Math.max(1,e-1)),disabled:1===P,className:"px-3 py-1.5 border rounded-md text-sm hover:bg-gray-50 disabled:opacity-40",children:"Previous"}),(0,t.jsx)("button",{onClick:()=>L(e=>Math.min(et,e+1)),disabled:P===et,className:"px-3 py-1.5 border rounded-md text-sm hover:bg-gray-50 disabled:opacity-40",children:"Next"})]})]})]}),(0,t.jsx)("div",{className:"mt-3",children:(0,t.jsx)(lO.default,{options:H,onApplyFilters:e=>{E(e),L(1)},onResetFilters:()=>{E({}),L(1)},buttonLabel:"Filters"})})]}),A&&(0,t.jsxs)("div",{className:"bg-green-50 border-b border-green-100 px-6 py-2 flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-sm text-green-700",children:"Auto-refreshing every 15 seconds"}),(0,t.jsx)("button",{onClick:()=>M(!1),className:"text-xs text-green-600 underline",children:"Stop"})]}),m&&(0,t.jsx)("div",{className:"mx-6 mt-4 p-3 bg-red-50 border border-red-200 rounded text-sm text-red-700",children:m}),(0,t.jsxs)(x.Table,{className:"[&_td]:py-0.5 [&_th]:py-1 w-full",children:[(0,t.jsx)(g.TableHead,{children:(0,t.jsxs)(j.TableRow,{children:[(0,t.jsx)(y.TableHeaderCell,{className:"py-1 h-8",children:(0,t.jsx)(X,{label:"Discovered",field:"created_at"})}),(0,t.jsx)(y.TableHeaderCell,{className:"py-1 h-8",children:(0,t.jsx)(X,{label:"Tool Name",field:"tool_name"})}),(0,t.jsx)(y.TableHeaderCell,{className:"py-1 h-8",children:(0,t.jsx)(X,{label:"Input Policy",field:"input_policy"})}),(0,t.jsx)(y.TableHeaderCell,{className:"py-1 h-8",children:(0,t.jsx)(X,{label:"Output Policy",field:"output_policy"})}),(0,t.jsx)(y.TableHeaderCell,{className:"py-1 h-8",children:(0,t.jsx)(X,{label:"# Calls",field:"call_count"})}),(0,t.jsx)(y.TableHeaderCell,{className:"py-1 h-8",children:(0,t.jsx)(X,{label:"Team Name",field:"team_id"})}),(0,t.jsx)(y.TableHeaderCell,{className:"py-1 h-8",children:"Key Hash"}),(0,t.jsx)(y.TableHeaderCell,{className:"py-1 h-8",children:(0,t.jsx)(X,{label:"Key Name",field:"key_alias"})}),(0,t.jsx)(y.TableHeaderCell,{className:"py-1 h-8",children:"User Agent"})]})}),(0,t.jsx)(p.TableBody,{children:n?(0,t.jsx)(j.TableRow,{children:(0,t.jsx)(h.TableCell,{colSpan:9,className:"h-8 text-center text-gray-500",children:"Loading tools…"})}):0===es.length?(0,t.jsx)(j.TableRow,{children:(0,t.jsx)(h.TableCell,{colSpan:9,className:"h-8 text-center text-gray-500",children:"No tools discovered yet. Make a chat completion that returns tool_calls to start auto-discovery."})}):es.map(e=>(0,t.jsxs)(j.TableRow,{id:`tool-row-${e.tool_id}`,className:"h-8 hover:bg-gray-50",children:[(0,t.jsx)(h.TableCell,{className:"py-0.5 max-h-8 overflow-hidden whitespace-nowrap",children:(0,t.jsx)(lE.TimeCell,{utcTime:e.created_at??""})}),(0,t.jsx)(h.TableCell,{className:"py-0.5 max-h-8 overflow-hidden",children:(0,t.jsx)("button",{type:"button",onClick:()=>s?.(e.tool_name),className:"text-left w-full font-mono text-xs max-w-[20ch] truncate block font-medium text-blue-600 hover:text-blue-800 hover:underline focus:outline-none focus:ring-0",children:(0,t.jsx)(N.Tooltip,{title:s?"Click to view details and block for team/key":e.tool_name,children:(0,t.jsx)("span",{children:e.tool_name})})})}),(0,t.jsx)(h.TableCell,{className:"py-0.5 max-h-8",children:(0,t.jsx)(lA,{value:e.input_policy,toolName:e.tool_name,saving:f===e.tool_name,onChange:B,policyType:"input"})}),(0,t.jsx)(h.TableCell,{className:"py-0.5 max-h-8",children:(0,t.jsx)(lA,{value:e.output_policy,toolName:e.tool_name,saving:_===e.tool_name,onChange:q,policyType:"output"})}),(0,t.jsx)(h.TableCell,{className:"py-0.5 max-h-8",children:(0,t.jsx)("div",{className:"flex items-center justify-end h-8 tabular-nums text-sm font-mono text-gray-700",children:(e.call_count??0).toLocaleString()})}),(0,t.jsx)(h.TableCell,{className:"py-0.5 max-h-8 overflow-hidden whitespace-nowrap",children:(0,t.jsx)(N.Tooltip,{title:e.team_id??"-",children:(0,t.jsx)("span",{className:"max-w-[15ch] truncate block",children:e.team_id??"-"})})}),(0,t.jsx)(h.TableCell,{className:"py-0.5 max-h-8 overflow-hidden whitespace-nowrap",children:(0,t.jsx)(N.Tooltip,{title:e.key_hash??"-",children:(0,t.jsx)("span",{className:"font-mono max-w-[15ch] truncate block text-blue-600",children:e.key_hash??"-"})})}),(0,t.jsx)(h.TableCell,{className:"py-0.5 max-h-8 overflow-hidden whitespace-nowrap",children:(0,t.jsx)(N.Tooltip,{title:e.key_alias??"-",children:(0,t.jsx)("span",{className:"max-w-[15ch] truncate block",children:e.key_alias??"-"})})}),(0,t.jsx)(h.TableCell,{className:"py-0.5 max-h-8 overflow-hidden whitespace-nowrap",children:(0,t.jsx)(N.Tooltip,{title:e.user_agent??"-",children:(0,t.jsx)("span",{className:"font-mono max-w-[20ch] truncate block text-xs text-gray-500",children:e.user_agent??"-"})})})]},e.tool_id))})]}),et>1&&(0,t.jsxs)("div",{className:"border-t px-6 py-3 flex items-center justify-between text-sm text-gray-600",children:[(0,t.jsxs)("span",{children:["Showing ",(P-1)*50+1," - ",Math.min(50*P,ee.length)," of"," ",ee.length]}),(0,t.jsxs)("div",{className:"flex gap-1",children:[(0,t.jsx)("button",{onClick:()=>L(e=>Math.max(1,e-1)),disabled:1===P,className:"px-3 py-1.5 border rounded-md hover:bg-gray-50 disabled:opacity-40",children:"Previous"}),(0,t.jsx)("button",{onClick:()=>L(e=>Math.min(et,e+1)),disabled:P===et,className:"px-3 py-1.5 border rounded-md hover:bg-gray-50 disabled:opacity-40",children:"Next"})]})]})]})]})};function l$({accessToken:e,userRole:s}){let[a,l]=(0,i.useState)({type:"overview"});return(0,t.jsx)("div",{className:"p-6 w-full min-w-0 flex-1",children:"detail"===a.type?(0,t.jsx)(lD,{toolName:a.toolName,onBack:()=>{l({type:"overview"})},accessToken:e}):(0,t.jsx)(lq,{accessToken:e,userRole:s,onSelectTool:e=>{l({type:"detail",toolName:e})}})})}var lU=e.i(936190),lH=e.i(910119),lV=e.i(275144),lG=e.i(161281),lK=e.i(321836),lW=e.i(947293),lQ=e.i(618566),lY=e.i(592143);function lJ(e,t="/"){document.cookie=`${e}=; Max-Age=0; Path=${t}`}function lX(){let[e,a]=(0,i.useState)(""),[r,m]=(0,i.useState)(!1),[u,x]=(0,i.useState)(!1),[p,h]=(0,i.useState)(null),[g,y]=(0,i.useState)(null),[j,f]=(0,i.useState)([]),[b,_]=(0,i.useState)([]),[v,N]=(0,i.useState)([]),[w,k]=(0,i.useState)({PROXY_BASE_URL:"",PROXY_LOGOUT_URL:""}),[C,S]=(0,i.useState)(!0),T=(0,lQ.useSearchParams)(),[I,F]=(0,i.useState)({data:[]}),[P,L]=(0,i.useState)(null),[A,M]=(0,i.useState)(!1),[D,E]=(0,i.useState)(!0),[O,R]=(0,i.useState)(null),[z,B]=(0,i.useState)(!0),[q,$]=(0,i.useState)(!1),[U,H]=(0,i.useState)(!1),[V,G]=(0,i.useState)(!1),[K,W]=(0,i.useState)(!1),[Q,Y]=(0,i.useState)(!1),J=T.get("invitation_id"),X="true"===T.get("create"),Z=(0,i.useMemo)(()=>{if(!X)return;let e=T.get("owned_by"),t=T.get("team_id"),s=T.get("key_alias"),a=T.get("models"),l=T.get("key_type");if(!e&&!t&&!s&&!a&&!l)return;let r=e&&["you","service_account","another_user"].includes(e)?e:void 0,i=l&&["default","llm_api","management"].includes(l)?l:void 0,n=s?s.trim().slice(0,256):void 0,o=a?a.split(",").slice(0,100).map(e=>e.trim().slice(0,256)).filter(e=>e.length>0):void 0;return{owned_by:r,team_id:t?.trim()||void 0,key_alias:n,models:o&&o.length>0?o:void 0,key_type:i}},[T,X]),[ee,et]=(0,i.useState)(()=>T.get("page")||"api-keys"),[es,ea]=(0,i.useState)(null),[el,er]=(0,i.useState)(!1),ei=(0,i.useRef)(!1),en=e=>{f(t=>t?[...t,e]:[e]),M(()=>!A)},eo=!1===D&&null===P&&null===J;return((0,i.useEffect)(()=>{let e=!1;return(async()=>{try{await (0,l.getUiConfig)()}catch{}if(e)return;let t=function(e){let t=document.cookie.split("; ").find(t=>t.startsWith(e+"="));if(!t)return null;let s=t.slice(e.length+1);try{return decodeURIComponent(s)}catch{return s}}("token"),s=t&&!(0,lG.isJwtExpired)(t)?t:null;t&&!s&&lJ("token","/"),e||(L(s),E(!1))})(),()=>{e=!0}},[]),(0,i.useEffect)(()=>{if(eo){(0,lK.storeReturnUrl)();let e=(l.proxyBaseUrl||"")+"/ui/login",t=(0,lK.buildLoginUrlWithReturn)(e);window.location.replace(t)}},[eo]),(0,i.useEffect)(()=>{if(D||!P||ei.current)return;ei.current=!0;let e=(0,lK.consumeReturnUrl)();if(e){let t=window.location.href;(0,lK.normalizeUrlForCompare)(e)!==(0,lK.normalizeUrlForCompare)(t)&&window.location.replace(e)}},[D,P]),(0,i.useEffect)(()=>{P||(ei.current=!1)},[P]),(0,i.useEffect)(()=>{if(!P)return;if((0,lG.isJwtExpired)(P)){lJ("token","/"),L(null);return}let e=null;try{e=(0,lW.jwtDecode)(P)}catch{lJ("token","/"),L(null);return}if(e){if(ea(e.key),x(e.disabled_non_admin_personal_key_creation),e.user_role){let t=(0,ek.formatUserRole)(e.user_role);a(t),"Admin Viewer"==t&&et("usage")}e.user_email&&h(e.user_email),e.login_method&&S("username_password"==e.login_method),e.premium_user&&m(e.premium_user),e.auth_header_name&&(0,l.setGlobalLitellmHeaderName)(e.auth_header_name),e.user_id&&R(e.user_id)}},[P]),(0,i.useEffect)(()=>{es&&O&&e&&(0,sJ.fetchUserModels)(O,e,es,N),es&&O&&e&&(0,eG.fetchTeams)(es,O,e,null,y),es&&(0,sX.fetchOrganizations)(es,_)},[es,O,e]),(0,i.useEffect)(()=>{es&&P&&(async()=>{try{let e=await (0,l.getInProductNudgesCall)(es),t=e?.is_claude_code_enabled||!1;H(t),t&&(G(!0),B(!1))}catch(e){console.error("Failed to fetch in-product nudges:",e)}})()},[es,P]),(0,i.useEffect)(()=>{if(z&&!q){let e=setTimeout(()=>{B(!1)},15e3);return()=>clearTimeout(e)}},[z,q]),(0,i.useEffect)(()=>{if(V&&!K){let e=setTimeout(()=>{G(!1)},15e3);return()=>clearTimeout(e)}},[V,K]),D||eo)?(0,t.jsx)(eK.default,{}):(0,t.jsx)(i.Suspense,{fallback:(0,t.jsx)(eK.default,{}),children:(0,t.jsx)(lY.ConfigProvider,{theme:{algorithm:Q?aO.theme.darkAlgorithm:aO.theme.defaultAlgorithm},children:(0,t.jsx)(lV.ThemeProvider,{accessToken:es,children:J?(0,t.jsx)(aS.default,{userID:O,userRole:e,premiumUser:r,teams:g,keys:j,setUserRole:a,userEmail:p,setUserEmail:h,setTeams:y,setKeys:f,organizations:b,addKey:en,createClicked:A}):(0,t.jsxs)("div",{className:"flex flex-col min-h-screen",children:[(0,t.jsx)(sv.default,{userID:O,userRole:e,premiumUser:r,userEmail:p,setProxySettings:k,proxySettings:w,accessToken:es,isPublicPage:!1,sidebarCollapsed:el,onToggleSidebar:()=>{er(!el)},isDarkMode:Q,toggleDarkMode:()=>{Y(!Q)}}),(0,t.jsxs)("div",{className:"flex flex-1",children:[(0,t.jsx)("div",{className:"mt-2",children:(0,t.jsx)(n,{setPage:e=>{let t=new URLSearchParams(T);t.set("page",e),window.history.pushState(null,"",`?${t.toString()}`),et(e)},defaultSelectedKey:ee,sidebarCollapsed:el})}),"api-keys"==ee?(0,t.jsx)(aS.default,{userID:O,userRole:e,premiumUser:r,teams:g,keys:j,setUserRole:a,userEmail:p,setUserEmail:h,setTeams:y,setKeys:f,organizations:b,addKey:en,createClicked:A,autoOpenCreate:X,prefillData:Z}):"models"==ee?(0,t.jsx)(o.default,{token:P,keys:j,modelData:I,setModelData:F,premiumUser:r,teams:g}):"llm-playground"==ee?(0,t.jsx)(d.default,{}):"users"==ee?(0,t.jsx)(lH.default,{userID:O,userRole:e,token:P,keys:j,teams:g,accessToken:es,setKeys:f}):"teams"==ee?(0,t.jsx)(sY,{teams:g,setTeams:y,accessToken:es,userID:O,userRole:e,organizations:b,premiumUser:r,searchParams:T}):"organizations"==ee?(0,t.jsx)(sX.default,{organizations:b,setOrganizations:_,userModels:v,accessToken:es,userRole:e,premiumUser:r}):"admin-panel"==ee?(0,t.jsx)(c.default,{proxySettings:w}):"api_ref"==ee?(0,t.jsx)(s.default,{proxySettings:w}):"logging-and-alerts"==ee?(0,t.jsx)(ai.default,{userID:O,userRole:e,accessToken:es,premiumUser:r}):"budgets"==ee?(0,t.jsx)(eU.default,{accessToken:es}):"guardrails"==ee?(0,t.jsx)(sj.default,{accessToken:es,userRole:e}):"policies"==ee?(0,t.jsx)(sf.default,{accessToken:es,userRole:e}):"agents"==ee?(0,t.jsx)(e$,{accessToken:es,userRole:e,teams:g}):"prompts"==ee?(0,t.jsx)(s0.default,{accessToken:es,userRole:e}):"transform-request"==ee?(0,t.jsx)(aw.default,{accessToken:es}):"router-settings"==ee?(0,t.jsx)(tJ.default,{userID:O,userRole:e,accessToken:es,modelData:I}):"ui-theme"==ee?(0,t.jsx)(ak.default,{userID:O,userRole:e,accessToken:es}):"cost-tracking"==ee?(0,t.jsx)(tY,{userID:O,userRole:e,accessToken:es}):"model-hub-table"==ee?(0,ek.isAdminRole)(e)?(0,t.jsx)(s_.default,{accessToken:es,publicPage:!1,premiumUser:r,userRole:e}):(0,t.jsx)(s1.default,{accessToken:es,isEmbedded:!0}):"caching"==ee?(0,t.jsx)(eH.default,{userID:O,userRole:e,token:P,accessToken:es,premiumUser:r}):"pass-through-settings"==ee?(0,t.jsx)(sZ.default,{userID:O,userRole:e,accessToken:es,modelData:I,premiumUser:r}):"logs"==ee?(0,t.jsx)(lU.default,{userID:O,userRole:e,token:P,accessToken:es,allTeams:g??[],premiumUser:r}):"mcp-servers"==ee?(0,t.jsx)(sb.MCPServers,{accessToken:es,userRole:e,userID:O}):"search-tools"==ee?(0,t.jsx)(ar,{accessToken:es,userRole:e,userID:O}):"tag-management"==ee?(0,t.jsx)(aN.default,{accessToken:es,userRole:e,userID:O}):"claude-code-plugins"==ee?(0,t.jsx)(eV.default,{accessToken:es,userRole:e}):"access-groups"==ee?(0,t.jsx)(lr,{}):"projects"==ee?(0,t.jsx)(lC,{}):"vector-stores"==ee?(0,t.jsx)(lS.default,{accessToken:es,userRole:e,userID:O}):"tool-policies"==ee?(0,t.jsx)(l$,{accessToken:es,userRole:e}):"guardrails-monitor"==ee?(0,t.jsx)(sy,{accessToken:es}):"new_usage"==ee?(0,t.jsx)(sN.default,{teams:g??[],organizations:b??[]}):(0,t.jsx)(aC.default,{userID:O,userRole:e,token:P,accessToken:es,keys:j,premiumUser:r})]}),(0,t.jsx)(ax,{isVisible:z,onOpen:()=>{B(!1),$(!0)},onDismiss:()=>{B(!1)}}),(0,t.jsx)(af,{isOpen:q,onClose:()=>{$(!1),B(!0)},onComplete:()=>{$(!1)}}),(0,t.jsx)(a_,{isVisible:V,onOpen:()=>{G(!1),W(!0)},onDismiss:()=>{G(!1)}}),(0,t.jsx)(av,{isOpen:K,onClose:()=>{W(!1),G(!0)},onComplete:()=>{W(!1)}})]})})})})}function lZ(){return(0,t.jsx)(i.Suspense,{fallback:(0,t.jsx)(eK.default,{}),children:(0,t.jsx)(lX,{})})}e.s(["default",()=>lZ],952683)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/22e715061d511345.js b/litellm/proxy/_experimental/out/_next/static/chunks/22e715061d511345.js new file mode 100644 index 00000000000..56cfe8a5162 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/22e715061d511345.js @@ -0,0 +1,8 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,434626,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("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"}))});e.s(["ExternalLinkIcon",0,r],434626)},902555,e=>{"use strict";var t=e.i(843476),r=e.i(591935),a=e.i(122577),o=e.i(278587),l=e.i(68155),n=e.i(360820),i=e.i(871943),s=e.i(434626),d=e.i(592968),c=e.i(115504),m=e.i(752978);function g({icon:e,onClick:r,className:a,disabled:o,dataTestId:l}){return o?(0,t.jsx)(m.Icon,{icon:e,size:"sm",className:"opacity-50 cursor-not-allowed","data-testid":l}):(0,t.jsx)(m.Icon,{icon:e,size:"sm",onClick:r,className:(0,c.cx)("cursor-pointer",a),"data-testid":l})}let u={Edit:{icon:r.PencilAltIcon,className:"hover:text-blue-600"},Delete:{icon:l.TrashIcon,className:"hover:text-red-600"},Test:{icon:a.PlayIcon,className:"hover:text-blue-600"},Regenerate:{icon:o.RefreshIcon,className:"hover:text-green-600"},Up:{icon:n.ChevronUpIcon,className:"hover:text-blue-600"},Down:{icon:i.ChevronDownIcon,className:"hover:text-blue-600"},Open:{icon:s.ExternalLinkIcon,className:"hover:text-green-600"}};function b({onClick:e,tooltipText:r,disabled:a=!1,disabledTooltipText:o,dataTestId:l,variant:n}){let{icon:i,className:s}=u[n];return(0,t.jsx)(d.Tooltip,{title:a?o:r,children:(0,t.jsx)("span",{children:(0,t.jsx)(g,{icon:i,onClick:e,className:s,disabled:a,dataTestId:l})})})}e.s(["default",()=>b],902555)},122577,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"}),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 12a9 9 0 11-18 0 9 9 0 0118 0z"}))});e.s(["PlayIcon",0,r],122577)},728889,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(829087),o=e.i(480731),l=e.i(444755),n=e.i(673706),i=e.i(95779);let s={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"}},d={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"}},c={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:""}},m=(0,n.makeClassName)("Icon"),g=r.default.forwardRef((e,g)=>{let{icon:u,variant:b="simple",tooltip:h,size:f=o.Sizes.SM,color:p,className:C}=e,k=(0,t.__rest)(e,["icon","variant","tooltip","size","color","className"]),x=((e,t)=>{switch(e){case"simple":return{textColor:t?(0,n.getColorClassNames)(t,i.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",bgColor:"",borderColor:"",ringColor:""};case"light":return{textColor:t?(0,n.getColorClassNames)(t,i.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",bgColor:t?(0,l.tremorTwMerge)((0,n.getColorClassNames)(t,i.colorPalette.background).bgColor,"bg-opacity-20"):"bg-tremor-brand-muted dark:bg-dark-tremor-brand-muted",borderColor:"",ringColor:""};case"shadow":return{textColor:t?(0,n.getColorClassNames)(t,i.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",bgColor:t?(0,l.tremorTwMerge)((0,n.getColorClassNames)(t,i.colorPalette.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:t?(0,n.getColorClassNames)(t,i.colorPalette.text).textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",bgColor:t?(0,l.tremorTwMerge)((0,n.getColorClassNames)(t,i.colorPalette.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:t?(0,n.getColorClassNames)(t,i.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",bgColor:t?(0,l.tremorTwMerge)((0,n.getColorClassNames)(t,i.colorPalette.background).bgColor,"bg-opacity-20"):"bg-tremor-background dark:bg-dark-tremor-background",borderColor:t?(0,n.getColorClassNames)(t,i.colorPalette.ring).borderColor:"border-tremor-brand-subtle dark:border-dark-tremor-brand-subtle",ringColor:t?(0,l.tremorTwMerge)((0,n.getColorClassNames)(t,i.colorPalette.ring).ringColor,"ring-opacity-40"):"ring-tremor-brand-muted dark:ring-dark-tremor-brand-muted"}}})(b,p),{tooltipProps:w,getReferenceProps:v}=(0,a.useTooltip)();return r.default.createElement("span",Object.assign({ref:(0,n.mergeRefs)([g,w.refs.setReference]),className:(0,l.tremorTwMerge)(m("root"),"inline-flex shrink-0 items-center justify-center",x.bgColor,x.textColor,x.borderColor,x.ringColor,c[b].rounded,c[b].border,c[b].shadow,c[b].ring,s[f].paddingX,s[f].paddingY,C)},v,k),r.default.createElement(a.default,Object.assign({text:h},w)),r.default.createElement(u,{className:(0,l.tremorTwMerge)(m("icon"),"shrink-0",d[f].height,d[f].width)}))});g.displayName="Icon",e.s(["default",()=>g],728889)},752978,e=>{"use strict";var t=e.i(728889);e.s(["Icon",()=>t.default])},591935,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.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.s(["PencilAltIcon",0,r],591935)},599724,936325,e=>{"use strict";var t=e.i(95779),r=e.i(444755),a=e.i(673706),o=e.i(271645);let l=o.default.forwardRef((e,l)=>{let{color:n,className:i,children:s}=e;return o.default.createElement("p",{ref:l,className:(0,r.tremorTwMerge)("text-tremor-default",n?(0,a.getColorClassNames)(n,t.colorPalette.text).textColor:(0,r.tremorTwMerge)("text-tremor-content","dark:text-dark-tremor-content"),i)},s)});l.displayName="Text",e.s(["default",()=>l],936325),e.s(["Text",()=>l],599724)},994388,e=>{"use strict";var t=e.i(290571),r=e.i(829087),a=e.i(271645);let o=["preEnter","entering","entered","preExit","exiting","exited","unmounted"],l=e=>({_s:e,status:o[e],isEnter:e<3,isMounted:6!==e,isResolved:2===e||e>4}),n=e=>e?6:5,i=(e,t,r,a,o)=>{clearTimeout(a.current);let n=l(e);t(n),r.current=n,o&&o({current:n})};var s=e.i(480731),d=e.i(444755),c=e.i(673706);let m=e=>{var r=(0,t.__rest)(e,[]);return a.default.createElement("svg",Object.assign({},r,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"}),a.default.createElement("path",{fill:"none",d:"M0 0h24v24H0z"}),a.default.createElement("path",{d:"M18.364 5.636L16.95 7.05A7 7 0 1 0 19 12h2a9 9 0 1 1-2.636-6.364z"}))};var g=e.i(95779);let u={xs:{height:"h-4",width:"w-4"},sm:{height:"h-5",width:"w-5"},md:{height:"h-5",width:"w-5"},lg:{height:"h-6",width:"w-6"},xl:{height:"h-6",width:"w-6"}},b=(e,t)=>{switch(e){case"primary":return{textColor:t?(0,c.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",hoverTextColor:t?(0,c.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",bgColor:t?(0,c.getColorClassNames)(t,g.colorPalette.background).bgColor:"bg-tremor-brand dark:bg-dark-tremor-brand",hoverBgColor:t?(0,c.getColorClassNames)(t,g.colorPalette.darkBackground).hoverBgColor:"hover:bg-tremor-brand-emphasis dark:hover:bg-dark-tremor-brand-emphasis",borderColor:t?(0,c.getColorClassNames)(t,g.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",hoverBorderColor:t?(0,c.getColorClassNames)(t,g.colorPalette.darkBorder).hoverBorderColor:"hover:border-tremor-brand-emphasis dark:hover:border-dark-tremor-brand-emphasis"};case"secondary":return{textColor:t?(0,c.getColorClassNames)(t,g.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,c.getColorClassNames)(t,g.colorPalette.text).textColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,c.getColorClassNames)("transparent").bgColor,hoverBgColor:t?(0,d.tremorTwMerge)((0,c.getColorClassNames)(t,g.colorPalette.background).hoverBgColor,"hover:bg-opacity-20 dark:hover:bg-opacity-20"):"hover:bg-tremor-brand-faint dark:hover:bg-dark-tremor-brand-faint",borderColor:t?(0,c.getColorClassNames)(t,g.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand"};case"light":return{textColor:t?(0,c.getColorClassNames)(t,g.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,c.getColorClassNames)(t,g.colorPalette.darkText).hoverTextColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,c.getColorClassNames)("transparent").bgColor,borderColor:"",hoverBorderColor:""}}},h=(0,c.makeClassName)("Button"),f=({loading:e,iconSize:t,iconPosition:r,Icon:o,needMargin:l,transitionStatus:n})=>{let i=l?r===s.HorizontalPositions.Left?(0,d.tremorTwMerge)("-ml-1","mr-1.5"):(0,d.tremorTwMerge)("-mr-1","ml-1.5"):"",c=(0,d.tremorTwMerge)("w-0 h-0"),g={default:c,entering:c,entered:t,exiting:t,exited:c};return e?a.default.createElement(m,{className:(0,d.tremorTwMerge)(h("icon"),"animate-spin shrink-0",i,g.default,g[n]),style:{transition:"width 150ms"}}):a.default.createElement(o,{className:(0,d.tremorTwMerge)(h("icon"),"shrink-0",t,i)})},p=a.default.forwardRef((e,o)=>{let{icon:m,iconPosition:g=s.HorizontalPositions.Left,size:p=s.Sizes.SM,color:C,variant:k="primary",disabled:x,loading:w=!1,loadingText:v,children:N,tooltip:$,className:j}=e,T=(0,t.__rest)(e,["icon","iconPosition","size","color","variant","disabled","loading","loadingText","children","tooltip","className"]),y=w||x,E=void 0!==m||w,O=w&&v,M=!(!N&&!O),R=(0,d.tremorTwMerge)(u[p].height,u[p].width),P="light"!==k?(0,d.tremorTwMerge)("rounded-tremor-default border","shadow-tremor-input","dark:shadow-dark-tremor-input"):"",z=b(k,C),B=("light"!==k?{xs:{paddingX:"px-2.5",paddingY:"py-1.5",fontSize:"text-xs"},sm:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-sm"},md:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-md"},lg:{paddingX:"px-4",paddingY:"py-2.5",fontSize:"text-lg"},xl:{paddingX:"px-4",paddingY:"py-3",fontSize:"text-xl"}}:{xs:{paddingX:"",paddingY:"",fontSize:"text-xs"},sm:{paddingX:"",paddingY:"",fontSize:"text-sm"},md:{paddingX:"",paddingY:"",fontSize:"text-md"},lg:{paddingX:"",paddingY:"",fontSize:"text-lg"},xl:{paddingX:"",paddingY:"",fontSize:"text-xl"}})[p],{tooltipProps:S,getReferenceProps:I}=(0,r.useTooltip)(300),[L,q]=(({enter:e=!0,exit:t=!0,preEnter:r,preExit:o,timeout:s,initialEntered:d,mountOnEnter:c,unmountOnExit:m,onStateChange:g}={})=>{let[u,b]=(0,a.useState)(()=>l(d?2:n(c))),h=(0,a.useRef)(u),f=(0,a.useRef)(0),[p,C]="object"==typeof s?[s.enter,s.exit]:[s,s],k=(0,a.useCallback)(()=>{let e=((e,t)=>{switch(e){case 1:case 0:return 2;case 4:case 3:return n(t)}})(h.current._s,m);e&&i(e,b,h,f,g)},[g,m]);return[u,(0,a.useCallback)(a=>{let l=e=>{switch(i(e,b,h,f,g),e){case 1:p>=0&&(f.current=((...e)=>setTimeout(...e))(k,p));break;case 4:C>=0&&(f.current=((...e)=>setTimeout(...e))(k,C));break;case 0:case 3:f.current=((...e)=>setTimeout(...e))(()=>{isNaN(document.body.offsetTop)||l(e+1)},0)}},s=h.current.isEnter;"boolean"!=typeof a&&(a=!s),a?s||l(e?+!r:2):s&&l(t?o?3:4:n(m))},[k,g,e,t,r,o,p,C,m]),k]})({timeout:50});return(0,a.useEffect)(()=>{q(w)},[w]),a.default.createElement("button",Object.assign({ref:(0,c.mergeRefs)([o,S.refs.setReference]),className:(0,d.tremorTwMerge)(h("root"),"shrink-0 inline-flex justify-center items-center group font-medium outline-none",P,B.paddingX,B.paddingY,B.fontSize,z.textColor,z.bgColor,z.borderColor,z.hoverBorderColor,y?"opacity-50 cursor-not-allowed":(0,d.tremorTwMerge)(b(k,C).hoverTextColor,b(k,C).hoverBgColor,b(k,C).hoverBorderColor),j),disabled:y},I,T),a.default.createElement(r.default,Object.assign({text:$},S)),E&&g!==s.HorizontalPositions.Right?a.default.createElement(f,{loading:w,iconSize:R,iconPosition:g,Icon:m,transitionStatus:L.status,needMargin:M}):null,O||N?a.default.createElement("span",{className:(0,d.tremorTwMerge)(h("text"),"text-tremor-default whitespace-nowrap")},O?v:N):null,E&&g===s.HorizontalPositions.Right?a.default.createElement(f,{loading:w,iconSize:R,iconPosition:g,Icon:m,transitionStatus:L.status,needMargin:M}):null)});p.displayName="Button",e.s(["Button",()=>p],994388)},304967,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(480731),o=e.i(95779),l=e.i(444755),n=e.i(673706);let i=(0,n.makeClassName)("Card"),s=r.default.forwardRef((e,s)=>{let{decoration:d="",decorationColor:c,children:m,className:g}=e,u=(0,t.__rest)(e,["decoration","decorationColor","children","className"]);return r.default.createElement("div",Object.assign({ref:s,className:(0,l.tremorTwMerge)(i("root"),"relative w-full text-left ring-1 rounded-tremor-default p-6","bg-tremor-background ring-tremor-ring shadow-tremor-card","dark:bg-dark-tremor-background dark:ring-dark-tremor-ring dark:shadow-dark-tremor-card",c?(0,n.getColorClassNames)(c,o.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",(e=>{if(!e)return"";switch(e){case a.HorizontalPositions.Left:return"border-l-4";case a.VerticalPositions.Top:return"border-t-4";case a.HorizontalPositions.Right:return"border-r-4";case a.VerticalPositions.Bottom:return"border-b-4";default:return""}})(d),g)},u),m)});s.displayName="Card",e.s(["Card",()=>s],304967)},185793,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),a=e.i(242064),o=e.i(529681);let l=e=>{let{prefixCls:a,className:o,style:l,size:n,shape:i}=e,s=(0,r.default)({[`${a}-lg`]:"large"===n,[`${a}-sm`]:"small"===n}),d=(0,r.default)({[`${a}-circle`]:"circle"===i,[`${a}-square`]:"square"===i,[`${a}-round`]:"round"===i}),c=t.useMemo(()=>"number"==typeof n?{width:n,height:n,lineHeight:`${n}px`}:{},[n]);return t.createElement("span",{className:(0,r.default)(a,s,d,o),style:Object.assign(Object.assign({},c),l)})};e.i(296059);var n=e.i(694758),i=e.i(915654),s=e.i(246422),d=e.i(838378);let c=new n.Keyframes("ant-skeleton-loading",{"0%":{backgroundPosition:"100% 50%"},"100%":{backgroundPosition:"0 50%"}}),m=e=>({height:e,lineHeight:(0,i.unit)(e)}),g=e=>Object.assign({width:e},m(e)),u=(e,t)=>Object.assign({width:t(e).mul(5).equal(),minWidth:t(e).mul(5).equal()},m(e)),b=e=>Object.assign({width:e},m(e)),h=(e,t,r)=>{let{skeletonButtonCls:a}=e;return{[`${r}${a}-circle`]:{width:t,minWidth:t,borderRadius:"50%"},[`${r}${a}-round`]:{borderRadius:t}}},f=(e,t)=>Object.assign({width:t(e).mul(2).equal(),minWidth:t(e).mul(2).equal()},m(e)),p=(0,s.genStyleHooks)("Skeleton",e=>{let{componentCls:t,calc:r}=e;return(e=>{let{componentCls:t,skeletonAvatarCls:r,skeletonTitleCls:a,skeletonParagraphCls:o,skeletonButtonCls:l,skeletonInputCls:n,skeletonImageCls:i,controlHeight:s,controlHeightLG:d,controlHeightSM:m,gradientFromColor:p,padding:C,marginSM:k,borderRadius:x,titleHeight:w,blockRadius:v,paragraphLiHeight:N,controlHeightXS:$,paragraphMarginTop:j}=e;return{[t]:{display:"table",width:"100%",[`${t}-header`]:{display:"table-cell",paddingInlineEnd:C,verticalAlign:"top",[r]:Object.assign({display:"inline-block",verticalAlign:"top",background:p},g(s)),[`${r}-circle`]:{borderRadius:"50%"},[`${r}-lg`]:Object.assign({},g(d)),[`${r}-sm`]:Object.assign({},g(m))},[`${t}-content`]:{display:"table-cell",width:"100%",verticalAlign:"top",[a]:{width:"100%",height:w,background:p,borderRadius:v,[`+ ${o}`]:{marginBlockStart:m}},[o]:{padding:0,"> li":{width:"100%",height:N,listStyle:"none",background:p,borderRadius:v,"+ li":{marginBlockStart:$}}},[`${o}> li:last-child:not(:first-child):not(:nth-child(2))`]:{width:"61%"}},[`&-round ${t}-content`]:{[`${a}, ${o} > li`]:{borderRadius:x}}},[`${t}-with-avatar ${t}-content`]:{[a]:{marginBlockStart:k,[`+ ${o}`]:{marginBlockStart:j}}},[`${t}${t}-element`]:Object.assign(Object.assign(Object.assign(Object.assign({display:"inline-block",width:"auto"},(e=>{let{borderRadiusSM:t,skeletonButtonCls:r,controlHeight:a,controlHeightLG:o,controlHeightSM:l,gradientFromColor:n,calc:i}=e;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({[r]:Object.assign({display:"inline-block",verticalAlign:"top",background:n,borderRadius:t,width:i(a).mul(2).equal(),minWidth:i(a).mul(2).equal()},f(a,i))},h(e,a,r)),{[`${r}-lg`]:Object.assign({},f(o,i))}),h(e,o,`${r}-lg`)),{[`${r}-sm`]:Object.assign({},f(l,i))}),h(e,l,`${r}-sm`))})(e)),(e=>{let{skeletonAvatarCls:t,gradientFromColor:r,controlHeight:a,controlHeightLG:o,controlHeightSM:l}=e;return{[t]:Object.assign({display:"inline-block",verticalAlign:"top",background:r},g(a)),[`${t}${t}-circle`]:{borderRadius:"50%"},[`${t}${t}-lg`]:Object.assign({},g(o)),[`${t}${t}-sm`]:Object.assign({},g(l))}})(e)),(e=>{let{controlHeight:t,borderRadiusSM:r,skeletonInputCls:a,controlHeightLG:o,controlHeightSM:l,gradientFromColor:n,calc:i}=e;return{[a]:Object.assign({display:"inline-block",verticalAlign:"top",background:n,borderRadius:r},u(t,i)),[`${a}-lg`]:Object.assign({},u(o,i)),[`${a}-sm`]:Object.assign({},u(l,i))}})(e)),(e=>{let{skeletonImageCls:t,imageSizeBase:r,gradientFromColor:a,borderRadiusSM:o,calc:l}=e;return{[t]:Object.assign(Object.assign({display:"inline-flex",alignItems:"center",justifyContent:"center",verticalAlign:"middle",background:a,borderRadius:o},b(l(r).mul(2).equal())),{[`${t}-path`]:{fill:"#bfbfbf"},[`${t}-svg`]:Object.assign(Object.assign({},b(r)),{maxWidth:l(r).mul(4).equal(),maxHeight:l(r).mul(4).equal()}),[`${t}-svg${t}-svg-circle`]:{borderRadius:"50%"}}),[`${t}${t}-circle`]:{borderRadius:"50%"}}})(e)),[`${t}${t}-block`]:{width:"100%",[l]:{width:"100%"},[n]:{width:"100%"}},[`${t}${t}-active`]:{[` + ${a}, + ${o} > li, + ${r}, + ${l}, + ${n}, + ${i} + `]:Object.assign({},{background:e.skeletonLoadingBackground,backgroundSize:"400% 100%",animationName:c,animationDuration:e.skeletonLoadingMotionDuration,animationTimingFunction:"ease",animationIterationCount:"infinite"})}}})((0,d.mergeToken)(e,{skeletonAvatarCls:`${t}-avatar`,skeletonTitleCls:`${t}-title`,skeletonParagraphCls:`${t}-paragraph`,skeletonButtonCls:`${t}-button`,skeletonInputCls:`${t}-input`,skeletonImageCls:`${t}-image`,imageSizeBase:r(e.controlHeight).mul(1.5).equal(),borderRadius:100,skeletonLoadingBackground:`linear-gradient(90deg, ${e.gradientFromColor} 25%, ${e.gradientToColor} 37%, ${e.gradientFromColor} 63%)`,skeletonLoadingMotionDuration:"1.4s"}))},e=>{let{colorFillContent:t,colorFill:r}=e;return{color:t,colorGradientEnd:r,gradientFromColor:t,gradientToColor:r,titleHeight:e.controlHeight/2,blockRadius:e.borderRadiusSM,paragraphMarginTop:e.marginLG+e.marginXXS,paragraphLiHeight:e.controlHeight/2}},{deprecatedTokens:[["color","gradientFromColor"],["colorGradientEnd","gradientToColor"]]}),C=e=>{let{prefixCls:a,className:o,style:l,rows:n=0}=e,i=Array.from({length:n}).map((r,a)=>t.createElement("li",{key:a,style:{width:((e,t)=>{let{width:r,rows:a=2}=t;return Array.isArray(r)?r[e]:a-1===e?r:void 0})(a,e)}}));return t.createElement("ul",{className:(0,r.default)(a,o),style:l},i)},k=({prefixCls:e,className:a,width:o,style:l})=>t.createElement("h3",{className:(0,r.default)(e,a),style:Object.assign({width:o},l)});function x(e){return e&&"object"==typeof e?e:{}}let w=e=>{let{prefixCls:o,loading:n,className:i,rootClassName:s,style:d,children:c,avatar:m=!1,title:g=!0,paragraph:u=!0,active:b,round:h}=e,{getPrefixCls:f,direction:w,className:v,style:N}=(0,a.useComponentConfig)("skeleton"),$=f("skeleton",o),[j,T,y]=p($);if(n||!("loading"in e)){let e,a,o=!!m,n=!!g,c=!!u;if(o){let r=Object.assign(Object.assign({prefixCls:`${$}-avatar`},n&&!c?{size:"large",shape:"square"}:{size:"large",shape:"circle"}),x(m));e=t.createElement("div",{className:`${$}-header`},t.createElement(l,Object.assign({},r)))}if(n||c){let e,r;if(n){let r=Object.assign(Object.assign({prefixCls:`${$}-title`},!o&&c?{width:"38%"}:o&&c?{width:"50%"}:{}),x(g));e=t.createElement(k,Object.assign({},r))}if(c){let e,a=Object.assign(Object.assign({prefixCls:`${$}-paragraph`},(e={},o&&n||(e.width="61%"),!o&&n?e.rows=3:e.rows=2,e)),x(u));r=t.createElement(C,Object.assign({},a))}a=t.createElement("div",{className:`${$}-content`},e,r)}let f=(0,r.default)($,{[`${$}-with-avatar`]:o,[`${$}-active`]:b,[`${$}-rtl`]:"rtl"===w,[`${$}-round`]:h},v,i,s,T,y);return j(t.createElement("div",{className:f,style:Object.assign(Object.assign({},N),d)},e,a))}return null!=c?c:null};w.Button=e=>{let{prefixCls:n,className:i,rootClassName:s,active:d,block:c=!1,size:m="default"}=e,{getPrefixCls:g}=t.useContext(a.ConfigContext),u=g("skeleton",n),[b,h,f]=p(u),C=(0,o.default)(e,["prefixCls"]),k=(0,r.default)(u,`${u}-element`,{[`${u}-active`]:d,[`${u}-block`]:c},i,s,h,f);return b(t.createElement("div",{className:k},t.createElement(l,Object.assign({prefixCls:`${u}-button`,size:m},C))))},w.Avatar=e=>{let{prefixCls:n,className:i,rootClassName:s,active:d,shape:c="circle",size:m="default"}=e,{getPrefixCls:g}=t.useContext(a.ConfigContext),u=g("skeleton",n),[b,h,f]=p(u),C=(0,o.default)(e,["prefixCls","className"]),k=(0,r.default)(u,`${u}-element`,{[`${u}-active`]:d},i,s,h,f);return b(t.createElement("div",{className:k},t.createElement(l,Object.assign({prefixCls:`${u}-avatar`,shape:c,size:m},C))))},w.Input=e=>{let{prefixCls:n,className:i,rootClassName:s,active:d,block:c,size:m="default"}=e,{getPrefixCls:g}=t.useContext(a.ConfigContext),u=g("skeleton",n),[b,h,f]=p(u),C=(0,o.default)(e,["prefixCls"]),k=(0,r.default)(u,`${u}-element`,{[`${u}-active`]:d,[`${u}-block`]:c},i,s,h,f);return b(t.createElement("div",{className:k},t.createElement(l,Object.assign({prefixCls:`${u}-input`,size:m},C))))},w.Image=e=>{let{prefixCls:o,className:l,rootClassName:n,style:i,active:s}=e,{getPrefixCls:d}=t.useContext(a.ConfigContext),c=d("skeleton",o),[m,g,u]=p(c),b=(0,r.default)(c,`${c}-element`,{[`${c}-active`]:s},l,n,g,u);return m(t.createElement("div",{className:b},t.createElement("div",{className:(0,r.default)(`${c}-image`,l),style:i},t.createElement("svg",{viewBox:"0 0 1098 1024",xmlns:"http://www.w3.org/2000/svg",className:`${c}-image-svg`},t.createElement("title",null,"Image placeholder"),t.createElement("path",{d:"M365.714286 329.142857q0 45.714286-32.036571 77.677714t-77.677714 32.036571-77.677714-32.036571-32.036571-77.677714 32.036571-77.677714 77.677714-32.036571 77.677714 32.036571 32.036571 77.677714zM950.857143 548.571429l0 256-804.571429 0 0-109.714286 182.857143-182.857143 91.428571 91.428571 292.571429-292.571429zM1005.714286 146.285714l-914.285714 0q-7.460571 0-12.873143 5.412571t-5.412571 12.873143l0 694.857143q0 7.460571 5.412571 12.873143t12.873143 5.412571l914.285714 0q7.460571 0 12.873143-5.412571t5.412571-12.873143l0-694.857143q0-7.460571-5.412571-12.873143t-12.873143-5.412571zM1097.142857 164.571429l0 694.857143q0 37.741714-26.843429 64.585143t-64.585143 26.843429l-914.285714 0q-37.741714 0-64.585143-26.843429t-26.843429-64.585143l0-694.857143q0-37.741714 26.843429-64.585143t64.585143-26.843429l914.285714 0q37.741714 0 64.585143 26.843429t26.843429 64.585143z",className:`${c}-image-path`})))))},w.Node=e=>{let{prefixCls:o,className:l,rootClassName:n,style:i,active:s,children:d}=e,{getPrefixCls:c}=t.useContext(a.ConfigContext),m=c("skeleton",o),[g,u,b]=p(m),h=(0,r.default)(m,`${m}-element`,{[`${m}-active`]:s},u,l,n,b);return g(t.createElement("div",{className:h},t.createElement("div",{className:(0,r.default)(`${m}-image`,l),style:i},d)))},e.s(["default",0,w],185793)},959013,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8z"}},{tag:"path",attrs:{d:"M192 474h672q8 0 8 8v60q0 8-8 8H160q-8 0-8-8v-60q0-8 8-8z"}}]},name:"plus",theme:"outlined"};var o=e.i(9583),l=r.forwardRef(function(e,l){return r.createElement(o.default,(0,t.default)({},e,{ref:l,icon:a}))});e.s(["default",0,l],959013)},269200,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let o=(0,e.i(673706).makeClassName)("Table"),l=r.default.forwardRef((e,l)=>{let{children:n,className:i}=e,s=(0,t.__rest)(e,["children","className"]);return r.default.createElement("div",{className:(0,a.tremorTwMerge)(o("root"),"overflow-auto",i)},r.default.createElement("table",Object.assign({ref:l,className:(0,a.tremorTwMerge)(o("table"),"w-full text-tremor-default","text-tremor-content","dark:text-dark-tremor-content")},s),n))});l.displayName="Table",e.s(["Table",()=>l],269200)},942232,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let o=(0,e.i(673706).makeClassName)("TableBody"),l=r.default.forwardRef((e,l)=>{let{children:n,className:i}=e,s=(0,t.__rest)(e,["children","className"]);return r.default.createElement(r.default.Fragment,null,r.default.createElement("tbody",Object.assign({ref:l,className:(0,a.tremorTwMerge)(o("root"),"align-top divide-y","divide-tremor-border","dark:divide-dark-tremor-border",i)},s),n))});l.displayName="TableBody",e.s(["TableBody",()=>l],942232)},977572,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let o=(0,e.i(673706).makeClassName)("TableCell"),l=r.default.forwardRef((e,l)=>{let{children:n,className:i}=e,s=(0,t.__rest)(e,["children","className"]);return r.default.createElement(r.default.Fragment,null,r.default.createElement("td",Object.assign({ref:l,className:(0,a.tremorTwMerge)(o("root"),"align-middle whitespace-nowrap text-left p-4",i)},s),n))});l.displayName="TableCell",e.s(["TableCell",()=>l],977572)},427612,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let o=(0,e.i(673706).makeClassName)("TableHead"),l=r.default.forwardRef((e,l)=>{let{children:n,className:i}=e,s=(0,t.__rest)(e,["children","className"]);return r.default.createElement(r.default.Fragment,null,r.default.createElement("thead",Object.assign({ref:l,className:(0,a.tremorTwMerge)(o("root"),"text-left","text-tremor-content","dark:text-dark-tremor-content",i)},s),n))});l.displayName="TableHead",e.s(["TableHead",()=>l],427612)},64848,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let o=(0,e.i(673706).makeClassName)("TableHeaderCell"),l=r.default.forwardRef((e,l)=>{let{children:n,className:i}=e,s=(0,t.__rest)(e,["children","className"]);return r.default.createElement(r.default.Fragment,null,r.default.createElement("th",Object.assign({ref:l,className:(0,a.tremorTwMerge)(o("root"),"whitespace-nowrap text-left font-semibold top-0 px-4 py-3.5","text-tremor-content-strong","dark:text-dark-tremor-content-strong",i)},s),n))});l.displayName="TableHeaderCell",e.s(["TableHeaderCell",()=>l],64848)},496020,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let o=(0,e.i(673706).makeClassName)("TableRow"),l=r.default.forwardRef((e,l)=>{let{children:n,className:i}=e,s=(0,t.__rest)(e,["children","className"]);return r.default.createElement(r.default.Fragment,null,r.default.createElement("tr",Object.assign({ref:l,className:(0,a.tremorTwMerge)(o("row"),i)},s),n))});l.displayName="TableRow",e.s(["TableRow",()=>l],496020)},68155,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.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.s(["TrashIcon",0,r],68155)},360820,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 15l7-7 7 7"}))});e.s(["ChevronUpIcon",0,r],360820)},871943,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"}))});e.s(["ChevronDownIcon",0,r],871943)},278587,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",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"}))});e.s(["RefreshIcon",0,r],278587)},207670,e=>{"use strict";function t(){for(var e,t,r=0,a="",o=arguments.length;rt,"default",0,t])}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/23887804eaacee0d.js b/litellm/proxy/_experimental/out/_next/static/chunks/23887804eaacee0d.js deleted file mode 100644 index 4019ec21b4d..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/23887804eaacee0d.js +++ /dev/null @@ -1,23 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,185793,e=>{"use strict";e.i(247167);var t=e.i(271645),l=e.i(343794),a=e.i(242064),n=e.i(529681);let r=e=>{let{prefixCls:a,className:n,style:r,size:i,shape:o}=e,s=(0,l.default)({[`${a}-lg`]:"large"===i,[`${a}-sm`]:"small"===i}),d=(0,l.default)({[`${a}-circle`]:"circle"===o,[`${a}-square`]:"square"===o,[`${a}-round`]:"round"===o}),c=t.useMemo(()=>"number"==typeof i?{width:i,height:i,lineHeight:`${i}px`}:{},[i]);return t.createElement("span",{className:(0,l.default)(a,s,d,n),style:Object.assign(Object.assign({},c),r)})};e.i(296059);var i=e.i(694758),o=e.i(915654),s=e.i(246422),d=e.i(838378);let c=new i.Keyframes("ant-skeleton-loading",{"0%":{backgroundPosition:"100% 50%"},"100%":{backgroundPosition:"0 50%"}}),u=e=>({height:e,lineHeight:(0,o.unit)(e)}),g=e=>Object.assign({width:e},u(e)),m=(e,t)=>Object.assign({width:t(e).mul(5).equal(),minWidth:t(e).mul(5).equal()},u(e)),b=e=>Object.assign({width:e},u(e)),f=(e,t,l)=>{let{skeletonButtonCls:a}=e;return{[`${l}${a}-circle`]:{width:t,minWidth:t,borderRadius:"50%"},[`${l}${a}-round`]:{borderRadius:t}}},p=(e,t)=>Object.assign({width:t(e).mul(2).equal(),minWidth:t(e).mul(2).equal()},u(e)),h=(0,s.genStyleHooks)("Skeleton",e=>{let{componentCls:t,calc:l}=e;return(e=>{let{componentCls:t,skeletonAvatarCls:l,skeletonTitleCls:a,skeletonParagraphCls:n,skeletonButtonCls:r,skeletonInputCls:i,skeletonImageCls:o,controlHeight:s,controlHeightLG:d,controlHeightSM:u,gradientFromColor:h,padding:$,marginSM:v,borderRadius:y,titleHeight:O,blockRadius:x,paragraphLiHeight:j,controlHeightXS:C,paragraphMarginTop:k}=e;return{[t]:{display:"table",width:"100%",[`${t}-header`]:{display:"table-cell",paddingInlineEnd:$,verticalAlign:"top",[l]:Object.assign({display:"inline-block",verticalAlign:"top",background:h},g(s)),[`${l}-circle`]:{borderRadius:"50%"},[`${l}-lg`]:Object.assign({},g(d)),[`${l}-sm`]:Object.assign({},g(u))},[`${t}-content`]:{display:"table-cell",width:"100%",verticalAlign:"top",[a]:{width:"100%",height:O,background:h,borderRadius:x,[`+ ${n}`]:{marginBlockStart:u}},[n]:{padding:0,"> li":{width:"100%",height:j,listStyle:"none",background:h,borderRadius:x,"+ li":{marginBlockStart:C}}},[`${n}> li:last-child:not(:first-child):not(:nth-child(2))`]:{width:"61%"}},[`&-round ${t}-content`]:{[`${a}, ${n} > li`]:{borderRadius:y}}},[`${t}-with-avatar ${t}-content`]:{[a]:{marginBlockStart:v,[`+ ${n}`]:{marginBlockStart:k}}},[`${t}${t}-element`]:Object.assign(Object.assign(Object.assign(Object.assign({display:"inline-block",width:"auto"},(e=>{let{borderRadiusSM:t,skeletonButtonCls:l,controlHeight:a,controlHeightLG:n,controlHeightSM:r,gradientFromColor:i,calc:o}=e;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({[l]:Object.assign({display:"inline-block",verticalAlign:"top",background:i,borderRadius:t,width:o(a).mul(2).equal(),minWidth:o(a).mul(2).equal()},p(a,o))},f(e,a,l)),{[`${l}-lg`]:Object.assign({},p(n,o))}),f(e,n,`${l}-lg`)),{[`${l}-sm`]:Object.assign({},p(r,o))}),f(e,r,`${l}-sm`))})(e)),(e=>{let{skeletonAvatarCls:t,gradientFromColor:l,controlHeight:a,controlHeightLG:n,controlHeightSM:r}=e;return{[t]:Object.assign({display:"inline-block",verticalAlign:"top",background:l},g(a)),[`${t}${t}-circle`]:{borderRadius:"50%"},[`${t}${t}-lg`]:Object.assign({},g(n)),[`${t}${t}-sm`]:Object.assign({},g(r))}})(e)),(e=>{let{controlHeight:t,borderRadiusSM:l,skeletonInputCls:a,controlHeightLG:n,controlHeightSM:r,gradientFromColor:i,calc:o}=e;return{[a]:Object.assign({display:"inline-block",verticalAlign:"top",background:i,borderRadius:l},m(t,o)),[`${a}-lg`]:Object.assign({},m(n,o)),[`${a}-sm`]:Object.assign({},m(r,o))}})(e)),(e=>{let{skeletonImageCls:t,imageSizeBase:l,gradientFromColor:a,borderRadiusSM:n,calc:r}=e;return{[t]:Object.assign(Object.assign({display:"inline-flex",alignItems:"center",justifyContent:"center",verticalAlign:"middle",background:a,borderRadius:n},b(r(l).mul(2).equal())),{[`${t}-path`]:{fill:"#bfbfbf"},[`${t}-svg`]:Object.assign(Object.assign({},b(l)),{maxWidth:r(l).mul(4).equal(),maxHeight:r(l).mul(4).equal()}),[`${t}-svg${t}-svg-circle`]:{borderRadius:"50%"}}),[`${t}${t}-circle`]:{borderRadius:"50%"}}})(e)),[`${t}${t}-block`]:{width:"100%",[r]:{width:"100%"},[i]:{width:"100%"}},[`${t}${t}-active`]:{[` - ${a}, - ${n} > li, - ${l}, - ${r}, - ${i}, - ${o} - `]:Object.assign({},{background:e.skeletonLoadingBackground,backgroundSize:"400% 100%",animationName:c,animationDuration:e.skeletonLoadingMotionDuration,animationTimingFunction:"ease",animationIterationCount:"infinite"})}}})((0,d.mergeToken)(e,{skeletonAvatarCls:`${t}-avatar`,skeletonTitleCls:`${t}-title`,skeletonParagraphCls:`${t}-paragraph`,skeletonButtonCls:`${t}-button`,skeletonInputCls:`${t}-input`,skeletonImageCls:`${t}-image`,imageSizeBase:l(e.controlHeight).mul(1.5).equal(),borderRadius:100,skeletonLoadingBackground:`linear-gradient(90deg, ${e.gradientFromColor} 25%, ${e.gradientToColor} 37%, ${e.gradientFromColor} 63%)`,skeletonLoadingMotionDuration:"1.4s"}))},e=>{let{colorFillContent:t,colorFill:l}=e;return{color:t,colorGradientEnd:l,gradientFromColor:t,gradientToColor:l,titleHeight:e.controlHeight/2,blockRadius:e.borderRadiusSM,paragraphMarginTop:e.marginLG+e.marginXXS,paragraphLiHeight:e.controlHeight/2}},{deprecatedTokens:[["color","gradientFromColor"],["colorGradientEnd","gradientToColor"]]}),$=e=>{let{prefixCls:a,className:n,style:r,rows:i=0}=e,o=Array.from({length:i}).map((l,a)=>t.createElement("li",{key:a,style:{width:((e,t)=>{let{width:l,rows:a=2}=t;return Array.isArray(l)?l[e]:a-1===e?l:void 0})(a,e)}}));return t.createElement("ul",{className:(0,l.default)(a,n),style:r},o)},v=({prefixCls:e,className:a,width:n,style:r})=>t.createElement("h3",{className:(0,l.default)(e,a),style:Object.assign({width:n},r)});function y(e){return e&&"object"==typeof e?e:{}}let O=e=>{let{prefixCls:n,loading:i,className:o,rootClassName:s,style:d,children:c,avatar:u=!1,title:g=!0,paragraph:m=!0,active:b,round:f}=e,{getPrefixCls:p,direction:O,className:x,style:j}=(0,a.useComponentConfig)("skeleton"),C=p("skeleton",n),[k,S,w]=h(C);if(i||!("loading"in e)){let e,a,n=!!u,i=!!g,c=!!m;if(n){let l=Object.assign(Object.assign({prefixCls:`${C}-avatar`},i&&!c?{size:"large",shape:"square"}:{size:"large",shape:"circle"}),y(u));e=t.createElement("div",{className:`${C}-header`},t.createElement(r,Object.assign({},l)))}if(i||c){let e,l;if(i){let l=Object.assign(Object.assign({prefixCls:`${C}-title`},!n&&c?{width:"38%"}:n&&c?{width:"50%"}:{}),y(g));e=t.createElement(v,Object.assign({},l))}if(c){let e,a=Object.assign(Object.assign({prefixCls:`${C}-paragraph`},(e={},n&&i||(e.width="61%"),!n&&i?e.rows=3:e.rows=2,e)),y(m));l=t.createElement($,Object.assign({},a))}a=t.createElement("div",{className:`${C}-content`},e,l)}let p=(0,l.default)(C,{[`${C}-with-avatar`]:n,[`${C}-active`]:b,[`${C}-rtl`]:"rtl"===O,[`${C}-round`]:f},x,o,s,S,w);return k(t.createElement("div",{className:p,style:Object.assign(Object.assign({},j),d)},e,a))}return null!=c?c:null};O.Button=e=>{let{prefixCls:i,className:o,rootClassName:s,active:d,block:c=!1,size:u="default"}=e,{getPrefixCls:g}=t.useContext(a.ConfigContext),m=g("skeleton",i),[b,f,p]=h(m),$=(0,n.default)(e,["prefixCls"]),v=(0,l.default)(m,`${m}-element`,{[`${m}-active`]:d,[`${m}-block`]:c},o,s,f,p);return b(t.createElement("div",{className:v},t.createElement(r,Object.assign({prefixCls:`${m}-button`,size:u},$))))},O.Avatar=e=>{let{prefixCls:i,className:o,rootClassName:s,active:d,shape:c="circle",size:u="default"}=e,{getPrefixCls:g}=t.useContext(a.ConfigContext),m=g("skeleton",i),[b,f,p]=h(m),$=(0,n.default)(e,["prefixCls","className"]),v=(0,l.default)(m,`${m}-element`,{[`${m}-active`]:d},o,s,f,p);return b(t.createElement("div",{className:v},t.createElement(r,Object.assign({prefixCls:`${m}-avatar`,shape:c,size:u},$))))},O.Input=e=>{let{prefixCls:i,className:o,rootClassName:s,active:d,block:c,size:u="default"}=e,{getPrefixCls:g}=t.useContext(a.ConfigContext),m=g("skeleton",i),[b,f,p]=h(m),$=(0,n.default)(e,["prefixCls"]),v=(0,l.default)(m,`${m}-element`,{[`${m}-active`]:d,[`${m}-block`]:c},o,s,f,p);return b(t.createElement("div",{className:v},t.createElement(r,Object.assign({prefixCls:`${m}-input`,size:u},$))))},O.Image=e=>{let{prefixCls:n,className:r,rootClassName:i,style:o,active:s}=e,{getPrefixCls:d}=t.useContext(a.ConfigContext),c=d("skeleton",n),[u,g,m]=h(c),b=(0,l.default)(c,`${c}-element`,{[`${c}-active`]:s},r,i,g,m);return u(t.createElement("div",{className:b},t.createElement("div",{className:(0,l.default)(`${c}-image`,r),style:o},t.createElement("svg",{viewBox:"0 0 1098 1024",xmlns:"http://www.w3.org/2000/svg",className:`${c}-image-svg`},t.createElement("title",null,"Image placeholder"),t.createElement("path",{d:"M365.714286 329.142857q0 45.714286-32.036571 77.677714t-77.677714 32.036571-77.677714-32.036571-32.036571-77.677714 32.036571-77.677714 77.677714-32.036571 77.677714 32.036571 32.036571 77.677714zM950.857143 548.571429l0 256-804.571429 0 0-109.714286 182.857143-182.857143 91.428571 91.428571 292.571429-292.571429zM1005.714286 146.285714l-914.285714 0q-7.460571 0-12.873143 5.412571t-5.412571 12.873143l0 694.857143q0 7.460571 5.412571 12.873143t12.873143 5.412571l914.285714 0q7.460571 0 12.873143-5.412571t5.412571-12.873143l0-694.857143q0-7.460571-5.412571-12.873143t-12.873143-5.412571zM1097.142857 164.571429l0 694.857143q0 37.741714-26.843429 64.585143t-64.585143 26.843429l-914.285714 0q-37.741714 0-64.585143-26.843429t-26.843429-64.585143l0-694.857143q0-37.741714 26.843429-64.585143t64.585143-26.843429l914.285714 0q37.741714 0 64.585143 26.843429t26.843429 64.585143z",className:`${c}-image-path`})))))},O.Node=e=>{let{prefixCls:n,className:r,rootClassName:i,style:o,active:s,children:d}=e,{getPrefixCls:c}=t.useContext(a.ConfigContext),u=c("skeleton",n),[g,m,b]=h(u),f=(0,l.default)(u,`${u}-element`,{[`${u}-active`]:s},m,r,i,b);return g(t.createElement("div",{className:f},t.createElement("div",{className:(0,l.default)(`${u}-image`,r),style:o},d)))},e.s(["default",0,O],185793)},959013,e=>{"use strict";e.i(247167);var t=e.i(931067),l=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8z"}},{tag:"path",attrs:{d:"M192 474h672q8 0 8 8v60q0 8-8 8H160q-8 0-8-8v-60q0-8 8-8z"}}]},name:"plus",theme:"outlined"};var n=e.i(9583),r=l.forwardRef(function(e,r){return l.createElement(n.default,(0,t.default)({},e,{ref:r,icon:a}))});e.s(["default",0,r],959013)},269200,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let n=(0,e.i(673706).makeClassName)("Table"),r=l.default.forwardRef((e,r)=>{let{children:i,className:o}=e,s=(0,t.__rest)(e,["children","className"]);return l.default.createElement("div",{className:(0,a.tremorTwMerge)(n("root"),"overflow-auto",o)},l.default.createElement("table",Object.assign({ref:r,className:(0,a.tremorTwMerge)(n("table"),"w-full text-tremor-default","text-tremor-content","dark:text-dark-tremor-content")},s),i))});r.displayName="Table",e.s(["Table",()=>r],269200)},942232,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let n=(0,e.i(673706).makeClassName)("TableBody"),r=l.default.forwardRef((e,r)=>{let{children:i,className:o}=e,s=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("tbody",Object.assign({ref:r,className:(0,a.tremorTwMerge)(n("root"),"align-top divide-y","divide-tremor-border","dark:divide-dark-tremor-border",o)},s),i))});r.displayName="TableBody",e.s(["TableBody",()=>r],942232)},977572,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let n=(0,e.i(673706).makeClassName)("TableCell"),r=l.default.forwardRef((e,r)=>{let{children:i,className:o}=e,s=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("td",Object.assign({ref:r,className:(0,a.tremorTwMerge)(n("root"),"align-middle whitespace-nowrap text-left p-4",o)},s),i))});r.displayName="TableCell",e.s(["TableCell",()=>r],977572)},427612,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let n=(0,e.i(673706).makeClassName)("TableHead"),r=l.default.forwardRef((e,r)=>{let{children:i,className:o}=e,s=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("thead",Object.assign({ref:r,className:(0,a.tremorTwMerge)(n("root"),"text-left","text-tremor-content","dark:text-dark-tremor-content",o)},s),i))});r.displayName="TableHead",e.s(["TableHead",()=>r],427612)},64848,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let n=(0,e.i(673706).makeClassName)("TableHeaderCell"),r=l.default.forwardRef((e,r)=>{let{children:i,className:o}=e,s=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("th",Object.assign({ref:r,className:(0,a.tremorTwMerge)(n("root"),"whitespace-nowrap text-left font-semibold top-0 px-4 py-3.5","text-tremor-content-strong","dark:text-dark-tremor-content-strong",o)},s),i))});r.displayName="TableHeaderCell",e.s(["TableHeaderCell",()=>r],64848)},496020,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let n=(0,e.i(673706).makeClassName)("TableRow"),r=l.default.forwardRef((e,r)=>{let{children:i,className:o}=e,s=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("tr",Object.assign({ref:r,className:(0,a.tremorTwMerge)(n("row"),o)},s),i))});r.displayName="TableRow",e.s(["TableRow",()=>r],496020)},91874,e=>{"use strict";var t=e.i(931067),l=e.i(209428),a=e.i(211577),n=e.i(392221),r=e.i(703923),i=e.i(343794),o=e.i(914949),s=e.i(271645),d=["prefixCls","className","style","checked","disabled","defaultChecked","type","title","onChange"],c=(0,s.forwardRef)(function(e,c){var u=e.prefixCls,g=void 0===u?"rc-checkbox":u,m=e.className,b=e.style,f=e.checked,p=e.disabled,h=e.defaultChecked,$=e.type,v=void 0===$?"checkbox":$,y=e.title,O=e.onChange,x=(0,r.default)(e,d),j=(0,s.useRef)(null),C=(0,s.useRef)(null),k=(0,o.default)(void 0!==h&&h,{value:f}),S=(0,n.default)(k,2),w=S[0],E=S[1];(0,s.useImperativeHandle)(c,function(){return{focus:function(e){var t;null==(t=j.current)||t.focus(e)},blur:function(){var e;null==(e=j.current)||e.blur()},input:j.current,nativeElement:C.current}});var N=(0,i.default)(g,m,(0,a.default)((0,a.default)({},"".concat(g,"-checked"),w),"".concat(g,"-disabled"),p));return s.createElement("span",{className:N,title:y,style:b,ref:C},s.createElement("input",(0,t.default)({},x,{className:"".concat(g,"-input"),ref:j,onChange:function(t){p||("checked"in e||E(t.target.checked),null==O||O({target:(0,l.default)((0,l.default)({},e),{},{type:v,checked:t.target.checked}),stopPropagation:function(){t.stopPropagation()},preventDefault:function(){t.preventDefault()},nativeEvent:t.nativeEvent}))},disabled:p,checked:!!w,type:v})),s.createElement("span",{className:"".concat(g,"-inner")}))});e.s(["default",0,c])},421512,236836,e=>{"use strict";let t=e.i(271645).default.createContext(null);e.s(["default",0,t],421512),e.i(296059);var l=e.i(915654),a=e.i(183293),n=e.i(246422),r=e.i(838378);function i(e,t){return(e=>{let{checkboxCls:t}=e,n=`${t}-wrapper`;return[{[`${t}-group`]:Object.assign(Object.assign({},(0,a.resetComponent)(e)),{display:"inline-flex",flexWrap:"wrap",columnGap:e.marginXS,[`> ${e.antCls}-row`]:{flex:1}}),[n]:Object.assign(Object.assign({},(0,a.resetComponent)(e)),{display:"inline-flex",alignItems:"baseline",cursor:"pointer","&:after":{display:"inline-block",width:0,overflow:"hidden",content:"'\\a0'"},[`& + ${n}`]:{marginInlineStart:0},[`&${n}-in-form-item`]:{'input[type="checkbox"]':{width:14,height:14}}}),[t]:Object.assign(Object.assign({},(0,a.resetComponent)(e)),{position:"relative",whiteSpace:"nowrap",lineHeight:1,cursor:"pointer",borderRadius:e.borderRadiusSM,alignSelf:"center",[`${t}-input`]:{position:"absolute",inset:0,zIndex:1,cursor:"pointer",opacity:0,margin:0,[`&:focus-visible + ${t}-inner`]:(0,a.genFocusOutline)(e)},[`${t}-inner`]:{boxSizing:"border-box",display:"block",width:e.checkboxSize,height:e.checkboxSize,direction:"ltr",backgroundColor:e.colorBgContainer,border:`${(0,l.unit)(e.lineWidth)} ${e.lineType} ${e.colorBorder}`,borderRadius:e.borderRadiusSM,borderCollapse:"separate",transition:`all ${e.motionDurationSlow}`,"&:after":{boxSizing:"border-box",position:"absolute",top:"50%",insetInlineStart:"25%",display:"table",width:e.calc(e.checkboxSize).div(14).mul(5).equal(),height:e.calc(e.checkboxSize).div(14).mul(8).equal(),border:`${(0,l.unit)(e.lineWidthBold)} solid ${e.colorWhite}`,borderTop:0,borderInlineStart:0,transform:"rotate(45deg) scale(0) translate(-50%,-50%)",opacity:0,content:'""',transition:`all ${e.motionDurationFast} ${e.motionEaseInBack}, opacity ${e.motionDurationFast}`}},"& + span":{paddingInlineStart:e.paddingXS,paddingInlineEnd:e.paddingXS}})},{[` - ${n}:not(${n}-disabled), - ${t}:not(${t}-disabled) - `]:{[`&:hover ${t}-inner`]:{borderColor:e.colorPrimary}},[`${n}:not(${n}-disabled)`]:{[`&:hover ${t}-checked:not(${t}-disabled) ${t}-inner`]:{backgroundColor:e.colorPrimaryHover,borderColor:"transparent"},[`&:hover ${t}-checked:not(${t}-disabled):after`]:{borderColor:e.colorPrimaryHover}}},{[`${t}-checked`]:{[`${t}-inner`]:{backgroundColor:e.colorPrimary,borderColor:e.colorPrimary,"&:after":{opacity:1,transform:"rotate(45deg) scale(1) translate(-50%,-50%)",transition:`all ${e.motionDurationMid} ${e.motionEaseOutBack} ${e.motionDurationFast}`}}},[` - ${n}-checked:not(${n}-disabled), - ${t}-checked:not(${t}-disabled) - `]:{[`&:hover ${t}-inner`]:{backgroundColor:e.colorPrimaryHover,borderColor:"transparent"}}},{[t]:{"&-indeterminate":{"&":{[`${t}-inner`]:{backgroundColor:`${e.colorBgContainer}`,borderColor:`${e.colorBorder}`,"&:after":{top:"50%",insetInlineStart:"50%",width:e.calc(e.fontSizeLG).div(2).equal(),height:e.calc(e.fontSizeLG).div(2).equal(),backgroundColor:e.colorPrimary,border:0,transform:"translate(-50%, -50%) scale(1)",opacity:1,content:'""'}},[`&:hover ${t}-inner`]:{backgroundColor:`${e.colorBgContainer}`,borderColor:`${e.colorPrimary}`}}}}},{[`${n}-disabled`]:{cursor:"not-allowed"},[`${t}-disabled`]:{[`&, ${t}-input`]:{cursor:"not-allowed",pointerEvents:"none"},[`${t}-inner`]:{background:e.colorBgContainerDisabled,borderColor:e.colorBorder,"&:after":{borderColor:e.colorTextDisabled}},"&:after":{display:"none"},"& + span":{color:e.colorTextDisabled},[`&${t}-indeterminate ${t}-inner::after`]:{background:e.colorTextDisabled}}}]})((0,r.mergeToken)(t,{checkboxCls:`.${e}`,checkboxSize:t.controlInteractiveSize}))}let o=(0,n.genStyleHooks)("Checkbox",(e,{prefixCls:t})=>[i(t,e)]);e.s(["default",0,o,"getStyle",()=>i],236836)},681216,e=>{"use strict";var t=e.i(271645),l=e.i(963188);function a(e){let a=t.default.useRef(null),n=()=>{l.default.cancel(a.current),a.current=null};return[()=>{n(),a.current=(0,l.default)(()=>{a.current=null})},t=>{a.current&&(t.stopPropagation(),n()),null==e||e(t)}]}e.s(["default",()=>a])},374276,e=>{"use strict";e.i(247167);var t=e.i(271645),l=e.i(343794),a=e.i(91874),n=e.i(611935),r=e.i(121872),i=e.i(26905),o=e.i(242064),s=e.i(937328),d=e.i(321883),c=e.i(62139),u=e.i(421512),g=e.i(236836),m=e.i(681216),b=function(e,t){var l={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(l[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,a=Object.getOwnPropertySymbols(e);nt.indexOf(a[n])&&Object.prototype.propertyIsEnumerable.call(e,a[n])&&(l[a[n]]=e[a[n]]);return l};let f=t.forwardRef((e,f)=>{var p;let{prefixCls:h,className:$,rootClassName:v,children:y,indeterminate:O=!1,style:x,onMouseEnter:j,onMouseLeave:C,skipGroup:k=!1,disabled:S}=e,w=b(e,["prefixCls","className","rootClassName","children","indeterminate","style","onMouseEnter","onMouseLeave","skipGroup","disabled"]),{getPrefixCls:E,direction:N,checkbox:T}=t.useContext(o.ConfigContext),z=t.useContext(u.default),{isFormItemInput:B}=t.useContext(c.FormItemInputContext),R=t.useContext(s.default),P=null!=(p=(null==z?void 0:z.disabled)||S)?p:R,M=t.useRef(w.value),I=t.useRef(null),H=(0,n.composeRef)(f,I);t.useEffect(()=>{null==z||z.registerValue(w.value)},[]),t.useEffect(()=>{if(!k)return w.value!==M.current&&(null==z||z.cancelValue(M.current),null==z||z.registerValue(w.value),M.current=w.value),()=>null==z?void 0:z.cancelValue(w.value)},[w.value]),t.useEffect(()=>{var e;(null==(e=I.current)?void 0:e.input)&&(I.current.input.indeterminate=O)},[O]);let L=E("checkbox",h),q=(0,d.default)(L),[G,W,A]=(0,g.default)(L,q),D=Object.assign({},w);z&&!k&&(D.onChange=(...e)=>{w.onChange&&w.onChange.apply(w,e),z.toggleOption&&z.toggleOption({label:y,value:w.value})},D.name=z.name,D.checked=z.value.includes(w.value));let F=(0,l.default)(`${L}-wrapper`,{[`${L}-rtl`]:"rtl"===N,[`${L}-wrapper-checked`]:D.checked,[`${L}-wrapper-disabled`]:P,[`${L}-wrapper-in-form-item`]:B},null==T?void 0:T.className,$,v,A,q,W),X=(0,l.default)({[`${L}-indeterminate`]:O},i.TARGET_CLS,W),[_,K]=(0,m.default)(D.onClick);return G(t.createElement(r.default,{component:"Checkbox",disabled:P},t.createElement("label",{className:F,style:Object.assign(Object.assign({},null==T?void 0:T.style),x),onMouseEnter:j,onMouseLeave:C,onClick:_},t.createElement(a.default,Object.assign({},D,{onClick:K,prefixCls:L,className:X,disabled:P,ref:H})),null!=y&&t.createElement("span",{className:`${L}-label`},y))))});var p=e.i(8211),h=e.i(529681),$=function(e,t){var l={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(l[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,a=Object.getOwnPropertySymbols(e);nt.indexOf(a[n])&&Object.prototype.propertyIsEnumerable.call(e,a[n])&&(l[a[n]]=e[a[n]]);return l};let v=t.forwardRef((e,a)=>{let{defaultValue:n,children:r,options:i=[],prefixCls:s,className:c,rootClassName:m,style:b,onChange:v}=e,y=$(e,["defaultValue","children","options","prefixCls","className","rootClassName","style","onChange"]),{getPrefixCls:O,direction:x}=t.useContext(o.ConfigContext),[j,C]=t.useState(y.value||n||[]),[k,S]=t.useState([]);t.useEffect(()=>{"value"in y&&C(y.value||[])},[y.value]);let w=t.useMemo(()=>i.map(e=>"string"==typeof e||"number"==typeof e?{label:e,value:e}:e),[i]),E=e=>{S(t=>t.filter(t=>t!==e))},N=e=>{S(t=>[].concat((0,p.default)(t),[e]))},T=e=>{let t=j.indexOf(e.value),l=(0,p.default)(j);-1===t?l.push(e.value):l.splice(t,1),"value"in y||C(l),null==v||v(l.filter(e=>k.includes(e)).sort((e,t)=>w.findIndex(t=>t.value===e)-w.findIndex(e=>e.value===t)))},z=O("checkbox",s),B=`${z}-group`,R=(0,d.default)(z),[P,M,I]=(0,g.default)(z,R),H=(0,h.default)(y,["value","disabled"]),L=i.length?w.map(e=>t.createElement(f,{prefixCls:z,key:e.value.toString(),disabled:"disabled"in e?e.disabled:y.disabled,value:e.value,checked:j.includes(e.value),onChange:e.onChange,className:(0,l.default)(`${B}-item`,e.className),style:e.style,title:e.title,id:e.id,required:e.required},e.label)):r,q=t.useMemo(()=>({toggleOption:T,value:j,disabled:y.disabled,name:y.name,registerValue:N,cancelValue:E}),[T,j,y.disabled,y.name,N,E]),G=(0,l.default)(B,{[`${B}-rtl`]:"rtl"===x},c,m,I,R,M);return P(t.createElement("div",Object.assign({className:G,style:b},H,{ref:a}),t.createElement(u.default.Provider,{value:q},L)))});f.Group=v,f.__ANT_CHECKBOX=!0,e.s(["default",0,f],374276)},536916,e=>{"use strict";var t=e.i(374276);e.s(["Checkbox",()=>t.default])},869216,e=>{"use strict";e.i(247167);var t=e.i(271645),l=e.i(343794),a=e.i(908206),n=e.i(242064),r=e.i(517455),i=e.i(150073);let o={xxl:3,xl:3,lg:3,md:3,sm:2,xs:1},s=t.default.createContext({});var d=e.i(876556),c=function(e,t){var l={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(l[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,a=Object.getOwnPropertySymbols(e);nt.indexOf(a[n])&&Object.prototype.propertyIsEnumerable.call(e,a[n])&&(l[a[n]]=e[a[n]]);return l},u=function(e,t){var l={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(l[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,a=Object.getOwnPropertySymbols(e);nt.indexOf(a[n])&&Object.prototype.propertyIsEnumerable.call(e,a[n])&&(l[a[n]]=e[a[n]]);return l};let g=e=>{let{itemPrefixCls:a,component:n,span:r,className:i,style:o,labelStyle:d,contentStyle:c,bordered:u,label:g,content:m,colon:b,type:f,styles:p}=e,{classNames:h}=t.useContext(s),$=Object.assign(Object.assign({},d),null==p?void 0:p.label),v=Object.assign(Object.assign({},c),null==p?void 0:p.content);if(u)return t.createElement(n,{colSpan:r,style:o,className:(0,l.default)(i,{[`${a}-item-${f}`]:"label"===f||"content"===f,[null==h?void 0:h.label]:(null==h?void 0:h.label)&&"label"===f,[null==h?void 0:h.content]:(null==h?void 0:h.content)&&"content"===f})},null!=g&&t.createElement("span",{style:$},g),null!=m&&t.createElement("span",{style:v},m));return t.createElement(n,{colSpan:r,style:o,className:(0,l.default)(`${a}-item`,i)},t.createElement("div",{className:`${a}-item-container`},null!=g&&t.createElement("span",{style:$,className:(0,l.default)(`${a}-item-label`,null==h?void 0:h.label,{[`${a}-item-no-colon`]:!b})},g),null!=m&&t.createElement("span",{style:v,className:(0,l.default)(`${a}-item-content`,null==h?void 0:h.content)},m)))};function m(e,{colon:l,prefixCls:a,bordered:n},{component:r,type:i,showLabel:o,showContent:s,labelStyle:d,contentStyle:c,styles:u}){return e.map(({label:e,children:m,prefixCls:b=a,className:f,style:p,labelStyle:h,contentStyle:$,span:v=1,key:y,styles:O},x)=>"string"==typeof r?t.createElement(g,{key:`${i}-${y||x}`,className:f,style:p,styles:{label:Object.assign(Object.assign(Object.assign(Object.assign({},d),null==u?void 0:u.label),h),null==O?void 0:O.label),content:Object.assign(Object.assign(Object.assign(Object.assign({},c),null==u?void 0:u.content),$),null==O?void 0:O.content)},span:v,colon:l,component:r,itemPrefixCls:b,bordered:n,label:o?e:null,content:s?m:null,type:i}):[t.createElement(g,{key:`label-${y||x}`,className:f,style:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},d),null==u?void 0:u.label),p),h),null==O?void 0:O.label),span:1,colon:l,component:r[0],itemPrefixCls:b,bordered:n,label:e,type:"label"}),t.createElement(g,{key:`content-${y||x}`,className:f,style:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},c),null==u?void 0:u.content),p),$),null==O?void 0:O.content),span:2*v-1,component:r[1],itemPrefixCls:b,bordered:n,content:m,type:"content"})])}let b=e=>{let l=t.useContext(s),{prefixCls:a,vertical:n,row:r,index:i,bordered:o}=e;return n?t.createElement(t.Fragment,null,t.createElement("tr",{key:`label-${i}`,className:`${a}-row`},m(r,e,Object.assign({component:"th",type:"label",showLabel:!0},l))),t.createElement("tr",{key:`content-${i}`,className:`${a}-row`},m(r,e,Object.assign({component:"td",type:"content",showContent:!0},l)))):t.createElement("tr",{key:i,className:`${a}-row`},m(r,e,Object.assign({component:o?["th","td"]:"td",type:"item",showLabel:!0,showContent:!0},l)))};e.i(296059);var f=e.i(915654),p=e.i(183293),h=e.i(246422),$=e.i(838378);let v=(0,h.genStyleHooks)("Descriptions",e=>(e=>{let{componentCls:t,extraColor:l,itemPaddingBottom:a,itemPaddingEnd:n,colonMarginRight:r,colonMarginLeft:i,titleMarginBottom:o}=e;return{[t]:Object.assign(Object.assign(Object.assign({},(0,p.resetComponent)(e)),(e=>{let{componentCls:t,labelBg:l}=e;return{[`&${t}-bordered`]:{[`> ${t}-view`]:{border:`${(0,f.unit)(e.lineWidth)} ${e.lineType} ${e.colorSplit}`,"> table":{tableLayout:"auto"},[`${t}-row`]:{borderBottom:`${(0,f.unit)(e.lineWidth)} ${e.lineType} ${e.colorSplit}`,"&:first-child":{"> th:first-child, > td:first-child":{borderStartStartRadius:e.borderRadiusLG}},"&:last-child":{borderBottom:"none","> th:first-child, > td:first-child":{borderEndStartRadius:e.borderRadiusLG}},[`> ${t}-item-label, > ${t}-item-content`]:{padding:`${(0,f.unit)(e.padding)} ${(0,f.unit)(e.paddingLG)}`,borderInlineEnd:`${(0,f.unit)(e.lineWidth)} ${e.lineType} ${e.colorSplit}`,"&:last-child":{borderInlineEnd:"none"}},[`> ${t}-item-label`]:{color:e.colorTextSecondary,backgroundColor:l,"&::after":{display:"none"}}}},[`&${t}-middle`]:{[`${t}-row`]:{[`> ${t}-item-label, > ${t}-item-content`]:{padding:`${(0,f.unit)(e.paddingSM)} ${(0,f.unit)(e.paddingLG)}`}}},[`&${t}-small`]:{[`${t}-row`]:{[`> ${t}-item-label, > ${t}-item-content`]:{padding:`${(0,f.unit)(e.paddingXS)} ${(0,f.unit)(e.padding)}`}}}}}})(e)),{"&-rtl":{direction:"rtl"},[`${t}-header`]:{display:"flex",alignItems:"center",marginBottom:o},[`${t}-title`]:Object.assign(Object.assign({},p.textEllipsis),{flex:"auto",color:e.titleColor,fontWeight:e.fontWeightStrong,fontSize:e.fontSizeLG,lineHeight:e.lineHeightLG}),[`${t}-extra`]:{marginInlineStart:"auto",color:l,fontSize:e.fontSize},[`${t}-view`]:{width:"100%",borderRadius:e.borderRadiusLG,table:{width:"100%",tableLayout:"fixed",borderCollapse:"collapse"}},[`${t}-row`]:{"> th, > td":{paddingBottom:a,paddingInlineEnd:n},"> th:last-child, > td:last-child":{paddingInlineEnd:0},"&:last-child":{borderBottom:"none","> th, > td":{paddingBottom:0}}},[`${t}-item-label`]:{color:e.labelColor,fontWeight:"normal",fontSize:e.fontSize,lineHeight:e.lineHeight,textAlign:"start","&::after":{content:'":"',position:"relative",top:-.5,marginInline:`${(0,f.unit)(i)} ${(0,f.unit)(r)}`},[`&${t}-item-no-colon::after`]:{content:'""'}},[`${t}-item-no-label`]:{"&::after":{margin:0,content:'""'}},[`${t}-item-content`]:{display:"table-cell",flex:1,color:e.contentColor,fontSize:e.fontSize,lineHeight:e.lineHeight,wordBreak:"break-word",overflowWrap:"break-word"},[`${t}-item`]:{paddingBottom:0,verticalAlign:"top","&-container":{display:"flex",[`${t}-item-label`]:{display:"inline-flex",alignItems:"baseline"},[`${t}-item-content`]:{display:"inline-flex",alignItems:"baseline",minWidth:"1em"}}},"&-middle":{[`${t}-row`]:{"> th, > td":{paddingBottom:e.paddingSM}}},"&-small":{[`${t}-row`]:{"> th, > td":{paddingBottom:e.paddingXS}}}})}})((0,$.mergeToken)(e,{})),e=>({labelBg:e.colorFillAlter,labelColor:e.colorTextTertiary,titleColor:e.colorText,titleMarginBottom:e.fontSizeSM*e.lineHeightSM,itemPaddingBottom:e.padding,itemPaddingEnd:e.padding,colonMarginRight:e.marginXS,colonMarginLeft:e.marginXXS/2,contentColor:e.colorText,extraColor:e.colorText}));var y=function(e,t){var l={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(l[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,a=Object.getOwnPropertySymbols(e);nt.indexOf(a[n])&&Object.prototype.propertyIsEnumerable.call(e,a[n])&&(l[a[n]]=e[a[n]]);return l};let O=e=>{let g,{prefixCls:m,title:f,extra:p,column:h,colon:$=!0,bordered:O,layout:x,children:j,className:C,rootClassName:k,style:S,size:w,labelStyle:E,contentStyle:N,styles:T,items:z,classNames:B}=e,R=y(e,["prefixCls","title","extra","column","colon","bordered","layout","children","className","rootClassName","style","size","labelStyle","contentStyle","styles","items","classNames"]),{getPrefixCls:P,direction:M,className:I,style:H,classNames:L,styles:q}=(0,n.useComponentConfig)("descriptions"),G=P("descriptions",m),W=(0,i.default)(),A=t.useMemo(()=>{var e;return"number"==typeof h?h:null!=(e=(0,a.matchScreen)(W,Object.assign(Object.assign({},o),h)))?e:3},[W,h]),D=(g=t.useMemo(()=>z||(0,d.default)(j).map(e=>Object.assign(Object.assign({},null==e?void 0:e.props),{key:e.key})),[z,j]),t.useMemo(()=>g.map(e=>{var{span:t}=e,l=c(e,["span"]);return"filled"===t?Object.assign(Object.assign({},l),{filled:!0}):Object.assign(Object.assign({},l),{span:"number"==typeof t?t:(0,a.matchScreen)(W,t)})}),[g,W])),F=(0,r.default)(w),X=((e,l)=>{let[a,n]=(0,t.useMemo)(()=>{let t,a,n,r;return t=[],a=[],n=!1,r=0,l.filter(e=>e).forEach(l=>{let{filled:i}=l,o=u(l,["filled"]);if(i){a.push(o),t.push(a),a=[],r=0;return}let s=e-r;(r+=l.span||1)>=e?(r>e?(n=!0,a.push(Object.assign(Object.assign({},o),{span:s}))):a.push(o),t.push(a),a=[],r=0):a.push(o)}),a.length>0&&t.push(a),[t=t.map(t=>{let l=t.reduce((e,t)=>e+(t.span||1),0);if(l({labelStyle:E,contentStyle:N,styles:{content:Object.assign(Object.assign({},q.content),null==T?void 0:T.content),label:Object.assign(Object.assign({},q.label),null==T?void 0:T.label)},classNames:{label:(0,l.default)(L.label,null==B?void 0:B.label),content:(0,l.default)(L.content,null==B?void 0:B.content)}}),[E,N,T,B,L,q]);return _(t.createElement(s.Provider,{value:Q},t.createElement("div",Object.assign({className:(0,l.default)(G,I,L.root,null==B?void 0:B.root,{[`${G}-${F}`]:F&&"default"!==F,[`${G}-bordered`]:!!O,[`${G}-rtl`]:"rtl"===M},C,k,K,V),style:Object.assign(Object.assign(Object.assign(Object.assign({},H),q.root),null==T?void 0:T.root),S)},R),(f||p)&&t.createElement("div",{className:(0,l.default)(`${G}-header`,L.header,null==B?void 0:B.header),style:Object.assign(Object.assign({},q.header),null==T?void 0:T.header)},f&&t.createElement("div",{className:(0,l.default)(`${G}-title`,L.title,null==B?void 0:B.title),style:Object.assign(Object.assign({},q.title),null==T?void 0:T.title)},f),p&&t.createElement("div",{className:(0,l.default)(`${G}-extra`,L.extra,null==B?void 0:B.extra),style:Object.assign(Object.assign({},q.extra),null==T?void 0:T.extra)},p)),t.createElement("div",{className:`${G}-view`},t.createElement("table",null,t.createElement("tbody",null,X.map((e,l)=>t.createElement(b,{key:l,index:l,colon:$,prefixCls:G,vertical:"vertical"===x,bordered:O,row:e}))))))))};O.Item=({children:e})=>e,e.s(["Descriptions",0,O],869216)},270377,e=>{"use strict";e.i(247167);var t=e.i(931067),l=e.i(271645);let 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 372z"}},{tag:"path",attrs:{d:"M464 688a48 48 0 1096 0 48 48 0 10-96 0zm24-112h48c4.4 0 8-3.6 8-8V296c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v272c0 4.4 3.6 8 8 8z"}}]},name:"exclamation-circle",theme:"outlined"};var n=e.i(9583),r=l.forwardRef(function(e,r){return l.createElement(n.default,(0,t.default)({},e,{ref:r,icon:a}))});e.s(["ExclamationCircleOutlined",0,r],270377)},175712,e=>{"use strict";e.i(247167);var t=e.i(271645),l=e.i(343794),a=e.i(529681),n=e.i(242064),r=e.i(517455),i=e.i(185793),o=e.i(721369),s=function(e,t){var l={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(l[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,a=Object.getOwnPropertySymbols(e);nt.indexOf(a[n])&&Object.prototype.propertyIsEnumerable.call(e,a[n])&&(l[a[n]]=e[a[n]]);return l};let d=e=>{var{prefixCls:a,className:r,hoverable:i=!0}=e,o=s(e,["prefixCls","className","hoverable"]);let{getPrefixCls:d}=t.useContext(n.ConfigContext),c=d("card",a),u=(0,l.default)(`${c}-grid`,r,{[`${c}-grid-hoverable`]:i});return t.createElement("div",Object.assign({},o,{className:u}))};e.i(296059);var c=e.i(915654),u=e.i(183293),g=e.i(246422),m=e.i(838378);let b=(0,g.genStyleHooks)("Card",e=>{let t=(0,m.mergeToken)(e,{cardShadow:e.boxShadowCard,cardHeadPadding:e.padding,cardPaddingBase:e.paddingLG,cardActionsIconSize:e.fontSize});return[(e=>{let{componentCls:t,cardShadow:l,cardHeadPadding:a,colorBorderSecondary:n,boxShadowTertiary:r,bodyPadding:i,extraColor:o}=e;return{[t]:Object.assign(Object.assign({},(0,u.resetComponent)(e)),{position:"relative",background:e.colorBgContainer,borderRadius:e.borderRadiusLG,[`&:not(${t}-bordered)`]:{boxShadow:r},[`${t}-head`]:(e=>{let{antCls:t,componentCls:l,headerHeight:a,headerPadding:n,tabsMarginBottom:r}=e;return Object.assign(Object.assign({display:"flex",justifyContent:"center",flexDirection:"column",minHeight:a,marginBottom:-1,padding:`0 ${(0,c.unit)(n)}`,color:e.colorTextHeading,fontWeight:e.fontWeightStrong,fontSize:e.headerFontSize,background:e.headerBg,borderBottom:`${(0,c.unit)(e.lineWidth)} ${e.lineType} ${e.colorBorderSecondary}`,borderRadius:`${(0,c.unit)(e.borderRadiusLG)} ${(0,c.unit)(e.borderRadiusLG)} 0 0`},(0,u.clearFix)()),{"&-wrapper":{width:"100%",display:"flex",alignItems:"center"},"&-title":Object.assign(Object.assign({display:"inline-block",flex:1},u.textEllipsis),{[` - > ${l}-typography, - > ${l}-typography-edit-content - `]:{insetInlineStart:0,marginTop:0,marginBottom:0}}),[`${t}-tabs-top`]:{clear:"both",marginBottom:r,color:e.colorText,fontWeight:"normal",fontSize:e.fontSize,"&-bar":{borderBottom:`${(0,c.unit)(e.lineWidth)} ${e.lineType} ${e.colorBorderSecondary}`}}})})(e),[`${t}-extra`]:{marginInlineStart:"auto",color:o,fontWeight:"normal",fontSize:e.fontSize},[`${t}-body`]:{padding:i,borderRadius:`0 0 ${(0,c.unit)(e.borderRadiusLG)} ${(0,c.unit)(e.borderRadiusLG)}`},[`${t}-grid`]:(e=>{let{cardPaddingBase:t,colorBorderSecondary:l,cardShadow:a,lineWidth:n}=e;return{width:"33.33%",padding:t,border:0,borderRadius:0,boxShadow:` - ${(0,c.unit)(n)} 0 0 0 ${l}, - 0 ${(0,c.unit)(n)} 0 0 ${l}, - ${(0,c.unit)(n)} ${(0,c.unit)(n)} 0 0 ${l}, - ${(0,c.unit)(n)} 0 0 0 ${l} inset, - 0 ${(0,c.unit)(n)} 0 0 ${l} inset; - `,transition:`all ${e.motionDurationMid}`,"&-hoverable:hover":{position:"relative",zIndex:1,boxShadow:a}}})(e),[`${t}-cover`]:{"> *":{display:"block",width:"100%",borderRadius:`${(0,c.unit)(e.borderRadiusLG)} ${(0,c.unit)(e.borderRadiusLG)} 0 0`}},[`${t}-actions`]:(e=>{let{componentCls:t,iconCls:l,actionsLiMargin:a,cardActionsIconSize:n,colorBorderSecondary:r,actionsBg:i}=e;return Object.assign(Object.assign({margin:0,padding:0,listStyle:"none",background:i,borderTop:`${(0,c.unit)(e.lineWidth)} ${e.lineType} ${r}`,display:"flex",borderRadius:`0 0 ${(0,c.unit)(e.borderRadiusLG)} ${(0,c.unit)(e.borderRadiusLG)}`},(0,u.clearFix)()),{"& > li":{margin:a,color:e.colorTextDescription,textAlign:"center","> span":{position:"relative",display:"block",minWidth:e.calc(e.cardActionsIconSize).mul(2).equal(),fontSize:e.fontSize,lineHeight:e.lineHeight,cursor:"pointer","&:hover":{color:e.colorPrimary,transition:`color ${e.motionDurationMid}`},[`a:not(${t}-btn), > ${l}`]:{display:"inline-block",width:"100%",color:e.colorIcon,lineHeight:(0,c.unit)(e.fontHeight),transition:`color ${e.motionDurationMid}`,"&:hover":{color:e.colorPrimary}},[`> ${l}`]:{fontSize:n,lineHeight:(0,c.unit)(e.calc(n).mul(e.lineHeight).equal())}},"&:not(:last-child)":{borderInlineEnd:`${(0,c.unit)(e.lineWidth)} ${e.lineType} ${r}`}}})})(e),[`${t}-meta`]:Object.assign(Object.assign({margin:`${(0,c.unit)(e.calc(e.marginXXS).mul(-1).equal())} 0`,display:"flex"},(0,u.clearFix)()),{"&-avatar":{paddingInlineEnd:e.padding},"&-detail":{overflow:"hidden",flex:1,"> div:not(:last-child)":{marginBottom:e.marginXS}},"&-title":Object.assign({color:e.colorTextHeading,fontWeight:e.fontWeightStrong,fontSize:e.fontSizeLG},u.textEllipsis),"&-description":{color:e.colorTextDescription}})}),[`${t}-bordered`]:{border:`${(0,c.unit)(e.lineWidth)} ${e.lineType} ${n}`,[`${t}-cover`]:{marginTop:-1,marginInlineStart:-1,marginInlineEnd:-1}},[`${t}-hoverable`]:{cursor:"pointer",transition:`box-shadow ${e.motionDurationMid}, border-color ${e.motionDurationMid}`,"&:hover":{borderColor:"transparent",boxShadow:l}},[`${t}-contain-grid`]:{borderRadius:`${(0,c.unit)(e.borderRadiusLG)} ${(0,c.unit)(e.borderRadiusLG)} 0 0 `,[`${t}-body`]:{display:"flex",flexWrap:"wrap"},[`&:not(${t}-loading) ${t}-body`]:{marginBlockStart:e.calc(e.lineWidth).mul(-1).equal(),marginInlineStart:e.calc(e.lineWidth).mul(-1).equal(),padding:0}},[`${t}-contain-tabs`]:{[`> div${t}-head`]:{minHeight:0,[`${t}-head-title, ${t}-extra`]:{paddingTop:a}}},[`${t}-type-inner`]:(e=>{let{componentCls:t,colorFillAlter:l,headerPadding:a,bodyPadding:n}=e;return{[`${t}-head`]:{padding:`0 ${(0,c.unit)(a)}`,background:l,"&-title":{fontSize:e.fontSize}},[`${t}-body`]:{padding:`${(0,c.unit)(e.padding)} ${(0,c.unit)(n)}`}}})(e),[`${t}-loading`]:(e=>{let{componentCls:t}=e;return{overflow:"hidden",[`${t}-body`]:{userSelect:"none"}}})(e),[`${t}-rtl`]:{direction:"rtl"}}})(t),(e=>{let{componentCls:t,bodyPaddingSM:l,headerPaddingSM:a,headerHeightSM:n,headerFontSizeSM:r}=e;return{[`${t}-small`]:{[`> ${t}-head`]:{minHeight:n,padding:`0 ${(0,c.unit)(a)}`,fontSize:r,[`> ${t}-head-wrapper`]:{[`> ${t}-extra`]:{fontSize:e.fontSize}}},[`> ${t}-body`]:{padding:l}},[`${t}-small${t}-contain-tabs`]:{[`> ${t}-head`]:{[`${t}-head-title, ${t}-extra`]:{paddingTop:0,display:"flex",alignItems:"center"}}}}})(t)]},e=>{var t,l;return{headerBg:"transparent",headerFontSize:e.fontSizeLG,headerFontSizeSM:e.fontSize,headerHeight:e.fontSizeLG*e.lineHeightLG+2*e.padding,headerHeightSM:e.fontSize*e.lineHeight+2*e.paddingXS,actionsBg:e.colorBgContainer,actionsLiMargin:`${e.paddingSM}px 0`,tabsMarginBottom:-e.padding-e.lineWidth,extraColor:e.colorText,bodyPaddingSM:12,headerPaddingSM:12,bodyPadding:null!=(t=e.bodyPadding)?t:e.paddingLG,headerPadding:null!=(l=e.headerPadding)?l:e.paddingLG}});var f=e.i(792812),p=function(e,t){var l={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(l[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,a=Object.getOwnPropertySymbols(e);nt.indexOf(a[n])&&Object.prototype.propertyIsEnumerable.call(e,a[n])&&(l[a[n]]=e[a[n]]);return l};let h=e=>{let{actionClasses:l,actions:a=[],actionStyle:n}=e;return t.createElement("ul",{className:l,style:n},a.map((e,l)=>{let n=`action-${l}`;return t.createElement("li",{style:{width:`${100/a.length}%`},key:n},t.createElement("span",null,e))}))},$=t.forwardRef((e,s)=>{let c,{prefixCls:u,className:g,rootClassName:m,style:$,extra:v,headStyle:y={},bodyStyle:O={},title:x,loading:j,bordered:C,variant:k,size:S,type:w,cover:E,actions:N,tabList:T,children:z,activeTabKey:B,defaultActiveTabKey:R,tabBarExtraContent:P,hoverable:M,tabProps:I={},classNames:H,styles:L}=e,q=p(e,["prefixCls","className","rootClassName","style","extra","headStyle","bodyStyle","title","loading","bordered","variant","size","type","cover","actions","tabList","children","activeTabKey","defaultActiveTabKey","tabBarExtraContent","hoverable","tabProps","classNames","styles"]),{getPrefixCls:G,direction:W,card:A}=t.useContext(n.ConfigContext),[D]=(0,f.default)("card",k,C),F=e=>{var t;return(0,l.default)(null==(t=null==A?void 0:A.classNames)?void 0:t[e],null==H?void 0:H[e])},X=e=>{var t;return Object.assign(Object.assign({},null==(t=null==A?void 0:A.styles)?void 0:t[e]),null==L?void 0:L[e])},_=t.useMemo(()=>{let e=!1;return t.Children.forEach(z,t=>{(null==t?void 0:t.type)===d&&(e=!0)}),e},[z]),K=G("card",u),[V,Q,U]=b(K),J=t.createElement(i.default,{loading:!0,active:!0,paragraph:{rows:4},title:!1},z),Y=void 0!==B,Z=Object.assign(Object.assign({},I),{[Y?"activeKey":"defaultActiveKey"]:Y?B:R,tabBarExtraContent:P}),ee=(0,r.default)(S),et=ee&&"default"!==ee?ee:"large",el=T?t.createElement(o.default,Object.assign({size:et},Z,{className:`${K}-head-tabs`,onChange:t=>{var l;null==(l=e.onTabChange)||l.call(e,t)},items:T.map(e=>{var{tab:t}=e;return Object.assign({label:t},p(e,["tab"]))})})):null;if(x||v||el){let e=(0,l.default)(`${K}-head`,F("header")),a=(0,l.default)(`${K}-head-title`,F("title")),n=(0,l.default)(`${K}-extra`,F("extra")),r=Object.assign(Object.assign({},y),X("header"));c=t.createElement("div",{className:e,style:r},t.createElement("div",{className:`${K}-head-wrapper`},x&&t.createElement("div",{className:a,style:X("title")},x),v&&t.createElement("div",{className:n,style:X("extra")},v)),el)}let ea=(0,l.default)(`${K}-cover`,F("cover")),en=E?t.createElement("div",{className:ea,style:X("cover")},E):null,er=(0,l.default)(`${K}-body`,F("body")),ei=Object.assign(Object.assign({},O),X("body")),eo=t.createElement("div",{className:er,style:ei},j?J:z),es=(0,l.default)(`${K}-actions`,F("actions")),ed=(null==N?void 0:N.length)?t.createElement(h,{actionClasses:es,actionStyle:X("actions"),actions:N}):null,ec=(0,a.default)(q,["onTabChange"]),eu=(0,l.default)(K,null==A?void 0:A.className,{[`${K}-loading`]:j,[`${K}-bordered`]:"borderless"!==D,[`${K}-hoverable`]:M,[`${K}-contain-grid`]:_,[`${K}-contain-tabs`]:null==T?void 0:T.length,[`${K}-${ee}`]:ee,[`${K}-type-${w}`]:!!w,[`${K}-rtl`]:"rtl"===W},g,m,Q,U),eg=Object.assign(Object.assign({},null==A?void 0:A.style),$);return V(t.createElement("div",Object.assign({ref:s},ec,{className:eu,style:eg}),c,en,eo,ed))});var v=function(e,t){var l={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(l[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,a=Object.getOwnPropertySymbols(e);nt.indexOf(a[n])&&Object.prototype.propertyIsEnumerable.call(e,a[n])&&(l[a[n]]=e[a[n]]);return l};$.Grid=d,$.Meta=e=>{let{prefixCls:a,className:r,avatar:i,title:o,description:s}=e,d=v(e,["prefixCls","className","avatar","title","description"]),{getPrefixCls:c}=t.useContext(n.ConfigContext),u=c("card",a),g=(0,l.default)(`${u}-meta`,r),m=i?t.createElement("div",{className:`${u}-meta-avatar`},i):null,b=o?t.createElement("div",{className:`${u}-meta-title`},o):null,f=s?t.createElement("div",{className:`${u}-meta-description`},s):null,p=b||f?t.createElement("div",{className:`${u}-meta-detail`},b,f):null;return t.createElement("div",Object.assign({},d,{className:g}),m,p)},e.s(["Card",0,$],175712)},127952,368869,e=>{"use strict";var t=e.i(843476),l=e.i(560445),a=e.i(175712),n=e.i(869216),r=e.i(311451),i=e.i(212931),o=e.i(898586);e.i(296059);var s=e.i(868297),d=e.i(732961),c=e.i(289882),u=e.i(170517),g=e.i(628882),m=e.i(320890),b=e.i(104458),f=e.i(722319),p=e.i(8398),h=e.i(279728);e.i(765846);var $=e.i(602716),v=e.i(328052);e.i(262370);var y=e.i(135551);let O=(e,t)=>new y.FastColor(e).setA(t).toRgbString(),x=(e,t)=>new y.FastColor(e).lighten(t).toHexString(),j=e=>{let t=(0,$.generate)(e,{theme:"dark"});return{1:t[0],2:t[1],3:t[2],4:t[3],5:t[6],6:t[5],7:t[4],8:t[6],9:t[5],10:t[4]}},C=(e,t)=>{let l=e||"#000",a=t||"#fff";return{colorBgBase:l,colorTextBase:a,colorText:O(a,.85),colorTextSecondary:O(a,.65),colorTextTertiary:O(a,.45),colorTextQuaternary:O(a,.25),colorFill:O(a,.18),colorFillSecondary:O(a,.12),colorFillTertiary:O(a,.08),colorFillQuaternary:O(a,.04),colorBgSolid:O(a,.95),colorBgSolidHover:O(a,1),colorBgSolidActive:O(a,.9),colorBgElevated:x(l,12),colorBgContainer:x(l,8),colorBgLayout:x(l,0),colorBgSpotlight:x(l,26),colorBgBlur:O(a,.04),colorBorder:x(l,26),colorBorderSecondary:x(l,19)}},k={defaultSeed:m.defaultConfig.token,useToken:function(){let[e,t,l]=(0,b.useToken)();return{theme:e,token:t,hashId:l}},defaultAlgorithm:f.default,darkAlgorithm:(e,t)=>{let l=Object.keys(u.defaultPresetColors).map(t=>{let l=(0,$.generate)(e[t],{theme:"dark"});return Array.from({length:10},()=>1).reduce((e,a,n)=>(e[`${t}-${n+1}`]=l[n],e[`${t}${n+1}`]=l[n],e),{})}).reduce((e,t)=>e=Object.assign(Object.assign({},e),t),{}),a=null!=t?t:(0,f.default)(e),n=(0,v.default)(e,{generateColorPalettes:j,generateNeutralColorPalettes:C});return Object.assign(Object.assign(Object.assign(Object.assign({},a),l),n),{colorPrimaryBg:n.colorPrimaryBorder,colorPrimaryBgHover:n.colorPrimaryBorderHover})},compactAlgorithm:(e,t)=>{let l=null!=t?t:(0,f.default)(e),a=l.fontSizeSM,n=l.controlHeight-4;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},l),function(e){let{sizeUnit:t,sizeStep:l}=e,a=l-2;return{sizeXXL:t*(a+10),sizeXL:t*(a+6),sizeLG:t*(a+2),sizeMD:t*(a+2),sizeMS:t*(a+1),size:t*a,sizeSM:t*a,sizeXS:t*(a-1),sizeXXS:t*(a-1)}}(null!=t?t:e)),(0,h.default)(a)),{controlHeight:n}),(0,p.default)(Object.assign(Object.assign({},l),{controlHeight:n})))},getDesignToken:e=>{let t=(null==e?void 0:e.algorithm)?(0,s.createTheme)(e.algorithm):c.default,l=Object.assign(Object.assign({},u.default),null==e?void 0:e.token);return(0,d.getComputedToken)(l,{override:null==e?void 0:e.token},t,g.default)},defaultConfig:m.defaultConfig,_internalContext:m.DesignTokenContext};e.s(["theme",0,k],368869);var S=e.i(270377),w=e.i(271645);function E({isOpen:e,title:s,alertMessage:d,message:c,resourceInformationTitle:u,resourceInformation:g,onCancel:m,onOk:b,confirmLoading:f,requiredConfirmation:p}){let{Title:h,Text:$}=o.Typography,{token:v}=k.useToken(),[y,O]=(0,w.useState)("");return(0,w.useEffect)(()=>{e&&O("")},[e]),(0,t.jsx)(i.Modal,{title:s,open:e,onOk:b,onCancel:m,confirmLoading:f,okText:f?"Deleting...":"Delete",cancelText:"Cancel",okButtonProps:{danger:!0,disabled:!!p&&y!==p||f},cancelButtonProps:{disabled:f},children:(0,t.jsxs)("div",{className:"space-y-4",children:[d&&(0,t.jsx)(l.Alert,{message:d,type:"warning"}),(0,t.jsx)(a.Card,{title:u,className:"mt-4",styles:{body:{padding:"16px"},header:{backgroundColor:v.colorErrorBg,borderColor:v.colorErrorBorder}},style:{backgroundColor:v.colorErrorBg,borderColor:v.colorErrorBorder},children:(0,t.jsx)(n.Descriptions,{column:1,size:"small",children:g&&g.map(({label:e,value:l,...a})=>(0,t.jsx)(n.Descriptions.Item,{label:(0,t.jsx)("span",{className:"font-semibold",children:e}),children:(0,t.jsx)($,{...a,children:l??"-"})},e))})}),(0,t.jsx)("div",{children:(0,t.jsx)($,{children:c})}),p&&(0,t.jsxs)("div",{className:"mb-6 mt-4 pt-4 border-t border-gray-200 dark:border-gray-700",children:[(0,t.jsxs)($,{className:"block text-base font-medium text-gray-700 dark:text-gray-300 mb-2",children:[(0,t.jsx)($,{children:"Type "}),(0,t.jsx)($,{strong:!0,type:"danger",children:p}),(0,t.jsx)($,{children:" to confirm deletion:"})]}),(0,t.jsx)(r.Input,{value:y,onChange:e=>O(e.target.value),placeholder:p,className:"rounded-md",prefix:(0,t.jsx)(S.ExclamationCircleOutlined,{style:{color:v.colorError}}),autoFocus:!0})]})]})})}e.s(["default",()=>E],127952)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/26fda1c4c6936e38.js b/litellm/proxy/_experimental/out/_next/static/chunks/26fda1c4c6936e38.js new file mode 100644 index 00000000000..9f6e5ddfe58 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/26fda1c4c6936e38.js @@ -0,0 +1 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,94629,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4"}))});e.s(["SwitchVerticalIcon",0,r],94629)},991124,e=>{"use strict";let t=(0,e.i(475254).default)("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"}]]);e.s(["default",()=>t])},678784,678745,e=>{"use strict";let t=(0,e.i(475254).default)("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);e.s(["default",()=>t],678745),e.s(["CheckIcon",()=>t],678784)},118366,e=>{"use strict";var t=e.i(991124);e.s(["CopyIcon",()=>t.default])},829672,836938,310730,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),a=e.i(914949),i=e.i(404948);let s=e=>e?"function"==typeof e?e():e:null;e.s(["getRenderPropValue",0,s],836938);var l=e.i(613541),n=e.i(763731),o=e.i(242064),u=e.i(491816);e.i(793154);var c=e.i(880476),d=e.i(183293),f=e.i(717356),p=e.i(320560),h=e.i(307358),m=e.i(246422),g=e.i(838378),y=e.i(617933);let v=(0,m.genStyleHooks)("Popover",e=>{let{colorBgElevated:t,colorText:r}=e,a=(0,g.mergeToken)(e,{popoverBg:t,popoverColor:r});return[(e=>{let{componentCls:t,popoverColor:r,titleMinWidth:a,fontWeightStrong:i,innerPadding:s,boxShadowSecondary:l,colorTextHeading:n,borderRadiusLG:o,zIndexPopup:u,titleMarginBottom:c,colorBgElevated:f,popoverBg:h,titleBorderBottom:m,innerContentPadding:g,titlePadding:y}=e;return[{[t]:Object.assign(Object.assign({},(0,d.resetComponent)(e)),{position:"absolute",top:0,left:{_skip_check_:!0,value:0},zIndex:u,fontWeight:"normal",whiteSpace:"normal",textAlign:"start",cursor:"auto",userSelect:"text","--valid-offset-x":"var(--arrow-offset-horizontal, var(--arrow-x))",transformOrigin:"var(--valid-offset-x, 50%) var(--arrow-y, 50%)","--antd-arrow-background-color":f,width:"max-content",maxWidth:"100vw","&-rtl":{direction:"rtl"},"&-hidden":{display:"none"},[`${t}-content`]:{position:"relative"},[`${t}-inner`]:{backgroundColor:h,backgroundClip:"padding-box",borderRadius:o,boxShadow:l,padding:s},[`${t}-title`]:{minWidth:a,marginBottom:c,color:n,fontWeight:i,borderBottom:m,padding:y},[`${t}-inner-content`]:{color:r,padding:g}})},(0,p.default)(e,"var(--antd-arrow-background-color)"),{[`${t}-pure`]:{position:"relative",maxWidth:"none",margin:e.sizePopupArrow,display:"inline-block",[`${t}-content`]:{display:"inline-block"}}}]})(a),(e=>{let{componentCls:t}=e;return{[t]:y.PresetColors.map(r=>{let a=e[`${r}6`];return{[`&${t}-${r}`]:{"--antd-arrow-background-color":a,[`${t}-inner`]:{backgroundColor:a},[`${t}-arrow`]:{background:"transparent"}}}})}})(a),(0,f.initZoomMotion)(a,"zoom-big")]},e=>{let{lineWidth:t,controlHeight:r,fontHeight:a,padding:i,wireframe:s,zIndexPopupBase:l,borderRadiusLG:n,marginXS:o,lineType:u,colorSplit:c,paddingSM:d}=e,f=r-a;return Object.assign(Object.assign(Object.assign({titleMinWidth:177,zIndexPopup:l+30},(0,h.getArrowToken)(e)),(0,p.getArrowOffsetToken)({contentRadius:n,limitVerticalRadius:!0})),{innerPadding:12*!s,titleMarginBottom:s?0:o,titlePadding:s?`${f/2}px ${i}px ${f/2-t}px`:0,titleBorderBottom:s?`${t}px ${u} ${c}`:"none",innerContentPadding:s?`${d}px ${i}px`:0})},{resetStyle:!1,deprecatedTokens:[["width","titleMinWidth"],["minWidth","titleMinWidth"]]});var b=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,a=Object.getOwnPropertySymbols(e);it.indexOf(a[i])&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(r[a[i]]=e[a[i]]);return r};let w=({title:e,content:r,prefixCls:a})=>e||r?t.createElement(t.Fragment,null,e&&t.createElement("div",{className:`${a}-title`},e),r&&t.createElement("div",{className:`${a}-inner-content`},r)):null,x=e=>{let{hashId:a,prefixCls:i,className:l,style:n,placement:o="top",title:u,content:d,children:f}=e,p=s(u),h=s(d),m=(0,r.default)(a,i,`${i}-pure`,`${i}-placement-${o}`,l);return t.createElement("div",{className:m,style:n},t.createElement("div",{className:`${i}-arrow`}),t.createElement(c.Popup,Object.assign({},e,{className:a,prefixCls:i}),f||t.createElement(w,{prefixCls:i,title:p,content:h})))},O=e=>{let{prefixCls:a,className:i}=e,s=b(e,["prefixCls","className"]),{getPrefixCls:l}=t.useContext(o.ConfigContext),n=l("popover",a),[u,c,d]=v(n);return u(t.createElement(x,Object.assign({},s,{prefixCls:n,hashId:c,className:(0,r.default)(i,d)})))};e.s(["Overlay",0,w,"default",0,O],310730);var C=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,a=Object.getOwnPropertySymbols(e);it.indexOf(a[i])&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(r[a[i]]=e[a[i]]);return r};let j=t.forwardRef((e,c)=>{var d,f;let{prefixCls:p,title:h,content:m,overlayClassName:g,placement:y="top",trigger:b="hover",children:x,mouseEnterDelay:O=.1,mouseLeaveDelay:j=.1,onOpenChange:S,overlayStyle:P={},styles:E,classNames:M}=e,$=C(e,["prefixCls","title","content","overlayClassName","placement","trigger","children","mouseEnterDelay","mouseLeaveDelay","onOpenChange","overlayStyle","styles","classNames"]),{getPrefixCls:N,className:k,style:I,classNames:R,styles:_}=(0,o.useComponentConfig)("popover"),D=N("popover",p),[K,z,F]=v(D),L=N(),T=(0,r.default)(g,z,F,k,R.root,null==M?void 0:M.root),A=(0,r.default)(R.body,null==M?void 0:M.body),[B,Q]=(0,a.default)(!1,{value:null!=(d=e.open)?d:e.visible,defaultValue:null!=(f=e.defaultOpen)?f:e.defaultVisible}),q=(e,t)=>{Q(e,!0),null==S||S(e,t)},G=s(h),W=s(m);return K(t.createElement(u.default,Object.assign({placement:y,trigger:b,mouseEnterDelay:O,mouseLeaveDelay:j},$,{prefixCls:D,classNames:{root:T,body:A},styles:{root:Object.assign(Object.assign(Object.assign(Object.assign({},_.root),I),P),null==E?void 0:E.root),body:Object.assign(Object.assign({},_.body),null==E?void 0:E.body)},ref:c,open:B,onOpenChange:e=>{q(e)},overlay:G||W?t.createElement(w,{prefixCls:D,title:G,content:W}):null,transitionName:(0,l.getTransitionName)(L,"zoom-big",$.transitionName),"data-popover-inject":!0}),(0,n.cloneElement)(x,{onKeyDown:e=>{var r,a;(0,t.isValidElement)(x)&&(null==(a=null==x?void 0:(r=x.props).onKeyDown)||a.call(r,e)),e.keyCode===i.default.ESC&&q(!1,e)}})))});j._InternalPanelDoNotUseOrYouWillBeFired=O,e.s(["default",0,j],829672)},282786,e=>{"use strict";var t=e.i(829672);e.s(["Popover",()=>t.default])},751904,e=>{"use strict";var t=e.i(401361);e.s(["EditOutlined",()=>t.default])},625901,e=>{"use strict";var t=e.i(266027),r=e.i(621482),a=e.i(243652),i=e.i(764205),s=e.i(135214);let l=(0,a.createQueryKeys)("models"),n=(0,a.createQueryKeys)("modelHub"),o=(0,a.createQueryKeys)("allProxyModels");(0,a.createQueryKeys)("selectedTeamModels");let u=(0,a.createQueryKeys)("infiniteModels");e.s(["useAllProxyModels",0,()=>{let{accessToken:e,userId:r,userRole:a}=(0,s.default)();return(0,t.useQuery)({queryKey:o.list({}),queryFn:async()=>await (0,i.modelAvailableCall)(e,r,a,!0,null,!0,!1,"expand"),enabled:!!(e&&r&&a)})},"useInfiniteModelInfo",0,(e=50,t)=>{let{accessToken:a,userId:l,userRole:n}=(0,s.default)();return(0,r.useInfiniteQuery)({queryKey:u.list({filters:{...l&&{userId:l},...n&&{userRole:n},size:e,...t&&{search:t}}}),queryFn:async({pageParam:r})=>await (0,i.modelInfoCall)(a,l,n,r,e,t),initialPageParam:1,getNextPageParam:e=>{if(e.current_page{let{accessToken:e}=(0,s.default)();return(0,t.useQuery)({queryKey:n.list({}),queryFn:async()=>await (0,i.modelHubCall)(e),enabled:!!e})},"useModelsInfo",0,(e=1,r=50,a,n,o,u,c)=>{let{accessToken:d,userId:f,userRole:p}=(0,s.default)();return(0,t.useQuery)({queryKey:l.list({filters:{...f&&{userId:f},...p&&{userRole:p},page:e,size:r,...a&&{search:a},...n&&{modelId:n},...o&&{teamId:o},...u&&{sortBy:u},...c&&{sortOrder:c}}}),queryFn:async()=>await (0,i.modelInfoCall)(d,f,p,e,r,a,n,o,u,c),enabled:!!(d&&f&&p)})}])},91979,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let 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"};var i=e.i(9583),s=r.forwardRef(function(e,s){return r.createElement(i.default,(0,t.default)({},e,{ref:s,icon:a}))});e.s(["ReloadOutlined",0,s],91979)},969550,e=>{"use strict";var t=e.i(843476),r=e.i(271645);let a=r.forwardRef(function(e,t){return r.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:t},e),r.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",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"}))});var i=e.i(464571),s=e.i(311451),l=e.i(199133),n=e.i(374009);e.s(["default",0,({options:e,onApplyFilters:o,onResetFilters:u,initialValues:c={},buttonLabel:d="Filters"})=>{let[f,p]=(0,r.useState)(!1),[h,m]=(0,r.useState)(c),[g,y]=(0,r.useState)({}),[v,b]=(0,r.useState)({}),[w,x]=(0,r.useState)({}),[O,C]=(0,r.useState)({}),j=(0,r.useCallback)((0,n.default)(async(e,t)=>{if(t.isSearchable&&t.searchFn){b(e=>({...e,[t.name]:!0}));try{let r=await t.searchFn(e);y(e=>({...e,[t.name]:r}))}catch(e){console.error("Error searching:",e),y(e=>({...e,[t.name]:[]}))}finally{b(e=>({...e,[t.name]:!1}))}}},300),[]),S=(0,r.useCallback)(async e=>{if(e.isSearchable&&e.searchFn&&!O[e.name]){b(t=>({...t,[e.name]:!0})),C(t=>({...t,[e.name]:!0}));try{let t=await e.searchFn("");y(r=>({...r,[e.name]:t}))}catch(t){console.error("Error loading initial options:",t),y(t=>({...t,[e.name]:[]}))}finally{b(t=>({...t,[e.name]:!1}))}}},[O]);(0,r.useEffect)(()=>{f&&e.forEach(e=>{e.isSearchable&&!O[e.name]&&S(e)})},[f,e,S,O]);let P=(e,t)=>{let r={...h,[e]:t};m(r),o(r)};return(0,t.jsxs)("div",{className:"w-full",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 mb-6",children:[(0,t.jsx)(i.Button,{icon:(0,t.jsx)(a,{className:"h-4 w-4"}),onClick:()=>p(!f),className:"flex items-center gap-2",children:d}),(0,t.jsx)(i.Button,{onClick:()=>{let t={};e.forEach(e=>{t[e.name]=""}),m(t),u()},children:"Reset Filters"})]}),f&&(0,t.jsx)("div",{className:"grid grid-cols-3 gap-x-6 gap-y-4 mb-6",children:["Team ID","Status","Organization ID","Key Alias","User ID","End User","Error Code","Error Message","Key Hash","Model"].map(r=>{let a,i=e.find(e=>e.label===r||e.name===r);return i?(0,t.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,t.jsx)("label",{className:"text-sm text-gray-600",children:i.label||i.name}),i.isSearchable?(0,t.jsx)(l.Select,{showSearch:!0,className:"w-full",placeholder:`Search ${i.label||i.name}...`,value:h[i.name]||void 0,onChange:e=>P(i.name,e),onOpenChange:e=>{e&&i.isSearchable&&!O[i.name]&&S(i)},onSearch:e=>{x(t=>({...t,[i.name]:e})),i.searchFn&&j(e,i)},filterOption:!1,loading:v[i.name],options:g[i.name]||[],allowClear:!0,notFoundContent:v[i.name]?"Loading...":"No results found"}):i.options?(0,t.jsx)(l.Select,{className:"w-full",placeholder:`Select ${i.label||i.name}...`,value:h[i.name]||void 0,onChange:e=>P(i.name,e),allowClear:!0,children:i.options.map(e=>(0,t.jsx)(l.Select.Option,{value:e.value,children:e.label},e.value))}):i.customComponent?(a=i.customComponent,(0,t.jsx)(a,{value:h[i.name]||void 0,onChange:e=>P(i.name,e??""),placeholder:`Select ${i.label||i.name}...`})):(0,t.jsx)(s.Input,{className:"w-full",placeholder:`Enter ${i.label||i.name}...`,value:h[i.name]||"",onChange:e=>P(i.name,e.target.value),allowClear:!0})]},i.name):null})})]})}],969550)},633627,e=>{"use strict";var t=e.i(764205);let r=(e,t,r,a)=>{for(let i of e){let e=i?.key_alias;e&&"string"==typeof e&&t.add(e.trim());let s=i?.organization_id??i?.org_id;s&&"string"==typeof s&&r.add(s.trim());let l=i?.user_id;if(l&&"string"==typeof l){let e=i?.user?.user_email||l;a.set(l,e)}}},a=async(e,a)=>{if(!e||!a)return{keyAliases:[],organizationIds:[],userIds:[]};try{let i=new Set,s=new Set,l=new Map,n=await (0,t.keyListCall)(e,null,a,null,null,null,1,100,null,null,"user",null),o=n?.keys||[],u=n?.total_pages??1;r(o,i,s,l);let c=Math.min(u,10)-1;if(c>0){let n=Array.from({length:c},(r,i)=>(0,t.keyListCall)(e,null,a,null,null,null,i+2,100,null,null,"user",null));for(let e of(await Promise.allSettled(n)))"fulfilled"===e.status&&r(e.value?.keys||[],i,s,l)}return{keyAliases:Array.from(i).sort(),organizationIds:Array.from(s).sort(),userIds:Array.from(l.entries()).map(([e,t])=>({id:e,email:t}))}}catch(e){return console.error("Error fetching team filter options:",e),{keyAliases:[],organizationIds:[],userIds:[]}}},i=async(e,r)=>{if(!e)return[];try{let a=[],i=1,s=!0;for(;s;){let l=await (0,t.teamListCall)(e,r||null,null);a=[...a,...l],i{if(!e)return[];try{let r=[],a=1,i=!0;for(;i;){let s=await (0,t.organizationListCall)(e);r=[...r,...s],a{"use strict";var t=e.i(271645),r=e.i(135214),a=e.i(270345);e.s(["default",0,()=>{let[e,i]=(0,t.useState)([]),{accessToken:s,userId:l,userRole:n}=(0,r.default)();return(0,t.useEffect)(()=>{(async()=>{i(await (0,a.fetchTeams)(s,l,n,null))})()},[s,l,n]),{teams:e,setTeams:i}}])},439189,435684,96226,497245,e=>{"use strict";function t(e){let t=Object.prototype.toString.call(e);return e instanceof Date||"object"==typeof e&&"[object Date]"===t?new e.constructor(+e):new Date("number"==typeof e||"[object Number]"===t||"string"==typeof e||"[object String]"===t?e:NaN)}function r(e,t){return e instanceof Date?new e.constructor(t):new Date(t)}function a(e,a){let i=t(e);return isNaN(a)?r(e,NaN):(a&&i.setDate(i.getDate()+a),i)}function i(e,a){let i=t(e);if(isNaN(a))return r(e,NaN);if(!a)return i;let s=i.getDate(),l=r(e,i.getTime());return(l.setMonth(i.getMonth()+a+1,0),s>=l.getDate())?l:(i.setFullYear(l.getFullYear(),l.getMonth(),s),i)}e.s(["toDate",()=>t],435684),e.s(["constructFrom",()=>r],96226),e.s(["addDays",()=>a],439189),e.s(["addMonths",()=>i],497245)},891547,e=>{"use strict";var t=e.i(843476),r=e.i(271645),a=e.i(199133),i=e.i(764205);e.s(["default",0,({onChange:e,value:s,className:l,accessToken:n,disabled:o})=>{let[u,c]=(0,r.useState)([]),[d,f]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{(async()=>{if(n){f(!0);try{let e=await (0,i.getGuardrailsList)(n);console.log("Guardrails response:",e),e.guardrails&&(console.log("Guardrails data:",e.guardrails),c(e.guardrails))}catch(e){console.error("Error fetching guardrails:",e)}finally{f(!1)}}})()},[n]),(0,t.jsx)("div",{children:(0,t.jsx)(a.Select,{mode:"multiple",disabled:o,placeholder:o?"Setting guardrails is a premium feature.":"Select guardrails",onChange:t=>{console.log("Selected guardrails:",t),e(t)},value:s,loading:d,className:l,allowClear:!0,options:u.map(e=>(console.log("Mapping guardrail:",e),{label:`${e.guardrail_name}`,value:e.guardrail_name})),optionFilterProp:"label",showSearch:!0,style:{width:"100%"}})})}])},921511,e=>{"use strict";var t=e.i(843476),r=e.i(271645),a=e.i(199133),i=e.i(764205);function s(e){return e.filter(e=>(e.version_status??"draft")!=="draft").map(e=>{var t;let r=e.version_number??1,a=e.version_status??"draft";return{label:`${e.policy_name} — v${r} (${a})${e.description?` — ${e.description}`:""}`,value:"production"===a?e.policy_name:e.policy_id?(t=e.policy_id,`policy_${t}`):e.policy_name}})}e.s(["default",0,({onChange:e,value:l,className:n,accessToken:o,disabled:u,onPoliciesLoaded:c})=>{let[d,f]=(0,r.useState)([]),[p,h]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{(async()=>{if(o){h(!0);try{let e=await (0,i.getPoliciesList)(o);e.policies&&(f(e.policies),c?.(e.policies))}catch(e){console.error("Error fetching policies:",e)}finally{h(!1)}}})()},[o,c]),(0,t.jsx)("div",{children:(0,t.jsx)(a.Select,{mode:"multiple",disabled:u,placeholder:u?"Setting policies is a premium feature.":"Select policies (production or published versions)",onChange:t=>{e(t)},value:l,loading:p,className:n,allowClear:!0,options:s(d),optionFilterProp:"label",showSearch:!0,style:{width:"100%"}})})},"getPolicyOptionEntries",()=>s])},637235,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let 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 372z"}},{tag:"path",attrs:{d:"M686.7 638.6L544.1 535.5V288c0-4.4-3.6-8-8-8H488c-4.4 0-8 3.6-8 8v275.4c0 2.6 1.2 5 3.3 6.5l165.4 120.6c3.6 2.6 8.6 1.8 11.2-1.7l28.6-39c2.6-3.7 1.8-8.7-1.8-11.2z"}}]},name:"clock-circle",theme:"outlined"};var i=e.i(9583),s=r.forwardRef(function(e,s){return r.createElement(i.default,(0,t.default)({},e,{ref:s,icon:a}))});e.s(["ClockCircleOutlined",0,s],637235)},646563,e=>{"use strict";var t=e.i(959013);e.s(["PlusOutlined",()=>t.default])},447566,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M872 474H286.9l350.2-304c5.6-4.9 2.2-14-5.2-14h-88.5c-3.9 0-7.6 1.4-10.5 3.9L155 487.8a31.96 31.96 0 000 48.3L535.1 866c1.5 1.3 3.3 2 5.2 2h91.5c7.4 0 10.8-9.2 5.2-14L286.9 550H872c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8z"}}]},name:"arrow-left",theme:"outlined"};var i=e.i(9583),s=r.forwardRef(function(e,s){return r.createElement(i.default,(0,t.default)({},e,{ref:s,icon:a}))});e.s(["ArrowLeftOutlined",0,s],447566)},954616,e=>{"use strict";var t=e.i(271645),r=e.i(114272),a=e.i(540143),i=e.i(915823),s=e.i(619273),l=class extends i.Subscribable{#e;#t=void 0;#r;#a;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),(0,s.shallowEqualObjects)(this.options,t)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#r,observer:this}),t?.mutationKey&&this.options.mutationKey&&(0,s.hashKey)(t.mutationKey)!==(0,s.hashKey)(this.options.mutationKey)?this.reset():this.#r?.state.status==="pending"&&this.#r.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#r?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#s(e)}getCurrentResult(){return this.#t}reset(){this.#r?.removeObserver(this),this.#r=void 0,this.#i(),this.#s()}mutate(e,t){return this.#a=t,this.#r?.removeObserver(this),this.#r=this.#e.getMutationCache().build(this.#e,this.options),this.#r.addObserver(this),this.#r.execute(e)}#i(){let e=this.#r?.state??(0,r.getDefaultState)();this.#t={...e,isPending:"pending"===e.status,isSuccess:"success"===e.status,isError:"error"===e.status,isIdle:"idle"===e.status,mutate:this.mutate,reset:this.reset}}#s(e){a.notifyManager.batch(()=>{if(this.#a&&this.hasListeners()){let t=this.#t.variables,r=this.#t.context,a={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#a.onSuccess?.(e.data,t,r,a)}catch(e){Promise.reject(e)}try{this.#a.onSettled?.(e.data,null,t,r,a)}catch(e){Promise.reject(e)}}else if(e?.type==="error"){try{this.#a.onError?.(e.error,t,r,a)}catch(e){Promise.reject(e)}try{this.#a.onSettled?.(void 0,e.error,t,r,a)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},n=e.i(912598);function o(e,r){let i=(0,n.useQueryClient)(r),[o]=t.useState(()=>new l(i,e));t.useEffect(()=>{o.setOptions(e)},[o,e]);let u=t.useSyncExternalStore(t.useCallback(e=>o.subscribe(a.notifyManager.batchCalls(e)),[o]),()=>o.getCurrentResult(),()=>o.getCurrentResult()),c=t.useCallback((e,t)=>{o.mutate(e,t).catch(s.noop)},[o]);if(u.error&&(0,s.shouldThrowError)(o.options.throwOnError,[u.error]))throw u.error;return{...u,mutate:c,mutateAsync:u.mutate}}e.s(["useMutation",()=>o],954616)},525720,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),a=e.i(529681),i=e.i(908286),s=e.i(242064),l=e.i(246422),n=e.i(838378);let o=["wrap","nowrap","wrap-reverse"],u=["flex-start","flex-end","start","end","center","space-between","space-around","space-evenly","stretch","normal","left","right"],c=["center","start","end","flex-start","flex-end","self-start","self-end","baseline","normal","stretch"],d=function(e,t){let a,i,s;return(0,r.default)(Object.assign(Object.assign(Object.assign({},(a=!0===t.wrap?"wrap":t.wrap,{[`${e}-wrap-${a}`]:a&&o.includes(a)})),(i={},c.forEach(r=>{i[`${e}-align-${r}`]=t.align===r}),i[`${e}-align-stretch`]=!t.align&&!!t.vertical,i)),(s={},u.forEach(r=>{s[`${e}-justify-${r}`]=t.justify===r}),s)))},f=(0,l.genStyleHooks)("Flex",e=>{let{paddingXS:t,padding:r,paddingLG:a}=e,i=(0,n.mergeToken)(e,{flexGapSM:t,flexGap:r,flexGapLG:a});return[(e=>{let{componentCls:t}=e;return{[t]:{display:"flex",margin:0,padding:0,"&-vertical":{flexDirection:"column"},"&-rtl":{direction:"rtl"},"&:empty":{display:"none"}}}})(i),(e=>{let{componentCls:t}=e;return{[t]:{"&-gap-small":{gap:e.flexGapSM},"&-gap-middle":{gap:e.flexGap},"&-gap-large":{gap:e.flexGapLG}}}})(i),(e=>{let{componentCls:t}=e,r={};return o.forEach(e=>{r[`${t}-wrap-${e}`]={flexWrap:e}}),r})(i),(e=>{let{componentCls:t}=e,r={};return c.forEach(e=>{r[`${t}-align-${e}`]={alignItems:e}}),r})(i),(e=>{let{componentCls:t}=e,r={};return u.forEach(e=>{r[`${t}-justify-${e}`]={justifyContent:e}}),r})(i)]},()=>({}),{resetStyle:!1});var p=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,a=Object.getOwnPropertySymbols(e);it.indexOf(a[i])&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(r[a[i]]=e[a[i]]);return r};let h=t.default.forwardRef((e,l)=>{let{prefixCls:n,rootClassName:o,className:u,style:c,flex:h,gap:m,vertical:g=!1,component:y="div",children:v}=e,b=p(e,["prefixCls","rootClassName","className","style","flex","gap","vertical","component","children"]),{flex:w,direction:x,getPrefixCls:O}=t.default.useContext(s.ConfigContext),C=O("flex",n),[j,S,P]=f(C),E=null!=g?g:null==w?void 0:w.vertical,M=(0,r.default)(u,o,null==w?void 0:w.className,C,S,P,d(C,e),{[`${C}-rtl`]:"rtl"===x,[`${C}-gap-${m}`]:(0,i.isPresetSize)(m),[`${C}-vertical`]:E}),$=Object.assign(Object.assign({},null==w?void 0:w.style),c);return h&&($.flex=h),m&&!(0,i.isPresetSize)(m)&&($.gap=m),j(t.default.createElement(y,Object.assign({ref:l,className:M,style:$},(0,a.default)(b,["justify","wrap","align"])),v))});e.s(["Flex",0,h],525720)},621482,e=>{"use strict";var t=e.i(869230),r=e.i(992571),a=class extends t.QueryObserver{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){super.setOptions({...e,behavior:(0,r.infiniteQueryBehavior)()})}getOptimisticResult(e){return e.behavior=(0,r.infiniteQueryBehavior)(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:a}=e,i=super.createResult(e,t),{isFetching:s,isRefetching:l,isError:n,isRefetchError:o}=i,u=a.fetchMeta?.fetchMore?.direction,c=n&&"forward"===u,d=s&&"forward"===u,f=n&&"backward"===u,p=s&&"backward"===u;return{...i,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:(0,r.hasNextPage)(t,a.data),hasPreviousPage:(0,r.hasPreviousPage)(t,a.data),isFetchNextPageError:c,isFetchingNextPage:d,isFetchPreviousPageError:f,isFetchingPreviousPage:p,isRefetchError:o&&!c&&!f,isRefetching:l&&!d&&!p}}},i=e.i(469637);function s(e,t){return(0,i.useBaseQuery)(e,a,t)}e.s(["useInfiniteQuery",()=>s],621482)},785242,e=>{"use strict";var t=e.i(619273),r=e.i(266027),a=e.i(912598),i=e.i(135214),s=e.i(270345),l=e.i(243652),n=e.i(764205);let o=(0,l.createQueryKeys)("teams"),u=async(e,t,r,a={})=>{try{let i=(0,n.getProxyBaseUrl)(),s=new URLSearchParams(Object.entries({team_id:a.teamID,organization_id:a.organizationID,team_alias:a.team_alias,user_id:a.userID,page:t,page_size:r,sort_by:a.sortBy,sort_order:a.sortOrder,status:"deleted"}).filter(([,e])=>null!=e).map(([e,t])=>[e,String(t)])),l=`${i?`${i}/v2/team/list`:"/v2/team/list"}?${s}`,o=await fetch(l,{method:"GET",headers:{[(0,n.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!o.ok){let e=await o.json(),t=(0,n.deriveErrorMessage)(e);throw(0,n.handleError)(t),Error(t)}let u=await o.json();if(console.log("/team/list?status=deleted API Response:",u),u&&"object"==typeof u&&"teams"in u)return u.teams;return u}catch(e){throw console.error("Failed to list deleted teams:",e),e}},c=(0,l.createQueryKeys)("deletedTeams");e.s(["useDeletedTeams",0,(e,a,s={})=>{let{accessToken:l}=(0,i.default)();return(0,r.useQuery)({queryKey:c.list({page:e,limit:a,...s}),queryFn:async()=>await u(l,e,a,s),enabled:!!l,staleTime:3e4,placeholderData:t.keepPreviousData})},"useTeam",0,e=>{let{accessToken:t}=(0,i.default)(),s=(0,a.useQueryClient)();return(0,r.useQuery)({queryKey:o.detail(e),enabled:!!(t&&e),queryFn:async()=>{if(!t||!e)throw Error("Missing auth or teamId");return(0,n.teamInfoCall)(t,e)},initialData:()=>{if(!e)return;let t=s.getQueryData(o.list({}));return t?.find(t=>t.team_id===e)}})},"useTeams",0,()=>{let{accessToken:e,userId:t,userRole:a}=(0,i.default)();return(0,r.useQuery)({queryKey:o.list({}),queryFn:async()=>await (0,s.fetchTeams)(e,t,a,null),enabled:!!e})}])}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/2ac51d4e6cc8e420.js b/litellm/proxy/_experimental/out/_next/static/chunks/2ac51d4e6cc8e420.js deleted file mode 100644 index b121d5e50e3..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/2ac51d4e6cc8e420.js +++ /dev/null @@ -1,8 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,871943,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"}))});e.s(["ChevronDownIcon",0,r],871943)},360820,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 15l7-7 7 7"}))});e.s(["ChevronUpIcon",0,r],360820)},185793,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),a=e.i(242064),o=e.i(529681);let l=e=>{let{prefixCls:a,className:o,style:l,size:i,shape:n}=e,s=(0,r.default)({[`${a}-lg`]:"large"===i,[`${a}-sm`]:"small"===i}),d=(0,r.default)({[`${a}-circle`]:"circle"===n,[`${a}-square`]:"square"===n,[`${a}-round`]:"round"===n}),c=t.useMemo(()=>"number"==typeof i?{width:i,height:i,lineHeight:`${i}px`}:{},[i]);return t.createElement("span",{className:(0,r.default)(a,s,d,o),style:Object.assign(Object.assign({},c),l)})};e.i(296059);var i=e.i(694758),n=e.i(915654),s=e.i(246422),d=e.i(838378);let c=new i.Keyframes("ant-skeleton-loading",{"0%":{backgroundPosition:"100% 50%"},"100%":{backgroundPosition:"0 50%"}}),m=e=>({height:e,lineHeight:(0,n.unit)(e)}),g=e=>Object.assign({width:e},m(e)),u=(e,t)=>Object.assign({width:t(e).mul(5).equal(),minWidth:t(e).mul(5).equal()},m(e)),p=e=>Object.assign({width:e},m(e)),f=(e,t,r)=>{let{skeletonButtonCls:a}=e;return{[`${r}${a}-circle`]:{width:t,minWidth:t,borderRadius:"50%"},[`${r}${a}-round`]:{borderRadius:t}}},h=(e,t)=>Object.assign({width:t(e).mul(2).equal(),minWidth:t(e).mul(2).equal()},m(e)),b=(0,s.genStyleHooks)("Skeleton",e=>{let{componentCls:t,calc:r}=e;return(e=>{let{componentCls:t,skeletonAvatarCls:r,skeletonTitleCls:a,skeletonParagraphCls:o,skeletonButtonCls:l,skeletonInputCls:i,skeletonImageCls:n,controlHeight:s,controlHeightLG:d,controlHeightSM:m,gradientFromColor:b,padding:v,marginSM:C,borderRadius:w,titleHeight:x,blockRadius:k,paragraphLiHeight:$,controlHeightXS:y,paragraphMarginTop:N}=e;return{[t]:{display:"table",width:"100%",[`${t}-header`]:{display:"table-cell",paddingInlineEnd:v,verticalAlign:"top",[r]:Object.assign({display:"inline-block",verticalAlign:"top",background:b},g(s)),[`${r}-circle`]:{borderRadius:"50%"},[`${r}-lg`]:Object.assign({},g(d)),[`${r}-sm`]:Object.assign({},g(m))},[`${t}-content`]:{display:"table-cell",width:"100%",verticalAlign:"top",[a]:{width:"100%",height:x,background:b,borderRadius:k,[`+ ${o}`]:{marginBlockStart:m}},[o]:{padding:0,"> li":{width:"100%",height:$,listStyle:"none",background:b,borderRadius:k,"+ li":{marginBlockStart:y}}},[`${o}> li:last-child:not(:first-child):not(:nth-child(2))`]:{width:"61%"}},[`&-round ${t}-content`]:{[`${a}, ${o} > li`]:{borderRadius:w}}},[`${t}-with-avatar ${t}-content`]:{[a]:{marginBlockStart:C,[`+ ${o}`]:{marginBlockStart:N}}},[`${t}${t}-element`]:Object.assign(Object.assign(Object.assign(Object.assign({display:"inline-block",width:"auto"},(e=>{let{borderRadiusSM:t,skeletonButtonCls:r,controlHeight:a,controlHeightLG:o,controlHeightSM:l,gradientFromColor:i,calc:n}=e;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({[r]:Object.assign({display:"inline-block",verticalAlign:"top",background:i,borderRadius:t,width:n(a).mul(2).equal(),minWidth:n(a).mul(2).equal()},h(a,n))},f(e,a,r)),{[`${r}-lg`]:Object.assign({},h(o,n))}),f(e,o,`${r}-lg`)),{[`${r}-sm`]:Object.assign({},h(l,n))}),f(e,l,`${r}-sm`))})(e)),(e=>{let{skeletonAvatarCls:t,gradientFromColor:r,controlHeight:a,controlHeightLG:o,controlHeightSM:l}=e;return{[t]:Object.assign({display:"inline-block",verticalAlign:"top",background:r},g(a)),[`${t}${t}-circle`]:{borderRadius:"50%"},[`${t}${t}-lg`]:Object.assign({},g(o)),[`${t}${t}-sm`]:Object.assign({},g(l))}})(e)),(e=>{let{controlHeight:t,borderRadiusSM:r,skeletonInputCls:a,controlHeightLG:o,controlHeightSM:l,gradientFromColor:i,calc:n}=e;return{[a]:Object.assign({display:"inline-block",verticalAlign:"top",background:i,borderRadius:r},u(t,n)),[`${a}-lg`]:Object.assign({},u(o,n)),[`${a}-sm`]:Object.assign({},u(l,n))}})(e)),(e=>{let{skeletonImageCls:t,imageSizeBase:r,gradientFromColor:a,borderRadiusSM:o,calc:l}=e;return{[t]:Object.assign(Object.assign({display:"inline-flex",alignItems:"center",justifyContent:"center",verticalAlign:"middle",background:a,borderRadius:o},p(l(r).mul(2).equal())),{[`${t}-path`]:{fill:"#bfbfbf"},[`${t}-svg`]:Object.assign(Object.assign({},p(r)),{maxWidth:l(r).mul(4).equal(),maxHeight:l(r).mul(4).equal()}),[`${t}-svg${t}-svg-circle`]:{borderRadius:"50%"}}),[`${t}${t}-circle`]:{borderRadius:"50%"}}})(e)),[`${t}${t}-block`]:{width:"100%",[l]:{width:"100%"},[i]:{width:"100%"}},[`${t}${t}-active`]:{[` - ${a}, - ${o} > li, - ${r}, - ${l}, - ${i}, - ${n} - `]:Object.assign({},{background:e.skeletonLoadingBackground,backgroundSize:"400% 100%",animationName:c,animationDuration:e.skeletonLoadingMotionDuration,animationTimingFunction:"ease",animationIterationCount:"infinite"})}}})((0,d.mergeToken)(e,{skeletonAvatarCls:`${t}-avatar`,skeletonTitleCls:`${t}-title`,skeletonParagraphCls:`${t}-paragraph`,skeletonButtonCls:`${t}-button`,skeletonInputCls:`${t}-input`,skeletonImageCls:`${t}-image`,imageSizeBase:r(e.controlHeight).mul(1.5).equal(),borderRadius:100,skeletonLoadingBackground:`linear-gradient(90deg, ${e.gradientFromColor} 25%, ${e.gradientToColor} 37%, ${e.gradientFromColor} 63%)`,skeletonLoadingMotionDuration:"1.4s"}))},e=>{let{colorFillContent:t,colorFill:r}=e;return{color:t,colorGradientEnd:r,gradientFromColor:t,gradientToColor:r,titleHeight:e.controlHeight/2,blockRadius:e.borderRadiusSM,paragraphMarginTop:e.marginLG+e.marginXXS,paragraphLiHeight:e.controlHeight/2}},{deprecatedTokens:[["color","gradientFromColor"],["colorGradientEnd","gradientToColor"]]}),v=e=>{let{prefixCls:a,className:o,style:l,rows:i=0}=e,n=Array.from({length:i}).map((r,a)=>t.createElement("li",{key:a,style:{width:((e,t)=>{let{width:r,rows:a=2}=t;return Array.isArray(r)?r[e]:a-1===e?r:void 0})(a,e)}}));return t.createElement("ul",{className:(0,r.default)(a,o),style:l},n)},C=({prefixCls:e,className:a,width:o,style:l})=>t.createElement("h3",{className:(0,r.default)(e,a),style:Object.assign({width:o},l)});function w(e){return e&&"object"==typeof e?e:{}}let x=e=>{let{prefixCls:o,loading:i,className:n,rootClassName:s,style:d,children:c,avatar:m=!1,title:g=!0,paragraph:u=!0,active:p,round:f}=e,{getPrefixCls:h,direction:x,className:k,style:$}=(0,a.useComponentConfig)("skeleton"),y=h("skeleton",o),[N,S,E]=b(y);if(i||!("loading"in e)){let e,a,o=!!m,i=!!g,c=!!u;if(o){let r=Object.assign(Object.assign({prefixCls:`${y}-avatar`},i&&!c?{size:"large",shape:"square"}:{size:"large",shape:"circle"}),w(m));e=t.createElement("div",{className:`${y}-header`},t.createElement(l,Object.assign({},r)))}if(i||c){let e,r;if(i){let r=Object.assign(Object.assign({prefixCls:`${y}-title`},!o&&c?{width:"38%"}:o&&c?{width:"50%"}:{}),w(g));e=t.createElement(C,Object.assign({},r))}if(c){let e,a=Object.assign(Object.assign({prefixCls:`${y}-paragraph`},(e={},o&&i||(e.width="61%"),!o&&i?e.rows=3:e.rows=2,e)),w(u));r=t.createElement(v,Object.assign({},a))}a=t.createElement("div",{className:`${y}-content`},e,r)}let h=(0,r.default)(y,{[`${y}-with-avatar`]:o,[`${y}-active`]:p,[`${y}-rtl`]:"rtl"===x,[`${y}-round`]:f},k,n,s,S,E);return N(t.createElement("div",{className:h,style:Object.assign(Object.assign({},$),d)},e,a))}return null!=c?c:null};x.Button=e=>{let{prefixCls:i,className:n,rootClassName:s,active:d,block:c=!1,size:m="default"}=e,{getPrefixCls:g}=t.useContext(a.ConfigContext),u=g("skeleton",i),[p,f,h]=b(u),v=(0,o.default)(e,["prefixCls"]),C=(0,r.default)(u,`${u}-element`,{[`${u}-active`]:d,[`${u}-block`]:c},n,s,f,h);return p(t.createElement("div",{className:C},t.createElement(l,Object.assign({prefixCls:`${u}-button`,size:m},v))))},x.Avatar=e=>{let{prefixCls:i,className:n,rootClassName:s,active:d,shape:c="circle",size:m="default"}=e,{getPrefixCls:g}=t.useContext(a.ConfigContext),u=g("skeleton",i),[p,f,h]=b(u),v=(0,o.default)(e,["prefixCls","className"]),C=(0,r.default)(u,`${u}-element`,{[`${u}-active`]:d},n,s,f,h);return p(t.createElement("div",{className:C},t.createElement(l,Object.assign({prefixCls:`${u}-avatar`,shape:c,size:m},v))))},x.Input=e=>{let{prefixCls:i,className:n,rootClassName:s,active:d,block:c,size:m="default"}=e,{getPrefixCls:g}=t.useContext(a.ConfigContext),u=g("skeleton",i),[p,f,h]=b(u),v=(0,o.default)(e,["prefixCls"]),C=(0,r.default)(u,`${u}-element`,{[`${u}-active`]:d,[`${u}-block`]:c},n,s,f,h);return p(t.createElement("div",{className:C},t.createElement(l,Object.assign({prefixCls:`${u}-input`,size:m},v))))},x.Image=e=>{let{prefixCls:o,className:l,rootClassName:i,style:n,active:s}=e,{getPrefixCls:d}=t.useContext(a.ConfigContext),c=d("skeleton",o),[m,g,u]=b(c),p=(0,r.default)(c,`${c}-element`,{[`${c}-active`]:s},l,i,g,u);return m(t.createElement("div",{className:p},t.createElement("div",{className:(0,r.default)(`${c}-image`,l),style:n},t.createElement("svg",{viewBox:"0 0 1098 1024",xmlns:"http://www.w3.org/2000/svg",className:`${c}-image-svg`},t.createElement("title",null,"Image placeholder"),t.createElement("path",{d:"M365.714286 329.142857q0 45.714286-32.036571 77.677714t-77.677714 32.036571-77.677714-32.036571-32.036571-77.677714 32.036571-77.677714 77.677714-32.036571 77.677714 32.036571 32.036571 77.677714zM950.857143 548.571429l0 256-804.571429 0 0-109.714286 182.857143-182.857143 91.428571 91.428571 292.571429-292.571429zM1005.714286 146.285714l-914.285714 0q-7.460571 0-12.873143 5.412571t-5.412571 12.873143l0 694.857143q0 7.460571 5.412571 12.873143t12.873143 5.412571l914.285714 0q7.460571 0 12.873143-5.412571t5.412571-12.873143l0-694.857143q0-7.460571-5.412571-12.873143t-12.873143-5.412571zM1097.142857 164.571429l0 694.857143q0 37.741714-26.843429 64.585143t-64.585143 26.843429l-914.285714 0q-37.741714 0-64.585143-26.843429t-26.843429-64.585143l0-694.857143q0-37.741714 26.843429-64.585143t64.585143-26.843429l914.285714 0q37.741714 0 64.585143 26.843429t26.843429 64.585143z",className:`${c}-image-path`})))))},x.Node=e=>{let{prefixCls:o,className:l,rootClassName:i,style:n,active:s,children:d}=e,{getPrefixCls:c}=t.useContext(a.ConfigContext),m=c("skeleton",o),[g,u,p]=b(m),f=(0,r.default)(m,`${m}-element`,{[`${m}-active`]:s},u,l,i,p);return g(t.createElement("div",{className:f},t.createElement("div",{className:(0,r.default)(`${m}-image`,l),style:n},d)))},e.s(["default",0,x],185793)},599724,936325,e=>{"use strict";var t=e.i(95779),r=e.i(444755),a=e.i(673706),o=e.i(271645);let l=o.default.forwardRef((e,l)=>{let{color:i,className:n,children:s}=e;return o.default.createElement("p",{ref:l,className:(0,r.tremorTwMerge)("text-tremor-default",i?(0,a.getColorClassNames)(i,t.colorPalette.text).textColor:(0,r.tremorTwMerge)("text-tremor-content","dark:text-dark-tremor-content"),n)},s)});l.displayName="Text",e.s(["default",()=>l],936325),e.s(["Text",()=>l],599724)},994388,e=>{"use strict";var t=e.i(290571),r=e.i(829087),a=e.i(271645);let o=["preEnter","entering","entered","preExit","exiting","exited","unmounted"],l=e=>({_s:e,status:o[e],isEnter:e<3,isMounted:6!==e,isResolved:2===e||e>4}),i=e=>e?6:5,n=(e,t,r,a,o)=>{clearTimeout(a.current);let i=l(e);t(i),r.current=i,o&&o({current:i})};var s=e.i(480731),d=e.i(444755),c=e.i(673706);let m=e=>{var r=(0,t.__rest)(e,[]);return a.default.createElement("svg",Object.assign({},r,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"}),a.default.createElement("path",{fill:"none",d:"M0 0h24v24H0z"}),a.default.createElement("path",{d:"M18.364 5.636L16.95 7.05A7 7 0 1 0 19 12h2a9 9 0 1 1-2.636-6.364z"}))};var g=e.i(95779);let u={xs:{height:"h-4",width:"w-4"},sm:{height:"h-5",width:"w-5"},md:{height:"h-5",width:"w-5"},lg:{height:"h-6",width:"w-6"},xl:{height:"h-6",width:"w-6"}},p=(e,t)=>{switch(e){case"primary":return{textColor:t?(0,c.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",hoverTextColor:t?(0,c.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",bgColor:t?(0,c.getColorClassNames)(t,g.colorPalette.background).bgColor:"bg-tremor-brand dark:bg-dark-tremor-brand",hoverBgColor:t?(0,c.getColorClassNames)(t,g.colorPalette.darkBackground).hoverBgColor:"hover:bg-tremor-brand-emphasis dark:hover:bg-dark-tremor-brand-emphasis",borderColor:t?(0,c.getColorClassNames)(t,g.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",hoverBorderColor:t?(0,c.getColorClassNames)(t,g.colorPalette.darkBorder).hoverBorderColor:"hover:border-tremor-brand-emphasis dark:hover:border-dark-tremor-brand-emphasis"};case"secondary":return{textColor:t?(0,c.getColorClassNames)(t,g.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,c.getColorClassNames)(t,g.colorPalette.text).textColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,c.getColorClassNames)("transparent").bgColor,hoverBgColor:t?(0,d.tremorTwMerge)((0,c.getColorClassNames)(t,g.colorPalette.background).hoverBgColor,"hover:bg-opacity-20 dark:hover:bg-opacity-20"):"hover:bg-tremor-brand-faint dark:hover:bg-dark-tremor-brand-faint",borderColor:t?(0,c.getColorClassNames)(t,g.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand"};case"light":return{textColor:t?(0,c.getColorClassNames)(t,g.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,c.getColorClassNames)(t,g.colorPalette.darkText).hoverTextColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,c.getColorClassNames)("transparent").bgColor,borderColor:"",hoverBorderColor:""}}},f=(0,c.makeClassName)("Button"),h=({loading:e,iconSize:t,iconPosition:r,Icon:o,needMargin:l,transitionStatus:i})=>{let n=l?r===s.HorizontalPositions.Left?(0,d.tremorTwMerge)("-ml-1","mr-1.5"):(0,d.tremorTwMerge)("-mr-1","ml-1.5"):"",c=(0,d.tremorTwMerge)("w-0 h-0"),g={default:c,entering:c,entered:t,exiting:t,exited:c};return e?a.default.createElement(m,{className:(0,d.tremorTwMerge)(f("icon"),"animate-spin shrink-0",n,g.default,g[i]),style:{transition:"width 150ms"}}):a.default.createElement(o,{className:(0,d.tremorTwMerge)(f("icon"),"shrink-0",t,n)})},b=a.default.forwardRef((e,o)=>{let{icon:m,iconPosition:g=s.HorizontalPositions.Left,size:b=s.Sizes.SM,color:v,variant:C="primary",disabled:w,loading:x=!1,loadingText:k,children:$,tooltip:y,className:N}=e,S=(0,t.__rest)(e,["icon","iconPosition","size","color","variant","disabled","loading","loadingText","children","tooltip","className"]),E=x||w,T=void 0!==m||x,O=x&&k,j=!(!$&&!O),z=(0,d.tremorTwMerge)(u[b].height,u[b].width),M="light"!==C?(0,d.tremorTwMerge)("rounded-tremor-default border","shadow-tremor-input","dark:shadow-dark-tremor-input"):"",R=p(C,v),I=("light"!==C?{xs:{paddingX:"px-2.5",paddingY:"py-1.5",fontSize:"text-xs"},sm:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-sm"},md:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-md"},lg:{paddingX:"px-4",paddingY:"py-2.5",fontSize:"text-lg"},xl:{paddingX:"px-4",paddingY:"py-3",fontSize:"text-xl"}}:{xs:{paddingX:"",paddingY:"",fontSize:"text-xs"},sm:{paddingX:"",paddingY:"",fontSize:"text-sm"},md:{paddingX:"",paddingY:"",fontSize:"text-md"},lg:{paddingX:"",paddingY:"",fontSize:"text-lg"},xl:{paddingX:"",paddingY:"",fontSize:"text-xl"}})[b],{tooltipProps:B,getReferenceProps:P}=(0,r.useTooltip)(300),[q,L]=(({enter:e=!0,exit:t=!0,preEnter:r,preExit:o,timeout:s,initialEntered:d,mountOnEnter:c,unmountOnExit:m,onStateChange:g}={})=>{let[u,p]=(0,a.useState)(()=>l(d?2:i(c))),f=(0,a.useRef)(u),h=(0,a.useRef)(0),[b,v]="object"==typeof s?[s.enter,s.exit]:[s,s],C=(0,a.useCallback)(()=>{let e=((e,t)=>{switch(e){case 1:case 0:return 2;case 4:case 3:return i(t)}})(f.current._s,m);e&&n(e,p,f,h,g)},[g,m]);return[u,(0,a.useCallback)(a=>{let l=e=>{switch(n(e,p,f,h,g),e){case 1:b>=0&&(h.current=((...e)=>setTimeout(...e))(C,b));break;case 4:v>=0&&(h.current=((...e)=>setTimeout(...e))(C,v));break;case 0:case 3:h.current=((...e)=>setTimeout(...e))(()=>{isNaN(document.body.offsetTop)||l(e+1)},0)}},s=f.current.isEnter;"boolean"!=typeof a&&(a=!s),a?s||l(e?+!r:2):s&&l(t?o?3:4:i(m))},[C,g,e,t,r,o,b,v,m]),C]})({timeout:50});return(0,a.useEffect)(()=>{L(x)},[x]),a.default.createElement("button",Object.assign({ref:(0,c.mergeRefs)([o,B.refs.setReference]),className:(0,d.tremorTwMerge)(f("root"),"shrink-0 inline-flex justify-center items-center group font-medium outline-none",M,I.paddingX,I.paddingY,I.fontSize,R.textColor,R.bgColor,R.borderColor,R.hoverBorderColor,E?"opacity-50 cursor-not-allowed":(0,d.tremorTwMerge)(p(C,v).hoverTextColor,p(C,v).hoverBgColor,p(C,v).hoverBorderColor),N),disabled:E},P,S),a.default.createElement(r.default,Object.assign({text:y},B)),T&&g!==s.HorizontalPositions.Right?a.default.createElement(h,{loading:x,iconSize:z,iconPosition:g,Icon:m,transitionStatus:q.status,needMargin:j}):null,O||$?a.default.createElement("span",{className:(0,d.tremorTwMerge)(f("text"),"text-tremor-default whitespace-nowrap")},O?k:$):null,T&&g===s.HorizontalPositions.Right?a.default.createElement(h,{loading:x,iconSize:z,iconPosition:g,Icon:m,transitionStatus:q.status,needMargin:j}):null)});b.displayName="Button",e.s(["Button",()=>b],994388)},304967,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(480731),o=e.i(95779),l=e.i(444755),i=e.i(673706);let n=(0,i.makeClassName)("Card"),s=r.default.forwardRef((e,s)=>{let{decoration:d="",decorationColor:c,children:m,className:g}=e,u=(0,t.__rest)(e,["decoration","decorationColor","children","className"]);return r.default.createElement("div",Object.assign({ref:s,className:(0,l.tremorTwMerge)(n("root"),"relative w-full text-left ring-1 rounded-tremor-default p-6","bg-tremor-background ring-tremor-ring shadow-tremor-card","dark:bg-dark-tremor-background dark:ring-dark-tremor-ring dark:shadow-dark-tremor-card",c?(0,i.getColorClassNames)(c,o.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",(e=>{if(!e)return"";switch(e){case a.HorizontalPositions.Left:return"border-l-4";case a.VerticalPositions.Top:return"border-t-4";case a.HorizontalPositions.Right:return"border-r-4";case a.VerticalPositions.Bottom:return"border-b-4";default:return""}})(d),g)},u),m)});s.displayName="Card",e.s(["Card",()=>s],304967)},269200,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let o=(0,e.i(673706).makeClassName)("Table"),l=r.default.forwardRef((e,l)=>{let{children:i,className:n}=e,s=(0,t.__rest)(e,["children","className"]);return r.default.createElement("div",{className:(0,a.tremorTwMerge)(o("root"),"overflow-auto",n)},r.default.createElement("table",Object.assign({ref:l,className:(0,a.tremorTwMerge)(o("table"),"w-full text-tremor-default","text-tremor-content","dark:text-dark-tremor-content")},s),i))});l.displayName="Table",e.s(["Table",()=>l],269200)},942232,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let o=(0,e.i(673706).makeClassName)("TableBody"),l=r.default.forwardRef((e,l)=>{let{children:i,className:n}=e,s=(0,t.__rest)(e,["children","className"]);return r.default.createElement(r.default.Fragment,null,r.default.createElement("tbody",Object.assign({ref:l,className:(0,a.tremorTwMerge)(o("root"),"align-top divide-y","divide-tremor-border","dark:divide-dark-tremor-border",n)},s),i))});l.displayName="TableBody",e.s(["TableBody",()=>l],942232)},977572,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let o=(0,e.i(673706).makeClassName)("TableCell"),l=r.default.forwardRef((e,l)=>{let{children:i,className:n}=e,s=(0,t.__rest)(e,["children","className"]);return r.default.createElement(r.default.Fragment,null,r.default.createElement("td",Object.assign({ref:l,className:(0,a.tremorTwMerge)(o("root"),"align-middle whitespace-nowrap text-left p-4",n)},s),i))});l.displayName="TableCell",e.s(["TableCell",()=>l],977572)},427612,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let o=(0,e.i(673706).makeClassName)("TableHead"),l=r.default.forwardRef((e,l)=>{let{children:i,className:n}=e,s=(0,t.__rest)(e,["children","className"]);return r.default.createElement(r.default.Fragment,null,r.default.createElement("thead",Object.assign({ref:l,className:(0,a.tremorTwMerge)(o("root"),"text-left","text-tremor-content","dark:text-dark-tremor-content",n)},s),i))});l.displayName="TableHead",e.s(["TableHead",()=>l],427612)},64848,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let o=(0,e.i(673706).makeClassName)("TableHeaderCell"),l=r.default.forwardRef((e,l)=>{let{children:i,className:n}=e,s=(0,t.__rest)(e,["children","className"]);return r.default.createElement(r.default.Fragment,null,r.default.createElement("th",Object.assign({ref:l,className:(0,a.tremorTwMerge)(o("root"),"whitespace-nowrap text-left font-semibold top-0 px-4 py-3.5","text-tremor-content-strong","dark:text-dark-tremor-content-strong",n)},s),i))});l.displayName="TableHeaderCell",e.s(["TableHeaderCell",()=>l],64848)},496020,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let o=(0,e.i(673706).makeClassName)("TableRow"),l=r.default.forwardRef((e,l)=>{let{children:i,className:n}=e,s=(0,t.__rest)(e,["children","className"]);return r.default.createElement(r.default.Fragment,null,r.default.createElement("tr",Object.assign({ref:l,className:(0,a.tremorTwMerge)(o("row"),n)},s),i))});l.displayName="TableRow",e.s(["TableRow",()=>l],496020)},68155,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.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.s(["TrashIcon",0,r],68155)},530212,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10 19l-7-7m0 0l7-7m-7 7h18"}))});e.s(["ArrowLeftIcon",0,r],530212)},350967,46757,e=>{"use strict";var t=e.i(290571),r=e.i(444755),a=e.i(673706),o=e.i(271645);let l={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"},i={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"},n={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"},s={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"},d={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"},c={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"},m={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"},g={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"};e.s(["colSpan",()=>d,"colSpanLg",()=>g,"colSpanMd",()=>m,"colSpanSm",()=>c,"gridCols",()=>l,"gridColsLg",()=>s,"gridColsMd",()=>n,"gridColsSm",()=>i],46757);let u=(0,a.makeClassName)("Grid"),p=(e,t)=>e&&Object.keys(t).includes(String(e))?t[e]:"",f=o.default.forwardRef((e,a)=>{let{numItems:d=1,numItemsSm:c,numItemsMd:m,numItemsLg:g,children:f,className:h}=e,b=(0,t.__rest)(e,["numItems","numItemsSm","numItemsMd","numItemsLg","children","className"]),v=p(d,l),C=p(c,i),w=p(m,n),x=p(g,s),k=(0,r.tremorTwMerge)(v,C,w,x);return o.default.createElement("div",Object.assign({ref:a,className:(0,r.tremorTwMerge)(u("root"),"grid",k,h)},b),f)});f.displayName="Grid",e.s(["Grid",()=>f],350967)},629569,e=>{"use strict";var t=e.i(290571),r=e.i(95779),a=e.i(444755),o=e.i(673706),l=e.i(271645);let i=l.default.forwardRef((e,i)=>{let{color:n,children:s,className:d}=e,c=(0,t.__rest)(e,["color","children","className"]);return l.default.createElement("p",Object.assign({ref:i,className:(0,a.tremorTwMerge)("font-medium text-tremor-title",n?(0,o.getColorClassNames)(n,r.colorPalette.darkText).textColor:"text-tremor-content-strong dark:text-dark-tremor-content-strong",d)},c),s)});i.displayName="Title",e.s(["Title",()=>i],629569)},244451,e=>{"use strict";let t;e.i(247167);var r=e.i(271645),a=e.i(343794),o=e.i(242064),l=e.i(763731),i=e.i(174428);let n=80*Math.PI,s=e=>{let{dotClassName:t,style:o,hasCircleCls:l}=e;return r.createElement("circle",{className:(0,a.default)(`${t}-circle`,{[`${t}-circle-bg`]:l}),r:40,cx:50,cy:50,strokeWidth:20,style:o})},d=({percent:e,prefixCls:t})=>{let o=`${t}-dot`,l=`${o}-holder`,d=`${l}-hidden`,[c,m]=r.useState(!1);(0,i.default)(()=>{0!==e&&m(!0)},[0!==e]);let g=Math.max(Math.min(e,100),0);if(!c)return null;let u={strokeDashoffset:`${n/4}`,strokeDasharray:`${n*g/100} ${n*(100-g)/100}`};return r.createElement("span",{className:(0,a.default)(l,`${o}-progress`,g<=0&&d)},r.createElement("svg",{viewBox:"0 0 100 100",role:"progressbar","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":g},r.createElement(s,{dotClassName:o,hasCircleCls:!0}),r.createElement(s,{dotClassName:o,style:u})))};function c(e){let{prefixCls:t,percent:o=0}=e,l=`${t}-dot`,i=`${l}-holder`,n=`${i}-hidden`;return r.createElement(r.Fragment,null,r.createElement("span",{className:(0,a.default)(i,o>0&&n)},r.createElement("span",{className:(0,a.default)(l,`${t}-dot-spin`)},[1,2,3,4].map(e=>r.createElement("i",{className:`${t}-dot-item`,key:e})))),r.createElement(d,{prefixCls:t,percent:o}))}function m(e){var t;let{prefixCls:o,indicator:i,percent:n}=e,s=`${o}-dot`;return i&&r.isValidElement(i)?(0,l.cloneElement)(i,{className:(0,a.default)(null==(t=i.props)?void 0:t.className,s),percent:n}):r.createElement(c,{prefixCls:o,percent:n})}e.i(296059);var g=e.i(694758),u=e.i(183293),p=e.i(246422),f=e.i(838378);let h=new g.Keyframes("antSpinMove",{to:{opacity:1}}),b=new g.Keyframes("antRotate",{to:{transform:"rotate(405deg)"}}),v=(0,p.genStyleHooks)("Spin",e=>(e=>{let{componentCls:t,calc:r}=e;return{[t]:Object.assign(Object.assign({},(0,u.resetComponent)(e)),{position:"absolute",display:"none",color:e.colorPrimary,fontSize:0,textAlign:"center",verticalAlign:"middle",opacity:0,transition:`transform ${e.motionDurationSlow} ${e.motionEaseInOutCirc}`,"&-spinning":{position:"relative",display:"inline-block",opacity:1},[`${t}-text`]:{fontSize:e.fontSize,paddingTop:r(r(e.dotSize).sub(e.fontSize)).div(2).add(2).equal()},"&-fullscreen":{position:"fixed",width:"100vw",height:"100vh",backgroundColor:e.colorBgMask,zIndex:e.zIndexPopupBase,inset:0,display:"flex",alignItems:"center",flexDirection:"column",justifyContent:"center",opacity:0,visibility:"hidden",transition:`all ${e.motionDurationMid}`,"&-show":{opacity:1,visibility:"visible"},[t]:{[`${t}-dot-holder`]:{color:e.colorWhite},[`${t}-text`]:{color:e.colorTextLightSolid}}},"&-nested-loading":{position:"relative",[`> div > ${t}`]:{position:"absolute",top:0,insetInlineStart:0,zIndex:4,display:"block",width:"100%",height:"100%",maxHeight:e.contentHeight,[`${t}-dot`]:{position:"absolute",top:"50%",insetInlineStart:"50%",margin:r(e.dotSize).mul(-1).div(2).equal()},[`${t}-text`]:{position:"absolute",top:"50%",width:"100%",textShadow:`0 1px 2px ${e.colorBgContainer}`},[`&${t}-show-text ${t}-dot`]:{marginTop:r(e.dotSize).div(2).mul(-1).sub(10).equal()},"&-sm":{[`${t}-dot`]:{margin:r(e.dotSizeSM).mul(-1).div(2).equal()},[`${t}-text`]:{paddingTop:r(r(e.dotSizeSM).sub(e.fontSize)).div(2).add(2).equal()},[`&${t}-show-text ${t}-dot`]:{marginTop:r(e.dotSizeSM).div(2).mul(-1).sub(10).equal()}},"&-lg":{[`${t}-dot`]:{margin:r(e.dotSizeLG).mul(-1).div(2).equal()},[`${t}-text`]:{paddingTop:r(r(e.dotSizeLG).sub(e.fontSize)).div(2).add(2).equal()},[`&${t}-show-text ${t}-dot`]:{marginTop:r(e.dotSizeLG).div(2).mul(-1).sub(10).equal()}}},[`${t}-container`]:{position:"relative",transition:`opacity ${e.motionDurationSlow}`,"&::after":{position:"absolute",top:0,insetInlineEnd:0,bottom:0,insetInlineStart:0,zIndex:10,width:"100%",height:"100%",background:e.colorBgContainer,opacity:0,transition:`all ${e.motionDurationSlow}`,content:'""',pointerEvents:"none"}},[`${t}-blur`]:{clear:"both",opacity:.5,userSelect:"none",pointerEvents:"none","&::after":{opacity:.4,pointerEvents:"auto"}}},"&-tip":{color:e.spinDotDefault},[`${t}-dot-holder`]:{width:"1em",height:"1em",fontSize:e.dotSize,display:"inline-block",transition:`transform ${e.motionDurationSlow} ease, opacity ${e.motionDurationSlow} ease`,transformOrigin:"50% 50%",lineHeight:1,color:e.colorPrimary,"&-hidden":{transform:"scale(0.3)",opacity:0}},[`${t}-dot-progress`]:{position:"absolute",inset:0},[`${t}-dot`]:{position:"relative",display:"inline-block",fontSize:e.dotSize,width:"1em",height:"1em","&-item":{position:"absolute",display:"block",width:r(e.dotSize).sub(r(e.marginXXS).div(2)).div(2).equal(),height:r(e.dotSize).sub(r(e.marginXXS).div(2)).div(2).equal(),background:"currentColor",borderRadius:"100%",transform:"scale(0.75)",transformOrigin:"50% 50%",opacity:.3,animationName:h,animationDuration:"1s",animationIterationCount:"infinite",animationTimingFunction:"linear",animationDirection:"alternate","&:nth-child(1)":{top:0,insetInlineStart:0,animationDelay:"0s"},"&:nth-child(2)":{top:0,insetInlineEnd:0,animationDelay:"0.4s"},"&:nth-child(3)":{insetInlineEnd:0,bottom:0,animationDelay:"0.8s"},"&:nth-child(4)":{bottom:0,insetInlineStart:0,animationDelay:"1.2s"}},"&-spin":{transform:"rotate(45deg)",animationName:b,animationDuration:"1.2s",animationIterationCount:"infinite",animationTimingFunction:"linear"},"&-circle":{strokeLinecap:"round",transition:["stroke-dashoffset","stroke-dasharray","stroke","stroke-width","opacity"].map(t=>`${t} ${e.motionDurationSlow} ease`).join(","),fillOpacity:0,stroke:"currentcolor"},"&-circle-bg":{stroke:e.colorFillSecondary}},[`&-sm ${t}-dot`]:{"&, &-holder":{fontSize:e.dotSizeSM}},[`&-sm ${t}-dot-holder`]:{i:{width:r(r(e.dotSizeSM).sub(r(e.marginXXS).div(2))).div(2).equal(),height:r(r(e.dotSizeSM).sub(r(e.marginXXS).div(2))).div(2).equal()}},[`&-lg ${t}-dot`]:{"&, &-holder":{fontSize:e.dotSizeLG}},[`&-lg ${t}-dot-holder`]:{i:{width:r(r(e.dotSizeLG).sub(e.marginXXS)).div(2).equal(),height:r(r(e.dotSizeLG).sub(e.marginXXS)).div(2).equal()}},[`&${t}-show-text ${t}-text`]:{display:"block"}})}})((0,f.mergeToken)(e,{spinDotDefault:e.colorTextDescription})),e=>{let{controlHeightLG:t,controlHeight:r}=e;return{contentHeight:400,dotSize:t/2,dotSizeSM:.35*t,dotSizeLG:r}}),C=[[30,.05],[70,.03],[96,.01]];var w=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,a=Object.getOwnPropertySymbols(e);ot.indexOf(a[o])&&Object.prototype.propertyIsEnumerable.call(e,a[o])&&(r[a[o]]=e[a[o]]);return r};let x=e=>{var l;let{prefixCls:i,spinning:n=!0,delay:s=0,className:d,rootClassName:c,size:g="default",tip:u,wrapperClassName:p,style:f,children:h,fullscreen:b=!1,indicator:x,percent:k}=e,$=w(e,["prefixCls","spinning","delay","className","rootClassName","size","tip","wrapperClassName","style","children","fullscreen","indicator","percent"]),{getPrefixCls:y,direction:N,className:S,style:E,indicator:T}=(0,o.useComponentConfig)("spin"),O=y("spin",i),[j,z,M]=v(O),[R,I]=r.useState(()=>n&&(!n||!s||!!Number.isNaN(Number(s)))),B=function(e,t){let[a,o]=r.useState(0),l=r.useRef(null),i="auto"===t;return r.useEffect(()=>(i&&e&&(o(0),l.current=setInterval(()=>{o(e=>{let t=100-e;for(let r=0;r{l.current&&(clearInterval(l.current),l.current=null)}),[i,e]),i?a:t}(R,k);r.useEffect(()=>{if(n){let e=function(e,t,r){var a,o=r||{},l=o.noTrailing,i=void 0!==l&&l,n=o.noLeading,s=void 0!==n&&n,d=o.debounceMode,c=void 0===d?void 0:d,m=!1,g=0;function u(){a&&clearTimeout(a)}function p(){for(var r=arguments.length,o=Array(r),l=0;le?s?(g=Date.now(),i||(a=setTimeout(c?f:p,e))):p():!0!==i&&(a=setTimeout(c?f:p,void 0===c?e-d:e)))}return p.cancel=function(e){var t=(e||{}).upcomingOnly;u(),m=!(void 0!==t&&t)},p}(s,()=>{I(!0)},{debounceMode:false});return e(),()=>{var t;null==(t=null==e?void 0:e.cancel)||t.call(e)}}I(!1)},[s,n]);let P=r.useMemo(()=>void 0!==h&&!b,[h,b]),q=(0,a.default)(O,S,{[`${O}-sm`]:"small"===g,[`${O}-lg`]:"large"===g,[`${O}-spinning`]:R,[`${O}-show-text`]:!!u,[`${O}-rtl`]:"rtl"===N},d,!b&&c,z,M),L=(0,a.default)(`${O}-container`,{[`${O}-blur`]:R}),D=null!=(l=null!=x?x:T)?l:t,H=Object.assign(Object.assign({},E),f),X=r.createElement("div",Object.assign({},$,{style:H,className:q,"aria-live":"polite","aria-busy":R}),r.createElement(m,{prefixCls:O,indicator:D,percent:B}),u&&(P||b)?r.createElement("div",{className:`${O}-text`},u):null);return j(P?r.createElement("div",Object.assign({},$,{className:(0,a.default)(`${O}-nested-loading`,p,z,M)}),R&&r.createElement("div",{key:"loading"},X),r.createElement("div",{className:L,key:"container"},h)):b?r.createElement("div",{className:(0,a.default)(`${O}-fullscreen`,{[`${O}-fullscreen-show`]:R},c,z,M)},X):X)};x.setDefaultIndicator=e=>{t=e},e.s(["default",0,x],244451)},482725,e=>{"use strict";var t=e.i(244451);e.s(["Spin",()=>t.default])}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/2f9ed92e7b7cd792.js b/litellm/proxy/_experimental/out/_next/static/chunks/2f9ed92e7b7cd792.js new file mode 100644 index 00000000000..47b035afd1f --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/2f9ed92e7b7cd792.js @@ -0,0 +1 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,916925,e=>{"use strict";var t,r=((t={}).A2A_Agent="A2A Agent",t.AI21="Ai21",t.AI21_CHAT="Ai21 Chat",t.AIML="AI/ML API",t.AIOHTTP_OPENAI="Aiohttp Openai",t.Anthropic="Anthropic",t.ANTHROPIC_TEXT="Anthropic Text",t.AssemblyAI="AssemblyAI",t.AUTO_ROUTER="Auto Router",t.Bedrock="Amazon Bedrock",t.BedrockMantle="Amazon Bedrock Mantle",t.SageMaker="AWS SageMaker",t.Azure="Azure",t.Azure_AI_Studio="Azure AI Foundry (Studio)",t.AZURE_TEXT="Azure Text",t.BASETEN="Baseten",t.BYTEZ="Bytez",t.Cerebras="Cerebras",t.CLARIFAI="Clarifai",t.CLOUDFLARE="Cloudflare",t.CODESTRAL="Codestral",t.Cohere="Cohere",t.COHERE_CHAT="Cohere Chat",t.COMETAPI="Cometapi",t.COMPACTIFAI="Compactifai",t.Cursor="Cursor",t.Dashscope="Dashscope",t.Databricks="Databricks (Qwen API)",t.DATAROBOT="Datarobot",t.DeepInfra="DeepInfra",t.Deepgram="Deepgram",t.Deepseek="Deepseek",t.DOCKER_MODEL_RUNNER="Docker Model Runner",t.DOTPROMPT="Dotprompt",t.ElevenLabs="ElevenLabs",t.EMPOWER="Empower",t.FalAI="Fal AI",t.FEATHERLESS_AI="Featherless Ai",t.FireworksAI="Fireworks AI",t.FRIENDLIAI="Friendliai",t.GALADRIEL="Galadriel",t.GITHUB_COPILOT="Github Copilot",t.Google_AI_Studio="Google AI Studio",t.GradientAI="GradientAI",t.Groq="Groq",t.HEROKU="Heroku",t.Hosted_Vllm="vllm",t.HUGGINGFACE="Huggingface",t.HYPERBOLIC="Hyperbolic",t.Infinity="Infinity",t.JinaAI="Jina AI",t.LAMBDA_AI="Lambda Ai",t.LEMONADE="Lemonade",t.LLAMAFILE="Llamafile",t.LM_STUDIO="Lm Studio",t.LLAMA="Meta Llama",t.MARITALK="Maritalk",t.MiniMax="MiniMax",t.MistralAI="Mistral AI",t.MOONSHOT="Moonshot",t.MORPH="Morph",t.NEBIUS="Nebius",t.NLP_CLOUD="Nlp Cloud",t.NOVITA="Novita",t.NSCALE="Nscale",t.NVIDIA_NIM="Nvidia Nim",t.Ollama="Ollama",t.OLLAMA_CHAT="Ollama Chat",t.OOBABOOGA="Oobabooga",t.OpenAI="OpenAI",t.OPENAI_LIKE="Openai Like",t.OpenAI_Compatible="OpenAI-Compatible Endpoints (Together AI, etc.)",t.OpenAI_Text="OpenAI Text Completion",t.OpenAI_Text_Compatible="OpenAI-Compatible Text Completion Models (Together AI, etc.)",t.Openrouter="Openrouter",t.Oracle="Oracle Cloud Infrastructure (OCI)",t.OVHCLOUD="Ovhcloud",t.Perplexity="Perplexity",t.PETALS="Petals",t.PG_VECTOR="Pg Vector",t.PREDIBASE="Predibase",t.RECRAFT="Recraft",t.REPLICATE="Replicate",t.RunwayML="RunwayML",t.SAGEMAKER_LEGACY="Sagemaker",t.Sambanova="Sambanova",t.SAP="SAP Generative AI Hub",t.Snowflake="Snowflake",t.TEXT_COMPLETION_CODESTRAL="Text-Completion-Codestral",t.TogetherAI="TogetherAI",t.TOPAZ="Topaz",t.Triton="Triton",t.V0="V0",t.VERCEL_AI_GATEWAY="Vercel Ai Gateway",t.Vertex_AI="Vertex AI (Anthropic, Gemini, etc.)",t.VERTEX_AI_BETA="Vertex Ai Beta",t.VLLM="Vllm",t.VolcEngine="VolcEngine",t.Voyage="Voyage AI",t.WANDB="Wandb",t.WATSONX="Watsonx",t.WATSONX_TEXT="Watsonx Text",t.xAI="xAI",t.XINFERENCE="Xinference",t);let a={A2A_Agent:"a2a_agent",AI21:"ai21",AI21_CHAT:"ai21_chat",AIML:"aiml",AIOHTTP_OPENAI:"aiohttp_openai",Anthropic:"anthropic",ANTHROPIC_TEXT:"anthropic_text",AssemblyAI:"assemblyai",AUTO_ROUTER:"auto_router",Azure:"azure",Azure_AI_Studio:"azure_ai",AZURE_TEXT:"azure_text",BASETEN:"baseten",Bedrock:"bedrock",BedrockMantle:"bedrock_mantle",BYTEZ:"bytez",Cerebras:"cerebras",CLARIFAI:"clarifai",CLOUDFLARE:"cloudflare",CODESTRAL:"codestral",Cohere:"cohere",COHERE_CHAT:"cohere_chat",COMETAPI:"cometapi",COMPACTIFAI:"compactifai",Cursor:"cursor",Dashscope:"dashscope",Databricks:"databricks",DATAROBOT:"datarobot",DeepInfra:"deepinfra",Deepgram:"deepgram",Deepseek:"deepseek",DOCKER_MODEL_RUNNER:"docker_model_runner",DOTPROMPT:"dotprompt",ElevenLabs:"elevenlabs",EMPOWER:"empower",FalAI:"fal_ai",FEATHERLESS_AI:"featherless_ai",FireworksAI:"fireworks_ai",FRIENDLIAI:"friendliai",GALADRIEL:"galadriel",GITHUB_COPILOT:"github_copilot",Google_AI_Studio:"gemini",GradientAI:"gradient_ai",Groq:"groq",HEROKU:"heroku",Hosted_Vllm:"hosted_vllm",HUGGINGFACE:"huggingface",HYPERBOLIC:"hyperbolic",Infinity:"infinity",JinaAI:"jina_ai",LAMBDA_AI:"lambda_ai",LEMONADE:"lemonade",LLAMAFILE:"llamafile",LLAMA:"meta_llama",LM_STUDIO:"lm_studio",MARITALK:"maritalk",MiniMax:"minimax",MistralAI:"mistral",MOONSHOT:"moonshot",MORPH:"morph",NEBIUS:"nebius",NLP_CLOUD:"nlp_cloud",NOVITA:"novita",NSCALE:"nscale",NVIDIA_NIM:"nvidia_nim",Ollama:"ollama",OLLAMA_CHAT:"ollama_chat",OOBABOOGA:"oobabooga",OpenAI:"openai",OPENAI_LIKE:"openai_like",OpenAI_Compatible:"openai",OpenAI_Text:"text-completion-openai",OpenAI_Text_Compatible:"text-completion-openai",Openrouter:"openrouter",Oracle:"oci",OVHCLOUD:"ovhcloud",Perplexity:"perplexity",PETALS:"petals",PG_VECTOR:"pg_vector",PREDIBASE:"predibase",RECRAFT:"recraft",REPLICATE:"replicate",RunwayML:"runwayml",SAGEMAKER_LEGACY:"sagemaker",SageMaker:"sagemaker_chat",Sambanova:"sambanova",SAP:"sap",Snowflake:"snowflake",TEXT_COMPLETION_CODESTRAL:"text-completion-codestral",TogetherAI:"together_ai",TOPAZ:"topaz",Triton:"triton",V0:"v0",VERCEL_AI_GATEWAY:"vercel_ai_gateway",Vertex_AI:"vertex_ai",VERTEX_AI_BETA:"vertex_ai_beta",VLLM:"vllm",VolcEngine:"volcengine",Voyage:"voyage",WANDB:"wandb",WATSONX:"watsonx",WATSONX_TEXT:"watsonx_text",xAI:"xai",XINFERENCE:"xinference"},i="../ui/assets/logos/",o={"A2A Agent":`${i}a2a_agent.png`,Ai21:`${i}ai21.svg`,"Ai21 Chat":`${i}ai21.svg`,"AI/ML API":`${i}aiml_api.svg`,"Aiohttp Openai":`${i}openai_small.svg`,Anthropic:`${i}anthropic.svg`,"Anthropic Text":`${i}anthropic.svg`,AssemblyAI:`${i}assemblyai_small.png`,Azure:`${i}microsoft_azure.svg`,"Azure AI Foundry (Studio)":`${i}microsoft_azure.svg`,"Azure Text":`${i}microsoft_azure.svg`,Baseten:`${i}baseten.svg`,"Amazon Bedrock":`${i}bedrock.svg`,"Amazon Bedrock Mantle":`${i}bedrock.svg`,"AWS SageMaker":`${i}bedrock.svg`,Cerebras:`${i}cerebras.svg`,Cloudflare:`${i}cloudflare.svg`,Codestral:`${i}mistral.svg`,Cohere:`${i}cohere.svg`,"Cohere Chat":`${i}cohere.svg`,Cometapi:`${i}cometapi.svg`,Cursor:`${i}cursor.svg`,"Databricks (Qwen API)":`${i}databricks.svg`,Dashscope:`${i}dashscope.svg`,Deepseek:`${i}deepseek.svg`,Deepgram:`${i}deepgram.png`,DeepInfra:`${i}deepinfra.png`,ElevenLabs:`${i}elevenlabs.png`,"Fal AI":`${i}fal_ai.jpg`,"Featherless Ai":`${i}featherless.svg`,"Fireworks AI":`${i}fireworks.svg`,Friendliai:`${i}friendli.svg`,"Github Copilot":`${i}github_copilot.svg`,"Google AI Studio":`${i}google.svg`,GradientAI:`${i}gradientai.svg`,Groq:`${i}groq.svg`,vllm:`${i}vllm.png`,Huggingface:`${i}huggingface.svg`,Hyperbolic:`${i}hyperbolic.svg`,Infinity:`${i}infinity.png`,"Jina AI":`${i}jina.png`,"Lambda Ai":`${i}lambda.svg`,"Lm Studio":`${i}lmstudio.svg`,"Meta Llama":`${i}meta_llama.svg`,MiniMax:`${i}minimax.svg`,"Mistral AI":`${i}mistral.svg`,Moonshot:`${i}moonshot.svg`,Morph:`${i}morph.svg`,Nebius:`${i}nebius.svg`,Novita:`${i}novita.svg`,"Nvidia Nim":`${i}nvidia_nim.svg`,Ollama:`${i}ollama.svg`,"Ollama Chat":`${i}ollama.svg`,Oobabooga:`${i}openai_small.svg`,OpenAI:`${i}openai_small.svg`,"Openai Like":`${i}openai_small.svg`,"OpenAI Text Completion":`${i}openai_small.svg`,"OpenAI-Compatible Text Completion Models (Together AI, etc.)":`${i}openai_small.svg`,"OpenAI-Compatible Endpoints (Together AI, etc.)":`${i}openai_small.svg`,Openrouter:`${i}openrouter.svg`,"Oracle Cloud Infrastructure (OCI)":`${i}oracle.svg`,Perplexity:`${i}perplexity-ai.svg`,Recraft:`${i}recraft.svg`,Replicate:`${i}replicate.svg`,RunwayML:`${i}runwayml.png`,Sagemaker:`${i}bedrock.svg`,Sambanova:`${i}sambanova.svg`,"SAP Generative AI Hub":`${i}sap.png`,Snowflake:`${i}snowflake.svg`,"Text-Completion-Codestral":`${i}mistral.svg`,TogetherAI:`${i}togetherai.svg`,Topaz:`${i}topaz.svg`,Triton:`${i}nvidia_triton.png`,V0:`${i}v0.svg`,"Vercel Ai Gateway":`${i}vercel.svg`,"Vertex AI (Anthropic, Gemini, etc.)":`${i}google.svg`,"Vertex Ai Beta":`${i}google.svg`,Vllm:`${i}vllm.png`,VolcEngine:`${i}volcengine.png`,"Voyage AI":`${i}voyage.webp`,Watsonx:`${i}watsonx.svg`,"Watsonx Text":`${i}watsonx.svg`,xAI:`${i}xai.svg`,Xinference:`${i}xinference.svg`};e.s(["Providers",()=>r,"getPlaceholder",0,e=>{if("AI/ML API"===e)return"aiml/flux-pro/v1.1";if("Vertex AI (Anthropic, Gemini, etc.)"===e)return"gemini-pro";if("Anthropic"==e)return"claude-3-opus";if("Amazon Bedrock"==e)return"claude-3-opus";if("AWS SageMaker"==e)return"sagemaker/jumpstart-dft-meta-textgeneration-llama-2-7b";else if("Google AI Studio"==e)return"gemini-pro";else if("Azure AI Foundry (Studio)"==e)return"azure_ai/command-r-plus";else if("Azure"==e)return"my-deployment";else if("Oracle Cloud Infrastructure (OCI)"==e)return"oci/xai.grok-4";else if("Snowflake"==e)return"snowflake/mistral-7b";else if("Voyage AI"==e)return"voyage/";else if("Jina AI"==e)return"jina_ai/";else if("VolcEngine"==e)return"volcengine/";else if("DeepInfra"==e)return"deepinfra/";else if("Fal AI"==e)return"fal_ai/fal-ai/flux-pro/v1.1-ultra";else if("RunwayML"==e)return"runwayml/gen4_turbo";else if("Watsonx"===e)return"watsonx/ibm/granite-3-3-8b-instruct";else if("Cursor"===e)return"cursor/claude-4-sonnet";else return"gpt-3.5-turbo"},"getProviderLogoAndName",0,e=>{if(!e)return{logo:"",displayName:"-"};if("gemini"===e.toLowerCase()){let e="Google AI Studio";return{logo:o[e],displayName:e}}let t=Object.keys(a).find(t=>a[t].toLowerCase()===e.toLowerCase());if(!t)return{logo:"",displayName:e};let i=r[t];return{logo:o[i],displayName:i}},"getProviderModels",0,(e,t)=>{console.log(`Provider key: ${e}`);let r=a[e];console.log(`Provider mapped to: ${r}`);let i=[];return e&&"object"==typeof t&&(Object.entries(t).forEach(([e,t])=>{if(null!==t&&"object"==typeof t&&"litellm_provider"in t){let a=t.litellm_provider;(a===r||"string"==typeof a&&a.includes(r))&&i.push(e)}}),"Cohere"==e&&(console.log("Adding cohere chat models"),Object.entries(t).forEach(([e,t])=>{null!==t&&"object"==typeof t&&"litellm_provider"in t&&"cohere_chat"===t.litellm_provider&&i.push(e)})),"AWS SageMaker"==e&&(console.log("Adding sagemaker chat models"),Object.entries(t).forEach(([e,t])=>{null!==t&&"object"==typeof t&&"litellm_provider"in t&&"sagemaker_chat"===t.litellm_provider&&i.push(e)}))),i},"providerLogoMap",0,o,"provider_map",0,a])},362024,e=>{"use strict";var t=e.i(988122);e.s(["Collapse",()=>t.default])},240647,e=>{"use strict";var t=e.i(286612);e.s(["RightOutlined",()=>t.default])},152473,e=>{"use strict";var t=e.i(271645);let r={enabled:!0,leading:!1,trailing:!0,wait:0,onExecute:()=>{}};class a{constructor(e,t){this.fn=e,this._canLeadingExecute=!0,this._isPending=!1,this._executionCount=0,this._options={...r,...t}}setOptions(e){return this._options={...this._options,...e},this._options.enabled||(this._isPending=!1),this._options}getOptions(){return this._options}maybeExecute(...e){this._options.leading&&this._canLeadingExecute&&(this.executeFunction(...e),this._canLeadingExecute=!1),(this._options.leading||this._options.trailing)&&(this._isPending=!0),this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=setTimeout(()=>{this._canLeadingExecute=!0,this._isPending=!1,this._options.trailing&&this.executeFunction(...e)},this._options.wait)}executeFunction(...e){this._options.enabled&&(this.fn(...e),this._executionCount++,this._options.onExecute(this))}cancel(){this._timeoutId&&(clearTimeout(this._timeoutId),this._canLeadingExecute=!0,this._isPending=!1)}getExecutionCount(){return this._executionCount}getIsPending(){return this._options.enabled&&this._isPending}}function i(e,r){let[i,o]=(0,t.useState)(e),n=function(e,r){let[i]=(0,t.useState)(()=>{var t;return Object.getOwnPropertyNames(Object.getPrototypeOf(t=new a(e,r))).filter(e=>"function"==typeof t[e]).reduce((e,r)=>{let a=t[r];return"function"==typeof a&&(e[r]=a.bind(t)),e},{})});return i.setOptions(r),i}(o,r);return[i,n.maybeExecute,n]}e.s(["useDebouncedState",()=>i],152473)},738014,e=>{"use strict";var t=e.i(135214),r=e.i(764205),a=e.i(266027);let i=(0,e.i(243652).createQueryKeys)("users");e.s(["useCurrentUser",0,()=>{let{accessToken:e,userId:o,userRole:n}=(0,t.default)();return(0,a.useQuery)({queryKey:i.detail(o),queryFn:async()=>{let t=await (0,r.userInfoCall)(e,o,n,!1,null,null);return console.log(`userInfo: ${JSON.stringify(t)}`),t.user_info},enabled:!!(e&&o&&n)})}])},906579,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),a=e.i(361275),i=e.i(702779),o=e.i(763731),n=e.i(242064);e.i(296059);var s=e.i(915654),l=e.i(694758),c=e.i(183293),u=e.i(403541),d=e.i(246422),m=e.i(838378);let g=new l.Keyframes("antStatusProcessing",{"0%":{transform:"scale(0.8)",opacity:.5},"100%":{transform:"scale(2.4)",opacity:0}}),p=new l.Keyframes("antZoomBadgeIn",{"0%":{transform:"scale(0) translate(50%, -50%)",opacity:0},"100%":{transform:"scale(1) translate(50%, -50%)"}}),f=new l.Keyframes("antZoomBadgeOut",{"0%":{transform:"scale(1) translate(50%, -50%)"},"100%":{transform:"scale(0) translate(50%, -50%)",opacity:0}}),h=new l.Keyframes("antNoWrapperZoomBadgeIn",{"0%":{transform:"scale(0)",opacity:0},"100%":{transform:"scale(1)"}}),b=new l.Keyframes("antNoWrapperZoomBadgeOut",{"0%":{transform:"scale(1)"},"100%":{transform:"scale(0)",opacity:0}}),v=new l.Keyframes("antBadgeLoadingCircle",{"0%":{transformOrigin:"50%"},"100%":{transform:"translate(50%, -50%) rotate(360deg)",transformOrigin:"50%"}}),A=e=>{let{fontHeight:t,lineWidth:r,marginXS:a,colorBorderBg:i}=e,o=e.colorTextLightSolid,n=e.colorError,s=e.colorErrorHover;return(0,m.mergeToken)(e,{badgeFontHeight:t,badgeShadowSize:r,badgeTextColor:o,badgeColor:n,badgeColorHover:s,badgeShadowColor:i,badgeProcessingDuration:"1.2s",badgeRibbonOffset:a,badgeRibbonCornerTransform:"scaleY(0.75)",badgeRibbonCornerFilter:"brightness(75%)"})},y=e=>{let{fontSize:t,lineHeight:r,fontSizeSM:a,lineWidth:i}=e;return{indicatorZIndex:"auto",indicatorHeight:Math.round(t*r)-2*i,indicatorHeightSM:t,dotSize:a/2,textFontSize:a,textFontSizeSM:a,textFontWeight:"normal",statusSize:a/2}},O=(0,d.genStyleHooks)("Badge",e=>(e=>{let{componentCls:t,iconCls:r,antCls:a,badgeShadowSize:i,textFontSize:o,textFontSizeSM:n,statusSize:l,dotSize:d,textFontWeight:m,indicatorHeight:A,indicatorHeightSM:y,marginXS:O,calc:x}=e,C=`${a}-scroll-number`,I=(0,u.genPresetColor)(e,(e,{darkColor:r})=>({[`&${t} ${t}-color-${e}`]:{background:r,[`&:not(${t}-count)`]:{color:r},"a:hover &":{background:r}}}));return{[t]:Object.assign(Object.assign(Object.assign(Object.assign({},(0,c.resetComponent)(e)),{position:"relative",display:"inline-block",width:"fit-content",lineHeight:1,[`${t}-count`]:{display:"inline-flex",justifyContent:"center",zIndex:e.indicatorZIndex,minWidth:A,height:A,color:e.badgeTextColor,fontWeight:m,fontSize:o,lineHeight:(0,s.unit)(A),whiteSpace:"nowrap",textAlign:"center",background:e.badgeColor,borderRadius:x(A).div(2).equal(),boxShadow:`0 0 0 ${(0,s.unit)(i)} ${e.badgeShadowColor}`,transition:`background ${e.motionDurationMid}`,a:{color:e.badgeTextColor},"a:hover":{color:e.badgeTextColor},"a:hover &":{background:e.badgeColorHover}},[`${t}-count-sm`]:{minWidth:y,height:y,fontSize:n,lineHeight:(0,s.unit)(y),borderRadius:x(y).div(2).equal()},[`${t}-multiple-words`]:{padding:`0 ${(0,s.unit)(e.paddingXS)}`,bdi:{unicodeBidi:"plaintext"}},[`${t}-dot`]:{zIndex:e.indicatorZIndex,width:d,minWidth:d,height:d,background:e.badgeColor,borderRadius:"100%",boxShadow:`0 0 0 ${(0,s.unit)(i)} ${e.badgeShadowColor}`},[`${t}-count, ${t}-dot, ${C}-custom-component`]:{position:"absolute",top:0,insetInlineEnd:0,transform:"translate(50%, -50%)",transformOrigin:"100% 0%",[`&${r}-spin`]:{animationName:v,animationDuration:"1s",animationIterationCount:"infinite",animationTimingFunction:"linear"}},[`&${t}-status`]:{lineHeight:"inherit",verticalAlign:"baseline",[`${t}-status-dot`]:{position:"relative",top:-1,display:"inline-block",width:l,height:l,verticalAlign:"middle",borderRadius:"50%"},[`${t}-status-success`]:{backgroundColor:e.colorSuccess},[`${t}-status-processing`]:{overflow:"visible",color:e.colorInfo,backgroundColor:e.colorInfo,borderColor:"currentcolor","&::after":{position:"absolute",top:0,insetInlineStart:0,width:"100%",height:"100%",borderWidth:i,borderStyle:"solid",borderColor:"inherit",borderRadius:"50%",animationName:g,animationDuration:e.badgeProcessingDuration,animationIterationCount:"infinite",animationTimingFunction:"ease-in-out",content:'""'}},[`${t}-status-default`]:{backgroundColor:e.colorTextPlaceholder},[`${t}-status-error`]:{backgroundColor:e.colorError},[`${t}-status-warning`]:{backgroundColor:e.colorWarning},[`${t}-status-text`]:{marginInlineStart:O,color:e.colorText,fontSize:e.fontSize}}}),I),{[`${t}-zoom-appear, ${t}-zoom-enter`]:{animationName:p,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack,animationFillMode:"both"},[`${t}-zoom-leave`]:{animationName:f,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack,animationFillMode:"both"},[`&${t}-not-a-wrapper`]:{[`${t}-zoom-appear, ${t}-zoom-enter`]:{animationName:h,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack},[`${t}-zoom-leave`]:{animationName:b,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack},[`&:not(${t}-status)`]:{verticalAlign:"middle"},[`${C}-custom-component, ${t}-count`]:{transform:"none"},[`${C}-custom-component, ${C}`]:{position:"relative",top:"auto",display:"block",transformOrigin:"50% 50%"}},[C]:{overflow:"hidden",transition:`all ${e.motionDurationMid} ${e.motionEaseOutBack}`,[`${C}-only`]:{position:"relative",display:"inline-block",height:A,transition:`all ${e.motionDurationSlow} ${e.motionEaseOutBack}`,WebkitTransformStyle:"preserve-3d",WebkitBackfaceVisibility:"hidden",[`> p${C}-only-unit`]:{height:A,margin:0,WebkitTransformStyle:"preserve-3d",WebkitBackfaceVisibility:"hidden"}},[`${C}-symbol`]:{verticalAlign:"top"}},"&-rtl":{direction:"rtl",[`${t}-count, ${t}-dot, ${C}-custom-component`]:{transform:"translate(-50%, -50%)"}}})}})(A(e)),y),x=(0,d.genStyleHooks)(["Badge","Ribbon"],e=>(e=>{let{antCls:t,badgeFontHeight:r,marginXS:a,badgeRibbonOffset:i,calc:o}=e,n=`${t}-ribbon`,l=`${t}-ribbon-wrapper`,d=(0,u.genPresetColor)(e,(e,{darkColor:t})=>({[`&${n}-color-${e}`]:{background:t,color:t}}));return{[l]:{position:"relative"},[n]:Object.assign(Object.assign(Object.assign(Object.assign({},(0,c.resetComponent)(e)),{position:"absolute",top:a,padding:`0 ${(0,s.unit)(e.paddingXS)}`,color:e.colorPrimary,lineHeight:(0,s.unit)(r),whiteSpace:"nowrap",backgroundColor:e.colorPrimary,borderRadius:e.borderRadiusSM,[`${n}-text`]:{color:e.badgeTextColor},[`${n}-corner`]:{position:"absolute",top:"100%",width:i,height:i,color:"currentcolor",border:`${(0,s.unit)(o(i).div(2).equal())} solid`,transform:e.badgeRibbonCornerTransform,transformOrigin:"top",filter:e.badgeRibbonCornerFilter}}),d),{[`&${n}-placement-end`]:{insetInlineEnd:o(i).mul(-1).equal(),borderEndEndRadius:0,[`${n}-corner`]:{insetInlineEnd:0,borderInlineEndColor:"transparent",borderBlockEndColor:"transparent"}},[`&${n}-placement-start`]:{insetInlineStart:o(i).mul(-1).equal(),borderEndStartRadius:0,[`${n}-corner`]:{insetInlineStart:0,borderBlockEndColor:"transparent",borderInlineStartColor:"transparent"}},"&-rtl":{direction:"rtl"}})}})(A(e)),y),C=e=>{let a,{prefixCls:i,value:o,current:n,offset:s=0}=e;return s&&(a={position:"absolute",top:`${s}00%`,left:0}),t.createElement("span",{style:a,className:(0,r.default)(`${i}-only-unit`,{current:n})},o)},I=e=>{let r,a,{prefixCls:i,count:o,value:n}=e,s=Number(n),l=Math.abs(o),[c,u]=t.useState(s),[d,m]=t.useState(l),g=()=>{u(s),m(l)};if(t.useEffect(()=>{let e=setTimeout(g,1e3);return()=>clearTimeout(e)},[s]),c===s||Number.isNaN(s)||Number.isNaN(c))r=[t.createElement(C,Object.assign({},e,{key:s,current:!0}))],a={transition:"none"};else{r=[];let i=s+10,o=[];for(let e=s;e<=i;e+=1)o.push(e);let n=de%10===c);r=(n<0?o.slice(0,u+1):o.slice(u)).map((r,a)=>t.createElement(C,Object.assign({},e,{key:r,value:r%10,offset:n<0?a-u:a,current:a===u}))),a={transform:`translateY(${-function(e,t,r){let a=e,i=0;for(;(a+10)%10!==t;)a+=r,i+=r;return i}(c,s,n)}00%)`}}return t.createElement("span",{className:`${i}-only`,style:a,onTransitionEnd:g},r)};var E=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,a=Object.getOwnPropertySymbols(e);it.indexOf(a[i])&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(r[a[i]]=e[a[i]]);return r};let $=t.forwardRef((e,a)=>{let{prefixCls:i,count:s,className:l,motionClassName:c,style:u,title:d,show:m,component:g="sup",children:p}=e,f=E(e,["prefixCls","count","className","motionClassName","style","title","show","component","children"]),{getPrefixCls:h}=t.useContext(n.ConfigContext),b=h("scroll-number",i),v=Object.assign(Object.assign({},f),{"data-show":m,style:u,className:(0,r.default)(b,l,c),title:d}),A=s;if(s&&Number(s)%1==0){let e=String(s).split("");A=t.createElement("bdi",null,e.map((r,a)=>t.createElement(I,{prefixCls:b,count:Number(s),value:r,key:e.length-a})))}return((null==u?void 0:u.borderColor)&&(v.style=Object.assign(Object.assign({},u),{boxShadow:`0 0 0 1px ${u.borderColor} inset`})),p)?(0,o.cloneElement)(p,e=>({className:(0,r.default)(`${b}-custom-component`,null==e?void 0:e.className,c)})):t.createElement(g,Object.assign({},v,{ref:a}),A)});var _=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,a=Object.getOwnPropertySymbols(e);it.indexOf(a[i])&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(r[a[i]]=e[a[i]]);return r};let T=t.forwardRef((e,s)=>{var l,c,u,d,m;let{prefixCls:g,scrollNumberPrefixCls:p,children:f,status:h,text:b,color:v,count:A=null,overflowCount:y=99,dot:x=!1,size:C="default",title:I,offset:E,style:T,className:w,rootClassName:S,classNames:N,styles:M,showZero:R=!1}=e,P=_(e,["prefixCls","scrollNumberPrefixCls","children","status","text","color","count","overflowCount","dot","size","title","offset","style","className","rootClassName","classNames","styles","showZero"]),{getPrefixCls:k,direction:j,badge:L}=t.useContext(n.ConfigContext),D=k("badge",g),[B,F,z]=O(D),H=A>y?`${y}+`:A,G="0"===H||0===H||"0"===b||0===b,V=null===A||G&&!R,W=(null!=h||null!=v)&&V,K=null!=h||!G,U=x&&!G,q=U?"":H,X=(0,t.useMemo)(()=>((null==q||""===q)&&(null==b||""===b)||G&&!R)&&!U,[q,G,R,U,b]),Q=(0,t.useRef)(A);X||(Q.current=A);let Z=Q.current,Y=(0,t.useRef)(q);X||(Y.current=q);let J=Y.current,ee=(0,t.useRef)(U);X||(ee.current=U);let et=(0,t.useMemo)(()=>{if(!E)return Object.assign(Object.assign({},null==L?void 0:L.style),T);let e={marginTop:E[1]};return"rtl"===j?e.left=Number.parseInt(E[0],10):e.right=-Number.parseInt(E[0],10),Object.assign(Object.assign(Object.assign({},e),null==L?void 0:L.style),T)},[j,E,T,null==L?void 0:L.style]),er=null!=I?I:"string"==typeof Z||"number"==typeof Z?Z:void 0,ea=!X&&(0===b?R:!!b&&!0!==b),ei=ea?t.createElement("span",{className:`${D}-status-text`},b):null,eo=Z&&"object"==typeof Z?(0,o.cloneElement)(Z,e=>({style:Object.assign(Object.assign({},et),e.style)})):void 0,en=(0,i.isPresetColor)(v,!1),es=(0,r.default)(null==N?void 0:N.indicator,null==(l=null==L?void 0:L.classNames)?void 0:l.indicator,{[`${D}-status-dot`]:W,[`${D}-status-${h}`]:!!h,[`${D}-color-${v}`]:en}),el={};v&&!en&&(el.color=v,el.background=v);let ec=(0,r.default)(D,{[`${D}-status`]:W,[`${D}-not-a-wrapper`]:!f,[`${D}-rtl`]:"rtl"===j},w,S,null==L?void 0:L.className,null==(c=null==L?void 0:L.classNames)?void 0:c.root,null==N?void 0:N.root,F,z);if(!f&&W&&(b||K||!V)){let e=et.color;return B(t.createElement("span",Object.assign({},P,{className:ec,style:Object.assign(Object.assign(Object.assign({},null==M?void 0:M.root),null==(u=null==L?void 0:L.styles)?void 0:u.root),et)}),t.createElement("span",{className:es,style:Object.assign(Object.assign(Object.assign({},null==M?void 0:M.indicator),null==(d=null==L?void 0:L.styles)?void 0:d.indicator),el)}),ea&&t.createElement("span",{style:{color:e},className:`${D}-status-text`},b)))}return B(t.createElement("span",Object.assign({ref:s},P,{className:ec,style:Object.assign(Object.assign({},null==(m=null==L?void 0:L.styles)?void 0:m.root),null==M?void 0:M.root)}),f,t.createElement(a.default,{visible:!X,motionName:`${D}-zoom`,motionAppear:!1,motionDeadline:1e3},({className:e})=>{var a,i;let o=k("scroll-number",p),n=ee.current,s=(0,r.default)(null==N?void 0:N.indicator,null==(a=null==L?void 0:L.classNames)?void 0:a.indicator,{[`${D}-dot`]:n,[`${D}-count`]:!n,[`${D}-count-sm`]:"small"===C,[`${D}-multiple-words`]:!n&&J&&J.toString().length>1,[`${D}-status-${h}`]:!!h,[`${D}-color-${v}`]:en}),l=Object.assign(Object.assign(Object.assign({},null==M?void 0:M.indicator),null==(i=null==L?void 0:L.styles)?void 0:i.indicator),et);return v&&!en&&((l=l||{}).background=v),t.createElement($,{prefixCls:o,show:!X,motionClassName:e,className:s,count:J,title:er,style:l,key:"scrollNumber"},eo)}),ei))});T.Ribbon=e=>{let{className:a,prefixCls:o,style:s,color:l,children:c,text:u,placement:d="end",rootClassName:m}=e,{getPrefixCls:g,direction:p}=t.useContext(n.ConfigContext),f=g("ribbon",o),h=`${f}-wrapper`,[b,v,A]=x(f,h),y=(0,i.isPresetColor)(l,!1),O=(0,r.default)(f,`${f}-placement-${d}`,{[`${f}-rtl`]:"rtl"===p,[`${f}-color-${l}`]:y},a),C={},I={};return l&&!y&&(C.background=l,I.color=l),b(t.createElement("div",{className:(0,r.default)(h,m,v,A)},c,t.createElement("div",{className:(0,r.default)(O,v),style:Object.assign(Object.assign({},C),s)},t.createElement("span",{className:`${f}-text`},u),t.createElement("div",{className:`${f}-corner`,style:I}))))},e.s(["Badge",0,T],906579)},621482,e=>{"use strict";var t=e.i(869230),r=e.i(992571),a=class extends t.QueryObserver{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){super.setOptions({...e,behavior:(0,r.infiniteQueryBehavior)()})}getOptimisticResult(e){return e.behavior=(0,r.infiniteQueryBehavior)(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:a}=e,i=super.createResult(e,t),{isFetching:o,isRefetching:n,isError:s,isRefetchError:l}=i,c=a.fetchMeta?.fetchMore?.direction,u=s&&"forward"===c,d=o&&"forward"===c,m=s&&"backward"===c,g=o&&"backward"===c;return{...i,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:(0,r.hasNextPage)(t,a.data),hasPreviousPage:(0,r.hasPreviousPage)(t,a.data),isFetchNextPageError:u,isFetchingNextPage:d,isFetchPreviousPageError:m,isFetchingPreviousPage:g,isRefetchError:l&&!u&&!m,isRefetching:n&&!d&&!g}}},i=e.i(469637);function o(e,t){return(0,i.useBaseQuery)(e,a,t)}e.s(["useInfiniteQuery",()=>o],621482)},785242,e=>{"use strict";var t=e.i(619273),r=e.i(266027),a=e.i(912598),i=e.i(135214),o=e.i(270345),n=e.i(243652),s=e.i(764205);let l=(0,n.createQueryKeys)("teams"),c=async(e,t,r,a={})=>{try{let i=(0,s.getProxyBaseUrl)(),o=new URLSearchParams(Object.entries({team_id:a.teamID,organization_id:a.organizationID,team_alias:a.team_alias,user_id:a.userID,page:t,page_size:r,sort_by:a.sortBy,sort_order:a.sortOrder,status:"deleted"}).filter(([,e])=>null!=e).map(([e,t])=>[e,String(t)])),n=`${i?`${i}/v2/team/list`:"/v2/team/list"}?${o}`,l=await fetch(n,{method:"GET",headers:{[(0,s.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!l.ok){let e=await l.json(),t=(0,s.deriveErrorMessage)(e);throw(0,s.handleError)(t),Error(t)}let c=await l.json();if(console.log("/team/list?status=deleted API Response:",c),c&&"object"==typeof c&&"teams"in c)return c.teams;return c}catch(e){throw console.error("Failed to list deleted teams:",e),e}},u=(0,n.createQueryKeys)("deletedTeams");e.s(["useDeletedTeams",0,(e,a,o={})=>{let{accessToken:n}=(0,i.default)();return(0,r.useQuery)({queryKey:u.list({page:e,limit:a,...o}),queryFn:async()=>await c(n,e,a,o),enabled:!!n,staleTime:3e4,placeholderData:t.keepPreviousData})},"useTeam",0,e=>{let{accessToken:t}=(0,i.default)(),o=(0,a.useQueryClient)();return(0,r.useQuery)({queryKey:l.detail(e),enabled:!!(t&&e),queryFn:async()=>{if(!t||!e)throw Error("Missing auth or teamId");return(0,s.teamInfoCall)(t,e)},initialData:()=>{if(!e)return;let t=o.getQueryData(l.list({}));return t?.find(t=>t.team_id===e)}})},"useTeams",0,()=>{let{accessToken:e,userId:t,userRole:a}=(0,i.default)();return(0,r.useQuery)({queryKey:l.list({}),queryFn:async()=>await (0,o.fetchTeams)(e,t,a,null),enabled:!!e})}])},980187,e=>{"use strict";e.s(["createTeamAliasMap",0,e=>e?e.reduce((e,t)=>(e[t.team_id]=t.team_alias,e),{}):{},"resolveTeamAliasFromTeamID",0,(e,t)=>{let r=t.find(t=>t.team_id===e);return r?r.team_alias:null}])},571303,e=>{"use strict";var t=e.i(843476),r=e.i(271645),a=e.i(115504);function i({className:e="",...i}){var o,n;let s=(0,r.useId)();return o=()=>{let e=document.getAnimations().filter(e=>e instanceof CSSAnimation&&"spin"===e.animationName),t=e.find(e=>e.effect.target?.getAttribute("data-spinner-id")===s),r=e.find(e=>e.effect instanceof KeyframeEffect&&e.effect.target?.getAttribute("data-spinner-id")!==s);t&&r&&(t.currentTime=r.currentTime)},n=[s],(0,r.useLayoutEffect)(o,n),(0,t.jsxs)("svg",{"data-spinner-id":s,className:(0,a.cx)("pointer-events-none size-12 animate-spin text-current",e),fill:"none",viewBox:"0 0 24 24",...i,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"})]})}e.s(["UiLoadingSpinner",()=>i],571303)},366283,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(95779),i=e.i(444755),o=e.i(673706);let n=(0,o.makeClassName)("Callout"),s=r.default.forwardRef((e,s)=>{let{title:l,icon:c,color:u,className:d,children:m}=e,g=(0,t.__rest)(e,["title","icon","color","className","children"]);return r.default.createElement("div",Object.assign({ref:s,className:(0,i.tremorTwMerge)(n("root"),"flex flex-col overflow-hidden rounded-tremor-default text-tremor-default border-l-4 py-3 pr-3 pl-4",u?(0,i.tremorTwMerge)((0,o.getColorClassNames)(u,a.colorPalette.background).bgColor,(0,o.getColorClassNames)(u,a.colorPalette.darkBorder).borderColor,(0,o.getColorClassNames)(u,a.colorPalette.darkText).textColor,"dark:bg-opacity-10 bg-opacity-10"):(0,i.tremorTwMerge)("bg-tremor-brand-faint border-tremor-brand-emphasis text-tremor-brand-emphasis","dark:bg-dark-tremor-brand-muted/70 dark:border-dark-tremor-brand-emphasis dark:text-dark-tremor-brand-emphasis"),d)},g),r.default.createElement("div",{className:(0,i.tremorTwMerge)(n("header"),"flex items-start")},c?r.default.createElement(c,{className:(0,i.tremorTwMerge)(n("icon"),"flex-none h-5 w-5 mr-1.5")}):null,r.default.createElement("h4",{className:(0,i.tremorTwMerge)(n("title"),"font-semibold")},l)),r.default.createElement("p",{className:(0,i.tremorTwMerge)(n("body"),"overflow-y-auto",m?"mt-2":"")},m))});s.displayName="Callout",e.s(["Callout",()=>s],366283)},418371,e=>{"use strict";var t=e.i(843476),r=e.i(271645),a=e.i(916925);e.s(["ProviderLogo",0,({provider:e,className:i="w-4 h-4"})=>{let[o,n]=(0,r.useState)(!1),{logo:s}=(0,a.getProviderLogoAndName)(e);return o||!s?(0,t.jsx)("div",{className:`${i} rounded-full bg-gray-200 flex items-center justify-center text-xs`,children:e?.charAt(0)||"-"}):(0,t.jsx)("img",{src:s,alt:`${e} logo`,className:i,onError:()=>n(!0)})}])},37091,e=>{"use strict";var t=e.i(290571),r=e.i(95779),a=e.i(444755),i=e.i(673706),o=e.i(271645);let n=o.default.forwardRef((e,n)=>{let{color:s,children:l,className:c}=e,u=(0,t.__rest)(e,["color","children","className"]);return o.default.createElement("p",Object.assign({ref:n,className:(0,a.tremorTwMerge)(s?(0,i.getColorClassNames)(s,r.colorPalette.lightText).textColor:"text-tremor-content-emphasis dark:text-dark-tremor-content-emphasis",c)},u),l)});n.displayName="Subtitle",e.s(["Subtitle",()=>n],37091)},214541,e=>{"use strict";var t=e.i(271645),r=e.i(135214),a=e.i(270345);e.s(["default",0,()=>{let[e,i]=(0,t.useState)([]),{accessToken:o,userId:n,userRole:s}=(0,r.default)();return(0,t.useEffect)(()=>{(async()=>{i(await (0,a.fetchTeams)(o,n,s,null))})()},[o,n,s]),{teams:e,setTeams:i}}])},439189,435684,96226,497245,e=>{"use strict";function t(e){let t=Object.prototype.toString.call(e);return e instanceof Date||"object"==typeof e&&"[object Date]"===t?new e.constructor(+e):new Date("number"==typeof e||"[object Number]"===t||"string"==typeof e||"[object String]"===t?e:NaN)}function r(e,t){return e instanceof Date?new e.constructor(t):new Date(t)}function a(e,a){let i=t(e);return isNaN(a)?r(e,NaN):(a&&i.setDate(i.getDate()+a),i)}function i(e,a){let i=t(e);if(isNaN(a))return r(e,NaN);if(!a)return i;let o=i.getDate(),n=r(e,i.getTime());return(n.setMonth(i.getMonth()+a+1,0),o>=n.getDate())?n:(i.setFullYear(n.getFullYear(),n.getMonth(),o),i)}e.s(["toDate",()=>t],435684),e.s(["constructFrom",()=>r],96226),e.s(["addDays",()=>a],439189),e.s(["addMonths",()=>i],497245)},891547,e=>{"use strict";var t=e.i(843476),r=e.i(271645),a=e.i(199133),i=e.i(764205);e.s(["default",0,({onChange:e,value:o,className:n,accessToken:s,disabled:l})=>{let[c,u]=(0,r.useState)([]),[d,m]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{(async()=>{if(s){m(!0);try{let e=await (0,i.getGuardrailsList)(s);console.log("Guardrails response:",e),e.guardrails&&(console.log("Guardrails data:",e.guardrails),u(e.guardrails))}catch(e){console.error("Error fetching guardrails:",e)}finally{m(!1)}}})()},[s]),(0,t.jsx)("div",{children:(0,t.jsx)(a.Select,{mode:"multiple",disabled:l,placeholder:l?"Setting guardrails is a premium feature.":"Select guardrails",onChange:t=>{console.log("Selected guardrails:",t),e(t)},value:o,loading:d,className:n,allowClear:!0,options:c.map(e=>(console.log("Mapping guardrail:",e),{label:`${e.guardrail_name}`,value:e.guardrail_name})),optionFilterProp:"label",showSearch:!0,style:{width:"100%"}})})}])},921511,e=>{"use strict";var t=e.i(843476),r=e.i(271645),a=e.i(199133),i=e.i(764205);function o(e){return e.filter(e=>(e.version_status??"draft")!=="draft").map(e=>{var t;let r=e.version_number??1,a=e.version_status??"draft";return{label:`${e.policy_name} — v${r} (${a})${e.description?` — ${e.description}`:""}`,value:"production"===a?e.policy_name:e.policy_id?(t=e.policy_id,`policy_${t}`):e.policy_name}})}e.s(["default",0,({onChange:e,value:n,className:s,accessToken:l,disabled:c,onPoliciesLoaded:u})=>{let[d,m]=(0,r.useState)([]),[g,p]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{(async()=>{if(l){p(!0);try{let e=await (0,i.getPoliciesList)(l);e.policies&&(m(e.policies),u?.(e.policies))}catch(e){console.error("Error fetching policies:",e)}finally{p(!1)}}})()},[l,u]),(0,t.jsx)("div",{children:(0,t.jsx)(a.Select,{mode:"multiple",disabled:c,placeholder:c?"Setting policies is a premium feature.":"Select policies (production or published versions)",onChange:t=>{e(t)},value:n,loading:g,className:s,allowClear:!0,options:o(d),optionFilterProp:"label",showSearch:!0,style:{width:"100%"}})})},"getPolicyOptionEntries",()=>o])},637235,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let 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 372z"}},{tag:"path",attrs:{d:"M686.7 638.6L544.1 535.5V288c0-4.4-3.6-8-8-8H488c-4.4 0-8 3.6-8 8v275.4c0 2.6 1.2 5 3.3 6.5l165.4 120.6c3.6 2.6 8.6 1.8 11.2-1.7l28.6-39c2.6-3.7 1.8-8.7-1.8-11.2z"}}]},name:"clock-circle",theme:"outlined"};var i=e.i(9583),o=r.forwardRef(function(e,o){return r.createElement(i.default,(0,t.default)({},e,{ref:o,icon:a}))});e.s(["ClockCircleOutlined",0,o],637235)},646563,e=>{"use strict";var t=e.i(959013);e.s(["PlusOutlined",()=>t.default])},447566,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M872 474H286.9l350.2-304c5.6-4.9 2.2-14-5.2-14h-88.5c-3.9 0-7.6 1.4-10.5 3.9L155 487.8a31.96 31.96 0 000 48.3L535.1 866c1.5 1.3 3.3 2 5.2 2h91.5c7.4 0 10.8-9.2 5.2-14L286.9 550H872c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8z"}}]},name:"arrow-left",theme:"outlined"};var i=e.i(9583),o=r.forwardRef(function(e,o){return r.createElement(i.default,(0,t.default)({},e,{ref:o,icon:a}))});e.s(["ArrowLeftOutlined",0,o],447566)},954616,e=>{"use strict";var t=e.i(271645),r=e.i(114272),a=e.i(540143),i=e.i(915823),o=e.i(619273),n=class extends i.Subscribable{#e;#t=void 0;#r;#a;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),(0,o.shallowEqualObjects)(this.options,t)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#r,observer:this}),t?.mutationKey&&this.options.mutationKey&&(0,o.hashKey)(t.mutationKey)!==(0,o.hashKey)(this.options.mutationKey)?this.reset():this.#r?.state.status==="pending"&&this.#r.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#r?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#o(e)}getCurrentResult(){return this.#t}reset(){this.#r?.removeObserver(this),this.#r=void 0,this.#i(),this.#o()}mutate(e,t){return this.#a=t,this.#r?.removeObserver(this),this.#r=this.#e.getMutationCache().build(this.#e,this.options),this.#r.addObserver(this),this.#r.execute(e)}#i(){let e=this.#r?.state??(0,r.getDefaultState)();this.#t={...e,isPending:"pending"===e.status,isSuccess:"success"===e.status,isError:"error"===e.status,isIdle:"idle"===e.status,mutate:this.mutate,reset:this.reset}}#o(e){a.notifyManager.batch(()=>{if(this.#a&&this.hasListeners()){let t=this.#t.variables,r=this.#t.context,a={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#a.onSuccess?.(e.data,t,r,a)}catch(e){Promise.reject(e)}try{this.#a.onSettled?.(e.data,null,t,r,a)}catch(e){Promise.reject(e)}}else if(e?.type==="error"){try{this.#a.onError?.(e.error,t,r,a)}catch(e){Promise.reject(e)}try{this.#a.onSettled?.(void 0,e.error,t,r,a)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},s=e.i(912598);function l(e,r){let i=(0,s.useQueryClient)(r),[l]=t.useState(()=>new n(i,e));t.useEffect(()=>{l.setOptions(e)},[l,e]);let c=t.useSyncExternalStore(t.useCallback(e=>l.subscribe(a.notifyManager.batchCalls(e)),[l]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),u=t.useCallback((e,t)=>{l.mutate(e,t).catch(o.noop)},[l]);if(c.error&&(0,o.shouldThrowError)(l.options.throwOnError,[c.error]))throw c.error;return{...c,mutate:u,mutateAsync:c.mutate}}e.s(["useMutation",()=>l],954616)},525720,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),a=e.i(529681),i=e.i(908286),o=e.i(242064),n=e.i(246422),s=e.i(838378);let l=["wrap","nowrap","wrap-reverse"],c=["flex-start","flex-end","start","end","center","space-between","space-around","space-evenly","stretch","normal","left","right"],u=["center","start","end","flex-start","flex-end","self-start","self-end","baseline","normal","stretch"],d=function(e,t){let a,i,o;return(0,r.default)(Object.assign(Object.assign(Object.assign({},(a=!0===t.wrap?"wrap":t.wrap,{[`${e}-wrap-${a}`]:a&&l.includes(a)})),(i={},u.forEach(r=>{i[`${e}-align-${r}`]=t.align===r}),i[`${e}-align-stretch`]=!t.align&&!!t.vertical,i)),(o={},c.forEach(r=>{o[`${e}-justify-${r}`]=t.justify===r}),o)))},m=(0,n.genStyleHooks)("Flex",e=>{let{paddingXS:t,padding:r,paddingLG:a}=e,i=(0,s.mergeToken)(e,{flexGapSM:t,flexGap:r,flexGapLG:a});return[(e=>{let{componentCls:t}=e;return{[t]:{display:"flex",margin:0,padding:0,"&-vertical":{flexDirection:"column"},"&-rtl":{direction:"rtl"},"&:empty":{display:"none"}}}})(i),(e=>{let{componentCls:t}=e;return{[t]:{"&-gap-small":{gap:e.flexGapSM},"&-gap-middle":{gap:e.flexGap},"&-gap-large":{gap:e.flexGapLG}}}})(i),(e=>{let{componentCls:t}=e,r={};return l.forEach(e=>{r[`${t}-wrap-${e}`]={flexWrap:e}}),r})(i),(e=>{let{componentCls:t}=e,r={};return u.forEach(e=>{r[`${t}-align-${e}`]={alignItems:e}}),r})(i),(e=>{let{componentCls:t}=e,r={};return c.forEach(e=>{r[`${t}-justify-${e}`]={justifyContent:e}}),r})(i)]},()=>({}),{resetStyle:!1});var g=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,a=Object.getOwnPropertySymbols(e);it.indexOf(a[i])&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(r[a[i]]=e[a[i]]);return r};let p=t.default.forwardRef((e,n)=>{let{prefixCls:s,rootClassName:l,className:c,style:u,flex:p,gap:f,vertical:h=!1,component:b="div",children:v}=e,A=g(e,["prefixCls","rootClassName","className","style","flex","gap","vertical","component","children"]),{flex:y,direction:O,getPrefixCls:x}=t.default.useContext(o.ConfigContext),C=x("flex",s),[I,E,$]=m(C),_=null!=h?h:null==y?void 0:y.vertical,T=(0,r.default)(c,l,null==y?void 0:y.className,C,E,$,d(C,e),{[`${C}-rtl`]:"rtl"===O,[`${C}-gap-${f}`]:(0,i.isPresetSize)(f),[`${C}-vertical`]:_}),w=Object.assign(Object.assign({},null==y?void 0:y.style),u);return p&&(w.flex=p),f&&!(0,i.isPresetSize)(f)&&(w.gap=f),I(t.default.createElement(b,Object.assign({ref:n,className:T,style:w},(0,a.default)(A,["justify","wrap","align"])),v))});e.s(["Flex",0,p],525720)},149121,e=>{"use strict";var t=e.i(843476),r=e.i(271645),a=e.i(152990),i=e.i(682830),o=e.i(269200),n=e.i(427612),s=e.i(64848),l=e.i(942232),c=e.i(496020),u=e.i(977572);function d({data:e=[],columns:d,onRowClick:m,renderSubComponent:g,renderChildRows:p,getRowCanExpand:f,isLoading:h=!1,loadingMessage:b="🚅 Loading logs...",noDataMessage:v="No logs found",enableSorting:A=!1}){let y=!!(g||p)&&!!f,[O,x]=(0,r.useState)([]),C=(0,a.useReactTable)({data:e,columns:d,...A&&{state:{sorting:O},onSortingChange:x,enableSortingRemoval:!1},...y&&{getRowCanExpand:f},getRowId:(e,t)=>e?.request_id??String(t),getCoreRowModel:(0,i.getCoreRowModel)(),...A&&{getSortedRowModel:(0,i.getSortedRowModel)()},...y&&{getExpandedRowModel:(0,i.getExpandedRowModel)()}});return(0,t.jsx)("div",{className:"rounded-lg custom-border overflow-x-auto w-full max-w-full box-border",children:(0,t.jsxs)(o.Table,{className:"[&_td]:py-0.5 [&_th]:py-1 table-fixed w-full box-border",style:{minWidth:"400px"},children:[(0,t.jsx)(n.TableHead,{children:C.getHeaderGroups().map(e=>(0,t.jsx)(c.TableRow,{children:e.headers.map(e=>{let r=A&&e.column.getCanSort(),i=e.column.getIsSorted();return(0,t.jsx)(s.TableHeaderCell,{className:`py-1 h-8 ${r?"cursor-pointer select-none hover:bg-gray-50":""}`,onClick:r?e.column.getToggleSortingHandler():void 0,children:e.isPlaceholder?null:(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,a.flexRender)(e.column.columnDef.header,e.getContext()),r&&(0,t.jsx)("span",{className:"text-gray-400",children:"asc"===i?"↑":"desc"===i?"↓":"⇅"})]})},e.id)})},e.id))}),(0,t.jsx)(l.TableBody,{children:h?(0,t.jsx)(c.TableRow,{children:(0,t.jsx)(u.TableCell,{colSpan:d.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:b})})})}):C.getRowModel().rows.length>0?C.getRowModel().rows.map(e=>(0,t.jsxs)(r.Fragment,{children:[(0,t.jsx)(c.TableRow,{className:`h-8 ${m?"cursor-pointer hover:bg-gray-50":""}`,onClick:()=>m?.(e.original),children:e.getVisibleCells().map(e=>(0,t.jsx)(u.TableCell,{className:"py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap",children:(0,a.flexRender)(e.column.columnDef.cell,e.getContext())},e.id))}),y&&e.getIsExpanded()&&p&&p({row:e}),y&&e.getIsExpanded()&&g&&!p&&(0,t.jsx)(c.TableRow,{children:(0,t.jsx)(u.TableCell,{colSpan:e.getVisibleCells().length,className:"p-0",children:(0,t.jsx)("div",{className:"w-full max-w-full overflow-hidden box-border",children:g({row:e})})})})]},e.id)):(0,t.jsx)(c.TableRow,{children:(0,t.jsx)(u.TableCell,{colSpan:d.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:v})})})})})]})})}e.s(["DataTable",()=>d])},986888,e=>{"use strict";var t=e.i(843476),r=e.i(797305),a=e.i(135214),i=e.i(214541);e.s(["default",0,()=>{let{accessToken:e,userRole:o,userId:n,premiumUser:s}=(0,a.default)(),{teams:l}=(0,i.default)();return(0,t.jsx)(r.default,{teams:l??[],organizations:[]})}])},601236,e=>{e.v(e=>Promise.resolve().then(()=>e(764205)))}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/31ad6450b9c696ec.js b/litellm/proxy/_experimental/out/_next/static/chunks/31ad6450b9c696ec.js new file mode 100644 index 00000000000..de88919e325 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/31ad6450b9c696ec.js @@ -0,0 +1 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,367240,555436,e=>{"use strict";let t=(0,e.i(475254).default)("rotate-ccw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);e.s(["RotateCcw",()=>t],367240);var l=e.i(54943);e.s(["Search",()=>l.default],555436)},846753,e=>{"use strict";let t=(0,e.i(475254).default)("user",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);e.s(["default",()=>t])},655913,38419,78334,e=>{"use strict";var t=e.i(843476),l=e.i(115504),a=e.i(311451),i=e.i(374009),r=e.i(271645);e.s(["FilterInput",0,({placeholder:e,value:s,onChange:n,icon:o,className:d})=>{let[c,m]=(0,r.useState)(s);(0,r.useEffect)(()=>{m(s)},[s]);let u=(0,r.useMemo)(()=>(0,i.default)(e=>n(e),300),[n]);(0,r.useEffect)(()=>()=>{u.cancel()},[u]);let g=(0,r.useCallback)(e=>{let t=e.target.value;m(t),u(t)},[u]);return(0,t.jsx)(a.Input,{placeholder:e,value:c,onChange:g,prefix:o?(0,t.jsx)(o,{size:16,className:"text-gray-500"}):void 0,className:(0,l.cx)("w-64",d)})}],655913);var s=e.i(906579),n=e.i(464571);let o=(0,e.i(475254).default)("funnel",[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]]);e.s(["FiltersButton",0,({onClick:e,active:l,hasActiveFilters:a,label:i="Filters"})=>(0,t.jsx)(s.Badge,{color:"blue",dot:a,children:(0,t.jsx)(n.Button,{type:"default",onClick:e,icon:(0,t.jsx)(o,{size:16}),className:l?"bg-gray-100":"",children:i})})],38419);var d=e.i(367240);e.s(["ResetFiltersButton",0,({onClick:e,label:l="Reset Filters"})=>(0,t.jsx)(n.Button,{type:"default",onClick:e,icon:(0,t.jsx)(d.RotateCcw,{size:16}),children:l})],78334)},284614,e=>{"use strict";var t=e.i(846753);e.s(["User",()=>t.default])},906579,e=>{"use strict";e.i(247167);var t=e.i(271645),l=e.i(343794),a=e.i(361275),i=e.i(702779),r=e.i(763731),s=e.i(242064);e.i(296059);var n=e.i(915654),o=e.i(694758),d=e.i(183293),c=e.i(403541),m=e.i(246422),u=e.i(838378);let g=new o.Keyframes("antStatusProcessing",{"0%":{transform:"scale(0.8)",opacity:.5},"100%":{transform:"scale(2.4)",opacity:0}}),x=new o.Keyframes("antZoomBadgeIn",{"0%":{transform:"scale(0) translate(50%, -50%)",opacity:0},"100%":{transform:"scale(1) translate(50%, -50%)"}}),h=new o.Keyframes("antZoomBadgeOut",{"0%":{transform:"scale(1) translate(50%, -50%)"},"100%":{transform:"scale(0) translate(50%, -50%)",opacity:0}}),b=new o.Keyframes("antNoWrapperZoomBadgeIn",{"0%":{transform:"scale(0)",opacity:0},"100%":{transform:"scale(1)"}}),p=new o.Keyframes("antNoWrapperZoomBadgeOut",{"0%":{transform:"scale(1)"},"100%":{transform:"scale(0)",opacity:0}}),_=new o.Keyframes("antBadgeLoadingCircle",{"0%":{transformOrigin:"50%"},"100%":{transform:"translate(50%, -50%) rotate(360deg)",transformOrigin:"50%"}}),f=e=>{let{fontHeight:t,lineWidth:l,marginXS:a,colorBorderBg:i}=e,r=e.colorTextLightSolid,s=e.colorError,n=e.colorErrorHover;return(0,u.mergeToken)(e,{badgeFontHeight:t,badgeShadowSize:l,badgeTextColor:r,badgeColor:s,badgeColorHover:n,badgeShadowColor:i,badgeProcessingDuration:"1.2s",badgeRibbonOffset:a,badgeRibbonCornerTransform:"scaleY(0.75)",badgeRibbonCornerFilter:"brightness(75%)"})},j=e=>{let{fontSize:t,lineHeight:l,fontSizeSM:a,lineWidth:i}=e;return{indicatorZIndex:"auto",indicatorHeight:Math.round(t*l)-2*i,indicatorHeightSM:t,dotSize:a/2,textFontSize:a,textFontSizeSM:a,textFontWeight:"normal",statusSize:a/2}},v=(0,m.genStyleHooks)("Badge",e=>(e=>{let{componentCls:t,iconCls:l,antCls:a,badgeShadowSize:i,textFontSize:r,textFontSizeSM:s,statusSize:o,dotSize:m,textFontWeight:u,indicatorHeight:f,indicatorHeightSM:j,marginXS:v,calc:y}=e,C=`${a}-scroll-number`,w=(0,c.genPresetColor)(e,(e,{darkColor:l})=>({[`&${t} ${t}-color-${e}`]:{background:l,[`&:not(${t}-count)`]:{color:l},"a:hover &":{background:l}}}));return{[t]:Object.assign(Object.assign(Object.assign(Object.assign({},(0,d.resetComponent)(e)),{position:"relative",display:"inline-block",width:"fit-content",lineHeight:1,[`${t}-count`]:{display:"inline-flex",justifyContent:"center",zIndex:e.indicatorZIndex,minWidth:f,height:f,color:e.badgeTextColor,fontWeight:u,fontSize:r,lineHeight:(0,n.unit)(f),whiteSpace:"nowrap",textAlign:"center",background:e.badgeColor,borderRadius:y(f).div(2).equal(),boxShadow:`0 0 0 ${(0,n.unit)(i)} ${e.badgeShadowColor}`,transition:`background ${e.motionDurationMid}`,a:{color:e.badgeTextColor},"a:hover":{color:e.badgeTextColor},"a:hover &":{background:e.badgeColorHover}},[`${t}-count-sm`]:{minWidth:j,height:j,fontSize:s,lineHeight:(0,n.unit)(j),borderRadius:y(j).div(2).equal()},[`${t}-multiple-words`]:{padding:`0 ${(0,n.unit)(e.paddingXS)}`,bdi:{unicodeBidi:"plaintext"}},[`${t}-dot`]:{zIndex:e.indicatorZIndex,width:m,minWidth:m,height:m,background:e.badgeColor,borderRadius:"100%",boxShadow:`0 0 0 ${(0,n.unit)(i)} ${e.badgeShadowColor}`},[`${t}-count, ${t}-dot, ${C}-custom-component`]:{position:"absolute",top:0,insetInlineEnd:0,transform:"translate(50%, -50%)",transformOrigin:"100% 0%",[`&${l}-spin`]:{animationName:_,animationDuration:"1s",animationIterationCount:"infinite",animationTimingFunction:"linear"}},[`&${t}-status`]:{lineHeight:"inherit",verticalAlign:"baseline",[`${t}-status-dot`]:{position:"relative",top:-1,display:"inline-block",width:o,height:o,verticalAlign:"middle",borderRadius:"50%"},[`${t}-status-success`]:{backgroundColor:e.colorSuccess},[`${t}-status-processing`]:{overflow:"visible",color:e.colorInfo,backgroundColor:e.colorInfo,borderColor:"currentcolor","&::after":{position:"absolute",top:0,insetInlineStart:0,width:"100%",height:"100%",borderWidth:i,borderStyle:"solid",borderColor:"inherit",borderRadius:"50%",animationName:g,animationDuration:e.badgeProcessingDuration,animationIterationCount:"infinite",animationTimingFunction:"ease-in-out",content:'""'}},[`${t}-status-default`]:{backgroundColor:e.colorTextPlaceholder},[`${t}-status-error`]:{backgroundColor:e.colorError},[`${t}-status-warning`]:{backgroundColor:e.colorWarning},[`${t}-status-text`]:{marginInlineStart:v,color:e.colorText,fontSize:e.fontSize}}}),w),{[`${t}-zoom-appear, ${t}-zoom-enter`]:{animationName:x,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack,animationFillMode:"both"},[`${t}-zoom-leave`]:{animationName:h,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack,animationFillMode:"both"},[`&${t}-not-a-wrapper`]:{[`${t}-zoom-appear, ${t}-zoom-enter`]:{animationName:b,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack},[`${t}-zoom-leave`]:{animationName:p,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack},[`&:not(${t}-status)`]:{verticalAlign:"middle"},[`${C}-custom-component, ${t}-count`]:{transform:"none"},[`${C}-custom-component, ${C}`]:{position:"relative",top:"auto",display:"block",transformOrigin:"50% 50%"}},[C]:{overflow:"hidden",transition:`all ${e.motionDurationMid} ${e.motionEaseOutBack}`,[`${C}-only`]:{position:"relative",display:"inline-block",height:f,transition:`all ${e.motionDurationSlow} ${e.motionEaseOutBack}`,WebkitTransformStyle:"preserve-3d",WebkitBackfaceVisibility:"hidden",[`> p${C}-only-unit`]:{height:f,margin:0,WebkitTransformStyle:"preserve-3d",WebkitBackfaceVisibility:"hidden"}},[`${C}-symbol`]:{verticalAlign:"top"}},"&-rtl":{direction:"rtl",[`${t}-count, ${t}-dot, ${C}-custom-component`]:{transform:"translate(-50%, -50%)"}}})}})(f(e)),j),y=(0,m.genStyleHooks)(["Badge","Ribbon"],e=>(e=>{let{antCls:t,badgeFontHeight:l,marginXS:a,badgeRibbonOffset:i,calc:r}=e,s=`${t}-ribbon`,o=`${t}-ribbon-wrapper`,m=(0,c.genPresetColor)(e,(e,{darkColor:t})=>({[`&${s}-color-${e}`]:{background:t,color:t}}));return{[o]:{position:"relative"},[s]:Object.assign(Object.assign(Object.assign(Object.assign({},(0,d.resetComponent)(e)),{position:"absolute",top:a,padding:`0 ${(0,n.unit)(e.paddingXS)}`,color:e.colorPrimary,lineHeight:(0,n.unit)(l),whiteSpace:"nowrap",backgroundColor:e.colorPrimary,borderRadius:e.borderRadiusSM,[`${s}-text`]:{color:e.badgeTextColor},[`${s}-corner`]:{position:"absolute",top:"100%",width:i,height:i,color:"currentcolor",border:`${(0,n.unit)(r(i).div(2).equal())} solid`,transform:e.badgeRibbonCornerTransform,transformOrigin:"top",filter:e.badgeRibbonCornerFilter}}),m),{[`&${s}-placement-end`]:{insetInlineEnd:r(i).mul(-1).equal(),borderEndEndRadius:0,[`${s}-corner`]:{insetInlineEnd:0,borderInlineEndColor:"transparent",borderBlockEndColor:"transparent"}},[`&${s}-placement-start`]:{insetInlineStart:r(i).mul(-1).equal(),borderEndStartRadius:0,[`${s}-corner`]:{insetInlineStart:0,borderBlockEndColor:"transparent",borderInlineStartColor:"transparent"}},"&-rtl":{direction:"rtl"}})}})(f(e)),j),C=e=>{let a,{prefixCls:i,value:r,current:s,offset:n=0}=e;return n&&(a={position:"absolute",top:`${n}00%`,left:0}),t.createElement("span",{style:a,className:(0,l.default)(`${i}-only-unit`,{current:s})},r)},w=e=>{let l,a,{prefixCls:i,count:r,value:s}=e,n=Number(s),o=Math.abs(r),[d,c]=t.useState(n),[m,u]=t.useState(o),g=()=>{c(n),u(o)};if(t.useEffect(()=>{let e=setTimeout(g,1e3);return()=>clearTimeout(e)},[n]),d===n||Number.isNaN(n)||Number.isNaN(d))l=[t.createElement(C,Object.assign({},e,{key:n,current:!0}))],a={transition:"none"};else{l=[];let i=n+10,r=[];for(let e=n;e<=i;e+=1)r.push(e);let s=me%10===d);l=(s<0?r.slice(0,c+1):r.slice(c)).map((l,a)=>t.createElement(C,Object.assign({},e,{key:l,value:l%10,offset:s<0?a-c:a,current:a===c}))),a={transform:`translateY(${-function(e,t,l){let a=e,i=0;for(;(a+10)%10!==t;)a+=l,i+=l;return i}(d,n,s)}00%)`}}return t.createElement("span",{className:`${i}-only`,style:a,onTransitionEnd:g},l)};var N=function(e,t){var l={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(l[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,a=Object.getOwnPropertySymbols(e);it.indexOf(a[i])&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(l[a[i]]=e[a[i]]);return l};let T=t.forwardRef((e,a)=>{let{prefixCls:i,count:n,className:o,motionClassName:d,style:c,title:m,show:u,component:g="sup",children:x}=e,h=N(e,["prefixCls","count","className","motionClassName","style","title","show","component","children"]),{getPrefixCls:b}=t.useContext(s.ConfigContext),p=b("scroll-number",i),_=Object.assign(Object.assign({},h),{"data-show":u,style:c,className:(0,l.default)(p,o,d),title:m}),f=n;if(n&&Number(n)%1==0){let e=String(n).split("");f=t.createElement("bdi",null,e.map((l,a)=>t.createElement(w,{prefixCls:p,count:Number(n),value:l,key:e.length-a})))}return((null==c?void 0:c.borderColor)&&(_.style=Object.assign(Object.assign({},c),{boxShadow:`0 0 0 1px ${c.borderColor} inset`})),x)?(0,r.cloneElement)(x,e=>({className:(0,l.default)(`${p}-custom-component`,null==e?void 0:e.className,d)})):t.createElement(g,Object.assign({},_,{ref:a}),f)});var z=function(e,t){var l={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(l[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,a=Object.getOwnPropertySymbols(e);it.indexOf(a[i])&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(l[a[i]]=e[a[i]]);return l};let S=t.forwardRef((e,n)=>{var o,d,c,m,u;let{prefixCls:g,scrollNumberPrefixCls:x,children:h,status:b,text:p,color:_,count:f=null,overflowCount:j=99,dot:y=!1,size:C="default",title:w,offset:N,style:S,className:O,rootClassName:$,classNames:k,styles:I,showZero:F=!1}=e,M=z(e,["prefixCls","scrollNumberPrefixCls","children","status","text","color","count","overflowCount","dot","size","title","offset","style","className","rootClassName","classNames","styles","showZero"]),{getPrefixCls:E,direction:B,badge:R}=t.useContext(s.ConfigContext),D=E("badge",g),[P,A,L]=v(D),H=f>j?`${j}+`:f,U="0"===H||0===H||"0"===p||0===p,V=null===f||U&&!F,W=(null!=b||null!=_)&&V,q=null!=b||!U,G=y&&!U,K=G?"":H,Z=(0,t.useMemo)(()=>((null==K||""===K)&&(null==p||""===p)||U&&!F)&&!G,[K,U,F,G,p]),J=(0,t.useRef)(f);Z||(J.current=f);let Y=J.current,Q=(0,t.useRef)(K);Z||(Q.current=K);let X=Q.current,ee=(0,t.useRef)(G);Z||(ee.current=G);let et=(0,t.useMemo)(()=>{if(!N)return Object.assign(Object.assign({},null==R?void 0:R.style),S);let e={marginTop:N[1]};return"rtl"===B?e.left=Number.parseInt(N[0],10):e.right=-Number.parseInt(N[0],10),Object.assign(Object.assign(Object.assign({},e),null==R?void 0:R.style),S)},[B,N,S,null==R?void 0:R.style]),el=null!=w?w:"string"==typeof Y||"number"==typeof Y?Y:void 0,ea=!Z&&(0===p?F:!!p&&!0!==p),ei=ea?t.createElement("span",{className:`${D}-status-text`},p):null,er=Y&&"object"==typeof Y?(0,r.cloneElement)(Y,e=>({style:Object.assign(Object.assign({},et),e.style)})):void 0,es=(0,i.isPresetColor)(_,!1),en=(0,l.default)(null==k?void 0:k.indicator,null==(o=null==R?void 0:R.classNames)?void 0:o.indicator,{[`${D}-status-dot`]:W,[`${D}-status-${b}`]:!!b,[`${D}-color-${_}`]:es}),eo={};_&&!es&&(eo.color=_,eo.background=_);let ed=(0,l.default)(D,{[`${D}-status`]:W,[`${D}-not-a-wrapper`]:!h,[`${D}-rtl`]:"rtl"===B},O,$,null==R?void 0:R.className,null==(d=null==R?void 0:R.classNames)?void 0:d.root,null==k?void 0:k.root,A,L);if(!h&&W&&(p||q||!V)){let e=et.color;return P(t.createElement("span",Object.assign({},M,{className:ed,style:Object.assign(Object.assign(Object.assign({},null==I?void 0:I.root),null==(c=null==R?void 0:R.styles)?void 0:c.root),et)}),t.createElement("span",{className:en,style:Object.assign(Object.assign(Object.assign({},null==I?void 0:I.indicator),null==(m=null==R?void 0:R.styles)?void 0:m.indicator),eo)}),ea&&t.createElement("span",{style:{color:e},className:`${D}-status-text`},p)))}return P(t.createElement("span",Object.assign({ref:n},M,{className:ed,style:Object.assign(Object.assign({},null==(u=null==R?void 0:R.styles)?void 0:u.root),null==I?void 0:I.root)}),h,t.createElement(a.default,{visible:!Z,motionName:`${D}-zoom`,motionAppear:!1,motionDeadline:1e3},({className:e})=>{var a,i;let r=E("scroll-number",x),s=ee.current,n=(0,l.default)(null==k?void 0:k.indicator,null==(a=null==R?void 0:R.classNames)?void 0:a.indicator,{[`${D}-dot`]:s,[`${D}-count`]:!s,[`${D}-count-sm`]:"small"===C,[`${D}-multiple-words`]:!s&&X&&X.toString().length>1,[`${D}-status-${b}`]:!!b,[`${D}-color-${_}`]:es}),o=Object.assign(Object.assign(Object.assign({},null==I?void 0:I.indicator),null==(i=null==R?void 0:R.styles)?void 0:i.indicator),et);return _&&!es&&((o=o||{}).background=_),t.createElement(T,{prefixCls:r,show:!Z,motionClassName:e,className:n,count:X,title:el,style:o,key:"scrollNumber"},er)}),ei))});S.Ribbon=e=>{let{className:a,prefixCls:r,style:n,color:o,children:d,text:c,placement:m="end",rootClassName:u}=e,{getPrefixCls:g,direction:x}=t.useContext(s.ConfigContext),h=g("ribbon",r),b=`${h}-wrapper`,[p,_,f]=y(h,b),j=(0,i.isPresetColor)(o,!1),v=(0,l.default)(h,`${h}-placement-${m}`,{[`${h}-rtl`]:"rtl"===x,[`${h}-color-${o}`]:j},a),C={},w={};return o&&!j&&(C.background=o,w.color=o),p(t.createElement("div",{className:(0,l.default)(b,u,_,f)},d,t.createElement("div",{className:(0,l.default)(v,_),style:Object.assign(Object.assign({},C),n)},t.createElement("span",{className:`${h}-text`},c),t.createElement("div",{className:`${h}-corner`,style:w}))))},e.s(["Badge",0,S],906579)},738014,e=>{"use strict";var t=e.i(135214),l=e.i(764205),a=e.i(266027);let i=(0,e.i(243652).createQueryKeys)("users");e.s(["useCurrentUser",0,()=>{let{accessToken:e,userId:r,userRole:s}=(0,t.default)();return(0,a.useQuery)({queryKey:i.detail(r),queryFn:async()=>{let t=await (0,l.userInfoCall)(e,r,s,!1,null,null);return console.log(`userInfo: ${JSON.stringify(t)}`),t.user_info},enabled:!!(e&&r&&s)})}])},980187,e=>{"use strict";e.s(["createTeamAliasMap",0,e=>e?e.reduce((e,t)=>(e[t.team_id]=t.team_alias,e),{}):{},"resolveTeamAliasFromTeamID",0,(e,t)=>{let l=t.find(t=>t.team_id===e);return l?l.team_alias:null}])},846835,e=>{"use strict";var t=e.i(843476),l=e.i(655913),a=e.i(38419),i=e.i(78334),r=e.i(555436),s=e.i(284614);let n=({filters:e,showFilters:n,onToggleFilters:o,onChange:d,onReset:c})=>{let m=!!(e.org_id||e.org_alias);return(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)(l.FilterInput,{placeholder:"Search by Organization Name",value:e.org_alias,onChange:e=>d("org_alias",e),icon:r.Search,className:"w-64"}),(0,t.jsx)(a.FiltersButton,{onClick:()=>o(!n),active:n,hasActiveFilters:m}),(0,t.jsx)(i.ResetFiltersButton,{onClick:c})]}),n&&(0,t.jsx)("div",{className:"flex flex-wrap items-center gap-3 mt-3",children:(0,t.jsx)(l.FilterInput,{placeholder:"Search by Organization ID",value:e.org_id,onChange:e=>d("org_id",e),icon:s.User,className:"w-64"})})]})};var o=e.i(827252),d=e.i(871943),c=e.i(502547),m=e.i(278587),u=e.i(389083),g=e.i(994388),x=e.i(304967),h=e.i(309426),b=e.i(350967),p=e.i(752978),_=e.i(197647),f=e.i(653824),j=e.i(269200),v=e.i(942232),y=e.i(977572),C=e.i(427612),w=e.i(64848),N=e.i(496020),T=e.i(881073),z=e.i(404206),S=e.i(723731),O=e.i(599724),$=e.i(779241),k=e.i(808613),I=e.i(311451),F=e.i(212931),M=e.i(199133),E=e.i(592968),B=e.i(271645),R=e.i(500330),D=e.i(127952),P=e.i(902555),A=e.i(355619),L=e.i(75921),H=e.i(162386),U=e.i(727749),V=e.i(764205),W=e.i(785242),q=e.i(980187),G=e.i(530212),K=e.i(629569),Z=e.i(464571),J=e.i(653496),Y=e.i(898586),Q=e.i(678784),X=e.i(118366),ee=e.i(294612),et=e.i(907308),el=e.i(384767),ea=e.i(435451),ei=e.i(276173),er=e.i(916940);let es=({organizationId:e,onClose:l,accessToken:a,is_org_admin:i,is_proxy_admin:r,userModels:s,editOrg:n})=>{let[o,d]=(0,B.useState)(null),[c,m]=(0,B.useState)(!0),[h]=k.Form.useForm(),[p,_]=(0,B.useState)(!1),[f,j]=(0,B.useState)(!1),[v,y]=(0,B.useState)(!1),[C,w]=(0,B.useState)(null),[N,T]=(0,B.useState)({}),[z,S]=(0,B.useState)(!1),F=i||r,{data:E}=(0,W.useTeams)(),D=(0,B.useMemo)(()=>(0,q.createTeamAliasMap)(E),[E]),P=async()=>{try{if(m(!0),!a)return;let t=await (0,V.organizationInfoCall)(a,e);d(t)}catch(e){U.default.fromBackend("Failed to load organization information"),console.error("Error fetching organization info:",e)}finally{m(!1)}};(0,B.useEffect)(()=>{P()},[e,a]);let A=async t=>{try{if(null==a)return;let l={user_email:t.user_email,user_id:t.user_id,role:t.role};await (0,V.organizationMemberAddCall)(a,e,l),U.default.success("Organization member added successfully"),j(!1),h.resetFields(),P()}catch(e){U.default.fromBackend("Failed to add organization member"),console.error("Error adding organization member:",e)}},es=async t=>{try{if(!a)return;let l={user_email:t.user_email,user_id:t.user_id,role:t.role};await (0,V.organizationMemberUpdateCall)(a,e,l),U.default.success("Organization member updated successfully"),y(!1),h.resetFields(),P()}catch(e){U.default.fromBackend("Failed to update organization member"),console.error("Error updating organization member:",e)}},en=async t=>{try{if(!a)return;await (0,V.organizationMemberDeleteCall)(a,e,t.user_id),U.default.success("Organization member deleted successfully"),y(!1),h.resetFields(),P()}catch(e){U.default.fromBackend("Failed to delete organization member"),console.error("Error deleting organization member:",e)}},eo=async t=>{try{if(!a)return;S(!0);let l={organization_id:e,organization_alias:t.organization_alias,models:t.models,litellm_budget_table:{tpm_limit:t.tpm_limit,rpm_limit:t.rpm_limit,max_budget:t.max_budget,budget_duration:t.budget_duration},metadata:t.metadata?JSON.parse(t.metadata):null};if((void 0!==t.vector_stores||void 0!==t.mcp_servers_and_groups)&&(l.object_permission={...o?.object_permission,vector_stores:t.vector_stores||[]},void 0!==t.mcp_servers_and_groups)){let{servers:e,accessGroups:a}=t.mcp_servers_and_groups||{servers:[],accessGroups:[]};e&&e.length>0&&(l.object_permission.mcp_servers=e),a&&a.length>0&&(l.object_permission.mcp_access_groups=a)}await (0,V.organizationUpdateCall)(a,l),U.default.success("Organization settings updated successfully"),_(!1),P()}catch(e){U.default.fromBackend("Failed to update organization settings"),console.error("Error updating organization:",e)}finally{S(!1)}};if(c)return(0,t.jsx)("div",{className:"p-4",children:"Loading..."});if(!o)return(0,t.jsx)("div",{className:"p-4",children:"Organization not found"});let ed=async(e,t)=>{await (0,R.copyToClipboard)(e)&&(T(e=>({...e,[t]:!0})),setTimeout(()=>{T(e=>({...e,[t]:!1}))},2e3))},ec=[{title:"Spend (USD)",key:"spend",render:(e,l)=>{let a=null!=l.user_id?(o.members||[]).find(e=>e.user_id===l.user_id):void 0;return(0,t.jsxs)(Y.Typography.Text,{children:["$",(0,R.formatNumberWithCommas)(a?.spend??0,4)]})}},{title:"Created At",key:"created_at",render:(e,l)=>{let a=null!=l.user_id?(o.members||[]).find(e=>e.user_id===l.user_id):void 0;return(0,t.jsx)(Y.Typography.Text,{children:a?.created_at?new Date(a.created_at).toLocaleString():"-"})}}];return(0,t.jsxs)("div",{className:"w-full h-screen p-4 bg-white",children:[(0,t.jsx)("div",{className:"flex justify-between items-center mb-6",children:(0,t.jsxs)("div",{children:[(0,t.jsx)(g.Button,{icon:G.ArrowLeftIcon,onClick:l,variant:"light",className:"mb-4",children:"Back to Organizations"}),(0,t.jsx)(K.Title,{children:o.organization_alias}),(0,t.jsxs)("div",{className:"flex items-center cursor-pointer",children:[(0,t.jsx)(O.Text,{className:"text-gray-500 font-mono",children:o.organization_id}),(0,t.jsx)(Z.Button,{type:"text",size:"small",icon:N["org-id"]?(0,t.jsx)(Q.CheckIcon,{size:12}):(0,t.jsx)(X.CopyIcon,{size:12}),onClick:()=>ed(o.organization_id,"org-id"),className:`left-2 z-10 transition-all duration-200 ${N["org-id"]?"text-green-600 bg-green-50 border-green-200":"text-gray-500 hover:text-gray-700 hover:bg-gray-100"}`})]})]})}),(0,t.jsx)(J.Tabs,{defaultActiveKey:n?"settings":"overview",className:"mb-4",items:[{key:"overview",label:"Overview",children:(0,t.jsxs)(b.Grid,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,t.jsxs)(x.Card,{children:[(0,t.jsx)(O.Text,{children:"Organization Details"}),(0,t.jsxs)("div",{className:"mt-2",children:[(0,t.jsxs)(O.Text,{children:["Created: ",new Date(o.created_at).toLocaleDateString()]}),(0,t.jsxs)(O.Text,{children:["Updated: ",new Date(o.updated_at).toLocaleDateString()]}),(0,t.jsxs)(O.Text,{children:["Created By: ",o.created_by]})]})]}),(0,t.jsxs)(x.Card,{children:[(0,t.jsx)(O.Text,{children:"Budget Status"}),(0,t.jsxs)("div",{className:"mt-2",children:[(0,t.jsxs)(K.Title,{children:["$",(0,R.formatNumberWithCommas)(o.spend,4)]}),(0,t.jsxs)(O.Text,{children:["of"," ",null===o.litellm_budget_table.max_budget?"Unlimited":`$${(0,R.formatNumberWithCommas)(o.litellm_budget_table.max_budget,4)}`]}),o.litellm_budget_table.budget_duration&&(0,t.jsxs)(O.Text,{className:"text-gray-500",children:["Reset: ",o.litellm_budget_table.budget_duration]})]})]}),(0,t.jsxs)(x.Card,{children:[(0,t.jsx)(O.Text,{children:"Rate Limits"}),(0,t.jsxs)("div",{className:"mt-2",children:[(0,t.jsxs)(O.Text,{children:["TPM: ",o.litellm_budget_table.tpm_limit||"Unlimited"]}),(0,t.jsxs)(O.Text,{children:["RPM: ",o.litellm_budget_table.rpm_limit||"Unlimited"]}),o.litellm_budget_table.max_parallel_requests&&(0,t.jsxs)(O.Text,{children:["Max Parallel Requests: ",o.litellm_budget_table.max_parallel_requests]})]})]}),(0,t.jsxs)(x.Card,{children:[(0,t.jsx)(O.Text,{children:"Models"}),(0,t.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:0===o.models.length?(0,t.jsx)(u.Badge,{color:"red",children:"All proxy models"}):o.models.map((e,l)=>(0,t.jsx)(u.Badge,{color:"red",children:e},l))})]}),(0,t.jsxs)(x.Card,{children:[(0,t.jsx)(O.Text,{children:"Teams"}),(0,t.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:o.teams?.map((e,l)=>(0,t.jsx)(u.Badge,{color:"red",children:D[e.team_id]||e.team_id},l))})]}),(0,t.jsx)(el.default,{objectPermission:o.object_permission,variant:"card",accessToken:a})]})},{key:"members",label:"Members",children:(0,t.jsx)("div",{className:"space-y-4",children:(0,t.jsx)(ee.default,{members:(o.members||[]).map(e=>({role:e.user_role||"",user_id:e.user_id,user_email:e.user_email})),canEdit:F,onEdit:e=>{w(e),y(!0)},onDelete:e=>en(e),onAddMember:()=>j(!0),roleColumnTitle:"Organization Role",extraColumns:ec,emptyText:"No members found"})})},{key:"settings",label:"Settings",children:(0,t.jsxs)(x.Card,{className:"overflow-y-auto max-h-[65vh]",children:[(0,t.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,t.jsx)(K.Title,{children:"Organization Settings"}),F&&!p&&(0,t.jsx)(g.Button,{onClick:()=>_(!0),children:"Edit Settings"})]}),p?(0,t.jsxs)(k.Form,{form:h,onFinish:eo,initialValues:{organization_alias:o.organization_alias,models:o.models,tpm_limit:o.litellm_budget_table.tpm_limit,rpm_limit:o.litellm_budget_table.rpm_limit,max_budget:o.litellm_budget_table.max_budget,budget_duration:o.litellm_budget_table.budget_duration,metadata:o.metadata?JSON.stringify(o.metadata,null,2):"",vector_stores:o.object_permission?.vector_stores||[],mcp_servers_and_groups:{servers:o.object_permission?.mcp_servers||[],accessGroups:o.object_permission?.mcp_access_groups||[]}},layout:"vertical",children:[(0,t.jsx)(k.Form.Item,{label:"Organization Name",name:"organization_alias",rules:[{required:!0,message:"Please input an organization name"}],children:(0,t.jsx)($.TextInput,{})}),(0,t.jsx)(k.Form.Item,{label:"Models",name:"models",children:(0,t.jsx)(H.ModelSelect,{value:h.getFieldValue("models"),onChange:e=>h.setFieldValue("models",e),context:"organization",options:{includeSpecialOptions:!0,showAllProxyModelsOverride:!0}})}),(0,t.jsx)(k.Form.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,t.jsx)(ea.default,{step:.01,precision:2,style:{width:"100%"}})}),(0,t.jsx)(k.Form.Item,{label:"Reset Budget",name:"budget_duration",children:(0,t.jsxs)(M.Select,{placeholder:"n/a",children:[(0,t.jsx)(M.Select.Option,{value:"24h",children:"daily"}),(0,t.jsx)(M.Select.Option,{value:"7d",children:"weekly"}),(0,t.jsx)(M.Select.Option,{value:"30d",children:"monthly"})]})}),(0,t.jsx)(k.Form.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,t.jsx)(ea.default,{step:1,style:{width:"100%"}})}),(0,t.jsx)(k.Form.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,t.jsx)(ea.default,{step:1,style:{width:"100%"}})}),(0,t.jsx)(k.Form.Item,{label:"Vector Stores",name:"vector_stores",children:(0,t.jsx)(er.default,{onChange:e=>h.setFieldValue("vector_stores",e),value:h.getFieldValue("vector_stores"),accessToken:a||"",placeholder:"Select vector stores"})}),(0,t.jsx)(k.Form.Item,{label:"MCP Servers & Access Groups",name:"mcp_servers_and_groups",children:(0,t.jsx)(L.default,{onChange:e=>h.setFieldValue("mcp_servers_and_groups",e),value:h.getFieldValue("mcp_servers_and_groups"),accessToken:a||"",placeholder:"Select MCP servers and access groups"})}),(0,t.jsx)(k.Form.Item,{label:"Metadata",name:"metadata",children:(0,t.jsx)(I.Input.TextArea,{rows:4})}),(0,t.jsx)("div",{className:"sticky z-10 bg-white p-4 border-t border-gray-200 bottom-[-1.5rem] inset-x-[-1.5rem]",children:(0,t.jsxs)("div",{className:"flex justify-end items-center gap-2",children:[(0,t.jsx)(g.Button,{variant:"secondary",onClick:()=>_(!1),disabled:z,children:"Cancel"}),(0,t.jsx)(g.Button,{type:"submit",loading:z,children:"Save Changes"})]})})]}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(O.Text,{className:"font-medium",children:"Organization Name"}),(0,t.jsx)("div",{children:o.organization_alias})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(O.Text,{className:"font-medium",children:"Organization ID"}),(0,t.jsx)("div",{className:"font-mono",children:o.organization_id})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(O.Text,{className:"font-medium",children:"Created At"}),(0,t.jsx)("div",{children:new Date(o.created_at).toLocaleString()})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(O.Text,{className:"font-medium",children:"Models"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:o.models.map((e,l)=>(0,t.jsx)(u.Badge,{color:"red",children:e},l))})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(O.Text,{className:"font-medium",children:"Rate Limits"}),(0,t.jsxs)("div",{children:["TPM: ",o.litellm_budget_table.tpm_limit||"Unlimited"]}),(0,t.jsxs)("div",{children:["RPM: ",o.litellm_budget_table.rpm_limit||"Unlimited"]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(O.Text,{className:"font-medium",children:"Budget"}),(0,t.jsxs)("div",{children:["Max:"," ",null!==o.litellm_budget_table.max_budget?`$${(0,R.formatNumberWithCommas)(o.litellm_budget_table.max_budget,4)}`:"No Limit"]}),(0,t.jsxs)("div",{children:["Reset: ",o.litellm_budget_table.budget_duration||"Never"]})]}),(0,t.jsx)(el.default,{objectPermission:o.object_permission,variant:"inline",className:"pt-4 border-t border-gray-200",accessToken:a})]})]})}]}),(0,t.jsx)(et.default,{isVisible:f,onCancel:()=>j(!1),onSubmit:A,accessToken:a,title:"Add Organization Member",roles:[{label:"org_admin",value:"org_admin",description:"Can add and remove members, and change their roles."},{label:"internal_user",value:"internal_user",description:"Can view/create keys for themselves within organization."},{label:"internal_user_viewer",value:"internal_user_viewer",description:"Can only view their keys within organization."}],defaultRole:"internal_user"}),(0,t.jsx)(ei.default,{visible:v,onCancel:()=>y(!1),onSubmit:es,initialData:C,mode:"edit",config:{title:"Edit Member",showEmail:!0,showUserId:!0,roleOptions:[{label:"Org Admin",value:"org_admin"},{label:"Internal User",value:"internal_user"},{label:"Internal User Viewer",value:"internal_user_viewer"}]}})]})},en=async(e,t,l=null,a=null)=>{t(await (0,V.organizationListCall)(e,l,a))};e.s(["default",0,({organizations:e,userRole:l,userModels:a,accessToken:i,lastRefreshed:r,handleRefreshClick:s,currentOrg:W,guardrailsList:q=[],setOrganizations:G,premiumUser:K})=>{let[Z,J]=(0,B.useState)(null),[Y,Q]=(0,B.useState)(!1),[X,ee]=(0,B.useState)(!1),[et,el]=(0,B.useState)(null),[ei,eo]=(0,B.useState)(!1),[ed,ec]=(0,B.useState)(!1),[em]=k.Form.useForm(),[eu,eg]=(0,B.useState)({}),[ex,eh]=(0,B.useState)(!1),[eb,ep]=(0,B.useState)({org_id:"",org_alias:"",sort_by:"created_at",sort_order:"desc"}),e_=async()=>{if(et&&i)try{eo(!0),await (0,V.organizationDeleteCall)(i,et),U.default.success("Organization deleted successfully"),ee(!1),el(null),await en(i,G,eb.org_id||null,eb.org_alias||null)}catch(e){console.error("Error deleting organization:",e)}finally{eo(!1)}},ef=async e=>{try{if(!i)return;console.log(`values in organizations new create call: ${JSON.stringify(e)}`),(e.allowed_vector_store_ids&&e.allowed_vector_store_ids.length>0||e.allowed_mcp_servers_and_groups&&(e.allowed_mcp_servers_and_groups.servers?.length>0||e.allowed_mcp_servers_and_groups.accessGroups?.length>0))&&(e.object_permission={},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&&(e.allowed_mcp_servers_and_groups.servers?.length>0&&(e.object_permission.mcp_servers=e.allowed_mcp_servers_and_groups.servers),e.allowed_mcp_servers_and_groups.accessGroups?.length>0&&(e.object_permission.mcp_access_groups=e.allowed_mcp_servers_and_groups.accessGroups),delete e.allowed_mcp_servers_and_groups)),await (0,V.organizationCreateCall)(i,e),U.default.success("Organization created successfully"),ec(!1),em.resetFields(),en(i,G,eb.org_id||null,eb.org_alias||null)}catch(e){console.error("Error creating organization:",e)}};return K?(0,t.jsxs)("div",{className:"w-full mx-4 h-[75vh]",children:[(0,t.jsx)(b.Grid,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:(0,t.jsxs)(h.Col,{numColSpan:1,className:"flex flex-col gap-2",children:[("Admin"===l||"Org Admin"===l)&&(0,t.jsx)(g.Button,{className:"w-fit",onClick:()=>ec(!0),children:"+ Create New Organization"}),Z?(0,t.jsx)(es,{organizationId:Z,onClose:()=>{J(null),Q(!1)},accessToken:i,is_org_admin:!0,is_proxy_admin:"Admin"===l,userModels:a,editOrg:Y}):(0,t.jsxs)(f.TabGroup,{className:"gap-2 h-[75vh] w-full",children:[(0,t.jsxs)(T.TabList,{className:"flex justify-between mt-2 w-full items-center",children:[(0,t.jsx)("div",{className:"flex",children:(0,t.jsx)(_.Tab,{children:"Your Organizations"})}),(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[r&&(0,t.jsxs)(O.Text,{children:["Last Refreshed: ",r]}),(0,t.jsx)(p.Icon,{icon:m.RefreshIcon,variant:"shadow",size:"xs",className:"self-center",onClick:s})]})]}),(0,t.jsx)(S.TabPanels,{children:(0,t.jsxs)(z.TabPanel,{children:[(0,t.jsx)(O.Text,{children:"Click on “Organization ID” to view organization details."}),(0,t.jsx)(b.Grid,{numItems:1,className:"gap-2 pt-2 pb-2 h-[75vh] w-full mt-2",children:(0,t.jsx)(h.Col,{numColSpan:1,children:(0,t.jsxs)(x.Card,{className:"w-full mx-auto flex-auto overflow-hidden overflow-y-auto max-h-[50vh]",children:[(0,t.jsx)("div",{className:"border-b px-6 py-4",children:(0,t.jsx)("div",{className:"flex flex-col space-y-4",children:(0,t.jsx)(n,{filters:eb,showFilters:ex,onToggleFilters:eh,onChange:(e,t)=>{let l={...eb,[e]:t};ep(l),i&&(0,V.organizationListCall)(i,l.org_id||null,l.org_alias||null).then(e=>{e&&G(e)}).catch(e=>{console.error("Error fetching organizations:",e)})},onReset:()=>{ep({org_id:"",org_alias:"",sort_by:"created_at",sort_order:"desc"}),i&&(0,V.organizationListCall)(i,null,null).then(e=>{e&&G(e)}).catch(e=>{console.error("Error fetching organizations:",e)})}})})}),(0,t.jsxs)(j.Table,{children:[(0,t.jsx)(C.TableHead,{children:(0,t.jsxs)(N.TableRow,{children:[(0,t.jsx)(w.TableHeaderCell,{children:"Organization ID"}),(0,t.jsx)(w.TableHeaderCell,{children:"Organization Name"}),(0,t.jsx)(w.TableHeaderCell,{children:"Created"}),(0,t.jsx)(w.TableHeaderCell,{children:"Spend (USD)"}),(0,t.jsx)(w.TableHeaderCell,{children:"Budget (USD)"}),(0,t.jsx)(w.TableHeaderCell,{children:"Models"}),(0,t.jsx)(w.TableHeaderCell,{children:"TPM / RPM Limits"}),(0,t.jsx)(w.TableHeaderCell,{children:"Info"}),(0,t.jsx)(w.TableHeaderCell,{children:"Actions"})]})}),(0,t.jsx)(v.TableBody,{children:e&&e.length>0?e.sort((e,t)=>new Date(t.created_at).getTime()-new Date(e.created_at).getTime()).map(e=>(0,t.jsxs)(N.TableRow,{children:[(0,t.jsx)(y.TableCell,{children:(0,t.jsx)("div",{className:"overflow-hidden",children:(0,t.jsx)(E.Tooltip,{title:e.organization_id,children:(0,t.jsxs)(g.Button,{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:()=>J(e.organization_id),children:[e.organization_id?.slice(0,7),"..."]})})})}),(0,t.jsx)(y.TableCell,{children:e.organization_alias}),(0,t.jsx)(y.TableCell,{children:e.created_at?new Date(e.created_at).toLocaleDateString():"N/A"}),(0,t.jsx)(y.TableCell,{children:(0,R.formatNumberWithCommas)(e.spend,4)}),(0,t.jsx)(y.TableCell,{children:e.litellm_budget_table?.max_budget!==null&&e.litellm_budget_table?.max_budget!==void 0?e.litellm_budget_table?.max_budget:"No limit"}),(0,t.jsx)(y.TableCell,{style:{maxWidth:"8-x",whiteSpace:"pre-wrap",overflow:"hidden"},className:e.models.length>3?"px-0":"",children:(0,t.jsx)("div",{className:"flex flex-col",children:Array.isArray(e.models)?(0,t.jsx)("div",{className:"flex flex-col",children:0===e.models.length?(0,t.jsx)(u.Badge,{size:"xs",className:"mb-1",color:"red",children:(0,t.jsx)(O.Text,{children:"All Proxy Models"})}):(0,t.jsx)(t.Fragment,{children:(0,t.jsxs)("div",{className:"flex items-start",children:[e.models.length>3&&(0,t.jsx)("div",{children:(0,t.jsx)(p.Icon,{icon:eu[e.organization_id||""]?d.ChevronDownIcon:c.ChevronRightIcon,className:"cursor-pointer",size:"xs",onClick:()=>{eg(t=>({...t,[e.organization_id||""]:!t[e.organization_id||""]}))}})}),(0,t.jsxs)("div",{className:"flex flex-wrap gap-1",children:[e.models.slice(0,3).map((e,l)=>"all-proxy-models"===e?(0,t.jsx)(u.Badge,{size:"xs",color:"red",children:(0,t.jsx)(O.Text,{children:"All Proxy Models"})},l):(0,t.jsx)(u.Badge,{size:"xs",color:"blue",children:(0,t.jsx)(O.Text,{children:e.length>30?`${(0,A.getModelDisplayName)(e).slice(0,30)}...`:(0,A.getModelDisplayName)(e)})},l)),e.models.length>3&&!eu[e.organization_id||""]&&(0,t.jsx)(u.Badge,{size:"xs",color:"gray",className:"cursor-pointer",children:(0,t.jsxs)(O.Text,{children:["+",e.models.length-3," ",e.models.length-3==1?"more model":"more models"]})}),eu[e.organization_id||""]&&(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:e.models.slice(3).map((e,l)=>"all-proxy-models"===e?(0,t.jsx)(u.Badge,{size:"xs",color:"red",children:(0,t.jsx)(O.Text,{children:"All Proxy Models"})},l+3):(0,t.jsx)(u.Badge,{size:"xs",color:"blue",children:(0,t.jsx)(O.Text,{children:e.length>30?`${(0,A.getModelDisplayName)(e).slice(0,30)}...`:(0,A.getModelDisplayName)(e)})},l+3))})]})]})})}):null})}),(0,t.jsx)(y.TableCell,{children:(0,t.jsxs)(O.Text,{children:["TPM:"," ",e.litellm_budget_table?.tpm_limit?e.litellm_budget_table?.tpm_limit:"Unlimited",(0,t.jsx)("br",{}),"RPM:"," ",e.litellm_budget_table?.rpm_limit?e.litellm_budget_table?.rpm_limit:"Unlimited"]})}),(0,t.jsx)(y.TableCell,{children:(0,t.jsxs)(O.Text,{children:[e.members?.length||0," Members"]})}),(0,t.jsx)(y.TableCell,{children:"Admin"===l&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(P.default,{variant:"Edit",tooltipText:"Edit organization",onClick:()=>{J(e.organization_id),Q(!0)}}),(0,t.jsx)(P.default,{variant:"Delete",tooltipText:"Delete organization",onClick:()=>{var t;(t=e.organization_id)&&(el(t),ee(!0))}})]})})]},e.organization_id)):null})]})]})})})]})})]})]})}),(0,t.jsx)(F.Modal,{title:"Create Organization",visible:ed,width:800,footer:null,onCancel:()=>{ec(!1),em.resetFields()},children:(0,t.jsxs)(k.Form,{form:em,onFinish:ef,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,t.jsx)(k.Form.Item,{label:"Organization Name",name:"organization_alias",rules:[{required:!0,message:"Please input an organization name"}],children:(0,t.jsx)($.TextInput,{placeholder:""})}),(0,t.jsx)(k.Form.Item,{label:"Models",name:"models",children:(0,t.jsx)(H.ModelSelect,{options:{showAllProxyModelsOverride:!0,includeSpecialOptions:!0},value:em.getFieldValue("models"),onChange:e=>em.setFieldValue("models",e),context:"organization"})}),(0,t.jsx)(k.Form.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,t.jsx)(ea.default,{step:.01,precision:2,width:200})}),(0,t.jsx)(k.Form.Item,{label:"Reset Budget",name:"budget_duration",children:(0,t.jsxs)(M.Select,{defaultValue:null,placeholder:"n/a",children:[(0,t.jsx)(M.Select.Option,{value:"24h",children:"daily"}),(0,t.jsx)(M.Select.Option,{value:"7d",children:"weekly"}),(0,t.jsx)(M.Select.Option,{value:"30d",children:"monthly"})]})}),(0,t.jsx)(k.Form.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,t.jsx)(ea.default,{step:1,width:400})}),(0,t.jsx)(k.Form.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,t.jsx)(ea.default,{step:1,width:400})}),(0,t.jsx)(k.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Vector Stores"," ",(0,t.jsx)(E.Tooltip,{title:"Select which vector stores this organization can access by default. Leave empty for access to all vector stores",children:(0,t.jsx)(o.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_vector_store_ids",className:"mt-4",help:"Select vector stores this organization can access. Leave empty for access to all vector stores",children:(0,t.jsx)(er.default,{onChange:e=>em.setFieldValue("allowed_vector_store_ids",e),value:em.getFieldValue("allowed_vector_store_ids"),accessToken:i||"",placeholder:"Select vector stores (optional)"})}),(0,t.jsx)(k.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed MCP Servers"," ",(0,t.jsx)(E.Tooltip,{title:"Select which MCP servers and access groups this organization can access by default.",children:(0,t.jsx)(o.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_mcp_servers_and_groups",className:"mt-4",help:"Select MCP servers and access groups this organization can access.",children:(0,t.jsx)(L.default,{onChange:e=>em.setFieldValue("allowed_mcp_servers_and_groups",e),value:em.getFieldValue("allowed_mcp_servers_and_groups"),accessToken:i||"",placeholder:"Select MCP servers and access groups (optional)"})}),(0,t.jsx)(k.Form.Item,{label:"Metadata",name:"metadata",children:(0,t.jsx)(I.Input.TextArea,{rows:4})}),(0,t.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,t.jsx)(g.Button,{type:"submit",children:"Create Organization"})})]})}),(0,t.jsx)(D.default,{isOpen:X,title:"Delete Organization?",message:"Are you sure you want to delete this organization? This action cannot be undone.",resourceInformationTitle:"Organization Information",resourceInformation:[{label:"Organization ID",value:et,code:!0}],onCancel:()=>{ee(!1),el(null)},onOk:e_,confirmLoading:ei})]}):(0,t.jsx)("div",{children:(0,t.jsxs)(O.Text,{children:["This is a LiteLLM Enterprise feature, and requires a valid key to use. Get a trial key"," ",(0,t.jsx)("a",{href:"https://www.litellm.ai/#pricing",target:"_blank",rel:"noopener noreferrer",children:"here"}),"."]})})},"fetchOrganizations",0,en],846835)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/31e02a31dea7d5d2.js b/litellm/proxy/_experimental/out/_next/static/chunks/31e02a31dea7d5d2.js new file mode 100644 index 00000000000..d392a68c996 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/31e02a31dea7d5d2.js @@ -0,0 +1,8 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,135214,708347,e=>{"use strict";var t=e.i(764205),r=e.i(268004),i=e.i(161281),s=e.i(321836),n=e.i(618566),a=e.i(271645);let l=["Admin","Admin Viewer","proxy_admin","proxy_admin_viewer","org_admin"],o=(e,t)=>null!=e&&e.some(e=>e.user_id===t&&"admin"===e.role),u=e=>{if(!e)return"Undefined Role";switch(e.toLowerCase()){case"app_owner":case"demo_app_owner":return"App Owner";case"app_admin":case"proxy_admin":return"Admin";case"proxy_admin_viewer":return"Admin Viewer";case"org_admin":return"Org Admin";case"internal_user":return"Internal User";case"internal_user_viewer":case"internal_viewer":return"Internal Viewer";case"app_user":return"App User";default:return"Unknown Role"}};e.s(["all_admin_roles",0,l,"formatUserRole",0,u,"internalUserRoles",0,["Internal User","Internal Viewer"],"isAdminRole",0,e=>l.includes(e),"isProxyAdminRole",0,e=>"proxy_admin"===e||"Admin"===e,"isUserTeamAdminForAnyTeam",0,(e,t)=>null!=e&&e.some(e=>o(e.members_with_roles,t)),"isUserTeamAdminForSingleTeam",0,o,"rolesWithWriteAccess",0,["Internal User","Admin","proxy_admin"]],708347);var c=e.i(612256);e.s(["default",0,()=>{let e=(0,n.useRouter)(),{data:l,isLoading:o}=(0,c.useUIConfig)(),d="u">typeof document?(0,r.getCookie)("token"):null,h=(0,a.useMemo)(()=>(0,i.decodeToken)(d),[d]),f=(0,a.useMemo)(()=>(0,i.checkTokenValidity)(d),[d])&&!l?.admin_ui_disabled,p=(0,a.useCallback)(()=>{(0,s.storeReturnUrl)();let r=`${(0,t.getProxyBaseUrl)()}/ui/login`,i=(0,s.buildLoginUrlWithReturn)(r);e.replace(i)},[e]);return(0,a.useEffect)(()=>{!o&&(f||(d&&(0,r.clearTokenCookies)(),p()))},[o,f,d,p]),{isLoading:o,isAuthorized:f,token:f?d:null,accessToken:h?.key??null,userId:h?.user_id??null,userEmail:h?.user_email??null,userRole:u(h?.user_role),premiumUser:h?.premium_user??null,disabledPersonalKeyCreation:h?.disabled_non_admin_personal_key_creation??null,showSSOBanner:h?.login_method==="username_password"}}],135214)},95779,e=>{"use strict";var t=e.i(480731);let r={canvasBackground:50,lightBackground:100,background:500,darkBackground:600,darkestBackground:800,lightBorder:200,border:500,darkBorder:700,lightRing:200,ring:300,iconRing:500,lightText:400,text:500,iconText:600,darkText:700,darkestText:900,icon:500},i=[t.BaseColors.Blue,t.BaseColors.Cyan,t.BaseColors.Sky,t.BaseColors.Indigo,t.BaseColors.Violet,t.BaseColors.Purple,t.BaseColors.Fuchsia,t.BaseColors.Slate,t.BaseColors.Gray,t.BaseColors.Zinc,t.BaseColors.Neutral,t.BaseColors.Stone,t.BaseColors.Red,t.BaseColors.Orange,t.BaseColors.Amber,t.BaseColors.Yellow,t.BaseColors.Lime,t.BaseColors.Green,t.BaseColors.Emerald,t.BaseColors.Teal,t.BaseColors.Pink,t.BaseColors.Rose];e.s(["colorPalette",()=>r,"themeColorRange",()=>i])},618566,(e,t,r)=>{t.exports=e.r(976562)},947293,e=>{"use strict";class t extends Error{}function r(e,r){let i;if("string"!=typeof e)throw new t("Invalid token specified: must be a string");r||(r={});let s=+(!0!==r.header),n=e.split(".")[s];if("string"!=typeof n)throw new t(`Invalid token specified: missing part #${s+1}`);try{i=function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw Error("base64 string is not of the correct length")}try{var r;return r=t,decodeURIComponent(atob(r).replace(/(.)/g,(e,t)=>{let r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}catch(e){return atob(t)}}(n)}catch(e){throw new t(`Invalid token specified: invalid base64 for part #${s+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new t(`Invalid token specified: invalid json for part #${s+1} (${e.message})`)}}t.prototype.name="InvalidTokenError",e.s(["jwtDecode",()=>r])},266027,869230,469637,243652,e=>{"use strict";let t;var r=e.i(175555),i=e.i(540143),s=e.i(286491),n=e.i(915823),a=e.i(793803),l=e.i(619273),o=e.i(180166),u=class extends n.Subscribable{constructor(e,t){super(),this.options=t,this.#e=e,this.#t=null,this.#r=(0,a.pendingThenable)(),this.bindMethods(),this.setOptions(t)}#e;#i=void 0;#s=void 0;#n=void 0;#a;#l;#r;#t;#o;#u;#c;#d;#h;#f;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){1===this.listeners.size&&(this.#i.addObserver(this),c(this.#i,this.options)?this.#m():this.updateResult(),this.#g())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return d(this.#i,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return d(this.#i,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#y(),this.#i.removeObserver(this)}setOptions(e){let t=this.options,r=this.#i;if(this.options=this.#e.defaultQueryOptions(e),void 0!==this.options.enabled&&"boolean"!=typeof this.options.enabled&&"function"!=typeof this.options.enabled&&"boolean"!=typeof(0,l.resolveEnabled)(this.options.enabled,this.#i))throw Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#v(),this.#i.setOptions(this.options),t._defaulted&&!(0,l.shallowEqualObjects)(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#i,observer:this});let i=this.hasListeners();i&&h(this.#i,r,this.options,t)&&this.#m(),this.updateResult(),i&&(this.#i!==r||(0,l.resolveEnabled)(this.options.enabled,this.#i)!==(0,l.resolveEnabled)(t.enabled,this.#i)||(0,l.resolveStaleTime)(this.options.staleTime,this.#i)!==(0,l.resolveStaleTime)(t.staleTime,this.#i))&&this.#R();let s=this.#C();i&&(this.#i!==r||(0,l.resolveEnabled)(this.options.enabled,this.#i)!==(0,l.resolveEnabled)(t.enabled,this.#i)||s!==this.#f)&&this.#w(s)}getOptimisticResult(e){var t,r;let i=this.#e.getQueryCache().build(this.#e,e),s=this.createResult(i,e);return t=this,r=s,(0,l.shallowEqualObjects)(t.getCurrentResult(),r)||(this.#n=s,this.#l=this.options,this.#a=this.#i.state),s}getCurrentResult(){return this.#n}trackResult(e,t){return new Proxy(e,{get:(e,r)=>(this.trackProp(r),t?.(r),"promise"===r&&(this.trackProp("data"),this.options.experimental_prefetchInRender||"pending"!==this.#r.status||this.#r.reject(Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(e,r))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#i}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),r=this.#e.getQueryCache().build(this.#e,t);return r.fetch().then(()=>this.createResult(r,t))}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#n))}#m(e){this.#v();let t=this.#i.fetch(this.options,e);return e?.throwOnError||(t=t.catch(l.noop)),t}#R(){this.#b();let e=(0,l.resolveStaleTime)(this.options.staleTime,this.#i);if(l.isServer||this.#n.isStale||!(0,l.isValidTimeout)(e))return;let t=(0,l.timeUntilStale)(this.#n.dataUpdatedAt,e);this.#d=o.timeoutManager.setTimeout(()=>{this.#n.isStale||this.updateResult()},t+1)}#C(){return("function"==typeof this.options.refetchInterval?this.options.refetchInterval(this.#i):this.options.refetchInterval)??!1}#w(e){this.#y(),this.#f=e,!l.isServer&&!1!==(0,l.resolveEnabled)(this.options.enabled,this.#i)&&(0,l.isValidTimeout)(this.#f)&&0!==this.#f&&(this.#h=o.timeoutManager.setInterval(()=>{(this.options.refetchIntervalInBackground||r.focusManager.isFocused())&&this.#m()},this.#f))}#g(){this.#R(),this.#w(this.#C())}#b(){this.#d&&(o.timeoutManager.clearTimeout(this.#d),this.#d=void 0)}#y(){this.#h&&(o.timeoutManager.clearInterval(this.#h),this.#h=void 0)}createResult(e,t){let r,i=this.#i,n=this.options,o=this.#n,u=this.#a,d=this.#l,p=e!==i?e.state:this.#s,{state:m}=e,g={...m},b=!1;if(t._optimisticResults){let r=this.hasListeners(),a=!r&&c(e,t),l=r&&h(e,i,t,n);(a||l)&&(g={...g,...(0,s.fetchState)(m.data,e.options)}),"isRestoring"===t._optimisticResults&&(g.fetchStatus="idle")}let{error:y,errorUpdatedAt:v,status:R}=g;r=g.data;let C=!1;if(void 0!==t.placeholderData&&void 0===r&&"pending"===R){let e;o?.isPlaceholderData&&t.placeholderData===d?.placeholderData?(e=o.data,C=!0):e="function"==typeof t.placeholderData?t.placeholderData(this.#c?.state.data,this.#c):t.placeholderData,void 0!==e&&(R="success",r=(0,l.replaceData)(o?.data,e,t),b=!0)}if(t.select&&void 0!==r&&!C)if(o&&r===u?.data&&t.select===this.#o)r=this.#u;else try{this.#o=t.select,r=t.select(r),r=(0,l.replaceData)(o?.data,r,t),this.#u=r,this.#t=null}catch(e){this.#t=e}this.#t&&(y=this.#t,r=this.#u,v=Date.now(),R="error");let w="fetching"===g.fetchStatus,$="pending"===R,k="error"===R,O=$&&w,E=void 0!==r,x={status:R,fetchStatus:g.fetchStatus,isPending:$,isSuccess:"success"===R,isError:k,isInitialLoading:O,isLoading:O,data:r,dataUpdatedAt:g.dataUpdatedAt,error:y,errorUpdatedAt:v,failureCount:g.fetchFailureCount,failureReason:g.fetchFailureReason,errorUpdateCount:g.errorUpdateCount,isFetched:g.dataUpdateCount>0||g.errorUpdateCount>0,isFetchedAfterMount:g.dataUpdateCount>p.dataUpdateCount||g.errorUpdateCount>p.errorUpdateCount,isFetching:w,isRefetching:w&&!$,isLoadingError:k&&!E,isPaused:"paused"===g.fetchStatus,isPlaceholderData:b,isRefetchError:k&&E,isStale:f(e,t),refetch:this.refetch,promise:this.#r,isEnabled:!1!==(0,l.resolveEnabled)(t.enabled,e)};if(this.options.experimental_prefetchInRender){let t=void 0!==x.data,r="error"===x.status&&!t,s=e=>{r?e.reject(x.error):t&&e.resolve(x.data)},n=()=>{s(this.#r=x.promise=(0,a.pendingThenable)())},l=this.#r;switch(l.status){case"pending":e.queryHash===i.queryHash&&s(l);break;case"fulfilled":(r||x.data!==l.value)&&n();break;case"rejected":r&&x.error===l.reason||n()}}return x}updateResult(){let e=this.#n,t=this.createResult(this.#i,this.options);if(this.#a=this.#i.state,this.#l=this.options,void 0!==this.#a.data&&(this.#c=this.#i),(0,l.shallowEqualObjects)(t,e))return;this.#n=t;let r=()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,r="function"==typeof t?t():t;if("all"===r||!r&&!this.#p.size)return!0;let i=new Set(r??this.#p);return this.options.throwOnError&&i.add("error"),Object.keys(this.#n).some(t=>this.#n[t]!==e[t]&&i.has(t))};this.#$({listeners:r()})}#v(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#i)return;let t=this.#i;this.#i=e,this.#s=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#g()}#$(e){i.notifyManager.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#n)}),this.#e.getQueryCache().notify({query:this.#i,type:"observerResultsUpdated"})})}};function c(e,t){return!1!==(0,l.resolveEnabled)(t.enabled,e)&&void 0===e.state.data&&("error"!==e.state.status||!1!==t.retryOnMount)||void 0!==e.state.data&&d(e,t,t.refetchOnMount)}function d(e,t,r){if(!1!==(0,l.resolveEnabled)(t.enabled,e)&&"static"!==(0,l.resolveStaleTime)(t.staleTime,e)){let i="function"==typeof r?r(e):r;return"always"===i||!1!==i&&f(e,t)}return!1}function h(e,t,r,i){return(e!==t||!1===(0,l.resolveEnabled)(i.enabled,e))&&(!r.suspense||"error"!==e.state.status)&&f(e,r)}function f(e,t){return!1!==(0,l.resolveEnabled)(t.enabled,e)&&e.isStaleByTime((0,l.resolveStaleTime)(t.staleTime,e))}e.s(["QueryObserver",()=>u],869230),e.i(247167);var p=e.i(271645),m=e.i(912598);e.i(843476);var g=p.createContext((t=!1,{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t})),b=p.createContext(!1);b.Provider;var y=(e,t,r)=>t.fetchOptimistic(e).catch(()=>{r.clearReset()});function v(e,t,r){let s,n=p.useContext(b),a=p.useContext(g),o=(0,m.useQueryClient)(r),u=o.defaultQueryOptions(e);o.getDefaultOptions().queries?._experimental_beforeQuery?.(u);let c=o.getQueryCache().get(u.queryHash);if(u._optimisticResults=n?"isRestoring":"optimistic",u.suspense){let e=e=>"static"===e?e:Math.max(e??1e3,1e3),t=u.staleTime;u.staleTime="function"==typeof t?(...r)=>e(t(...r)):e(t),"number"==typeof u.gcTime&&(u.gcTime=Math.max(u.gcTime,1e3))}s=c?.state.error&&"function"==typeof u.throwOnError?(0,l.shouldThrowError)(u.throwOnError,[c.state.error,c]):u.throwOnError,(u.suspense||u.experimental_prefetchInRender||s)&&!a.isReset()&&(u.retryOnMount=!1),p.useEffect(()=>{a.clearReset()},[a]);let d=!o.getQueryCache().get(u.queryHash),[h]=p.useState(()=>new t(o,u)),f=h.getOptimisticResult(u),v=!n&&!1!==e.subscribed;if(p.useSyncExternalStore(p.useCallback(e=>{let t=v?h.subscribe(i.notifyManager.batchCalls(e)):l.noop;return h.updateResult(),t},[h,v]),()=>h.getCurrentResult(),()=>h.getCurrentResult()),p.useEffect(()=>{h.setOptions(u)},[u,h]),u?.suspense&&f.isPending)throw y(u,h,a);if((({result:e,errorResetBoundary:t,throwOnError:r,query:i,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&i&&(s&&void 0===e.data||(0,l.shouldThrowError)(r,[e.error,i])))({result:f,errorResetBoundary:a,throwOnError:u.throwOnError,query:c,suspense:u.suspense}))throw f.error;if(o.getDefaultOptions().queries?._experimental_afterQuery?.(u,f),u.experimental_prefetchInRender&&!l.isServer&&f.isLoading&&f.isFetching&&!n){let e=d?y(u,h,a):c?.promise;e?.catch(l.noop).finally(()=>{h.updateResult()})}return u.notifyOnChangeProps?f:h.trackResult(f)}function R(e,t){return v(e,u,t)}function C(e){let t=[e];return{all:t,lists:()=>[...t,"list"],list:e=>[...t,"list",{params:e}],details:()=>[...t,"detail"],detail:e=>[...t,"detail",e]}}e.s(["useBaseQuery",()=>v],469637),e.s(["useQuery",()=>R],266027),e.s(["createQueryKeys",()=>C],243652)},612256,e=>{"use strict";var t=e.i(764205),r=e.i(266027);let i=(0,e.i(243652).createQueryKeys)("uiConfig");e.s(["useUIConfig",0,()=>(0,r.useQuery)({queryKey:i.list({}),queryFn:async()=>await (0,t.getUiConfig)(),staleTime:864e5,gcTime:864e5})])},161281,321836,e=>{"use strict";var t=e.i(947293);function r(e){try{let r=(0,t.jwtDecode)(e);if(r&&"number"==typeof r.exp)return 1e3*r.exp<=Date.now();return!1}catch{return!0}}function i(e){if(!e)return null;try{return(0,t.jwtDecode)(e)}catch{return null}}function s(e){return!!e&&null!==i(e)&&!r(e)}e.s(["checkTokenValidity",()=>s,"decodeToken",()=>i,"isJwtExpired",()=>r],161281);let n="litellm_return_url",a="redirect_to";function l(){return window.location.href}function o(){let e=l();e&&function(e,t,r=300){if("u"typeof document&&(document.cookie=`${n}=; path=/; max-age=0`)}catch(e){console.error("Failed to clear return URL cookie:",e)}}function d(){return new URLSearchParams(window.location.search).get(a)}function h(e,t){let r=t||l();if(!r||r.includes("/login"))return e;let i=e.includes("?")?"&":"?";return`${e}${i}${a}=${encodeURIComponent(r)}`}function f(){let e=d();if(e)return e;let t=u();return t||null}function p(){let e=window.location.hostname;return"localhost"===e||"127.0.0.1"===e||"::1"===e||e.startsWith("127.")||e.endsWith(".local")}function m(e){if(!e)return!1;if(e.startsWith("/")&&!e.startsWith("//"))return!0;try{let t=new URL(e),r=window.location.hostname;if(t.hostname!==r)return!1;if(p())return!0;return t.origin===window.location.origin}catch{return!1}}function g(e){try{let t=new URL(e,window.location.origin),r=t.pathname;r.length>1&&r.endsWith("/")&&(r=r.slice(0,-1));let i=new URLSearchParams(t.search),s=new URLSearchParams;Array.from(i.entries()).sort(([e],[t])=>e.localeCompare(t)).forEach(([e,t])=>{s.append(e,t)});let n=s.toString(),a=t.hash||"";return`${t.origin}${r}${n?`?${n}`:""}${a}`}catch{return e}}function b(){let e=d();if(e){if(m(e))return c(),e;p()&&console.warn("[returnUrlUtils] Invalid return URL in params rejected:",e)}let t=u();if(t){if(m(t))return c(),t;p()&&console.warn("[returnUrlUtils] Invalid return URL in cookie rejected:",t)}return null}e.s(["buildLoginUrlWithReturn",()=>h,"consumeReturnUrl",()=>b,"getReturnUrl",()=>f,"isValidReturnUrl",()=>m,"normalizeUrlForCompare",()=>g,"storeReturnUrl",()=>o],321836)},563113,887719,e=>{"use strict";var t=e.i(271645),r=e.i(864517),i=e.i(244009),s=e.i(408850),n=e.i(87414);let a=function(...e){let t={};return e.forEach(e=>{e&&Object.keys(e).forEach(r=>{void 0!==e[r]&&(t[r]=e[r])})}),t};function l(e){if(!e)return;let{closable:t,closeIcon:r}=e;return{closable:t,closeIcon:r}}function o(e){let{closable:r,closeIcon:i}=e||{};return t.default.useMemo(()=>{if(!r&&(!1===r||!1===i||null===i))return!1;if(void 0===r&&void 0===i)return null;let e={closeIcon:"boolean"!=typeof i&&null!==i?i:void 0};return r&&"object"==typeof r&&(e=Object.assign(Object.assign({},e),r)),e},[r,i])}e.s(["default",0,a],887719);let u={};e.s(["pickClosable",()=>l,"useClosable",0,(e,l,c=u)=>{let d=o(e),h=o(l),[f]=(0,s.useLocale)("global",n.default.global),p="boolean"!=typeof d&&!!(null==d?void 0:d.disabled),m=t.default.useMemo(()=>Object.assign({closeIcon:t.default.createElement(r.default,null)},c),[c]),g=t.default.useMemo(()=>!1!==d&&(d?a(m,h,d):!1!==h&&(h?a(m,h):!!m.closable&&m)),[d,h,m]);return t.default.useMemo(()=>{var e,r;if(!1===g)return[!1,null,p,{}];let{closeIconRender:s}=m,{closeIcon:n}=g,a=n,l=(0,i.default)(g,!0);return null!=a&&(s&&(a=s(n)),a=t.default.isValidElement(a)?t.default.cloneElement(a,Object.assign(Object.assign(Object.assign({},a.props),{"aria-label":null!=(r=null==(e=a.props)?void 0:e["aria-label"])?r:f.close}),l)):t.default.createElement("span",Object.assign({"aria-label":f.close},l),a)),[!0,a,p,l]},[p,f.close,g,m])}],563113)},735049,e=>{"use strict";var t=e.i(654310),r=function(e){if((0,t.default)()&&window.document.documentElement){var r=Array.isArray(e)?e:[e],i=window.document.documentElement;return r.some(function(e){return e in i.style})}return!1},i=function(e,t){if(!r(e))return!1;var i=document.createElement("div"),s=i.style[e];return i.style[e]=t,i.style[e]!==s};function s(e,t){return Array.isArray(e)||void 0===t?r(e):i(e,t)}e.s(["isStyleSupport",()=>s])},190144,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let i={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M832 64H296c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h496v688c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8V96c0-17.7-14.3-32-32-32zM704 192H192c-17.7 0-32 14.3-32 32v530.7c0 8.5 3.4 16.6 9.4 22.6l173.3 173.3c2.2 2.2 4.7 4 7.4 5.5v1.9h4.2c3.5 1.3 7.2 2 11 2H704c17.7 0 32-14.3 32-32V224c0-17.7-14.3-32-32-32zM350 856.2L263.9 770H350v86.2zM664 888H414V746c0-22.1-17.9-40-40-40H232V264h432v624z"}}]},name:"copy",theme:"outlined"};var s=e.i(9583),n=r.forwardRef(function(e,n){return r.createElement(s.default,(0,t.default)({},e,{ref:n,icon:i}))});e.s(["default",0,n],190144)},464571,e=>{"use strict";var t=e.i(920228);e.s(["Button",()=>t.default])},185793,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),i=e.i(242064),s=e.i(529681);let n=e=>{let{prefixCls:i,className:s,style:n,size:a,shape:l}=e,o=(0,r.default)({[`${i}-lg`]:"large"===a,[`${i}-sm`]:"small"===a}),u=(0,r.default)({[`${i}-circle`]:"circle"===l,[`${i}-square`]:"square"===l,[`${i}-round`]:"round"===l}),c=t.useMemo(()=>"number"==typeof a?{width:a,height:a,lineHeight:`${a}px`}:{},[a]);return t.createElement("span",{className:(0,r.default)(i,o,u,s),style:Object.assign(Object.assign({},c),n)})};e.i(296059);var a=e.i(694758),l=e.i(915654),o=e.i(246422),u=e.i(838378);let c=new a.Keyframes("ant-skeleton-loading",{"0%":{backgroundPosition:"100% 50%"},"100%":{backgroundPosition:"0 50%"}}),d=e=>({height:e,lineHeight:(0,l.unit)(e)}),h=e=>Object.assign({width:e},d(e)),f=(e,t)=>Object.assign({width:t(e).mul(5).equal(),minWidth:t(e).mul(5).equal()},d(e)),p=e=>Object.assign({width:e},d(e)),m=(e,t,r)=>{let{skeletonButtonCls:i}=e;return{[`${r}${i}-circle`]:{width:t,minWidth:t,borderRadius:"50%"},[`${r}${i}-round`]:{borderRadius:t}}},g=(e,t)=>Object.assign({width:t(e).mul(2).equal(),minWidth:t(e).mul(2).equal()},d(e)),b=(0,o.genStyleHooks)("Skeleton",e=>{let{componentCls:t,calc:r}=e;return(e=>{let{componentCls:t,skeletonAvatarCls:r,skeletonTitleCls:i,skeletonParagraphCls:s,skeletonButtonCls:n,skeletonInputCls:a,skeletonImageCls:l,controlHeight:o,controlHeightLG:u,controlHeightSM:d,gradientFromColor:b,padding:y,marginSM:v,borderRadius:R,titleHeight:C,blockRadius:w,paragraphLiHeight:$,controlHeightXS:k,paragraphMarginTop:O}=e;return{[t]:{display:"table",width:"100%",[`${t}-header`]:{display:"table-cell",paddingInlineEnd:y,verticalAlign:"top",[r]:Object.assign({display:"inline-block",verticalAlign:"top",background:b},h(o)),[`${r}-circle`]:{borderRadius:"50%"},[`${r}-lg`]:Object.assign({},h(u)),[`${r}-sm`]:Object.assign({},h(d))},[`${t}-content`]:{display:"table-cell",width:"100%",verticalAlign:"top",[i]:{width:"100%",height:C,background:b,borderRadius:w,[`+ ${s}`]:{marginBlockStart:d}},[s]:{padding:0,"> li":{width:"100%",height:$,listStyle:"none",background:b,borderRadius:w,"+ li":{marginBlockStart:k}}},[`${s}> li:last-child:not(:first-child):not(:nth-child(2))`]:{width:"61%"}},[`&-round ${t}-content`]:{[`${i}, ${s} > li`]:{borderRadius:R}}},[`${t}-with-avatar ${t}-content`]:{[i]:{marginBlockStart:v,[`+ ${s}`]:{marginBlockStart:O}}},[`${t}${t}-element`]:Object.assign(Object.assign(Object.assign(Object.assign({display:"inline-block",width:"auto"},(e=>{let{borderRadiusSM:t,skeletonButtonCls:r,controlHeight:i,controlHeightLG:s,controlHeightSM:n,gradientFromColor:a,calc:l}=e;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({[r]:Object.assign({display:"inline-block",verticalAlign:"top",background:a,borderRadius:t,width:l(i).mul(2).equal(),minWidth:l(i).mul(2).equal()},g(i,l))},m(e,i,r)),{[`${r}-lg`]:Object.assign({},g(s,l))}),m(e,s,`${r}-lg`)),{[`${r}-sm`]:Object.assign({},g(n,l))}),m(e,n,`${r}-sm`))})(e)),(e=>{let{skeletonAvatarCls:t,gradientFromColor:r,controlHeight:i,controlHeightLG:s,controlHeightSM:n}=e;return{[t]:Object.assign({display:"inline-block",verticalAlign:"top",background:r},h(i)),[`${t}${t}-circle`]:{borderRadius:"50%"},[`${t}${t}-lg`]:Object.assign({},h(s)),[`${t}${t}-sm`]:Object.assign({},h(n))}})(e)),(e=>{let{controlHeight:t,borderRadiusSM:r,skeletonInputCls:i,controlHeightLG:s,controlHeightSM:n,gradientFromColor:a,calc:l}=e;return{[i]:Object.assign({display:"inline-block",verticalAlign:"top",background:a,borderRadius:r},f(t,l)),[`${i}-lg`]:Object.assign({},f(s,l)),[`${i}-sm`]:Object.assign({},f(n,l))}})(e)),(e=>{let{skeletonImageCls:t,imageSizeBase:r,gradientFromColor:i,borderRadiusSM:s,calc:n}=e;return{[t]:Object.assign(Object.assign({display:"inline-flex",alignItems:"center",justifyContent:"center",verticalAlign:"middle",background:i,borderRadius:s},p(n(r).mul(2).equal())),{[`${t}-path`]:{fill:"#bfbfbf"},[`${t}-svg`]:Object.assign(Object.assign({},p(r)),{maxWidth:n(r).mul(4).equal(),maxHeight:n(r).mul(4).equal()}),[`${t}-svg${t}-svg-circle`]:{borderRadius:"50%"}}),[`${t}${t}-circle`]:{borderRadius:"50%"}}})(e)),[`${t}${t}-block`]:{width:"100%",[n]:{width:"100%"},[a]:{width:"100%"}},[`${t}${t}-active`]:{[` + ${i}, + ${s} > li, + ${r}, + ${n}, + ${a}, + ${l} + `]:Object.assign({},{background:e.skeletonLoadingBackground,backgroundSize:"400% 100%",animationName:c,animationDuration:e.skeletonLoadingMotionDuration,animationTimingFunction:"ease",animationIterationCount:"infinite"})}}})((0,u.mergeToken)(e,{skeletonAvatarCls:`${t}-avatar`,skeletonTitleCls:`${t}-title`,skeletonParagraphCls:`${t}-paragraph`,skeletonButtonCls:`${t}-button`,skeletonInputCls:`${t}-input`,skeletonImageCls:`${t}-image`,imageSizeBase:r(e.controlHeight).mul(1.5).equal(),borderRadius:100,skeletonLoadingBackground:`linear-gradient(90deg, ${e.gradientFromColor} 25%, ${e.gradientToColor} 37%, ${e.gradientFromColor} 63%)`,skeletonLoadingMotionDuration:"1.4s"}))},e=>{let{colorFillContent:t,colorFill:r}=e;return{color:t,colorGradientEnd:r,gradientFromColor:t,gradientToColor:r,titleHeight:e.controlHeight/2,blockRadius:e.borderRadiusSM,paragraphMarginTop:e.marginLG+e.marginXXS,paragraphLiHeight:e.controlHeight/2}},{deprecatedTokens:[["color","gradientFromColor"],["colorGradientEnd","gradientToColor"]]}),y=e=>{let{prefixCls:i,className:s,style:n,rows:a=0}=e,l=Array.from({length:a}).map((r,i)=>t.createElement("li",{key:i,style:{width:((e,t)=>{let{width:r,rows:i=2}=t;return Array.isArray(r)?r[e]:i-1===e?r:void 0})(i,e)}}));return t.createElement("ul",{className:(0,r.default)(i,s),style:n},l)},v=({prefixCls:e,className:i,width:s,style:n})=>t.createElement("h3",{className:(0,r.default)(e,i),style:Object.assign({width:s},n)});function R(e){return e&&"object"==typeof e?e:{}}let C=e=>{let{prefixCls:s,loading:a,className:l,rootClassName:o,style:u,children:c,avatar:d=!1,title:h=!0,paragraph:f=!0,active:p,round:m}=e,{getPrefixCls:g,direction:C,className:w,style:$}=(0,i.useComponentConfig)("skeleton"),k=g("skeleton",s),[O,E,x]=b(k);if(a||!("loading"in e)){let e,i,s=!!d,a=!!h,c=!!f;if(s){let r=Object.assign(Object.assign({prefixCls:`${k}-avatar`},a&&!c?{size:"large",shape:"square"}:{size:"large",shape:"circle"}),R(d));e=t.createElement("div",{className:`${k}-header`},t.createElement(n,Object.assign({},r)))}if(a||c){let e,r;if(a){let r=Object.assign(Object.assign({prefixCls:`${k}-title`},!s&&c?{width:"38%"}:s&&c?{width:"50%"}:{}),R(h));e=t.createElement(v,Object.assign({},r))}if(c){let e,i=Object.assign(Object.assign({prefixCls:`${k}-paragraph`},(e={},s&&a||(e.width="61%"),!s&&a?e.rows=3:e.rows=2,e)),R(f));r=t.createElement(y,Object.assign({},i))}i=t.createElement("div",{className:`${k}-content`},e,r)}let g=(0,r.default)(k,{[`${k}-with-avatar`]:s,[`${k}-active`]:p,[`${k}-rtl`]:"rtl"===C,[`${k}-round`]:m},w,l,o,E,x);return O(t.createElement("div",{className:g,style:Object.assign(Object.assign({},$),u)},e,i))}return null!=c?c:null};C.Button=e=>{let{prefixCls:a,className:l,rootClassName:o,active:u,block:c=!1,size:d="default"}=e,{getPrefixCls:h}=t.useContext(i.ConfigContext),f=h("skeleton",a),[p,m,g]=b(f),y=(0,s.default)(e,["prefixCls"]),v=(0,r.default)(f,`${f}-element`,{[`${f}-active`]:u,[`${f}-block`]:c},l,o,m,g);return p(t.createElement("div",{className:v},t.createElement(n,Object.assign({prefixCls:`${f}-button`,size:d},y))))},C.Avatar=e=>{let{prefixCls:a,className:l,rootClassName:o,active:u,shape:c="circle",size:d="default"}=e,{getPrefixCls:h}=t.useContext(i.ConfigContext),f=h("skeleton",a),[p,m,g]=b(f),y=(0,s.default)(e,["prefixCls","className"]),v=(0,r.default)(f,`${f}-element`,{[`${f}-active`]:u},l,o,m,g);return p(t.createElement("div",{className:v},t.createElement(n,Object.assign({prefixCls:`${f}-avatar`,shape:c,size:d},y))))},C.Input=e=>{let{prefixCls:a,className:l,rootClassName:o,active:u,block:c,size:d="default"}=e,{getPrefixCls:h}=t.useContext(i.ConfigContext),f=h("skeleton",a),[p,m,g]=b(f),y=(0,s.default)(e,["prefixCls"]),v=(0,r.default)(f,`${f}-element`,{[`${f}-active`]:u,[`${f}-block`]:c},l,o,m,g);return p(t.createElement("div",{className:v},t.createElement(n,Object.assign({prefixCls:`${f}-input`,size:d},y))))},C.Image=e=>{let{prefixCls:s,className:n,rootClassName:a,style:l,active:o}=e,{getPrefixCls:u}=t.useContext(i.ConfigContext),c=u("skeleton",s),[d,h,f]=b(c),p=(0,r.default)(c,`${c}-element`,{[`${c}-active`]:o},n,a,h,f);return d(t.createElement("div",{className:p},t.createElement("div",{className:(0,r.default)(`${c}-image`,n),style:l},t.createElement("svg",{viewBox:"0 0 1098 1024",xmlns:"http://www.w3.org/2000/svg",className:`${c}-image-svg`},t.createElement("title",null,"Image placeholder"),t.createElement("path",{d:"M365.714286 329.142857q0 45.714286-32.036571 77.677714t-77.677714 32.036571-77.677714-32.036571-32.036571-77.677714 32.036571-77.677714 77.677714-32.036571 77.677714 32.036571 32.036571 77.677714zM950.857143 548.571429l0 256-804.571429 0 0-109.714286 182.857143-182.857143 91.428571 91.428571 292.571429-292.571429zM1005.714286 146.285714l-914.285714 0q-7.460571 0-12.873143 5.412571t-5.412571 12.873143l0 694.857143q0 7.460571 5.412571 12.873143t12.873143 5.412571l914.285714 0q7.460571 0 12.873143-5.412571t5.412571-12.873143l0-694.857143q0-7.460571-5.412571-12.873143t-12.873143-5.412571zM1097.142857 164.571429l0 694.857143q0 37.741714-26.843429 64.585143t-64.585143 26.843429l-914.285714 0q-37.741714 0-64.585143-26.843429t-26.843429-64.585143l0-694.857143q0-37.741714 26.843429-64.585143t64.585143-26.843429l914.285714 0q37.741714 0 64.585143 26.843429t26.843429 64.585143z",className:`${c}-image-path`})))))},C.Node=e=>{let{prefixCls:s,className:n,rootClassName:a,style:l,active:o,children:u}=e,{getPrefixCls:c}=t.useContext(i.ConfigContext),d=c("skeleton",s),[h,f,p]=b(d),m=(0,r.default)(d,`${d}-element`,{[`${d}-active`]:o},f,n,a,p);return h(t.createElement("div",{className:m},t.createElement("div",{className:(0,r.default)(`${d}-image`,n),style:l},u)))},e.s(["default",0,C],185793)},959013,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let i={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8z"}},{tag:"path",attrs:{d:"M192 474h672q8 0 8 8v60q0 8-8 8H160q-8 0-8-8v-60q0-8 8-8z"}}]},name:"plus",theme:"outlined"};var s=e.i(9583),n=r.forwardRef(function(e,n){return r.createElement(s.default,(0,t.default)({},e,{ref:n,icon:i}))});e.s(["default",0,n],959013)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/3413b6a1ede03f29.js b/litellm/proxy/_experimental/out/_next/static/chunks/3413b6a1ede03f29.js new file mode 100644 index 00000000000..016e8f37d8d --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/3413b6a1ede03f29.js @@ -0,0 +1 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,384767,e=>{"use strict";var t=e.i(843476),r=e.i(599724),a=e.i(271645),s=e.i(389083);let l=a.forwardRef(function(e,t){return a.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:t},e),a.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4m0 5c0 2.21-3.582 4-8 4s-8-1.79-8-4"}))});var n=e.i(764205);let i=function({vectorStores:e,accessToken:i}){let[o,c]=(0,a.useState)([]);return(0,a.useEffect)(()=>{(async()=>{if(i&&0!==e.length)try{let e=await (0,n.vectorStoreListCall)(i);e.data&&c(e.data.map(e=>({vector_store_id:e.vector_store_id,vector_store_name:e.vector_store_name})))}catch(e){console.error("Error fetching vector stores:",e)}})()},[i,e.length]),(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(l,{className:"h-4 w-4 text-blue-600"}),(0,t.jsx)(r.Text,{className:"font-semibold text-gray-900",children:"Vector Stores"}),(0,t.jsx)(s.Badge,{color:"blue",size:"xs",children:e.length})]}),e.length>0?(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:e.map((e,r)=>{let a;return(0,t.jsx)("div",{className:"inline-flex items-center px-3 py-1.5 rounded-lg bg-blue-50 border border-blue-200 text-blue-800 text-sm font-medium",children:(a=o.find(t=>t.vector_store_id===e))?`${a.vector_store_name||a.vector_store_id} (${a.vector_store_id})`:e},r)})}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 border border-gray-200",children:[(0,t.jsx)(l,{className:"h-4 w-4 text-gray-400"}),(0,t.jsx)(r.Text,{className:"text-gray-500 text-sm",children:"No vector stores configured"})]})]})},o=a.forwardRef(function(e,t){return a.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:t},e),a.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01"}))});var c=e.i(871943),d=e.i(502547),u=e.i(592968);let m=function({mcpServers:l,mcpAccessGroups:i=[],mcpToolPermissions:m={},accessToken:p}){let[g,f]=(0,a.useState)([]),[x,h]=(0,a.useState)([]),[b,y]=(0,a.useState)(new Set);(0,a.useEffect)(()=>{(async()=>{if(p&&l.length>0)try{let e=await (0,n.fetchMCPServers)(p);e&&Array.isArray(e)?f(e):e.data&&Array.isArray(e.data)&&f(e.data)}catch(e){console.error("Error fetching MCP servers:",e)}})()},[p,l.length]),(0,a.useEffect)(()=>{(async()=>{if(p&&i.length>0)try{let t=await e.A(601236).then(e=>e.fetchMCPAccessGroups(p));h(Array.isArray(t)?t:t.data||[])}catch(e){console.error("Error fetching MCP access groups:",e)}})()},[p,i.length]);let v=[...l.map(e=>({type:"server",value:e})),...i.map(e=>({type:"accessGroup",value:e}))],j=v.length;return(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(o,{className:"h-4 w-4 text-blue-600"}),(0,t.jsx)(r.Text,{className:"font-semibold text-gray-900",children:"MCP Servers"}),(0,t.jsx)(s.Badge,{color:"blue",size:"xs",children:j})]}),j>0?(0,t.jsx)("div",{className:"max-h-[400px] overflow-y-auto space-y-2 pr-1",children:v.map((e,r)=>{let a="server"===e.type?m[e.value]:void 0,s=a&&a.length>0,l=b.has(e.value);return(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{onClick:()=>{var t;return s&&(t=e.value,void y(e=>{let r=new Set(e);return r.has(t)?r.delete(t):r.add(t),r}))},className:`flex items-center gap-3 py-2 px-3 rounded-lg border border-gray-200 transition-all ${s?"cursor-pointer hover:bg-gray-50 hover:border-gray-300":"bg-white"}`,children:[(0,t.jsx)("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:"server"===e.type?(0,t.jsx)(u.Tooltip,{title:`Full ID: ${e.value}`,placement:"top",children:(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 min-w-0",children:[(0,t.jsx)("span",{className:"inline-block w-1.5 h-1.5 bg-blue-500 rounded-full flex-shrink-0"}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-900 truncate",children:(e=>{let t=g.find(t=>t.server_id===e);if(t){let r=e.length>7?`${e.slice(0,3)}...${e.slice(-4)}`:e;return`${t.alias} (${r})`}return e})(e.value)})]})}):(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 min-w-0",children:[(0,t.jsx)("span",{className:"inline-block w-1.5 h-1.5 bg-green-500 rounded-full flex-shrink-0"}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-900 truncate",children:e.value}),(0,t.jsx)("span",{className:"ml-1 px-1.5 py-0.5 text-[9px] font-semibold text-green-600 bg-green-50 border border-green-200 rounded uppercase tracking-wide flex-shrink-0",children:"Group"})]})}),s&&(0,t.jsxs)("div",{className:"flex items-center gap-1 flex-shrink-0 whitespace-nowrap",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-gray-600",children:a.length}),(0,t.jsx)("span",{className:"text-xs text-gray-500",children:1===a.length?"tool":"tools"}),l?(0,t.jsx)(c.ChevronDownIcon,{className:"h-3.5 w-3.5 text-gray-400 ml-0.5"}):(0,t.jsx)(d.ChevronRightIcon,{className:"h-3.5 w-3.5 text-gray-400 ml-0.5"})]})]}),s&&l&&(0,t.jsx)("div",{className:"ml-4 pl-4 border-l-2 border-blue-200 pb-1",children:(0,t.jsx)("div",{className:"flex flex-wrap gap-1.5",children:a.map((e,r)=>(0,t.jsx)("span",{className:"inline-flex items-center px-2.5 py-1 rounded-lg bg-blue-50 border border-blue-200 text-blue-800 text-xs font-medium",children:e},r))})})]},r)})}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 border border-gray-200",children:[(0,t.jsx)(o,{className:"h-4 w-4 text-gray-400"}),(0,t.jsx)(r.Text,{className:"text-gray-500 text-sm",children:"No MCP servers or access groups configured"})]})]})},p=a.forwardRef(function(e,t){return a.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:t},e),a.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"}))}),g=function({agents:e,agentAccessGroups:l=[],accessToken:i}){let[o,c]=(0,a.useState)([]);(0,a.useEffect)(()=>{(async()=>{if(i&&e.length>0)try{let e=await (0,n.getAgentsList)(i);e&&e.agents&&Array.isArray(e.agents)&&c(e.agents)}catch(e){console.error("Error fetching agents:",e)}})()},[i,e.length]);let d=[...e.map(e=>({type:"agent",value:e})),...l.map(e=>({type:"accessGroup",value:e}))],m=d.length;return(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(p,{className:"h-4 w-4 text-purple-600"}),(0,t.jsx)(r.Text,{className:"font-semibold text-gray-900",children:"Agents"}),(0,t.jsx)(s.Badge,{color:"purple",size:"xs",children:m})]}),m>0?(0,t.jsx)("div",{className:"max-h-[400px] overflow-y-auto space-y-2 pr-1",children:d.map((e,r)=>(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsx)("div",{className:"flex items-center gap-3 py-2 px-3 rounded-lg border border-gray-200 bg-white",children:(0,t.jsx)("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:"agent"===e.type?(0,t.jsx)(u.Tooltip,{title:`Full ID: ${e.value}`,placement:"top",children:(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 min-w-0",children:[(0,t.jsx)("span",{className:"inline-block w-1.5 h-1.5 bg-purple-500 rounded-full flex-shrink-0"}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-900 truncate",children:(e=>{let t=o.find(t=>t.agent_id===e);if(t){let r=e.length>7?`${e.slice(0,3)}...${e.slice(-4)}`:e;return`${t.agent_name} (${r})`}return e})(e.value)})]})}):(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 min-w-0",children:[(0,t.jsx)("span",{className:"inline-block w-1.5 h-1.5 bg-green-500 rounded-full flex-shrink-0"}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-900 truncate",children:e.value}),(0,t.jsx)("span",{className:"ml-1 px-1.5 py-0.5 text-[9px] font-semibold text-green-600 bg-green-50 border border-green-200 rounded uppercase tracking-wide flex-shrink-0",children:"Group"})]})})})},r))}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 border border-gray-200",children:[(0,t.jsx)(p,{className:"h-4 w-4 text-gray-400"}),(0,t.jsx)(r.Text,{className:"text-gray-500 text-sm",children:"No agents or access groups configured"})]})]})};e.s(["default",0,function({objectPermission:e,variant:a="card",className:s="",accessToken:l}){let n=e?.vector_stores||[],o=e?.mcp_servers||[],c=e?.mcp_access_groups||[],d=e?.mcp_tool_permissions||{},u=e?.agents||[],p=e?.agent_access_groups||[],f=(0,t.jsxs)("div",{className:"card"===a?"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6":"space-y-4",children:[(0,t.jsx)(i,{vectorStores:n,accessToken:l}),(0,t.jsx)(m,{mcpServers:o,mcpAccessGroups:c,mcpToolPermissions:d,accessToken:l}),(0,t.jsx)(g,{agents:u,agentAccessGroups:p,accessToken:l})]});return"card"===a?(0,t.jsxs)("div",{className:`bg-white border border-gray-200 rounded-lg p-6 ${s}`,children:[(0,t.jsx)("div",{className:"flex items-center gap-2 mb-6",children:(0,t.jsxs)("div",{children:[(0,t.jsx)(r.Text,{className:"font-semibold text-gray-900",children:"Object Permissions"}),(0,t.jsx)(r.Text,{className:"text-xs text-gray-500",children:"Access control for Vector Stores and MCP Servers"})]})}),f]}):(0,t.jsxs)("div",{className:`${s}`,children:[(0,t.jsx)(r.Text,{className:"font-medium text-gray-900 mb-3",children:"Object Permissions"}),f]})}],384767)},270345,e=>{"use strict";var t=e.i(764205);let r=async(e,r,a,s)=>"Admin"!=a&&"Admin Viewer"!=a?await (0,t.teamListCall)(e,s?.organization_id||null,r):await (0,t.teamListCall)(e,s?.organization_id||null);e.s(["fetchTeams",0,r])},519756,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={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"};var s=e.i(9583),l=r.forwardRef(function(e,l){return r.createElement(s.default,(0,t.default)({},e,{ref:l,icon:a}))});e.s(["UploadOutlined",0,l],519756)},981339,e=>{"use strict";var t=e.i(185793);e.s(["Skeleton",()=>t.default])},500330,e=>{"use strict";var t=e.i(727749);function r(e,t){let r=structuredClone(e);for(let[e,a]of Object.entries(t))e in r&&(r[e]=a);return r}let a=(e,t=0,r=!1,a=!0)=>{if(null==e||!Number.isFinite(e)||0===e&&!a)return"-";let s={minimumFractionDigits:t,maximumFractionDigits:t};if(!r)return e.toLocaleString("en-US",s);let l=e<0?"-":"",n=Math.abs(e),i=n,o="";return n>=1e6?(i=n/1e6,o="M"):n>=1e3&&(i=n/1e3,o="K"),`${l}${i.toLocaleString("en-US",s)}${o}`},s=async(e,r="Copied to clipboard")=>{if(!e)return!1;if(!navigator||!navigator.clipboard||!navigator.clipboard.writeText)return l(e,r);try{return await navigator.clipboard.writeText(e),t.default.success(r),!0}catch(t){return console.error("Clipboard API failed: ",t),l(e,r)}},l=(e,r)=>{try{let a=document.createElement("textarea");a.value=e,a.style.position="fixed",a.style.left="-999999px",a.style.top="-999999px",a.setAttribute("readonly",""),document.body.appendChild(a),a.focus(),a.select();let s=document.execCommand("copy");if(document.body.removeChild(a),s)return t.default.success(r),!0;throw Error("execCommand failed")}catch(e){return t.default.fromBackend("Failed to copy to clipboard"),console.error("Failed to copy: ",e),!1}};e.s(["copyToClipboard",0,s,"formatNumberWithCommas",0,a,"getSpendString",0,(e,t=6)=>{if(null==e||!Number.isFinite(e)||0===e)return"-";let r=a(e,t,!1,!1);if(0===Number(r.replace(/,/g,""))){let e=(1/10**t).toFixed(t);return`< $${e}`}return`$${r}`},"updateExistingKeys",()=>r])},743151,(e,t,r)=>{"use strict";function a(e){return(a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}Object.defineProperty(r,"__esModule",{value:!0}),r.CopyToClipboard=void 0;var s=i(e.r(271645)),l=i(e.r(844343)),n=["text","onCopy","options","children"];function i(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,a)}return r}function c(e){for(var t=1;t=0||(s[r]=e[r]);return s}(e,t);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(e);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(s[r]=e[r])}return s}(e,n),a=s.default.Children.only(t);return s.default.cloneElement(a,c(c({},r),{},{onClick:this.onClick}))}}],function(e,t){for(var r=0;r{"use strict";var a=e.r(743151).CopyToClipboard;a.CopyToClipboard=a,t.exports=a},109799,e=>{"use strict";var t=e.i(135214),r=e.i(764205),a=e.i(266027),s=e.i(912598);let l=(0,e.i(243652).createQueryKeys)("organizations");e.s(["useOrganization",0,e=>{let n=(0,s.useQueryClient)(),{accessToken:i}=(0,t.default)();return(0,a.useQuery)({queryKey:l.detail(e),enabled:!!(i&&e),queryFn:async()=>{if(!i||!e)throw Error("Missing auth or teamId");return(0,r.organizationInfoCall)(i,e)},initialData:()=>{if(!e)return;let t=n.getQueryData(l.list({}));return t?.find(t=>t.organization_id===e)}})},"useOrganizations",0,()=>{let{accessToken:e,userId:s,userRole:n}=(0,t.default)();return(0,a.useQuery)({queryKey:l.list({}),queryFn:async()=>await (0,r.organizationListCall)(e),enabled:!!(e&&s&&n)})}])},309426,e=>{"use strict";var t=e.i(290571),r=e.i(444755),a=e.i(673706),s=e.i(271645),l=e.i(46757);let n=(0,a.makeClassName)("Col"),i=s.default.forwardRef((e,a)=>{let i,o,c,d,{numColSpan:u=1,numColSpanSm:m,numColSpanMd:p,numColSpanLg:g,children:f,className:x}=e,h=(0,t.__rest)(e,["numColSpan","numColSpanSm","numColSpanMd","numColSpanLg","children","className"]),b=(e,t)=>e&&Object.keys(t).includes(String(e))?t[e]:"";return s.default.createElement("div",Object.assign({ref:a,className:(0,r.tremorTwMerge)(n("root"),(i=b(u,l.colSpan),o=b(m,l.colSpanSm),c=b(p,l.colSpanMd),d=b(g,l.colSpanLg),(0,r.tremorTwMerge)(i,o,c,d)),x)},h),f)});i.displayName="Col",e.s(["Col",()=>i],309426)},988297,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 4v16m8-8H4"}))});e.s(["PlusIcon",0,r],988297)},797672,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"}))});e.s(["PencilIcon",0,r],797672)},992619,e=>{"use strict";var t=e.i(843476),r=e.i(271645),a=e.i(779241),s=e.i(599724),l=e.i(199133),n=e.i(983561),i=e.i(689020);e.s(["default",0,({accessToken:e,value:o,placeholder:c="Select a Model",onChange:d,disabled:u=!1,style:m,className:p,showLabel:g=!0,labelText:f="Select Model"})=>{let[x,h]=(0,r.useState)(o),[b,y]=(0,r.useState)(!1),[v,j]=(0,r.useState)([]),w=(0,r.useRef)(null);return(0,r.useEffect)(()=>{h(o)},[o]),(0,r.useEffect)(()=>{e&&(async()=>{try{let t=await (0,i.fetchAvailableModels)(e);console.log("Fetched models for selector:",t),t.length>0&&j(t)}catch(e){console.error("Error fetching model info:",e)}})()},[e]),(0,t.jsxs)("div",{children:[g&&(0,t.jsxs)(s.Text,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,t.jsx)(n.RobotOutlined,{className:"mr-2"})," ",f]}),(0,t.jsx)(l.Select,{value:x,placeholder:c,onChange:e=>{"custom"===e?(y(!0),h(void 0)):(y(!1),h(e),d&&d(e))},options:[...Array.from(new Set(v.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%",...m},showSearch:!0,className:`rounded-md ${p||""}`,disabled:u}),b&&(0,t.jsx)(a.TextInput,{className:"mt-2",placeholder:"Enter custom model name",onValueChange:e=>{w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{h(e),d&&d(e)},500)},disabled:u})]})}])},91739,e=>{"use strict";var t=e.i(544195);e.s(["Radio",()=>t.default])},409797,e=>{"use strict";var t=e.i(631171);e.s(["ChevronDownIcon",()=>t.default])},500727,696609,531516,e=>{"use strict";var t=e.i(266027),r=e.i(243652),a=e.i(764205),s=e.i(135214);let l=(0,r.createQueryKeys)("mcpServers");e.s(["useMCPServers",0,e=>{let{accessToken:r}=(0,s.default)();return(0,t.useQuery)({queryKey:l.list(e?{filters:{teamId:e}}:void 0),queryFn:async()=>await (0,a.fetchMCPServers)(r,e),enabled:!!r})}],500727);var n=e.i(843476),i=e.i(271645),o=e.i(536916),c=e.i(599724),d=e.i(409797),u=e.i(246349),u=u;let m=/\b(delete|remove|destroy|purge|drop|erase|unlink)\b/i,p=/\b(create|add|insert|new|post|submit|register|make|generate|write|upload)\b/i,g=/\b(update|edit|modify|change|patch|put|set|rename|move|transform)\b/i,f=/\b(get|read|list|fetch|search|find|query|retrieve|show|view|check|describe|info)\b/i;function x(e,t=""){let r=e.toLowerCase();if(f.test(r))return"read";if(m.test(r))return"delete";if(g.test(r))return"update";if(p.test(r))return"create";if(t){let e=t.toLowerCase();if(f.test(e))return"read";if(m.test(e))return"delete";if(g.test(e))return"update";if(p.test(e))return"create"}return"unknown"}function h(e){let t={read:[],create:[],update:[],delete:[],unknown:[]};for(let r of e)t[x(r.name,r.description)].push(r);return t}let b={read:{label:"Read",description:"Safe operations — fetch, list, search. No side effects.",risk:"low"},create:{label:"Create",description:"Add new resources — insert, upload, register.",risk:"medium"},update:{label:"Update",description:"Modify existing resources — edit, patch, rename.",risk:"medium"},delete:{label:"Delete",description:"Destructive operations — remove, purge, destroy.",risk:"high"},unknown:{label:"Other",description:"Operations that could not be automatically classified.",risk:"unknown"}};e.s(["CRUD_GROUP_META",0,b,"classifyToolOp",()=>x,"groupToolsByCrud",()=>h],696609);let y=["read","create","update","delete","unknown"],v={low:"bg-green-100 text-green-800",medium:"bg-yellow-100 text-yellow-800",high:"bg-red-100 text-red-800 font-semibold",unknown:"bg-gray-100 text-gray-700"},j={read:"border-green-200",create:"border-blue-200",update:"border-yellow-200",delete:"border-red-300",unknown:"border-gray-200"},w={read:"bg-green-50",create:"bg-blue-50",update:"bg-yellow-50",delete:"bg-red-50",unknown:"bg-gray-50"};e.s(["default",0,({tools:e,value:t,onChange:r,readOnly:a=!1,searchFilter:s=""})=>{let[l,m]=(0,i.useState)({read:!1,create:!1,update:!1,delete:!1,unknown:!0}),p=(0,i.useMemo)(()=>h(e),[e]),g=(0,i.useMemo)(()=>new Set(void 0===t?e.map(e=>e.name):t),[t,e]),f=e=>{if(a)return;let t=new Set(g);t.has(e)?t.delete(e):t.add(e),r(Array.from(t))};return 0===e.length?null:(0,n.jsx)("div",{className:"space-y-3",children:y.map(e=>{let t,i=p[e];if(0===i.length)return null;if(s){let e=s.toLowerCase();if(!i.some(t=>t.name.toLowerCase().includes(e)||(t.description??"").toLowerCase().includes(e)))return null}let x=b[e],h=(t=p[e]).length>0&&t.every(e=>g.has(e.name)),y=(e=>{let t=p[e];if(0===t.length)return!1;let r=t.filter(e=>g.has(e.name)).length;return r>0&&r{m(t=>({...t,[e]:!t[e]}))},children:[N?(0,n.jsx)(u.default,{className:"w-4 h-4 text-gray-500 flex-shrink-0"}):(0,n.jsx)(d.ChevronDownIcon,{className:"w-4 h-4 text-gray-500 flex-shrink-0"}),(0,n.jsx)("span",{className:"font-semibold text-gray-900 text-sm",children:x.label}),(0,n.jsx)("span",{className:`text-xs px-2 py-0.5 rounded-full ${v[x.risk]}`,children:"high"===x.risk?"High Risk":"medium"===x.risk?"Medium Risk":"low"===x.risk?"Safe":"Unclassified"}),(0,n.jsxs)("span",{className:"text-xs text-gray-500 ml-1",children:[i.filter(e=>g.has(e.name)).length,"/",i.length," allowed"]})]}),!a&&(0,n.jsxs)("div",{className:"flex items-center gap-2 ml-4",children:[(0,n.jsx)(c.Text,{className:"text-xs text-gray-500",children:h?"All on":y?"Partial":"All off"}),(0,n.jsx)(o.Checkbox,{checked:h,indeterminate:y,onChange:t=>((e,t)=>{if(a)return;let s=new Set(g);for(let r of p[e])t?s.add(r.name):s.delete(r.name);r(Array.from(s))})(e,t.target.checked),onClick:e=>e.stopPropagation()})]})]}),!N&&(0,n.jsx)("div",{className:"px-4 pt-2 pb-1 text-xs text-gray-500 bg-white border-b border-gray-100",children:x.description}),!N&&(0,n.jsx)("div",{className:"bg-white divide-y divide-gray-50",children:i.filter(e=>!s||e.name.toLowerCase().includes(s.toLowerCase())||(e.description??"").toLowerCase().includes(s.toLowerCase())).map(e=>{let t,r=(t=e.name,g.has(t));return(0,n.jsxs)("div",{className:`flex items-start gap-3 px-4 py-2.5 transition-colors hover:bg-gray-50 ${!a?"cursor-pointer":""} ${r?"":"opacity-60"}`,onClick:()=>f(e.name),children:[(0,n.jsx)(o.Checkbox,{checked:r,onChange:()=>f(e.name),disabled:a,onClick:e=>e.stopPropagation()}),(0,n.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,n.jsx)(c.Text,{className:"font-medium text-gray-900 text-sm",children:e.name}),e.description&&(0,n.jsx)(c.Text,{className:"text-xs text-gray-500 mt-0.5 leading-snug",children:e.description})]}),(0,n.jsx)("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${r?"bg-green-100 text-green-700":"bg-gray-100 text-gray-500"}`,children:r?"on":"off"})]},e.name)})})]},e)})})}],531516)},361653,e=>{"use strict";let t=(0,e.i(475254).default)("circle-alert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);e.s(["default",()=>t])},603908,e=>{"use strict";let t=(0,e.i(475254).default)("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);e.s(["default",()=>t])},841947,e=>{"use strict";let t=(0,e.i(475254).default)("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);e.s(["default",()=>t])},793130,e=>{"use strict";var t=e.i(290571),r=e.i(429427),a=e.i(371330),s=e.i(271645),l=e.i(394487),n=e.i(503269),i=e.i(214520),o=e.i(746725),c=e.i(914189),d=e.i(144279),u=e.i(294316),m=e.i(601893),p=e.i(140721),g=e.i(942803),f=e.i(233538),x=e.i(694421),h=e.i(700020),b=e.i(35889),y=e.i(998348),v=e.i(722678);let j=(0,s.createContext)(null);j.displayName="GroupContext";let w=s.Fragment,N=Object.assign((0,h.forwardRefWithAs)(function(e,t){var w;let N=(0,s.useId)(),k=(0,g.useProvidedId)(),C=(0,m.useDisabled)(),{id:S=k||`headlessui-switch-${N}`,disabled:M=C||!1,checked:_,defaultChecked:O,onChange:T,name:E,value:P,form:L,autoFocus:R=!1,...F}=e,$=(0,s.useContext)(j),[A,D]=(0,s.useState)(null),B=(0,s.useRef)(null),I=(0,u.useSyncRefs)(B,t,null===$?null:$.setSwitch,D),z=(0,i.useDefaultValue)(O),[q,K]=(0,n.useControllable)(_,T,null!=z&&z),V=(0,o.useDisposables)(),[G,H]=(0,s.useState)(!1),U=(0,c.useEvent)(()=>{H(!0),null==K||K(!q),V.nextFrame(()=>{H(!1)})}),Q=(0,c.useEvent)(e=>{if((0,f.isDisabledReactIssue7711)(e.currentTarget))return e.preventDefault();e.preventDefault(),U()}),W=(0,c.useEvent)(e=>{e.key===y.Keys.Space?(e.preventDefault(),U()):e.key===y.Keys.Enter&&(0,x.attemptSubmit)(e.currentTarget)}),J=(0,c.useEvent)(e=>e.preventDefault()),X=(0,v.useLabelledBy)(),Y=(0,b.useDescribedBy)(),{isFocusVisible:Z,focusProps:ee}=(0,r.useFocusRing)({autoFocus:R}),{isHovered:et,hoverProps:er}=(0,a.useHover)({isDisabled:M}),{pressed:ea,pressProps:es}=(0,l.useActivePress)({disabled:M}),el=(0,s.useMemo)(()=>({checked:q,disabled:M,hover:et,focus:Z,active:ea,autofocus:R,changing:G}),[q,et,Z,ea,M,G,R]),en=(0,h.mergeProps)({id:S,ref:I,role:"switch",type:(0,d.useResolveButtonType)(e,A),tabIndex:-1===e.tabIndex?0:null!=(w=e.tabIndex)?w:0,"aria-checked":q,"aria-labelledby":X,"aria-describedby":Y,disabled:M||void 0,autoFocus:R,onClick:Q,onKeyUp:W,onKeyPress:J},ee,er,es),ei=(0,s.useCallback)(()=>{if(void 0!==z)return null==K?void 0:K(z)},[K,z]),eo=(0,h.useRender)();return s.default.createElement(s.default.Fragment,null,null!=E&&s.default.createElement(p.FormFields,{disabled:M,data:{[E]:P||"on"},overrides:{type:"checkbox",checked:q},form:L,onReset:ei}),eo({ourProps:en,theirProps:F,slot:el,defaultTag:"button",name:"Switch"}))}),{Group:function(e){var t;let[r,a]=(0,s.useState)(null),[l,n]=(0,v.useLabels)(),[i,o]=(0,b.useDescriptions)(),c=(0,s.useMemo)(()=>({switch:r,setSwitch:a}),[r,a]),d=(0,h.useRender)();return s.default.createElement(o,{name:"Switch.Description",value:i},s.default.createElement(n,{name:"Switch.Label",value:l,props:{htmlFor:null==(t=c.switch)?void 0:t.id,onClick(e){r&&(e.currentTarget instanceof HTMLLabelElement&&e.preventDefault(),r.click(),r.focus({preventScroll:!0}))}}},s.default.createElement(j.Provider,{value:c},d({ourProps:{},theirProps:e,slot:{},defaultTag:w,name:"Switch.Group"}))))},Label:v.Label,Description:b.Description});var k=e.i(888288),C=e.i(95779),S=e.i(444755),M=e.i(673706),_=e.i(829087);let O=(0,M.makeClassName)("Switch"),T=s.default.forwardRef((e,r)=>{let{checked:a,defaultChecked:l=!1,onChange:n,color:i,name:o,error:c,errorMessage:d,disabled:u,required:m,tooltip:p,id:g}=e,f=(0,t.__rest)(e,["checked","defaultChecked","onChange","color","name","error","errorMessage","disabled","required","tooltip","id"]),x={bgColor:i?(0,M.getColorClassNames)(i,C.colorPalette.background).bgColor:"bg-tremor-brand dark:bg-dark-tremor-brand",ringColor:i?(0,M.getColorClassNames)(i,C.colorPalette.ring).ringColor:"ring-tremor-brand-muted dark:ring-dark-tremor-brand-muted"},[h,b]=(0,k.default)(l,a),[y,v]=(0,s.useState)(!1),{tooltipProps:j,getReferenceProps:w}=(0,_.useTooltip)(300);return s.default.createElement("div",{className:"flex flex-row items-center justify-start"},s.default.createElement(_.default,Object.assign({text:p},j)),s.default.createElement("div",Object.assign({ref:(0,M.mergeRefs)([r,j.refs.setReference]),className:(0,S.tremorTwMerge)(O("root"),"flex flex-row relative h-5")},f,w),s.default.createElement("input",{type:"checkbox",className:(0,S.tremorTwMerge)(O("input"),"absolute w-5 h-5 cursor-pointer left-0 top-0 opacity-0"),name:o,required:m,checked:h,onChange:e=>{e.preventDefault()}}),s.default.createElement(N,{checked:h,onChange:e=>{b(e),null==n||n(e)},disabled:u,className:(0,S.tremorTwMerge)(O("switch"),"w-10 h-5 group relative inline-flex shrink-0 cursor-pointer items-center justify-center rounded-tremor-full","focus:outline-none",u?"cursor-not-allowed":""),onFocus:()=>v(!0),onBlur:()=>v(!1),id:g},s.default.createElement("span",{className:(0,S.tremorTwMerge)(O("sr-only"),"sr-only")},"Switch ",h?"on":"off"),s.default.createElement("span",{"aria-hidden":"true",className:(0,S.tremorTwMerge)(O("background"),h?x.bgColor:"bg-tremor-border dark:bg-dark-tremor-border","pointer-events-none absolute mx-auto h-3 w-9 rounded-tremor-full transition-colors duration-100 ease-in-out")}),s.default.createElement("span",{"aria-hidden":"true",className:(0,S.tremorTwMerge)(O("round"),h?(0,S.tremorTwMerge)(x.bgColor,"translate-x-5 border-tremor-background dark:border-dark-tremor-background"):"translate-x-0 bg-tremor-border dark:bg-dark-tremor-border border-tremor-background dark:border-dark-tremor-background","pointer-events-none absolute left-0 inline-block h-5 w-5 transform rounded-tremor-full border-2 shadow-tremor-input duration-100 ease-in-out transition",y?(0,S.tremorTwMerge)("ring-2",x.ringColor):"")}))),c&&d?s.default.createElement("p",{className:(0,S.tremorTwMerge)(O("errorMessage"),"text-sm text-red-500 mt-1 ")},d):null)});T.displayName="Switch",e.s(["Switch",()=>T],793130)},158392,419470,e=>{"use strict";var t=e.i(843476),r=e.i(779241);let a={ttl:3600,lowest_latency_buffer:0},s=({routingStrategyArgs:e})=>{let s={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,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"max-w-3xl",children:[(0,t.jsx)("h3",{className:"text-sm font-medium text-gray-900",children:"Latency-Based Configuration"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Fine-tune latency-based routing behavior"})]}),(0,t.jsx)("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2 xl:grid-cols-3",children:Object.entries(e||a).map(([e,a])=>(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsxs)("label",{className:"block",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:e.replace(/_/g," ")}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-2",children:s[e]||""}),(0,t.jsx)(r.TextInput,{name:e,defaultValue:"object"==typeof a?JSON.stringify(a,null,2):a?.toString(),className:"font-mono text-sm w-full"})]})},e))})]}),(0,t.jsx)("div",{className:"border-t border-gray-200"})]})},l=({routerSettings:e,routerFieldsMetadata:a})=>(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"max-w-3xl",children:[(0,t.jsx)("h3",{className:"text-sm font-medium text-gray-900",children:"Reliability & Retries"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Configure retry logic and failure handling"})]}),(0,t.jsx)("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2 xl:grid-cols-3",children:Object.entries(e).filter(([e,t])=>"fallbacks"!=e&&"context_window_fallbacks"!=e&&"routing_strategy_args"!=e&&"routing_strategy"!=e&&"enable_tag_filtering"!=e).map(([e,s])=>(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsxs)("label",{className:"block",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:a[e]?.ui_field_name||e}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-2",children:a[e]?.field_description||""}),(0,t.jsx)(r.TextInput,{name:e,defaultValue:null==s||"null"===s?"":"object"==typeof s?JSON.stringify(s,null,2):s?.toString()||"",placeholder:"—",className:"font-mono text-sm w-full"})]})},e))})]});var n=e.i(199133);let i=({selectedStrategy:e,availableStrategies:r,routingStrategyDescriptions:a,routerFieldsMetadata:s,onStrategyChange:l})=>(0,t.jsxs)("div",{className:"space-y-2 max-w-3xl",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:s.routing_strategy?.ui_field_name||"Routing Strategy"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-2",children:s.routing_strategy?.field_description||""})]}),(0,t.jsx)("div",{className:"routing-strategy-select max-w-3xl",children:(0,t.jsx)(n.Select,{value:e,onChange:l,style:{width:"100%"},size:"large",children:r.map(e=>(0,t.jsx)(n.Select.Option,{value:e,label:e,children:(0,t.jsxs)("div",{className:"flex flex-col gap-0.5 py-1",children:[(0,t.jsx)("span",{className:"font-mono text-sm font-medium",children:e}),a[e]&&(0,t.jsx)("span",{className:"text-xs text-gray-500 font-normal",children:a[e]})]})},e))})})]});var o=e.i(793130);let c=({enabled:e,routerFieldsMetadata:r,onToggle:a})=>(0,t.jsx)("div",{className:"space-y-3 max-w-3xl",children:(0,t.jsxs)("div",{className:"flex items-start justify-between",children:[(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsx)("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:r.enable_tag_filtering?.ui_field_name||"Enable Tag Filtering"}),(0,t.jsxs)("p",{className:"text-xs text-gray-500 mt-0.5",children:[r.enable_tag_filtering?.field_description||"",r.enable_tag_filtering?.link&&(0,t.jsxs)(t.Fragment,{children:[" ",(0,t.jsx)("a",{href:r.enable_tag_filtering.link,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"Learn more"})]})]})]}),(0,t.jsx)(o.Switch,{checked:e,onChange:a,className:"ml-4"})]})});e.s(["default",0,({value:e,onChange:r,routerFieldsMetadata:a,availableRoutingStrategies:n,routingStrategyDescriptions:o})=>(0,t.jsxs)("div",{className:"w-full space-y-8 py-2",children:[(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"max-w-3xl",children:[(0,t.jsx)("h3",{className:"text-sm font-medium text-gray-900",children:"Routing Settings"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Configure how requests are routed to deployments"})]}),n.length>0&&(0,t.jsx)(i,{selectedStrategy:e.selectedStrategy||e.routerSettings.routing_strategy||null,availableStrategies:n,routingStrategyDescriptions:o,routerFieldsMetadata:a,onStrategyChange:t=>{r({...e,selectedStrategy:t})}}),(0,t.jsx)(c,{enabled:e.enableTagFiltering,routerFieldsMetadata:a,onToggle:t=>{r({...e,enableTagFiltering:t})}})]}),(0,t.jsx)("div",{className:"border-t border-gray-200"}),"latency-based-routing"===e.selectedStrategy&&(0,t.jsx)(s,{routingStrategyArgs:e.routerSettings.routing_strategy_args}),(0,t.jsx)(l,{routerSettings:e.routerSettings,routerFieldsMetadata:a})]})],158392);var d=e.i(994388),u=e.i(998573),m=e.i(653496),p=e.i(107233),g=e.i(271645),f=e.i(592968),x=e.i(361653),x=x;let h=(0,e.i(475254).default)("arrow-down",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);var b=e.i(37727);function y({group:e,onChange:r,availableModels:a,maxFallbacks:s}){let l=a.filter(t=>t!==e.primaryModel),i=e.fallbackModels.length{let a=[...e.fallbackModels];a.includes(t)&&(a=a.filter(e=>e!==t)),r({...e,primaryModel:t,fallbackModels:a})},showSearch:!0,filterOption:(e,t)=>(t?.label??"").toLowerCase().includes(e.toLowerCase()),options:a.map(e=>({label:e,value:e}))}),!e.primaryModel&&(0,t.jsxs)("div",{className:"mt-2 flex items-center gap-2 text-amber-600 text-xs bg-amber-50 p-2 rounded",children:[(0,t.jsx)(x.default,{className:"w-4 h-4"}),(0,t.jsx)("span",{children:"Select a model to begin configuring fallbacks"})]})]}),(0,t.jsx)("div",{className:"flex items-center justify-center -my-4 z-10",children:(0,t.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,t.jsx)(h,{className:"w-4 h-4"}),"IF FAILS, TRY..."]})}),(0,t.jsxs)("div",{className:`transition-opacity duration-300 ${!e.primaryModel?"opacity-50 pointer-events-none":"opacity-100"}`,children:[(0,t.jsxs)("label",{className:"block text-sm font-semibold text-gray-700 mb-2",children:["Fallback Chain ",(0,t.jsx)("span",{className:"text-red-500",children:"*"}),(0,t.jsxs)("span",{className:"text-xs text-gray-500 font-normal ml-2",children:["(Max ",s," fallbacks at a time)"]})]}),(0,t.jsxs)("div",{className:"bg-gray-50 rounded-xl p-4 border border-gray-200",children:[(0,t.jsxs)("div",{className:"mb-4",children:[(0,t.jsx)(n.Select,{mode:"multiple",className:"w-full",size:"large",placeholder:i?"Select fallback models to add...":`Maximum ${s} fallbacks reached`,value:e.fallbackModels,onChange:t=>{let a=t.slice(0,s);r({...e,fallbackModels:a})},disabled:!e.primaryModel,options:l.map(e=>({label:e,value:e})),optionRender:(r,a)=>{let s=e.fallbackModels.includes(r.value),l=s?e.fallbackModels.indexOf(r.value)+1:null;return(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[s&&null!==l&&(0,t.jsx)("span",{className:"flex items-center justify-center w-5 h-5 rounded bg-indigo-100 text-indigo-600 text-xs font-bold",children:l}),(0,t.jsx)("span",{children:r.label})]})},maxTagCount:"responsive",maxTagPlaceholder:e=>(0,t.jsx)(f.Tooltip,{styles:{root:{pointerEvents:"none"}},title:e.map(({value:e})=>e).join(", "),children:(0,t.jsxs)("span",{children:["+",e.length," more"]})}),showSearch:!0,filterOption:(e,t)=>(t?.label??"").toLowerCase().includes(e.toLowerCase())}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1 ml-1",children:i?`Search and select multiple models. Selected models will appear below in order. (${e.fallbackModels.length}/${s} used)`:`Maximum ${s} fallbacks reached. Remove some to add more.`})]}),(0,t.jsx)("div",{className:"space-y-2 min-h-[100px]",children:0===e.fallbackModels.length?(0,t.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,t.jsx)("span",{className:"text-sm",children:"No fallback models selected"}),(0,t.jsx)("span",{className:"text-xs mt-1",children:"Add models from the dropdown above"})]}):e.fallbackModels.map((a,s)=>(0,t.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,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.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,t.jsx)("span",{className:"text-xs font-bold",children:s+1})}),(0,t.jsx)("div",{children:(0,t.jsx)("span",{className:"font-medium text-gray-800",children:a})})]}),(0,t.jsx)("button",{type:"button",onClick:()=>{let t;return t=e.fallbackModels.filter((e,t)=>t!==s),void r({...e,fallbackModels:t})},className:"opacity-0 group-hover:opacity-100 transition-opacity text-gray-400 hover:text-red-500 p-1",children:(0,t.jsx)(b.X,{className:"w-4 h-4"})})]},`${a}-${s}`))})]})]})]})}function v({groups:e,onGroupsChange:r,availableModels:a,maxFallbacks:s=10,maxGroups:l=5}){let[n,i]=(0,g.useState)(e.length>0?e[0].id:"1");(0,g.useEffect)(()=>{e.length>0?e.some(e=>e.id===n)||i(e[0].id):i("1")},[e]);let o=()=>{if(e.length>=l)return;let t=Date.now().toString();r([...e,{id:t,primaryModel:null,fallbackModels:[]}]),i(t)},c=t=>{r(e.map(e=>e.id===t.id?t:e))},f=e.map((r,l)=>{let n=r.primaryModel?r.primaryModel:`Group ${l+1}`;return{key:r.id,label:n,closable:e.length>1,children:(0,t.jsx)(y,{group:r,onChange:c,availableModels:a,maxFallbacks:s})}});return 0===e.length?(0,t.jsxs)("div",{className:"text-center py-12 bg-gray-50 rounded-lg border border-dashed border-gray-300",children:[(0,t.jsx)("p",{className:"text-gray-500 mb-4",children:"No fallback groups configured"}),(0,t.jsx)(d.Button,{variant:"primary",onClick:o,icon:()=>(0,t.jsx)(p.Plus,{className:"w-4 h-4"}),children:"Create First Group"})]}):(0,t.jsx)(m.Tabs,{type:"editable-card",activeKey:n,onChange:i,onEdit:(t,a)=>{"add"===a?o():"remove"===a&&e.length>1&&(t=>{if(1===e.length)return u.message.warning("At least one group is required");let a=e.filter(e=>e.id!==t);r(a),n===t&&a.length>0&&i(a[a.length-1].id)})(t)},items:f,className:"fallback-tabs",tabBarStyle:{marginBottom:0},hideAdd:e.length>=l})}e.s(["FallbackSelectionForm",()=>v],419470)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/34775f0167305a22.js b/litellm/proxy/_experimental/out/_next/static/chunks/34775f0167305a22.js deleted file mode 100644 index 3181c4a61a6..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/34775f0167305a22.js +++ /dev/null @@ -1 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,59935,(e,t,r)=>{var i;let n;e.e,i=function e(){var t,r="u">typeof self?self:"u">typeof window?window:void 0!==r?r:{},i=!r.document&&!!r.postMessage,n=r.IS_PAPA_WORKER||!1,s={},o=0,a={};function l(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=v(e);t.chunkSize=parseInt(t.chunkSize),e.step||e.chunk||(t.chunkSize=null),this._handle=new f(t),(this._handle.streamer=this)._config=t}).call(this,e),this.parseChunk=function(e,t){var i=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&0=this._config.preview,n)r.postMessage({results:s,workerId:a.WORKER_ID,finished:i});else if(k(this._config.chunk)&&!t){if(this._config.chunk(s,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);this._completeResults=s=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(s.data),this._completeResults.errors=this._completeResults.errors.concat(s.errors),this._completeResults.meta=s.meta),this._completed||!i||!k(this._config.complete)||s&&s.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),i||s&&s.meta.paused||this._nextChunk(),s}this._halted=!0},this._sendError=function(e){k(this._config.error)?this._config.error(e):n&&this._config.error&&r.postMessage({workerId:a.WORKER_ID,error:e,finished:!1})}}function c(e){var t;(e=e||{}).chunkSize||(e.chunkSize=a.RemoteChunkSize),l.call(this,e),this._nextChunk=i?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),i||(t.onload=b(this._chunkLoaded,this),t.onerror=b(this._chunkError,this)),t.open(this._config.downloadRequestBody?"POST":"GET",this._input,!i),this._config.downloadRequestHeaders){var e,r,n=this._config.downloadRequestHeaders;for(r in n)t.setRequestHeader(r,n[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)}i&&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 u(e){(e=e||{}).chunkSize||(e.chunkSize=a.LocalChunkSize),l.call(this,e);var t,r,i="u">typeof FileReader;this.stream=function(e){this._input=e,r=e.slice||e.webkitSlice||e.mozSlice,i?((t=new FileReader).onload=b(this._chunkLoaded,this),t.onerror=b(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;l.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 h(e){l.call(this,e=e||{});var t=[],r=!0,i=!1;this.pause=function(){l.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){l.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(){i&&1===t.length&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),t.length?this.parseChunk(t.shift()):r=!0},this._streamData=b(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=b(function(e){this._streamCleanUp(),this._sendError(e)},this),this._streamEnd=b(function(){this._streamCleanUp(),i=!0,this._streamData("")},this),this._streamCleanUp=b(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}function f(e){var t,r,i,n,s=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,o=/^((\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)))$/,l=this,c=0,u=0,d=!1,h=!1,f=[],m={data:[],errors:[],meta:{}};function y(t){return"greedy"===e.skipEmptyLines?""===t.join("").trim():1===t.length&&0===t[0].length}function _(){if(m&&i&&(C("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+a.DefaultDelimiter+"'"),i=!1),e.skipEmptyLines&&(m.data=m.data.filter(function(e){return!y(e)})),b()){if(m)if(Array.isArray(m.data[0])){for(var t,r=0;b()&&r(e.dynamicTypingFunction&&void 0===e.dynamicTyping[t]&&(e.dynamicTyping[t]=e.dynamicTypingFunction(t)),!0===(e.dynamicTyping[t]||e.dynamicTyping))?"true"===r||"TRUE"===r||"false"!==r&&"FALSE"!==r&&((e=>{if(s.test(e)&&-0x20000000000000<(e=parseFloat(e))&&e<0x20000000000000)return 1})(r)?parseFloat(r):o.test(r)?new Date(r):""===r?null:r):r)(a=e.header?n>=f.length?"__parsed_extra":f[n]:a,l=e.transform?e.transform(l,a):l);"__parsed_extra"===a?(i[a]=i[a]||[],i[a].push(l)):i[a]=l}return e.header&&(n>f.length?C("FieldMismatch","TooManyFields","Too many fields: expected "+f.length+" fields but parsed "+n,u+r):ne.preview?r.abort():(m.data=m.data[0],n(m,l))))}),this.parse=function(n,s,o){var l=e.quoteChar||'"',l=(e.newline||(e.newline=this.guessLineEndings(n,l)),i=!1,e.delimiter?k(e.delimiter)&&(e.delimiter=e.delimiter(n),m.meta.delimiter=e.delimiter):((l=((t,r,i,n,s)=>{var o,l,c,u;s=s||[","," ","|",";",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 g(e){var t=(e=e||{}).delimiter,r=e.newline,i=e.comments,n=e.step,s=e.preview,o=e.fastMode,l=null,c=!1,u=null==e.quoteChar?'"':e.quoteChar,d=u;if(void 0!==e.escapeChar&&(d=e.escapeChar),("string"!=typeof t||-1=s)return M(!0);break}x.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:E.length,index:h}),j++}}else if(i&&0===w.length&&a.substring(h,h+b)===i){if(-1===A)return M();h=A+v,A=a.indexOf(r,h),R=a.indexOf(t,h)}else if(-1!==R&&(R=s)return M(!0)}return z();function T(e){E.push(e),S=h}function L(e){return -1!==e&&(e=a.substring(j+1,e))&&""===e.trim()?e.length:0}function z(e){return m||(void 0===e&&(e=a.substring(h)),w.push(e),h=y,T(w),C&&P()),M()}function F(e){h=e,T(w),w=[],A=a.indexOf(r,h)}function M(i){if(e.header&&!g&&E.length&&!c){var n=E[0],s=Object.create(null),o=new Set(n);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||(n=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||(c=t.skipEmptyLines),"string"==typeof t.newline&&(s=t.newline),"string"==typeof t.quoteChar&&(o=t.quoteChar),"boolean"==typeof t.header&&(i=t.header),Array.isArray(t.columns)){if(0===t.columns.length)throw Error("Option columns is empty");u=t.columns}void 0!==t.escapeChar&&(l=t.escapeChar+o),t.escapeFormulae instanceof RegExp?d=t.escapeFormulae:"boolean"==typeof t.escapeFormulae&&t.escapeFormulae&&(d=/^[=+\-@\t\r].*$/)}})(),RegExp(p(o),"g"));if("string"==typeof e&&(e=JSON.parse(e)),Array.isArray(e)){if(!e.length||Array.isArray(e[0]))return f(null,e,c);if("object"==typeof e[0])return f(u||Object.keys(e[0]),e,c)}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||u),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])),f(e.fields||[],e.data||[],c);throw Error("Unable to serialize unrecognized input");function f(e,t,r){var o="",a=("string"==typeof e&&(e=JSON.parse(e)),"string"==typeof t&&(t=JSON.parse(t)),Array.isArray(e)&&0{for(var r=0;r{"use strict";var t=e.i(843476),r=e.i(271645),i=e.i(199133),n=e.i(764205);e.s(["default",0,({onChange:e,value:s,className:o,accessToken:a,placeholder:l="Select vector stores",disabled:c=!1})=>{let[u,d]=(0,r.useState)([]),[h,f]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{(async()=>{if(a){f(!0);try{let e=await (0,n.vectorStoreListCall)(a);e.data&&d(e.data)}catch(e){console.error("Error fetching vector stores:",e)}finally{f(!1)}}})()},[a]),(0,t.jsx)("div",{children:(0,t.jsx)(i.Select,{mode:"multiple",placeholder:l,onChange:e,value:s,loading:h,className:o,allowClear:!0,options:u.map(e=>({label:`${e.vector_store_name||e.vector_store_id} (${e.vector_store_id})`,value:e.vector_store_id,title:e.vector_store_description||e.vector_store_id})),optionFilterProp:"label",showSearch:!0,style:{width:"100%"},disabled:c})})}])},689020,e=>{"use strict";var t=e.i(764205);let r=async e=>{try{let r=await (0,t.modelHubCall)(e);if(console.log("model_info:",r),r?.data.length>0){let e=r.data.map(e=>({model_group:e.model_group,mode:e?.mode}));return e.sort((e,t)=>e.model_group.localeCompare(t.model_group)),e}return[]}catch(e){throw console.error("Error fetching model info:",e),e}};e.s(["fetchAvailableModels",0,r])},983561,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let i={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"};var n=e.i(9583),s=r.forwardRef(function(e,s){return r.createElement(n.default,(0,t.default)({},e,{ref:s,icon:i}))});e.s(["RobotOutlined",0,s],983561)},955135,e=>{"use strict";var t=e.i(597440);e.s(["DeleteOutlined",()=>t.default])},309821,e=>{"use strict";e.i(247167);var t=e.i(271645);e.i(262370);var r=e.i(135551),i=e.i(201072),n=e.i(121229),s=e.i(726289),o=e.i(864517),a=e.i(343794),l=e.i(529681),c=e.i(242064),u=e.i(931067),d=e.i(209428),h=e.i(703923),f={percent:0,prefixCls:"rc-progress",strokeColor:"#2db7f5",strokeLinecap:"round",strokeWidth:1,trailColor:"#D9D9D9",trailWidth:1,gapPosition:"bottom"},p=function(){var e=(0,t.useRef)([]),r=(0,t.useRef)(null);return(0,t.useEffect)(function(){var t=Date.now(),i=!1;e.current.forEach(function(e){if(e){i=!0;var n=e.style;n.transitionDuration=".3s, .3s, .3s, .06s",r.current&&t-r.current<100&&(n.transitionDuration="0s, 0s")}}),i&&(r.current=Date.now())}),e.current},g=e.i(410160),m=e.i(392221),y=e.i(654310),_=0,v=(0,y.default)();let b=function(e){var r=t.useState(),i=(0,m.default)(r,2),n=i[0],s=i[1];return t.useEffect(function(){var e;s("rc_progress_".concat((v?(e=_,_+=1):e="TEST_OR_SSR",e)))},[]),e||n};var k=function(e){var r=e.bg,i=e.children;return t.createElement("div",{style:{width:"100%",height:"100%",background:r}},i)};function C(e,t){return Object.keys(e).map(function(r){var i=parseFloat(r),n="".concat(Math.floor(i*t),"%");return"".concat(e[r]," ").concat(n)})}var E=t.forwardRef(function(e,r){var i=e.prefixCls,n=e.color,s=e.gradientId,o=e.radius,a=e.style,l=e.ptg,c=e.strokeLinecap,u=e.strokeWidth,d=e.size,h=e.gapDegree,f=n&&"object"===(0,g.default)(n),p=d/2,m=t.createElement("circle",{className:"".concat(i,"-circle-path"),r:o,cx:p,cy:p,stroke:f?"#FFF":void 0,strokeLinecap:c,strokeWidth:u,opacity:+(0!==l),style:a,ref:r});if(!f)return m;var y="".concat(s,"-conic"),_=C(n,(360-h)/360),v=C(n,1),b="conic-gradient(from ".concat(h?"".concat(180+h/2,"deg"):"0deg",", ").concat(_.join(", "),")"),E="linear-gradient(to ".concat(h?"bottom":"top",", ").concat(v.join(", "),")");return t.createElement(t.Fragment,null,t.createElement("mask",{id:y},m),t.createElement("foreignObject",{x:0,y:0,width:d,height:d,mask:"url(#".concat(y,")")},t.createElement(k,{bg:E},t.createElement(k,{bg:b}))))}),x=function(e,t,r,i,n,s,o,a,l,c){var u=arguments.length>10&&void 0!==arguments[10]?arguments[10]:0,d=(100-i)/100*t;return"round"===l&&100!==i&&(d+=c/2)>=t&&(d=t-.01),{stroke:"string"==typeof a?a:void 0,strokeDasharray:"".concat(t,"px ").concat(e),strokeDashoffset:d+u,transform:"rotate(".concat(n+r/100*360*((360-s)/360)+(0===s?0:({bottom:0,top:180,left:90,right:-90})[o]),"deg)"),transformOrigin:"".concat(50,"px ").concat(50,"px"),transition:"stroke-dashoffset .3s ease 0s, stroke-dasharray .3s ease 0s, stroke .3s, stroke-width .06s ease .3s, opacity .3s ease 0s",fillOpacity:0}},w=["id","prefixCls","steps","strokeWidth","trailWidth","gapDegree","gapPosition","trailColor","strokeLinecap","style","className","strokeColor","percent"];function S(e){var t=null!=e?e:[];return Array.isArray(t)?t:[t]}let $=function(e){var r,i,n,s,o=(0,d.default)((0,d.default)({},f),e),l=o.id,c=o.prefixCls,m=o.steps,y=o.strokeWidth,_=o.trailWidth,v=o.gapDegree,k=void 0===v?0:v,C=o.gapPosition,$=o.trailColor,O=o.strokeLinecap,R=o.style,A=o.className,I=o.strokeColor,j=o.percent,D=(0,h.default)(o,w),T=b(l),L="".concat(T,"-gradient"),z=50-y/2,F=2*Math.PI*z,M=k>0?90+k/2:-90,P=(360-k)/360*F,N="object"===(0,g.default)(m)?m:{count:m,gap:2},W=N.count,B=N.gap,H=S(j),U=S(I),q=U.find(function(e){return e&&"object"===(0,g.default)(e)}),K=q&&"object"===(0,g.default)(q)?"butt":O,X=x(F,P,0,100,M,k,C,$,K,y),Q=p();return t.createElement("svg",(0,u.default)({className:(0,a.default)("".concat(c,"-circle"),A),viewBox:"0 0 ".concat(100," ").concat(100),style:R,id:l,role:"presentation"},D),!W&&t.createElement("circle",{className:"".concat(c,"-circle-trail"),r:z,cx:50,cy:50,stroke:$,strokeLinecap:K,strokeWidth:_||y,style:X}),W?(r=Math.round(W*(H[0]/100)),i=100/W,n=0,Array(W).fill(null).map(function(e,s){var o=s<=r-1?U[0]:$,a=o&&"object"===(0,g.default)(o)?"url(#".concat(L,")"):void 0,l=x(F,P,n,i,M,k,C,o,"butt",y,B);return n+=(P-l.strokeDashoffset+B)*100/P,t.createElement("circle",{key:s,className:"".concat(c,"-circle-path"),r:z,cx:50,cy:50,stroke:a,strokeWidth:y,opacity:1,style:l,ref:function(e){Q[s]=e}})})):(s=0,H.map(function(e,r){var i=U[r]||U[U.length-1],n=x(F,P,s,e,M,k,C,i,K,y);return s+=e,t.createElement(E,{key:r,color:i,ptg:e,radius:z,prefixCls:c,gradientId:L,style:n,strokeLinecap:K,strokeWidth:y,gapDegree:k,ref:function(e){Q[r]=e},size:100})}).reverse()))};var O=e.i(491816);e.i(765846);var R=e.i(896091);function A(e){return!e||e<0?0:e>100?100:e}function I({success:e,successPercent:t}){let r=t;return e&&"progress"in e&&(r=e.progress),e&&"percent"in e&&(r=e.percent),r}let j=(e,t,r)=>{var i,n,s,o;let a=-1,l=-1;if("step"===t){let t=r.steps,i=r.strokeWidth;"string"==typeof e||void 0===e?(a="small"===e?2:14,l=null!=i?i:8):"number"==typeof e?[a,l]=[e,e]:[a=14,l=8]=Array.isArray(e)?e:[e.width,e.height],a*=t}else if("line"===t){let t=null==r?void 0:r.strokeWidth;"string"==typeof e||void 0===e?l=t||("small"===e?6:8):"number"==typeof e?[a,l]=[e,e]:[a=-1,l=8]=Array.isArray(e)?e:[e.width,e.height]}else("circle"===t||"dashboard"===t)&&("string"==typeof e||void 0===e?[a,l]="small"===e?[60,60]:[120,120]:"number"==typeof e?[a,l]=[e,e]:Array.isArray(e)&&(a=null!=(n=null!=(i=e[0])?i:e[1])?n:120,l=null!=(o=null!=(s=e[0])?s:e[1])?o:120));return[a,l]},D=e=>{let{prefixCls:r,trailColor:i=null,strokeLinecap:n="round",gapPosition:s,gapDegree:o,width:l=120,type:c,children:u,success:d,size:h=l,steps:f}=e,[p,g]=j(h,"circle"),{strokeWidth:m}=e;void 0===m&&(m=Math.max(3/p*100,6));let y=t.useMemo(()=>o||0===o?o:"dashboard"===c?75:void 0,[o,c]),_=(({percent:e,success:t,successPercent:r})=>{let i=A(I({success:t,successPercent:r}));return[i,A(A(e)-i)]})(e),v="[object Object]"===Object.prototype.toString.call(e.strokeColor),b=(({success:e={},strokeColor:t})=>{let{strokeColor:r}=e;return[r||R.presetPrimaryColors.green,t||null]})({success:d,strokeColor:e.strokeColor}),k=(0,a.default)(`${r}-inner`,{[`${r}-circle-gradient`]:v}),C=t.createElement($,{steps:f,percent:f?_[1]:_,strokeWidth:m,trailWidth:m,strokeColor:f?b[1]:b,strokeLinecap:n,trailColor:i,prefixCls:r,gapDegree:y,gapPosition:s||"dashboard"===c&&"bottom"||void 0}),E=p<=20,x=t.createElement("div",{className:k,style:{width:p,height:g,fontSize:.15*p+6}},C,!E&&u);return E?t.createElement(O.default,{title:u},x):x};e.i(296059);var T=e.i(694758),L=e.i(915654),z=e.i(183293),F=e.i(246422),M=e.i(838378);let P="--progress-line-stroke-color",N="--progress-percent",W=e=>{let t=e?"100%":"-100%";return new T.Keyframes(`antProgress${e?"RTL":"LTR"}Active`,{"0%":{transform:`translateX(${t}) scaleX(0)`,opacity:.1},"20%":{transform:`translateX(${t}) scaleX(0)`,opacity:.5},to:{transform:"translateX(0) scaleX(1)",opacity:0}})},B=(0,F.genStyleHooks)("Progress",e=>{let t=e.calc(e.marginXXS).div(2).equal(),r=(0,M.mergeToken)(e,{progressStepMarginInlineEnd:t,progressStepMinWidth:t,progressActiveMotionDuration:"2.4s"});return[(e=>{let{componentCls:t,iconCls:r}=e;return{[t]:Object.assign(Object.assign({},(0,z.resetComponent)(e)),{display:"inline-block","&-rtl":{direction:"rtl"},"&-line":{position:"relative",width:"100%",fontSize:e.fontSize},[`${t}-outer`]:{display:"inline-flex",alignItems:"center",width:"100%"},[`${t}-inner`]:{position:"relative",display:"inline-block",width:"100%",flex:1,overflow:"hidden",verticalAlign:"middle",backgroundColor:e.remainingColor,borderRadius:e.lineBorderRadius},[`${t}-inner:not(${t}-circle-gradient)`]:{[`${t}-circle-path`]:{stroke:e.defaultColor}},[`${t}-success-bg, ${t}-bg`]:{position:"relative",background:e.defaultColor,borderRadius:e.lineBorderRadius,transition:`all ${e.motionDurationSlow} ${e.motionEaseInOutCirc}`},[`${t}-layout-bottom`]:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",[`${t}-text`]:{width:"max-content",marginInlineStart:0,marginTop:e.marginXXS}},[`${t}-bg`]:{overflow:"hidden","&::after":{content:'""',background:{_multi_value_:!0,value:["inherit",`var(${P})`]},height:"100%",width:`calc(1 / var(${N}) * 100%)`,display:"block"},[`&${t}-bg-inner`]:{minWidth:"max-content","&::after":{content:"none"},[`${t}-text-inner`]:{color:e.colorWhite,[`&${t}-text-bright`]:{color:"rgba(0, 0, 0, 0.45)"}}}},[`${t}-success-bg`]:{position:"absolute",insetBlockStart:0,insetInlineStart:0,backgroundColor:e.colorSuccess},[`${t}-text`]:{display:"inline-block",marginInlineStart:e.marginXS,color:e.colorText,lineHeight:1,width:"2em",whiteSpace:"nowrap",textAlign:"start",verticalAlign:"middle",wordBreak:"normal",[r]:{fontSize:e.fontSize},[`&${t}-text-outer`]:{width:"max-content"},[`&${t}-text-outer${t}-text-start`]:{width:"max-content",marginInlineStart:0,marginInlineEnd:e.marginXS}},[`${t}-text-inner`]:{display:"flex",justifyContent:"center",alignItems:"center",width:"100%",height:"100%",marginInlineStart:0,padding:`0 ${(0,L.unit)(e.paddingXXS)}`,[`&${t}-text-start`]:{justifyContent:"start"},[`&${t}-text-end`]:{justifyContent:"end"}},[`&${t}-status-active`]:{[`${t}-bg::before`]:{position:"absolute",inset:0,backgroundColor:e.colorBgContainer,borderRadius:e.lineBorderRadius,opacity:0,animationName:W(),animationDuration:e.progressActiveMotionDuration,animationTimingFunction:e.motionEaseOutQuint,animationIterationCount:"infinite",content:'""'}},[`&${t}-rtl${t}-status-active`]:{[`${t}-bg::before`]:{animationName:W(!0)}},[`&${t}-status-exception`]:{[`${t}-bg`]:{backgroundColor:e.colorError},[`${t}-text`]:{color:e.colorError}},[`&${t}-status-exception ${t}-inner:not(${t}-circle-gradient)`]:{[`${t}-circle-path`]:{stroke:e.colorError}},[`&${t}-status-success`]:{[`${t}-bg`]:{backgroundColor:e.colorSuccess},[`${t}-text`]:{color:e.colorSuccess}},[`&${t}-status-success ${t}-inner:not(${t}-circle-gradient)`]:{[`${t}-circle-path`]:{stroke:e.colorSuccess}}})}})(r),(e=>{let{componentCls:t,iconCls:r}=e;return{[t]:{[`${t}-circle-trail`]:{stroke:e.remainingColor},[`&${t}-circle ${t}-inner`]:{position:"relative",lineHeight:1,backgroundColor:"transparent"},[`&${t}-circle ${t}-text`]:{position:"absolute",insetBlockStart:"50%",insetInlineStart:0,width:"100%",margin:0,padding:0,color:e.circleTextColor,fontSize:e.circleTextFontSize,lineHeight:1,whiteSpace:"normal",textAlign:"center",transform:"translateY(-50%)",[r]:{fontSize:e.circleIconFontSize}},[`${t}-circle&-status-exception`]:{[`${t}-text`]:{color:e.colorError}},[`${t}-circle&-status-success`]:{[`${t}-text`]:{color:e.colorSuccess}}},[`${t}-inline-circle`]:{lineHeight:1,[`${t}-inner`]:{verticalAlign:"bottom"}}}})(r),(e=>{let{componentCls:t}=e;return{[t]:{[`${t}-steps`]:{display:"inline-block","&-outer":{display:"flex",flexDirection:"row",alignItems:"center"},"&-item":{flexShrink:0,minWidth:e.progressStepMinWidth,marginInlineEnd:e.progressStepMarginInlineEnd,backgroundColor:e.remainingColor,transition:`all ${e.motionDurationSlow}`,"&-active":{backgroundColor:e.defaultColor}}}}}})(r),(e=>{let{componentCls:t,iconCls:r}=e;return{[t]:{[`${t}-small&-line, ${t}-small&-line ${t}-text ${r}`]:{fontSize:e.fontSizeSM}}}})(r)]},e=>({circleTextColor:e.colorText,defaultColor:e.colorInfo,remainingColor:e.colorFillSecondary,lineBorderRadius:100,circleTextFontSize:"1em",circleIconFontSize:`${e.fontSize/e.fontSizeSM}em`}));var H=function(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&0>t.indexOf(i)&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,i=Object.getOwnPropertySymbols(e);nt.indexOf(i[n])&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]]);return r};let U=e=>{let{prefixCls:r,direction:i,percent:n,size:s,strokeWidth:o,strokeColor:l,strokeLinecap:c="round",children:u,trailColor:d=null,percentPosition:h,success:f}=e,{align:p,type:g}=h,m=l&&"string"!=typeof l?((e,t)=>{let{from:r=R.presetPrimaryColors.blue,to:i=R.presetPrimaryColors.blue,direction:n="rtl"===t?"to left":"to right"}=e,s=H(e,["from","to","direction"]);if(0!==Object.keys(s).length){let e,t=(e=[],Object.keys(s).forEach(t=>{let r=Number.parseFloat(t.replace(/%/g,""));Number.isNaN(r)||e.push({key:r,value:s[t]})}),(e=e.sort((e,t)=>e.key-t.key)).map(({key:e,value:t})=>`${t} ${e}%`).join(", ")),r=`linear-gradient(${n}, ${t})`;return{background:r,[P]:r}}let o=`linear-gradient(${n}, ${r}, ${i})`;return{background:o,[P]:o}})(l,i):{[P]:l,background:l},y="square"===c||"butt"===c?0:void 0,[_,v]=j(null!=s?s:[-1,o||("small"===s?6:8)],"line",{strokeWidth:o}),b=Object.assign(Object.assign({width:`${A(n)}%`,height:v,borderRadius:y},m),{[N]:A(n)/100}),k=I(e),C={width:`${A(k)}%`,height:v,borderRadius:y,backgroundColor:null==f?void 0:f.strokeColor},E=t.createElement("div",{className:`${r}-inner`,style:{backgroundColor:d||void 0,borderRadius:y}},t.createElement("div",{className:(0,a.default)(`${r}-bg`,`${r}-bg-${g}`),style:b},"inner"===g&&u),void 0!==k&&t.createElement("div",{className:`${r}-success-bg`,style:C})),x="outer"===g&&"start"===p,w="outer"===g&&"end"===p;return"outer"===g&&"center"===p?t.createElement("div",{className:`${r}-layout-bottom`},E,u):t.createElement("div",{className:`${r}-outer`,style:{width:_<0?"100%":_}},x&&u,E,w&&u)},q=e=>{let{size:r,steps:i,rounding:n=Math.round,percent:s=0,strokeWidth:o=8,strokeColor:l,trailColor:c=null,prefixCls:u,children:d}=e,h=n(s/100*i),[f,p]=j(null!=r?r:["small"===r?2:14,o],"step",{steps:i,strokeWidth:o}),g=f/i,m=Array.from({length:i});for(let e=0;et.indexOf(i)&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,i=Object.getOwnPropertySymbols(e);nt.indexOf(i[n])&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]]);return r};let X=["normal","exception","active","success"],Q=t.forwardRef((e,u)=>{let d,{prefixCls:h,className:f,rootClassName:p,steps:g,strokeColor:m,percent:y=0,size:_="default",showInfo:v=!0,type:b="line",status:k,format:C,style:E,percentPosition:x={}}=e,w=K(e,["prefixCls","className","rootClassName","steps","strokeColor","percent","size","showInfo","type","status","format","style","percentPosition"]),{align:S="end",type:$="outer"}=x,O=Array.isArray(m)?m[0]:m,R="string"==typeof m||Array.isArray(m)?m:void 0,T=t.useMemo(()=>{if(O){let e="string"==typeof O?O:Object.values(O)[0];return new r.FastColor(e).isLight()}return!1},[m]),L=t.useMemo(()=>{var t,r;let i=I(e);return Number.parseInt(void 0!==i?null==(t=null!=i?i:0)?void 0:t.toString():null==(r=null!=y?y:0)?void 0:r.toString(),10)},[y,e.success,e.successPercent]),z=t.useMemo(()=>!X.includes(k)&&L>=100?"success":k||"normal",[k,L]),{getPrefixCls:F,direction:M,progress:P}=t.useContext(c.ConfigContext),N=F("progress",h),[W,H,Q]=B(N),J="line"===b,Y=J&&!g,Z=t.useMemo(()=>{let r;if(!v)return null;let l=I(e),c=C||(e=>`${e}%`),u=J&&T&&"inner"===$;return"inner"===$||C||"exception"!==z&&"success"!==z?r=c(A(y),A(l)):"exception"===z?r=J?t.createElement(s.default,null):t.createElement(o.default,null):"success"===z&&(r=J?t.createElement(i.default,null):t.createElement(n.default,null)),t.createElement("span",{className:(0,a.default)(`${N}-text`,{[`${N}-text-bright`]:u,[`${N}-text-${S}`]:Y,[`${N}-text-${$}`]:Y}),title:"string"==typeof r?r:void 0},r)},[v,y,L,z,b,N,C]);"line"===b?d=g?t.createElement(q,Object.assign({},e,{strokeColor:R,prefixCls:N,steps:"object"==typeof g?g.count:g}),Z):t.createElement(U,Object.assign({},e,{strokeColor:O,prefixCls:N,direction:M,percentPosition:{align:S,type:$}}),Z):("circle"===b||"dashboard"===b)&&(d=t.createElement(D,Object.assign({},e,{strokeColor:O,prefixCls:N,progressStatus:z}),Z));let G=(0,a.default)(N,`${N}-status-${z}`,{[`${N}-${"dashboard"===b&&"circle"||b}`]:"line"!==b,[`${N}-inline-circle`]:"circle"===b&&j(_,"circle")[0]<=20,[`${N}-line`]:Y,[`${N}-line-align-${S}`]:Y,[`${N}-line-position-${$}`]:Y,[`${N}-steps`]:g,[`${N}-show-info`]:v,[`${N}-${_}`]:"string"==typeof _,[`${N}-rtl`]:"rtl"===M},null==P?void 0:P.className,f,p,H,Q);return W(t.createElement("div",Object.assign({ref:u,style:Object.assign(Object.assign({},null==P?void 0:P.style),E),className:G,role:"progressbar","aria-valuenow":L,"aria-valuemin":0,"aria-valuemax":100},(0,l.default)(w,["trailColor","strokeWidth","width","gapDegree","gapPosition","strokeLinecap","success","successPercent"])),d))});e.s(["default",0,Q],309821)},597440,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let i={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M360 184h-8c4.4 0 8-3.6 8-8v8h304v-8c0 4.4 3.6 8 8 8h-8v72h72v-80c0-35.3-28.7-64-64-64H352c-35.3 0-64 28.7-64 64v80h72v-72zm504 72H160c-17.7 0-32 14.3-32 32v32c0 4.4 3.6 8 8 8h60.4l24.7 523c1.6 34.1 29.8 61 63.9 61h454c34.2 0 62.3-26.8 63.9-61l24.7-523H888c4.4 0 8-3.6 8-8v-32c0-17.7-14.3-32-32-32zM731.3 840H292.7l-24.2-512h487l-24.2 512z"}}]},name:"delete",theme:"outlined"};var n=e.i(9583),s=r.forwardRef(function(e,s){return r.createElement(n.default,(0,t.default)({},e,{ref:s,icon:i}))});e.s(["default",0,s],597440)},737434,e=>{"use strict";var t=e.i(184163);e.s(["DownloadOutlined",()=>t.default])}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/3569f12d1e9d5e0d.js b/litellm/proxy/_experimental/out/_next/static/chunks/3569f12d1e9d5e0d.js new file mode 100644 index 00000000000..8a99e192931 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/3569f12d1e9d5e0d.js @@ -0,0 +1 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,788191,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={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 372z"}},{tag:"path",attrs:{d:"M719.4 499.1l-296.1-215A15.9 15.9 0 00398 297v430c0 13.1 14.8 20.5 25.3 12.9l296.1-215a15.9 15.9 0 000-25.8zm-257.6 134V390.9L628.5 512 461.8 633.1z"}}]},name:"play-circle",theme:"outlined"};var r=e.i(9583),i=a.forwardRef(function(e,i){return a.createElement(r.default,(0,t.default)({},e,{ref:i,icon:s}))});e.s(["PlayCircleOutlined",0,i],788191)},399219,e=>{"use strict";let t=(0,e.i(475254).default)("chevron-up",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);e.s(["default",()=>t])},582458,e=>{"use strict";let t=(0,e.i(475254).default)("triangle-alert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);e.s(["default",()=>t])},19732,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M512 472a40 40 0 1080 0 40 40 0 10-80 0zm367 352.9L696.3 352V178H768v-68H256v68h71.7v174L145 824.9c-2.8 7.4-4.3 15.2-4.3 23.1 0 35.3 28.7 64 64 64h614.6c7.9 0 15.7-1.5 23.1-4.3 33-12.7 49.4-49.8 36.6-82.8zM395.7 364.7V180h232.6v184.7L719.2 600c-20.7-5.3-42.1-8-63.9-8-61.2 0-119.2 21.5-165.3 60a188.78 188.78 0 01-121.3 43.9c-32.7 0-64.1-8.3-91.8-23.7l118.8-307.5zM210.5 844l41.7-107.8c35.7 18.1 75.4 27.8 116.6 27.8 61.2 0 119.2-21.5 165.3-60 33.9-28.2 76.3-43.9 121.3-43.9 35 0 68.4 9.5 97.6 27.1L813.5 844h-603z"}}]},name:"experiment",theme:"outlined"};var r=e.i(9583),i=a.forwardRef(function(e,i){return a.createElement(r.default,(0,t.default)({},e,{ref:i,icon:s}))});e.s(["ExperimentOutlined",0,i],19732)},438957,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M608 112c-167.9 0-304 136.1-304 304 0 70.3 23.9 135 63.9 186.5l-41.1 41.1-62.3-62.3a8.15 8.15 0 00-11.4 0l-39.8 39.8a8.15 8.15 0 000 11.4l62.3 62.3-44.9 44.9-62.3-62.3a8.15 8.15 0 00-11.4 0l-39.8 39.8a8.15 8.15 0 000 11.4l62.3 62.3-65.3 65.3a8.03 8.03 0 000 11.3l42.3 42.3c3.1 3.1 8.2 3.1 11.3 0l253.6-253.6A304.06 304.06 0 00608 720c167.9 0 304-136.1 304-304S775.9 112 608 112zm161.2 465.2C726.2 620.3 668.9 644 608 644c-60.9 0-118.2-23.7-161.2-66.8-43.1-43-66.8-100.3-66.8-161.2 0-60.9 23.7-118.2 66.8-161.2 43-43.1 100.3-66.8 161.2-66.8 60.9 0 118.2 23.7 161.2 66.8 43.1 43 66.8 100.3 66.8 161.2 0 60.9-23.7 118.2-66.8 161.2z"}}]},name:"key",theme:"outlined"};var r=e.i(9583),i=a.forwardRef(function(e,i){return a.createElement(r.default,(0,t.default)({},e,{ref:i,icon:s}))});e.s(["KeyOutlined",0,i],438957)},366308,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={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"};var r=e.i(9583),i=a.forwardRef(function(e,i){return a.createElement(r.default,(0,t.default)({},e,{ref:i,icon:s}))});e.s(["ToolOutlined",0,i],366308)},313603,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M924.8 625.7l-65.5-56c3.1-19 4.7-38.4 4.7-57.8s-1.6-38.8-4.7-57.8l65.5-56a32.03 32.03 0 009.3-35.2l-.9-2.6a443.74 443.74 0 00-79.7-137.9l-1.8-2.1a32.12 32.12 0 00-35.1-9.5l-81.3 28.9c-30-24.6-63.5-44-99.7-57.6l-15.7-85a32.05 32.05 0 00-25.8-25.7l-2.7-.5c-52.1-9.4-106.9-9.4-159 0l-2.7.5a32.05 32.05 0 00-25.8 25.7l-15.8 85.4a351.86 351.86 0 00-99 57.4l-81.9-29.1a32 32 0 00-35.1 9.5l-1.8 2.1a446.02 446.02 0 00-79.7 137.9l-.9 2.6c-4.5 12.5-.8 26.5 9.3 35.2l66.3 56.6c-3.1 18.8-4.6 38-4.6 57.1 0 19.2 1.5 38.4 4.6 57.1L99 625.5a32.03 32.03 0 00-9.3 35.2l.9 2.6c18.1 50.4 44.9 96.9 79.7 137.9l1.8 2.1a32.12 32.12 0 0035.1 9.5l81.9-29.1c29.8 24.5 63.1 43.9 99 57.4l15.8 85.4a32.05 32.05 0 0025.8 25.7l2.7.5a449.4 449.4 0 00159 0l2.7-.5a32.05 32.05 0 0025.8-25.7l15.7-85a350 350 0 0099.7-57.6l81.3 28.9a32 32 0 0035.1-9.5l1.8-2.1c34.8-41.1 61.6-87.5 79.7-137.9l.9-2.6c4.5-12.3.8-26.3-9.3-35zM788.3 465.9c2.5 15.1 3.8 30.6 3.8 46.1s-1.3 31-3.8 46.1l-6.6 40.1 74.7 63.9a370.03 370.03 0 01-42.6 73.6L721 702.8l-31.4 25.8c-23.9 19.6-50.5 35-79.3 45.8l-38.1 14.3-17.9 97a377.5 377.5 0 01-85 0l-17.9-97.2-37.8-14.5c-28.5-10.8-55-26.2-78.7-45.7l-31.4-25.9-93.4 33.2c-17-22.9-31.2-47.6-42.6-73.6l75.5-64.5-6.5-40c-2.4-14.9-3.7-30.3-3.7-45.5 0-15.3 1.2-30.6 3.7-45.5l6.5-40-75.5-64.5c11.3-26.1 25.6-50.7 42.6-73.6l93.4 33.2 31.4-25.9c23.7-19.5 50.2-34.9 78.7-45.7l37.9-14.3 17.9-97.2c28.1-3.2 56.8-3.2 85 0l17.9 97 38.1 14.3c28.7 10.8 55.4 26.2 79.3 45.8l31.4 25.8 92.8-32.9c17 22.9 31.2 47.6 42.6 73.6L781.8 426l6.5 39.9zM512 326c-97.2 0-176 78.8-176 176s78.8 176 176 176 176-78.8 176-176-78.8-176-176-176zm79.2 255.2A111.6 111.6 0 01512 614c-29.9 0-58-11.7-79.2-32.8A111.6 111.6 0 01400 502c0-29.9 11.7-58 32.8-79.2C454 401.6 482.1 390 512 390c29.9 0 58 11.6 79.2 32.8A111.6 111.6 0 01624 502c0 29.9-11.7 58-32.8 79.2z"}}]},name:"setting",theme:"outlined"};var r=e.i(9583),i=a.forwardRef(function(e,i){return a.createElement(r.default,(0,t.default)({},e,{ref:i,icon:s}))});e.s(["SettingOutlined",0,i],313603)},232164,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M483.2 790.3L861.4 412c1.7-1.7 2.5-4 2.3-6.3l-25.5-301.4c-.7-7.8-6.8-13.9-14.6-14.6L522.2 64.3c-2.3-.2-4.7.6-6.3 2.3L137.7 444.8a8.03 8.03 0 000 11.3l334.2 334.2c3.1 3.2 8.2 3.2 11.3 0zm62.6-651.7l224.6 19 19 224.6L477.5 694 233.9 450.5l311.9-311.9zm60.16 186.23a48 48 0 1067.88-67.89 48 48 0 10-67.88 67.89zM889.7 539.8l-39.6-39.5a8.03 8.03 0 00-11.3 0l-362 361.3-237.6-237a8.03 8.03 0 00-11.3 0l-39.6 39.5a8.03 8.03 0 000 11.3l243.2 242.8 39.6 39.5c3.1 3.1 8.2 3.1 11.3 0l407.3-406.6c3.1-3.1 3.1-8.2 0-11.3z"}}]},name:"tags",theme:"outlined"};var r=e.i(9583),i=a.forwardRef(function(e,i){return a.createElement(r.default,(0,t.default)({},e,{ref:i,icon:s}))});e.s(["TagsOutlined",0,i],232164)},210612,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M832 64H192c-17.7 0-32 14.3-32 32v832c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V96c0-17.7-14.3-32-32-32zm-600 72h560v208H232V136zm560 480H232V408h560v208zm0 272H232V680h560v208zM304 240a40 40 0 1080 0 40 40 0 10-80 0zm0 272a40 40 0 1080 0 40 40 0 10-80 0zm0 272a40 40 0 1080 0 40 40 0 10-80 0z"}}]},name:"database",theme:"outlined"};var r=e.i(9583),i=a.forwardRef(function(e,i){return a.createElement(r.default,(0,t.default)({},e,{ref:i,icon:s}))});e.s(["DatabaseOutlined",0,i],210612)},218129,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M917.7 148.8l-42.4-42.4c-1.6-1.6-3.6-2.3-5.7-2.3s-4.1.8-5.7 2.3l-76.1 76.1a199.27 199.27 0 00-112.1-34.3c-51.2 0-102.4 19.5-141.5 58.6L432.3 308.7a8.03 8.03 0 000 11.3L704 591.7c1.6 1.6 3.6 2.3 5.7 2.3 2 0 4.1-.8 5.7-2.3l101.9-101.9c68.9-69 77-175.7 24.3-253.5l76.1-76.1c3.1-3.2 3.1-8.3 0-11.4zM769.1 441.7l-59.4 59.4-186.8-186.8 59.4-59.4c24.9-24.9 58.1-38.7 93.4-38.7 35.3 0 68.4 13.7 93.4 38.7 24.9 24.9 38.7 58.1 38.7 93.4 0 35.3-13.8 68.4-38.7 93.4zm-190.2 105a8.03 8.03 0 00-11.3 0L501 613.3 410.7 523l66.7-66.7c3.1-3.1 3.1-8.2 0-11.3L441 408.6a8.03 8.03 0 00-11.3 0L363 475.3l-43-43a7.85 7.85 0 00-5.7-2.3c-2 0-4.1.8-5.7 2.3L206.8 534.2c-68.9 69-77 175.7-24.3 253.5l-76.1 76.1a8.03 8.03 0 000 11.3l42.4 42.4c1.6 1.6 3.6 2.3 5.7 2.3s4.1-.8 5.7-2.3l76.1-76.1c33.7 22.9 72.9 34.3 112.1 34.3 51.2 0 102.4-19.5 141.5-58.6l101.9-101.9c3.1-3.1 3.1-8.2 0-11.3l-43-43 66.7-66.7c3.1-3.1 3.1-8.2 0-11.3l-36.6-36.2zM441.7 769.1a131.32 131.32 0 01-93.4 38.7c-35.3 0-68.4-13.7-93.4-38.7a131.32 131.32 0 01-38.7-93.4c0-35.3 13.7-68.4 38.7-93.4l59.4-59.4 186.8 186.8-59.4 59.4z"}}]},name:"api",theme:"outlined"};var r=e.i(9583),i=a.forwardRef(function(e,i){return a.createElement(r.default,(0,t.default)({},e,{ref:i,icon:s}))});e.s(["ApiOutlined",0,i],218129)},878894,664659,531278,e=>{"use strict";var t=e.i(582458);e.s(["AlertTriangle",()=>t.default],878894);var a=e.i(631171);e.s(["ChevronDown",()=>a.default],664659);let s=(0,e.i(475254).default)("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);e.s(["Loader2",()=>s],531278)},477189,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M464 144H160c-8.8 0-16 7.2-16 16v304c0 8.8 7.2 16 16 16h304c8.8 0 16-7.2 16-16V160c0-8.8-7.2-16-16-16zm-52 268H212V212h200v200zm452-268H560c-8.8 0-16 7.2-16 16v304c0 8.8 7.2 16 16 16h304c8.8 0 16-7.2 16-16V160c0-8.8-7.2-16-16-16zm-52 268H612V212h200v200zM464 544H160c-8.8 0-16 7.2-16 16v304c0 8.8 7.2 16 16 16h304c8.8 0 16-7.2 16-16V560c0-8.8-7.2-16-16-16zm-52 268H212V612h200v200zm452-268H560c-8.8 0-16 7.2-16 16v304c0 8.8 7.2 16 16 16h304c8.8 0 16-7.2 16-16V560c0-8.8-7.2-16-16-16zm-52 268H612V612h200v200z"}}]},name:"appstore",theme:"outlined"};var r=e.i(9583),i=a.forwardRef(function(e,i){return a.createElement(r.default,(0,t.default)({},e,{ref:i,icon:s}))});e.s(["AppstoreOutlined",0,i],477189)},153702,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M888 792H200V168c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v688c0 4.4 3.6 8 8 8h752c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm-600-80h56c4.4 0 8-3.6 8-8V560c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v144c0 4.4 3.6 8 8 8zm152 0h56c4.4 0 8-3.6 8-8V384c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v320c0 4.4 3.6 8 8 8zm152 0h56c4.4 0 8-3.6 8-8V462c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v242c0 4.4 3.6 8 8 8zm152 0h56c4.4 0 8-3.6 8-8V304c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v400c0 4.4 3.6 8 8 8z"}}]},name:"bar-chart",theme:"outlined"};var r=e.i(9583),i=a.forwardRef(function(e,i){return a.createElement(r.default,(0,t.default)({},e,{ref:i,icon:s}))});e.s(["BarChartOutlined",0,i],153702)},299251,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M894 462c30.9 0 43.8-39.7 18.7-58L530.8 126.2a31.81 31.81 0 00-37.6 0L111.3 404c-25.1 18.2-12.2 58 18.8 58H192v374h-72c-4.4 0-8 3.6-8 8v52c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-52c0-4.4-3.6-8-8-8h-72V462h62zM512 196.7l271.1 197.2H240.9L512 196.7zM264 462h117v374H264V462zm189 0h117v374H453V462zm307 374H642V462h118v374z"}}]},name:"bank",theme:"outlined"};var r=e.i(9583),i=a.forwardRef(function(e,i){return a.createElement(r.default,(0,t.default)({},e,{ref:i,icon:s}))});e.s(["BankOutlined",0,i],299251)},777579,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M888 792H200V168c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v688c0 4.4 3.6 8 8 8h752c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zM305.8 637.7c3.1 3.1 8.1 3.1 11.3 0l138.3-137.6L583 628.5c3.1 3.1 8.2 3.1 11.3 0l275.4-275.3c3.1-3.1 3.1-8.2 0-11.3l-39.6-39.6a8.03 8.03 0 00-11.3 0l-230 229.9L461.4 404a8.03 8.03 0 00-11.3 0L266.3 586.7a8.03 8.03 0 000 11.3l39.5 39.7z"}}]},name:"line-chart",theme:"outlined"};var r=e.i(9583),i=a.forwardRef(function(e,i){return a.createElement(r.default,(0,t.default)({},e,{ref:i,icon:s}))});e.s(["LineChartOutlined",0,i],777579)},372943,899268,e=>{"use strict";e.i(247167);var t=e.i(8211),a=e.i(271645),s=e.i(343794),r=e.i(529681),i=e.i(242064),l=e.i(704914),n=e.i(876556),c=e.i(290224),d=e.i(251224),o=function(e,t){var a={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&0>t.indexOf(s)&&(a[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,s=Object.getOwnPropertySymbols(e);rt.indexOf(s[r])&&Object.prototype.propertyIsEnumerable.call(e,s[r])&&(a[s[r]]=e[s[r]]);return a};function m({suffixCls:e,tagName:t,displayName:s}){return s=>a.forwardRef((r,i)=>a.createElement(s,Object.assign({ref:i,suffixCls:e,tagName:t},r)))}let u=a.forwardRef((e,t)=>{let{prefixCls:r,suffixCls:l,className:n,tagName:c}=e,m=o(e,["prefixCls","suffixCls","className","tagName"]),{getPrefixCls:u}=a.useContext(i.ConfigContext),f=u("layout",r),[h,x,g]=(0,d.default)(f),v=l?`${f}-${l}`:f;return h(a.createElement(c,Object.assign({className:(0,s.default)(r||v,n,x,g),ref:t},m)))}),f=a.forwardRef((e,m)=>{let{direction:u}=a.useContext(i.ConfigContext),[f,h]=a.useState([]),{prefixCls:x,className:g,rootClassName:v,children:y,hasSider:p,tagName:b,style:N}=e,w=o(e,["prefixCls","className","rootClassName","children","hasSider","tagName","style"]),j=(0,r.default)(w,["suffixCls"]),{getPrefixCls:L,className:z,style:M}=(0,i.useComponentConfig)("layout"),O=L("layout",x),k="boolean"==typeof p?p:!!f.length||(0,n.default)(y).some(e=>e.type===c.default),[C,H,_]=(0,d.default)(O),V=(0,s.default)(O,{[`${O}-has-sider`]:k,[`${O}-rtl`]:"rtl"===u},z,g,v,H,_),E=a.useMemo(()=>({siderHook:{addSider:e=>{h(a=>[].concat((0,t.default)(a),[e]))},removeSider:e=>{h(t=>t.filter(t=>t!==e))}}}),[]);return C(a.createElement(l.LayoutContext.Provider,{value:E},a.createElement(b,Object.assign({ref:m,className:V,style:Object.assign(Object.assign({},M),N)},j),y)))}),h=m({tagName:"div",displayName:"Layout"})(f),x=m({suffixCls:"header",tagName:"header",displayName:"Header"})(u),g=m({suffixCls:"footer",tagName:"footer",displayName:"Footer"})(u),v=m({suffixCls:"content",tagName:"main",displayName:"Content"})(u);h.Header=x,h.Footer=g,h.Content=v,h.Sider=c.default,h._InternalSiderContext=c.SiderContext,e.s(["Layout",0,h],372943);var y=e.i(60699);e.s(["Menu",()=>y.default],899268)},592143,e=>{"use strict";var t=e.i(609587);e.s(["ConfigProvider",()=>t.default])},182399,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M856 376H648V168c0-8.8-7.2-16-16-16H168c-8.8 0-16 7.2-16 16v464c0 8.8 7.2 16 16 16h208v208c0 8.8 7.2 16 16 16h464c8.8 0 16-7.2 16-16V392c0-8.8-7.2-16-16-16zm-480 16v188H220V220h360v156H392c-8.8 0-16 7.2-16 16zm204 52v136H444V444h136zm224 360H444V648h188c8.8 0 16-7.2 16-16V444h156v360z"}}]},name:"block",theme:"outlined"};var r=e.i(9583),i=a.forwardRef(function(e,i){return a.createElement(r.default,(0,t.default)({},e,{ref:i,icon:s}))});e.s(["BlockOutlined",0,i],182399)},457202,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M296 250c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8h384c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8H296zm184 144H296c-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-8zm-48 458H208V148h560v320c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8V108c0-17.7-14.3-32-32-32H168c-17.7 0-32 14.3-32 32v784c0 17.7 14.3 32 32 32h264c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm440-88H728v-36.6c46.3-13.8 80-56.6 80-107.4 0-61.9-50.1-112-112-112s-112 50.1-112 112c0 50.7 33.7 93.6 80 107.4V764H520c-8.8 0-16 7.2-16 16v152c0 8.8 7.2 16 16 16h352c8.8 0 16-7.2 16-16V780c0-8.8-7.2-16-16-16zM646 620c0-27.6 22.4-50 50-50s50 22.4 50 50-22.4 50-50 50-50-22.4-50-50zm180 266H566v-60h260v60z"}}]},name:"audit",theme:"outlined"};var r=e.i(9583),i=a.forwardRef(function(e,i){return a.createElement(r.default,(0,t.default)({},e,{ref:i,icon:s}))});e.s(["AuditOutlined",0,i],457202)},87316,655900,299023,25652,882293,e=>{"use strict";var t=e.i(475254);let a=(0,t.default)("calendar",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]]);e.s(["Calendar",()=>a],87316);var s=e.i(399219);e.s(["ChevronUp",()=>s.default],655900);let r=(0,t.default)("minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);e.s(["Minus",()=>r],299023);let i=(0,t.default)("trending-up",[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]]);e.s(["TrendingUp",()=>i],25652);let l=(0,t.default)("user-check",[["path",{d:"m16 11 2 2 4-4",key:"9rsbq5"}],["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]]);e.s(["UserCheck",()=>l],882293)},761911,98740,e=>{"use strict";let t=(0,e.i(475254).default)("users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]]);e.s(["default",()=>t],98740),e.s(["Users",()=>t],761911)},190983,e=>{"use strict";var t=e.i(843476),a=e.i(371401);e.i(389083);var s=e.i(878894),r=e.i(87316);e.i(664659),e.i(655900);var i=e.i(531278),l=e.i(299023),n=e.i(25652),c=e.i(882293),d=e.i(761911),o=e.i(271645),m=e.i(764205);let u=(...e)=>e.filter(Boolean).join(" ");function f({accessToken:e,width:f=220}){let h=(0,a.useDisableUsageIndicator)(),[x,g]=(0,o.useState)(!1),[v,y]=(0,o.useState)(!1),[p,b]=(0,o.useState)(null),[N,w]=(0,o.useState)(null),[j,L]=(0,o.useState)(!1),[z,M]=(0,o.useState)(null);(0,o.useEffect)(()=>{(async()=>{if(e){L(!0),M(null);try{let[t,a]=await Promise.all([(0,m.getRemainingUsers)(e),(0,m.getLicenseInfo)(e).catch(()=>null)]);b(t),w(a)}catch(e){console.error("Failed to fetch usage data:",e),M("Failed to load usage data")}finally{L(!1)}}})()},[e]);let O=N?.expiration_date?(e=>{if(!e)return null;let t=new Date(e+"T00:00:00Z"),a=new Date;return a.setHours(0,0,0,0),Math.ceil((t.getTime()-a.getTime())/864e5)})(N.expiration_date):null,k=null!==O&&O<0,C=null!==O&&O>=0&&O<30,{isOverLimit:H,isNearLimit:_,usagePercentage:V,userMetrics:E,teamMetrics:R}=(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 t=e.total_users?e.total_users_used/e.total_users*100:0,a=t>100,s=t>=80&&t<=100,r=e.total_teams?e.total_teams_used/e.total_teams*100:0,i=r>100,l=r>=80&&r<=100,n=a||i;return{isOverLimit:n,isNearLimit:(s||l)&&!n,usagePercentage:Math.max(t,r),userMetrics:{isOverLimit:a,isNearLimit:s,usagePercentage:t},teamMetrics:{isOverLimit:i,isNearLimit:l,usagePercentage:r}}})(p),S=H||_||k||C,U=H||k,B=(_||C)&&!U;return h||!e||p?.total_users===null&&p?.total_teams===null?null:(0,t.jsx)("div",{className:"fixed bottom-4 left-4 z-50",style:{width:`${Math.min(f,220)}px`},children:(0,t.jsx)(()=>v?(0,t.jsx)("button",{onClick:()=>y(!1),className:u("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)(d.Users,{className:"h-4 w-4 flex-shrink-0"}),S&&(0,t.jsx)("span",{className:"flex-shrink-0",children:U?(0,t.jsx)(s.AlertTriangle,{className:"h-3 w-3"}):B?(0,t.jsx)(n.TrendingUp,{className:"h-3 w-3"}):null}),(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm font-medium truncate",children:[p&&null!==p.total_users&&(0,t.jsxs)("span",{className:u("flex-shrink-0 px-1.5 py-0.5 rounded text-xs border",E.isOverLimit&&"bg-red-50 text-red-700 border-red-200",E.isNearLimit&&"bg-yellow-50 text-yellow-700 border-yellow-200",!E.isOverLimit&&!E.isNearLimit&&"bg-gray-50 text-gray-700 border-gray-200"),children:["U: ",p.total_users_used,"/",p.total_users]}),p&&null!==p.total_teams&&(0,t.jsxs)("span",{className:u("flex-shrink-0 px-1.5 py-0.5 rounded text-xs border",R.isOverLimit&&"bg-red-50 text-red-700 border-red-200",R.isNearLimit&&"bg-yellow-50 text-yellow-700 border-yellow-200",!R.isOverLimit&&!R.isNearLimit&&"bg-gray-50 text-gray-700 border-gray-200"),children:["T: ",p.total_teams_used,"/",p.total_teams]}),N?.expiration_date&&null!==O&&(0,t.jsx)("span",{className:u("flex-shrink-0 px-1.5 py-0.5 rounded text-xs border",k&&"bg-red-50 text-red-700 border-red-200",C&&"bg-yellow-50 text-yellow-700 border-yellow-200",!k&&!C&&"bg-gray-50 text-gray-700 border-gray-200"),children:O<0?"Exp!":`${O}d`}),!p||null===p.total_users&&null===p.total_teams&&!N&&(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)(i.Loader2,{className:"h-4 w-4 animate-spin"}),(0,t.jsx)("span",{className:"text-sm text-gray-500 truncate",children:"Loading..."})]})}):z||!p?(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:z||"No data"})}),(0,t.jsx)("button",{onClick:()=>y(!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)(l.Minus,{className:"h-3 w-3 text-gray-400"})})]})}):(0,t.jsxs)("div",{className:u("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)(d.Users,{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:()=>y(!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)(l.Minus,{className:"h-3 w-3 text-gray-400"})})]}),(0,t.jsxs)("div",{className:"space-y-3 text-sm",children:[N?.has_license&&N.expiration_date&&(0,t.jsxs)("div",{className:u("space-y-1 border rounded-md p-2",k&&"border-red-200 bg-red-50",C&&"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)(r.Calendar,{className:"h-3 w-3"}),(0,t.jsx)("span",{className:"font-medium",children:"License"}),(0,t.jsx)("span",{className:u("ml-1 px-1.5 py-0.5 rounded border",k&&"bg-red-50 text-red-700 border-red-200",C&&"bg-yellow-50 text-yellow-700 border-yellow-200",!k&&!C&&"bg-gray-50 text-gray-600 border-gray-200"),children:k?"Expired":C?"Expiring soon":"OK"})]}),(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[(0,t.jsx)("span",{className:"text-gray-600 text-xs",children:"Status:"}),(0,t.jsx)("span",{className:u("font-medium text-right",k&&"text-red-600",C&&"text-yellow-600"),children:(e=>{if(null===e)return"No expiration";if(e<0)return"Expired";if(0===e)return"Expires today";if(1===e)return"1 day remaining";if(e<30)return`${e} days remaining`;if(e<60)return"1 month remaining";let t=Math.floor(e/30);return`${t} months remaining`})(O)})]}),N.license_type&&(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[(0,t.jsx)("span",{className:"text-gray-600 text-xs",children:"Type:"}),(0,t.jsx)("span",{className:"font-medium text-right capitalize",children:N.license_type})]})]}),null!==p.total_users&&(0,t.jsxs)("div",{className:u("space-y-1 border rounded-md p-2",E.isOverLimit&&"border-red-200 bg-red-50",E.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)(d.Users,{className:"h-3 w-3"}),(0,t.jsx)("span",{className:"font-medium",children:"Users"}),(0,t.jsx)("span",{className:u("ml-1 px-1.5 py-0.5 rounded border",E.isOverLimit&&"bg-red-50 text-red-700 border-red-200",E.isNearLimit&&"bg-yellow-50 text-yellow-700 border-yellow-200",!E.isOverLimit&&!E.isNearLimit&&"bg-gray-50 text-gray-600 border-gray-200"),children:E.isOverLimit?"Over limit":E.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:[p.total_users_used,"/",p.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:u("font-medium text-right",E.isOverLimit&&"text-red-600",E.isNearLimit&&"text-yellow-600"),children:p.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(E.usagePercentage),"%"]})]}),(0,t.jsx)("div",{className:"w-full bg-gray-200 rounded-full h-2",children:(0,t.jsx)("div",{className:u("h-2 rounded-full transition-all duration-300",E.isOverLimit&&"bg-red-500",E.isNearLimit&&"bg-yellow-500",!E.isOverLimit&&!E.isNearLimit&&"bg-green-500"),style:{width:`${Math.min(E.usagePercentage,100)}%`}})})]}),null!==p.total_teams&&(0,t.jsxs)("div",{className:u("space-y-1 border rounded-md p-2",R.isOverLimit&&"border-red-200 bg-red-50",R.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.UserCheck,{className:"h-3 w-3"}),(0,t.jsx)("span",{className:"font-medium",children:"Teams"}),(0,t.jsx)("span",{className:u("ml-1 px-1.5 py-0.5 rounded border",R.isOverLimit&&"bg-red-50 text-red-700 border-red-200",R.isNearLimit&&"bg-yellow-50 text-yellow-700 border-yellow-200",!R.isOverLimit&&!R.isNearLimit&&"bg-gray-50 text-gray-600 border-gray-200"),children:R.isOverLimit?"Over limit":R.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:[p.total_teams_used,"/",p.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:u("font-medium text-right",R.isOverLimit&&"text-red-600",R.isNearLimit&&"text-yellow-600"),children:p.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(R.usagePercentage),"%"]})]}),(0,t.jsx)("div",{className:"w-full bg-gray-200 rounded-full h-2",children:(0,t.jsx)("div",{className:u("h-2 rounded-full transition-all duration-300",R.isOverLimit&&"bg-red-500",R.isNearLimit&&"bg-yellow-500",!R.isOverLimit&&!R.isNearLimit&&"bg-green-500"),style:{width:`${Math.min(R.usagePercentage,100)}%`}})})]})]})]}),{})})}e.s(["default",()=>f])}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/3675074b1d85e268.js b/litellm/proxy/_experimental/out/_next/static/chunks/3675074b1d85e268.js new file mode 100644 index 00000000000..5ee39281126 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/3675074b1d85e268.js @@ -0,0 +1,10 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,161059,147612,e=>{"use strict";var t=e.i(843476),l=e.i(764205),s=e.i(266027),a=e.i(243652),r=e.i(135214);let i=(0,a.createQueryKeys)("credentials"),o=()=>{let{accessToken:e}=(0,r.default)();return(0,s.useQuery)({queryKey:i.list({}),queryFn:async()=>await (0,l.credentialListCall)(e),enabled:!!e})};var n=e.i(368670),d=e.i(625901),c=e.i(292639),m=e.i(785242),u=e.i(152990),h=e.i(682830),x=e.i(271645),p=e.i(269200),g=e.i(427612),f=e.i(64848),j=e.i(942232),_=e.i(496020),y=e.i(977572),b=e.i(446891);function v({data:e=[],columns:l,isLoading:s=!1,sorting:a=[],onSortingChange:r,pagination:i,onPaginationChange:o,enablePagination:n=!1,onRowClick:d}){let[c]=x.default.useState("onChange"),[m,v]=x.default.useState({}),[N,w]=x.default.useState({}),C=(0,u.useReactTable)({data:e,columns:l,state:{sorting:a,columnSizing:m,columnVisibility:N,...n&&i?{pagination:i}:{}},columnResizeMode:c,onSortingChange:r,onColumnSizingChange:v,onColumnVisibilityChange:w,...n&&o?{onPaginationChange:o}:{},getCoreRowModel:(0,h.getCoreRowModel)(),...n?{getPaginationRowModel:(0,h.getPaginationRowModel)()}:{},enableSorting:!0,enableColumnResizing:!0,manualSorting:!0,defaultColumn:{minSize:40,maxSize:500}});return(0,t.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,t.jsx)("div",{className:"overflow-x-auto",children:(0,t.jsx)("div",{className:"relative min-w-full",children:(0,t.jsxs)(p.Table,{className:"[&_td]:py-2 [&_th]:py-2",style:{width:C.getTotalSize(),minWidth:"100%",tableLayout:"fixed"},children:[(0,t.jsx)(g.TableHead,{children:C.getHeaderGroups().map(e=>(0,t.jsx)(_.TableRow,{children:e.headers.map(e=>(0,t.jsxs)(f.TableHeaderCell,{className:`py-1 h-8 relative ${"actions"===e.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)] w-[120px] ml-8":""} ${e.column.columnDef.meta?.className||""}`,style:{width:"actions"===e.id?120:e.getSize(),position:"actions"===e.id?"sticky":"relative",right:"actions"===e.id?0:"auto"},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,u.flexRender)(e.column.columnDef.header,e.getContext())}),"actions"!==e.id&&e.column.getCanSort()&&r&&(0,t.jsx)(b.TableHeaderSortDropdown,{sortState:!1!==e.column.getIsSorted()&&e.column.getIsSorted(),onSortChange:t=>{!1===t?r([]):r([{id:e.column.id,desc:"desc"===t}])},columnId:e.column.id})]}),e.column.getCanResize()&&(0,t.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 ${e.column.getIsResizing()?"bg-blue-500":"hover:bg-blue-200"}`})]},e.id))},e.id))}),(0,t.jsx)(j.TableBody,{children:s?(0,t.jsx)(_.TableRow,{children:(0,t.jsx)(y.TableCell,{colSpan:l.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:"🚅 Loading models..."})})})}):C.getRowModel().rows.length>0?C.getRowModel().rows.map(e=>(0,t.jsx)(_.TableRow,{className:d?"cursor-pointer hover:bg-gray-50":"",onClick:()=>d?.(e.original),children:e.getVisibleCells().map(e=>(0,t.jsx)(y.TableCell,{className:`py-0.5 overflow-hidden ${"actions"===e.column.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)] w-[120px] ml-8":""} ${e.column.columnDef.meta?.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,u.flexRender)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,t.jsx)(_.TableRow,{children:(0,t.jsx)(y.TableCell,{colSpan:l.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:"No models found"})})})})})]})})})})}var N=e.i(751904),w=e.i(827252),C=e.i(772345),S=e.i(68155),k=e.i(389083),T=e.i(994388),F=e.i(752978),I=e.i(312361),M=e.i(525720),P=e.i(282786),A=e.i(770914),E=e.i(592968),L=e.i(898586),R=e.i(418371);let{Text:O,Title:B}=L.Typography,z=(0,t.jsxs)(A.Space,{direction:"vertical",size:12,children:[(0,t.jsx)(O,{strong:!0,style:{fontSize:13},children:"Credential types"}),(0,t.jsxs)(A.Space,{direction:"vertical",size:8,children:[(0,t.jsx)(M.Flex,{align:"center",gap:8,children:(0,t.jsxs)(A.Space,{direction:"vertical",children:[(0,t.jsxs)(M.Flex,{align:"center",gap:8,children:[(0,t.jsx)(C.SyncOutlined,{style:{color:"#1890ff"}}),(0,t.jsx)(B,{level:5,style:{margin:0,color:"#1890ff"},children:"Reusable"})]}),(0,t.jsx)(O,{type:"secondary",children:"Credentials saved in LiteLLM that can be added to models repeatedly."})]})}),(0,t.jsx)(I.Divider,{size:"small"}),(0,t.jsx)(M.Flex,{align:"center",gap:8,children:(0,t.jsxs)(A.Space,{direction:"vertical",size:8,children:[(0,t.jsxs)(M.Flex,{align:"center",gap:8,children:[(0,t.jsx)(N.EditOutlined,{style:{color:"#8c8c8c",fontSize:14,flexShrink:0}}),(0,t.jsx)(B,{level:5,style:{margin:0},children:"Manual"})]}),(0,t.jsx)(O,{type:"secondary",children:"Credentials added directly during model creation or defined in the config file."})]})})]})]}),q=e=>e?.model_info?.team_public_model_name?e.model_info.team_public_model_name:e?.model_name||"-";var V=e.i(127952),D=e.i(727749),H=e.i(313603),G=e.i(912598),$=e.i(350967),U=e.i(404206),J=e.i(906579),K=e.i(464571),W=e.i(199133),Q=e.i(981339),Y=e.i(153472),X=e.i(954616);let Z=async(e,t)=>{let s=(0,l.getProxyBaseUrl)(),a=s?`${s}/config/field/update`:"/config/field/update",r=await fetch(a,{method:"POST",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({field_name:"store_model_in_db",field_value:t.store_model_in_db,config_type:"general_settings"})});if(!r.ok){let e=await r.json().catch(()=>({}));throw Error(e?.error?.message||e?.message||e?.detail||"Failed to update model storage settings")}return await r.json()};var ee=e.i(190702),et=e.i(808613),el=e.i(212931),es=e.i(790848);let ea=({isVisible:e,onCancel:l,onSuccess:s})=>{let[a]=et.Form.useForm(),{mutateAsync:i,isPending:o}=(()=>{let{accessToken:e}=(0,r.default)();return(0,X.useMutation)({mutationFn:async t=>{if(!e)throw Error("Access token is required");return await Z(e,t)}})})(),{data:n,isLoading:d,refetch:c}=(0,Y.useProxyConfig)(Y.ConfigType.GENERAL_SETTINGS);(0,x.useEffect)(()=>{e&&c()},[e,c]);let m=(0,x.useMemo)(()=>{if(!n)return{store_model_in_db:!1};let e=n.find(e=>"store_model_in_db"===e.field_name);return{store_model_in_db:e?.field_value??!1}},[n]),u=async e=>{try{await i(e,{onSuccess:()=>{D.default.success("Model storage settings updated successfully"),c(),s?.()},onError:e=>{D.default.fromBackend("Failed to save model storage settings: "+(0,ee.parseErrorMessage)(e))}})}catch(e){D.default.fromBackend("Failed to save model storage settings: "+(0,ee.parseErrorMessage)(e))}},h=()=>{a.resetFields(),l()};return(0,t.jsx)(el.Modal,{title:(0,t.jsx)(L.Typography.Title,{level:5,children:"Model Settings"}),open:e,footer:(0,t.jsxs)(A.Space,{children:[(0,t.jsx)(K.Button,{onClick:h,disabled:o||d,children:"Cancel"}),(0,t.jsx)(K.Button,{type:"primary",loading:o,disabled:d,onClick:()=>a.submit(),children:o?"Saving...":"Save Settings"})]}),onCancel:h,children:(0,t.jsx)(et.Form,{form:a,layout:"horizontal",onFinish:u,initialValues:m,children:(0,t.jsx)(et.Form.Item,{label:"Store Model in DB",name:"store_model_in_db",tooltip:n?.find(e=>"store_model_in_db"===e.field_name)?.field_description||"If enabled, models and config are stored in and loaded from the database.",valuePropName:"checked",children:d?(0,t.jsx)(Q.Skeleton.Input,{active:!0,block:!0}):(0,t.jsx)(es.Switch,{})})},n?JSON.stringify(m):"loading")})};var er=e.i(374009);let ei=(e,t)=>{if(!e?.data)return{data:[]};let l=JSON.parse(JSON.stringify(e.data));for(let e=0;e"model"!==e&&"api_base"!==e))),l[e].provider=o,l[e].input_cost=n,l[e].output_cost=d,l[e].litellm_model_name=a,null!=l[e].input_cost&&(l[e].input_cost=(1e6*Number(l[e].input_cost)).toFixed(2)),null!=l[e].output_cost&&(l[e].output_cost=(1e6*Number(l[e].output_cost)).toFixed(2)),l[e].max_tokens=c,l[e].max_input_tokens=m,l[e].api_base=s?.litellm_params?.api_base,l[e].cleanedLitellmParams=u}return{data:l}},{Text:eo}=L.Typography,en=({selectedModelGroup:e,setSelectedModelGroup:s,availableModelGroups:a,availableModelAccessGroups:i,setSelectedModelId:o,setSelectedTeamId:c})=>{let{data:u,isLoading:h}=(0,n.useModelCostMap)(),{accessToken:p,userId:g,userRole:f,premiumUser:j}=(0,r.default)(),{data:_,isLoading:y}=(0,m.useTeams)(),b=(0,G.useQueryClient)(),[I,L]=(0,x.useState)(""),[B,Y]=(0,x.useState)(""),[X,Z]=(0,x.useState)("current_team"),[ee,et]=(0,x.useState)("personal"),[el,es]=(0,x.useState)(!1),[en,ed]=(0,x.useState)(null),[ec,em]=(0,x.useState)(new Set),[eu,eh]=(0,x.useState)(1),[ex]=(0,x.useState)(50),[ep,eg]=(0,x.useState)({pageIndex:0,pageSize:50}),[ef,ej]=(0,x.useState)([]),[e_,ey]=(0,x.useState)(!1),eb=(0,x.useMemo)(()=>(0,er.default)(e=>{Y(e),eh(1),eg(e=>({...e,pageIndex:0}))},200),[]);(0,x.useEffect)(()=>(eb(I),()=>{eb.cancel()}),[I,eb]);let ev="personal"===ee?void 0:ee.team_id,eN=(0,x.useMemo)(()=>{if(0===ef.length)return;let e=ef[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},[ef]),ew=(0,x.useMemo)(()=>{if(0!==ef.length)return ef[0].desc?"desc":"asc"},[ef]),{data:eC,isLoading:eS,refetch:ek}=(0,d.useModelsInfo)(eu,ex,B||void 0,void 0,ev,eN,ew),eT=eS||h,eF=e=>null!=u&&"object"==typeof u&&e in u?u[e].litellm_provider:"openai",eI=(0,x.useMemo)(()=>eC?ei(eC,eF):{data:[]},[eC,u]),[eM,eP]=(0,x.useState)(null),[eA,eE]=(0,x.useState)(!1),eL=(0,x.useMemo)(()=>eC?{total_count:eC.total_count??0,current_page:eC.current_page??1,total_pages:eC.total_pages??1,size:eC.size??ex}:{total_count:0,current_page:1,total_pages:1,size:ex},[eC,ex]),eR=(0,x.useMemo)(()=>eI&&eI.data&&0!==eI.data.length?eI.data.filter(t=>{let l="all"===e||t.model_name===e||!e||"wildcard"===e&&t.model_name?.includes("*"),s="all"===en||t.model_info.access_groups?.includes(en)||!en;return l&&s}):[],[eI,e,en]);(0,x.useEffect)(()=>{eg(e=>({...e,pageIndex:0})),eh(1)},[e,en]),(0,x.useEffect)(()=>{eh(1),eg(e=>({...e,pageIndex:0}))},[ev]),(0,x.useEffect)(()=>{eh(1),eg(e=>({...e,pageIndex:0}))},[ef]);let eO=(0,x.useMemo)(()=>eM&&eI?.data?eI.data.find(e=>e.model_info.id===eM):null,[eM,eI]),eB=async()=>{if(p&&eM)try{eE(!0),await (0,l.modelDeleteCall)(p,eM),D.default.success("Model deleted successfully"),b.invalidateQueries({queryKey:["models","list"]}),ek()}catch(e){console.error("Error deleting model:",e),D.default.fromBackend(e)}finally{eE(!1),eP(null)}};return(0,t.jsxs)(U.TabPanel,{children:[(0,t.jsx)($.Grid,{children:(0,t.jsx)("div",{className:"flex flex-col space-y-4",children:(0,t.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,t.jsxs)("div",{className:"border-b px-6 py-4 bg-gray-50",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsxs)("div",{className:"flex items-center gap-4",children:[(0,t.jsx)(eo,{className:"text-lg font-semibold text-gray-900",children:"Current Team:"}),(0,t.jsx)("div",{className:"w-80",children:eT?(0,t.jsx)(Q.Skeleton.Input,{active:!0,block:!0,size:"large"}):(0,t.jsx)(W.Select,{style:{width:"100%"},size:"large",defaultValue:"personal",value:"personal"===ee?"personal":ee.team_id,onChange:e=>{if("personal"===e)et("personal"),eh(1),eg(e=>({...e,pageIndex:0}));else{let t=_?.find(t=>t.team_id===e);t&&(et(t),eh(1),eg(e=>({...e,pageIndex:0})))}},loading:y,options:[{value:"personal",label:(0,t.jsxs)(A.Space,{direction:"horizontal",align:"center",children:[(0,t.jsx)(J.Badge,{color:"blue",size:"small"}),(0,t.jsx)(eo,{style:{fontSize:16},children:"Personal"})]})},..._?.filter(e=>e.team_id).map(e=>({value:e.team_id,label:(0,t.jsxs)(A.Space,{direction:"horizontal",align:"center",children:[(0,t.jsx)(J.Badge,{color:"green",size:"small"}),(0,t.jsx)(eo,{ellipsis:!0,style:{fontSize:16},children:e.team_alias?e.team_alias:e.team_id})]})}))??[]]})})]}),(0,t.jsxs)("div",{className:"flex items-center gap-4",children:[(0,t.jsx)(eo,{className:"text-lg font-semibold text-gray-900",children:"View:"}),(0,t.jsx)("div",{className:"w-64",children:eT?(0,t.jsx)(Q.Skeleton.Input,{active:!0,block:!0,size:"large"}):(0,t.jsx)(W.Select,{style:{width:"100%"},size:"large",defaultValue:"current_team",value:X,onChange:e=>Z(e),options:[{value:"current_team",label:(0,t.jsxs)(A.Space,{direction:"horizontal",align:"center",children:[(0,t.jsx)(J.Badge,{color:"purple",size:"small"}),(0,t.jsx)(eo,{style:{fontSize:16},children:"Current Team Models"})]})},{value:"all",label:(0,t.jsxs)(A.Space,{direction:"horizontal",align:"center",children:[(0,t.jsx)(J.Badge,{color:"gray",size:"small"}),(0,t.jsx)(eo,{style:{fontSize:16},children:"All Available Models"})]})}]})})]})]}),"current_team"===X&&(0,t.jsxs)("div",{className:"flex items-start gap-2 mt-3",children:[(0,t.jsx)(w.InfoCircleOutlined,{className:"text-gray-400 mt-0.5 flex-shrink-0 text-xs"}),(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"personal"===ee?(0,t.jsxs)("span",{children:["To access these models: Create a Virtual Key without selecting a team on the"," ",(0,t.jsx)("a",{href:"/public?login=success&page=api-keys",className:"text-gray-600 hover:text-gray-800 underline",children:"Virtual Keys page"})]}):(0,t.jsxs)("span",{children:['To access these models: Create a Virtual Key and select Team as "',"string"!=typeof ee?ee.team_alias||ee.team_id:"",'" on the'," ",(0,t.jsx)("a",{href:"/public?login=success&page=api-keys",className:"text-gray-600 hover:text-gray-800 underline",children:"Virtual Keys page"})]})})]})]}),(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 items-center justify-between gap-3",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,t.jsxs)("div",{className:"relative w-64",children:[(0,t.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:I,onChange:e=>L(e.target.value)}),(0,t.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,t.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,t.jsxs)("button",{className:`px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2 ${el?"bg-gray-100":""}`,onClick:()=>es(!el),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:"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,t.jsxs)("button",{className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2",onClick:()=>{L(""),s("all"),ed(null),et("personal"),Z("current_team"),eh(1),eg({pageIndex:0,pageSize:50}),ej([])},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:"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"]})]}),(0,t.jsx)(K.Button,{icon:(0,t.jsx)(H.SettingOutlined,{}),onClick:()=>ey(!0),title:"Model Settings"})]}),el&&(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-3 mt-3",children:[(0,t.jsx)("div",{className:"w-64",children:(0,t.jsx)(W.Select,{className:"w-full",value:e??"all",onChange:e=>s("all"===e?"all":e),placeholder:"Filter by Public Model Name",showSearch:!0,options:[{value:"all",label:"All Models"},{value:"wildcard",label:"Wildcard Models (*)"},...a.map((e,t)=>({value:e,label:e}))]})}),(0,t.jsx)("div",{className:"w-64",children:(0,t.jsx)(W.Select,{className:"w-full",value:en??"all",onChange:e=>ed("all"===e?null:e),placeholder:"Filter by Model Access Group",showSearch:!0,options:[{value:"all",label:"All Model Access Groups"},...i.map((e,t)=>({value:e,label:e}))]})})]}),(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[eT?(0,t.jsx)(Q.Skeleton.Input,{active:!0,style:{width:184,height:20}}):(0,t.jsx)("span",{className:"text-sm text-gray-700",children:eL.total_count>0?`Showing ${(eu-1)*ex+1} - ${Math.min(eu*ex,eL.total_count)} of ${eL.total_count} results`:"Showing 0 results"}),(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[eT?(0,t.jsx)(Q.Skeleton.Button,{active:!0,style:{width:84,height:30}}):(0,t.jsx)("button",{onClick:()=>{eh(eu-1),eg(e=>({...e,pageIndex:0}))},disabled:1===eu,className:`px-3 py-1 text-sm border rounded-md ${1===eu?"bg-gray-100 text-gray-400 cursor-not-allowed":"hover:bg-gray-50"}`,children:"Previous"}),eT?(0,t.jsx)(Q.Skeleton.Button,{active:!0,style:{width:56,height:30}}):(0,t.jsx)("button",{onClick:()=>{eh(eu+1),eg(e=>({...e,pageIndex:0}))},disabled:eu>=eL.total_pages,className:`px-3 py-1 text-sm border rounded-md ${eu>=eL.total_pages?"bg-gray-100 text-gray-400 cursor-not-allowed":"hover:bg-gray-50"}`,children:"Next"})]})]})]})}),(0,t.jsx)(v,{columns:[{header:()=>(0,t.jsx)("span",{className:"text-sm font-semibold",children:"Model ID"}),accessorKey:"model_info.id",enableSorting:!1,size:130,minSize:80,cell:({row:e})=>{let l=e.original;return(0,t.jsx)(E.Tooltip,{title:l.model_info.id,children:(0,t.jsx)(O,{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:e=>{e.stopPropagation(),o(l.model_info.id)},children:l.model_info.id})})}},{header:()=>(0,t.jsx)("span",{className:"text-sm font-semibold",children:"Model Information"}),accessorKey:"model_name",size:250,minSize:120,cell:({row:e})=>{let l=e.original,s=q(e.original)||"-",a=(0,t.jsxs)(A.Space,{direction:"vertical",size:12,style:{minWidth:220},children:[(0,t.jsxs)(M.Flex,{align:"center",gap:8,children:[(0,t.jsx)(R.ProviderLogo,{provider:l.provider}),(0,t.jsx)(O,{type:"secondary",style:{fontSize:12},ellipsis:!0,children:l.provider||"Unknown provider"})]}),(0,t.jsxs)(A.Space,{direction:"vertical",size:6,children:[(0,t.jsxs)(A.Space,{direction:"vertical",size:2,style:{width:"100%"},children:[(0,t.jsx)(O,{type:"secondary",style:{fontSize:11},children:"Public Model Name"}),(0,t.jsx)(O,{strong:!0,style:{fontSize:13,maxWidth:480},ellipsis:!0,title:s,children:s})]}),(0,t.jsxs)(A.Space,{direction:"vertical",size:2,children:[(0,t.jsx)(O,{type:"secondary",style:{fontSize:11},children:"LiteLLM Model Name"}),(0,t.jsx)(O,{style:{fontSize:13},copyable:{text:l.litellm_model_name||"-"},ellipsis:!0,title:l.litellm_model_name||"-",children:l.litellm_model_name||"-"})]})]})]});return(0,t.jsx)(P.Popover,{content:a,placement:"right",arrow:{pointAtCenter:!0},styles:{root:{maxWidth:500}},children:(0,t.jsxs)("div",{className:"flex items-start space-x-2 min-w-0 w-full cursor-pointer",children:[(0,t.jsx)("div",{className:"flex-shrink-0 mt-0.5",children:l.provider?(0,t.jsx)(R.ProviderLogo,{provider:l.provider}):(0,t.jsx)("div",{className:"w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",children:"-"})}),(0,t.jsxs)("div",{className:"flex flex-col min-w-0 flex-1",children:[(0,t.jsx)(O,{ellipsis:!0,className:"text-gray-900",style:{fontSize:12,fontWeight:500,lineHeight:"16px"},children:s}),(0,t.jsx)(O,{ellipsis:!0,type:"secondary",style:{fontSize:12,lineHeight:"16px",marginTop:2},children:l.litellm_model_name||"-"})]})]})})}},{header:()=>(0,t.jsxs)("span",{className:"flex items-center gap-1",children:[(0,t.jsx)("span",{className:"text-sm font-semibold",children:"Credentials"}),(0,t.jsx)(P.Popover,{content:z,placement:"bottom",arrow:{pointAtCenter:!0},children:(0,t.jsx)(w.InfoCircleOutlined,{className:"cursor-pointer text-gray-400 hover:text-gray-600",style:{fontSize:12}})})]}),accessorKey:"litellm_credential_name",enableSorting:!1,size:180,minSize:100,cell:({row:e})=>{let l=e.original,s=l.litellm_params?.litellm_credential_name,a=!!s;return(0,t.jsx)("div",{className:"flex items-center space-x-2 min-w-0 w-full",children:a?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(C.SyncOutlined,{className:"flex-shrink-0",style:{color:"#1890ff",fontSize:14}}),(0,t.jsx)("span",{className:"text-xs truncate text-blue-600",title:s,children:s})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(N.EditOutlined,{className:"flex-shrink-0",style:{color:"#8c8c8c",fontSize:14}}),(0,t.jsx)("span",{className:"text-xs text-gray-500",children:"Manual"})]})})}},{header:()=>(0,t.jsx)("span",{className:"text-sm font-semibold",children:"Created By"}),accessorKey:"model_info.created_by",sortingFn:"datetime",size:160,minSize:100,cell:({row:e})=>{let l=e.original,s=!l.model_info?.db_model,a=l.model_info.created_by,r=l.model_info.created_at?new Date(l.model_info.created_at).toLocaleDateString():null;return(0,t.jsxs)("div",{className:"flex flex-col min-w-0 w-full",children:[(0,t.jsx)("div",{className:"text-xs font-medium text-gray-900 truncate",title:s?"Defined in config":a||"Unknown",children:s?"Defined in config":a||"Unknown"}),(0,t.jsx)("div",{className:"text-xs text-gray-500 truncate mt-0.5",title:s?"Config file":r||"Unknown date",children:s?"-":r||"Unknown date"})]})}},{header:()=>(0,t.jsx)("span",{className:"text-sm font-semibold",children:"Updated At"}),accessorKey:"model_info.updated_at",sortingFn:"datetime",size:120,minSize:80,cell:({row:e})=>{let l=e.original;return(0,t.jsx)("span",{className:"text-xs",children:l.model_info.updated_at?new Date(l.model_info.updated_at).toLocaleDateString():"-"})}},{header:()=>(0,t.jsx)("span",{className:"text-sm font-semibold",children:"Costs"}),accessorKey:"input_cost",size:120,minSize:80,cell:({row:e})=>{let l=e.original,s=l.input_cost,a=l.output_cost;return null==s&&null==a?(0,t.jsx)("div",{className:"w-full",children:(0,t.jsx)("span",{className:"text-xs text-gray-400",children:"-"})}):(0,t.jsx)(E.Tooltip,{title:"Cost per 1M tokens",children:(0,t.jsxs)("div",{className:"flex flex-col min-w-0 w-full",children:[null!=s&&(0,t.jsxs)("div",{className:"text-xs font-medium text-gray-900 truncate",children:["In: $",s]}),null!=a&&(0,t.jsxs)("div",{className:"text-xs text-gray-500 truncate mt-0.5",children:["Out: $",a]})]})})}},{header:()=>(0,t.jsx)("span",{className:"text-sm font-semibold",children:"Team ID"}),accessorKey:"model_info.team_id",enableSorting:!1,size:130,minSize:80,cell:({row:e})=>{let l=e.original;return l.model_info.team_id?(0,t.jsx)("div",{className:"overflow-hidden w-full",children:(0,t.jsx)(E.Tooltip,{title:l.model_info.team_id,children:(0,t.jsxs)(T.Button,{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:e=>{e.stopPropagation(),c(l.model_info.team_id)},children:[l.model_info.team_id.slice(0,7),"..."]})})}):"-"}},{header:()=>(0,t.jsx)("span",{className:"text-sm font-semibold",children:"Model Access Group"}),accessorKey:"model_info.model_access_group",enableSorting:!1,size:180,minSize:100,cell:({row:e})=>{let l=e.original,s=l.model_info.access_groups;if(!s||0===s.length)return"-";let a=l.model_info.id,r=ec.has(a),i=s.length>1;return(0,t.jsxs)("div",{className:"flex items-center gap-1 overflow-hidden w-full",children:[(0,t.jsx)(k.Badge,{size:"xs",color:"blue",className:"text-xs px-1.5 py-0.5 h-5 leading-tight flex-shrink-0",children:s[0]}),(r||!i&&2===s.length)&&s.slice(1).map((e,l)=>(0,t.jsx)(k.Badge,{size:"xs",color:"blue",className:"text-xs px-1.5 py-0.5 h-5 leading-tight flex-shrink-0",children:e},l+1)),i&&(0,t.jsx)("button",{onClick:e=>{let t;e.stopPropagation(),t=new Set(ec),r?t.delete(a):t.add(a),em(t)},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:r?"−":`+${s.length-1}`})]})}},{header:()=>(0,t.jsx)("span",{className:"text-sm font-semibold",children:"Status"}),accessorKey:"model_info.db_model",size:120,minSize:80,cell:({row:e})=>{let l=e.original;return(0,t.jsx)("div",{className:` + inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium + ${l.model_info.db_model?"bg-blue-50 text-blue-600":"bg-gray-100 text-gray-600"} + `,children:l.model_info.db_model?"DB Model":"Config Model"})}},{id:"actions",header:()=>(0,t.jsx)("span",{className:"text-sm font-semibold",children:"Actions"}),size:60,minSize:40,enableResizing:!1,cell:({row:e})=>{let l=e.original,s="Admin"===f||l.model_info?.created_by===g,a=!l.model_info?.db_model;return(0,t.jsx)("div",{className:"flex items-center justify-end gap-2 pr-4",children:a?(0,t.jsx)(E.Tooltip,{title:"Config model cannot be deleted on the dashboard. Please delete it from the config file.",children:(0,t.jsx)(F.Icon,{icon:S.TrashIcon,size:"sm",className:"opacity-50 cursor-not-allowed"})}):(0,t.jsx)(E.Tooltip,{title:"Delete model",children:(0,t.jsx)(F.Icon,{icon:S.TrashIcon,size:"sm",onClick:e=>{e.stopPropagation(),s&&eP&&eP(l.model_info.id)},className:s?"cursor-pointer hover:text-red-600":"opacity-50 cursor-not-allowed"})})})}}],data:eR,isLoading:eS,sorting:ef,onSortingChange:ej,pagination:ep,onPaginationChange:eg,enablePagination:!0,onRowClick:e=>o(e.model_info.id)})]})})}),(0,t.jsx)(V.default,{isOpen:!!eM,title:"Delete Model",alertMessage:"This action cannot be undone.",message:"Are you sure you want to delete this model?",resourceInformationTitle:"Model Information",resourceInformation:eO?[{label:"Model Name",value:eO.model_name||"Not Set"},{label:"LiteLLM Model Name",value:eO.litellm_model_name||"Not Set"},{label:"Provider",value:eO.provider||"Not Set"},{label:"Created By",value:eO.model_info?.created_by||"Not Set"}]:[],onCancel:()=>eP(null),onOk:eB,confirmLoading:eA}),(0,t.jsx)(ea,{isVisible:e_,onCancel:()=>ey(!1),onSuccess:()=>ey(!1)})]})};var ed=e.i(206929),ec=e.i(35983),em=e.i(599724),eu=e.i(629569),eh=e.i(28651);let ex={"BadRequestError (400)":"BadRequestErrorRetries","AuthenticationError (401)":"AuthenticationErrorRetries","TimeoutError (408)":"TimeoutErrorRetries","RateLimitError (429)":"RateLimitErrorRetries","ContentPolicyViolationError (400)":"ContentPolicyViolationErrorRetries","InternalServerError (500)":"InternalServerErrorRetries"},ep=({selectedModelGroup:e,setSelectedModelGroup:l,availableModelGroups:s,globalRetryPolicy:a,setGlobalRetryPolicy:r,defaultRetry:i,modelGroupRetryPolicy:o,setModelGroupRetryPolicy:n,handleSaveRetrySettings:d})=>(0,t.jsxs)(U.TabPanel,{children:[(0,t.jsx)("div",{className:"flex items-center gap-4 mb-6",children:(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(em.Text,{children:"Retry Policy Scope:"}),(0,t.jsxs)(ed.Select,{className:"ml-2 w-48",defaultValue:"global",value:"global"===e?"global":e||s[0],onValueChange:e=>l(e),children:[(0,t.jsx)(ec.SelectItem,{value:"global",children:"Global Default"}),s.map((e,s)=>(0,t.jsx)(ec.SelectItem,{value:e,onClick:()=>l(e),children:e},s))]})]})}),"global"===e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(eu.Title,{children:"Global Retry Policy"}),(0,t.jsx)(em.Text,{className:"mb-6",children:"Default retry settings applied to all model groups unless overridden"})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(eu.Title,{children:["Retry Policy for ",e]}),(0,t.jsx)(em.Text,{className:"mb-6",children:"Model-specific retry settings. Falls back to global defaults if not set."})]}),ex&&(0,t.jsx)("table",{children:(0,t.jsx)("tbody",{children:Object.entries(ex).map(([l,s],d)=>{let c;if("global"===e)c=a?.[s]??i;else{let t=o?.[e]?.[s];c=null!=t?t:a?.[s]??i}return(0,t.jsxs)("tr",{className:"flex justify-between items-center mt-2",children:[(0,t.jsxs)("td",{children:[(0,t.jsx)(em.Text,{children:l}),"global"!==e&&(0,t.jsxs)(em.Text,{className:"text-xs text-gray-500 ml-2",children:["(Global: ",a?.[s]??i,")"]})]}),(0,t.jsx)("td",{children:(0,t.jsx)(eh.InputNumber,{className:"ml-5",value:c,min:0,step:1,onChange:t=>{"global"===e?r(e=>null==t?e:{...e??{},[s]:t}):n(l=>{let a=l?.[e]??{};return{...l??{},[e]:{...a,[s]:t}}})}})})]},d)})})}),(0,t.jsx)(T.Button,{className:"mt-6 mr-8",onClick:d,children:"Save"})]});var eg=e.i(883552),ef=e.i(262218),ej=e.i(175712),e_=e.i(91979),ey=e.i(637235),eb=e.i(724154);e.i(247167);var ev=e.i(931067);let eN={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M811.4 418.7C765.6 297.9 648.9 212 512.2 212S258.8 297.8 213 418.6C127.3 441.1 64 519.1 64 612c0 110.5 89.5 200 199.9 200h496.2C870.5 812 960 722.5 960 612c0-92.7-63.1-170.7-148.6-193.3zm36.3 281a123.07 123.07 0 01-87.6 36.3H263.9c-33.1 0-64.2-12.9-87.6-36.3A123.3 123.3 0 01140 612c0-28 9.1-54.3 26.2-76.3a125.7 125.7 0 0166.1-43.7l37.9-9.9 13.9-36.6c8.6-22.8 20.6-44.1 35.7-63.4a245.6 245.6 0 0152.4-49.9c41.1-28.9 89.5-44.2 140-44.2s98.9 15.3 140 44.2c19.9 14 37.5 30.8 52.4 49.9 15.1 19.3 27.1 40.7 35.7 63.4l13.8 36.5 37.8 10c54.3 14.5 92.1 63.8 92.1 120 0 33.1-12.9 64.3-36.3 87.7z"}}]},name:"cloud",theme:"outlined"};var ew=e.i(9583),eC=x.forwardRef(function(e,t){return x.createElement(ew.default,(0,ev.default)({},e,{ref:t,icon:eN}))}),eS=e.i(210612),ek=e.i(285027);let{Text:eT}=L.Typography,eF=({accessToken:e,onReloadSuccess:s,buttonText:a="Reload Price Data",showIcon:r=!0,size:i="middle",type:o="primary",className:n=""})=>{let[d,c]=(0,x.useState)(!1),[m,u]=(0,x.useState)(!1),[h,p]=(0,x.useState)(!1),[g,f]=(0,x.useState)(!1),[j,_]=(0,x.useState)(6),[y,b]=(0,x.useState)(null),[v,N]=(0,x.useState)(!1),[C,S]=(0,x.useState)(null),[k,T]=(0,x.useState)(!1);(0,x.useEffect)(()=>{F(),M();let e=setInterval(()=>{F(),M()},3e4);return()=>clearInterval(e)},[e]);let F=async()=>{if(e){N(!0);try{console.log("Fetching reload status...");let t=await (0,l.getModelCostMapReloadStatus)(e);console.log("Received status:",t),b(t)}catch(e){console.error("Failed to fetch reload status:",e),b({scheduled:!1,interval_hours:null,last_run:null,next_run:null})}finally{N(!1)}}},M=async()=>{if(e){T(!0);try{let t=await (0,l.getModelCostMapSource)(e);S(t)}catch(e){console.error("Failed to fetch cost map source info:",e)}finally{T(!1)}}},P=async()=>{if(!e)return void D.default.fromBackend("No access token available");c(!0);try{let t=await (0,l.reloadModelCostMap)(e);"success"===t.status?(D.default.success(`Price data reloaded successfully! ${t.models_count||0} models updated.`),s?.(),await F(),await M()):D.default.fromBackend("Failed to reload price data")}catch(e){console.error("Error reloading price data:",e),D.default.fromBackend("Failed to reload price data. Please try again.")}finally{c(!1)}},L=async()=>{if(!e)return void D.default.fromBackend("No access token available");if(j<=0)return void D.default.fromBackend("Hours must be greater than 0");u(!0);try{let t=await (0,l.scheduleModelCostMapReload)(e,j);"success"===t.status?(D.default.success(`Periodic reload scheduled for every ${j} hours`),f(!1),await F()):D.default.fromBackend("Failed to schedule periodic reload")}catch(e){console.error("Error scheduling reload:",e),D.default.fromBackend("Failed to schedule periodic reload. Please try again.")}finally{u(!1)}},R=async()=>{if(!e)return void D.default.fromBackend("No access token available");p(!0);try{let t=await (0,l.cancelModelCostMapReload)(e);"success"===t.status?(D.default.success("Periodic reload cancelled successfully"),await F()):D.default.fromBackend("Failed to cancel periodic reload")}catch(e){console.error("Error cancelling reload:",e),D.default.fromBackend("Failed to cancel periodic reload. Please try again.")}finally{p(!1)}},O=e=>{if(!e)return"Never";try{return new Date(e).toLocaleString()}catch{return e}};return(0,t.jsxs)("div",{className:n,children:[(0,t.jsxs)(A.Space,{direction:"horizontal",size:"middle",style:{marginBottom:16},children:[(0,t.jsx)(eg.Popconfirm,{title:"Hard Refresh Price Data",description:"This will immediately fetch the latest pricing information from the remote source. Continue?",onConfirm:P,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,t.jsx)(K.Button,{type:o,size:i,loading:d,icon:r?(0,t.jsx)(e_.ReloadOutlined,{}):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:a})}),y?.scheduled?(0,t.jsx)(K.Button,{type:"default",size:i,danger:!0,icon:(0,t.jsx)(eb.StopOutlined,{}),loading:h,onClick:R,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,t.jsx)(K.Button,{type:"default",size:i,icon:(0,t.jsx)(ey.ClockCircleOutlined,{}),onClick:()=>f(!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"})]}),C&&(0,t.jsx)(ej.Card,{size:"small",style:{backgroundColor:"remote"===C.source?"#f0f7ff":"#fff8f0",border:`1px solid ${"remote"===C.source?"#bae0ff":"#ffd591"}`,borderRadius:8,marginBottom:12},children:(0,t.jsxs)(A.Space,{direction:"vertical",size:"small",style:{width:"100%"},children:[(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:["remote"===C.source?(0,t.jsx)(eC,{style:{color:"#1677ff",fontSize:16}}):(0,t.jsx)(eS.DatabaseOutlined,{style:{color:"#fa8c16",fontSize:16}}),(0,t.jsx)(eT,{strong:!0,style:{fontSize:"13px"},children:"Pricing Data Source"}),(0,t.jsx)(ef.Tag,{color:"remote"===C.source?"blue":"orange",style:{marginLeft:"auto",fontWeight:600,textTransform:"uppercase",fontSize:"11px"},children:"remote"===C.source?"Remote":"Local"})]}),(0,t.jsx)(I.Divider,{style:{margin:"6px 0"}}),(0,t.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[(0,t.jsx)(eT,{type:"secondary",style:{fontSize:"12px"},children:"Models loaded:"}),(0,t.jsx)(eT,{strong:!0,style:{fontSize:"12px"},children:C.model_count.toLocaleString()})]}),C.url&&(0,t.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:8},children:[(0,t.jsx)(eT,{type:"secondary",style:{fontSize:"12px",whiteSpace:"nowrap"},children:"remote"===C.source?"Loaded from:":"Attempted URL:"}),(0,t.jsx)(E.Tooltip,{title:C.url,children:(0,t.jsx)(eT,{style:{fontSize:"11px",maxWidth:240,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",color:"#1677ff",cursor:"default"},children:C.url})})]}),C.is_env_forced&&(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,marginTop:2},children:[(0,t.jsx)(w.InfoCircleOutlined,{style:{color:"#fa8c16",fontSize:12}}),(0,t.jsxs)(eT,{type:"secondary",style:{fontSize:"11px"},children:["Local mode forced via ",(0,t.jsx)("code",{children:"LITELLM_LOCAL_MODEL_COST_MAP=True"})]})]}),C.fallback_reason&&(0,t.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:6,backgroundColor:"#fff7e6",border:"1px solid #ffd591",borderRadius:4,padding:"4px 8px",marginTop:2},children:[(0,t.jsx)(ek.WarningOutlined,{style:{color:"#fa8c16",fontSize:12,marginTop:2}}),(0,t.jsxs)(eT,{style:{fontSize:"11px",color:"#614700"},children:["Fell back to local: ",C.fallback_reason]})]})]})}),y&&(0,t.jsx)(ej.Card,{size:"small",style:{backgroundColor:"#f8f9fa",border:"1px solid #e9ecef",borderRadius:8},children:(0,t.jsxs)(A.Space,{direction:"vertical",size:"small",style:{width:"100%"},children:[y.scheduled?(0,t.jsx)("div",{children:(0,t.jsxs)(ef.Tag,{color:"green",icon:(0,t.jsx)(ey.ClockCircleOutlined,{}),children:["Scheduled every ",y.interval_hours," hours"]})}):(0,t.jsx)(eT,{type:"secondary",children:"No periodic reload scheduled"}),(0,t.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[(0,t.jsx)(eT,{type:"secondary",style:{fontSize:"12px"},children:"Last run:"}),(0,t.jsx)(eT,{style:{fontSize:"12px"},children:O(y.last_run)})]}),y.scheduled&&(0,t.jsxs)(t.Fragment,{children:[y.next_run&&(0,t.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[(0,t.jsx)(eT,{type:"secondary",style:{fontSize:"12px"},children:"Next run:"}),(0,t.jsx)(eT,{style:{fontSize:"12px"},children:O(y.next_run)})]}),(0,t.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[(0,t.jsx)(eT,{type:"secondary",style:{fontSize:"12px"},children:"Status:"}),(0,t.jsx)(ef.Tag,{color:y?.scheduled?y.last_run?"success":"processing":"default",children:y?.scheduled?y.last_run?"Active":"Ready":"Not scheduled"})]})]})]})}),(0,t.jsxs)(el.Modal,{title:"Set Up Periodic Reload",open:g,onOk:L,onCancel:()=>f(!1),confirmLoading:m,okText:"Schedule",cancelText:"Cancel",okButtonProps:{style:{backgroundColor:"#6366f1",borderColor:"#6366f1",color:"white"}},children:[(0,t.jsx)("div",{style:{marginBottom:16},children:(0,t.jsx)(eT,{children:"Set up automatic reload of price data every:"})}),(0,t.jsx)("div",{style:{marginBottom:16},children:(0,t.jsx)(eh.InputNumber,{min:1,max:168,value:j,onChange:e=>_(e||6),addonAfter:"hours",style:{width:"100%"}})}),(0,t.jsx)("div",{children:(0,t.jsxs)(eT,{type:"secondary",children:["This will automatically fetch the latest pricing data from the remote source every ",j," hours."]})})]})]})},eI=()=>{let{accessToken:e}=(0,r.default)(),{refetch:l}=(0,n.useModelCostMap)();return(0,t.jsx)(U.TabPanel,{children:(0,t.jsxs)("div",{className:"p-6",children:[(0,t.jsxs)("div",{className:"mb-6",children:[(0,t.jsx)(eu.Title,{children:"Price Data Management"}),(0,t.jsx)(em.Text,{className:"text-tremor-content",children:"Manage model pricing data and configure automatic reload schedules"})]}),(0,t.jsx)(eF,{accessToken:e,onReloadSuccess:()=>{l()},buttonText:"Reload Price Data",size:"middle",type:"primary",className:"w-full"})]})})};var eM=e.i(916925);let eP=async(e,t,l)=>{try{console.log("handling submit for formValues:",e);let t=e.model_mappings||[];if("model_mappings"in e&&delete e.model_mappings,e.model&&e.model.includes("all-wildcard")){let l=e.custom_llm_provider,s=(eM.provider_map[l]??l.toLowerCase())+"/*";e.model_name=s,t.push({public_name:s,litellm_model:s}),e.model=s}let l=[];for(let s of t){let t={},a={},r=s.public_name;for(let[l,r]of(t.model=s.litellm_model,void 0!==e.input_cost_per_token&&null!==e.input_cost_per_token&&""!==e.input_cost_per_token&&(e.input_cost_per_token=Number(e.input_cost_per_token)/1e6),void 0!==e.output_cost_per_token&&null!==e.output_cost_per_token&&""!==e.output_cost_per_token&&(e.output_cost_per_token=Number(e.output_cost_per_token)/1e6),t.model=s.litellm_model,console.log("formValues add deployment:",e),Object.entries(e)))if(""!==r&&"custom_pricing"!==l&&"pricing_model"!==l&&"cache_control"!==l)if("model_name"==l)t.model=r;else if("custom_llm_provider"==l){console.log("custom_llm_provider:",r);let e=eM.provider_map[r]??r.toLowerCase();t.custom_llm_provider=e,console.log("custom_llm_provider mappingResult:",e)}else if("model"==l)continue;else if("base_model"===l)a[l]=r;else if("team_id"===l)a.team_id=r;else if("model_access_group"===l)a.access_groups=r;else if("mode"==l)console.log("placing mode in modelInfo"),a.mode=r,delete t.mode;else if("custom_model_name"===l)t.model=r;else if("litellm_extra_params"==l){console.log("litellm_extra_params:",r);let e={};if(r&&void 0!=r){try{e=JSON.parse(r),"litellm_credential_name"in e&&delete e.litellm_credential_name}catch(e){throw D.default.fromBackend("Failed to parse LiteLLM Extra Params: "+e),Error("Failed to parse litellm_extra_params: "+e)}for(let[l,s]of Object.entries(e))t[l]=s}}else if("model_info_params"==l){console.log("model_info_params:",r);let e={};if(r&&void 0!=r){try{e=JSON.parse(r)}catch(e){throw D.default.fromBackend("Failed to parse LiteLLM Extra Params: "+e),Error("Failed to parse litellm_extra_params: "+e)}for(let[t,l]of Object.entries(e))a[t]=l}}else if("input_cost_per_token"===l||"output_cost_per_token"===l||"input_cost_per_second"===l){null!=r&&""!==r&&(t[l]=Number(r));continue}else t[l]=r;l.push({litellmParamsObj:t,modelInfoObj:a,modelName:r})}return l}catch(e){D.default.fromBackend("Failed to create model: "+e)}},eA=async(e,t,s,a)=>{try{let r=await eP(e,t,s);if(!r||0===r.length)return;for(let e of r){let{litellmParamsObj:s,modelInfoObj:a,modelName:r}=e,i={model_name:r,litellm_params:s,model_info:a},o=await (0,l.modelCreateCall)(t,i);console.log(`response for model create call: ${o.data}`)}a&&a(),s.resetFields()}catch(e){D.default.fromBackend("Failed to add model: "+e)}};var eE=e.i(591935),eL=e.i(304967),eR=e.i(779241);let eO=(0,a.createQueryKeys)("providerFields"),eB=()=>(0,s.useQuery)({queryKey:eO.list({}),queryFn:async()=>await (0,l.getProviderCreateMetadata)(),staleTime:864e5,gcTime:864e5});var ez=e.i(519756),eq=e.i(178654),eV=e.i(311451),eD=e.i(621192),eH=e.i(515831);let{Link:eG}=L.Typography,e$=e=>{let t="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:e.placeholder??void 0,tooltip:e.tooltip??void 0,required:e.required??!1,type:t,options:e.options??void 0,defaultValue:e.default_value??void 0}},eU={},eJ=({selectedProvider:e,uploadProps:l})=>{let s=eM.Providers[e],a=et.Form.useFormInstance(),{data:r,isLoading:i,error:o}=eB(),n=x.default.useMemo(()=>{if(!r)return null;let e={};return r.forEach(t=>{let l=t.provider_display_name,s=t.credential_fields.map(e$);e[l]=s,t.provider&&(e[t.provider]=s),t.litellm_provider&&(e[t.litellm_provider]=s)}),e},[r]);x.default.useEffect(()=>{n&&Object.assign(eU,n)},[n]);let d=x.default.useMemo(()=>{let t=eU[s]??eU[e];if(t)return t;if(!r)return[];let l=r.find(t=>t.provider_display_name===s||t.provider===e||t.litellm_provider===e);if(!l)return[];let a=l.credential_fields.map(e$);return eU[l.provider_display_name]=a,l.provider&&(eU[l.provider]=a),l.litellm_provider&&(eU[l.litellm_provider]=a),a},[s,e,r]),c={name:"file",accept:".json",beforeUpload:e=>{if("application/json"===e.type){let t=new FileReader;t.onload=e=>{if(e.target){let t=e.target.result;console.log(`Setting field value from JSON, length: ${t.length}`),a.setFieldsValue({vertex_credentials:t}),console.log("Form values after setting:",a.getFieldsValue())}},t.readAsText(e)}return!1},onChange(e){console.log("Upload onChange triggered in ProviderSpecificFields"),console.log("Current form values:",a.getFieldsValue()),"uploading"!==e.file.status&&console.log(e.file,e.fileList)}};return(0,t.jsxs)(t.Fragment,{children:[i&&0===d.length&&(0,t.jsx)(eD.Row,{children:(0,t.jsx)(eq.Col,{span:24,children:(0,t.jsx)(em.Text,{className:"mb-2",children:"Loading provider fields..."})})}),o&&0===d.length&&(0,t.jsx)(eD.Row,{children:(0,t.jsx)(eq.Col,{span:24,children:(0,t.jsx)(em.Text,{className:"mb-2 text-red-500",children:o instanceof Error?o.message:"Failed to load provider credential fields"})})}),d.map(e=>(0,t.jsxs)(x.default.Fragment,{children:[(0,t.jsx)(et.Form.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,t.jsx)(W.Select,{placeholder:e.placeholder,defaultValue:e.defaultValue,children:e.options?.map(e=>(0,t.jsx)(W.Select.Option,{value:e,children:e},e))}):"upload"===e.type?(0,t.jsx)(eH.Upload,{...c,onChange:t=>{l?.onChange&&l.onChange(t),setTimeout(()=>{let t=a.getFieldValue(e.key);console.log(`${e.key} value after upload:`,JSON.stringify(t))},500)},children:(0,t.jsx)(K.Button,{icon:(0,t.jsx)(ez.UploadOutlined,{}),children:"Click to Upload"})}):"textarea"===e.type?(0,t.jsx)(eV.Input.TextArea,{placeholder:e.placeholder,defaultValue:e.defaultValue,rows:6,style:{fontFamily:"monospace",fontSize:"12px"}}):(0,t.jsx)(eR.TextInput,{placeholder:e.placeholder,type:"password"===e.type?"password":"text",defaultValue:e.defaultValue})}),"vertex_credentials"===e.key&&(0,t.jsx)(eD.Row,{children:(0,t.jsx)(eq.Col,{children:(0,t.jsx)(em.Text,{className:"mb-3 mt-1",children:"Give a gcp service account(.json file)"})})}),"base_model"===e.key&&(0,t.jsxs)(eD.Row,{children:[(0,t.jsx)(eq.Col,{span:10}),(0,t.jsx)(eq.Col,{span:10,children:(0,t.jsxs)(em.Text,{className:"mb-2",children:["The actual model your azure deployment uses. Used for accurate cost tracking. Select name from"," ",(0,t.jsx)(eG,{href:"https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json",target:"_blank",children:"here"})]})})]})]},e.key))]})},{Link:eK}=L.Typography,eW=({open:e,onCancel:l,onAddCredential:s,uploadProps:a})=>{let[r]=et.Form.useForm(),[i,o]=(0,x.useState)(eM.Providers.OpenAI);return(0,t.jsx)(el.Modal,{title:"Add New Credential",open:e,onCancel:()=>{l(),r.resetFields()},footer:null,width:600,children:(0,t.jsxs)(et.Form,{form:r,onFinish:e=>{s(Object.entries(e).reduce((e,[t,l])=>(""!==l&&null!=l&&(e[t]=l),e),{})),r.resetFields()},layout:"vertical",children:[(0,t.jsx)(et.Form.Item,{label:"Credential Name:",name:"credential_name",rules:[{required:!0,message:"Credential name is required"}],children:(0,t.jsx)(eR.TextInput,{placeholder:"Enter a friendly name for these credentials"})}),(0,t.jsx)(et.Form.Item,{rules:[{required:!0,message:"Required"}],label:"Provider:",name:"custom_llm_provider",tooltip:"Helper to auto-populate provider specific fields",children:(0,t.jsx)(W.Select,{showSearch:!0,onChange:e=>{o(e),r.setFieldValue("custom_llm_provider",e)},children:Object.entries(eM.Providers).map(([e,l])=>(0,t.jsx)(W.Select.Option,{value:e,children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("img",{src:eM.providerLogoMap[l],alt:`${e} logo`,className:"w-5 h-5",onError:e=>{let t=e.target,s=t.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=l.charAt(0),s.replaceChild(e,t)}}}),(0,t.jsx)("span",{children:l})]})},e))})}),(0,t.jsx)(eJ,{selectedProvider:i,uploadProps:a}),(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[(0,t.jsx)(E.Tooltip,{title:"Get help on our github",children:(0,t.jsx)(eK,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,t.jsxs)("div",{children:[(0,t.jsx)(K.Button,{onClick:()=>{l(),r.resetFields()},style:{marginRight:10},children:"Cancel"}),(0,t.jsx)(K.Button,{htmlType:"submit",children:"Add Credential"})]})]})]})})},{Link:eQ}=L.Typography;function eY({open:e,onCancel:l,onUpdateCredential:s,uploadProps:a,existingCredential:r}){let[i]=et.Form.useForm(),[o,n]=(0,x.useState)(eM.Providers.Anthropic);return(0,x.useEffect)(()=>{if(r){let e=Object.entries(r.credential_values||{}).reduce((e,[t,l])=>(e[t]=l??null,e),{});i.setFieldsValue({credential_name:r.credential_name,custom_llm_provider:r.credential_info.custom_llm_provider,...e}),n(r.credential_info.custom_llm_provider)}},[r]),(0,t.jsx)(el.Modal,{title:"Edit Credential",open:e,onCancel:()=>{l(),i.resetFields()},footer:null,width:600,destroyOnHidden:!0,children:(0,t.jsxs)(et.Form,{form:i,onFinish:e=>{s(Object.entries(e).reduce((e,[t,l])=>(""!==l&&null!=l&&(e[t]=l),e),{})),i.resetFields()},layout:"vertical",children:[(0,t.jsx)(et.Form.Item,{label:"Credential Name:",name:"credential_name",rules:[{required:!0,message:"Credential name is required"}],initialValue:r?.credential_name,children:(0,t.jsx)(eR.TextInput,{placeholder:"Enter a friendly name for these credentials",disabled:!!r?.credential_name})}),(0,t.jsx)(et.Form.Item,{rules:[{required:!0,message:"Required"}],label:"Provider:",name:"custom_llm_provider",tooltip:"Helper to auto-populate provider specific fields",children:(0,t.jsx)(W.Select,{showSearch:!0,onChange:e=>{n(e),i.setFieldValue("custom_llm_provider",e)},children:Object.entries(eM.Providers).map(([e,l])=>(0,t.jsx)(W.Select.Option,{value:e,children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("img",{src:eM.providerLogoMap[l],alt:`${e} logo`,className:"w-5 h-5",onError:e=>{let t=e.target,s=t.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=l.charAt(0),s.replaceChild(e,t)}}}),(0,t.jsx)("span",{children:l})]})},e))})}),(0,t.jsx)(eJ,{selectedProvider:o,uploadProps:a}),(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[(0,t.jsx)(E.Tooltip,{title:"Get help on our github",children:(0,t.jsx)(eQ,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,t.jsxs)("div",{children:[(0,t.jsx)(K.Button,{onClick:()=>{l(),i.resetFields()},style:{marginRight:10},children:"Cancel"}),(0,t.jsx)(K.Button,{htmlType:"submit",children:"Update Credential"})]})]})]})})}let eX=({uploadProps:e})=>{let{accessToken:s}=(0,r.default)(),{data:a,refetch:i}=o(),n=a?.credentials||[],[d,c]=(0,x.useState)(!1),[m,u]=(0,x.useState)(!1),[h,b]=(0,x.useState)(null),[v,N]=(0,x.useState)(null),[w,C]=(0,x.useState)(!1),[F,I]=(0,x.useState)(!1),[M]=et.Form.useForm(),P=["credential_name","custom_llm_provider"],A=async e=>{if(!s)return;let t=Object.entries(e).filter(([e])=>!P.includes(e)).reduce((e,[t,l])=>({...e,[t]:l}),{}),a={credential_name:e.credential_name,credential_values:t,credential_info:{custom_llm_provider:e.custom_llm_provider}};await (0,l.credentialUpdateCall)(s,e.credential_name,a),D.default.success("Credential updated successfully"),u(!1),await i()},E=async e=>{if(!s)return;let t=Object.entries(e).filter(([e])=>!P.includes(e)).reduce((e,[t,l])=>({...e,[t]:l}),{}),a={credential_name:e.credential_name,credential_values:t,credential_info:{custom_llm_provider:e.custom_llm_provider}};await (0,l.credentialCreateCall)(s,a),D.default.success("Credential added successfully"),c(!1),await i()},L=async()=>{if(s&&v){I(!0);try{await (0,l.credentialDeleteCall)(s,v.credential_name),D.default.success("Credential deleted successfully"),await i()}catch(e){D.default.error("Failed to delete credential")}finally{N(null),C(!1),I(!1)}}};return(0,t.jsxs)("div",{className:"w-full mx-auto flex-auto overflow-y-auto p-2",children:[(0,t.jsx)(T.Button,{onClick:()=>c(!0),children:"Add Credential"}),(0,t.jsx)("div",{className:"flex justify-between items-center mt-4 mb-4",children:(0,t.jsx)(em.Text,{children:"Configured credentials for different AI providers. Add and manage your API credentials."})}),(0,t.jsx)(eL.Card,{children:(0,t.jsxs)(p.Table,{children:[(0,t.jsx)(g.TableHead,{children:(0,t.jsxs)(_.TableRow,{children:[(0,t.jsx)(f.TableHeaderCell,{children:"Credential Name"}),(0,t.jsx)(f.TableHeaderCell,{children:"Provider"}),(0,t.jsx)(f.TableHeaderCell,{children:"Actions"})]})}),(0,t.jsx)(j.TableBody,{children:n&&0!==n.length?n.map((e,l)=>{var s;let a,r;return(0,t.jsxs)(_.TableRow,{children:[(0,t.jsx)(y.TableCell,{children:e.credential_name}),(0,t.jsx)(y.TableCell,{children:(s=e.credential_info?.custom_llm_provider||"-",r=(a={openai:"blue",azure:"indigo",anthropic:"purple",default:"gray"})[s.toLowerCase()]||a.default,(0,t.jsx)(k.Badge,{color:r,size:"xs",children:s}))}),(0,t.jsxs)(y.TableCell,{children:[(0,t.jsx)(T.Button,{icon:eE.PencilAltIcon,variant:"light",size:"sm",onClick:()=>{b(e),u(!0)}}),(0,t.jsx)(T.Button,{icon:S.TrashIcon,variant:"light",size:"sm",onClick:()=>{N(e),C(!0)},className:"ml-2"})]})]},l)}):(0,t.jsx)(_.TableRow,{children:(0,t.jsx)(y.TableCell,{colSpan:4,className:"text-center py-4 text-gray-500",children:"No credentials configured"})})})]})}),d&&(0,t.jsx)(eW,{onAddCredential:E,open:d,onCancel:()=>c(!1),uploadProps:e}),m&&(0,t.jsx)(eY,{open:m,existingCredential:h,onUpdateCredential:A,uploadProps:e,onCancel:()=>u(!1)}),(0,t.jsx)(V.default,{isOpen:w,onCancel:()=>{N(null),C(!1)},onOk:L,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:v?.credential_name},{label:"Provider",value:v?.credential_info?.custom_llm_provider||"-"}],confirmLoading:F,requiredConfirmation:v?.credential_name})]})};var eZ=e.i(708347),e0=e.i(278587),e1=e.i(309426),e2=e.i(197647),e4=e.i(653824),e5=e.i(881073),e6=e.i(723731),e3=e.i(475647),e8=e.i(91739),e7=e.i(437902),e9=e.i(166406);let{Text:te}=L.Typography,tt=({formValues:e,accessToken:s,testMode:a,modelName:r="this model",onClose:i,onTestComplete:o})=>{var n,d,c;let m,u,[h,p]=x.default.useState(null),[g,f]=x.default.useState(null),[j,_]=x.default.useState(null),[y,b]=x.default.useState(!0),[v,N]=x.default.useState(!1),[C,S]=x.default.useState(!1),k=async()=>{b(!0),S(!1),p(null),f(null),_(null),N(!1),await new Promise(e=>setTimeout(e,100));try{console.log("Testing connection with form values:",e);let t=await eP(e,s,null);if(!t){console.log("No result from prepareModelAddRequest"),p("Failed to prepare model data. Please check your form inputs."),N(!1),b(!1);return}console.log("Result from prepareModelAddRequest:",t);let{litellmParamsObj:a,modelInfoObj:r,modelName:i}=t[0],o=await (0,l.testConnectionRequest)(s,a,r,r?.mode);if("success"===o.status)D.default.success("Connection test successful!"),p(null),N(!0);else{let e=o.result?.error||o.message||"Unknown error";p(e),f(a),_(o.result?.raw_request_typed_dict),N(!1)}}catch(e){console.error("Test connection error:",e),p(e instanceof Error?e.message:String(e)),N(!1)}finally{b(!1),o&&o()}};x.default.useEffect(()=>{let e=setTimeout(()=>{k()},200);return()=>clearTimeout(e)},[]);let T=e=>e?e.split("stack trace:")[0].trim().replace(/^litellm\.(.*?)Error: /,""):"Unknown error",F="string"==typeof h?T(h):h?.message?T(h.message):"Unknown error",M=j?(n=j.raw_request_api_base,d=j.raw_request_body,c=j.raw_request_headers||{},m=JSON.stringify(d,null,2).split("\n").map(e=>` ${e}`).join("\n"),u=Object.entries(c).map(([e,t])=>`-H '${e}: ${t}'`).join(" \\\n "),`curl -X POST \\ + ${n} \\ + ${u?`${u} \\ + `:""}-H 'Content-Type: application/json' \\ + -d '{ +${m} + }'`):"";return(0,t.jsxs)("div",{style:{padding:"24px",borderRadius:"8px",backgroundColor:"#fff"},children:[y?(0,t.jsxs)("div",{style:{textAlign:"center",padding:"32px 20px"},className:"jsx-dc9a0e2d897fe63b",children:[(0,t.jsx)("div",{style:{marginBottom:"16px"},className:"jsx-dc9a0e2d897fe63b loading-spinner",children:(0,t.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,t.jsxs)(te,{style:{fontSize:"16px"},children:["Testing connection to ",r,"..."]}),(0,t.jsx)(e7.default,{id:"dc9a0e2d897fe63b",children:"@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}"})]}):v?(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"32px 20px"},children:[(0,t.jsx)("div",{style:{color:"#52c41a",fontSize:"24px",display:"flex",alignItems:"center"},children:(0,t.jsx)("svg",{viewBox:"64 64 896 896",focusable:"false","data-icon":"check-circle",width:"1em",height:"1em",fill:"currentColor","aria-hidden":"true",children:(0,t.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,t.jsxs)(te,{type:"success",style:{fontSize:"18px",fontWeight:500,marginLeft:"10px"},children:["Connection to ",r," successful!"]})]}):(0,t.jsx)(t.Fragment,{children:(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",marginBottom:"20px"},children:[(0,t.jsx)(ek.WarningOutlined,{style:{color:"#ff4d4f",fontSize:"24px",marginRight:"12px"}}),(0,t.jsxs)(te,{type:"danger",style:{fontSize:"18px",fontWeight:500},children:["Connection to ",r," failed"]})]}),(0,t.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,t.jsxs)(te,{strong:!0,style:{display:"block",marginBottom:"8px"},children:["Error:"," "]}),(0,t.jsx)(te,{type:"danger",style:{fontSize:"14px",lineHeight:"1.5"},children:F}),h&&(0,t.jsx)("div",{style:{marginTop:"12px"},children:(0,t.jsx)(K.Button,{type:"link",onClick:()=>S(!C),style:{paddingLeft:0,height:"auto"},children:C?"Hide Details":"Show Details"})})]}),C&&(0,t.jsxs)("div",{style:{marginBottom:"20px"},children:[(0,t.jsx)(te,{strong:!0,style:{display:"block",marginBottom:"8px",fontSize:"15px"},children:"Troubleshooting Details"}),(0,t.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 h?h:JSON.stringify(h,null,2)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(te,{strong:!0,style:{display:"block",marginBottom:"8px",fontSize:"15px"},children:"API Request"}),(0,t.jsx)("pre",{style:{backgroundColor:"#f5f5f5",padding:"16px",borderRadius:"8px",fontSize:"13px",maxHeight:"250px",overflow:"auto",border:"1px solid #e8e8e8",lineHeight:"1.5"},children:M||"No request data available"}),(0,t.jsx)(K.Button,{style:{marginTop:"8px"},icon:(0,t.jsx)(e9.CopyOutlined,{}),onClick:()=>{navigator.clipboard.writeText(M||""),D.default.success("Copied to clipboard")},children:"Copy to Clipboard"})]})]})}),(0,t.jsx)(I.Divider,{style:{margin:"24px 0 16px"}}),(0,t.jsx)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:(0,t.jsx)(K.Button,{type:"link",href:"https://docs.litellm.ai/docs/providers",target:"_blank",icon:(0,t.jsx)(w.InfoCircleOutlined,{}),children:"View Documentation"})})]})},tl=async(e,t,s,a)=>{try{let r;console.log("=== AUTO ROUTER SUBMIT HANDLER CALLED ==="),console.log("handling auto router submit for formValues:",e),console.log("Model type:",e.model_type),"complexity_router"===e.model_type?(console.log("Creating complexity router configuration"),r={model_name:e.auto_router_name,litellm_params:{model:"auto_router/complexity_router",complexity_router_config:e.complexity_router_config,complexity_router_default_model:e.auto_router_default_model},model_info:{}},console.log("Complexity router config:",e.complexity_router_config)):(console.log("Creating semantic router configuration"),r={model_name:e.auto_router_name,litellm_params:{model:`auto_router/${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),console.log("Semantic router config (stringified):",r.litellm_params.auto_router_config)),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("Calling modelCreateCall...");let i=await (0,l.modelCreateCall)(t,r);console.log("response for auto router create call:",i);let o="complexity_router"===e.model_type?"Complexity Router":"Semantic Router";D.default.success(`Successfully created ${o}: ${e.auto_router_name}`),s.resetFields(),a&&a()}catch(e){console.error("Failed to add auto router:",e),D.default.fromBackend("Failed to add auto router: "+e)}};var ts=e.i(689020),ta=e.i(955135),tr=e.i(646563),ti=e.i(362024),to=e.i(21548);let{Text:tn}=L.Typography,{TextArea:td}=eV.Input,tc=({modelInfo:e,value:l,onChange:s})=>{let[a,r]=(0,x.useState)([]),[i,o]=(0,x.useState)(!1),[n,d]=(0,x.useState)([]);(0,x.useEffect)(()=>{let e=l?.routes;if(e){let t=[];r(l=>e.map((e,s)=>{let a=l[s],r=a?.id||e.id||`route-${s}-${Date.now()}`;return t.push(r),{id:r,model:e.name||e.model||"",utterances:e.utterances||[],description:e.description||"",score_threshold:e.score_threshold??.5}})),d(t)}else r([]),d([])},[l]);let c=(e,t,l)=>{let s=a.map(s=>s.id===e?{...s,[t]:l}:s);r(s),m(s)},m=e=>{let t={routes:e.map(e=>({name:e.model,utterances:e.utterances,description:e.description,score_threshold:e.score_threshold}))};s?.(t)},u=e.map(e=>({value:e.model_group,label:e.model_group}));return(0,t.jsxs)("div",{className:"w-full max-w-none",children:[(0,t.jsxs)(M.Flex,{justify:"space-between",align:"center",gap:"middle",style:{width:"100%",marginBottom:24},children:[(0,t.jsxs)(A.Space,{align:"center",children:[(0,t.jsx)(L.Typography.Title,{level:4,style:{margin:0},children:"Routes Configuration"}),(0,t.jsx)(E.Tooltip,{title:"Configure routing logic to automatically select the best model based on user input patterns",children:(0,t.jsx)(w.InfoCircleOutlined,{className:"text-gray-400"})})]}),(0,t.jsx)(K.Button,{type:"primary",icon:(0,t.jsx)(tr.PlusOutlined,{}),onClick:()=>{let e=`route-${Date.now()}`,t=[...a,{id:e,model:"",utterances:[],description:"",score_threshold:.5}];r(t),m(t),d(t=>[...t,e])},className:"bg-blue-600 hover:bg-blue-700",children:"Add Route"})]}),0===a.length?(0,t.jsx)(ej.Card,{children:(0,t.jsx)(to.Empty,{description:'No routes configured. Click "Add Route" to get started.'})}):(0,t.jsx)(ti.Collapse,{activeKey:n,onChange:e=>d(Array.isArray(e)?e:[e].filter(Boolean)),style:{width:"100%"},items:a.map((e,l)=>({key:e.id,label:(0,t.jsxs)(tn,{style:{fontSize:16},children:["Route ",l+1,": ",e.model||"Unnamed"]}),extra:(0,t.jsx)(K.Button,{type:"text",danger:!0,size:"small",icon:(0,t.jsx)(ta.DeleteOutlined,{}),onClick:t=>{var l;let s;t.stopPropagation(),l=e.id,r(s=a.filter(e=>e.id!==l)),m(s),d(e=>e.filter(e=>e!==l))}}),children:(0,t.jsxs)(ej.Card,{children:[(0,t.jsxs)("div",{className:"mb-4 w-full",children:[(0,t.jsx)(tn,{className:"text-sm font-medium mb-2 block",children:"Model"}),(0,t.jsx)(W.Select,{value:e.model,onChange:t=>c(e.id,"model",t),placeholder:"Select model",showSearch:!0,style:{width:"100%"},options:u})]}),(0,t.jsxs)("div",{className:"mb-4 w-full",children:[(0,t.jsx)(tn,{className:"text-sm font-medium mb-2 block",children:"Description"}),(0,t.jsx)(td,{value:e.description,onChange:t=>c(e.id,"description",t.target.value),placeholder:"Describe when this route should be used...",rows:2,style:{width:"100%"}})]}),(0,t.jsxs)("div",{className:"mb-4 w-full",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 mb-2",children:[(0,t.jsx)(tn,{className:"text-sm font-medium",children:"Score Threshold"}),(0,t.jsx)(E.Tooltip,{title:"Minimum similarity score to route to this model (0-1)",children:(0,t.jsx)(w.InfoCircleOutlined,{className:"text-gray-400"})})]}),(0,t.jsx)(eh.InputNumber,{value:e.score_threshold,onChange:t=>c(e.id,"score_threshold",t||0),min:0,max:1,step:.1,style:{width:"100%"},placeholder:"0.5"})]}),(0,t.jsxs)("div",{className:"w-full",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 mb-2",children:[(0,t.jsx)(tn,{className:"text-sm font-medium",children:"Example Utterances"}),(0,t.jsx)(E.Tooltip,{title:"Training examples for this route. Type an utterance and press Enter to add it.",children:(0,t.jsx)(w.InfoCircleOutlined,{className:"text-gray-400"})})]}),(0,t.jsx)(tn,{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,t.jsx)(W.Select,{mode:"tags",value:e.utterances,onChange:t=>c(e.id,"utterances",t),placeholder:"Type an utterance and press Enter...",style:{width:"100%"},tokenSeparators:["\n"],maxTagCount:"responsive",allowClear:!0})]})]},e.id)}))}),(0,t.jsx)(I.Divider,{}),(0,t.jsxs)("div",{className:"flex justify-between items-center mb-4 w-full",children:[(0,t.jsx)(tn,{className:"text-lg font-semibold",children:"JSON Preview"}),(0,t.jsx)(K.Button,{type:"link",onClick:()=>o(!i),className:"text-blue-600 p-0",children:i?"Hide":"Show"})]}),i&&(0,t.jsx)(ej.Card,{className:"bg-gray-50 w-full",children:(0,t.jsx)("pre",{className:"text-sm overflow-auto max-h-64 w-full",children:JSON.stringify({routes:a.map(e=>({name:e.model,utterances:e.utterances,description:e.description,score_threshold:e.score_threshold}))},null,2)})})]})},{Text:tm}=L.Typography,tu={SIMPLE:{label:"Simple",description:"Basic questions, greetings, simple factual queries",examples:'"Hello!", "What is Python?", "Thanks!"'},MEDIUM:{label:"Medium",description:"Standard queries requiring some reasoning or explanation",examples:'"Explain how REST APIs work", "Debug this error"'},COMPLEX:{label:"Complex",description:"Technical, multi-part requests requiring deep knowledge",examples:'"Design a microservices architecture", "Implement a rate limiter"'},REASONING:{label:"Reasoning",description:"Chain-of-thought, analysis, explicit reasoning requests",examples:'"Think step by step...", "Analyze the pros and cons..."'}},th=({modelInfo:e,value:l,onChange:s})=>{let a=e.map(e=>({value:e.model_group,label:e.model_group}));return(0,t.jsxs)("div",{className:"w-full max-w-none",children:[(0,t.jsxs)(A.Space,{align:"center",style:{marginBottom:16},children:[(0,t.jsx)(L.Typography.Title,{level:4,style:{margin:0},children:"Complexity Tier Configuration"}),(0,t.jsx)(E.Tooltip,{title:"Map each complexity tier to a model. Simple queries use cheaper/faster models, complex queries use more capable models.",children:(0,t.jsx)(w.InfoCircleOutlined,{className:"text-gray-400"})})]}),(0,t.jsx)(tm,{type:"secondary",style:{display:"block",marginBottom:24},children:"The complexity router automatically classifies requests by complexity using rule-based scoring (no API calls, <1ms latency). Configure which model handles each tier."}),(0,t.jsx)(ej.Card,{children:Object.keys(tu).map((e,r)=>{let i=tu[e];return(0,t.jsxs)("div",{children:[r>0&&(0,t.jsx)(I.Divider,{style:{margin:"16px 0"}}),(0,t.jsxs)("div",{className:"mb-4",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 mb-2",children:[(0,t.jsxs)(tm,{strong:!0,style:{fontSize:16},children:[i.label," Tier"]}),(0,t.jsx)(E.Tooltip,{title:i.description,children:(0,t.jsx)(w.InfoCircleOutlined,{className:"text-gray-400"})})]}),(0,t.jsxs)(tm,{type:"secondary",style:{display:"block",marginBottom:8,fontSize:12},children:["Examples: ",i.examples]}),(0,t.jsx)(W.Select,{value:l[e],onChange:t=>{s({...l,[e]:t})},placeholder:`Select model for ${i.label.toLowerCase()} queries`,showSearch:!0,style:{width:"100%"},options:a})]})]},e)})}),(0,t.jsx)(I.Divider,{}),(0,t.jsxs)(ej.Card,{className:"bg-gray-50",children:[(0,t.jsx)(tm,{strong:!0,style:{display:"block",marginBottom:8},children:"How Classification Works"}),(0,t.jsx)(tm,{type:"secondary",style:{fontSize:13},children:"The router scores each request across 7 dimensions: token count, code presence, reasoning markers, technical terms, simple indicators, multi-step patterns, and question complexity. The weighted score determines the tier:"}),(0,t.jsxs)("ul",{style:{marginTop:8,marginBottom:0,paddingLeft:20,fontSize:13,color:"rgba(0, 0, 0, 0.45)"},children:[(0,t.jsxs)("li",{children:[(0,t.jsx)("strong",{children:"SIMPLE"}),": Score < 0.15"]}),(0,t.jsxs)("li",{children:[(0,t.jsx)("strong",{children:"MEDIUM"}),": Score 0.15 - 0.35"]}),(0,t.jsxs)("li",{children:[(0,t.jsx)("strong",{children:"COMPLEX"}),": Score 0.35 - 0.60"]}),(0,t.jsxs)("li",{children:[(0,t.jsx)("strong",{children:"REASONING"}),": Score > 0.60 (or 2+ reasoning markers)"]})]})]})]})};var tx=e.i(962944);let tp={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M740 161c-61.8 0-112 50.2-112 112 0 50.1 33.1 92.6 78.5 106.9v95.9L320 602.4V318.1c44.2-15 76-56.9 76-106.1 0-61.8-50.2-112-112-112s-112 50.2-112 112c0 49.2 31.8 91 76 106.1V706c-44.2 15-76 56.9-76 106.1 0 61.8 50.2 112 112 112s112-50.2 112-112c0-49.2-31.8-91-76-106.1v-27.8l423.5-138.7a50.52 50.52 0 0034.9-48.2V378.2c42.9-15.8 73.6-57 73.6-105.2 0-61.8-50.2-112-112-112zm-504 51a48.01 48.01 0 0196 0 48.01 48.01 0 01-96 0zm96 600a48.01 48.01 0 01-96 0 48.01 48.01 0 0196 0zm408-491a48.01 48.01 0 010-96 48.01 48.01 0 010 96z"}}]},name:"branches",theme:"outlined"};var tg=x.forwardRef(function(e,t){return x.createElement(ew.default,(0,ev.default)({},e,{ref:t,icon:tp}))});let{Title:tf,Link:tj}=L.Typography,t_=({form:e,handleOk:s,accessToken:a,userRole:r})=>{let[i,o]=(0,x.useState)(!1),[n,d]=(0,x.useState)(!1),[c,m]=(0,x.useState)(""),[u,h]=(0,x.useState)([]),[p,g]=(0,x.useState)([]),[f,j]=(0,x.useState)(!1),[_,y]=(0,x.useState)(!1),[b,v]=(0,x.useState)("complexity"),[N,w]=(0,x.useState)(null),[C,S]=(0,x.useState)({SIMPLE:"",MEDIUM:"",COMPLEX:"",REASONING:""});(0,x.useEffect)(()=>{(async()=>{h((await (0,l.modelAvailableCall)(a,"","",!1,null,!0,!0)).data.map(e=>e.id))})()},[a]),(0,x.useEffect)(()=>{(async()=>{try{let e=await (0,ts.fetchAvailableModels)(a);console.log("Fetched models for auto router:",e),g(e)}catch(e){console.error("Error fetching model info for auto router:",e)}})()},[a]);let k=eZ.all_admin_roles.includes(r),T=async()=>{d(!0),m(`test-${Date.now()}`),o(!0)},F=()=>{console.log("Auto router submit triggered!"),console.log("Router type:",b);let t=e.getFieldsValue();if(console.log("Form values:",t),!t.auto_router_name)return void D.default.fromBackend("Please enter an Auto Router Name");if("complexity"===b){if(0===Object.values(C).filter(Boolean).length)return void D.default.fromBackend("Please select at least one model for a complexity tier");let l=C.MEDIUM||C.SIMPLE||C.COMPLEX||C.REASONING;e.setFieldsValue({custom_llm_provider:"auto_router",model:t.auto_router_name,api_key:"not_required_for_auto_router",auto_router_default_model:l}),e.validateFields(["auto_router_name"]).then(r=>{console.log("Complexity router validation passed");let i={...r,auto_router_name:t.auto_router_name,auto_router_default_model:l,model_type:"complexity_router",complexity_router_config:{tiers:C},model_access_group:t.model_access_group};console.log("Final submit values:",i),tl(i,a,e,s)}).catch(e=>{console.error("Validation failed:",e),D.default.fromBackend("Please fill in all required fields")})}else{if(!t.auto_router_default_model)return void D.default.fromBackend("Please select a Default Model");if(e.setFieldsValue({custom_llm_provider:"auto_router",model:t.auto_router_name,api_key:"not_required_for_auto_router"}),!N||!N.routes||0===N.routes.length)return void D.default.fromBackend("Please configure at least one route for the auto router");if(N.routes.filter(e=>!e.name||!e.description||0===e.utterances.length).length>0)return void D.default.fromBackend("Please ensure all routes have a target model, description, and at least one utterance");e.validateFields().then(t=>{console.log("Form validation passed, submitting with values:",t);let l={...t,auto_router_config:N,model_type:"semantic_router"};console.log("Final submit values:",l),tl(l,a,e,s)}).catch(e=>{console.error("Validation failed:",e);let t=e.errorFields||[];if(t.length>0){let e=t.map(e=>{let t=e.name[0];return({auto_router_name:"Auto Router Name",auto_router_default_model:"Default Model",auto_router_embedding_model:"Embedding Model"})[t]||t});D.default.fromBackend(`Please fill in the following required fields: ${e.join(", ")}`)}else D.default.fromBackend("Please fill in all required fields")})}};return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(tf,{level:2,children:"Add Auto Router"}),(0,t.jsx)(em.Text,{className:"text-gray-600 mb-6",children:"Create an auto router that automatically selects the best model based on request complexity or semantic matching."}),(0,t.jsx)(ej.Card,{className:"mb-4",children:(0,t.jsxs)("div",{className:"mb-4",children:[(0,t.jsx)(em.Text,{className:"text-sm font-medium mb-2 block",children:"Router Type"}),(0,t.jsx)(e8.Radio.Group,{value:b,onChange:e=>v(e.target.value),className:"w-full",children:(0,t.jsxs)(A.Space,{direction:"vertical",className:"w-full",children:[(0,t.jsxs)(e8.Radio,{value:"complexity",className:"w-full",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(tx.ThunderboltOutlined,{className:"text-yellow-500"}),(0,t.jsx)("span",{className:"font-medium",children:"Complexity Router"}),(0,t.jsx)(J.Badge,{count:"Recommended",style:{backgroundColor:"#52c41a",fontSize:"10px",padding:"0 6px"}})]}),(0,t.jsxs)("div",{className:"text-xs text-gray-500 ml-6 mt-1",children:["Automatically routes based on request complexity. No training data needed — just pick 4 models and go.",(0,t.jsx)("br",{}),(0,t.jsx)("span",{className:"text-green-600",children:"✓ Zero API calls"})," · ",(0,t.jsx)("span",{className:"text-green-600",children:"✓ <1ms latency"})," · ",(0,t.jsx)("span",{className:"text-green-600",children:"✓ No cost"})]})]}),(0,t.jsxs)(e8.Radio,{value:"semantic",className:"w-full mt-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(tg,{className:"text-blue-500"}),(0,t.jsx)("span",{className:"font-medium",children:"Semantic Router"})]}),(0,t.jsx)("div",{className:"text-xs text-gray-500 ml-6 mt-1",children:"Routes based on semantic similarity to example utterances. Requires embedding model and training examples."})]})]})})]})}),(0,t.jsx)(ej.Card,{children:(0,t.jsxs)(et.Form,{form:e,onFinish:F,labelCol:{span:10},wrapperCol:{span:16},labelAlign:"left",children:[(0,t.jsx)(et.Form.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,t.jsx)(eR.TextInput,{placeholder:"e.g., smart_router, auto_router_1"})}),"complexity"===b?(0,t.jsx)("div",{className:"w-full mb-4",children:(0,t.jsx)(th,{modelInfo:p,value:C,onChange:e=>{S(e)}})}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:"w-full mb-4",children:(0,t.jsx)(tc,{modelInfo:p,value:N,onChange:t=>{w(t),e.setFieldValue("auto_router_config",t)}})}),(0,t.jsx)(et.Form.Item,{rules:[{required:"semantic"===b,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,t.jsx)(W.Select,{placeholder:"Select a default model",onChange:e=>{j("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,t.jsx)(et.Form.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,t.jsx)(W.Select,{value:e.getFieldValue("auto_router_embedding_model"),placeholder:"Select an embedding model (optional)",onChange:t=>{y("custom"===t),e.setFieldValue("auto_router_embedding_model",t)},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,t.jsxs)("div",{className:"flex items-center my-4",children:[(0,t.jsx)("div",{className:"flex-grow border-t border-gray-200"}),(0,t.jsx)("span",{className:"px-4 text-gray-500 text-sm",children:"Additional Settings"}),(0,t.jsx)("div",{className:"flex-grow border-t border-gray-200"})]}),k&&(0,t.jsx)(et.Form.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,t.jsx)(W.Select,{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,t.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,t.jsx)(E.Tooltip,{title:"Get help on our github",children:(0,t.jsx)(L.Typography.Link,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,t.jsxs)("div",{className:"space-x-2",children:[(0,t.jsx)(K.Button,{onClick:T,loading:n,children:"Test Connection"}),(0,t.jsx)(K.Button,{type:"primary",onClick:()=>{console.log("Add Auto Router button clicked!"),F()},children:"Add Auto Router"})]})]})]})}),(0,t.jsx)(el.Modal,{title:"Connection Test Results",open:i,onCancel:()=>{o(!1),d(!1)},footer:[(0,t.jsx)(K.Button,{onClick:()=>{o(!1),d(!1)},children:"Close"},"close")],width:700,children:i&&(0,t.jsx)(tt,{formValues:e.getFieldsValue(),accessToken:a,testMode:"chat",modelName:e.getFieldValue("auto_router_name"),onClose:()=>{o(!1),d(!1)},onTestComplete:()=>d(!1)},c)})]})},ty=(0,a.createQueryKeys)("guardrails"),tb=(0,a.createQueryKeys)("tags");var tv=e.i(793130),tN=e.i(560445),tw=e.i(663435),tC=e.i(677667),tS=e.i(898667),tk=e.i(130643),tT=e.i(635432),tF=e.i(564897),tI=e.i(435451);let{Text:tM}=L.Typography,tP=({form:e,showCacheControl:l,onCacheControlChange:s})=>{let a=t=>{let l=e.getFieldValue("litellm_extra_params");try{let s=l?JSON.parse(l):{};t.length>0?s.cache_control_injection_points=t:delete s.cache_control_injection_points,Object.keys(s).length>0?e.setFieldValue("litellm_extra_params",JSON.stringify(s,null,2)):e.setFieldValue("litellm_extra_params","")}catch(e){console.error("Error updating cache control points:",e)}};return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(et.Form.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,t.jsx)(es.Switch,{onChange:s,className:"bg-gray-600"})}),l&&(0,t.jsxs)("div",{className:"ml-6 pl-4 border-l-2 border-gray-200",children:[(0,t.jsx)(tM,{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,t.jsx)(et.Form.List,{name:"cache_control_injection_points",initialValue:[{location:"message"}],children:(l,{add:s,remove:r})=>(0,t.jsxs)(t.Fragment,{children:[l.map((s,i)=>(0,t.jsxs)("div",{className:"flex items-center mb-4 gap-4",children:[(0,t.jsx)(et.Form.Item,{...s,label:"Type",name:[s.name,"location"],initialValue:"message",className:"mb-0",style:{width:"180px"},children:(0,t.jsx)(W.Select,{disabled:!0,options:[{value:"message",label:"Message"}]})}),(0,t.jsx)(et.Form.Item,{...s,label:"Role",name:[s.name,"role"],className:"mb-0",style:{width:"180px"},tooltip:"LiteLLM will mark all messages of this role as cacheable",children:(0,t.jsx)(W.Select,{placeholder:"Select a role",allowClear:!0,options:[{value:"user",label:"User"},{value:"system",label:"System"},{value:"assistant",label:"Assistant"}],onChange:()=>{a(e.getFieldValue("cache_control_points"))}})}),(0,t.jsx)(et.Form.Item,{...s,label:"Index",name:[s.name,"index"],className:"mb-0",style:{width:"180px"},tooltip:"(Optional) If set litellm will mark the message at this index as cacheable",children:(0,t.jsx)(tI.default,{type:"number",placeholder:"Optional",step:1,onChange:()=>{a(e.getFieldValue("cache_control_points"))}})}),l.length>1&&(0,t.jsx)(tF.MinusCircleOutlined,{className:"text-red-500 cursor-pointer text-lg ml-12",onClick:()=>{r(s.name),setTimeout(()=>{a(e.getFieldValue("cache_control_points"))},0)}})]},s.key)),(0,t.jsx)(et.Form.Item,{children:(0,t.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:()=>s(),children:[(0,t.jsx)(tr.PlusOutlined,{className:"mr-2"}),"Add Injection Point"]})})]})})]})]})};var tA=e.i(916940),tE=e.i(122550);let{Link:tL}=L.Typography,tR=({showAdvancedSettings:e,setShowAdvancedSettings:l,teams:s,guardrailsList:a,tagsList:r,accessToken:i})=>{let[o]=et.Form.useForm(),[n,d]=x.default.useState(!1),[c,m]=x.default.useState("per_token"),[u,h]=x.default.useState(!1),p=(e,t)=>t&&(isNaN(Number(t))||0>Number(t))?Promise.reject("Please enter a valid positive number"):Promise.resolve();return(0,t.jsx)(t.Fragment,{children:(0,t.jsxs)(tC.Accordion,{className:"mt-2 mb-4",children:[(0,t.jsx)(tS.AccordionHeader,{children:(0,t.jsx)("b",{children:"Advanced Settings"})}),(0,t.jsx)(tk.AccordionBody,{children:(0,t.jsxs)("div",{className:"bg-white rounded-lg",children:[(0,t.jsx)(et.Form.Item,{label:"Custom Pricing",name:"custom_pricing",valuePropName:"checked",className:"mb-4",children:(0,t.jsx)(es.Switch,{onChange:e=>{d(e),e||o.setFieldsValue({input_cost_per_token:void 0,output_cost_per_token:void 0,input_cost_per_second:void 0})},className:"bg-gray-600"})}),(0,t.jsx)(et.Form.Item,{label:(0,t.jsxs)("span",{children:["Attached Knowledge Bases (RAG)"," ",(0,t.jsx)(E.Tooltip,{title:"Vector stores to use for RAG. Every request to this model will automatically retrieve context from these knowledge bases.",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/completion/knowledgebase",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(w.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"vector_store_ids",className:"mt-4",help:"Select vector stores to attach. Requests to this model will automatically use these for RAG. Set up vector stores in Tools > Vector Stores.",children:(0,t.jsx)(tA.default,{onChange:()=>{},accessToken:i,placeholder:"Select knowledge bases (optional)"})}),(0,t.jsx)(et.Form.Item,{label:(0,t.jsxs)("span",{children:["Guardrails"," ",(0,t.jsx)(E.Tooltip,{title:"Apply safety guardrails to this key to filter content or enforce policies",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(w.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",className:"mt-4",help:"Select existing guardrails. Go to 'Guardrails' tab to create new guardrails.",children:(0,t.jsx)(W.Select,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter guardrails",options:a.map(e=>({value:e,label:e}))})}),(0,t.jsx)(et.Form.Item,{label:"Tags",name:"tags",className:"mb-4",children:(0,t.jsx)(W.Select,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter tags",options:Object.values(r).map(e=>({value:e.name,label:e.name,title:e.description||e.name}))})}),n&&(0,t.jsxs)("div",{className:"ml-6 pl-4 border-l-2 border-gray-200",children:[(0,t.jsx)(et.Form.Item,{label:"Pricing Model",name:"pricing_model",className:"mb-4",children:(0,t.jsx)(W.Select,{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,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(et.Form.Item,{label:"Input Cost (per 1M tokens)",name:"input_cost_per_token",rules:[{validator:p}],className:"mb-4",children:(0,t.jsx)(eR.TextInput,{})}),(0,t.jsx)(et.Form.Item,{label:"Output Cost (per 1M tokens)",name:"output_cost_per_token",rules:[{validator:p}],className:"mb-4",children:(0,t.jsx)(eR.TextInput,{})})]}):(0,t.jsx)(et.Form.Item,{label:"Cost Per Second",name:"input_cost_per_second",rules:[{validator:p}],className:"mb-4",children:(0,t.jsx)(eR.TextInput,{})})]}),(0,t.jsx)(et.Form.Item,{label:"Use in pass through routes",name:"use_in_pass_through",valuePropName:"checked",className:"mb-4 mt-4",tooltip:(0,t.jsxs)("span",{children:["Allow using these credentials in pass through routes."," ",(0,t.jsx)(tL,{href:"https://docs.litellm.ai/docs/pass_through/vertex_ai",target:"_blank",children:"Learn more"})]}),children:(0,t.jsx)(es.Switch,{onChange:e=>{let t=o.getFieldValue("litellm_extra_params");try{let l=t?JSON.parse(t):{};e?l.use_in_pass_through=!0:delete l.use_in_pass_through,Object.keys(l).length>0?o.setFieldValue("litellm_extra_params",JSON.stringify(l,null,2)):o.setFieldValue("litellm_extra_params","")}catch(t){e?o.setFieldValue("litellm_extra_params",JSON.stringify({use_in_pass_through:!0},null,2)):o.setFieldValue("litellm_extra_params","")}},className:"bg-gray-600"})}),(0,t.jsx)(tP,{form:o,showCacheControl:u,onCacheControlChange:e=>{if(h(e),!e){let e=o.getFieldValue("litellm_extra_params");try{let t=e?JSON.parse(e):{};delete t.cache_control_injection_points,Object.keys(t).length>0?o.setFieldValue("litellm_extra_params",JSON.stringify(t,null,2)):o.setFieldValue("litellm_extra_params","")}catch(e){o.setFieldValue("litellm_extra_params","")}}}}),(0,t.jsx)(et.Form.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:tE.formItemValidateJSON}],children:(0,t.jsx)(tT.default,{rows:4,placeholder:'{ "rpm": 100, "timeout": 0, "stream_timeout": 0 }'})}),(0,t.jsxs)(eD.Row,{className:"mb-4",children:[(0,t.jsx)(eq.Col,{span:10}),(0,t.jsx)(eq.Col,{span:10,children:(0,t.jsxs)(em.Text,{className:"text-gray-600 text-sm",children:["Pass JSON of litellm supported params"," ",(0,t.jsx)(tL,{href:"https://docs.litellm.ai/docs/completion/input",target:"_blank",children:"litellm.completion() call"})]})})]}),(0,t.jsx)(et.Form.Item,{label:"Model Info",name:"model_info_params",tooltip:"Optional model info params. Returned when calling `/model/info` endpoint.",className:"mb-0",rules:[{validator:tE.formItemValidateJSON}],children:(0,t.jsx)(tT.default,{rows:4,placeholder:'{ "mode": "chat" }'})})]})})]})})};var tO=e.i(291542),tB=e.i(750113);let tz=({content:e,children:l,width:s="auto",className:a=""})=>{let[r,i]=(0,x.useState)(!1),[o,n]=(0,x.useState)("top"),d=(0,x.useRef)(null);return(0,t.jsxs)("div",{className:"relative inline-block",ref:d,children:[l||(0,t.jsx)(tB.QuestionCircleOutlined,{className:"ml-1 text-gray-500 cursor-help",onMouseEnter:()=>{if(d.current){let e=d.current.getBoundingClientRect(),t=e.top,l=window.innerHeight-e.bottom;t<300&&l>300?n("bottom"):n("top")}i(!0)},onMouseLeave:()=>i(!1)}),r&&(0,t.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 ${a}`,style:{["top"===o?"bottom":"top"]:"100%",width:s,marginBottom:"top"===o?"8px":"0",marginTop:"bottom"===o?"8px":"0"},children:[e,(0,t.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"}})]})]})},tq=()=>{let e=et.Form.useFormInstance(),[l,s]=(0,x.useState)(0),a=et.Form.useWatch("model",e)||[],r=Array.isArray(a)?a:[a],i=et.Form.useWatch("custom_model_name",e),o=!r.includes("all-wildcard"),n=et.Form.useWatch("custom_llm_provider",e);if((0,x.useEffect)(()=>{if(i&&r.includes("custom")){let t=(e.getFieldValue("model_mappings")||[]).map(e=>"custom"===e.public_name||"custom"===e.litellm_model?n===eM.Providers.Azure?{public_name:i,litellm_model:`azure/${i}`}:{public_name:i,litellm_model:i}:e);e.setFieldValue("model_mappings",t),s(e=>e+1)}},[i,r,n,e]),(0,x.useEffect)(()=>{if(r.length>0&&!r.includes("all-wildcard")){let t=e.getFieldValue("model_mappings")||[];if(t.length!==r.length||!r.every(e=>t.some(t=>"custom"===e?"custom"===t.litellm_model||t.litellm_model===i:n===eM.Providers.Azure?t.litellm_model===`azure/${e}`:t.litellm_model===e))){let t=r.map(e=>"custom"===e&&i?n===eM.Providers.Azure?{public_name:i,litellm_model:`azure/${i}`}:{public_name:i,litellm_model:i}:n===eM.Providers.Azure?{public_name:e,litellm_model:`azure/${e}`}:{public_name:e,litellm_model:e});e.setFieldValue("model_mappings",t),s(e=>e+1)}}},[r,i,n,e]),!o)return null;let d=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:"mb-2 font-normal",children:"The name you specify in your API calls to LiteLLM Proxy"}),(0,t.jsxs)("div",{className:"mb-2 font-normal",children:[(0,t.jsx)("strong",{children:"Example:"})," If you name your public model"," ",(0,t.jsx)("code",{className:"bg-gray-700 px-1 py-0.5 rounded text-xs",children:"example-name"}),", and choose"," ",(0,t.jsx)("code",{className:"bg-gray-700 px-1 py-0.5 rounded text-xs",children:"openai/qwen-plus-latest"})," as the LiteLLM model"]}),(0,t.jsxs)("div",{className:"mb-2 font-normal",children:[(0,t.jsx)("strong",{children:"Usage:"})," You make an API call to the LiteLLM proxy with"," ",(0,t.jsx)("code",{className:"bg-gray-700 px-1 py-0.5 rounded text-xs",children:'model = "example-name"'})]}),(0,t.jsxs)("div",{className:"font-normal",children:[(0,t.jsx)("strong",{children:"Result:"})," LiteLLM sends"," ",(0,t.jsx)("code",{className:"bg-gray-700 px-1 py-0.5 rounded text-xs",children:"qwen-plus-latest"})," to the provider"]})]}),c=(0,t.jsx)("div",{children:"The model name LiteLLM will send to the LLM API"}),m=[{title:(0,t.jsxs)("span",{className:"flex items-center",children:["Public Model Name",(0,t.jsx)(tz,{content:d,width:"500px"})]}),dataIndex:"public_name",key:"public_name",render:(l,s,a)=>(0,t.jsx)(eR.TextInput,{value:l,onChange:t=>{let l=t.target.value,s=[...e.getFieldValue("model_mappings")],r=n===eM.Providers.Anthropic,i=l.endsWith("-1m"),o=e.getFieldValue("litellm_extra_params"),d=!o||""===o.trim(),c=l;if(r&&i&&d){let t=JSON.stringify({extra_headers:{"anthropic-beta":"context-1m-2025-08-07"}},null,2);e.setFieldValue("litellm_extra_params",t),c=l.slice(0,-3)}s[a].public_name=c,e.setFieldValue("model_mappings",s)}})},{title:(0,t.jsxs)("span",{className:"flex items-center",children:["LiteLLM Model Name",(0,t.jsx)(tz,{content:c,width:"360px"})]}),dataIndex:"litellm_model",key:"litellm_model"}];return(0,t.jsx)(t.Fragment,{children:(0,t.jsx)(et.Form.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,t)=>{if(!t||0===t.length)throw Error("At least one model mapping is required");if(t.filter(e=>!e.public_name||""===e.public_name.trim()).length>0)throw Error("All model mappings must have valid public names")}}],children:(0,t.jsx)(tO.Table,{dataSource:e.getFieldValue("model_mappings"),columns:m,pagination:!1,size:"small"},l)})})},tV=({selectedProvider:e,providerModels:l,getPlaceholder:s})=>{let a=et.Form.useFormInstance(),r=t=>{let l=t.target.value,s=(a.getFieldValue("model_mappings")||[]).map(t=>"custom"===t.public_name||"custom"===t.litellm_model?e===eM.Providers.Azure?{public_name:l,litellm_model:`azure/${l}`}:{public_name:l,litellm_model:l}:t);a.setFieldsValue({model_mappings:s})};return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(et.Form.Item,{label:"LiteLLM Model Name(s)",tooltip:"The model name LiteLLM will send to the LLM API",className:"mb-0",children:[(0,t.jsx)(et.Form.Item,{name:"model",rules:[{required:!0,message:`Please enter ${e===eM.Providers.Azure?"a deployment name":"at least one model"}.`}],noStyle:!0,children:e===eM.Providers.Azure||e===eM.Providers.OpenAI_Compatible||e===eM.Providers.Ollama?(0,t.jsx)(t.Fragment,{children:(0,t.jsx)(eR.TextInput,{placeholder:s(e),onChange:e===eM.Providers.Azure?e=>{let t=e.target.value,l=t?[{public_name:t,litellm_model:`azure/${t}`}]:[];a.setFieldsValue({model:t,model_mappings:l})}:void 0})}):l.length>0?(0,t.jsx)(W.Select,{mode:"multiple",allowClear:!0,showSearch:!0,placeholder:"Select models",onChange:t=>{let l=Array.isArray(t)?t:[t];if(l.includes("all-wildcard"))a.setFieldsValue({model_name:void 0,model_mappings:[]});else if(JSON.stringify(a.getFieldValue("model"))!==JSON.stringify(l)){let t=l.map(t=>e===eM.Providers.Azure?{public_name:t,litellm_model:`azure/${t}`}:{public_name:t,litellm_model:t});a.setFieldsValue({model:l,model_mappings:t})}},optionFilterProp:"children",filterOption:(e,t)=>(t?.label??"").toLowerCase().includes(e.toLowerCase()),options:[{label:"Custom Model Name (Enter below)",value:"custom"},{label:`All ${e} Models (Wildcard)`,value:"all-wildcard"},...l.map(e=>({label:e,value:e}))],style:{width:"100%"}}):(0,t.jsx)(eR.TextInput,{placeholder:s(e)})}),(0,t.jsx)(et.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.model!==t.model,children:({getFieldValue:l})=>{let s=l("model")||[];return(Array.isArray(s)?s:[s]).includes("custom")&&(0,t.jsx)(et.Form.Item,{name:"custom_model_name",rules:[{required:!0,message:"Please enter a custom model name."}],className:"mt-2",children:(0,t.jsx)(eR.TextInput,{placeholder:e===eM.Providers.Azure?"Enter Azure deployment name":"Enter custom model name",onChange:r})})}})]}),(0,t.jsxs)(eD.Row,{children:[(0,t.jsx)(eq.Col,{span:10}),(0,t.jsx)(eq.Col,{span:14,children:(0,t.jsx)(em.Text,{className:"mb-3 mt-1",children:e===eM.Providers.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"})})]})]})},tD=[{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:tH,Link:tG}=L.Typography,t$=({form:e,handleOk:a,selectedProvider:i,setSelectedProvider:o,providerModels:n,setProviderModelsFn:d,getPlaceholder:c,uploadProps:m,showAdvancedSettings:u,setShowAdvancedSettings:h,teams:p,credentials:g})=>{let[f,j]=(0,x.useState)("chat"),[_,y]=(0,x.useState)(!1),[b,v]=(0,x.useState)(!1),[N,w]=(0,x.useState)(""),{accessToken:C,userRole:S,premiumUser:k,userId:T}=(0,r.default)(),{data:F,isLoading:I,error:M}=eB(),{data:P,isLoading:A,error:O}=(()=>{let{accessToken:e,userId:t,userRole:a}=(0,r.default)();return(0,s.useQuery)({queryKey:ty.list({}),queryFn:async()=>(await (0,l.getGuardrailsList)(e)).guardrails.map(e=>e.guardrail_name),enabled:!!(e&&t&&a)})})(),{data:B,isLoading:z,error:q}=(()=>{let{accessToken:e,userId:t,userRole:a}=(0,r.default)();return(0,s.useQuery)({queryKey:tb.list({}),queryFn:async()=>await (0,l.tagListCall)(e),enabled:!!(e&&t&&a)})})(),V=async()=>{v(!0),w(`test-${Date.now()}`),y(!0)},[D,H]=(0,x.useState)(!1),[G,$]=(0,x.useState)([]),[U,J]=(0,x.useState)(null);(0,x.useEffect)(()=>{(async()=>{$((await (0,l.modelAvailableCall)(C,"","",!1,null,!0,!0)).data.map(e=>e.id))})()},[C]);let Q=(0,x.useMemo)(()=>F?[...F].sort((e,t)=>e.provider_display_name.localeCompare(t.provider_display_name)):[],[F]),Y=M?M instanceof Error?M.message:"Failed to load providers":null,X=eZ.all_admin_roles.includes(S),Z=(0,eZ.isUserTeamAdminForAnyTeam)(p,T);return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(tH,{level:2,children:"Add Model"}),(0,t.jsx)(ej.Card,{children:(0,t.jsx)(et.Form,{form:e,onFinish:async e=>{console.log("🔥 Form onFinish triggered with values:",e),await a().then(()=>{J(null)})},onFinishFailed:e=>{console.log("💥 Form onFinishFailed triggered:",e)},labelCol:{span:10},wrapperCol:{span:16},labelAlign:"left",children:(0,t.jsxs)(t.Fragment,{children:[Z&&!X&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(et.Form.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,t.jsx)(tw.default,{teams:p,onChange:e=>{J(e)}})}),!U&&(0,t.jsx)(tN.Alert,{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||Z&&U)&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(et.Form.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,t.jsxs)(W.Select,{virtual:!1,showSearch:!0,loading:I,placeholder:I?"Loading providers...":"Select a provider",optionFilterProp:"data-label",onChange:t=>{o(t),d(t),e.setFieldsValue({custom_llm_provider:t}),e.setFieldsValue({model:[],model_name:void 0})},children:[Y&&0===Q.length&&(0,t.jsx)(W.Select.Option,{value:"",children:Y},"__error"),Q.map(e=>{let l=e.provider_display_name,s=e.provider;return eM.providerLogoMap[l],(0,t.jsx)(W.Select.Option,{value:s,"data-label":l,children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)(R.ProviderLogo,{provider:s,className:"w-5 h-5"}),(0,t.jsx)("span",{children:l})]})},s)})]})}),(0,t.jsx)(tV,{selectedProvider:i,providerModels:n,getPlaceholder:c}),(0,t.jsx)(tq,{}),(0,t.jsx)(et.Form.Item,{label:"Mode",name:"mode",className:"mb-1",children:(0,t.jsx)(W.Select,{style:{width:"100%"},value:f,onChange:e=>j(e),options:tD})}),(0,t.jsxs)(eD.Row,{children:[(0,t.jsx)(eq.Col,{span:10}),(0,t.jsx)(eq.Col,{span:10,children:(0,t.jsxs)(em.Text,{className:"mb-5 mt-1",children:[(0,t.jsx)("strong",{children:"Optional"})," - LiteLLM endpoint to use when health checking this model"," ",(0,t.jsx)(tG,{href:"https://docs.litellm.ai/docs/proxy/health#health",target:"_blank",children:"Learn more"})]})})]}),(0,t.jsx)("div",{className:"mb-4",children:(0,t.jsx)(L.Typography.Text,{className:"text-sm text-gray-500 mb-2",children:"Either select existing credentials OR enter new provider credentials below"})}),(0,t.jsx)(et.Form.Item,{label:"Existing Credentials",name:"litellm_credential_name",initialValue:null,children:(0,t.jsx)(W.Select,{showSearch:!0,placeholder:"Select or search for existing credentials",optionFilterProp:"children",filterOption:(e,t)=>(t?.label??"").toLowerCase().includes(e.toLowerCase()),options:[{value:null,label:"None"},...g.map(e=>({value:e.credential_name,label:e.credential_name}))],allowClear:!0})}),(0,t.jsx)(et.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.litellm_credential_name!==t.litellm_credential_name||e.provider!==t.provider,children:({getFieldValue:e})=>{let l=e("litellm_credential_name");return(console.log("🔑 Credential Name Changed:",l),l)?null:(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"flex items-center my-4",children:[(0,t.jsx)("div",{className:"flex-grow border-t border-gray-200"}),(0,t.jsx)("span",{className:"px-4 text-gray-500 text-sm",children:"OR"}),(0,t.jsx)("div",{className:"flex-grow border-t border-gray-200"})]}),(0,t.jsx)(eJ,{selectedProvider:i,uploadProps:m})]})}}),(0,t.jsxs)("div",{className:"flex items-center my-4",children:[(0,t.jsx)("div",{className:"flex-grow border-t border-gray-200"}),(0,t.jsx)("span",{className:"px-4 text-gray-500 text-sm",children:"Additional Model Info Settings"}),(0,t.jsx)("div",{className:"flex-grow border-t border-gray-200"})]}),(X||!Z)&&(0,t.jsx)(et.Form.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,t.jsx)(E.Tooltip,{title:k?"":"This is an enterprise-only feature. Upgrade to premium to restrict model+credential combinations to a specific team.",placement:"top",children:(0,t.jsx)(tv.Switch,{checked:D,onChange:t=>{H(t),t||e.setFieldValue("team_id",void 0)},disabled:!k})})}),D&&(X||!Z)&&(0,t.jsx)(et.Form.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:D&&!X,message:"Please select a team."}],children:(0,t.jsx)(tw.default,{teams:p,disabled:!k})}),X&&(0,t.jsx)(t.Fragment,{children:(0,t.jsx)(et.Form.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,t.jsx)(W.Select,{mode:"tags",showSearch:!0,placeholder:"Select existing groups or type to create new ones",optionFilterProp:"children",tokenSeparators:[","],options:G.map(e=>({value:e,label:e})),maxTagCount:"responsive",allowClear:!0})})}),(0,t.jsx)(tR,{showAdvancedSettings:u,setShowAdvancedSettings:h,teams:p,guardrailsList:P||[],tagsList:B||{},accessToken:C||""})]}),(0,t.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,t.jsx)(E.Tooltip,{title:"Get help on our github",children:(0,t.jsx)(L.Typography.Link,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,t.jsxs)("div",{className:"space-x-2",children:[(0,t.jsx)(K.Button,{onClick:V,loading:b,children:"Test Connect"}),(0,t.jsx)(K.Button,{htmlType:"submit",children:"Add Model"})]})]})]})})}),(0,t.jsx)(el.Modal,{title:"Connection Test Results",open:_,onCancel:()=>{y(!1),v(!1)},footer:[(0,t.jsx)(K.Button,{onClick:()=>{y(!1),v(!1)},children:"Close"},"close")],width:700,children:_&&(0,t.jsx)(tt,{formValues:e.getFieldsValue(),accessToken:C,testMode:f,modelName:e.getFieldValue("model_name")||e.getFieldValue("model"),onClose:()=>{y(!1),v(!1)},onTestComplete:()=>v(!1)},N)})]})},tU=({form:e,handleOk:l,selectedProvider:s,setSelectedProvider:a,providerModels:r,setProviderModelsFn:i,getPlaceholder:o,uploadProps:n,showAdvancedSettings:d,setShowAdvancedSettings:c,teams:m,credentials:u,accessToken:h,userRole:x})=>{let[p]=et.Form.useForm();return(0,t.jsx)(t.Fragment,{children:(0,t.jsxs)(e4.TabGroup,{className:"w-full",children:[(0,t.jsxs)(e5.TabList,{className:"mb-4",children:[(0,t.jsx)(e2.Tab,{children:"Add Model"}),(0,t.jsx)(e2.Tab,{children:"Add Auto Router"})]}),(0,t.jsxs)(e6.TabPanels,{children:[(0,t.jsx)(U.TabPanel,{children:(0,t.jsx)(t$,{form:e,handleOk:l,selectedProvider:s,setSelectedProvider:a,providerModels:r,setProviderModelsFn:i,getPlaceholder:o,uploadProps:n,showAdvancedSettings:d,setShowAdvancedSettings:c,teams:m,credentials:u})}),(0,t.jsx)(U.TabPanel,{children:(0,t.jsx)(t_,{form:p,handleOk:()=>{p.validateFields().then(e=>{tl(e,h,p,l)}).catch(e=>{console.error("Validation failed:",e)})},accessToken:h,userRole:x})})]})]})})};var tJ=e.i(798496),tK=e.i(536916),tW=e.i(502275),tQ=e.i(122577);let tY=[{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"}],tX=({accessToken:e,modelData:s,all_models_on_proxy:a,getDisplayModelName:r,setSelectedModelId:i,teams:o})=>{let n,d,c,m,[u,h]=(0,x.useState)({}),[p,g]=(0,x.useState)([]),[f,j]=(0,x.useState)(!1),[_,y]=(0,x.useState)(!1),[b,v]=(0,x.useState)(null),[N,w]=(0,x.useState)(!1),[C,S]=(0,x.useState)(null);(0,x.useRef)(null),(0,x.useEffect)(()=>{e&&s?.data&&(async()=>{let t={};s.data.forEach(e=>{let l=e.model_info?.id;l&&(t[l]={status:"none",lastCheck:"None",lastSuccess:"None",loading:!1,error:void 0,fullError:void 0,successResponse:void 0})});try{let a=await (0,l.latestHealthChecksCall)(e);a&&a.latest_health_checks&&"object"==typeof a.latest_health_checks&&Object.entries(a.latest_health_checks).forEach(([e,l])=>{if(!l||!s.data.some(t=>t.model_info?.id===e))return;let a=l.error_message||void 0;t[e]={status:l.status||"unknown",lastCheck:l.checked_at?new Date(l.checked_at).toLocaleString():"None",lastSuccess:"healthy"===l.status&&l.checked_at?new Date(l.checked_at).toLocaleString():"None",loading:!1,error:a?F(a):void 0,fullError:a,successResponse:"healthy"===l.status?l:void 0}})}catch(e){console.warn("Failed to load health check history (using default states):",e)}h(t)})()},[e,s]);let F=e=>{if(!e)return"Health check failed";let t="string"==typeof e?e:JSON.stringify(e),l=t.match(/(\w+Error):\s*(\d{3})/i);if(l)return`${l[1]}: ${l[2]}`;let s=t.match(/(AuthenticationError|RateLimitError|BadRequestError|InternalServerError|TimeoutError|NotFoundError|ForbiddenError|ServiceUnavailableError|BadGatewayError|ContentPolicyViolationError|\w+Error)/i),a=t.match(/\b(400|401|403|404|408|429|500|502|503|504)\b/);if(s&&a)return`${s[1]}: ${a[1]}`;if(a){let e=a[1];return`${({400:"BadRequestError",401:"AuthenticationError",403:"ForbiddenError",404:"NotFoundError",408:"TimeoutError",429:"RateLimitError",500:"InternalServerError",502:"BadGatewayError",503:"ServiceUnavailableError",504:"GatewayTimeoutError"})[e]}: ${e}`}if(s){let e=s[1],t={AuthenticationError:"401",RateLimitError:"429",BadRequestError:"400",InternalServerError:"500",TimeoutError:"408",NotFoundError:"404",ForbiddenError:"403",ServiceUnavailableError:"503",BadGatewayError:"502",GatewayTimeoutError:"504",ContentPolicyViolationError:"400"}[e];return t?`${e}: ${t}`:e}for(let{pattern:e,replacement:l}of tY)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 r=t.replace(/[\n\r]+/g," ").replace(/\s+/g," ").trim(),i=r.split(/[.!?]/),o=i[0]?.trim();return o&&o.length>0?o.length>100?o.substring(0,97)+"...":o:r.length>100?r.substring(0,97)+"...":r},I=async t=>{if(e){h(e=>({...e,[t]:{...e[t],loading:!0,status:"checking"}}));try{let s=await (0,l.individualModelHealthCheckCall)(e,t),a=new Date().toLocaleString();if(s.unhealthy_count>0&&s.unhealthy_endpoints&&s.unhealthy_endpoints.length>0){let e=s.unhealthy_endpoints[0]?.error||"Health check failed",l=F(e);h(s=>({...s,[t]:{status:"unhealthy",lastCheck:a,lastSuccess:s[t]?.lastSuccess||"None",loading:!1,error:l,fullError:e}}))}else h(e=>({...e,[t]:{status:"healthy",lastCheck:a,lastSuccess:a,loading:!1,successResponse:s}}));try{let s=await (0,l.latestHealthChecksCall)(e),a=s.latest_health_checks?.[t];if(a){let e=a.error_message||void 0;h(l=>({...l,[t]:{status:a.status||l[t]?.status||"unknown",lastCheck:a.checked_at?new Date(a.checked_at).toLocaleString():l[t]?.lastCheck||"None",lastSuccess:"healthy"===a.status&&a.checked_at?new Date(a.checked_at).toLocaleString():l[t]?.lastSuccess||"None",loading:!1,error:e?F(e):l[t]?.error,fullError:e||l[t]?.fullError,successResponse:"healthy"===a.status?a:l[t]?.successResponse}}))}}catch(e){console.debug("Could not fetch updated status from database (non-critical):",e)}}catch(a){let e=new Date().toLocaleString(),l=a instanceof Error?a.message:String(a),s=F(l);h(a=>({...a,[t]:{status:"unhealthy",lastCheck:e,lastSuccess:a[t]?.lastSuccess||"None",loading:!1,error:s,fullError:l}}))}}},M=async()=>{let t=p.length>0?p:a,s=t.reduce((e,t)=>(e[t]={...u[t],loading:!0,status:"checking"},e),{});h(e=>({...e,...s}));let r={},i=t.map(async t=>{if(e)try{let s=await (0,l.individualModelHealthCheckCall)(e,t);r[t]=s;let a=new Date().toLocaleString();if(s.unhealthy_count>0&&s.unhealthy_endpoints&&s.unhealthy_endpoints.length>0){let e=s.unhealthy_endpoints[0]?.error||"Health check failed",l=F(e);h(s=>({...s,[t]:{status:"unhealthy",lastCheck:a,lastSuccess:s[t]?.lastSuccess||"None",loading:!1,error:l,fullError:e}}))}else h(e=>({...e,[t]:{status:"healthy",lastCheck:a,lastSuccess:a,loading:!1,successResponse:s}}))}catch(a){console.error(`Health check failed for model id ${t}:`,a);let e=new Date().toLocaleString(),l=a instanceof Error?a.message:String(a),s=F(l);h(a=>({...a,[t]:{status:"unhealthy",lastCheck:e,lastSuccess:a[t]?.lastSuccess||"None",loading:!1,error:s,fullError:l}}))}});await Promise.allSettled(i);try{if(!e)return;let s=await (0,l.latestHealthChecksCall)(e);s.latest_health_checks&&Object.entries(s.latest_health_checks).forEach(([e,l])=>{if(t.includes(e)&&l){let t=l.error_message||void 0;h(s=>{let a=s[e];return{...s,[e]:{status:l.status||a?.status||"unknown",lastCheck:l.checked_at?new Date(l.checked_at).toLocaleString():a?.lastCheck||"None",lastSuccess:"healthy"===l.status&&l.checked_at?new Date(l.checked_at).toLocaleString():a?.lastSuccess||"None",loading:!1,error:t?F(t):a?.error,fullError:t||a?.fullError,successResponse:"healthy"===l.status?l:a?.successResponse}}})}})}catch(e){console.warn("Failed to fetch updated health statuses from database (non-critical):",e)}},P=e=>{j(e),e?g(a):g([])},A=()=>{y(!1),v(null)},L=()=>{w(!1),S(null)};return(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"mb-6",children:(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(eu.Title,{children:"Model Health Status"}),(0,t.jsx)(em.Text,{className:"text-gray-600 mt-1",children:"Run health checks on individual models to verify they are working correctly"})]}),(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[p.length>0&&(0,t.jsx)(T.Button,{size:"sm",variant:"light",onClick:()=>P(!1),className:"px-3 py-1 text-sm",children:"Clear Selection"}),(0,t.jsx)(T.Button,{size:"sm",variant:"secondary",onClick:M,disabled:Object.values(u).some(e=>e.loading),className:"px-3 py-1 text-sm",children:p.length>0&&p.length{t?g(t=>[...t,e]):(g(t=>t.filter(t=>t!==e)),j(!1))},d=e=>{switch(e){case"healthy":return(0,t.jsx)(k.Badge,{color:"emerald",children:"healthy"});case"unhealthy":return(0,t.jsx)(k.Badge,{color:"red",children:"unhealthy"});case"checking":return(0,t.jsx)(k.Badge,{color:"blue",children:"checking"});case"none":return(0,t.jsx)(k.Badge,{color:"gray",children:"none"});default:return(0,t.jsx)(k.Badge,{color:"gray",children:"unknown"})}},c=(e,t,l)=>{v({modelName:e,cleanedError:t,fullError:l}),y(!0)},m=(e,t)=>{S({modelName:e,response:t}),w(!0)},[{header:()=>(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(tK.Checkbox,{checked:f,indeterminate:p.length>0&&!f,onChange:e=>P(e.target.checked),onClick:e=>e.stopPropagation()}),(0,t.jsx)("span",{children:"Model ID"})]}),accessorKey:"model_info.id",enableSorting:!0,sortingFn:"alphanumeric",cell:({row:e})=>{let l=e.original,s=l.model_info?.id??"",a=p.includes(s);return(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(tK.Checkbox,{checked:a,onChange:e=>n(s,e.target.checked),onClick:e=>e.stopPropagation()}),(0,t.jsx)(E.Tooltip,{title:l.model_info.id,children:(0,t.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:()=>i&&i(l.model_info.id),children:l.model_info.id})})]})}},{header:"Model Name",accessorKey:"model_name",enableSorting:!0,sortingFn:"alphanumeric",cell:({row:e})=>{let l=e.original,s=r(l)||l.model_name;return(0,t.jsx)("div",{className:"font-medium text-sm",children:(0,t.jsx)(E.Tooltip,{title:s,children:(0,t.jsx)("div",{className:"truncate max-w-[200px]",children:s})})})}},{header:"Team Alias",accessorKey:"model_info.team_id",enableSorting:!0,sortingFn:"alphanumeric",cell:({row:e})=>{let l=e.original,s=l.model_info?.team_id;if(!s)return(0,t.jsx)("span",{className:"text-gray-400 text-sm",children:"-"});let a=o?.find(e=>e.team_id===s),r=a?.team_alias||s;return(0,t.jsx)("div",{className:"text-sm",children:(0,t.jsx)(E.Tooltip,{title:r,children:(0,t.jsx)("div",{className:"truncate max-w-[150px]",children:r})})})}},{header:"Health Status",accessorKey:"health_status",enableSorting:!0,sortingFn:(e,t,l)=>{let s=e.getValue("health_status")||"unknown",a=t.getValue("health_status")||"unknown",r={healthy:0,checking:1,unknown:2,unhealthy:3};return(r[s]??4)-(r[a]??4)},cell:({row:e})=>{let l=e.original,s={status:l.health_status,loading:l.health_loading,error:l.health_error};if(s.loading)return(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsxs)("div",{className:"flex space-x-1",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-indigo-500 rounded-full animate-pulse"}),(0,t.jsx)("div",{className:"w-2 h-2 bg-indigo-500 rounded-full animate-pulse",style:{animationDelay:"0.2s"}}),(0,t.jsx)("div",{className:"w-2 h-2 bg-indigo-500 rounded-full animate-pulse",style:{animationDelay:"0.4s"}})]}),(0,t.jsx)(em.Text,{className:"text-gray-600 text-sm",children:"Checking..."})]});let a=l.model_info?.id??"",i=r(l)||l.model_name,o="healthy"===s.status&&u[a]?.successResponse;return(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[d(s.status),o&&m&&(0,t.jsx)(E.Tooltip,{title:"View response details",placement:"top",children:(0,t.jsx)("button",{onClick:()=>m(i,u[a]?.successResponse),className:"p-1 text-green-600 hover:text-green-800 hover:bg-green-50 rounded cursor-pointer transition-colors",children:(0,t.jsx)(tW.InformationCircleIcon,{className:"h-4 w-4"})})})]})}},{header:"Error Details",accessorKey:"health_error",enableSorting:!1,cell:({row:e})=>{let l=e.original,s=l.model_info?.id??"",a=r(l)||l.model_name,i=u[s];if(!i?.error)return(0,t.jsx)(em.Text,{className:"text-gray-400 text-sm",children:"No errors"});let o=i.error,n=i.fullError||i.error;return(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("div",{className:"max-w-[200px]",children:(0,t.jsx)(E.Tooltip,{title:o,placement:"top",children:(0,t.jsx)(em.Text,{className:"text-red-600 text-sm truncate",children:o})})}),c&&n!==o&&(0,t.jsx)(E.Tooltip,{title:"View full error details",placement:"top",children:(0,t.jsx)("button",{onClick:()=>c(a,o,n),className:"p-1 text-red-600 hover:text-red-800 hover:bg-red-50 rounded cursor-pointer transition-colors",children:(0,t.jsx)(tW.InformationCircleIcon,{className:"h-4 w-4"})})})]})}},{header:"Last Check",accessorKey:"last_check",enableSorting:!0,sortingFn:(e,t,l)=>{let s=e.getValue("last_check")||"Never checked",a=t.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:({row:e})=>{let l=e.original;return(0,t.jsx)(em.Text,{className:"text-gray-600 text-sm",children:l.health_loading?"Check in progress...":l.last_check})}},{header:"Last Success",accessorKey:"last_success",enableSorting:!0,sortingFn:(e,t,l)=>{let s=e.getValue("last_success")||"Never succeeded",a=t.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:({row:e})=>{let l=e.original,s=u[l.model_info?.id??""],a=s?.lastSuccess||"None";return(0,t.jsx)(em.Text,{className:"text-gray-600 text-sm",children:a})}},{header:"Actions",id:"actions",cell:({row:e})=>{let l=e.original,s=l.model_info?.id??"",a=l.health_status&&"none"!==l.health_status,r=l.health_loading?"Checking...":a?"Re-run Health Check":"Run Health Check";return(0,t.jsx)(E.Tooltip,{title:r,placement:"top",children:(0,t.jsx)("button",{"data-testid":"run-health-check-btn",className:`p-2 rounded-md transition-colors ${l.health_loading?"text-gray-400 cursor-not-allowed bg-gray-100":"text-indigo-600 hover:text-indigo-700 hover:bg-indigo-50"}`,onClick:()=>{l.health_loading||I(s)},disabled:l.health_loading,children:l.health_loading?(0,t.jsxs)("div",{className:"flex space-x-1",children:[(0,t.jsx)("div",{className:"w-1 h-1 bg-gray-400 rounded-full animate-pulse"}),(0,t.jsx)("div",{className:"w-1 h-1 bg-gray-400 rounded-full animate-pulse",style:{animationDelay:"0.2s"}}),(0,t.jsx)("div",{className:"w-1 h-1 bg-gray-400 rounded-full animate-pulse",style:{animationDelay:"0.4s"}})]}):a?(0,t.jsx)(e0.RefreshIcon,{className:"h-4 w-4"}):(0,t.jsx)(tQ.PlayIcon,{className:"h-4 w-4"})})})},enableSorting:!1}]),data:s.data.map(e=>{let t=e.model_info?.id,l=(t?u[t]:null)||{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,t.jsx)(el.Modal,{title:b?`Health Check Error - ${b.modelName}`:"Error Details",open:_,onCancel:A,footer:[(0,t.jsx)(K.Button,{onClick:A,children:"Close"},"close")],width:800,children:b&&(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Error:"}),(0,t.jsx)("div",{className:"mt-2 p-3 bg-red-50 border border-red-200 rounded-md",children:(0,t.jsx)(em.Text,{className:"text-red-800",children:b.cleanedError})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Full Error Details:"}),(0,t.jsx)("div",{className:"mt-2 p-3 bg-gray-50 border border-gray-200 rounded-md max-h-96 overflow-y-auto",children:(0,t.jsx)("pre",{className:"text-sm text-gray-800 whitespace-pre-wrap",children:b.fullError})})]})]})}),(0,t.jsx)(el.Modal,{title:C?`Health Check Response - ${C.modelName}`:"Response Details",open:N,onCancel:L,footer:[(0,t.jsx)(K.Button,{onClick:L,children:"Close"},"close")],width:800,children:C&&(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Status:"}),(0,t.jsx)("div",{className:"mt-2 p-3 bg-green-50 border border-green-200 rounded-md",children:(0,t.jsx)(em.Text,{className:"text-green-800",children:"Health check passed successfully"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Response Details:"}),(0,t.jsx)("div",{className:"mt-2 p-3 bg-gray-50 border border-gray-200 rounded-md max-h-96 overflow-y-auto",children:(0,t.jsx)("pre",{className:"text-sm text-gray-800 whitespace-pre-wrap",children:JSON.stringify(C.response,null,2)})})]})]})})]})};var tZ=e.i(250980),t0=e.i(797672),t1=e.i(871943),t2=e.i(502547);let t4=({accessToken:e,initialModelGroupAlias:s={},onAliasUpdate:a})=>{let[r,i]=(0,x.useState)([]),[o,n]=(0,x.useState)({aliasName:"",targetModelGroup:""}),[d,c]=(0,x.useState)(null),[m,u]=(0,x.useState)(!0);(0,x.useEffect)(()=>{i(Object.entries(s).map(([e,t],l)=>({id:`${l}-${e}`,aliasName:e,targetModelGroup:"string"==typeof t?t:t?.model??""})))},[s]);let h=async t=>{if(!e)return console.error("Access token is missing"),!1;try{let s={};return t.forEach(e=>{s[e.aliasName]=e.targetModelGroup}),console.log("Saving model group alias:",s),await (0,l.setCallbacksCall)(e,{router_settings:{model_group_alias:s}}),a&&a(s),!0}catch(e){return console.error("Failed to save model group alias settings:",e),D.default.fromBackend("Failed to save model group alias settings"),!1}},b=async()=>{if(!o.aliasName||!o.targetModelGroup)return void D.default.fromBackend("Please provide both alias name and target model group");if(r.some(e=>e.aliasName===o.aliasName))return void D.default.fromBackend("An alias with this name already exists");let e=[...r,{id:`${Date.now()}-${o.aliasName}`,aliasName:o.aliasName,targetModelGroup:o.targetModelGroup}];await h(e)&&(i(e),n({aliasName:"",targetModelGroup:""}),D.default.success("Alias added successfully"))},v=async()=>{if(!d)return;if(!d.aliasName||!d.targetModelGroup)return void D.default.fromBackend("Please provide both alias name and target model group");if(r.some(e=>e.id!==d.id&&e.aliasName===d.aliasName))return void D.default.fromBackend("An alias with this name already exists");let e=r.map(e=>e.id===d.id?d:e);await h(e)&&(i(e),c(null),D.default.success("Alias updated successfully"))},N=()=>{c(null)},w=async e=>{let t=r.filter(t=>t.id!==e);await h(t)&&(i(t),D.default.success("Alias deleted successfully"))},C=r.reduce((e,t)=>(e[t.aliasName]=t.targetModelGroup,e),{});return(0,t.jsxs)(eL.Card,{className:"mb-6",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between cursor-pointer",onClick:()=>u(!m),children:[(0,t.jsxs)("div",{className:"flex flex-col",children:[(0,t.jsx)(eu.Title,{className:"mb-0",children:"Model Group Alias Settings"}),(0,t.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,t.jsx)("div",{className:"flex items-center",children:m?(0,t.jsx)(t1.ChevronDownIcon,{className:"w-5 h-5 text-gray-500"}):(0,t.jsx)(t2.ChevronRightIcon,{className:"w-5 h-5 text-gray-500"})})]}),m&&(0,t.jsxs)("div",{className:"mt-4",children:[(0,t.jsxs)("div",{className:"mb-6",children:[(0,t.jsx)(em.Text,{className:"text-sm font-medium text-gray-700 mb-2",children:"Add New Alias"}),(0,t.jsxs)("div",{className:"grid grid-cols-3 gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-xs text-gray-500 mb-1",children:"Alias Name"}),(0,t.jsx)("input",{type:"text",value:o.aliasName,onChange:e=>n({...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,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-xs text-gray-500 mb-1",children:"Target Model Group"}),(0,t.jsx)("input",{type:"text",value:o.targetModelGroup,onChange:e=>n({...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,t.jsx)("div",{className:"flex items-end",children:(0,t.jsxs)("button",{onClick:b,disabled:!o.aliasName||!o.targetModelGroup,className:`flex items-center px-4 py-2 rounded-md text-sm ${!o.aliasName||!o.targetModelGroup?"bg-gray-300 text-gray-500 cursor-not-allowed":"bg-green-600 text-white hover:bg-green-700"}`,children:[(0,t.jsx)(tZ.PlusCircleIcon,{className:"w-4 h-4 mr-1"}),"Add Alias"]})})]})]}),(0,t.jsx)(em.Text,{className:"text-sm font-medium text-gray-700 mb-2",children:"Manage Existing Aliases"}),(0,t.jsx)("div",{className:"rounded-lg custom-border relative mb-6",children:(0,t.jsx)("div",{className:"overflow-x-auto",children:(0,t.jsxs)(p.Table,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,t.jsx)(g.TableHead,{children:(0,t.jsxs)(_.TableRow,{children:[(0,t.jsx)(f.TableHeaderCell,{className:"py-1 h-8",children:"Alias Name"}),(0,t.jsx)(f.TableHeaderCell,{className:"py-1 h-8",children:"Target Model Group"}),(0,t.jsx)(f.TableHeaderCell,{className:"py-1 h-8",children:"Actions"})]})}),(0,t.jsxs)(j.TableBody,{children:[r.map(e=>(0,t.jsx)(_.TableRow,{className:"h-8",children:d&&d.id===e.id?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(y.TableCell,{className:"py-0.5",children:(0,t.jsx)("input",{type:"text",value:d.aliasName,onChange:e=>c({...d,aliasName:e.target.value}),className:"w-full px-2 py-1 border border-gray-300 rounded-md text-sm"})}),(0,t.jsx)(y.TableCell,{className:"py-0.5",children:(0,t.jsx)("input",{type:"text",value:d.targetModelGroup,onChange:e=>c({...d,targetModelGroup:e.target.value}),className:"w-full px-2 py-1 border border-gray-300 rounded-md text-sm"})}),(0,t.jsx)(y.TableCell,{className:"py-0.5 whitespace-nowrap",children:(0,t.jsxs)("div",{className:"flex space-x-2",children:[(0,t.jsx)("button",{onClick:v,className:"text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded hover:bg-blue-100",children:"Save"}),(0,t.jsx)("button",{onClick:N,className:"text-xs bg-gray-50 text-gray-600 px-2 py-1 rounded hover:bg-gray-100",children:"Cancel"})]})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(y.TableCell,{className:"py-0.5 text-sm text-gray-900",children:e.aliasName}),(0,t.jsx)(y.TableCell,{className:"py-0.5 text-sm text-gray-500",children:e.targetModelGroup}),(0,t.jsx)(y.TableCell,{className:"py-0.5 whitespace-nowrap",children:(0,t.jsxs)("div",{className:"flex space-x-2",children:[(0,t.jsx)("button",{onClick:()=>{c({...e})},className:"text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded hover:bg-blue-100",children:(0,t.jsx)(t0.PencilIcon,{className:"w-3 h-3"})}),(0,t.jsx)("button",{onClick:()=>w(e.id),className:"text-xs bg-red-50 text-red-600 px-2 py-1 rounded hover:bg-red-100",children:(0,t.jsx)(S.TrashIcon,{className:"w-3 h-3"})})]})})]})},e.id)),0===r.length&&(0,t.jsx)(_.TableRow,{children:(0,t.jsx)(y.TableCell,{colSpan:3,className:"py-0.5 text-sm text-gray-500 text-center",children:"No aliases added yet. Add a new alias above."})})]})]})})}),(0,t.jsxs)(eL.Card,{children:[(0,t.jsx)(eu.Title,{className:"mb-4",children:"Configuration Example"}),(0,t.jsx)(em.Text,{className:"text-gray-600 mb-4",children:"Here's how your current aliases would look in the config.yaml:"}),(0,t.jsx)("div",{className:"bg-gray-100 rounded-lg p-4 font-mono text-sm",children:(0,t.jsxs)("div",{className:"text-gray-700",children:["router_settings:",(0,t.jsx)("br",{}),"  model_group_alias:",0===Object.keys(C).length?(0,t.jsxs)("span",{className:"text-gray-500",children:[(0,t.jsx)("br",{}),"    # No aliases configured yet"]}):Object.entries(C).map(([e,l])=>(0,t.jsxs)("span",{children:[(0,t.jsx)("br",{}),'    "',e,'": "',l,'"']},e))]})})]})]})]})};var t5=e.i(530212);let t6=x.forwardRef(function(e,t){return x.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:t},e),x.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"}))});var t3=e.i(678784),t8=e.i(118366),t7=e.i(500330);let t9=({isVisible:e,onCancel:s,onSuccess:a,modelData:r,accessToken:i,userRole:o})=>{let[n]=et.Form.useForm(),[d,c]=(0,x.useState)(!1),[m,u]=(0,x.useState)([]),[h,p]=(0,x.useState)([]),[g,f]=(0,x.useState)(!1),[j,_]=(0,x.useState)(!1),[y,b]=(0,x.useState)(null);(0,x.useEffect)(()=>{e&&r&&v()},[e,r]),(0,x.useEffect)(()=>{let t=async()=>{if(i)try{let e=await (0,l.modelAvailableCall)(i,"","",!1,null,!0,!0);u(e.data.map(e=>e.id))}catch(e){console.error("Error fetching model access groups:",e)}},s=async()=>{if(i)try{let e=await (0,ts.fetchAvailableModels)(i);p(e)}catch(e){console.error("Error fetching model info:",e)}};e&&(t(),s())},[e,i]);let v=()=>{try{let e=null;r.litellm_params?.auto_router_config&&(e="string"==typeof r.litellm_params.auto_router_config?JSON.parse(r.litellm_params.auto_router_config):r.litellm_params.auto_router_config),b(e),n.setFieldsValue({auto_router_name:r.model_name,auto_router_default_model:r.litellm_params?.auto_router_default_model||"",auto_router_embedding_model:r.litellm_params?.auto_router_embedding_model||"",model_access_group:r.model_info?.access_groups||[]});let t=new Set(h.map(e=>e.model_group));f(!t.has(r.litellm_params?.auto_router_default_model)),_(!t.has(r.litellm_params?.auto_router_embedding_model))}catch(e){console.error("Error parsing auto router config:",e),D.default.fromBackend("Error loading auto router configuration")}},N=async()=>{try{c(!0);let e=await n.validateFields(),t={...r.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},o={...r.model_info,access_groups:e.model_access_group||[]},d={model_name:e.auto_router_name,litellm_params:t,model_info:o};await (0,l.modelPatchUpdateCall)(i,d,r.model_info.id);let m={...r,model_name:e.auto_router_name,litellm_params:t,model_info:o};D.default.success("Auto router configuration updated successfully"),a(m),s()}catch(e){console.error("Error updating auto router:",e),D.default.fromBackend("Failed to update auto router configuration")}finally{c(!1)}},w=h.map(e=>({value:e.model_group,label:e.model_group}));return(0,t.jsx)(el.Modal,{title:"Edit Auto Router Configuration",open:e,onCancel:s,footer:[(0,t.jsx)(K.Button,{onClick:s,children:"Cancel"},"cancel"),(0,t.jsx)(K.Button,{loading:d,onClick:N,children:"Save Changes"},"submit")],width:1e3,destroyOnHidden:!0,children:(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsx)(em.Text,{className:"text-gray-600",children:"Edit the auto router configuration including routing logic, default models, and access settings."}),(0,t.jsxs)(et.Form,{form:n,layout:"vertical",className:"space-y-4",children:[(0,t.jsx)(et.Form.Item,{label:"Auto Router Name",name:"auto_router_name",rules:[{required:!0,message:"Auto router name is required"}],children:(0,t.jsx)(eR.TextInput,{placeholder:"e.g., auto_router_1, smart_routing"})}),(0,t.jsx)("div",{className:"w-full",children:(0,t.jsx)(tc,{modelInfo:h,value:y,onChange:e=>{b(e)}})}),(0,t.jsx)(et.Form.Item,{label:"Default Model",name:"auto_router_default_model",rules:[{required:!0,message:"Default model is required"}],children:(0,t.jsx)(W.Select,{placeholder:"Select a default model",onChange:e=>{f("custom"===e)},options:[...w,{value:"custom",label:"Enter custom model name"}],showSearch:!0})}),(0,t.jsx)(et.Form.Item,{label:"Embedding Model",name:"auto_router_embedding_model",children:(0,t.jsx)(W.Select,{placeholder:"Select an embedding model (optional)",onChange:e=>{_("custom"===e)},options:[...w,{value:"custom",label:"Enter custom model name"}],showSearch:!0,allowClear:!0})}),"Admin"===o&&(0,t.jsx)(et.Form.Item,{label:"Model Access Groups",name:"model_access_group",tooltip:"Control who can access this auto router",children:(0,t.jsx)(W.Select,{mode:"tags",showSearch:!0,placeholder:"Select existing groups or type to create new ones",optionFilterProp:"children",tokenSeparators:[","],options:m.map(e=>({value:e,label:e})),maxTagCount:"responsive",allowClear:!0})})]})]})})},{Title:le,Link:lt}=L.Typography,ll=({isVisible:e,onCancel:l,onAddCredential:s,existingCredential:a,setIsCredentialModalOpen:r})=>{let[i]=et.Form.useForm();return console.log(`existingCredential in add credentials tab: ${JSON.stringify(a)}`),(0,t.jsx)(el.Modal,{title:"Reuse Credentials",open:e,onCancel:()=>{l(),i.resetFields()},footer:null,width:600,children:(0,t.jsxs)(et.Form,{form:i,onFinish:e=>{s(e),i.resetFields(),r(!1)},layout:"vertical",children:[(0,t.jsx)(et.Form.Item,{label:"Credential Name:",name:"credential_name",rules:[{required:!0,message:"Credential name is required"}],initialValue:a?.credential_name,children:(0,t.jsx)(eR.TextInput,{placeholder:"Enter a friendly name for these credentials"})}),Object.entries(a?.credential_values||{}).map(([e,l])=>(0,t.jsx)(et.Form.Item,{label:e,name:e,initialValue:l,children:(0,t.jsx)(eR.TextInput,{placeholder:`Enter ${e}`,disabled:!0})},e)),(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[(0,t.jsx)(E.Tooltip,{title:"Get help on our github",children:(0,t.jsx)(lt,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,t.jsxs)("div",{children:[(0,t.jsx)(K.Button,{onClick:()=>{l(),i.resetFields()},style:{marginRight:10},children:"Cancel"}),(0,t.jsx)(K.Button,{htmlType:"submit",children:"Reuse Credentials"})]})]})]})})};function ls({modelId:e,onClose:s,accessToken:a,userID:r,userRole:i,onModelUpdate:o,modelAccessGroups:c}){let m,[u]=et.Form.useForm(),[h,p]=(0,x.useState)(null),[g,f]=(0,x.useState)(!1),[j,_]=(0,x.useState)(!1),[y,b]=(0,x.useState)(!1),[v,N]=(0,x.useState)(!1),[C,k]=(0,x.useState)(!1),[F,I]=(0,x.useState)(!1),[M,P]=(0,x.useState)(null),[A,L]=(0,x.useState)(!1),[R,O]=(0,x.useState)({}),[B,z]=(0,x.useState)(!1),[H,G]=(0,x.useState)([]),[J,Q]=(0,x.useState)({}),[Y,X]=(0,x.useState)([]),{data:Z,isLoading:ee}=(0,d.useModelsInfo)(1,50,void 0,e),{data:es}=(0,n.useModelCostMap)(),{data:ea}=(0,d.useModelHub)(),er=e=>null!=es&&"object"==typeof es&&e in es?es[e].litellm_provider:"openai",eo=(0,x.useMemo)(()=>Z?.data&&0!==Z.data.length&&ei(Z,er).data[0]||null,[Z,es]),en=("Admin"===i||eo?.model_info?.created_by===r)&&eo?.model_info?.db_model,ed="Admin"===i,ec=eo?.litellm_params?.auto_router_config!=null,eh=eo?.litellm_params?.litellm_credential_name!=null&&eo?.litellm_params?.litellm_credential_name!=void 0;(0,x.useEffect)(()=>{if(eo&&!h){let e=eo;e.litellm_model_name||(e={...e,litellm_model_name:e?.litellm_params?.litellm_model_name??e?.litellm_params?.model??e?.model_info?.key??null}),p(e),e?.litellm_params?.cache_control_injection_points&&L(!0)}},[eo,h]),(0,x.useEffect)(()=>{let t=async()=>{if(!a||eo)return;let t=(await (0,l.modelInfoV1Call)(a,e)).data[0];t&&!t.litellm_model_name&&(t={...t,litellm_model_name:t?.litellm_params?.litellm_model_name??t?.litellm_params?.model??t?.model_info?.key??null}),p(t),t?.litellm_params?.cache_control_injection_points&&L(!0)},s=async()=>{if(a)try{let e=(await (0,l.getGuardrailsList)(a)).guardrails.map(e=>e.guardrail_name);G(e)}catch(e){console.error("Failed to fetch guardrails:",e)}},r=async()=>{if(a)try{let e=await (0,l.tagListCall)(a);Q(e)}catch(e){console.error("Failed to fetch tags:",e)}},i=async()=>{if(a)try{let e=await (0,l.credentialListCall)(a);X(e.credentials||[])}catch(e){console.error("Failed to fetch credentials:",e)}};(async()=>{if(!a||eh)return;let t=await (0,l.credentialGetCall)(a,null,e);P({credential_name:t.credential_name,credential_values:t.credential_values,credential_info:t.credential_info})})(),t(),s(),r(),i()},[a,e]);let ex=async t=>{if(!a)return;let s={credential_name:t.credential_name,model_id:e,credential_info:{custom_llm_provider:h.litellm_params?.custom_llm_provider}};D.default.info("Storing credential.."),await (0,l.credentialCreateCall)(a,s),D.default.success("Credential stored successfully")},ep=async t=>{try{let s;if(!a)return;k(!0);let r={};try{r=t.litellm_extra_params?JSON.parse(t.litellm_extra_params):{},delete r.litellm_credential_name}catch(e){D.default.fromBackend("Invalid JSON in LiteLLM Params"),k(!1);return}let i={...t.litellm_params,...r,model:t.litellm_model_name,api_base:t.api_base,custom_llm_provider:t.custom_llm_provider,organization:t.organization,tpm:t.tpm,rpm:t.rpm,max_retries:t.max_retries,timeout:t.timeout,stream_timeout:t.stream_timeout,input_cost_per_token:t.input_cost/1e6,output_cost_per_token:t.output_cost/1e6,tags:t.tags};t.litellm_credential_name?i.litellm_credential_name=t.litellm_credential_name:delete i.litellm_credential_name,t.guardrails&&(i.guardrails=t.guardrails),void 0!==t.vector_store_ids&&(i.vector_store_ids=Array.isArray(t.vector_store_ids)?t.vector_store_ids:[]),t.cache_control&&t.cache_control_injection_points?.length>0?i.cache_control_injection_points=t.cache_control_injection_points:delete i.cache_control_injection_points;try{s=t.model_info?JSON.parse(t.model_info):eo.model_info,t.model_access_group&&(s={...s,access_groups:t.model_access_group}),void 0!==t.health_check_model&&(s={...s,health_check_model:t.health_check_model})}catch(e){D.default.fromBackend("Invalid JSON in Model Info");return}let n={model_name:t.model_name,litellm_params:i,model_info:s};await (0,l.modelPatchUpdateCall)(a,n,e);let d={...h,model_name:t.model_name,litellm_model_name:t.litellm_model_name,litellm_params:i,model_info:s};p(d),o&&o(d),D.default.success("Model settings updated successfully"),N(!1),I(!1)}catch(e){console.error("Error updating model:",e),D.default.fromBackend("Failed to update model settings")}finally{k(!1)}};if(ee)return(0,t.jsxs)("div",{className:"p-4",children:[(0,t.jsx)(T.Button,{icon:t5.ArrowLeftIcon,variant:"light",onClick:s,className:"mb-4",children:"Back to Models"}),(0,t.jsx)(em.Text,{children:"Loading..."})]});if(!eo)return(0,t.jsxs)("div",{className:"p-4",children:[(0,t.jsx)(T.Button,{icon:t5.ArrowLeftIcon,variant:"light",onClick:s,className:"mb-4",children:"Back to Models"}),(0,t.jsx)(em.Text,{children:"Model not found"})]});let eg=async()=>{if(a)try{D.default.info("Testing connection...");let e=await (0,l.testConnectionRequest)(a,{custom_llm_provider:h.litellm_params.custom_llm_provider,litellm_credential_name:h.litellm_params.litellm_credential_name,model:h.litellm_model_name},{mode:h.model_info?.mode},h.model_info?.mode);if("success"===e.status)D.default.success("Connection test successful!");else throw Error(e?.result?.error||e?.message||"Unknown error")}catch(e){e instanceof Error?D.default.error("Error testing connection: "+(0,tE.truncateString)(e.message,100)):D.default.error("Error testing connection: "+String(e))}},ef=async()=>{try{if(_(!0),!a)return;await (0,l.modelDeleteCall)(a,e),D.default.success("Model deleted successfully"),o&&o({deleted:!0,model_info:{id:e}}),s()}catch(e){console.error("Error deleting the model:",e),D.default.fromBackend("Failed to delete model")}finally{_(!1),f(!1)}},ej=async(e,t)=>{await (0,t7.copyToClipboard)(e)&&(O(e=>({...e,[t]:!0})),setTimeout(()=>{O(e=>({...e,[t]:!1}))},2e3))},e_=eo.litellm_model_name.includes("*");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)(T.Button,{icon:t5.ArrowLeftIcon,variant:"light",onClick:s,className:"mb-4",children:"Back to Models"}),(0,t.jsxs)(eu.Title,{children:["Public Model Name: ",q(eo)]}),(0,t.jsxs)("div",{className:"flex items-center cursor-pointer",children:[(0,t.jsx)(em.Text,{className:"text-gray-500 font-mono",children:eo.model_info.id}),(0,t.jsx)(K.Button,{type:"text",size:"small",icon:R["model-id"]?(0,t.jsx)(t3.CheckIcon,{size:12}):(0,t.jsx)(t8.CopyIcon,{size:12}),onClick:()=>ej(eo.model_info.id,"model-id"),className:`left-2 z-10 transition-all duration-200 ${R["model-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",{className:"flex gap-2",children:[(0,t.jsx)(T.Button,{variant:"secondary",icon:e0.RefreshIcon,onClick:eg,className:"flex items-center gap-2","data-testid":"test-connection-button",children:"Test Connection"}),(0,t.jsx)(T.Button,{icon:t6,variant:"secondary",onClick:()=>b(!0),className:"flex items-center",disabled:!ed,"data-testid":"reuse-credentials-button",children:"Re-use Credentials"}),(0,t.jsx)(T.Button,{icon:S.TrashIcon,variant:"secondary",onClick:()=>f(!0),className:"flex items-center text-red-500 border-red-500 hover:text-red-700",disabled:!en,"data-testid":"delete-model-button",children:"Delete Model"})]})]}),(0,t.jsxs)(e4.TabGroup,{children:[(0,t.jsxs)(e5.TabList,{className:"mb-6",children:[(0,t.jsx)(e2.Tab,{children:"Overview"}),(0,t.jsx)(e2.Tab,{children:"Raw JSON"})]}),(0,t.jsxs)(e6.TabPanels,{children:[(0,t.jsxs)(U.TabPanel,{children:[(0,t.jsxs)($.Grid,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6 mb-6",children:[(0,t.jsxs)(eL.Card,{children:[(0,t.jsx)(em.Text,{children:"Provider"}),(0,t.jsxs)("div",{className:"mt-2 flex items-center space-x-2",children:[eo.provider&&(0,t.jsx)("img",{src:(0,eM.getProviderLogoAndName)(eo.provider).logo,alt:`${eo.provider} logo`,className:"w-4 h-4",onError:e=>{let t=e.currentTarget,l=t.parentElement;if(l&&l.contains(t))try{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=eo.provider?.charAt(0)||"-",l.replaceChild(e,t)}catch(e){console.error("Failed to replace provider logo fallback:",e)}}}),(0,t.jsx)(eu.Title,{children:eo.provider||"Not Set"})]})]}),(0,t.jsxs)(eL.Card,{children:[(0,t.jsx)(em.Text,{children:"LiteLLM Model"}),(0,t.jsx)("div",{className:"mt-2 overflow-hidden",children:(0,t.jsx)(E.Tooltip,{title:eo.litellm_model_name||"Not Set",children:(0,t.jsx)("div",{className:"break-all text-sm font-medium leading-relaxed cursor-pointer",children:eo.litellm_model_name||"Not Set"})})})]}),(0,t.jsxs)(eL.Card,{children:[(0,t.jsx)(em.Text,{children:"Pricing"}),(0,t.jsxs)("div",{className:"mt-2",children:[(0,t.jsxs)(em.Text,{children:["Input: $",eo.input_cost,"/1M tokens"]}),(0,t.jsxs)(em.Text,{children:["Output: $",eo.output_cost,"/1M tokens"]})]})]})]}),(0,t.jsxs)("div",{className:"mb-6 text-sm text-gray-500 flex items-center gap-x-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-x-2",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:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),"Created At"," ",eo.model_info.created_at?new Date(eo.model_info.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"Not Set"]}),(0,t.jsxs)("div",{className:"flex items-center gap-x-2",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:"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 ",eo.model_info.created_by||"Not Set"]})]}),(0,t.jsxs)(eL.Card,{children:[(0,t.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,t.jsx)(eu.Title,{children:"Model Settings"}),(0,t.jsxs)("div",{className:"flex gap-2",children:[ec&&en&&!F&&(0,t.jsx)(T.Button,{onClick:()=>z(!0),className:"flex items-center",children:"Edit Auto Router"}),en?!F&&(0,t.jsx)(T.Button,{onClick:()=>I(!0),className:"flex items-center",children:"Edit Settings"}):(0,t.jsx)(E.Tooltip,{title:"Only DB models can be edited. You must be an admin or the creator of the model to edit it.",children:(0,t.jsx)(w.InfoCircleOutlined,{})})]})]}),h?(0,t.jsx)(et.Form,{form:u,onFinish:ep,initialValues:{model_name:h.model_name,litellm_model_name:h.litellm_model_name,api_base:h.litellm_params.api_base,custom_llm_provider:h.litellm_params.custom_llm_provider,organization:h.litellm_params.organization,tpm:h.litellm_params.tpm,rpm:h.litellm_params.rpm,max_retries:h.litellm_params.max_retries,timeout:h.litellm_params.timeout,stream_timeout:h.litellm_params.stream_timeout,input_cost:h.litellm_params.input_cost_per_token?1e6*h.litellm_params.input_cost_per_token:h.model_info?.input_cost_per_token*1e6||null,output_cost:h.litellm_params?.output_cost_per_token?1e6*h.litellm_params.output_cost_per_token:h.model_info?.output_cost_per_token*1e6||null,cache_control:!!h.litellm_params?.cache_control_injection_points,cache_control_injection_points:h.litellm_params?.cache_control_injection_points||[],model_access_group:Array.isArray(h.model_info?.access_groups)?h.model_info.access_groups:[],guardrails:Array.isArray(h.litellm_params?.guardrails)?h.litellm_params.guardrails:[],vector_store_ids:Array.isArray(h.litellm_params?.vector_store_ids)?h.litellm_params.vector_store_ids:[],tags:Array.isArray(h.litellm_params?.tags)?h.litellm_params.tags:[],health_check_model:e_?h.model_info?.health_check_model:null,litellm_credential_name:h.litellm_params?.litellm_credential_name||"",litellm_extra_params:JSON.stringify(Object.fromEntries(Object.entries(h.litellm_params||{}).filter(([e])=>"litellm_credential_name"!==e)),null,2)},layout:"vertical",onValuesChange:()=>N(!0),children:(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Model Name"}),F?(0,t.jsx)(et.Form.Item,{name:"model_name",className:"mb-0",children:(0,t.jsx)(eR.TextInput,{placeholder:"Enter model name"})}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:h.model_name})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"LiteLLM Model Name"}),F?(0,t.jsx)(et.Form.Item,{name:"litellm_model_name",className:"mb-0",children:(0,t.jsx)(eR.TextInput,{placeholder:"Enter LiteLLM model name"})}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:h.litellm_model_name})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Input Cost (per 1M tokens)"}),F?(0,t.jsx)(et.Form.Item,{name:"input_cost",className:"mb-0",children:(0,t.jsx)(tI.default,{placeholder:"Enter input cost"})}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:h?.litellm_params?.input_cost_per_token?(h.litellm_params?.input_cost_per_token*1e6).toFixed(4):h?.model_info?.input_cost_per_token?(1e6*h.model_info.input_cost_per_token).toFixed(4):"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Output Cost (per 1M tokens)"}),F?(0,t.jsx)(et.Form.Item,{name:"output_cost",className:"mb-0",children:(0,t.jsx)(tI.default,{placeholder:"Enter output cost"})}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:h?.litellm_params?.output_cost_per_token?(1e6*h.litellm_params.output_cost_per_token).toFixed(4):h?.model_info?.output_cost_per_token?(1e6*h.model_info.output_cost_per_token).toFixed(4):"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"API Base"}),F?(0,t.jsx)(et.Form.Item,{name:"api_base",className:"mb-0",children:(0,t.jsx)(eR.TextInput,{placeholder:"Enter API base"})}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:h.litellm_params?.api_base||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Custom LLM Provider"}),F?(0,t.jsx)(et.Form.Item,{name:"custom_llm_provider",className:"mb-0",children:(0,t.jsx)(eR.TextInput,{placeholder:"Enter custom LLM provider"})}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:h.litellm_params?.custom_llm_provider||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Organization"}),F?(0,t.jsx)(et.Form.Item,{name:"organization",className:"mb-0",children:(0,t.jsx)(eR.TextInput,{placeholder:"Enter organization"})}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:h.litellm_params?.organization||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"TPM (Tokens per Minute)"}),F?(0,t.jsx)(et.Form.Item,{name:"tpm",className:"mb-0",children:(0,t.jsx)(tI.default,{placeholder:"Enter TPM"})}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:h.litellm_params?.tpm||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"RPM (Requests per Minute)"}),F?(0,t.jsx)(et.Form.Item,{name:"rpm",className:"mb-0",children:(0,t.jsx)(tI.default,{placeholder:"Enter RPM"})}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:h.litellm_params?.rpm||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Max Retries"}),F?(0,t.jsx)(et.Form.Item,{name:"max_retries",className:"mb-0",children:(0,t.jsx)(tI.default,{placeholder:"Enter max retries"})}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:h.litellm_params?.max_retries||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Timeout (seconds)"}),F?(0,t.jsx)(et.Form.Item,{name:"timeout",className:"mb-0",children:(0,t.jsx)(tI.default,{placeholder:"Enter timeout"})}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:h.litellm_params?.timeout||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Stream Timeout (seconds)"}),F?(0,t.jsx)(et.Form.Item,{name:"stream_timeout",className:"mb-0",children:(0,t.jsx)(tI.default,{placeholder:"Enter stream timeout"})}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:h.litellm_params?.stream_timeout||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Model Access Groups"}),F?(0,t.jsx)(et.Form.Item,{name:"model_access_group",className:"mb-0",children:(0,t.jsx)(W.Select,{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:c?.map(e=>({value:e,label:e}))})}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:h.model_info?.access_groups?Array.isArray(h.model_info.access_groups)?h.model_info.access_groups.length>0?(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:h.model_info.access_groups.map((e,l)=>(0,t.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":h.model_info.access_groups:"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)(em.Text,{className:"font-medium",children:["Guardrails",(0,t.jsx)(E.Tooltip,{title:"Apply safety guardrails to this model to filter content or enforce policies",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(w.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),F?(0,t.jsx)(et.Form.Item,{name:"guardrails",className:"mb-0",children:(0,t.jsx)(W.Select,{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:H.map(e=>({value:e,label:e}))})}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:h.litellm_params?.guardrails?Array.isArray(h.litellm_params.guardrails)?h.litellm_params.guardrails.length>0?(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:h.litellm_params.guardrails.map((e,l)=>(0,t.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":h.litellm_params.guardrails:"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)(em.Text,{className:"font-medium",children:["Attached Knowledge Bases (RAG)",(0,t.jsx)(E.Tooltip,{title:"Vector stores used for RAG. Every request to this model will automatically retrieve context from these knowledge bases.",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/completion/knowledgebase",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(w.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),F?(0,t.jsx)(et.Form.Item,{name:"vector_store_ids",className:"mb-0",children:(0,t.jsx)(tA.default,{onChange:()=>{},accessToken:a||"",placeholder:"Select knowledge bases (optional)"})}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:h.litellm_params?.vector_store_ids?Array.isArray(h.litellm_params.vector_store_ids)?h.litellm_params.vector_store_ids.length>0?(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:h.litellm_params.vector_store_ids.map((e,l)=>(0,t.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 knowledge bases attached":String(h.litellm_params.vector_store_ids):"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Tags"}),F?(0,t.jsx)(et.Form.Item,{name:"tags",className:"mb-0",children:(0,t.jsx)(W.Select,{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(J).map(e=>({value:e.name,label:e.name,title:e.description||e.name}))})}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:h.litellm_params?.tags?Array.isArray(h.litellm_params.tags)?h.litellm_params.tags.length>0?(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:h.litellm_params.tags.map((e,l)=>(0,t.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":h.litellm_params.tags:"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Existing Credentials"}),F?(0,t.jsx)(et.Form.Item,{name:"litellm_credential_name",className:"mb-0",children:(0,t.jsx)(W.Select,{showSearch:!0,placeholder:"Select or search for existing credentials",optionFilterProp:"children",filterOption:(e,t)=>(t?.label??"").toLowerCase().includes(e.toLowerCase()),options:[{value:"",label:"None"},...Y.map(e=>({value:e.credential_name,label:e.credential_name}))],allowClear:!0})}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:h.litellm_params?.litellm_credential_name||"Manual"})]}),e_&&(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Health Check Model"}),F?(0,t.jsx)(et.Form.Item,{name:"health_check_model",className:"mb-0",children:(0,t.jsx)(W.Select,{showSearch:!0,placeholder:"Select existing health check model",optionFilterProp:"children",allowClear:!0,options:(m=eo.litellm_model_name.split("/")[0],ea?.data?.filter(e=>e.providers?.includes(m)&&e.model_group!==eo.litellm_model_name).map(e=>({value:e.model_group,label:e.model_group}))||[])})}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:h.model_info?.health_check_model||"Not Set"})]}),F?(0,t.jsx)(tP,{form:u,showCacheControl:A,onCacheControlChange:e=>L(e)}):(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Cache Control"}),(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:h.litellm_params?.cache_control_injection_points?(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{children:"Enabled"}),(0,t.jsx)("div",{className:"mt-2",children:h.litellm_params.cache_control_injection_points.map((e,l)=>(0,t.jsxs)("div",{className:"text-sm text-gray-600 mb-1",children:["Location: ",e.location,",",e.role&&(0,t.jsxs)("span",{children:[" Role: ",e.role]}),void 0!==e.index&&(0,t.jsxs)("span",{children:[" Index: ",e.index]})]},l))})]}):"Disabled"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Model Info"}),F?(0,t.jsx)(et.Form.Item,{name:"model_info",className:"mb-0",children:(0,t.jsx)(eV.Input.TextArea,{rows:4,placeholder:'{"gpt-4": 100, "claude-v1": 200}',defaultValue:JSON.stringify(eo.model_info,null,2)})}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(0,t.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify(h.model_info,null,2)})})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)(em.Text,{className:"font-medium",children:["LiteLLM Params",(0,t.jsx)(E.Tooltip,{title:"Optional litellm params used for making a litellm.completion() call. Some params are automatically added by LiteLLM.",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/completion/input",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(w.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),F?(0,t.jsx)(et.Form.Item,{name:"litellm_extra_params",rules:[{validator:tE.formItemValidateJSON}],children:(0,t.jsx)(eV.Input.TextArea,{rows:4,placeholder:'{ "rpm": 100, "timeout": 0, "stream_timeout": 0 }'})}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(0,t.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify(h.litellm_params,null,2)})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Team ID"}),(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:eo.model_info.team_id||"Not Set"})]})]}),F&&(0,t.jsxs)("div",{className:"mt-6 flex justify-end gap-2",children:[(0,t.jsx)(T.Button,{variant:"secondary",onClick:()=>{u.resetFields(),N(!1),I(!1)},disabled:C,children:"Cancel"}),(0,t.jsx)(T.Button,{variant:"primary",onClick:()=>u.submit(),loading:C,children:"Save Changes"})]})]})}):(0,t.jsx)(em.Text,{children:"Loading..."})]})]}),(0,t.jsx)(U.TabPanel,{children:(0,t.jsx)(eL.Card,{children:(0,t.jsx)("pre",{className:"bg-gray-100 p-4 rounded text-xs overflow-auto",children:JSON.stringify(eo,null,2)})})})]})]}),(0,t.jsx)(V.default,{isOpen:g,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:eo?.model_name||"Not Set"},{label:"LiteLLM Model Name",value:eo?.litellm_model_name||"Not Set"},{label:"Provider",value:eo?.provider||"Not Set"},{label:"Created By",value:eo?.model_info?.created_by||"Not Set"}],onCancel:()=>f(!1),onOk:ef,confirmLoading:j}),y&&!eh?(0,t.jsx)(ll,{isVisible:y,onCancel:()=>b(!1),onAddCredential:ex,existingCredential:M,setIsCredentialModalOpen:b}):(0,t.jsx)(el.Modal,{open:y,onCancel:()=>b(!1),title:"Using Existing Credential",children:(0,t.jsx)(em.Text,{children:eo.litellm_params.litellm_credential_name})}),(0,t.jsx)(t9,{isVisible:B,onCancel:()=>z(!1),onSuccess:e=>{p(e),o&&o(e)},modelData:h||eo,accessToken:a||"",userRole:i||""})]})}var la=e.i(37091),lr=e.i(218129);let li=({value:e={},onChange:l})=>{let[s,a]=(0,x.useState)(Object.entries(e)),r=(e,t,r)=>{let i=[...s];i[e]=[t,r],a(i),l?.(Object.fromEntries(i))};return(0,t.jsxs)("div",{children:[s.map(([e,i],o)=>(0,t.jsxs)(A.Space,{style:{display:"flex",marginBottom:8},align:"center",children:[(0,t.jsx)(eR.TextInput,{placeholder:"Header Name",value:e,onChange:e=>r(o,e.target.value,i)}),(0,t.jsx)(eR.TextInput,{placeholder:"Header Value",value:i,onChange:t=>r(o,e,t.target.value)}),(0,t.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"},children:(0,t.jsx)(tF.MinusCircleOutlined,{onClick:()=>{let e;a(e=s.filter((e,t)=>t!==o)),l?.(Object.fromEntries(e))},style:{cursor:"pointer"}})})]},o)),(0,t.jsx)(K.Button,{type:"dashed",onClick:()=>{a([...s,["",""]])},icon:(0,t.jsx)(tr.PlusOutlined,{}),children:"Add Header"})]})},lo=({value:e={},onChange:l})=>{let[s,a]=(0,x.useState)(Object.entries(e)),r=(e,t,r)=>{let i=[...s];i[e]=[t,r],a(i),l?.(Object.fromEntries(i))};return(0,t.jsxs)("div",{children:[s.map(([e,i],o)=>(0,t.jsxs)(A.Space,{style:{display:"flex",marginBottom:8},align:"center",children:[(0,t.jsx)(eR.TextInput,{placeholder:"Parameter Name (e.g., version)",value:e,onChange:e=>r(o,e.target.value,i)}),(0,t.jsx)(eR.TextInput,{placeholder:"Parameter Value (e.g., v1)",value:i,onChange:t=>r(o,e,t.target.value)}),(0,t.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"},children:(0,t.jsx)(tF.MinusCircleOutlined,{onClick:()=>{let e;a(e=s.filter((e,t)=>t!==o)),l?.(Object.fromEntries(e))},style:{cursor:"pointer"}})})]},o)),(0,t.jsx)(K.Button,{type:"dashed",onClick:()=>{a([...s,["",""]])},icon:(0,t.jsx)(tr.PlusOutlined,{}),children:"Add Query Parameter"})]})};var ln=e.i(240647);let ld=({pathValue:e,targetValue:s,includeSubpath:a})=>{let r=(0,l.getProxyBaseUrl)();return e&&s?(0,t.jsxs)(eL.Card,{className:"p-5",children:[(0,t.jsx)(eu.Title,{className:"text-lg font-semibold text-gray-900 mb-2",children:"Route Preview"}),(0,t.jsx)(la.Subtitle,{className:"text-gray-600 mb-5",children:"How your requests will be routed"}),(0,t.jsxs)("div",{className:"space-y-5",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-base font-semibold text-gray-900 mb-3",children:"Basic routing:"}),(0,t.jsxs)("div",{className:"flex items-center gap-4",children:[(0,t.jsxs)("div",{className:"flex-1 bg-gray-50 border border-gray-200 rounded-lg p-3",children:[(0,t.jsx)("div",{className:"text-sm text-gray-600 mb-2",children:"Your endpoint"}),(0,t.jsx)("code",{className:"font-mono text-sm text-gray-900",children:e?`${r}${e}`:""})]}),(0,t.jsx)("div",{className:"text-gray-400",children:(0,t.jsx)(ln.RightOutlined,{className:"text-lg"})}),(0,t.jsxs)("div",{className:"flex-1 bg-gray-50 border border-gray-200 rounded-lg p-3",children:[(0,t.jsx)("div",{className:"text-sm text-gray-600 mb-2",children:"Forwards to"}),(0,t.jsx)("code",{className:"font-mono text-sm text-gray-900",children:s})]})]})]}),a&&(0,t.jsx)(t.Fragment,{children:(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-base font-semibold text-gray-900 mb-3",children:"With subpaths:"}),(0,t.jsxs)("div",{className:"flex items-center gap-4",children:[(0,t.jsxs)("div",{className:"flex-1 bg-gray-50 border border-gray-200 rounded-lg p-3",children:[(0,t.jsx)("div",{className:"text-sm text-gray-600 mb-2",children:"Your endpoint + subpath"}),(0,t.jsxs)("code",{className:"font-mono text-sm text-gray-900",children:[e&&`${r}${e}`,(0,t.jsx)("span",{className:"text-blue-600",children:"/v1/text-to-image/base/model"})]})]}),(0,t.jsx)("div",{className:"text-gray-400",children:(0,t.jsx)(ln.RightOutlined,{className:"text-lg"})}),(0,t.jsxs)("div",{className:"flex-1 bg-gray-50 border border-gray-200 rounded-lg p-3",children:[(0,t.jsx)("div",{className:"text-sm text-gray-600 mb-2",children:"Forwards to"}),(0,t.jsxs)("code",{className:"font-mono text-sm text-gray-900",children:[s,(0,t.jsx)("span",{className:"text-blue-600",children:"/v1/text-to-image/base/model"})]})]})]}),(0,t.jsxs)("div",{className:"mt-3 text-sm text-gray-600",children:["Any path after ",e," will be appended to the target URL"]})]})}),!a&&(0,t.jsx)("div",{className:"mt-4 p-3 bg-blue-50 rounded-md border border-blue-200",children:(0,t.jsxs)("div",{className:"flex items-start",children:[(0,t.jsx)(w.InfoCircleOutlined,{className:"text-blue-500 mt-0.5 mr-2 flex-shrink-0"}),(0,t.jsxs)("div",{className:"text-sm text-blue-700",children:[(0,t.jsx)("span",{className:"font-medium",children:"Not seeing the routing you wanted?"})," Try enabling - Include Subpaths - above - this allows subroutes like"," ",(0,t.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},lc=({premiumUser:e,authEnabled:l,onAuthChange:s})=>(0,t.jsxs)(eL.Card,{className:"p-6",children:[(0,t.jsx)(eu.Title,{className:"text-lg font-semibold text-gray-900 mb-2",children:"Security"}),(0,t.jsx)(la.Subtitle,{className:"text-gray-600 mb-4",children:"When enabled, requests to this endpoint will require a valid LiteLLM Virtual Key"}),e?(0,t.jsx)(et.Form.Item,{name:"auth",valuePropName:"checked",className:"mb-0",children:(0,t.jsx)(es.Switch,{checked:l,onChange:e=>{s(e)}})}):(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center mb-3",children:[(0,t.jsx)(es.Switch,{disabled:!0,checked:!1,style:{outline:"2px solid #d1d5db",outlineOffset:"2px"}}),(0,t.jsx)("span",{className:"ml-2 text-sm text-gray-400",children:"Authentication (Premium)"})]}),(0,t.jsx)("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-lg",children:(0,t.jsxs)(em.Text,{className:"text-sm text-yellow-800",children:["Setting authentication for pass-through endpoints is a LiteLLM Enterprise feature. Get a trial key"," ",(0,t.jsx)("a",{href:"https://www.litellm.ai/#pricing",target:"_blank",rel:"noopener noreferrer",className:"underline",children:"here"}),"."]})})]})]});var lm=e.i(891547);let lu=({accessToken:e,value:l={},onChange:s,disabled:a=!1})=>{let[r,i]=(0,x.useState)(Object.keys(l)),[o,n]=(0,x.useState)(l);(0,x.useEffect)(()=>{n(l),i(Object.keys(l))},[l]);let d=(e,t,l)=>{let a=o[e]||{},r={...o,[e]:{...a,[t]:l.length>0?l:void 0}};r[e]?.request_fields||r[e]?.response_fields||(r[e]=null),n(r),s&&s(r)};return(0,t.jsxs)(eL.Card,{className:"p-6",children:[(0,t.jsx)(eu.Title,{className:"text-lg font-semibold text-gray-900 mb-2",children:"Guardrails"}),(0,t.jsx)(la.Subtitle,{className:"text-gray-600 mb-6",children:"Configure guardrails to enforce policies on requests and responses. Guardrails are opt-in for passthrough endpoints."}),(0,t.jsx)(tN.Alert,{message:(0,t.jsxs)("span",{children:["Field-Level Targeting"," ",(0,t.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,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("div",{children:"Optionally specify which fields to check. If left empty, the entire request/response is sent to the guardrail."}),(0,t.jsxs)("div",{className:"text-xs space-y-1 mt-2",children:[(0,t.jsx)("div",{className:"font-medium",children:"Common Examples:"}),(0,t.jsxs)("div",{children:["• ",(0,t.jsx)("code",{className:"bg-gray-100 px-1 rounded",children:"query"})," - Single field"]}),(0,t.jsxs)("div",{children:["• ",(0,t.jsx)("code",{className:"bg-gray-100 px-1 rounded",children:"documents[*].text"})," - All text in documents array"]}),(0,t.jsxs)("div",{children:["• ",(0,t.jsx)("code",{className:"bg-gray-100 px-1 rounded",children:"messages[*].content"})," - All message contents"]})]})]}),type:"info",showIcon:!0,className:"mb-4"}),(0,t.jsx)(et.Form.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Select Guardrails",(0,t.jsx)(E.Tooltip,{title:"Choose which guardrails should run on this endpoint. Org/team/key level guardrails will also be included.",children:(0,t.jsx)(w.InfoCircleOutlined,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),children:(0,t.jsx)(lm.default,{accessToken:e,value:r,onChange:e=>{i(e);let t={};e.forEach(e=>{t[e]=o[e]||null}),n(t),s&&s(t)},disabled:a})}),r.length>0&&(0,t.jsxs)("div",{className:"mt-6 space-y-4",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-3",children:[(0,t.jsx)("div",{className:"text-sm font-medium text-gray-700",children:"Field Targeting (Optional)"}),(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"💡 Tip: Leave empty to check entire payload"})]}),r.map(e=>(0,t.jsxs)(eL.Card,{className:"p-4 bg-gray-50",children:[(0,t.jsx)("div",{className:"text-sm font-medium text-gray-900 mb-3",children:e}),(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,t.jsxs)("label",{className:"text-xs text-gray-600 flex items-center",children:["Request Fields (pre_call)",(0,t.jsx)(E.Tooltip,{title:(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"font-medium mb-1",children:"Specify which request fields to check"}),(0,t.jsxs)("div",{className:"text-xs space-y-1",children:[(0,t.jsx)("div",{children:"Examples:"}),(0,t.jsx)("div",{children:"• query"}),(0,t.jsx)("div",{children:"• documents[*].text"}),(0,t.jsx)("div",{children:"• messages[*].content"})]})]}),children:(0,t.jsx)(w.InfoCircleOutlined,{className:"ml-1 text-gray-400"})})]}),(0,t.jsxs)("div",{className:"flex gap-1",children:[(0,t.jsx)("button",{type:"button",onClick:()=>{let t=o[e]?.request_fields||[];d(e,"request_fields",[...t,"query"])},className:"text-xs px-2 py-1 bg-white border border-gray-300 rounded hover:bg-gray-50",disabled:a,children:"+ query"}),(0,t.jsx)("button",{type:"button",onClick:()=>{let t=o[e]?.request_fields||[];d(e,"request_fields",[...t,"documents[*]"])},className:"text-xs px-2 py-1 bg-white border border-gray-300 rounded hover:bg-gray-50",disabled:a,children:"+ documents[*]"})]})]}),(0,t.jsx)(W.Select,{mode:"tags",style:{width:"100%"},placeholder:"Type field name or use + buttons above (e.g., query, documents[*].text)",value:o[e]?.request_fields||[],onChange:t=>d(e,"request_fields",t),disabled:a,tokenSeparators:[","]})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,t.jsxs)("label",{className:"text-xs text-gray-600 flex items-center",children:["Response Fields (post_call)",(0,t.jsx)(E.Tooltip,{title:(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"font-medium mb-1",children:"Specify which response fields to check"}),(0,t.jsxs)("div",{className:"text-xs space-y-1",children:[(0,t.jsx)("div",{children:"Examples:"}),(0,t.jsx)("div",{children:"• results[*].text"}),(0,t.jsx)("div",{children:"• choices[*].message.content"})]})]}),children:(0,t.jsx)(w.InfoCircleOutlined,{className:"ml-1 text-gray-400"})})]}),(0,t.jsx)("div",{className:"flex gap-1",children:(0,t.jsx)("button",{type:"button",onClick:()=>{let t=o[e]?.response_fields||[];d(e,"response_fields",[...t,"results[*]"])},className:"text-xs px-2 py-1 bg-white border border-gray-300 rounded hover:bg-gray-50",disabled:a,children:"+ results[*]"})})]}),(0,t.jsx)(W.Select,{mode:"tags",style:{width:"100%"},placeholder:"Type field name or use + buttons above (e.g., results[*].text)",value:o[e]?.response_fields||[],onChange:t=>d(e,"response_fields",t),disabled:a,tokenSeparators:[","]})]})]})]},e))]})]})},{Option:lh}=W.Select,lx=["GET","POST","PUT","DELETE","PATCH"],lp=({accessToken:e,setPassThroughItems:s,passThroughItems:a,premiumUser:r=!1})=>{let[i]=et.Form.useForm(),[o,n]=(0,x.useState)(!1),[d,c]=(0,x.useState)(!1),[m,u]=(0,x.useState)(""),[h,p]=(0,x.useState)(""),[g,f]=(0,x.useState)(""),[j,_]=(0,x.useState)(!0),[y,b]=(0,x.useState)(!1),[v,N]=(0,x.useState)([]),[C,S]=(0,x.useState)({}),k=()=>{i.resetFields(),p(""),f(""),_(!0),N([]),S({}),n(!1)},F=async t=>{console.log("addPassThrough called with:",t),c(!0);try{!r&&"auth"in t&&delete t.auth,C&&Object.keys(C).length>0&&(t.guardrails=C),v&&v.length>0&&(t.methods=v),console.log(`formValues: ${JSON.stringify(t)}`);let o=(await (0,l.createPassThroughEndpoint)(e,t)).endpoints[0],d=[...a,o];s(d),D.default.success("Pass-through endpoint created successfully"),i.resetFields(),p(""),f(""),_(!0),N([]),S({}),n(!1)}catch(e){D.default.fromBackend("Error creating pass-through endpoint: "+e)}finally{c(!1)}};return(0,t.jsxs)("div",{children:[(0,t.jsx)(T.Button,{className:"mx-auto mb-4 mt-4",onClick:()=>n(!0),children:"+ Add Pass-Through Endpoint"}),(0,t.jsx)(el.Modal,{title:(0,t.jsxs)("div",{className:"flex items-center space-x-3 pb-4 border-b border-gray-100",children:[(0,t.jsx)(lr.ApiOutlined,{className:"text-xl text-blue-500"}),(0,t.jsx)("h2",{className:"text-xl font-semibold text-gray-900",children:"Add Pass-Through Endpoint"})]}),open:o,width:1e3,onCancel:k,footer:null,className:"top-8",styles:{body:{padding:"24px"},header:{padding:"24px 24px 0 24px",border:"none"}},children:(0,t.jsxs)("div",{className:"mt-6",children:[(0,t.jsx)(tN.Alert,{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,t.jsxs)(et.Form,{form:i,onFinish:F,layout:"vertical",className:"space-y-6",initialValues:{include_subpath:!0,path:h,target:g},children:[(0,t.jsxs)(eL.Card,{className:"p-5",children:[(0,t.jsx)(eu.Title,{className:"text-lg font-semibold text-gray-900 mb-2",children:"Route Configuration"}),(0,t.jsx)(la.Subtitle,{className:"text-gray-600 mb-5",children:"Configure how requests to your domain will be forwarded to the target API"}),(0,t.jsxs)("div",{className:"space-y-5",children:[(0,t.jsx)(et.Form.Item,{label:(0,t.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,t.jsx)("div",{className:"text-xs text-gray-500 mt-1",children:"Example: /bria, /adobe-photoshop, /elasticsearch"}),className:"mb-4",children:(0,t.jsx)("div",{className:"flex items-center",children:(0,t.jsx)(eR.TextInput,{placeholder:"bria",value:h,onChange:e=>{var t;let l;return l=t=e.target.value,void(t&&!t.startsWith("/")&&(l="/"+t),p(l),i.setFieldsValue({path:l}))},className:"flex-1"})})}),(0,t.jsx)(et.Form.Item,{label:(0,t.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,t.jsx)("div",{className:"text-xs text-gray-500 mt-1",children:"Example:https://engine.prod.bria-api.com"}),className:"mb-4",children:(0,t.jsx)(eR.TextInput,{placeholder:"https://engine.prod.bria-api.com",value:g,onChange:e=>{f(e.target.value),i.setFieldsValue({target:e.target.value})}})}),(0,t.jsx)(et.Form.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["HTTP Methods (Optional)",(0,t.jsx)(E.Tooltip,{title:"Select specific HTTP methods. Leave empty to support all methods (GET, POST, PUT, DELETE, PATCH). Useful when the same path needs different targets for different methods.",children:(0,t.jsx)(w.InfoCircleOutlined,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:"methods",extra:(0,t.jsx)("div",{className:"text-xs text-gray-500 mt-1",children:0===v.length?"All HTTP methods supported (default)":`Only ${v.join(", ")} requests will be routed to this endpoint`}),className:"mb-4",children:(0,t.jsx)(W.Select,{mode:"multiple",placeholder:"Select methods (leave empty for all)",value:v,onChange:N,allowClear:!0,style:{width:"100%"},children:lx.map(e=>(0,t.jsx)(lh,{value:e,children:e},e))})}),(0,t.jsxs)("div",{className:"flex items-center justify-between py-3",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-gray-700",children:"Include Subpaths"}),(0,t.jsx)("div",{className:"text-xs text-gray-500 mt-0.5",children:"Forward all subpaths to the target API (recommended for REST APIs)"})]}),(0,t.jsx)(et.Form.Item,{name:"include_subpath",valuePropName:"checked",className:"mb-0",children:(0,t.jsx)(tv.Switch,{checked:j,onChange:_})})]})]})]}),(0,t.jsx)(ld,{pathValue:h,targetValue:g,includeSubpath:j}),(0,t.jsxs)(eL.Card,{className:"p-6",children:[(0,t.jsx)(eu.Title,{className:"text-lg font-semibold text-gray-900 mb-2",children:"Headers"}),(0,t.jsx)(la.Subtitle,{className:"text-gray-600 mb-6",children:"Add headers that will be sent with every request to the target API"}),(0,t.jsx)(et.Form.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Authentication Headers",(0,t.jsx)(E.Tooltip,{title:"Authentication and other headers to forward with requests",children:(0,t.jsx)(w.InfoCircleOutlined,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:"headers",rules:[{required:!0,message:"Please configure the headers"}],extra:(0,t.jsxs)("div",{className:"text-xs text-gray-500 mt-2",children:[(0,t.jsx)("div",{className:"font-medium mb-1",children:"Add authentication tokens and other required headers"}),(0,t.jsx)("div",{children:"Common examples: auth_token, Authorization, x-api-key"})]}),children:(0,t.jsx)(li,{})})]}),(0,t.jsxs)(eL.Card,{className:"p-6",children:[(0,t.jsx)(eu.Title,{className:"text-lg font-semibold text-gray-900 mb-2",children:"Default Query Parameters"}),(0,t.jsx)(la.Subtitle,{className:"text-gray-600 mb-6",children:"Add query parameters that will be automatically sent with every request to the target API"}),(0,t.jsx)(et.Form.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Default Query Parameters (Optional)",(0,t.jsx)(E.Tooltip,{title:"Query parameters that will be added to all requests. Clients can override these by providing their own values.",children:(0,t.jsx)(w.InfoCircleOutlined,{className:"ml-2 text-blue-400 hover:text-blue-600 cursor-help"})})]}),name:"default_query_params",extra:(0,t.jsxs)("div",{className:"text-xs text-gray-500 mt-2",children:[(0,t.jsx)("div",{className:"font-medium mb-1",children:"Parameters are sent with all GET, POST, PUT, PATCH requests"}),(0,t.jsx)("div",{children:"Client parameters override defaults. Examples: version=v1, format=json, key=default"})]}),children:(0,t.jsx)(lo,{})})]}),(0,t.jsx)(lc,{premiumUser:r,authEnabled:y,onAuthChange:e=>{b(e),i.setFieldsValue({auth:e})}}),(0,t.jsx)(lu,{accessToken:e,value:C,onChange:S}),(0,t.jsxs)(eL.Card,{className:"p-6",children:[(0,t.jsx)(eu.Title,{className:"text-lg font-semibold text-gray-900 mb-2",children:"Billing"}),(0,t.jsx)(la.Subtitle,{className:"text-gray-600 mb-6",children:"Optional cost tracking for this endpoint"}),(0,t.jsx)(et.Form.Item,{label:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700 flex items-center",children:["Cost Per Request (USD)",(0,t.jsx)(E.Tooltip,{title:"Optional: Track costs for requests to this endpoint",children:(0,t.jsx)(w.InfoCircleOutlined,{className:"ml-2 text-gray-400 hover:text-gray-600"})})]}),name:"cost_per_request",extra:(0,t.jsx)("div",{className:"text-xs text-gray-500 mt-2",children:"The cost charged for each request through this endpoint"}),children:(0,t.jsx)(tI.default,{min:0,step:.001,precision:4,placeholder:"2.0000",size:"large"})})]}),(0,t.jsxs)("div",{className:"flex items-center justify-end space-x-3 pt-6 border-t border-gray-100",children:[(0,t.jsx)(T.Button,{variant:"secondary",onClick:k,children:"Cancel"}),(0,t.jsx)(T.Button,{variant:"primary",loading:d,onClick:()=>{console.log("Submit button clicked"),i.submit()},children:d?"Creating...":"Add Pass-Through Endpoint"})]})]})]})})]})};var lg=e.i(286536),lf=e.i(77705);let lj=["GET","POST","PUT","DELETE","PATCH"],{Option:l_}=W.Select,ly=({value:e})=>{let[l,s]=(0,x.useState)(!1),a=JSON.stringify(e,null,2);return(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("pre",{className:"font-mono text-xs bg-gray-50 p-2 rounded max-w-md overflow-auto",children:l?a:"••••••••"}),(0,t.jsx)("button",{onClick:()=>s(!l),className:"p-1 hover:bg-gray-100 rounded",type:"button",children:l?(0,t.jsx)(lf.EyeOff,{className:"w-4 h-4 text-gray-500"}):(0,t.jsx)(lg.Eye,{className:"w-4 h-4 text-gray-500"})})]})},lb=({endpointData:e,onClose:s,accessToken:a,isAdmin:r,premiumUser:i=!1,onEndpointUpdated:o})=>{let[n,d]=(0,x.useState)(e),[c,m]=(0,x.useState)(!1),[u,h]=(0,x.useState)(!1),[p,g]=(0,x.useState)(e?.auth||!1),[f,j]=(0,x.useState)(e?.methods||[]),[_,y]=(0,x.useState)(e?.guardrails||{}),[b]=et.Form.useForm(),v=async e=>{try{if(!a||!n?.id)return;let t={};if(e.headers)try{t="string"==typeof e.headers?JSON.parse(e.headers):e.headers}catch(e){D.default.fromBackend("Invalid JSON format for headers");return}let s={path:n.path,target:e.target,headers:t,include_subpath:e.include_subpath,cost_per_request:e.cost_per_request,auth:i?e.auth:void 0,methods:f&&f.length>0?f:void 0,guardrails:_&&Object.keys(_).length>0?_:void 0};await (0,l.updatePassThroughEndpoint)(a,n.id,s),d({...n,...s}),h(!1),o&&o()}catch(e){console.error("Error updating endpoint:",e),D.default.fromBackend("Failed to update pass through endpoint")}},N=async()=>{try{if(!a||!n?.id)return;await (0,l.deletePassThroughEndpointsCall)(a,n.id),D.default.success("Pass through endpoint deleted successfully"),s(),o&&o()}catch(e){console.error("Error deleting endpoint:",e),D.default.fromBackend("Failed to delete pass through endpoint")}};return c?(0,t.jsx)("div",{className:"p-4",children:"Loading..."}):n?(0,t.jsxs)("div",{className:"p-4",children:[(0,t.jsx)("div",{className:"flex justify-between items-center mb-6",children:(0,t.jsxs)("div",{children:[(0,t.jsx)(K.Button,{onClick:s,className:"mb-4",children:"← Back"}),(0,t.jsxs)(eu.Title,{children:["Pass Through Endpoint: ",n.path]}),(0,t.jsx)(em.Text,{className:"text-gray-500 font-mono",children:n.id})]})}),(0,t.jsxs)(e4.TabGroup,{children:[(0,t.jsxs)(e5.TabList,{className:"mb-4",children:[(0,t.jsx)(e2.Tab,{children:"Overview"},"overview"),r?(0,t.jsx)(e2.Tab,{children:"Settings"},"settings"):(0,t.jsx)(t.Fragment,{})]}),(0,t.jsxs)(e6.TabPanels,{children:[(0,t.jsxs)(U.TabPanel,{children:[(0,t.jsxs)($.Grid,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,t.jsxs)(eL.Card,{children:[(0,t.jsx)(em.Text,{children:"Path"}),(0,t.jsx)("div",{className:"mt-2",children:(0,t.jsx)(eu.Title,{className:"font-mono",children:n.path})})]}),(0,t.jsxs)(eL.Card,{children:[(0,t.jsx)(em.Text,{children:"Target"}),(0,t.jsx)("div",{className:"mt-2",children:(0,t.jsx)(eu.Title,{children:n.target})})]}),(0,t.jsxs)(eL.Card,{children:[(0,t.jsx)(em.Text,{children:"Configuration"}),(0,t.jsxs)("div",{className:"mt-2 space-y-2",children:[(0,t.jsx)("div",{children:(0,t.jsx)(k.Badge,{color:n.include_subpath?"green":"gray",children:n.include_subpath?"Include Subpath":"Exact Path"})}),(0,t.jsx)("div",{children:(0,t.jsx)(k.Badge,{color:n.auth?"blue":"gray",children:n.auth?"Auth Required":"No Auth"})}),n.methods&&n.methods.length>0&&(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"text-xs text-gray-500",children:"HTTP Methods:"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-1 mt-1",children:n.methods.map(e=>(0,t.jsx)(k.Badge,{color:"indigo",size:"sm",children:e},e))})]}),(!n.methods||0===n.methods.length)&&(0,t.jsx)("div",{children:(0,t.jsx)(em.Text,{className:"text-xs text-gray-500",children:"All HTTP methods supported"})}),void 0!==n.cost_per_request&&(0,t.jsx)("div",{children:(0,t.jsxs)(em.Text,{children:["Cost per request: $",n.cost_per_request]})})]})]})]}),(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(ld,{pathValue:n.path,targetValue:n.target,includeSubpath:n.include_subpath||!1})}),n.headers&&Object.keys(n.headers).length>0&&(0,t.jsxs)(eL.Card,{className:"mt-6",children:[(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Headers"}),(0,t.jsxs)(k.Badge,{color:"blue",children:[Object.keys(n.headers).length," headers configured"]})]}),(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(ly,{value:n.headers})})]}),n.guardrails&&Object.keys(n.guardrails).length>0&&(0,t.jsxs)(eL.Card,{className:"mt-6",children:[(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Guardrails"}),(0,t.jsxs)(k.Badge,{color:"purple",children:[Object.keys(n.guardrails).length," guardrails configured"]})]}),(0,t.jsx)("div",{className:"mt-4 space-y-2",children:Object.entries(n.guardrails).map(([e,l])=>(0,t.jsxs)("div",{className:"p-3 bg-gray-50 rounded",children:[(0,t.jsx)("div",{className:"font-medium text-sm",children:e}),l&&(l.request_fields||l.response_fields)&&(0,t.jsxs)("div",{className:"mt-2 text-xs text-gray-600 space-y-1",children:[l.request_fields&&(0,t.jsxs)("div",{children:["Request fields: ",l.request_fields.join(", ")]}),l.response_fields&&(0,t.jsxs)("div",{children:["Response fields: ",l.response_fields.join(", ")]})]}),!l&&(0,t.jsx)("div",{className:"text-xs text-gray-600 mt-1",children:"Uses entire payload"})]},e))})]})]}),r&&(0,t.jsx)(U.TabPanel,{children:(0,t.jsxs)(eL.Card,{children:[(0,t.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,t.jsx)(eu.Title,{children:"Pass Through Endpoint Settings"}),(0,t.jsx)("div",{className:"space-x-2",children:!u&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(T.Button,{onClick:()=>h(!0),children:"Edit Settings"}),(0,t.jsx)(T.Button,{onClick:N,variant:"secondary",color:"red",children:"Delete Endpoint"})]})})]}),u?(0,t.jsxs)(et.Form,{form:b,onFinish:v,initialValues:{target:n.target,headers:n.headers?JSON.stringify(n.headers,null,2):"",include_subpath:n.include_subpath||!1,cost_per_request:n.cost_per_request,auth:n.auth||!1,methods:n.methods||[]},layout:"vertical",children:[(0,t.jsx)(et.Form.Item,{label:"Target URL",name:"target",rules:[{required:!0,message:"Please input a target URL"}],children:(0,t.jsx)(eR.TextInput,{placeholder:"https://api.example.com"})}),(0,t.jsx)(et.Form.Item,{label:"Headers (JSON)",name:"headers",children:(0,t.jsx)(eV.Input.TextArea,{rows:5,placeholder:'{"Authorization": "Bearer your-token", "Content-Type": "application/json"}'})}),(0,t.jsx)(et.Form.Item,{label:"HTTP Methods (Optional)",name:"methods",extra:0===f.length?"All HTTP methods supported (default)":`Only ${f.join(", ")} requests will be routed to this endpoint`,children:(0,t.jsx)(W.Select,{mode:"multiple",placeholder:"Select methods (leave empty for all)",value:f,onChange:j,allowClear:!0,style:{width:"100%"},children:lj.map(e=>(0,t.jsx)(l_,{value:e,children:e},e))})}),(0,t.jsx)(et.Form.Item,{label:"Include Subpath",name:"include_subpath",valuePropName:"checked",children:(0,t.jsx)(es.Switch,{})}),(0,t.jsx)(et.Form.Item,{label:"Cost per Request",name:"cost_per_request",children:(0,t.jsx)(eh.InputNumber,{min:0,step:.01,precision:2,placeholder:"0.00",addonBefore:"$"})}),(0,t.jsx)(lc,{premiumUser:i,authEnabled:p,onAuthChange:e=>{g(e),b.setFieldsValue({auth:e})}}),(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(lu,{accessToken:a||"",value:_,onChange:y})}),(0,t.jsxs)("div",{className:"flex justify-end gap-2 mt-6",children:[(0,t.jsx)(K.Button,{onClick:()=>h(!1),children:"Cancel"}),(0,t.jsx)(T.Button,{children:"Save Changes"})]})]}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Path"}),(0,t.jsx)("div",{className:"font-mono",children:n.path})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Target URL"}),(0,t.jsx)("div",{children:n.target})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Include Subpath"}),(0,t.jsx)(k.Badge,{color:n.include_subpath?"green":"gray",children:n.include_subpath?"Yes":"No"})]}),void 0!==n.cost_per_request&&(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Cost per Request"}),(0,t.jsxs)("div",{children:["$",n.cost_per_request]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Authentication Required"}),(0,t.jsx)(k.Badge,{color:n.auth?"green":"gray",children:n.auth?"Yes":"No"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(em.Text,{className:"font-medium",children:"Headers"}),n.headers&&Object.keys(n.headers).length>0?(0,t.jsx)("div",{className:"mt-2",children:(0,t.jsx)(ly,{value:n.headers})}):(0,t.jsx)("div",{className:"text-gray-500",children:"No headers configured"})]})]})]})})]})]})]}):(0,t.jsx)("div",{className:"p-4",children:"Pass through endpoint not found"})};var lv=e.i(149121);let lN=({value:e})=>{let[l,s]=(0,x.useState)(!1),a=JSON.stringify(e);return(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("span",{className:"font-mono text-xs",children:l?a:"••••••••"}),(0,t.jsx)("button",{onClick:()=>s(!l),className:"p-1 hover:bg-gray-100 rounded",type:"button",children:l?(0,t.jsx)(lf.EyeOff,{className:"w-4 h-4 text-gray-500"}):(0,t.jsx)(lg.Eye,{className:"w-4 h-4 text-gray-500"})})]})},lw=({accessToken:e,userRole:s,userID:a,modelData:r,premiumUser:i})=>{let[o,n]=(0,x.useState)([]),[d,c]=(0,x.useState)(null),[m,u]=(0,x.useState)(!1),[h,p]=(0,x.useState)(null);(0,x.useEffect)(()=>{e&&s&&a&&(0,l.getPassThroughEndpointsCall)(e).then(e=>{n(e.endpoints)})},[e,s,a]);let g=async e=>{p(e),u(!0)},f=async()=>{if(null!=h&&e){try{await (0,l.deletePassThroughEndpointsCall)(e,h);let t=o.filter(e=>e.id!==h);n(t),D.default.success("Endpoint deleted successfully.")}catch(e){console.error("Error deleting the endpoint:",e),D.default.fromBackend("Error deleting the endpoint: "+e)}u(!1),p(null)}},j=[{header:"ID",accessorKey:"id",cell:e=>(0,t.jsx)(E.Tooltip,{title:e.row.original.id,children:(0,t.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&&c(e.row.original.id),children:e.row.original.id})})},{header:"Path",accessorKey:"path"},{header:"Target",accessorKey:"target",cell:e=>(0,t.jsx)(em.Text,{children:e.getValue()})},{header:()=>(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,t.jsx)("span",{children:"Methods"}),(0,t.jsx)(E.Tooltip,{title:"HTTP methods supported by this endpoint",children:(0,t.jsx)(tW.InformationCircleIcon,{className:"w-4 h-4 text-gray-400 cursor-help"})})]}),accessorKey:"methods",cell:e=>{let l=e.getValue();return l&&0!==l.length?(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:l.map(e=>(0,t.jsx)(J.Badge,{color:"indigo",className:"text-xs",children:e},e))}):(0,t.jsx)(J.Badge,{color:"blue",children:"ALL"})}},{header:()=>(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,t.jsx)("span",{children:"Authentication"}),(0,t.jsx)(E.Tooltip,{title:"LiteLLM Virtual Key required to call endpoint",children:(0,t.jsx)(tW.InformationCircleIcon,{className:"w-4 h-4 text-gray-400 cursor-help"})})]}),accessorKey:"auth",cell:e=>(0,t.jsx)(J.Badge,{color:e.getValue()?"green":"gray",children:e.getValue()?"Yes":"No"})},{header:"Headers",accessorKey:"headers",cell:e=>(0,t.jsx)(lN,{value:e.getValue()||{}})},{header:"Actions",id:"actions",cell:({row:e})=>(0,t.jsxs)("div",{className:"flex space-x-1",children:[(0,t.jsx)(F.Icon,{icon:eE.PencilAltIcon,size:"sm",onClick:()=>e.original.id&&c(e.original.id),title:"Edit"}),(0,t.jsx)(F.Icon,{icon:S.TrashIcon,size:"sm",onClick:()=>{var t;return t=e.original.id,e.index,void g(t)},title:"Delete"})]})}];if(!e)return null;if(d){console.log("selectedEndpointId",d),console.log("generalSettings",o);let a=o.find(e=>e.id===d);return a?(0,t.jsx)(lb,{endpointData:a,onClose:()=>c(null),accessToken:e,isAdmin:"Admin"===s||"admin"===s,premiumUser:i,onEndpointUpdated:()=>{e&&(0,l.getPassThroughEndpointsCall)(e).then(e=>{n(e.endpoints)})}}):(0,t.jsx)("div",{children:"Endpoint not found"})}return(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(eu.Title,{children:"Pass Through Endpoints"}),(0,t.jsx)(em.Text,{className:"text-tremor-content",children:"Configure and manage your pass-through endpoints"})]}),(0,t.jsx)(lp,{accessToken:e,setPassThroughItems:n,passThroughItems:o,premiumUser:i}),(0,t.jsx)(lv.DataTable,{data:o,columns:j,renderSubComponent:()=>(0,t.jsx)("div",{}),getRowCanExpand:()=>!1,isLoading:!1,noDataMessage:"No pass-through endpoints configured"}),m&&(0,t.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,t.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,t.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,t.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,t.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,t.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,t.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,t.jsx)("div",{className:"sm:flex sm:items-start",children:(0,t.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,t.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Pass-Through Endpoint"}),(0,t.jsx)("div",{className:"mt-2",children:(0,t.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,t.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,t.jsx)(T.Button,{onClick:f,color:"red",className:"ml-2",children:"Delete"}),(0,t.jsx)(T.Button,{onClick:()=>{u(!1),p(null)},children:"Cancel"})]})]})]})})]})};e.s(["default",0,lw],147612);var lC=e.i(56567);e.s(["default",0,({premiumUser:e,teams:s})=>{let{accessToken:a,token:i,userRole:m,userId:u}=(0,r.default)(),[h]=et.Form.useForm(),[p,g]=(0,x.useState)(""),[f,j]=(0,x.useState)([]),[_,y]=(0,x.useState)(eM.Providers.Anthropic),[b,v]=(0,x.useState)(null),[N,w]=(0,x.useState)(null),[C,S]=(0,x.useState)(null),[k,T]=(0,x.useState)(0),[I,M]=(0,x.useState)({}),[P,A]=(0,x.useState)(!1),[E,R]=(0,x.useState)(null),[O,B]=(0,x.useState)(null),[z,V]=(0,x.useState)(0),[H,J]=(0,x.useState)(()=>"true"!==localStorage.getItem("hideMissingProviderBanner")),K=(0,G.useQueryClient)(),{data:W,isLoading:Q,refetch:Y}=(0,d.useModelsInfo)(),{data:X,isLoading:Z}=(0,n.useModelCostMap)(),{data:ee,isLoading:el}=o(),es=ee?.credentials||[],{data:ea,isLoading:er}=(0,c.useUISettings)(),eo=(0,x.useMemo)(()=>{if(!W?.data)return[];let e=new Set;for(let t of W.data)e.add(t.model_name);return Array.from(e).sort()},[W?.data]),ed=(0,x.useMemo)(()=>{if(!W?.data)return[];let e=new Set;for(let t of W.data){let l=t.model_info;if(l?.access_groups)for(let t of l.access_groups)e.add(t)}return Array.from(e)},[W?.data]),ec=(0,x.useMemo)(()=>W?.data?W.data.map(e=>e.model_name):[],[W?.data]),em=(0,x.useMemo)(()=>W?.data?W.data.map(e=>e.model_info?.id).filter(e=>!!e):[],[W?.data]),eu=e=>null!=X&&"object"==typeof X&&e in X?X[e].litellm_provider:"openai",eh=(0,x.useMemo)(()=>W?.data?ei(W,eu):{data:[]},[W?.data,eu]),ex=m&&(0,eZ.isProxyAdminRole)(m),eg=m&&eZ.internalUserRoles.includes(m),ef=u&&(0,eZ.isUserTeamAdminForAnyTeam)(s,u),ej=eg&&ea?.values?.disable_model_add_for_internal_users===!0,e_=!ex&&(ej||!ef),ey={name:"file",accept:".json",pastable:!1,beforeUpload:e=>{if("application/json"===e.type){let t=new FileReader;t.onload=e=>{if(e.target){let t=e.target.result;h.setFieldsValue({vertex_credentials:t})}},t.readAsText(e)}return!1},onChange(e){"done"===e.file.status?D.default.success(`${e.file.name} file uploaded successfully`):"error"===e.file.status&&D.default.fromBackend(`${e.file.name} file upload failed.`)}},eb=()=>{g(new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})),K.invalidateQueries({queryKey:["models","list"]}),Y()},ev=async()=>{if(a)try{let e={router_settings:{}};"global"===b?(C&&(e.router_settings.retry_policy=C),D.default.success("Global retry settings saved successfully")):(N&&(e.router_settings.model_group_retry_policy=N),D.default.success(`Retry settings saved successfully for ${b}`)),await (0,l.setCallbacksCall)(a,e)}catch(e){D.default.fromBackend("Failed to save retry settings")}};if((0,x.useEffect)(()=>{if(!a||!i||!m||!u||!W)return;let e=async()=>{try{let e=(await (0,l.getCallbacksCall)(a,u,m)).router_settings,t=e.model_group_retry_policy,s=e.num_retries;w(t),S(e.retry_policy),T(s);let r=e.model_group_alias||{};M(r)}catch(e){console.error("Error fetching model data:",e)}};a&&i&&m&&u&&W&&e()},[a,i,m,u,W]),m&&"Admin Viewer"==m){let{Title:e,Paragraph:l}=L.Typography;return(0,t.jsxs)("div",{children:[(0,t.jsx)(e,{level:1,children:"Access Denied"}),(0,t.jsx)(l,{children:"Ask your proxy admin for access to view all models"})]})}let eN=async()=>{try{let e=await h.validateFields();await eA(e,a,h,eb)}catch(t){let e=t.errorFields?.map(e=>`${e.name.join(".")}: ${e.errors.join(", ")}`).join(" | ")||"Unknown validation error";D.default.fromBackend(`Please fill in the following required fields: ${e}`)}};return(Object.keys(eM.Providers).find(e=>eM.Providers[e]===_),O)?(0,t.jsx)("div",{className:"w-full h-full",children:(0,t.jsx)(lC.default,{teamId:O,onClose:()=>B(null),accessToken:a,is_team_admin:"Admin"===m,is_proxy_admin:"Proxy Admin"===m,userModels:ec,editTeam:!1,onUpdate:eb,premiumUser:e})}):(0,t.jsx)("div",{className:"w-full mx-4 h-[75vh]",children:(0,t.jsx)($.Grid,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:(0,t.jsxs)(e1.Col,{numColSpan:1,className:"flex flex-col gap-2",children:[(0,t.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-semibold",children:"Model Management"}),eZ.all_admin_roles.includes(m)?(0,t.jsx)("p",{className:"text-sm text-gray-600",children:"Add and manage models for the proxy"}):(0,t.jsx)("p",{className:"text-sm text-gray-600",children:"Add models for teams you are an admin for."})]}),!H&&(0,t.jsxs)("a",{href:"https://models.litellm.ai/?request=true",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-[#6366f1] hover:text-[#5558e3] border border-[#6366f1] hover:border-[#5558e3] rounded-lg transition-colors",children:[(0,t.jsx)(e3.PlusCircleOutlined,{style:{fontSize:"12px"}}),"Request Provider"]})]}),H&&(0,t.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,t.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,t.jsx)(e3.PlusCircleOutlined,{style:{fontSize:"18px",color:"#6366f1"}})}),(0,t.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,t.jsx)("h4",{className:"text-gray-900 font-semibold text-sm m-0",children:"Missing a provider?"}),(0,t.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,t.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,t.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,t.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"})})]}),(0,t.jsx)("button",{onClick:()=>{J(!1),localStorage.setItem("hideMissingProviderBanner","true")},className:"flex-shrink-0 p-1 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-full transition-colors","aria-label":"Dismiss banner",children:(0,t.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:(0,t.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})})]}),E&&!(Q||Z||el||er)?(0,t.jsx)(ls,{modelId:E,onClose:()=>{R(null)},accessToken:a,userID:u,userRole:m,onModelUpdate:e=>{K.invalidateQueries({queryKey:["models","list"]}),eb()},modelAccessGroups:ed}):(0,t.jsxs)(e4.TabGroup,{index:z,onIndexChange:V,className:"gap-2 h-[75vh] w-full ",children:[(0,t.jsxs)(e5.TabList,{className:"flex justify-between mt-2 w-full items-center",children:[(0,t.jsxs)("div",{className:"flex",children:[eZ.all_admin_roles.includes(m)?(0,t.jsx)(e2.Tab,{children:"All Models"}):(0,t.jsx)(e2.Tab,{children:"Your Models"}),!e_&&(0,t.jsx)(e2.Tab,{children:"Add Model"}),eZ.all_admin_roles.includes(m)&&(0,t.jsx)(e2.Tab,{children:"LLM Credentials"}),eZ.all_admin_roles.includes(m)&&(0,t.jsx)(e2.Tab,{children:"Pass-Through Endpoints"}),eZ.all_admin_roles.includes(m)&&(0,t.jsx)(e2.Tab,{children:"Health Status"}),eZ.all_admin_roles.includes(m)&&(0,t.jsx)(e2.Tab,{children:"Model Retry Settings"}),eZ.all_admin_roles.includes(m)&&(0,t.jsx)(e2.Tab,{children:"Model Group Alias"}),eZ.all_admin_roles.includes(m)&&(0,t.jsx)(e2.Tab,{children:"Price Data Reload"})]}),(0,t.jsxs)("div",{className:"flex items-center space-x-2 self-center",children:[p&&(0,t.jsxs)("span",{className:"text-xs text-gray-500",children:["Last Refreshed: ",p]}),(0,t.jsx)(F.Icon,{icon:e0.RefreshIcon,variant:"shadow",size:"xs",className:"cursor-pointer",onClick:eb})]})]}),(0,t.jsxs)(e6.TabPanels,{children:[(0,t.jsx)(en,{selectedModelGroup:b,setSelectedModelGroup:v,availableModelGroups:eo,availableModelAccessGroups:ed,setSelectedModelId:R,setSelectedTeamId:B}),!e_&&(0,t.jsx)(U.TabPanel,{className:"h-full",children:(0,t.jsx)(tU,{form:h,handleOk:eN,selectedProvider:_,setSelectedProvider:y,providerModels:f,setProviderModelsFn:e=>{j((0,eM.getProviderModels)(e,X))},getPlaceholder:eM.getPlaceholder,uploadProps:ey,showAdvancedSettings:P,setShowAdvancedSettings:A,teams:s,credentials:es,accessToken:a,userRole:m})}),(0,t.jsx)(U.TabPanel,{children:(0,t.jsx)(eX,{uploadProps:ey})}),(0,t.jsx)(U.TabPanel,{children:(0,t.jsx)(lw,{accessToken:a,userRole:m,userID:u,modelData:eh,premiumUser:e})}),(0,t.jsx)(U.TabPanel,{children:(0,t.jsx)(tX,{accessToken:a,modelData:eh,all_models_on_proxy:em,getDisplayModelName:q,setSelectedModelId:R,teams:s})}),(0,t.jsx)(ep,{selectedModelGroup:b,setSelectedModelGroup:v,availableModelGroups:eo,globalRetryPolicy:C,setGlobalRetryPolicy:S,defaultRetry:k,modelGroupRetryPolicy:N,setModelGroupRetryPolicy:w,handleSaveRetrySettings:ev}),(0,t.jsx)(U.TabPanel,{children:(0,t.jsx)(t4,{accessToken:a,initialModelGroupAlias:I,onAliasUpdate:M})}),(0,t.jsx)(eI,{})]})]})]})})})}],161059)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/39768ec0eebd2554.js b/litellm/proxy/_experimental/out/_next/static/chunks/39768ec0eebd2554.js new file mode 100644 index 00000000000..d95f5a3ef89 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/39768ec0eebd2554.js @@ -0,0 +1 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,728889,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(829087),i=e.i(480731),l=e.i(444755),n=e.i(673706),o=e.i(95779);let s={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"}},d={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"}},c={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:""}},u=(0,n.makeClassName)("Icon"),m=r.default.forwardRef((e,m)=>{let{icon:g,variant:p="simple",tooltip:f,size:h=i.Sizes.SM,color:v,className:b}=e,y=(0,t.__rest)(e,["icon","variant","tooltip","size","color","className"]),$=((e,t)=>{switch(e){case"simple":return{textColor:t?(0,n.getColorClassNames)(t,o.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",bgColor:"",borderColor:"",ringColor:""};case"light":return{textColor:t?(0,n.getColorClassNames)(t,o.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",bgColor:t?(0,l.tremorTwMerge)((0,n.getColorClassNames)(t,o.colorPalette.background).bgColor,"bg-opacity-20"):"bg-tremor-brand-muted dark:bg-dark-tremor-brand-muted",borderColor:"",ringColor:""};case"shadow":return{textColor:t?(0,n.getColorClassNames)(t,o.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",bgColor:t?(0,l.tremorTwMerge)((0,n.getColorClassNames)(t,o.colorPalette.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:t?(0,n.getColorClassNames)(t,o.colorPalette.text).textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",bgColor:t?(0,l.tremorTwMerge)((0,n.getColorClassNames)(t,o.colorPalette.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:t?(0,n.getColorClassNames)(t,o.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",bgColor:t?(0,l.tremorTwMerge)((0,n.getColorClassNames)(t,o.colorPalette.background).bgColor,"bg-opacity-20"):"bg-tremor-background dark:bg-dark-tremor-background",borderColor:t?(0,n.getColorClassNames)(t,o.colorPalette.ring).borderColor:"border-tremor-brand-subtle dark:border-dark-tremor-brand-subtle",ringColor:t?(0,l.tremorTwMerge)((0,n.getColorClassNames)(t,o.colorPalette.ring).ringColor,"ring-opacity-40"):"ring-tremor-brand-muted dark:ring-dark-tremor-brand-muted"}}})(p,v),{tooltipProps:x,getReferenceProps:k}=(0,a.useTooltip)();return r.default.createElement("span",Object.assign({ref:(0,n.mergeRefs)([m,x.refs.setReference]),className:(0,l.tremorTwMerge)(u("root"),"inline-flex shrink-0 items-center justify-center",$.bgColor,$.textColor,$.borderColor,$.ringColor,c[p].rounded,c[p].border,c[p].shadow,c[p].ring,s[h].paddingX,s[h].paddingY,b)},k,y),r.default.createElement(a.default,Object.assign({text:f},x)),r.default.createElement(g,{className:(0,l.tremorTwMerge)(u("icon"),"shrink-0",d[h].height,d[h].width)}))});m.displayName="Icon",e.s(["default",()=>m],728889)},752978,e=>{"use strict";var t=e.i(728889);e.s(["Icon",()=>t.default])},94629,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4"}))});e.s(["SwitchVerticalIcon",0,r],94629)},637235,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let 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 372z"}},{tag:"path",attrs:{d:"M686.7 638.6L544.1 535.5V288c0-4.4-3.6-8-8-8H488c-4.4 0-8 3.6-8 8v275.4c0 2.6 1.2 5 3.3 6.5l165.4 120.6c3.6 2.6 8.6 1.8 11.2-1.7l28.6-39c2.6-3.7 1.8-8.7-1.8-11.2z"}}]},name:"clock-circle",theme:"outlined"};var i=e.i(9583),l=r.forwardRef(function(e,l){return r.createElement(i.default,(0,t.default)({},e,{ref:l,icon:a}))});e.s(["ClockCircleOutlined",0,l],637235)},646563,e=>{"use strict";var t=e.i(959013);e.s(["PlusOutlined",()=>t.default])},447566,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M872 474H286.9l350.2-304c5.6-4.9 2.2-14-5.2-14h-88.5c-3.9 0-7.6 1.4-10.5 3.9L155 487.8a31.96 31.96 0 000 48.3L535.1 866c1.5 1.3 3.3 2 5.2 2h91.5c7.4 0 10.8-9.2 5.2-14L286.9 550H872c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8z"}}]},name:"arrow-left",theme:"outlined"};var i=e.i(9583),l=r.forwardRef(function(e,l){return r.createElement(i.default,(0,t.default)({},e,{ref:l,icon:a}))});e.s(["ArrowLeftOutlined",0,l],447566)},409797,e=>{"use strict";var t=e.i(631171);e.s(["ChevronDownIcon",()=>t.default])},361653,e=>{"use strict";let t=(0,e.i(475254).default)("circle-alert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);e.s(["default",()=>t])},603908,e=>{"use strict";let t=(0,e.i(475254).default)("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);e.s(["default",()=>t])},841947,e=>{"use strict";let t=(0,e.i(475254).default)("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);e.s(["default",()=>t])},244451,e=>{"use strict";let t;e.i(247167);var r=e.i(271645),a=e.i(343794),i=e.i(242064),l=e.i(763731),n=e.i(174428);let o=80*Math.PI,s=e=>{let{dotClassName:t,style:i,hasCircleCls:l}=e;return r.createElement("circle",{className:(0,a.default)(`${t}-circle`,{[`${t}-circle-bg`]:l}),r:40,cx:50,cy:50,strokeWidth:20,style:i})},d=({percent:e,prefixCls:t})=>{let i=`${t}-dot`,l=`${i}-holder`,d=`${l}-hidden`,[c,u]=r.useState(!1);(0,n.default)(()=>{0!==e&&u(!0)},[0!==e]);let m=Math.max(Math.min(e,100),0);if(!c)return null;let g={strokeDashoffset:`${o/4}`,strokeDasharray:`${o*m/100} ${o*(100-m)/100}`};return r.createElement("span",{className:(0,a.default)(l,`${i}-progress`,m<=0&&d)},r.createElement("svg",{viewBox:"0 0 100 100",role:"progressbar","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":m},r.createElement(s,{dotClassName:i,hasCircleCls:!0}),r.createElement(s,{dotClassName:i,style:g})))};function c(e){let{prefixCls:t,percent:i=0}=e,l=`${t}-dot`,n=`${l}-holder`,o=`${n}-hidden`;return r.createElement(r.Fragment,null,r.createElement("span",{className:(0,a.default)(n,i>0&&o)},r.createElement("span",{className:(0,a.default)(l,`${t}-dot-spin`)},[1,2,3,4].map(e=>r.createElement("i",{className:`${t}-dot-item`,key:e})))),r.createElement(d,{prefixCls:t,percent:i}))}function u(e){var t;let{prefixCls:i,indicator:n,percent:o}=e,s=`${i}-dot`;return n&&r.isValidElement(n)?(0,l.cloneElement)(n,{className:(0,a.default)(null==(t=n.props)?void 0:t.className,s),percent:o}):r.createElement(c,{prefixCls:i,percent:o})}e.i(296059);var m=e.i(694758),g=e.i(183293),p=e.i(246422),f=e.i(838378);let h=new m.Keyframes("antSpinMove",{to:{opacity:1}}),v=new m.Keyframes("antRotate",{to:{transform:"rotate(405deg)"}}),b=(0,p.genStyleHooks)("Spin",e=>(e=>{let{componentCls:t,calc:r}=e;return{[t]:Object.assign(Object.assign({},(0,g.resetComponent)(e)),{position:"absolute",display:"none",color:e.colorPrimary,fontSize:0,textAlign:"center",verticalAlign:"middle",opacity:0,transition:`transform ${e.motionDurationSlow} ${e.motionEaseInOutCirc}`,"&-spinning":{position:"relative",display:"inline-block",opacity:1},[`${t}-text`]:{fontSize:e.fontSize,paddingTop:r(r(e.dotSize).sub(e.fontSize)).div(2).add(2).equal()},"&-fullscreen":{position:"fixed",width:"100vw",height:"100vh",backgroundColor:e.colorBgMask,zIndex:e.zIndexPopupBase,inset:0,display:"flex",alignItems:"center",flexDirection:"column",justifyContent:"center",opacity:0,visibility:"hidden",transition:`all ${e.motionDurationMid}`,"&-show":{opacity:1,visibility:"visible"},[t]:{[`${t}-dot-holder`]:{color:e.colorWhite},[`${t}-text`]:{color:e.colorTextLightSolid}}},"&-nested-loading":{position:"relative",[`> div > ${t}`]:{position:"absolute",top:0,insetInlineStart:0,zIndex:4,display:"block",width:"100%",height:"100%",maxHeight:e.contentHeight,[`${t}-dot`]:{position:"absolute",top:"50%",insetInlineStart:"50%",margin:r(e.dotSize).mul(-1).div(2).equal()},[`${t}-text`]:{position:"absolute",top:"50%",width:"100%",textShadow:`0 1px 2px ${e.colorBgContainer}`},[`&${t}-show-text ${t}-dot`]:{marginTop:r(e.dotSize).div(2).mul(-1).sub(10).equal()},"&-sm":{[`${t}-dot`]:{margin:r(e.dotSizeSM).mul(-1).div(2).equal()},[`${t}-text`]:{paddingTop:r(r(e.dotSizeSM).sub(e.fontSize)).div(2).add(2).equal()},[`&${t}-show-text ${t}-dot`]:{marginTop:r(e.dotSizeSM).div(2).mul(-1).sub(10).equal()}},"&-lg":{[`${t}-dot`]:{margin:r(e.dotSizeLG).mul(-1).div(2).equal()},[`${t}-text`]:{paddingTop:r(r(e.dotSizeLG).sub(e.fontSize)).div(2).add(2).equal()},[`&${t}-show-text ${t}-dot`]:{marginTop:r(e.dotSizeLG).div(2).mul(-1).sub(10).equal()}}},[`${t}-container`]:{position:"relative",transition:`opacity ${e.motionDurationSlow}`,"&::after":{position:"absolute",top:0,insetInlineEnd:0,bottom:0,insetInlineStart:0,zIndex:10,width:"100%",height:"100%",background:e.colorBgContainer,opacity:0,transition:`all ${e.motionDurationSlow}`,content:'""',pointerEvents:"none"}},[`${t}-blur`]:{clear:"both",opacity:.5,userSelect:"none",pointerEvents:"none","&::after":{opacity:.4,pointerEvents:"auto"}}},"&-tip":{color:e.spinDotDefault},[`${t}-dot-holder`]:{width:"1em",height:"1em",fontSize:e.dotSize,display:"inline-block",transition:`transform ${e.motionDurationSlow} ease, opacity ${e.motionDurationSlow} ease`,transformOrigin:"50% 50%",lineHeight:1,color:e.colorPrimary,"&-hidden":{transform:"scale(0.3)",opacity:0}},[`${t}-dot-progress`]:{position:"absolute",inset:0},[`${t}-dot`]:{position:"relative",display:"inline-block",fontSize:e.dotSize,width:"1em",height:"1em","&-item":{position:"absolute",display:"block",width:r(e.dotSize).sub(r(e.marginXXS).div(2)).div(2).equal(),height:r(e.dotSize).sub(r(e.marginXXS).div(2)).div(2).equal(),background:"currentColor",borderRadius:"100%",transform:"scale(0.75)",transformOrigin:"50% 50%",opacity:.3,animationName:h,animationDuration:"1s",animationIterationCount:"infinite",animationTimingFunction:"linear",animationDirection:"alternate","&:nth-child(1)":{top:0,insetInlineStart:0,animationDelay:"0s"},"&:nth-child(2)":{top:0,insetInlineEnd:0,animationDelay:"0.4s"},"&:nth-child(3)":{insetInlineEnd:0,bottom:0,animationDelay:"0.8s"},"&:nth-child(4)":{bottom:0,insetInlineStart:0,animationDelay:"1.2s"}},"&-spin":{transform:"rotate(45deg)",animationName:v,animationDuration:"1.2s",animationIterationCount:"infinite",animationTimingFunction:"linear"},"&-circle":{strokeLinecap:"round",transition:["stroke-dashoffset","stroke-dasharray","stroke","stroke-width","opacity"].map(t=>`${t} ${e.motionDurationSlow} ease`).join(","),fillOpacity:0,stroke:"currentcolor"},"&-circle-bg":{stroke:e.colorFillSecondary}},[`&-sm ${t}-dot`]:{"&, &-holder":{fontSize:e.dotSizeSM}},[`&-sm ${t}-dot-holder`]:{i:{width:r(r(e.dotSizeSM).sub(r(e.marginXXS).div(2))).div(2).equal(),height:r(r(e.dotSizeSM).sub(r(e.marginXXS).div(2))).div(2).equal()}},[`&-lg ${t}-dot`]:{"&, &-holder":{fontSize:e.dotSizeLG}},[`&-lg ${t}-dot-holder`]:{i:{width:r(r(e.dotSizeLG).sub(e.marginXXS)).div(2).equal(),height:r(r(e.dotSizeLG).sub(e.marginXXS)).div(2).equal()}},[`&${t}-show-text ${t}-text`]:{display:"block"}})}})((0,f.mergeToken)(e,{spinDotDefault:e.colorTextDescription})),e=>{let{controlHeightLG:t,controlHeight:r}=e;return{contentHeight:400,dotSize:t/2,dotSizeSM:.35*t,dotSizeLG:r}}),y=[[30,.05],[70,.03],[96,.01]];var $=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,a=Object.getOwnPropertySymbols(e);it.indexOf(a[i])&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(r[a[i]]=e[a[i]]);return r};let x=e=>{var l;let{prefixCls:n,spinning:o=!0,delay:s=0,className:d,rootClassName:c,size:m="default",tip:g,wrapperClassName:p,style:f,children:h,fullscreen:v=!1,indicator:x,percent:k}=e,C=$(e,["prefixCls","spinning","delay","className","rootClassName","size","tip","wrapperClassName","style","children","fullscreen","indicator","percent"]),{getPrefixCls:S,direction:w,className:E,style:z,indicator:N}=(0,i.useComponentConfig)("spin"),M=S("spin",n),[O,I,j]=b(M),[L,T]=r.useState(()=>o&&(!o||!s||!!Number.isNaN(Number(s)))),D=function(e,t){let[a,i]=r.useState(0),l=r.useRef(null),n="auto"===t;return r.useEffect(()=>(n&&e&&(i(0),l.current=setInterval(()=>{i(e=>{let t=100-e;for(let r=0;r{l.current&&(clearInterval(l.current),l.current=null)}),[n,e]),n?a:t}(L,k);r.useEffect(()=>{if(o){let e=function(e,t,r){var a,i=r||{},l=i.noTrailing,n=void 0!==l&&l,o=i.noLeading,s=void 0!==o&&o,d=i.debounceMode,c=void 0===d?void 0:d,u=!1,m=0;function g(){a&&clearTimeout(a)}function p(){for(var r=arguments.length,i=Array(r),l=0;le?s?(m=Date.now(),n||(a=setTimeout(c?f:p,e))):p():!0!==n&&(a=setTimeout(c?f:p,void 0===c?e-d:e)))}return p.cancel=function(e){var t=(e||{}).upcomingOnly;g(),u=!(void 0!==t&&t)},p}(s,()=>{T(!0)},{debounceMode:false});return e(),()=>{var t;null==(t=null==e?void 0:e.cancel)||t.call(e)}}T(!1)},[s,o]);let B=r.useMemo(()=>void 0!==h&&!v,[h,v]),H=(0,a.default)(M,E,{[`${M}-sm`]:"small"===m,[`${M}-lg`]:"large"===m,[`${M}-spinning`]:L,[`${M}-show-text`]:!!g,[`${M}-rtl`]:"rtl"===w},d,!v&&c,I,j),P=(0,a.default)(`${M}-container`,{[`${M}-blur`]:L}),R=null!=(l=null!=x?x:N)?l:t,V=Object.assign(Object.assign({},z),f),X=r.createElement("div",Object.assign({},C,{style:V,className:H,"aria-live":"polite","aria-busy":L}),r.createElement(u,{prefixCls:M,indicator:R,percent:D}),g&&(B||v)?r.createElement("div",{className:`${M}-text`},g):null);return O(B?r.createElement("div",Object.assign({},C,{className:(0,a.default)(`${M}-nested-loading`,p,I,j)}),L&&r.createElement("div",{key:"loading"},X),r.createElement("div",{className:P,key:"container"},h)):v?r.createElement("div",{className:(0,a.default)(`${M}-fullscreen`,{[`${M}-fullscreen-show`]:L},c,I,j)},X):X)};x.setDefaultIndicator=e=>{t=e},e.s(["default",0,x],244451)},482725,e=>{"use strict";var t=e.i(244451);e.s(["Spin",()=>t.default])},350967,46757,e=>{"use strict";var t=e.i(290571),r=e.i(444755),a=e.i(673706),i=e.i(271645);let l={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"},n={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"},o={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"},s={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"},d={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"},c={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"},u={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"},m={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"};e.s(["colSpan",()=>d,"colSpanLg",()=>m,"colSpanMd",()=>u,"colSpanSm",()=>c,"gridCols",()=>l,"gridColsLg",()=>s,"gridColsMd",()=>o,"gridColsSm",()=>n],46757);let g=(0,a.makeClassName)("Grid"),p=(e,t)=>e&&Object.keys(t).includes(String(e))?t[e]:"",f=i.default.forwardRef((e,a)=>{let{numItems:d=1,numItemsSm:c,numItemsMd:u,numItemsLg:m,children:f,className:h}=e,v=(0,t.__rest)(e,["numItems","numItemsSm","numItemsMd","numItemsLg","children","className"]),b=p(d,l),y=p(c,n),$=p(u,o),x=p(m,s),k=(0,r.tremorTwMerge)(b,y,$,x);return i.default.createElement("div",Object.assign({ref:a,className:(0,r.tremorTwMerge)(g("root"),"grid",k,h)},v),f)});f.displayName="Grid",e.s(["Grid",()=>f],350967)},530212,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10 19l-7-7m0 0l7-7m-7 7h18"}))});e.s(["ArrowLeftIcon",0,r],530212)},500330,e=>{"use strict";var t=e.i(727749);function r(e,t){let r=structuredClone(e);for(let[e,a]of Object.entries(t))e in r&&(r[e]=a);return r}let a=(e,t=0,r=!1,a=!0)=>{if(null==e||!Number.isFinite(e)||0===e&&!a)return"-";let i={minimumFractionDigits:t,maximumFractionDigits:t};if(!r)return e.toLocaleString("en-US",i);let l=e<0?"-":"",n=Math.abs(e),o=n,s="";return n>=1e6?(o=n/1e6,s="M"):n>=1e3&&(o=n/1e3,s="K"),`${l}${o.toLocaleString("en-US",i)}${s}`},i=async(e,r="Copied to clipboard")=>{if(!e)return!1;if(!navigator||!navigator.clipboard||!navigator.clipboard.writeText)return l(e,r);try{return await navigator.clipboard.writeText(e),t.default.success(r),!0}catch(t){return console.error("Clipboard API failed: ",t),l(e,r)}},l=(e,r)=>{try{let a=document.createElement("textarea");a.value=e,a.style.position="fixed",a.style.left="-999999px",a.style.top="-999999px",a.setAttribute("readonly",""),document.body.appendChild(a),a.focus(),a.select();let i=document.execCommand("copy");if(document.body.removeChild(a),i)return t.default.success(r),!0;throw Error("execCommand failed")}catch(e){return t.default.fromBackend("Failed to copy to clipboard"),console.error("Failed to copy: ",e),!1}};e.s(["copyToClipboard",0,i,"formatNumberWithCommas",0,a,"getSpendString",0,(e,t=6)=>{if(null==e||!Number.isFinite(e)||0===e)return"-";let r=a(e,t,!1,!1);if(0===Number(r.replace(/,/g,""))){let e=(1/10**t).toFixed(t);return`< $${e}`}return`$${r}`},"updateExistingKeys",()=>r])},519756,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={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"};var i=e.i(9583),l=r.forwardRef(function(e,l){return r.createElement(i.default,(0,t.default)({},e,{ref:l,icon:a}))});e.s(["UploadOutlined",0,l],519756)},435451,620250,e=>{"use strict";var t=e.i(843476),r=e.i(290571),a=e.i(271645);let i=e=>{var t=(0,r.__rest)(e,[]);return a.default.createElement("svg",Object.assign({},t,{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:"2.5"}),a.default.createElement("path",{d:"M12 4v16m8-8H4"}))},l=e=>{var t=(0,r.__rest)(e,[]);return a.default.createElement("svg",Object.assign({},t,{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:"2.5"}),a.default.createElement("path",{d:"M20 12H4"}))};var n=e.i(444755),o=e.i(673706),s=e.i(677955);let d="flex mx-auto text-tremor-content-subtle dark:text-dark-tremor-content-subtle",c="cursor-pointer hover:text-tremor-content dark:hover:text-dark-tremor-content",u=a.default.forwardRef((e,t)=>{let{onSubmit:u,enableStepper:m=!0,disabled:g,onValueChange:p,onChange:f}=e,h=(0,r.__rest)(e,["onSubmit","enableStepper","disabled","onValueChange","onChange"]),v=(0,a.useRef)(null),[b,y]=a.default.useState(!1),$=a.default.useCallback(()=>{y(!0)},[]),x=a.default.useCallback(()=>{y(!1)},[]),[k,C]=a.default.useState(!1),S=a.default.useCallback(()=>{C(!0)},[]),w=a.default.useCallback(()=>{C(!1)},[]);return a.default.createElement(s.default,Object.assign({type:"number",ref:(0,o.mergeRefs)([v,t]),disabled:g,makeInputClassName:(0,o.makeClassName)("NumberInput"),onKeyDown:e=>{var t;if("Enter"===e.key&&!e.ctrlKey&&!e.altKey&&!e.shiftKey){let e=null==(t=v.current)?void 0:t.value;null==u||u(parseFloat(null!=e?e:""))}"ArrowDown"===e.key&&$(),"ArrowUp"===e.key&&S()},onKeyUp:e=>{"ArrowDown"===e.key&&x(),"ArrowUp"===e.key&&w()},onChange:e=>{g||(null==p||p(parseFloat(e.target.value)),null==f||f(e))},stepper:m?a.default.createElement("div",{className:(0,n.tremorTwMerge)("flex justify-center align-middle")},a.default.createElement("div",{tabIndex:-1,onClick:e=>e.preventDefault(),onMouseDown:e=>e.preventDefault(),onTouchStart:e=>{e.cancelable&&e.preventDefault()},onMouseUp:()=>{var e,t;g||(null==(e=v.current)||e.stepDown(),null==(t=v.current)||t.dispatchEvent(new Event("input",{bubbles:!0})))},className:(0,n.tremorTwMerge)(!g&&c,d,"group py-[10px] px-2.5 border-l border-tremor-border dark:border-dark-tremor-border")},a.default.createElement(l,{"data-testid":"step-down",className:(b?"scale-95":"")+" h-4 w-4 duration-75 transition group-active:scale-95"})),a.default.createElement("div",{tabIndex:-1,onClick:e=>e.preventDefault(),onMouseDown:e=>e.preventDefault(),onTouchStart:e=>{e.cancelable&&e.preventDefault()},onMouseUp:()=>{var e,t;g||(null==(e=v.current)||e.stepUp(),null==(t=v.current)||t.dispatchEvent(new Event("input",{bubbles:!0})))},className:(0,n.tremorTwMerge)(!g&&c,d,"group py-[10px] px-2.5 border-l border-tremor-border dark:border-dark-tremor-border")},a.default.createElement(i,{"data-testid":"step-up",className:(k?"scale-95":"")+" h-4 w-4 duration-75 transition group-active:scale-95"}))):null},h))});u.displayName="NumberInput",e.s(["NumberInput",()=>u],620250),e.s(["default",0,({step:e=.01,style:r={width:"100%"},placeholder:a="Enter a numerical value",min:i,max:l,onChange:n,...o})=>(0,t.jsx)(u,{onWheel:e=>e.currentTarget.blur(),step:e,style:r,placeholder:a,min:i,max:l,onChange:n,...o})],435451)},21548,e=>{"use strict";var t=e.i(616303);e.s(["Empty",()=>t.default])},928685,e=>{"use strict";var t=e.i(38953);e.s(["SearchOutlined",()=>t.default])},879664,e=>{"use strict";let t=(0,e.i(475254).default)("info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]);e.s(["default",()=>t])},872934,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{"fill-rule":"evenodd",viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M880 912H144c-17.7 0-32-14.3-32-32V144c0-17.7 14.3-32 32-32h360c4.4 0 8 3.6 8 8v56c0 4.4-3.6 8-8 8H184v656h656V520c0-4.4 3.6-8 8-8h56c4.4 0 8 3.6 8 8v360c0 17.7-14.3 32-32 32zM770.87 199.13l-52.2-52.2a8.01 8.01 0 014.7-13.6l179.4-21c5.1-.6 9.5 3.7 8.9 8.9l-21 179.4c-.8 6.6-8.9 9.4-13.6 4.7l-52.4-52.4-256.2 256.2a8.03 8.03 0 01-11.3 0l-42.4-42.4a8.03 8.03 0 010-11.3l256.1-256.3z"}}]},name:"export",theme:"outlined"};var i=e.i(9583),l=r.forwardRef(function(e,l){return r.createElement(i.default,(0,t.default)({},e,{ref:l,icon:a}))});e.s(["ExportOutlined",0,l],872934)},149192,e=>{"use strict";var t=e.i(864517);e.s(["CloseOutlined",()=>t.default])},245094,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M516 673c0 4.4 3.4 8 7.5 8h185c4.1 0 7.5-3.6 7.5-8v-48c0-4.4-3.4-8-7.5-8h-185c-4.1 0-7.5 3.6-7.5 8v48zm-194.9 6.1l192-161c3.8-3.2 3.8-9.1 0-12.3l-192-160.9A7.95 7.95 0 00308 351v62.7c0 2.4 1 4.6 2.9 6.1L420.7 512l-109.8 92.2a8.1 8.1 0 00-2.9 6.1V673c0 6.8 7.9 10.5 13.1 6.1zM880 112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32zm-40 728H184V184h656v656z"}}]},name:"code",theme:"outlined"};var i=e.i(9583),l=r.forwardRef(function(e,l){return r.createElement(i.default,(0,t.default)({},e,{ref:l,icon:a}))});e.s(["CodeOutlined",0,l],245094)},166406,e=>{"use strict";var t=e.i(190144);e.s(["CopyOutlined",()=>t.default])},362024,e=>{"use strict";var t=e.i(988122);e.s(["Collapse",()=>t.default])},240647,e=>{"use strict";var t=e.i(286612);e.s(["RightOutlined",()=>t.default])},245704,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let 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"};var i=e.i(9583),l=r.forwardRef(function(e,l){return r.createElement(i.default,(0,t.default)({},e,{ref:l,icon:a}))});e.s(["CheckCircleOutlined",0,l],245704)},518617,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{"fill-rule":"evenodd",viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M512 64c247.4 0 448 200.6 448 448S759.4 960 512 960 64 759.4 64 512 264.6 64 512 64zm0 76c-205.4 0-372 166.6-372 372s166.6 372 372 372 372-166.6 372-372-166.6-372-372-372zm128.01 198.83c.03 0 .05.01.09.06l45.02 45.01a.2.2 0 01.05.09.12.12 0 010 .07c0 .02-.01.04-.05.08L557.25 512l127.87 127.86a.27.27 0 01.05.06v.02a.12.12 0 010 .07c0 .03-.01.05-.05.09l-45.02 45.02a.2.2 0 01-.09.05.12.12 0 01-.07 0c-.02 0-.04-.01-.08-.05L512 557.25 384.14 685.12c-.04.04-.06.05-.08.05a.12.12 0 01-.07 0c-.03 0-.05-.01-.09-.05l-45.02-45.02a.2.2 0 01-.05-.09.12.12 0 010-.07c0-.02.01-.04.06-.08L466.75 512 338.88 384.14a.27.27 0 01-.05-.06l-.01-.02a.12.12 0 010-.07c0-.03.01-.05.05-.09l45.02-45.02a.2.2 0 01.09-.05.12.12 0 01.07 0c.02 0 .04.01.08.06L512 466.75l127.86-127.86c.04-.05.06-.06.08-.06a.12.12 0 01.07 0z"}}]},name:"close-circle",theme:"outlined"};var i=e.i(9583),l=r.forwardRef(function(e,l){return r.createElement(i.default,(0,t.default)({},e,{ref:l,icon:a}))});e.s(["CloseCircleOutlined",0,l],518617)},724154,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let 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-372 0-89 31.3-170.8 83.5-234.8l523.3 523.3C682.8 852.7 601 884 512 884zm288.5-137.2L277.2 223.5C341.2 171.3 423 140 512 140c205.4 0 372 166.6 372 372 0 89-31.3 170.8-83.5 234.8z"}}]},name:"stop",theme:"outlined"};var i=e.i(9583),l=r.forwardRef(function(e,l){return r.createElement(i.default,(0,t.default)({},e,{ref:l,icon:a}))});e.s(["StopOutlined",0,l],724154)},546467,e=>{"use strict";let t=(0,e.i(475254).default)("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"}]]);e.s(["default",()=>t])},118366,e=>{"use strict";var t=e.i(991124);e.s(["CopyIcon",()=>t.default])},991124,e=>{"use strict";let t=(0,e.i(475254).default)("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"}]]);e.s(["default",()=>t])},678784,678745,e=>{"use strict";let t=(0,e.i(475254).default)("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);e.s(["default",()=>t],678745),e.s(["CheckIcon",()=>t],678784)},54943,e=>{"use strict";let t=(0,e.i(475254).default)("search",[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]);e.s(["default",()=>t])},995926,e=>{"use strict";var t=e.i(841947);e.s(["XIcon",()=>t.default])},987432,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M893.3 293.3L730.7 130.7c-7.5-7.5-16.7-13-26.7-16V112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V338.5c0-17-6.7-33.2-18.7-45.2zM384 184h256v104H384V184zm456 656H184V184h136v136c0 17.7 14.3 32 32 32h320c17.7 0 32-14.3 32-32V205.8l136 136V840zM512 442c-79.5 0-144 64.5-144 144s64.5 144 144 144 144-64.5 144-144-64.5-144-144-144zm0 224c-44.2 0-80-35.8-80-80s35.8-80 80-80 80 35.8 80 80-35.8 80-80 80z"}}]},name:"save",theme:"outlined"};var i=e.i(9583),l=r.forwardRef(function(e,l){return r.createElement(i.default,(0,t.default)({},e,{ref:l,icon:a}))});e.s(["SaveOutlined",0,l],987432)},211576,e=>{"use strict";var t=e.i(131757);e.s(["Col",()=>t.default])},988846,e=>{"use strict";var t=e.i(54943);e.s(["SearchIcon",()=>t.default])},54131,634831,438100,e=>{"use strict";var t=e.i(399219);e.s(["ChevronUpIcon",()=>t.default],54131);var r=e.i(546467);e.s(["ExternalLinkIcon",()=>r.default],634831);let a=(0,e.i(475254).default)("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"}]]);e.s(["KeyIcon",()=>a],438100)},302202,e=>{"use strict";let t=(0,e.i(475254).default)("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"}]]);e.s(["ServerIcon",()=>t],302202)},328196,e=>{"use strict";var t=e.i(361653);e.s(["AlertCircleIcon",()=>t.default])},573421,e=>{"use strict";e.i(247167);var t=e.i(8211),r=e.i(271645),a=e.i(343794),i=e.i(887719),l=e.i(908206),n=e.i(242064),o=e.i(721132),s=e.i(517455),d=e.i(264042),c=e.i(150073),u=e.i(165370),m=e.i(244451);let g=r.default.createContext({});g.Consumer;var p=e.i(763731),f=e.i(211576),h=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,a=Object.getOwnPropertySymbols(e);it.indexOf(a[i])&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(r[a[i]]=e[a[i]]);return r};let v=r.default.forwardRef((e,t)=>{let i,{prefixCls:l,children:o,actions:s,extra:d,styles:c,className:u,classNames:m,colStyle:v}=e,b=h(e,["prefixCls","children","actions","extra","styles","className","classNames","colStyle"]),{grid:y,itemLayout:$}=(0,r.useContext)(g),{getPrefixCls:x,list:k}=(0,r.useContext)(n.ConfigContext),C=e=>{var t,r;return(0,a.default)(null==(r=null==(t=null==k?void 0:k.item)?void 0:t.classNames)?void 0:r[e],null==m?void 0:m[e])},S=e=>{var t,r;return Object.assign(Object.assign({},null==(r=null==(t=null==k?void 0:k.item)?void 0:t.styles)?void 0:r[e]),null==c?void 0:c[e])},w=x("list",l),E=s&&s.length>0&&r.default.createElement("ul",{className:(0,a.default)(`${w}-item-action`,C("actions")),key:"actions",style:S("actions")},s.map((e,t)=>r.default.createElement("li",{key:`${w}-item-action-${t}`},e,t!==s.length-1&&r.default.createElement("em",{className:`${w}-item-action-split`})))),z=r.default.createElement(y?"div":"li",Object.assign({},b,y?{}:{ref:t},{className:(0,a.default)(`${w}-item`,{[`${w}-item-no-flex`]:!("vertical"===$?!!d:(i=!1,r.Children.forEach(o,e=>{"string"==typeof e&&(i=!0)}),!(i&&r.Children.count(o)>1)))},u)}),"vertical"===$&&d?[r.default.createElement("div",{className:`${w}-item-main`,key:"content"},o,E),r.default.createElement("div",{className:(0,a.default)(`${w}-item-extra`,C("extra")),key:"extra",style:S("extra")},d)]:[o,E,(0,p.cloneElement)(d,{key:"extra"})]);return y?r.default.createElement(f.Col,{ref:t,flex:1,style:v},z):z});v.Meta=e=>{var{prefixCls:t,className:i,avatar:l,title:o,description:s}=e,d=h(e,["prefixCls","className","avatar","title","description"]);let{getPrefixCls:c}=(0,r.useContext)(n.ConfigContext),u=c("list",t),m=(0,a.default)(`${u}-item-meta`,i),g=r.default.createElement("div",{className:`${u}-item-meta-content`},o&&r.default.createElement("h4",{className:`${u}-item-meta-title`},o),s&&r.default.createElement("div",{className:`${u}-item-meta-description`},s));return r.default.createElement("div",Object.assign({},d,{className:m}),l&&r.default.createElement("div",{className:`${u}-item-meta-avatar`},l),(o||s)&&g)},e.i(296059);var b=e.i(915654),y=e.i(183293),$=e.i(246422),x=e.i(838378);let k=(0,$.genStyleHooks)("List",e=>{let t=(0,x.mergeToken)(e,{listBorderedCls:`${e.componentCls}-bordered`,minHeight:e.controlHeightLG});return[(e=>{let{componentCls:t,antCls:r,controlHeight:a,minHeight:i,paddingSM:l,marginLG:n,padding:o,itemPadding:s,colorPrimary:d,itemPaddingSM:c,itemPaddingLG:u,paddingXS:m,margin:g,colorText:p,colorTextDescription:f,motionDurationSlow:h,lineWidth:v,headerBg:$,footerBg:x,emptyTextPadding:k,metaMarginBottom:C,avatarMarginRight:S,titleMarginBottom:w,descriptionFontSize:E}=e;return{[t]:Object.assign(Object.assign({},(0,y.resetComponent)(e)),{position:"relative","--rc-virtual-list-scrollbar-bg":e.colorSplit,"*":{outline:"none"},[`${t}-header`]:{background:$},[`${t}-footer`]:{background:x},[`${t}-header, ${t}-footer`]:{paddingBlock:l},[`${t}-pagination`]:{marginBlockStart:n,[`${r}-pagination-options`]:{textAlign:"start"}},[`${t}-spin`]:{minHeight:i,textAlign:"center"},[`${t}-items`]:{margin:0,padding:0,listStyle:"none"},[`${t}-item`]:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:s,color:p,[`${t}-item-meta`]:{display:"flex",flex:1,alignItems:"flex-start",maxWidth:"100%",[`${t}-item-meta-avatar`]:{marginInlineEnd:S},[`${t}-item-meta-content`]:{flex:"1 0",width:0,color:p},[`${t}-item-meta-title`]:{margin:`0 0 ${(0,b.unit)(e.marginXXS)} 0`,color:p,fontSize:e.fontSize,lineHeight:e.lineHeight,"> a":{color:p,transition:`all ${h}`,"&:hover":{color:d}}},[`${t}-item-meta-description`]:{color:f,fontSize:E,lineHeight:e.lineHeight}},[`${t}-item-action`]:{flex:"0 0 auto",marginInlineStart:e.marginXXL,padding:0,fontSize:0,listStyle:"none","& > li":{position:"relative",display:"inline-block",padding:`0 ${(0,b.unit)(m)}`,color:f,fontSize:e.fontSize,lineHeight:e.lineHeight,textAlign:"center","&:first-child":{paddingInlineStart:0}},[`${t}-item-action-split`]:{position:"absolute",insetBlockStart:"50%",insetInlineEnd:0,width:v,height:e.calc(e.fontHeight).sub(e.calc(e.marginXXS).mul(2)).equal(),transform:"translateY(-50%)",backgroundColor:e.colorSplit}}},[`${t}-empty`]:{padding:`${(0,b.unit)(o)} 0`,color:f,fontSize:e.fontSizeSM,textAlign:"center"},[`${t}-empty-text`]:{padding:k,color:e.colorTextDisabled,fontSize:e.fontSize,textAlign:"center"},[`${t}-item-no-flex`]:{display:"block"}}),[`${t}-grid ${r}-col > ${t}-item`]:{display:"block",maxWidth:"100%",marginBlockEnd:g,paddingBlock:0,borderBlockEnd:"none"},[`${t}-vertical ${t}-item`]:{alignItems:"initial",[`${t}-item-main`]:{display:"block",flex:1},[`${t}-item-extra`]:{marginInlineStart:n},[`${t}-item-meta`]:{marginBlockEnd:C,[`${t}-item-meta-title`]:{marginBlockStart:0,marginBlockEnd:w,color:p,fontSize:e.fontSizeLG,lineHeight:e.lineHeightLG}},[`${t}-item-action`]:{marginBlockStart:o,marginInlineStart:"auto","> li":{padding:`0 ${(0,b.unit)(o)}`,"&:first-child":{paddingInlineStart:0}}}},[`${t}-split ${t}-item`]:{borderBlockEnd:`${(0,b.unit)(e.lineWidth)} ${e.lineType} ${e.colorSplit}`,"&:last-child":{borderBlockEnd:"none"}},[`${t}-split ${t}-header`]:{borderBlockEnd:`${(0,b.unit)(e.lineWidth)} ${e.lineType} ${e.colorSplit}`},[`${t}-split${t}-empty ${t}-footer`]:{borderTop:`${(0,b.unit)(e.lineWidth)} ${e.lineType} ${e.colorSplit}`},[`${t}-loading ${t}-spin-nested-loading`]:{minHeight:a},[`${t}-split${t}-something-after-last-item ${r}-spin-container > ${t}-items > ${t}-item:last-child`]:{borderBlockEnd:`${(0,b.unit)(e.lineWidth)} ${e.lineType} ${e.colorSplit}`},[`${t}-lg ${t}-item`]:{padding:u},[`${t}-sm ${t}-item`]:{padding:c},[`${t}:not(${t}-vertical)`]:{[`${t}-item-no-flex`]:{[`${t}-item-action`]:{float:"right"}}}}})(t),(e=>{let{listBorderedCls:t,componentCls:r,paddingLG:a,margin:i,itemPaddingSM:l,itemPaddingLG:n,marginLG:o,borderRadiusLG:s}=e,d=(0,b.unit)(e.calc(s).sub(e.lineWidth).equal());return{[t]:{border:`${(0,b.unit)(e.lineWidth)} ${e.lineType} ${e.colorBorder}`,borderRadius:s,[`${r}-header`]:{borderRadius:`${d} ${d} 0 0`},[`${r}-footer`]:{borderRadius:`0 0 ${d} ${d}`},[`${r}-header,${r}-footer,${r}-item`]:{paddingInline:a},[`${r}-pagination`]:{margin:`${(0,b.unit)(i)} ${(0,b.unit)(o)}`}},[`${t}${r}-sm`]:{[`${r}-item,${r}-header,${r}-footer`]:{padding:l}},[`${t}${r}-lg`]:{[`${r}-item,${r}-header,${r}-footer`]:{padding:n}}}})(t),(e=>{let{componentCls:t,screenSM:r,screenMD:a,marginLG:i,marginSM:l,margin:n}=e;return{[`@media screen and (max-width:${a}px)`]:{[t]:{[`${t}-item`]:{[`${t}-item-action`]:{marginInlineStart:i}}},[`${t}-vertical`]:{[`${t}-item`]:{[`${t}-item-extra`]:{marginInlineStart:i}}}},[`@media screen and (max-width: ${r}px)`]:{[t]:{[`${t}-item`]:{flexWrap:"wrap",[`${t}-action`]:{marginInlineStart:l}}},[`${t}-vertical`]:{[`${t}-item`]:{flexWrap:"wrap-reverse",[`${t}-item-main`]:{minWidth:e.contentWidth},[`${t}-item-extra`]:{margin:`auto auto ${(0,b.unit)(n)}`}}}}}})(t)]},e=>({contentWidth:220,itemPadding:`${(0,b.unit)(e.paddingContentVertical)} 0`,itemPaddingSM:`${(0,b.unit)(e.paddingContentVerticalSM)} ${(0,b.unit)(e.paddingContentHorizontal)}`,itemPaddingLG:`${(0,b.unit)(e.paddingContentVerticalLG)} ${(0,b.unit)(e.paddingContentHorizontalLG)}`,headerBg:"transparent",footerBg:"transparent",emptyTextPadding:e.padding,metaMarginBottom:e.padding,avatarMarginRight:e.padding,titleMarginBottom:e.paddingSM,descriptionFontSize:e.fontSize}));var C=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,a=Object.getOwnPropertySymbols(e);it.indexOf(a[i])&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(r[a[i]]=e[a[i]]);return r};let S=r.forwardRef(function(e,p){let{pagination:f=!1,prefixCls:h,bordered:v=!1,split:b=!0,className:y,rootClassName:$,style:x,children:S,itemLayout:w,loadMore:E,grid:z,dataSource:N=[],size:M,header:O,footer:I,loading:j=!1,rowKey:L,renderItem:T,locale:D}=e,B=C(e,["pagination","prefixCls","bordered","split","className","rootClassName","style","children","itemLayout","loadMore","grid","dataSource","size","header","footer","loading","rowKey","renderItem","locale"]),H=f&&"object"==typeof f?f:{},[P,R]=r.useState(H.defaultCurrent||1),[V,X]=r.useState(H.defaultPageSize||10),{getPrefixCls:q,direction:A,className:W,style:G}=(0,n.useComponentConfig)("list"),{renderEmpty:F}=r.useContext(n.ConfigContext),K=e=>(t,r)=>{var a;R(t),X(r),f&&(null==(a=null==f?void 0:f[e])||a.call(f,t,r))},U=K("onChange"),_=K("onShowSizeChange"),Y=!!(E||f||I),J=q("list",h),[Q,Z,ee]=k(J),et=j;"boolean"==typeof et&&(et={spinning:et});let er=!!(null==et?void 0:et.spinning),ea=(0,s.default)(M),ei="";switch(ea){case"large":ei="lg";break;case"small":ei="sm"}let el=(0,a.default)(J,{[`${J}-vertical`]:"vertical"===w,[`${J}-${ei}`]:ei,[`${J}-split`]:b,[`${J}-bordered`]:v,[`${J}-loading`]:er,[`${J}-grid`]:!!z,[`${J}-something-after-last-item`]:Y,[`${J}-rtl`]:"rtl"===A},W,y,$,Z,ee),en=(0,i.default)({current:1,total:0,position:"bottom"},{total:N.length,current:P,pageSize:V},f||{}),eo=Math.ceil(en.total/en.pageSize);en.current=Math.min(en.current,eo);let es=f&&r.createElement("div",{className:(0,a.default)(`${J}-pagination`)},r.createElement(u.default,Object.assign({align:"end"},en,{onChange:U,onShowSizeChange:_}))),ed=(0,t.default)(N);f&&N.length>(en.current-1)*en.pageSize&&(ed=(0,t.default)(N).splice((en.current-1)*en.pageSize,en.pageSize));let ec=Object.keys(z||{}).some(e=>["xs","sm","md","lg","xl","xxl"].includes(e)),eu=(0,c.default)(ec),em=r.useMemo(()=>{for(let e=0;e{if(!z)return;let e=em&&z[em]?z[em]:z.column;if(e)return{width:`${100/e}%`,maxWidth:`${100/e}%`}},[JSON.stringify(z),em]),ep=er&&r.createElement("div",{style:{minHeight:53}});if(ed.length>0){let e=ed.map((e,t)=>{let a;return T?((a="function"==typeof L?L(e):L?e[L]:e.key)||(a=`list-item-${t}`),r.createElement(r.Fragment,{key:a},T(e,t))):null});ep=z?r.createElement(d.Row,{gutter:z.gutter},r.Children.map(e,e=>r.createElement("div",{key:null==e?void 0:e.key,style:eg},e))):r.createElement("ul",{className:`${J}-items`},e)}else S||er||(ep=r.createElement("div",{className:`${J}-empty-text`},(null==D?void 0:D.emptyText)||(null==F?void 0:F("List"))||r.createElement(o.default,{componentName:"List"})));let ef=en.position,eh=r.useMemo(()=>({grid:z,itemLayout:w}),[JSON.stringify(z),w]);return Q(r.createElement(g.Provider,{value:eh},r.createElement("div",Object.assign({ref:p,style:Object.assign(Object.assign({},G),x),className:el},B),("top"===ef||"both"===ef)&&es,O&&r.createElement("div",{className:`${J}-header`},O),r.createElement(m.default,Object.assign({},et),ep,S),I&&r.createElement("div",{className:`${J}-footer`},I),E||("bottom"===ef||"both"===ef)&&es)))});S.Item=v,e.s(["List",0,S],573421)},837007,e=>{"use strict";var t=e.i(603908);e.s(["PlusIcon",()=>t.default])},509345,e=>{"use strict";var t=e.i(843476),r=e.i(487304),a=e.i(135214);e.s(["default",0,()=>{let{accessToken:e}=(0,a.default)();return(0,t.jsx)(r.default,{accessToken:e})}])}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/3b2ec401925509b1.js b/litellm/proxy/_experimental/out/_next/static/chunks/3b2ec401925509b1.js deleted file mode 100644 index f9b567a99d6..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/3b2ec401925509b1.js +++ /dev/null @@ -1 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,621482,e=>{"use strict";var t=e.i(869230),a=e.i(992571),i=class extends t.QueryObserver{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){super.setOptions({...e,behavior:(0,a.infiniteQueryBehavior)()})}getOptimisticResult(e){return e.behavior=(0,a.infiniteQueryBehavior)(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:i}=e,r=super.createResult(e,t),{isFetching:l,isRefetching:s,isError:n,isRefetchError:o}=r,d=i.fetchMeta?.fetchMore?.direction,c=n&&"forward"===d,u=l&&"forward"===d,m=n&&"backward"===d,g=l&&"backward"===d;return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:(0,a.hasNextPage)(t,i.data),hasPreviousPage:(0,a.hasPreviousPage)(t,i.data),isFetchNextPageError:c,isFetchingNextPage:u,isFetchPreviousPageError:m,isFetchingPreviousPage:g,isRefetchError:o&&!c&&!m,isRefetching:s&&!u&&!g}}},r=e.i(469637);function l(e,t){return(0,r.useBaseQuery)(e,i,t)}e.s(["useInfiniteQuery",()=>l],621482)},785242,e=>{"use strict";var t=e.i(619273),a=e.i(266027),i=e.i(912598),r=e.i(135214),l=e.i(270345),s=e.i(243652),n=e.i(764205);let o=(0,s.createQueryKeys)("teams"),d=async(e,t,a,i={})=>{try{let r=(0,n.getProxyBaseUrl)(),l=new URLSearchParams(Object.entries({team_id:i.teamID,organization_id:i.organizationID,team_alias:i.team_alias,user_id:i.userID,page:t,page_size:a,sort_by:i.sortBy,sort_order:i.sortOrder,status:"deleted"}).filter(([,e])=>null!=e).map(([e,t])=>[e,String(t)])),s=`${r?`${r}/v2/team/list`:"/v2/team/list"}?${l}`,o=await fetch(s,{method:"GET",headers:{[(0,n.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!o.ok){let e=await o.json(),t=(0,n.deriveErrorMessage)(e);throw(0,n.handleError)(t),Error(t)}let d=await o.json();if(console.log("/team/list?status=deleted API Response:",d),d&&"object"==typeof d&&"teams"in d)return d.teams;return d}catch(e){throw console.error("Failed to list deleted teams:",e),e}},c=(0,s.createQueryKeys)("deletedTeams");e.s(["useDeletedTeams",0,(e,i,l={})=>{let{accessToken:s}=(0,r.default)();return(0,a.useQuery)({queryKey:c.list({page:e,limit:i,...l}),queryFn:async()=>await d(s,e,i,l),enabled:!!s,staleTime:3e4,placeholderData:t.keepPreviousData})},"useTeam",0,e=>{let{accessToken:t}=(0,r.default)(),l=(0,i.useQueryClient)();return(0,a.useQuery)({queryKey:o.detail(e),enabled:!!(t&&e),queryFn:async()=>{if(!t||!e)throw Error("Missing auth or teamId");return(0,n.teamInfoCall)(t,e)},initialData:()=>{if(!e)return;let t=l.getQueryData(o.list({}));return t?.find(t=>t.team_id===e)}})},"useTeams",0,()=>{let{accessToken:e,userId:t,userRole:i}=(0,r.default)();return(0,a.useQuery)({queryKey:o.list({}),queryFn:async()=>await (0,l.fetchTeams)(e,t,i,null),enabled:!!e})}])},738014,e=>{"use strict";var t=e.i(135214),a=e.i(764205),i=e.i(266027);let r=(0,e.i(243652).createQueryKeys)("users");e.s(["useCurrentUser",0,()=>{let{accessToken:e,userId:l,userRole:s}=(0,t.default)();return(0,i.useQuery)({queryKey:r.detail(l),queryFn:async()=>{let t=await (0,a.userInfoCall)(e,l,s,!1,null,null);return console.log(`userInfo: ${JSON.stringify(t)}`),t.user_info},enabled:!!(e&&l&&s)})}])},980187,e=>{"use strict";e.s(["createTeamAliasMap",0,e=>e?e.reduce((e,t)=>(e[t.team_id]=t.team_alias,e),{}):{},"resolveTeamAliasFromTeamID",0,(e,t)=>{let a=t.find(t=>t.team_id===e);return a?a.team_alias:null}])},655913,38419,78334,e=>{"use strict";var t=e.i(843476),a=e.i(115504),i=e.i(311451),r=e.i(374009),l=e.i(271645);e.s(["FilterInput",0,({placeholder:e,value:s,onChange:n,icon:o,className:d})=>{let[c,u]=(0,l.useState)(s);(0,l.useEffect)(()=>{u(s)},[s]);let m=(0,l.useMemo)(()=>(0,r.default)(e=>n(e),300),[n]);(0,l.useEffect)(()=>()=>{m.cancel()},[m]);let g=(0,l.useCallback)(e=>{let t=e.target.value;u(t),m(t)},[m]);return(0,t.jsx)(i.Input,{placeholder:e,value:c,onChange:g,prefix:o?(0,t.jsx)(o,{size:16,className:"text-gray-500"}):void 0,className:(0,a.cx)("w-64",d)})}],655913);var s=e.i(906579),n=e.i(464571);let o=(0,e.i(475254).default)("funnel",[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]]);e.s(["FiltersButton",0,({onClick:e,active:a,hasActiveFilters:i,label:r="Filters"})=>(0,t.jsx)(s.Badge,{color:"blue",dot:i,children:(0,t.jsx)(n.Button,{type:"default",onClick:e,icon:(0,t.jsx)(o,{size:16}),className:a?"bg-gray-100":"",children:r})})],38419);var d=e.i(367240);e.s(["ResetFiltersButton",0,({onClick:e,label:a="Reset Filters"})=>(0,t.jsx)(n.Button,{type:"default",onClick:e,icon:(0,t.jsx)(d.RotateCcw,{size:16}),children:a})],78334)},846753,e=>{"use strict";let t=(0,e.i(475254).default)("user",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);e.s(["default",()=>t])},284614,e=>{"use strict";var t=e.i(846753);e.s(["User",()=>t.default])},118366,e=>{"use strict";var t=e.i(991124);e.s(["CopyIcon",()=>t.default])},991124,e=>{"use strict";let t=(0,e.i(475254).default)("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"}]]);e.s(["default",()=>t])},678784,678745,e=>{"use strict";let t=(0,e.i(475254).default)("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);e.s(["default",()=>t],678745),e.s(["CheckIcon",()=>t],678784)},906579,e=>{"use strict";e.i(247167);var t=e.i(271645),a=e.i(343794),i=e.i(361275),r=e.i(702779),l=e.i(763731),s=e.i(242064);e.i(296059);var n=e.i(915654),o=e.i(694758),d=e.i(183293),c=e.i(403541),u=e.i(246422),m=e.i(838378);let g=new o.Keyframes("antStatusProcessing",{"0%":{transform:"scale(0.8)",opacity:.5},"100%":{transform:"scale(2.4)",opacity:0}}),h=new o.Keyframes("antZoomBadgeIn",{"0%":{transform:"scale(0) translate(50%, -50%)",opacity:0},"100%":{transform:"scale(1) translate(50%, -50%)"}}),x=new o.Keyframes("antZoomBadgeOut",{"0%":{transform:"scale(1) translate(50%, -50%)"},"100%":{transform:"scale(0) translate(50%, -50%)",opacity:0}}),p=new o.Keyframes("antNoWrapperZoomBadgeIn",{"0%":{transform:"scale(0)",opacity:0},"100%":{transform:"scale(1)"}}),b=new o.Keyframes("antNoWrapperZoomBadgeOut",{"0%":{transform:"scale(1)"},"100%":{transform:"scale(0)",opacity:0}}),f=new o.Keyframes("antBadgeLoadingCircle",{"0%":{transformOrigin:"50%"},"100%":{transform:"translate(50%, -50%) rotate(360deg)",transformOrigin:"50%"}}),_=e=>{let{fontHeight:t,lineWidth:a,marginXS:i,colorBorderBg:r}=e,l=e.colorTextLightSolid,s=e.colorError,n=e.colorErrorHover;return(0,m.mergeToken)(e,{badgeFontHeight:t,badgeShadowSize:a,badgeTextColor:l,badgeColor:s,badgeColorHover:n,badgeShadowColor:r,badgeProcessingDuration:"1.2s",badgeRibbonOffset:i,badgeRibbonCornerTransform:"scaleY(0.75)",badgeRibbonCornerFilter:"brightness(75%)"})},j=e=>{let{fontSize:t,lineHeight:a,fontSizeSM:i,lineWidth:r}=e;return{indicatorZIndex:"auto",indicatorHeight:Math.round(t*a)-2*r,indicatorHeightSM:t,dotSize:i/2,textFontSize:i,textFontSizeSM:i,textFontWeight:"normal",statusSize:i/2}},v=(0,u.genStyleHooks)("Badge",e=>(e=>{let{componentCls:t,iconCls:a,antCls:i,badgeShadowSize:r,textFontSize:l,textFontSizeSM:s,statusSize:o,dotSize:u,textFontWeight:m,indicatorHeight:_,indicatorHeightSM:j,marginXS:v,calc:y}=e,w=`${i}-scroll-number`,C=(0,c.genPresetColor)(e,(e,{darkColor:a})=>({[`&${t} ${t}-color-${e}`]:{background:a,[`&:not(${t}-count)`]:{color:a},"a:hover &":{background:a}}}));return{[t]:Object.assign(Object.assign(Object.assign(Object.assign({},(0,d.resetComponent)(e)),{position:"relative",display:"inline-block",width:"fit-content",lineHeight:1,[`${t}-count`]:{display:"inline-flex",justifyContent:"center",zIndex:e.indicatorZIndex,minWidth:_,height:_,color:e.badgeTextColor,fontWeight:m,fontSize:l,lineHeight:(0,n.unit)(_),whiteSpace:"nowrap",textAlign:"center",background:e.badgeColor,borderRadius:y(_).div(2).equal(),boxShadow:`0 0 0 ${(0,n.unit)(r)} ${e.badgeShadowColor}`,transition:`background ${e.motionDurationMid}`,a:{color:e.badgeTextColor},"a:hover":{color:e.badgeTextColor},"a:hover &":{background:e.badgeColorHover}},[`${t}-count-sm`]:{minWidth:j,height:j,fontSize:s,lineHeight:(0,n.unit)(j),borderRadius:y(j).div(2).equal()},[`${t}-multiple-words`]:{padding:`0 ${(0,n.unit)(e.paddingXS)}`,bdi:{unicodeBidi:"plaintext"}},[`${t}-dot`]:{zIndex:e.indicatorZIndex,width:u,minWidth:u,height:u,background:e.badgeColor,borderRadius:"100%",boxShadow:`0 0 0 ${(0,n.unit)(r)} ${e.badgeShadowColor}`},[`${t}-count, ${t}-dot, ${w}-custom-component`]:{position:"absolute",top:0,insetInlineEnd:0,transform:"translate(50%, -50%)",transformOrigin:"100% 0%",[`&${a}-spin`]:{animationName:f,animationDuration:"1s",animationIterationCount:"infinite",animationTimingFunction:"linear"}},[`&${t}-status`]:{lineHeight:"inherit",verticalAlign:"baseline",[`${t}-status-dot`]:{position:"relative",top:-1,display:"inline-block",width:o,height:o,verticalAlign:"middle",borderRadius:"50%"},[`${t}-status-success`]:{backgroundColor:e.colorSuccess},[`${t}-status-processing`]:{overflow:"visible",color:e.colorInfo,backgroundColor:e.colorInfo,borderColor:"currentcolor","&::after":{position:"absolute",top:0,insetInlineStart:0,width:"100%",height:"100%",borderWidth:r,borderStyle:"solid",borderColor:"inherit",borderRadius:"50%",animationName:g,animationDuration:e.badgeProcessingDuration,animationIterationCount:"infinite",animationTimingFunction:"ease-in-out",content:'""'}},[`${t}-status-default`]:{backgroundColor:e.colorTextPlaceholder},[`${t}-status-error`]:{backgroundColor:e.colorError},[`${t}-status-warning`]:{backgroundColor:e.colorWarning},[`${t}-status-text`]:{marginInlineStart:v,color:e.colorText,fontSize:e.fontSize}}}),C),{[`${t}-zoom-appear, ${t}-zoom-enter`]:{animationName:h,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack,animationFillMode:"both"},[`${t}-zoom-leave`]:{animationName:x,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack,animationFillMode:"both"},[`&${t}-not-a-wrapper`]:{[`${t}-zoom-appear, ${t}-zoom-enter`]:{animationName:p,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack},[`${t}-zoom-leave`]:{animationName:b,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack},[`&:not(${t}-status)`]:{verticalAlign:"middle"},[`${w}-custom-component, ${t}-count`]:{transform:"none"},[`${w}-custom-component, ${w}`]:{position:"relative",top:"auto",display:"block",transformOrigin:"50% 50%"}},[w]:{overflow:"hidden",transition:`all ${e.motionDurationMid} ${e.motionEaseOutBack}`,[`${w}-only`]:{position:"relative",display:"inline-block",height:_,transition:`all ${e.motionDurationSlow} ${e.motionEaseOutBack}`,WebkitTransformStyle:"preserve-3d",WebkitBackfaceVisibility:"hidden",[`> p${w}-only-unit`]:{height:_,margin:0,WebkitTransformStyle:"preserve-3d",WebkitBackfaceVisibility:"hidden"}},[`${w}-symbol`]:{verticalAlign:"top"}},"&-rtl":{direction:"rtl",[`${t}-count, ${t}-dot, ${w}-custom-component`]:{transform:"translate(-50%, -50%)"}}})}})(_(e)),j),y=(0,u.genStyleHooks)(["Badge","Ribbon"],e=>(e=>{let{antCls:t,badgeFontHeight:a,marginXS:i,badgeRibbonOffset:r,calc:l}=e,s=`${t}-ribbon`,o=`${t}-ribbon-wrapper`,u=(0,c.genPresetColor)(e,(e,{darkColor:t})=>({[`&${s}-color-${e}`]:{background:t,color:t}}));return{[o]:{position:"relative"},[s]:Object.assign(Object.assign(Object.assign(Object.assign({},(0,d.resetComponent)(e)),{position:"absolute",top:i,padding:`0 ${(0,n.unit)(e.paddingXS)}`,color:e.colorPrimary,lineHeight:(0,n.unit)(a),whiteSpace:"nowrap",backgroundColor:e.colorPrimary,borderRadius:e.borderRadiusSM,[`${s}-text`]:{color:e.badgeTextColor},[`${s}-corner`]:{position:"absolute",top:"100%",width:r,height:r,color:"currentcolor",border:`${(0,n.unit)(l(r).div(2).equal())} solid`,transform:e.badgeRibbonCornerTransform,transformOrigin:"top",filter:e.badgeRibbonCornerFilter}}),u),{[`&${s}-placement-end`]:{insetInlineEnd:l(r).mul(-1).equal(),borderEndEndRadius:0,[`${s}-corner`]:{insetInlineEnd:0,borderInlineEndColor:"transparent",borderBlockEndColor:"transparent"}},[`&${s}-placement-start`]:{insetInlineStart:l(r).mul(-1).equal(),borderEndStartRadius:0,[`${s}-corner`]:{insetInlineStart:0,borderBlockEndColor:"transparent",borderInlineStartColor:"transparent"}},"&-rtl":{direction:"rtl"}})}})(_(e)),j),w=e=>{let i,{prefixCls:r,value:l,current:s,offset:n=0}=e;return n&&(i={position:"absolute",top:`${n}00%`,left:0}),t.createElement("span",{style:i,className:(0,a.default)(`${r}-only-unit`,{current:s})},l)},C=e=>{let a,i,{prefixCls:r,count:l,value:s}=e,n=Number(s),o=Math.abs(l),[d,c]=t.useState(n),[u,m]=t.useState(o),g=()=>{c(n),m(o)};if(t.useEffect(()=>{let e=setTimeout(g,1e3);return()=>clearTimeout(e)},[n]),d===n||Number.isNaN(n)||Number.isNaN(d))a=[t.createElement(w,Object.assign({},e,{key:n,current:!0}))],i={transition:"none"};else{a=[];let r=n+10,l=[];for(let e=n;e<=r;e+=1)l.push(e);let s=ue%10===d);a=(s<0?l.slice(0,c+1):l.slice(c)).map((a,i)=>t.createElement(w,Object.assign({},e,{key:a,value:a%10,offset:s<0?i-c:i,current:i===c}))),i={transform:`translateY(${-function(e,t,a){let i=e,r=0;for(;(i+10)%10!==t;)i+=a,r+=a;return r}(d,n,s)}00%)`}}return t.createElement("span",{className:`${r}-only`,style:i,onTransitionEnd:g},a)};var N=function(e,t){var a={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&0>t.indexOf(i)&&(a[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,i=Object.getOwnPropertySymbols(e);rt.indexOf(i[r])&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(a[i[r]]=e[i[r]]);return a};let T=t.forwardRef((e,i)=>{let{prefixCls:r,count:n,className:o,motionClassName:d,style:c,title:u,show:m,component:g="sup",children:h}=e,x=N(e,["prefixCls","count","className","motionClassName","style","title","show","component","children"]),{getPrefixCls:p}=t.useContext(s.ConfigContext),b=p("scroll-number",r),f=Object.assign(Object.assign({},x),{"data-show":m,style:c,className:(0,a.default)(b,o,d),title:u}),_=n;if(n&&Number(n)%1==0){let e=String(n).split("");_=t.createElement("bdi",null,e.map((a,i)=>t.createElement(C,{prefixCls:b,count:Number(n),value:a,key:e.length-i})))}return((null==c?void 0:c.borderColor)&&(f.style=Object.assign(Object.assign({},c),{boxShadow:`0 0 0 1px ${c.borderColor} inset`})),h)?(0,l.cloneElement)(h,e=>({className:(0,a.default)(`${b}-custom-component`,null==e?void 0:e.className,d)})):t.createElement(g,Object.assign({},f,{ref:i}),_)});var z=function(e,t){var a={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&0>t.indexOf(i)&&(a[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,i=Object.getOwnPropertySymbols(e);rt.indexOf(i[r])&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(a[i[r]]=e[i[r]]);return a};let O=t.forwardRef((e,n)=>{var o,d,c,u,m;let{prefixCls:g,scrollNumberPrefixCls:h,children:x,status:p,text:b,color:f,count:_=null,overflowCount:j=99,dot:y=!1,size:w="default",title:C,offset:N,style:O,className:S,rootClassName:$,classNames:k,styles:I,showZero:F=!1}=e,M=z(e,["prefixCls","scrollNumberPrefixCls","children","status","text","color","count","overflowCount","dot","size","title","offset","style","className","rootClassName","classNames","styles","showZero"]),{getPrefixCls:P,direction:E,badge:B}=t.useContext(s.ConfigContext),R=P("badge",g),[D,A,L]=v(R),H=_>j?`${j}+`:_,U="0"===H||0===H||"0"===b||0===b,q=null===_||U&&!F,V=(null!=p||null!=f)&&q,W=null!=p||!U,K=y&&!U,Q=K?"":H,G=(0,t.useMemo)(()=>((null==Q||""===Q)&&(null==b||""===b)||U&&!F)&&!K,[Q,U,F,K,b]),Z=(0,t.useRef)(_);G||(Z.current=_);let J=Z.current,Y=(0,t.useRef)(Q);G||(Y.current=Q);let X=Y.current,ee=(0,t.useRef)(K);G||(ee.current=K);let et=(0,t.useMemo)(()=>{if(!N)return Object.assign(Object.assign({},null==B?void 0:B.style),O);let e={marginTop:N[1]};return"rtl"===E?e.left=Number.parseInt(N[0],10):e.right=-Number.parseInt(N[0],10),Object.assign(Object.assign(Object.assign({},e),null==B?void 0:B.style),O)},[E,N,O,null==B?void 0:B.style]),ea=null!=C?C:"string"==typeof J||"number"==typeof J?J:void 0,ei=!G&&(0===b?F:!!b&&!0!==b),er=ei?t.createElement("span",{className:`${R}-status-text`},b):null,el=J&&"object"==typeof J?(0,l.cloneElement)(J,e=>({style:Object.assign(Object.assign({},et),e.style)})):void 0,es=(0,r.isPresetColor)(f,!1),en=(0,a.default)(null==k?void 0:k.indicator,null==(o=null==B?void 0:B.classNames)?void 0:o.indicator,{[`${R}-status-dot`]:V,[`${R}-status-${p}`]:!!p,[`${R}-color-${f}`]:es}),eo={};f&&!es&&(eo.color=f,eo.background=f);let ed=(0,a.default)(R,{[`${R}-status`]:V,[`${R}-not-a-wrapper`]:!x,[`${R}-rtl`]:"rtl"===E},S,$,null==B?void 0:B.className,null==(d=null==B?void 0:B.classNames)?void 0:d.root,null==k?void 0:k.root,A,L);if(!x&&V&&(b||W||!q)){let e=et.color;return D(t.createElement("span",Object.assign({},M,{className:ed,style:Object.assign(Object.assign(Object.assign({},null==I?void 0:I.root),null==(c=null==B?void 0:B.styles)?void 0:c.root),et)}),t.createElement("span",{className:en,style:Object.assign(Object.assign(Object.assign({},null==I?void 0:I.indicator),null==(u=null==B?void 0:B.styles)?void 0:u.indicator),eo)}),ei&&t.createElement("span",{style:{color:e},className:`${R}-status-text`},b)))}return D(t.createElement("span",Object.assign({ref:n},M,{className:ed,style:Object.assign(Object.assign({},null==(m=null==B?void 0:B.styles)?void 0:m.root),null==I?void 0:I.root)}),x,t.createElement(i.default,{visible:!G,motionName:`${R}-zoom`,motionAppear:!1,motionDeadline:1e3},({className:e})=>{var i,r;let l=P("scroll-number",h),s=ee.current,n=(0,a.default)(null==k?void 0:k.indicator,null==(i=null==B?void 0:B.classNames)?void 0:i.indicator,{[`${R}-dot`]:s,[`${R}-count`]:!s,[`${R}-count-sm`]:"small"===w,[`${R}-multiple-words`]:!s&&X&&X.toString().length>1,[`${R}-status-${p}`]:!!p,[`${R}-color-${f}`]:es}),o=Object.assign(Object.assign(Object.assign({},null==I?void 0:I.indicator),null==(r=null==B?void 0:B.styles)?void 0:r.indicator),et);return f&&!es&&((o=o||{}).background=f),t.createElement(T,{prefixCls:l,show:!G,motionClassName:e,className:n,count:X,title:ea,style:o,key:"scrollNumber"},el)}),er))});O.Ribbon=e=>{let{className:i,prefixCls:l,style:n,color:o,children:d,text:c,placement:u="end",rootClassName:m}=e,{getPrefixCls:g,direction:h}=t.useContext(s.ConfigContext),x=g("ribbon",l),p=`${x}-wrapper`,[b,f,_]=y(x,p),j=(0,r.isPresetColor)(o,!1),v=(0,a.default)(x,`${x}-placement-${u}`,{[`${x}-rtl`]:"rtl"===h,[`${x}-color-${o}`]:j},i),w={},C={};return o&&!j&&(w.background=o,C.color=o),b(t.createElement("div",{className:(0,a.default)(p,m,f,_)},d,t.createElement("div",{className:(0,a.default)(v,f),style:Object.assign(Object.assign({},w),n)},t.createElement("span",{className:`${x}-text`},c),t.createElement("div",{className:`${x}-corner`,style:C}))))},e.s(["Badge",0,O],906579)},54943,e=>{"use strict";let t=(0,e.i(475254).default)("search",[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]);e.s(["default",()=>t])},367240,555436,e=>{"use strict";let t=(0,e.i(475254).default)("rotate-ccw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);e.s(["RotateCcw",()=>t],367240);var a=e.i(54943);e.s(["Search",()=>a.default],555436)},846835,e=>{"use strict";var t=e.i(843476),a=e.i(655913),i=e.i(38419),r=e.i(78334),l=e.i(555436),s=e.i(284614);let n=({filters:e,showFilters:n,onToggleFilters:o,onChange:d,onReset:c})=>{let u=!!(e.org_id||e.org_alias);return(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)(a.FilterInput,{placeholder:"Search by Organization Name",value:e.org_alias,onChange:e=>d("org_alias",e),icon:l.Search,className:"w-64"}),(0,t.jsx)(i.FiltersButton,{onClick:()=>o(!n),active:n,hasActiveFilters:u}),(0,t.jsx)(r.ResetFiltersButton,{onClick:c})]}),n&&(0,t.jsx)("div",{className:"flex flex-wrap items-center gap-3 mt-3",children:(0,t.jsx)(a.FilterInput,{placeholder:"Search by Organization ID",value:e.org_id,onChange:e=>d("org_id",e),icon:s.User,className:"w-64"})})]})};var o=e.i(827252),d=e.i(871943),c=e.i(502547),u=e.i(278587),m=e.i(389083),g=e.i(994388),h=e.i(304967),x=e.i(309426),p=e.i(350967),b=e.i(752978),f=e.i(197647),_=e.i(653824),j=e.i(269200),v=e.i(942232),y=e.i(977572),w=e.i(427612),C=e.i(64848),N=e.i(496020),T=e.i(881073),z=e.i(404206),O=e.i(723731),S=e.i(599724),$=e.i(779241),k=e.i(808613),I=e.i(311451),F=e.i(212931),M=e.i(199133),P=e.i(592968),E=e.i(271645),B=e.i(500330),R=e.i(127952),D=e.i(902555),A=e.i(355619),L=e.i(75921),H=e.i(162386),U=e.i(727749),q=e.i(764205),V=e.i(785242),W=e.i(980187),K=e.i(530212),Q=e.i(629569),G=e.i(464571),Z=e.i(653496),J=e.i(898586),Y=e.i(678784),X=e.i(118366),ee=e.i(294612),et=e.i(907308),ea=e.i(384767),ei=e.i(435451),er=e.i(276173),el=e.i(916940);let es=({organizationId:e,onClose:a,accessToken:i,is_org_admin:r,is_proxy_admin:l,userModels:s,editOrg:n})=>{let[o,d]=(0,E.useState)(null),[c,u]=(0,E.useState)(!0),[x]=k.Form.useForm(),[b,f]=(0,E.useState)(!1),[_,j]=(0,E.useState)(!1),[v,y]=(0,E.useState)(!1),[w,C]=(0,E.useState)(null),[N,T]=(0,E.useState)({}),[z,O]=(0,E.useState)(!1),F=r||l,{data:P}=(0,V.useTeams)(),R=(0,E.useMemo)(()=>(0,W.createTeamAliasMap)(P),[P]),D=async()=>{try{if(u(!0),!i)return;let t=await (0,q.organizationInfoCall)(i,e);d(t)}catch(e){U.default.fromBackend("Failed to load organization information"),console.error("Error fetching organization info:",e)}finally{u(!1)}};(0,E.useEffect)(()=>{D()},[e,i]);let A=async t=>{try{if(null==i)return;let a={user_email:t.user_email,user_id:t.user_id,role:t.role};await (0,q.organizationMemberAddCall)(i,e,a),U.default.success("Organization member added successfully"),j(!1),x.resetFields(),D()}catch(e){U.default.fromBackend("Failed to add organization member"),console.error("Error adding organization member:",e)}},es=async t=>{try{if(!i)return;let a={user_email:t.user_email,user_id:t.user_id,role:t.role};await (0,q.organizationMemberUpdateCall)(i,e,a),U.default.success("Organization member updated successfully"),y(!1),x.resetFields(),D()}catch(e){U.default.fromBackend("Failed to update organization member"),console.error("Error updating organization member:",e)}},en=async t=>{try{if(!i)return;await (0,q.organizationMemberDeleteCall)(i,e,t.user_id),U.default.success("Organization member deleted successfully"),y(!1),x.resetFields(),D()}catch(e){U.default.fromBackend("Failed to delete organization member"),console.error("Error deleting organization member:",e)}},eo=async t=>{try{if(!i)return;O(!0);let a={organization_id:e,organization_alias:t.organization_alias,models:t.models,litellm_budget_table:{tpm_limit:t.tpm_limit,rpm_limit:t.rpm_limit,max_budget:t.max_budget,budget_duration:t.budget_duration},metadata:t.metadata?JSON.parse(t.metadata):null};if((void 0!==t.vector_stores||void 0!==t.mcp_servers_and_groups)&&(a.object_permission={...o?.object_permission,vector_stores:t.vector_stores||[]},void 0!==t.mcp_servers_and_groups)){let{servers:e,accessGroups:i}=t.mcp_servers_and_groups||{servers:[],accessGroups:[]};e&&e.length>0&&(a.object_permission.mcp_servers=e),i&&i.length>0&&(a.object_permission.mcp_access_groups=i)}await (0,q.organizationUpdateCall)(i,a),U.default.success("Organization settings updated successfully"),f(!1),D()}catch(e){U.default.fromBackend("Failed to update organization settings"),console.error("Error updating organization:",e)}finally{O(!1)}};if(c)return(0,t.jsx)("div",{className:"p-4",children:"Loading..."});if(!o)return(0,t.jsx)("div",{className:"p-4",children:"Organization not found"});let ed=async(e,t)=>{await (0,B.copyToClipboard)(e)&&(T(e=>({...e,[t]:!0})),setTimeout(()=>{T(e=>({...e,[t]:!1}))},2e3))},ec=[{title:"Spend (USD)",key:"spend",render:(e,a)=>{let i=null!=a.user_id?(o.members||[]).find(e=>e.user_id===a.user_id):void 0;return(0,t.jsxs)(J.Typography.Text,{children:["$",(0,B.formatNumberWithCommas)(i?.spend??0,4)]})}},{title:"Created At",key:"created_at",render:(e,a)=>{let i=null!=a.user_id?(o.members||[]).find(e=>e.user_id===a.user_id):void 0;return(0,t.jsx)(J.Typography.Text,{children:i?.created_at?new Date(i.created_at).toLocaleString():"-"})}}];return(0,t.jsxs)("div",{className:"w-full h-screen p-4 bg-white",children:[(0,t.jsx)("div",{className:"flex justify-between items-center mb-6",children:(0,t.jsxs)("div",{children:[(0,t.jsx)(g.Button,{icon:K.ArrowLeftIcon,onClick:a,variant:"light",className:"mb-4",children:"Back to Organizations"}),(0,t.jsx)(Q.Title,{children:o.organization_alias}),(0,t.jsxs)("div",{className:"flex items-center cursor-pointer",children:[(0,t.jsx)(S.Text,{className:"text-gray-500 font-mono",children:o.organization_id}),(0,t.jsx)(G.Button,{type:"text",size:"small",icon:N["org-id"]?(0,t.jsx)(Y.CheckIcon,{size:12}):(0,t.jsx)(X.CopyIcon,{size:12}),onClick:()=>ed(o.organization_id,"org-id"),className:`left-2 z-10 transition-all duration-200 ${N["org-id"]?"text-green-600 bg-green-50 border-green-200":"text-gray-500 hover:text-gray-700 hover:bg-gray-100"}`})]})]})}),(0,t.jsx)(Z.Tabs,{defaultActiveKey:n?"settings":"overview",className:"mb-4",items:[{key:"overview",label:"Overview",children:(0,t.jsxs)(p.Grid,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,t.jsxs)(h.Card,{children:[(0,t.jsx)(S.Text,{children:"Organization Details"}),(0,t.jsxs)("div",{className:"mt-2",children:[(0,t.jsxs)(S.Text,{children:["Created: ",new Date(o.created_at).toLocaleDateString()]}),(0,t.jsxs)(S.Text,{children:["Updated: ",new Date(o.updated_at).toLocaleDateString()]}),(0,t.jsxs)(S.Text,{children:["Created By: ",o.created_by]})]})]}),(0,t.jsxs)(h.Card,{children:[(0,t.jsx)(S.Text,{children:"Budget Status"}),(0,t.jsxs)("div",{className:"mt-2",children:[(0,t.jsxs)(Q.Title,{children:["$",(0,B.formatNumberWithCommas)(o.spend,4)]}),(0,t.jsxs)(S.Text,{children:["of"," ",null===o.litellm_budget_table.max_budget?"Unlimited":`$${(0,B.formatNumberWithCommas)(o.litellm_budget_table.max_budget,4)}`]}),o.litellm_budget_table.budget_duration&&(0,t.jsxs)(S.Text,{className:"text-gray-500",children:["Reset: ",o.litellm_budget_table.budget_duration]})]})]}),(0,t.jsxs)(h.Card,{children:[(0,t.jsx)(S.Text,{children:"Rate Limits"}),(0,t.jsxs)("div",{className:"mt-2",children:[(0,t.jsxs)(S.Text,{children:["TPM: ",o.litellm_budget_table.tpm_limit||"Unlimited"]}),(0,t.jsxs)(S.Text,{children:["RPM: ",o.litellm_budget_table.rpm_limit||"Unlimited"]}),o.litellm_budget_table.max_parallel_requests&&(0,t.jsxs)(S.Text,{children:["Max Parallel Requests: ",o.litellm_budget_table.max_parallel_requests]})]})]}),(0,t.jsxs)(h.Card,{children:[(0,t.jsx)(S.Text,{children:"Models"}),(0,t.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:0===o.models.length?(0,t.jsx)(m.Badge,{color:"red",children:"All proxy models"}):o.models.map((e,a)=>(0,t.jsx)(m.Badge,{color:"red",children:e},a))})]}),(0,t.jsxs)(h.Card,{children:[(0,t.jsx)(S.Text,{children:"Teams"}),(0,t.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:o.teams?.map((e,a)=>(0,t.jsx)(m.Badge,{color:"red",children:R[e.team_id]||e.team_id},a))})]}),(0,t.jsx)(ea.default,{objectPermission:o.object_permission,variant:"card",accessToken:i})]})},{key:"members",label:"Members",children:(0,t.jsx)("div",{className:"space-y-4",children:(0,t.jsx)(ee.default,{members:(o.members||[]).map(e=>({role:e.user_role||"",user_id:e.user_id,user_email:e.user_email})),canEdit:F,onEdit:e=>{C(e),y(!0)},onDelete:e=>en(e),onAddMember:()=>j(!0),roleColumnTitle:"Organization Role",extraColumns:ec,emptyText:"No members found"})})},{key:"settings",label:"Settings",children:(0,t.jsxs)(h.Card,{className:"overflow-y-auto max-h-[65vh]",children:[(0,t.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,t.jsx)(Q.Title,{children:"Organization Settings"}),F&&!b&&(0,t.jsx)(g.Button,{onClick:()=>f(!0),children:"Edit Settings"})]}),b?(0,t.jsxs)(k.Form,{form:x,onFinish:eo,initialValues:{organization_alias:o.organization_alias,models:o.models,tpm_limit:o.litellm_budget_table.tpm_limit,rpm_limit:o.litellm_budget_table.rpm_limit,max_budget:o.litellm_budget_table.max_budget,budget_duration:o.litellm_budget_table.budget_duration,metadata:o.metadata?JSON.stringify(o.metadata,null,2):"",vector_stores:o.object_permission?.vector_stores||[],mcp_servers_and_groups:{servers:o.object_permission?.mcp_servers||[],accessGroups:o.object_permission?.mcp_access_groups||[]}},layout:"vertical",children:[(0,t.jsx)(k.Form.Item,{label:"Organization Name",name:"organization_alias",rules:[{required:!0,message:"Please input an organization name"}],children:(0,t.jsx)($.TextInput,{})}),(0,t.jsx)(k.Form.Item,{label:"Models",name:"models",children:(0,t.jsx)(H.ModelSelect,{value:x.getFieldValue("models"),onChange:e=>x.setFieldValue("models",e),context:"organization",options:{includeSpecialOptions:!0,showAllProxyModelsOverride:!0}})}),(0,t.jsx)(k.Form.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,t.jsx)(ei.default,{step:.01,precision:2,style:{width:"100%"}})}),(0,t.jsx)(k.Form.Item,{label:"Reset Budget",name:"budget_duration",children:(0,t.jsxs)(M.Select,{placeholder:"n/a",children:[(0,t.jsx)(M.Select.Option,{value:"24h",children:"daily"}),(0,t.jsx)(M.Select.Option,{value:"7d",children:"weekly"}),(0,t.jsx)(M.Select.Option,{value:"30d",children:"monthly"})]})}),(0,t.jsx)(k.Form.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,t.jsx)(ei.default,{step:1,style:{width:"100%"}})}),(0,t.jsx)(k.Form.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,t.jsx)(ei.default,{step:1,style:{width:"100%"}})}),(0,t.jsx)(k.Form.Item,{label:"Vector Stores",name:"vector_stores",children:(0,t.jsx)(el.default,{onChange:e=>x.setFieldValue("vector_stores",e),value:x.getFieldValue("vector_stores"),accessToken:i||"",placeholder:"Select vector stores"})}),(0,t.jsx)(k.Form.Item,{label:"MCP Servers & Access Groups",name:"mcp_servers_and_groups",children:(0,t.jsx)(L.default,{onChange:e=>x.setFieldValue("mcp_servers_and_groups",e),value:x.getFieldValue("mcp_servers_and_groups"),accessToken:i||"",placeholder:"Select MCP servers and access groups"})}),(0,t.jsx)(k.Form.Item,{label:"Metadata",name:"metadata",children:(0,t.jsx)(I.Input.TextArea,{rows:4})}),(0,t.jsx)("div",{className:"sticky z-10 bg-white p-4 border-t border-gray-200 bottom-[-1.5rem] inset-x-[-1.5rem]",children:(0,t.jsxs)("div",{className:"flex justify-end items-center gap-2",children:[(0,t.jsx)(g.Button,{variant:"secondary",onClick:()=>f(!1),disabled:z,children:"Cancel"}),(0,t.jsx)(g.Button,{type:"submit",loading:z,children:"Save Changes"})]})})]}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(S.Text,{className:"font-medium",children:"Organization Name"}),(0,t.jsx)("div",{children:o.organization_alias})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(S.Text,{className:"font-medium",children:"Organization ID"}),(0,t.jsx)("div",{className:"font-mono",children:o.organization_id})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(S.Text,{className:"font-medium",children:"Created At"}),(0,t.jsx)("div",{children:new Date(o.created_at).toLocaleString()})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(S.Text,{className:"font-medium",children:"Models"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:o.models.map((e,a)=>(0,t.jsx)(m.Badge,{color:"red",children:e},a))})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(S.Text,{className:"font-medium",children:"Rate Limits"}),(0,t.jsxs)("div",{children:["TPM: ",o.litellm_budget_table.tpm_limit||"Unlimited"]}),(0,t.jsxs)("div",{children:["RPM: ",o.litellm_budget_table.rpm_limit||"Unlimited"]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(S.Text,{className:"font-medium",children:"Budget"}),(0,t.jsxs)("div",{children:["Max:"," ",null!==o.litellm_budget_table.max_budget?`$${(0,B.formatNumberWithCommas)(o.litellm_budget_table.max_budget,4)}`:"No Limit"]}),(0,t.jsxs)("div",{children:["Reset: ",o.litellm_budget_table.budget_duration||"Never"]})]}),(0,t.jsx)(ea.default,{objectPermission:o.object_permission,variant:"inline",className:"pt-4 border-t border-gray-200",accessToken:i})]})]})}]}),(0,t.jsx)(et.default,{isVisible:_,onCancel:()=>j(!1),onSubmit:A,accessToken:i,title:"Add Organization Member",roles:[{label:"org_admin",value:"org_admin",description:"Can add and remove members, and change their roles."},{label:"internal_user",value:"internal_user",description:"Can view/create keys for themselves within organization."},{label:"internal_user_viewer",value:"internal_user_viewer",description:"Can only view their keys within organization."}],defaultRole:"internal_user"}),(0,t.jsx)(er.default,{visible:v,onCancel:()=>y(!1),onSubmit:es,initialData:w,mode:"edit",config:{title:"Edit Member",showEmail:!0,showUserId:!0,roleOptions:[{label:"Org Admin",value:"org_admin"},{label:"Internal User",value:"internal_user"},{label:"Internal User Viewer",value:"internal_user_viewer"}]}})]})},en=async(e,t,a=null,i=null)=>{t(await (0,q.organizationListCall)(e,a,i))};e.s(["default",0,({organizations:e,userRole:a,userModels:i,accessToken:r,lastRefreshed:l,handleRefreshClick:s,currentOrg:V,guardrailsList:W=[],setOrganizations:K,premiumUser:Q})=>{let[G,Z]=(0,E.useState)(null),[J,Y]=(0,E.useState)(!1),[X,ee]=(0,E.useState)(!1),[et,ea]=(0,E.useState)(null),[er,eo]=(0,E.useState)(!1),[ed,ec]=(0,E.useState)(!1),[eu]=k.Form.useForm(),[em,eg]=(0,E.useState)({}),[eh,ex]=(0,E.useState)(!1),[ep,eb]=(0,E.useState)({org_id:"",org_alias:"",sort_by:"created_at",sort_order:"desc"}),ef=async()=>{if(et&&r)try{eo(!0),await (0,q.organizationDeleteCall)(r,et),U.default.success("Organization deleted successfully"),ee(!1),ea(null),await en(r,K,ep.org_id||null,ep.org_alias||null)}catch(e){console.error("Error deleting organization:",e)}finally{eo(!1)}},e_=async e=>{try{if(!r)return;console.log(`values in organizations new create call: ${JSON.stringify(e)}`),(e.allowed_vector_store_ids&&e.allowed_vector_store_ids.length>0||e.allowed_mcp_servers_and_groups&&(e.allowed_mcp_servers_and_groups.servers?.length>0||e.allowed_mcp_servers_and_groups.accessGroups?.length>0))&&(e.object_permission={},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&&(e.allowed_mcp_servers_and_groups.servers?.length>0&&(e.object_permission.mcp_servers=e.allowed_mcp_servers_and_groups.servers),e.allowed_mcp_servers_and_groups.accessGroups?.length>0&&(e.object_permission.mcp_access_groups=e.allowed_mcp_servers_and_groups.accessGroups),delete e.allowed_mcp_servers_and_groups)),await (0,q.organizationCreateCall)(r,e),U.default.success("Organization created successfully"),ec(!1),eu.resetFields(),en(r,K,ep.org_id||null,ep.org_alias||null)}catch(e){console.error("Error creating organization:",e)}};return Q?(0,t.jsxs)("div",{className:"w-full mx-4 h-[75vh]",children:[(0,t.jsx)(p.Grid,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:(0,t.jsxs)(x.Col,{numColSpan:1,className:"flex flex-col gap-2",children:[("Admin"===a||"Org Admin"===a)&&(0,t.jsx)(g.Button,{className:"w-fit",onClick:()=>ec(!0),children:"+ Create New Organization"}),G?(0,t.jsx)(es,{organizationId:G,onClose:()=>{Z(null),Y(!1)},accessToken:r,is_org_admin:!0,is_proxy_admin:"Admin"===a,userModels:i,editOrg:J}):(0,t.jsxs)(_.TabGroup,{className:"gap-2 h-[75vh] w-full",children:[(0,t.jsxs)(T.TabList,{className:"flex justify-between mt-2 w-full items-center",children:[(0,t.jsx)("div",{className:"flex",children:(0,t.jsx)(f.Tab,{children:"Your Organizations"})}),(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[l&&(0,t.jsxs)(S.Text,{children:["Last Refreshed: ",l]}),(0,t.jsx)(b.Icon,{icon:u.RefreshIcon,variant:"shadow",size:"xs",className:"self-center",onClick:s})]})]}),(0,t.jsx)(O.TabPanels,{children:(0,t.jsxs)(z.TabPanel,{children:[(0,t.jsx)(S.Text,{children:"Click on “Organization ID” to view organization details."}),(0,t.jsx)(p.Grid,{numItems:1,className:"gap-2 pt-2 pb-2 h-[75vh] w-full mt-2",children:(0,t.jsx)(x.Col,{numColSpan:1,children:(0,t.jsxs)(h.Card,{className:"w-full mx-auto flex-auto overflow-hidden overflow-y-auto max-h-[50vh]",children:[(0,t.jsx)("div",{className:"border-b px-6 py-4",children:(0,t.jsx)("div",{className:"flex flex-col space-y-4",children:(0,t.jsx)(n,{filters:ep,showFilters:eh,onToggleFilters:ex,onChange:(e,t)=>{let a={...ep,[e]:t};eb(a),r&&(0,q.organizationListCall)(r,a.org_id||null,a.org_alias||null).then(e=>{e&&K(e)}).catch(e=>{console.error("Error fetching organizations:",e)})},onReset:()=>{eb({org_id:"",org_alias:"",sort_by:"created_at",sort_order:"desc"}),r&&(0,q.organizationListCall)(r,null,null).then(e=>{e&&K(e)}).catch(e=>{console.error("Error fetching organizations:",e)})}})})}),(0,t.jsxs)(j.Table,{children:[(0,t.jsx)(w.TableHead,{children:(0,t.jsxs)(N.TableRow,{children:[(0,t.jsx)(C.TableHeaderCell,{children:"Organization ID"}),(0,t.jsx)(C.TableHeaderCell,{children:"Organization Name"}),(0,t.jsx)(C.TableHeaderCell,{children:"Created"}),(0,t.jsx)(C.TableHeaderCell,{children:"Spend (USD)"}),(0,t.jsx)(C.TableHeaderCell,{children:"Budget (USD)"}),(0,t.jsx)(C.TableHeaderCell,{children:"Models"}),(0,t.jsx)(C.TableHeaderCell,{children:"TPM / RPM Limits"}),(0,t.jsx)(C.TableHeaderCell,{children:"Info"}),(0,t.jsx)(C.TableHeaderCell,{children:"Actions"})]})}),(0,t.jsx)(v.TableBody,{children:e&&e.length>0?e.sort((e,t)=>new Date(t.created_at).getTime()-new Date(e.created_at).getTime()).map(e=>(0,t.jsxs)(N.TableRow,{children:[(0,t.jsx)(y.TableCell,{children:(0,t.jsx)("div",{className:"overflow-hidden",children:(0,t.jsx)(P.Tooltip,{title:e.organization_id,children:(0,t.jsxs)(g.Button,{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:()=>Z(e.organization_id),children:[e.organization_id?.slice(0,7),"..."]})})})}),(0,t.jsx)(y.TableCell,{children:e.organization_alias}),(0,t.jsx)(y.TableCell,{children:e.created_at?new Date(e.created_at).toLocaleDateString():"N/A"}),(0,t.jsx)(y.TableCell,{children:(0,B.formatNumberWithCommas)(e.spend,4)}),(0,t.jsx)(y.TableCell,{children:e.litellm_budget_table?.max_budget!==null&&e.litellm_budget_table?.max_budget!==void 0?e.litellm_budget_table?.max_budget:"No limit"}),(0,t.jsx)(y.TableCell,{style:{maxWidth:"8-x",whiteSpace:"pre-wrap",overflow:"hidden"},className:e.models.length>3?"px-0":"",children:(0,t.jsx)("div",{className:"flex flex-col",children:Array.isArray(e.models)?(0,t.jsx)("div",{className:"flex flex-col",children:0===e.models.length?(0,t.jsx)(m.Badge,{size:"xs",className:"mb-1",color:"red",children:(0,t.jsx)(S.Text,{children:"All Proxy Models"})}):(0,t.jsx)(t.Fragment,{children:(0,t.jsxs)("div",{className:"flex items-start",children:[e.models.length>3&&(0,t.jsx)("div",{children:(0,t.jsx)(b.Icon,{icon:em[e.organization_id||""]?d.ChevronDownIcon:c.ChevronRightIcon,className:"cursor-pointer",size:"xs",onClick:()=>{eg(t=>({...t,[e.organization_id||""]:!t[e.organization_id||""]}))}})}),(0,t.jsxs)("div",{className:"flex flex-wrap gap-1",children:[e.models.slice(0,3).map((e,a)=>"all-proxy-models"===e?(0,t.jsx)(m.Badge,{size:"xs",color:"red",children:(0,t.jsx)(S.Text,{children:"All Proxy Models"})},a):(0,t.jsx)(m.Badge,{size:"xs",color:"blue",children:(0,t.jsx)(S.Text,{children:e.length>30?`${(0,A.getModelDisplayName)(e).slice(0,30)}...`:(0,A.getModelDisplayName)(e)})},a)),e.models.length>3&&!em[e.organization_id||""]&&(0,t.jsx)(m.Badge,{size:"xs",color:"gray",className:"cursor-pointer",children:(0,t.jsxs)(S.Text,{children:["+",e.models.length-3," ",e.models.length-3==1?"more model":"more models"]})}),em[e.organization_id||""]&&(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:e.models.slice(3).map((e,a)=>"all-proxy-models"===e?(0,t.jsx)(m.Badge,{size:"xs",color:"red",children:(0,t.jsx)(S.Text,{children:"All Proxy Models"})},a+3):(0,t.jsx)(m.Badge,{size:"xs",color:"blue",children:(0,t.jsx)(S.Text,{children:e.length>30?`${(0,A.getModelDisplayName)(e).slice(0,30)}...`:(0,A.getModelDisplayName)(e)})},a+3))})]})]})})}):null})}),(0,t.jsx)(y.TableCell,{children:(0,t.jsxs)(S.Text,{children:["TPM:"," ",e.litellm_budget_table?.tpm_limit?e.litellm_budget_table?.tpm_limit:"Unlimited",(0,t.jsx)("br",{}),"RPM:"," ",e.litellm_budget_table?.rpm_limit?e.litellm_budget_table?.rpm_limit:"Unlimited"]})}),(0,t.jsx)(y.TableCell,{children:(0,t.jsxs)(S.Text,{children:[e.members?.length||0," Members"]})}),(0,t.jsx)(y.TableCell,{children:"Admin"===a&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(D.default,{variant:"Edit",tooltipText:"Edit organization",onClick:()=>{Z(e.organization_id),Y(!0)}}),(0,t.jsx)(D.default,{variant:"Delete",tooltipText:"Delete organization",onClick:()=>{var t;(t=e.organization_id)&&(ea(t),ee(!0))}})]})})]},e.organization_id)):null})]})]})})})]})})]})]})}),(0,t.jsx)(F.Modal,{title:"Create Organization",visible:ed,width:800,footer:null,onCancel:()=>{ec(!1),eu.resetFields()},children:(0,t.jsxs)(k.Form,{form:eu,onFinish:e_,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,t.jsx)(k.Form.Item,{label:"Organization Name",name:"organization_alias",rules:[{required:!0,message:"Please input an organization name"}],children:(0,t.jsx)($.TextInput,{placeholder:""})}),(0,t.jsx)(k.Form.Item,{label:"Models",name:"models",children:(0,t.jsx)(H.ModelSelect,{options:{showAllProxyModelsOverride:!0,includeSpecialOptions:!0},value:eu.getFieldValue("models"),onChange:e=>eu.setFieldValue("models",e),context:"organization"})}),(0,t.jsx)(k.Form.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,t.jsx)(ei.default,{step:.01,precision:2,width:200})}),(0,t.jsx)(k.Form.Item,{label:"Reset Budget",name:"budget_duration",children:(0,t.jsxs)(M.Select,{defaultValue:null,placeholder:"n/a",children:[(0,t.jsx)(M.Select.Option,{value:"24h",children:"daily"}),(0,t.jsx)(M.Select.Option,{value:"7d",children:"weekly"}),(0,t.jsx)(M.Select.Option,{value:"30d",children:"monthly"})]})}),(0,t.jsx)(k.Form.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,t.jsx)(ei.default,{step:1,width:400})}),(0,t.jsx)(k.Form.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,t.jsx)(ei.default,{step:1,width:400})}),(0,t.jsx)(k.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Vector Stores"," ",(0,t.jsx)(P.Tooltip,{title:"Select which vector stores this organization can access by default. Leave empty for access to all vector stores",children:(0,t.jsx)(o.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_vector_store_ids",className:"mt-4",help:"Select vector stores this organization can access. Leave empty for access to all vector stores",children:(0,t.jsx)(el.default,{onChange:e=>eu.setFieldValue("allowed_vector_store_ids",e),value:eu.getFieldValue("allowed_vector_store_ids"),accessToken:r||"",placeholder:"Select vector stores (optional)"})}),(0,t.jsx)(k.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed MCP Servers"," ",(0,t.jsx)(P.Tooltip,{title:"Select which MCP servers and access groups this organization can access by default.",children:(0,t.jsx)(o.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_mcp_servers_and_groups",className:"mt-4",help:"Select MCP servers and access groups this organization can access.",children:(0,t.jsx)(L.default,{onChange:e=>eu.setFieldValue("allowed_mcp_servers_and_groups",e),value:eu.getFieldValue("allowed_mcp_servers_and_groups"),accessToken:r||"",placeholder:"Select MCP servers and access groups (optional)"})}),(0,t.jsx)(k.Form.Item,{label:"Metadata",name:"metadata",children:(0,t.jsx)(I.Input.TextArea,{rows:4})}),(0,t.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,t.jsx)(g.Button,{type:"submit",children:"Create Organization"})})]})}),(0,t.jsx)(R.default,{isOpen:X,title:"Delete Organization?",message:"Are you sure you want to delete this organization? This action cannot be undone.",resourceInformationTitle:"Organization Information",resourceInformation:[{label:"Organization ID",value:et,code:!0}],onCancel:()=>{ee(!1),ea(null)},onOk:ef,confirmLoading:er})]}):(0,t.jsx)("div",{children:(0,t.jsxs)(S.Text,{children:["This is a LiteLLM Enterprise feature, and requires a valid key to use. Get a trial key"," ",(0,t.jsx)("a",{href:"https://www.litellm.ai/#pricing",target:"_blank",rel:"noopener noreferrer",children:"here"}),"."]})})},"fetchOrganizations",0,en],846835)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/3e16ca85d4f4e974.js b/litellm/proxy/_experimental/out/_next/static/chunks/3e16ca85d4f4e974.js deleted file mode 100644 index 1fa79f02e23..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/3e16ca85d4f4e974.js +++ /dev/null @@ -1,179 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,976883,174886,e=>{"use strict";var s=e.i(843476),t=e.i(275144),l=e.i(434626),a=e.i(271645);let r=a.forwardRef(function(e,s){return a.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:s},e),a.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"}))});var i=e.i(994388),n=e.i(304967),c=e.i(599724),o=e.i(629569),d=e.i(212931),x=e.i(199133),m=e.i(653496),h=e.i(262218),u=e.i(592968),p=e.i(991124);e.s(["Copy",()=>p.default],174886);var p=p,g=e.i(879664),g=g,j=e.i(798496),b=e.i(727749),f=e.i(402874),v=e.i(764205),_=e.i(190272),N=e.i(785913),y=e.i(916925);let{TabPane:T}=m.Tabs;e.s(["default",0,({accessToken:e,isEmbedded:w=!1})=>{let S,C,k,A,M,P,L,[z,E]=(0,a.useState)(null),[O,D]=(0,a.useState)(null),[K,R]=(0,a.useState)(null),[I,U]=(0,a.useState)("LiteLLM Gateway"),[H,F]=(0,a.useState)(null),[W,$]=(0,a.useState)(""),[B,q]=(0,a.useState)({}),[G,V]=(0,a.useState)(!0),[X,J]=(0,a.useState)(!0),[Y,Q]=(0,a.useState)(!0),[Z,ee]=(0,a.useState)(""),[es,et]=(0,a.useState)(""),[el,ea]=(0,a.useState)(""),[er,ei]=(0,a.useState)([]),[en,ec]=(0,a.useState)([]),[eo,ed]=(0,a.useState)([]),[ex,em]=(0,a.useState)([]),[eh,eu]=(0,a.useState)([]),[ep,eg]=(0,a.useState)("I'm alive! ✓"),[ej,eb]=(0,a.useState)(!1),[ef,ev]=(0,a.useState)(!1),[e_,eN]=(0,a.useState)(!1),[ey,eT]=(0,a.useState)(null),[ew,eS]=(0,a.useState)(null),[eC,ek]=(0,a.useState)(null),[eA,eM]=(0,a.useState)({}),[eP,eL]=(0,a.useState)("models");(0,a.useEffect)(()=>{(async()=>{try{await (0,v.getUiConfig)()}catch(e){console.error("Failed to get UI config:",e)}let e=async()=>{try{V(!0);let e=await (0,v.modelHubPublicModelsCall)();console.log("ModelHubData:",e),E(e)}catch(e){console.error("There was an error fetching the public model data",e),eg("Service unavailable")}finally{V(!1)}},s=async()=>{try{J(!0);let e=await (0,v.agentHubPublicModelsCall)();console.log("AgentHubData:",e),D(e)}catch(e){console.error("There was an error fetching the public agent data",e)}finally{J(!1)}},t=async()=>{try{Q(!0);let e=await (0,v.mcpHubPublicServersCall)();console.log("MCPHubData:",e),R(e)}catch(e){console.error("There was an error fetching the public MCP server data",e)}finally{Q(!1)}};(async()=>{let e=await (0,v.getPublicModelHubInfo)();console.log("Public Model Hub Info:",e),U(e.docs_title),F(e.custom_docs_description),$(e.litellm_version),q(e.useful_links||{})})(),e(),s(),t()})()},[]),(0,a.useEffect)(()=>{},[Z,er,en,eo]);let ez=(0,a.useMemo)(()=>{if(!z||!Array.isArray(z))return[];let e=z;if(Z.trim()){let s=Z.toLowerCase(),t=s.split(/\s+/),l=z.filter(e=>{let l=e.model_group.toLowerCase();return!!l.includes(s)||t.every(e=>l.includes(e))});l.length>0&&(e=l.sort((e,t)=>{let l=e.model_group.toLowerCase(),a=t.model_group.toLowerCase(),r=1e3*(l===s),i=1e3*(a===s),n=100*!!l.startsWith(s),c=100*!!a.startsWith(s),o=50*!!s.split(/\s+/).every(e=>l.includes(e)),d=50*!!s.split(/\s+/).every(e=>a.includes(e)),x=l.length;return i+c+d+(1e3-a.length)-(r+n+o+(1e3-x))}))}return e.filter(e=>{let s=0===er.length||er.some(s=>e.providers.includes(s)),t=0===en.length||en.includes(e.mode||""),l=0===eo.length||Object.entries(e).filter(([e,s])=>e.startsWith("supports_")&&!0===s).some(([e])=>{let s=e.replace(/^supports_/,"").split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");return eo.includes(s)});return s&&t&&l})},[z,Z,er,en,eo]),eE=(0,a.useMemo)(()=>{if(!O||!Array.isArray(O))return[];let e=O;if(es.trim()){let s=es.toLowerCase(),t=s.split(/\s+/);e=(e=O.filter(e=>{let l=e.name.toLowerCase(),a=e.description.toLowerCase();return!!(l.includes(s)||a.includes(s))||t.every(e=>l.includes(e)||a.includes(e))})).sort((e,t)=>{let l=e.name.toLowerCase(),a=t.name.toLowerCase(),r=1e3*(l===s),i=1e3*(a===s),n=100*!!l.startsWith(s),c=100*!!a.startsWith(s),o=r+n+(1e3-l.length);return i+c+(1e3-a.length)-o})}return e.filter(e=>0===ex.length||e.skills?.some(e=>e.tags?.some(e=>ex.includes(e))))},[O,es,ex]),eO=(0,a.useMemo)(()=>{if(!K||!Array.isArray(K))return[];let e=K;if(el.trim()){let s=el.toLowerCase(),t=s.split(/\s+/);e=(e=K.filter(e=>{let l=e.server_name.toLowerCase(),a=(e.mcp_info?.description||"").toLowerCase();return!!(l.includes(s)||a.includes(s))||t.every(e=>l.includes(e)||a.includes(e))})).sort((e,t)=>{let l=e.server_name.toLowerCase(),a=t.server_name.toLowerCase(),r=1e3*(l===s),i=1e3*(a===s),n=100*!!l.startsWith(s),c=100*!!a.startsWith(s),o=r+n+(1e3-l.length);return i+c+(1e3-a.length)-o})}return e.filter(e=>0===eh.length||eh.includes(e.transport))},[K,el,eh]),eD=e=>{navigator.clipboard.writeText(e),b.default.success("Copied to clipboard!")},eK=e=>e.replace(/^supports_/,"").split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" "),eR=e=>`$${(1e6*e).toFixed(4)}`,eI=e=>e?e>=1e3?`${(e/1e3).toFixed(0)}K`:e.toString():"N/A";return(0,s.jsx)(t.ThemeProvider,{accessToken:e,children:(0,s.jsxs)("div",{className:w?"w-full":"min-h-screen bg-white",children:[!w&&(0,s.jsx)(f.default,{userID:null,userEmail:null,userRole:null,premiumUser:!1,setProxySettings:eM,proxySettings:eA,accessToken:e||null,isPublicPage:!0,isDarkMode:!1,toggleDarkMode:()=>{}}),(0,s.jsxs)("div",{className:w?"w-full p-6":"w-full px-8 py-12",children:[w&&(0,s.jsx)("div",{className:"mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg",children:(0,s.jsx)("p",{className:"text-sm text-gray-700",children:"These are models, agents, and MCP servers your proxy admin has indicated are available in your company."})}),!w&&(0,s.jsxs)(n.Card,{className:"mb-10 p-8 bg-white border border-gray-200 rounded-lg shadow-sm",children:[(0,s.jsx)(o.Title,{className:"text-2xl font-semibold mb-6 text-gray-900",children:"About"}),(0,s.jsx)("p",{className:"text-gray-700 mb-6 text-base leading-relaxed",children:H||"Proxy Server to call 100+ LLMs in the OpenAI format."}),(0,s.jsx)("div",{className:"flex items-center space-x-3 text-sm text-gray-600",children:(0,s.jsxs)("span",{className:"flex items-center",children:[(0,s.jsx)("span",{className:"w-4 h-4 mr-2",children:"🔧"}),"Built with litellm: v",W]})})]}),B&&Object.keys(B).length>0&&(0,s.jsxs)(n.Card,{className:"mb-10 p-8 bg-white border border-gray-200 rounded-lg shadow-sm",children:[(0,s.jsx)(o.Title,{className:"text-2xl font-semibold mb-6 text-gray-900",children:"Useful Links"}),(0,s.jsx)("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:Object.entries(B||{}).map(([e,s])=>({title:e,url:"string"==typeof s?s:s.url,index:"string"==typeof s?0:s.index??0})).sort((e,s)=>e.index-s.index).map(({title:e,url:t})=>(0,s.jsxs)("button",{onClick:()=>window.open(t,"_blank"),className:"flex items-center space-x-3 text-blue-600 hover:text-blue-800 transition-colors p-3 rounded-lg hover:bg-blue-50 border border-gray-200",children:[(0,s.jsx)(l.ExternalLinkIcon,{className:"w-4 h-4"}),(0,s.jsx)(c.Text,{className:"text-sm font-medium",children:e})]},e))})]}),!w&&(0,s.jsxs)(n.Card,{className:"mb-10 p-8 bg-white border border-gray-200 rounded-lg shadow-sm",children:[(0,s.jsx)(o.Title,{className:"text-2xl font-semibold mb-6 text-gray-900",children:"Health and Endpoint Status"}),(0,s.jsx)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:(0,s.jsxs)(c.Text,{className:"text-green-600 font-medium text-sm",children:["Service status: ",ep]})})]}),(0,s.jsx)(n.Card,{className:"p-8 bg-white border border-gray-200 rounded-lg shadow-sm",children:(0,s.jsxs)(m.Tabs,{activeKey:eP,onChange:eL,size:"large",className:"public-hub-tabs",children:[(0,s.jsxs)(T,{tab:"Model Hub",children:[(0,s.jsx)("div",{className:"flex justify-between items-center mb-8",children:(0,s.jsx)(o.Title,{className:"text-2xl font-semibold text-gray-900",children:"Available Models"})}),(0,s.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8 p-6 bg-gray-50 rounded-lg border border-gray-200",children:[(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center space-x-2 mb-3",children:[(0,s.jsx)(c.Text,{className:"text-sm font-medium text-gray-700",children:"Search Models:"}),(0,s.jsx)(u.Tooltip,{title:"Smart search with relevance ranking - finds models containing your search terms, ranked by relevance. Try searching 'xai grok-4', 'claude-4', 'gpt-4', or 'sonnet'",placement:"top",children:(0,s.jsx)(g.default,{className:"w-4 h-4 text-gray-400 cursor-help"})})]}),(0,s.jsxs)("div",{className:"relative",children:[(0,s.jsx)(r,{className:"w-4 h-4 text-gray-400 absolute left-3 top-1/2 transform -translate-y-1/2"}),(0,s.jsx)("input",{type:"text",placeholder:"Search model names... (smart search enabled)",value:Z,onChange:e=>ee(e.target.value),className:"border border-gray-300 rounded-lg pl-10 pr-4 py-2 w-full text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white"})]})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"text-sm font-medium mb-3 text-gray-700",children:"Provider:"}),(0,s.jsx)(x.Select,{mode:"multiple",value:er,onChange:e=>ei(e),placeholder:"Select providers",className:"w-full",size:"large",allowClear:!0,optionRender:e=>{let{logo:t}=(0,y.getProviderLogoAndName)(e.value);return(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[t&&(0,s.jsx)("img",{src:t,alt:e.label,className:"w-5 h-5 flex-shrink-0 object-contain",onError:e=>{e.target.style.display="none"}}),(0,s.jsx)("span",{className:"capitalize",children:e.label})]})},children:z&&Array.isArray(z)&&(S=new Set,z.forEach(e=>{e.providers.forEach(e=>S.add(e))}),Array.from(S)).map(e=>(0,s.jsx)(x.Select.Option,{value:e,children:e},e))})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"text-sm font-medium mb-3 text-gray-700",children:"Mode:"}),(0,s.jsx)(x.Select,{mode:"multiple",value:en,onChange:e=>ec(e),placeholder:"Select modes",className:"w-full",size:"large",allowClear:!0,children:z&&Array.isArray(z)&&(C=new Set,z.forEach(e=>{e.mode&&C.add(e.mode)}),Array.from(C)).map(e=>(0,s.jsx)(x.Select.Option,{value:e,children:e},e))})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"text-sm font-medium mb-3 text-gray-700",children:"Features:"}),(0,s.jsx)(x.Select,{mode:"multiple",value:eo,onChange:e=>ed(e),placeholder:"Select features",className:"w-full",size:"large",allowClear:!0,children:z&&Array.isArray(z)&&(k=new Set,z.forEach(e=>{Object.entries(e).filter(([e,s])=>e.startsWith("supports_")&&!0===s).forEach(([e])=>{let s=e.replace(/^supports_/,"").split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");k.add(s)})}),Array.from(k).sort()).map(e=>(0,s.jsx)(x.Select.Option,{value:e,children:e},e))})]})]}),(0,s.jsx)(j.ModelDataTable,{columns:[{header:"Model Name",accessorKey:"model_group",enableSorting:!0,cell:({row:e})=>(0,s.jsx)("div",{className:"overflow-hidden",children:(0,s.jsx)(u.Tooltip,{title:e.original.model_group,children:(0,s.jsx)(i.Button,{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",onClick:()=>{eT(e.original),eb(!0)},children:e.original.model_group})})}),size:150},{header:"Providers",accessorKey:"providers",enableSorting:!0,cell:({row:e})=>{let t=e.original.providers;return(0,s.jsx)("div",{className:"flex flex-wrap gap-1",children:t.map(e=>{let{logo:t}=(0,y.getProviderLogoAndName)(e);return(0,s.jsxs)("div",{className:"flex items-center space-x-1 px-2 py-1 bg-gray-100 rounded text-xs",children:[t&&(0,s.jsx)("img",{src:t,alt:e,className:"w-3 h-3 flex-shrink-0 object-contain",onError:e=>{e.target.style.display="none"}}),(0,s.jsx)("span",{className:"capitalize",children:e})]},e)})})},size:120},{header:"Mode",accessorKey:"mode",enableSorting:!0,cell:({row:e})=>{let t=e.original.mode;return(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,s.jsx)("span",{children:(e=>{switch(e?.toLowerCase()){case"chat":return"💬";case"rerank":return"🔄";case"embedding":return"📄";default:return"🤖"}})(t||"")}),(0,s.jsx)(c.Text,{children:t||"Chat"})]})},size:100},{header:"Max Input",accessorKey:"max_input_tokens",enableSorting:!0,cell:({row:e})=>(0,s.jsx)(c.Text,{className:"text-center",children:eI(e.original.max_input_tokens)}),size:100,meta:{className:"text-center"}},{header:"Max Output",accessorKey:"max_output_tokens",enableSorting:!0,cell:({row:e})=>(0,s.jsx)(c.Text,{className:"text-center",children:eI(e.original.max_output_tokens)}),size:100,meta:{className:"text-center"}},{header:"Input $/1M",accessorKey:"input_cost_per_token",enableSorting:!0,cell:({row:e})=>{let t=e.original.input_cost_per_token;return(0,s.jsx)(c.Text,{className:"text-center",children:t?eR(t):"Free"})},size:100,meta:{className:"text-center"}},{header:"Output $/1M",accessorKey:"output_cost_per_token",enableSorting:!0,cell:({row:e})=>{let t=e.original.output_cost_per_token;return(0,s.jsx)(c.Text,{className:"text-center",children:t?eR(t):"Free"})},size:100,meta:{className:"text-center"}},{header:"Features",accessorKey:"supports_vision",enableSorting:!1,cell:({row:e})=>{let t=Object.entries(e.original).filter(([e,s])=>e.startsWith("supports_")&&!0===s).map(([e])=>eK(e));return 0===t.length?(0,s.jsx)(c.Text,{className:"text-gray-400",children:"-"}):1===t.length?(0,s.jsx)("div",{className:"h-6 flex items-center",children:(0,s.jsx)(h.Tag,{color:"blue",className:"text-xs",children:t[0]})}):(0,s.jsxs)("div",{className:"h-6 flex items-center space-x-1",children:[(0,s.jsx)(h.Tag,{color:"blue",className:"text-xs",children:t[0]}),(0,s.jsx)(u.Tooltip,{title:(0,s.jsxs)("div",{className:"space-y-1",children:[(0,s.jsx)("div",{className:"font-medium",children:"All Features:"}),t.map((e,t)=>(0,s.jsxs)("div",{className:"text-xs",children:["• ",e]},t))]}),trigger:"click",placement:"topLeft",children:(0,s.jsxs)("span",{className:"text-xs text-blue-600 cursor-pointer hover:text-blue-800 hover:underline",onClick:e=>e.stopPropagation(),children:["+",t.length-1]})})]})},size:120},{header:"Health Status",accessorKey:"health_status",enableSorting:!0,cell:({row:e})=>{let t=e.original,l="healthy"===t.health_status?"green":"unhealthy"===t.health_status?"red":"default",a=t.health_response_time?`Response Time: ${Number(t.health_response_time).toFixed(2)}ms`:"N/A",r=t.health_checked_at?`Last Checked: ${new Date(t.health_checked_at).toLocaleString()}`:"N/A";return(0,s.jsx)(u.Tooltip,{title:(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("div",{children:a}),(0,s.jsx)("div",{children:r})]}),children:(0,s.jsx)(h.Tag,{color:l,children:(0,s.jsx)("span",{className:"capitalize",children:t.health_status??"Unknown"})},t.model_group)})},size:100},{header:"Limits",accessorKey:"rpm",enableSorting:!0,cell:({row:e})=>{var t,l;let a,r=e.original;return(0,s.jsx)(c.Text,{className:"text-xs text-gray-600",children:(t=r.rpm,l=r.tpm,a=[],t&&a.push(`RPM: ${t.toLocaleString()}`),l&&a.push(`TPM: ${l.toLocaleString()}`),a.length>0?a.join(", "):"N/A")})},size:150}],data:ez,isLoading:G,defaultSorting:[{id:"model_group",desc:!1}]}),(0,s.jsx)("div",{className:"mt-8 text-center",children:(0,s.jsxs)(c.Text,{className:"text-sm text-gray-600",children:["Showing ",ez.length," of ",z?.length||0," models"]})})]},"models"),O&&Array.isArray(O)&&O.length>0&&(0,s.jsxs)(T,{tab:"Agent Hub",children:[(0,s.jsx)("div",{className:"flex justify-between items-center mb-8",children:(0,s.jsx)(o.Title,{className:"text-2xl font-semibold text-gray-900",children:"Available Agents"})}),(0,s.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6 mb-8 p-6 bg-gray-50 rounded-lg border border-gray-200",children:[(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center space-x-2 mb-3",children:[(0,s.jsx)(c.Text,{className:"text-sm font-medium text-gray-700",children:"Search Agents:"}),(0,s.jsx)(u.Tooltip,{title:"Search agents by name or description",placement:"top",children:(0,s.jsx)(g.default,{className:"w-4 h-4 text-gray-400 cursor-help"})})]}),(0,s.jsxs)("div",{className:"relative",children:[(0,s.jsx)(r,{className:"w-4 h-4 text-gray-400 absolute left-3 top-1/2 transform -translate-y-1/2"}),(0,s.jsx)("input",{type:"text",placeholder:"Search agent names or descriptions...",value:es,onChange:e=>et(e.target.value),className:"border border-gray-300 rounded-lg pl-10 pr-4 py-2 w-full text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white"})]})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"text-sm font-medium mb-3 text-gray-700",children:"Skills:"}),(0,s.jsx)(x.Select,{mode:"multiple",value:ex,onChange:e=>em(e),placeholder:"Select skills",className:"w-full",size:"large",allowClear:!0,children:O&&Array.isArray(O)&&(A=new Set,O.forEach(e=>{e.skills?.forEach(e=>{e.tags?.forEach(e=>A.add(e))})}),Array.from(A).sort()).map(e=>(0,s.jsx)(x.Select.Option,{value:e,children:e},e))})]})]}),(0,s.jsx)(j.ModelDataTable,{columns:[{header:"Agent Name",accessorKey:"name",enableSorting:!0,cell:({row:e})=>(0,s.jsx)("div",{className:"overflow-hidden",children:(0,s.jsx)(u.Tooltip,{title:e.original.name,children:(0,s.jsx)(i.Button,{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",onClick:()=>{eS(e.original),ev(!0)},children:e.original.name})})}),size:150},{header:"Description",accessorKey:"description",enableSorting:!1,cell:({row:e})=>{let t=e.original.description,l=t.length>80?t.substring(0,80)+"...":t;return(0,s.jsx)(u.Tooltip,{title:t,children:(0,s.jsx)(c.Text,{className:"text-sm text-gray-700",children:l})})},size:250},{header:"Version",accessorKey:"version",enableSorting:!0,cell:({row:e})=>(0,s.jsx)(c.Text,{className:"text-sm",children:e.original.version}),size:80},{header:"Provider",accessorKey:"provider",enableSorting:!1,cell:({row:e})=>{let t=e.original.provider;return t?(0,s.jsx)("div",{className:"text-sm",children:(0,s.jsx)(c.Text,{className:"font-medium",children:t.organization})}):(0,s.jsx)(c.Text,{className:"text-gray-400",children:"-"})},size:120},{header:"Skills",accessorKey:"skills",enableSorting:!1,cell:({row:e})=>{let t=e.original.skills||[];return 0===t.length?(0,s.jsx)(c.Text,{className:"text-gray-400",children:"-"}):1===t.length?(0,s.jsx)("div",{className:"h-6 flex items-center",children:(0,s.jsx)(h.Tag,{color:"purple",className:"text-xs",children:t[0].name})}):(0,s.jsxs)("div",{className:"h-6 flex items-center space-x-1",children:[(0,s.jsx)(h.Tag,{color:"purple",className:"text-xs",children:t[0].name}),(0,s.jsx)(u.Tooltip,{title:(0,s.jsxs)("div",{className:"space-y-1",children:[(0,s.jsx)("div",{className:"font-medium",children:"All Skills:"}),t.map((e,t)=>(0,s.jsxs)("div",{className:"text-xs",children:["• ",e.name]},t))]}),trigger:"click",placement:"topLeft",children:(0,s.jsxs)("span",{className:"text-xs text-purple-600 cursor-pointer hover:text-purple-800 hover:underline",onClick:e=>e.stopPropagation(),children:["+",t.length-1]})})]})},size:150},{header:"Capabilities",accessorKey:"capabilities",enableSorting:!1,cell:({row:e})=>{let t=Object.entries(e.original.capabilities||{}).filter(([e,s])=>!0===s).map(([e])=>e);return 0===t.length?(0,s.jsx)(c.Text,{className:"text-gray-400",children:"-"}):(0,s.jsx)("div",{className:"flex flex-wrap gap-1",children:t.map(e=>(0,s.jsx)(h.Tag,{color:"green",className:"text-xs capitalize",children:e},e))})},size:150}],data:eE,isLoading:X,defaultSorting:[{id:"name",desc:!1}]}),(0,s.jsx)("div",{className:"mt-8 text-center",children:(0,s.jsxs)(c.Text,{className:"text-sm text-gray-600",children:["Showing ",eE.length," of ",O?.length||0," agents"]})})]},"agents"),K&&Array.isArray(K)&&K.length>0&&(0,s.jsxs)(T,{tab:"MCP Hub",children:[(0,s.jsx)("div",{className:"flex justify-between items-center mb-8",children:(0,s.jsx)(o.Title,{className:"text-2xl font-semibold text-gray-900",children:"Available MCP Servers"})}),(0,s.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6 mb-8 p-6 bg-gray-50 rounded-lg border border-gray-200",children:[(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center space-x-2 mb-3",children:[(0,s.jsx)(c.Text,{className:"text-sm font-medium text-gray-700",children:"Search MCP Servers:"}),(0,s.jsx)(u.Tooltip,{title:"Search MCP servers by name or description",placement:"top",children:(0,s.jsx)(g.default,{className:"w-4 h-4 text-gray-400 cursor-help"})})]}),(0,s.jsxs)("div",{className:"relative",children:[(0,s.jsx)(r,{className:"w-4 h-4 text-gray-400 absolute left-3 top-1/2 transform -translate-y-1/2"}),(0,s.jsx)("input",{type:"text",placeholder:"Search MCP server names or descriptions...",value:el,onChange:e=>ea(e.target.value),className:"border border-gray-300 rounded-lg pl-10 pr-4 py-2 w-full text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white"})]})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"text-sm font-medium mb-3 text-gray-700",children:"Transport:"}),(0,s.jsx)(x.Select,{mode:"multiple",value:eh,onChange:e=>eu(e),placeholder:"Select transport types",className:"w-full",size:"large",allowClear:!0,children:K&&Array.isArray(K)&&(M=new Set,K.forEach(e=>{e.transport&&M.add(e.transport)}),Array.from(M).sort()).map(e=>(0,s.jsx)(x.Select.Option,{value:e,children:e},e))})]})]}),(0,s.jsx)(j.ModelDataTable,{columns:[{header:"Server Name",accessorKey:"server_name",enableSorting:!0,cell:({row:e})=>(0,s.jsx)("div",{className:"overflow-hidden",children:(0,s.jsx)(u.Tooltip,{title:e.original.server_name,children:(0,s.jsx)(i.Button,{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",onClick:()=>{ek(e.original),eN(!0)},children:e.original.server_name})})}),size:150},{header:"Description",accessorKey:"mcp_info.description",enableSorting:!1,cell:({row:e})=>{let t=e.original.mcp_info?.description||"-",l=t.length>80?t.substring(0,80)+"...":t;return(0,s.jsx)(u.Tooltip,{title:t,children:(0,s.jsx)(c.Text,{className:"text-sm text-gray-700",children:l})})},size:250},{header:"URL",accessorKey:"url",enableSorting:!1,cell:({row:e})=>{let t=e.original.url,l=t.length>40?t.substring(0,40)+"...":t;return(0,s.jsx)(u.Tooltip,{title:t,children:(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,s.jsx)(c.Text,{className:"text-xs font-mono",children:l}),(0,s.jsx)(p.default,{onClick:()=>eD(t),className:"cursor-pointer text-gray-500 hover:text-blue-500 w-3 h-3"})]})})},size:200},{header:"Transport",accessorKey:"transport",enableSorting:!0,cell:({row:e})=>{let t=e.original.transport;return(0,s.jsx)(h.Tag,{color:"blue",className:"text-xs uppercase",children:t})},size:100},{header:"Auth Type",accessorKey:"auth_type",enableSorting:!0,cell:({row:e})=>{let t=e.original.auth_type;return(0,s.jsx)(h.Tag,{color:"none"===t?"gray":"green",className:"text-xs capitalize",children:t})},size:100}],data:eO,isLoading:Y,defaultSorting:[{id:"server_name",desc:!1}]}),(0,s.jsx)("div",{className:"mt-8 text-center",children:(0,s.jsxs)(c.Text,{className:"text-sm text-gray-600",children:["Showing ",eO.length," of ",K?.length||0," MCP servers"]})})]},"mcp")]})})]}),(0,s.jsx)(d.Modal,{title:(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,s.jsx)("span",{children:ey?.model_group||"Model Details"}),ey&&(0,s.jsx)(u.Tooltip,{title:"Copy model name",children:(0,s.jsx)(p.default,{onClick:()=>eD(ey.model_group),className:"cursor-pointer text-gray-500 hover:text-blue-500 w-4 h-4"})})]}),width:1e3,open:ej,footer:null,onOk:()=>{eb(!1),eT(null)},onCancel:()=>{eb(!1),eT(null)},children:ey&&(0,s.jsxs)("div",{className:"space-y-6",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"text-lg font-semibold mb-4",children:"Model Overview"}),(0,s.jsxs)("div",{className:"grid grid-cols-2 gap-4 mb-4",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"font-medium",children:"Model Name:"}),(0,s.jsx)(c.Text,{children:ey.model_group})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"font-medium",children:"Mode:"}),(0,s.jsx)(c.Text,{children:ey.mode||"Not specified"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"font-medium",children:"Providers:"}),(0,s.jsx)("div",{className:"flex flex-wrap gap-1 mt-1",children:ey.providers.map(e=>{let{logo:t}=(0,y.getProviderLogoAndName)(e);return(0,s.jsx)(h.Tag,{color:"blue",children:(0,s.jsxs)("div",{className:"flex items-center space-x-1",children:[t&&(0,s.jsx)("img",{src:t,alt:e,className:"w-3 h-3 flex-shrink-0 object-contain",onError:e=>{e.target.style.display="none"}}),(0,s.jsx)("span",{className:"capitalize",children:e})]})},e)})})]})]}),ey.model_group.includes("*")&&(0,s.jsx)("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 mb-4",children:(0,s.jsxs)("div",{className:"flex items-start space-x-2",children:[(0,s.jsx)(g.default,{className:"w-4 h-4 text-blue-600 mt-0.5 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"font-medium text-blue-900 mb-2",children:"Wildcard Routing"}),(0,s.jsxs)(c.Text,{className:"text-sm text-blue-800 mb-2",children:["This model uses wildcard routing. You can pass any value where you see the"," ",(0,s.jsx)("code",{className:"bg-blue-100 px-1 py-0.5 rounded text-xs",children:"*"})," symbol."]}),(0,s.jsxs)(c.Text,{className:"text-sm text-blue-800",children:["For example, with"," ",(0,s.jsx)("code",{className:"bg-blue-100 px-1 py-0.5 rounded text-xs",children:ey.model_group}),", you can use any string (",(0,s.jsx)("code",{className:"bg-blue-100 px-1 py-0.5 rounded text-xs",children:ey.model_group.replace("*","my-custom-value")}),") that matches this pattern."]})]})]})})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"text-lg font-semibold mb-4",children:"Token & Cost Information"}),(0,s.jsxs)("div",{className:"grid grid-cols-2 gap-4",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"font-medium",children:"Max Input Tokens:"}),(0,s.jsx)(c.Text,{children:ey.max_input_tokens?.toLocaleString()||"Not specified"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"font-medium",children:"Max Output Tokens:"}),(0,s.jsx)(c.Text,{children:ey.max_output_tokens?.toLocaleString()||"Not specified"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"font-medium",children:"Input Cost per 1M Tokens:"}),(0,s.jsx)(c.Text,{children:ey.input_cost_per_token?eR(ey.input_cost_per_token):"Not specified"})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"font-medium",children:"Output Cost per 1M Tokens:"}),(0,s.jsx)(c.Text,{children:ey.output_cost_per_token?eR(ey.output_cost_per_token):"Not specified"})]})]})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"text-lg font-semibold mb-4",children:"Capabilities"}),(0,s.jsx)("div",{className:"flex flex-wrap gap-2",children:(P=Object.entries(ey).filter(([e,s])=>e.startsWith("supports_")&&!0===s).map(([e])=>e),L=["green","blue","purple","orange","red","yellow"],0===P.length?(0,s.jsx)(c.Text,{className:"text-gray-500",children:"No special capabilities listed"}):P.map((e,t)=>(0,s.jsx)(h.Tag,{color:L[t%L.length],children:eK(e)},e)))})]}),(ey.tpm||ey.rpm)&&(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"text-lg font-semibold mb-4",children:"Rate Limits"}),(0,s.jsxs)("div",{className:"grid grid-cols-2 gap-4",children:[ey.tpm&&(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"font-medium",children:"Tokens per Minute:"}),(0,s.jsx)(c.Text,{children:ey.tpm.toLocaleString()})]}),ey.rpm&&(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"font-medium",children:"Requests per Minute:"}),(0,s.jsx)(c.Text,{children:ey.rpm.toLocaleString()})]})]})]}),ey.supported_openai_params&&(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"text-lg font-semibold mb-4",children:"Supported OpenAI Parameters"}),(0,s.jsx)("div",{className:"flex flex-wrap gap-2",children:ey.supported_openai_params.map(e=>(0,s.jsx)(h.Tag,{color:"green",children:e},e))})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"text-lg font-semibold mb-4",children:"Usage Example"}),(0,s.jsx)("div",{className:"bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto",children:(0,s.jsx)("pre",{className:"text-sm",children:(0,_.generateCodeSnippet)({apiKeySource:"custom",accessToken:null,apiKey:"your_api_key",inputMessage:"Hello, how are you?",chatHistory:[{role:"user",content:"Hello, how are you?",isImage:!1}],selectedTags:[],selectedVectorStores:[],selectedGuardrails:[],selectedPolicies:[],selectedMCPServers:[],endpointType:(0,N.getEndpointType)(ey.mode||"chat"),selectedModel:ey.model_group,selectedSdk:"openai"})})}),(0,s.jsx)("div",{className:"mt-2 text-right",children:(0,s.jsx)("button",{onClick:()=>{eD((0,_.generateCodeSnippet)({apiKeySource:"custom",accessToken:null,apiKey:"your_api_key",inputMessage:"Hello, how are you?",chatHistory:[{role:"user",content:"Hello, how are you?",isImage:!1}],selectedTags:[],selectedVectorStores:[],selectedGuardrails:[],selectedPolicies:[],selectedMCPServers:[],endpointType:(0,N.getEndpointType)(ey.mode||"chat"),selectedModel:ey.model_group,selectedSdk:"openai"}))},className:"text-sm text-blue-600 hover:text-blue-800 cursor-pointer",children:"Copy to clipboard"})})]})]})}),(0,s.jsx)(d.Modal,{title:(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,s.jsx)("span",{children:ew?.name||"Agent Details"}),ew&&(0,s.jsx)(u.Tooltip,{title:"Copy agent name",children:(0,s.jsx)(p.default,{onClick:()=>eD(ew.name),className:"cursor-pointer text-gray-500 hover:text-blue-500 w-4 h-4"})})]}),width:1e3,open:ef,footer:null,onOk:()=>{ev(!1),eS(null)},onCancel:()=>{ev(!1),eS(null)},children:ew&&(0,s.jsxs)("div",{className:"space-y-6",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"text-lg font-semibold mb-4",children:"Agent Overview"}),(0,s.jsxs)("div",{className:"grid grid-cols-2 gap-4 mb-4",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"font-medium",children:"Name:"}),(0,s.jsx)(c.Text,{children:ew.name})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"font-medium",children:"Version:"}),(0,s.jsx)(c.Text,{children:ew.version})]}),(0,s.jsxs)("div",{className:"col-span-2",children:[(0,s.jsx)(c.Text,{className:"font-medium",children:"Description:"}),(0,s.jsx)(c.Text,{children:ew.description})]}),ew.url&&(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"font-medium",children:"URL:"}),(0,s.jsx)("a",{href:ew.url,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 text-sm break-all",children:ew.url})]})]})]}),ew.capabilities&&(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"text-lg font-semibold mb-4",children:"Capabilities"}),(0,s.jsx)("div",{className:"flex flex-wrap gap-2",children:Object.entries(ew.capabilities).filter(([e,s])=>!0===s).map(([e])=>(0,s.jsx)(h.Tag,{color:"green",className:"capitalize",children:e},e))})]}),ew.skills&&ew.skills.length>0&&(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"text-lg font-semibold mb-4",children:"Skills"}),(0,s.jsx)("div",{className:"space-y-4",children:ew.skills.map((e,t)=>(0,s.jsxs)("div",{className:"border border-gray-200 rounded-lg p-4",children:[(0,s.jsx)("div",{className:"flex items-start justify-between mb-2",children:(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"font-medium text-base",children:e.name}),(0,s.jsx)(c.Text,{className:"text-sm text-gray-600",children:e.description})]})}),e.tags&&e.tags.length>0&&(0,s.jsx)("div",{className:"flex flex-wrap gap-1 mt-2",children:e.tags.map(e=>(0,s.jsx)(h.Tag,{color:"purple",className:"text-xs",children:e},e))})]},t))})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"text-lg font-semibold mb-4",children:"Input/Output Modes"}),(0,s.jsxs)("div",{className:"grid grid-cols-2 gap-4",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"font-medium",children:"Input Modes:"}),(0,s.jsx)("div",{className:"flex flex-wrap gap-1 mt-1",children:ew.defaultInputModes?.map(e=>(0,s.jsx)(h.Tag,{color:"blue",children:e},e))})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"font-medium",children:"Output Modes:"}),(0,s.jsx)("div",{className:"flex flex-wrap gap-1 mt-1",children:ew.defaultOutputModes?.map(e=>(0,s.jsx)(h.Tag,{color:"blue",children:e},e))})]})]})]}),ew.documentationUrl&&(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"text-lg font-semibold mb-4",children:"Documentation"}),(0,s.jsxs)("a",{href:ew.documentationUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 flex items-center space-x-2",children:[(0,s.jsx)(l.ExternalLinkIcon,{className:"w-4 h-4"}),(0,s.jsx)("span",{children:"View Documentation"})]})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"text-lg font-semibold mb-4",children:"Usage Example (A2A Protocol)"}),(0,s.jsxs)("div",{className:"mb-4",children:[(0,s.jsx)(c.Text,{className:"text-sm font-medium mb-2 text-gray-700",children:"Step 1: Retrieve Agent Card"}),(0,s.jsx)("div",{className:"bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto",children:(0,s.jsx)("pre",{className:"text-xs",children:`base_url = '${ew.url}' - -resolver = A2ACardResolver( - httpx_client=httpx_client, - base_url=base_url, - # agent_card_path uses default, extended_agent_card_path also uses default -) - -# Fetch Public Agent Card and Initialize Client -final_agent_card_to_use: AgentCard | None = None -_public_card = ( - await resolver.get_agent_card() -) # Fetches from default public path - \`/agents/{agent_id}/\` -final_agent_card_to_use = _public_card - -if _public_card.supports_authenticated_extended_card: - try: - auth_headers_dict = { - 'Authorization': 'Bearer dummy-token-for-extended-card' - } - _extended_card = await resolver.get_agent_card( - relative_card_path=EXTENDED_AGENT_CARD_PATH, - http_kwargs={'headers': auth_headers_dict}, - ) - final_agent_card_to_use = ( - _extended_card # Update to use the extended card - ) - except Exception as e_extended: - logger.warning( - f'Failed to fetch extended agent card: {e_extended}. Will proceed with public card.', - exc_info=True, - )`})}),(0,s.jsx)("div",{className:"mt-2 text-right",children:(0,s.jsx)("button",{onClick:()=>{eD(`from a2a.client import A2ACardResolver, A2AClient -from a2a.types import ( - AgentCard, - MessageSendParams, - SendMessageRequest, - SendStreamingMessageRequest, -) -from a2a.utils.constants import ( - AGENT_CARD_WELL_KNOWN_PATH, - EXTENDED_AGENT_CARD_PATH, -) - -base_url = '${ew.url}' - -resolver = A2ACardResolver( - httpx_client=httpx_client, - base_url=base_url, - # agent_card_path uses default, extended_agent_card_path also uses default -) - -# Fetch Public Agent Card and Initialize Client -final_agent_card_to_use: AgentCard | None = None -_public_card = ( - await resolver.get_agent_card() -) # Fetches from default public path - \`/agents/{agent_id}/\` -final_agent_card_to_use = _public_card - -if _public_card.supports_authenticated_extended_card: - try: - auth_headers_dict = { - 'Authorization': 'Bearer dummy-token-for-extended-card' - } - _extended_card = await resolver.get_agent_card( - relative_card_path=EXTENDED_AGENT_CARD_PATH, - http_kwargs={'headers': auth_headers_dict}, - ) - final_agent_card_to_use = ( - _extended_card # Update to use the extended card - ) - except Exception as e_extended: - logger.warning( - f'Failed to fetch extended agent card: {e_extended}. Will proceed with public card.', - exc_info=True, - )`)},className:"text-sm text-blue-600 hover:text-blue-800 cursor-pointer",children:"Copy to clipboard"})})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"text-sm font-medium mb-2 text-gray-700",children:"Step 2: Call the Agent"}),(0,s.jsx)("div",{className:"bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto",children:(0,s.jsx)("pre",{className:"text-xs",children:`client = A2AClient( - httpx_client=httpx_client, agent_card=final_agent_card_to_use -) - -send_message_payload: dict[str, Any] = { - 'message': { - 'role': 'user', - 'parts': [ - {'kind': 'text', 'text': 'how much is 10 USD in INR?'} - ], - 'messageId': uuid4().hex, - }, -} -request = SendMessageRequest( - id=str(uuid4()), params=MessageSendParams(**send_message_payload) -) - -response = await client.send_message(request) -print(response.model_dump(mode='json', exclude_none=True))`})}),(0,s.jsx)("div",{className:"mt-2 text-right",children:(0,s.jsx)("button",{onClick:()=>{eD(`client = A2AClient( - httpx_client=httpx_client, agent_card=final_agent_card_to_use -) - -send_message_payload: dict[str, Any] = { - 'message': { - 'role': 'user', - 'parts': [ - {'kind': 'text', 'text': 'how much is 10 USD in INR?'} - ], - 'messageId': uuid4().hex, - }, -} -request = SendMessageRequest( - id=str(uuid4()), params=MessageSendParams(**send_message_payload) -) - -response = await client.send_message(request) -print(response.model_dump(mode='json', exclude_none=True))`)},className:"text-sm text-blue-600 hover:text-blue-800 cursor-pointer",children:"Copy to clipboard"})})]})]})]})}),(0,s.jsx)(d.Modal,{title:(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,s.jsx)("span",{children:eC?.server_name||"MCP Server Details"}),eC&&(0,s.jsx)(u.Tooltip,{title:"Copy server name",children:(0,s.jsx)(p.default,{onClick:()=>eD(eC.server_name),className:"cursor-pointer text-gray-500 hover:text-blue-500 w-4 h-4"})})]}),width:1e3,open:e_,footer:null,onOk:()=>{eN(!1),ek(null)},onCancel:()=>{eN(!1),ek(null)},children:eC&&(0,s.jsxs)("div",{className:"space-y-6",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"text-lg font-semibold mb-4",children:"Server Overview"}),(0,s.jsxs)("div",{className:"grid grid-cols-2 gap-4 mb-4",children:[(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"font-medium",children:"Server Name:"}),(0,s.jsx)(c.Text,{children:eC.server_name})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"font-medium",children:"Transport:"}),(0,s.jsx)(h.Tag,{color:"blue",children:eC.transport})]}),eC.alias&&(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"font-medium",children:"Alias:"}),(0,s.jsx)(c.Text,{children:eC.alias})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"font-medium",children:"Auth Type:"}),(0,s.jsx)(h.Tag,{color:"none"===eC.auth_type?"gray":"green",children:eC.auth_type})]}),(0,s.jsxs)("div",{className:"col-span-2",children:[(0,s.jsx)(c.Text,{className:"font-medium",children:"Description:"}),(0,s.jsx)(c.Text,{children:eC.mcp_info?.description||"-"})]}),(0,s.jsxs)("div",{className:"col-span-2",children:[(0,s.jsx)(c.Text,{className:"font-medium",children:"URL:"}),(0,s.jsxs)("a",{href:eC.url,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 text-sm break-all flex items-center space-x-2",children:[(0,s.jsx)("span",{children:eC.url}),(0,s.jsx)(l.ExternalLinkIcon,{className:"w-4 h-4"})]})]})]})]}),eC.mcp_info&&Object.keys(eC.mcp_info).length>0&&(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"text-lg font-semibold mb-4",children:"Additional Information"}),(0,s.jsx)("div",{className:"bg-gray-50 p-4 rounded-lg",children:(0,s.jsx)("pre",{className:"text-xs overflow-x-auto",children:JSON.stringify(eC.mcp_info,null,2)})})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)(c.Text,{className:"text-lg font-semibold mb-4",children:"Usage Example"}),(0,s.jsx)("div",{className:"bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto",children:(0,s.jsx)("pre",{className:"text-sm",children:`# Using MCP Server with Python FastMCP - -from fastmcp import Client -import asyncio - -# Standard MCP configuration -config = { - "mcpServers": { - "${eC.server_name}": { - "url": "http://localhost:4000/${eC.server_name}/mcp", - "headers": { - "x-litellm-api-key": "Bearer sk-1234" - } - } - } -} - -# Create a client that connects to the server -client = Client(config) - -async def main(): - async with client: - # List available tools - tools = await client.list_tools() - print(f"Available tools: {[tool.name for tool in tools]}") - - # Call a tool - response = await client.call_tool( - name="tool_name", - arguments={"arg": "value"} - ) - print(f"Response: {response}") - -if __name__ == "__main__": - asyncio.run(main())`})}),(0,s.jsx)("div",{className:"mt-2 text-right",children:(0,s.jsx)("button",{onClick:()=>{eD(`# Using MCP Server with Python FastMCP - -from fastmcp import Client -import asyncio - -# Standard MCP configuration -config = { - "mcpServers": { - "${eC.server_name}": { - "url": "http://localhost:4000/${eC.server_name}/mcp", - "headers": { - "x-litellm-api-key": "Bearer sk-1234" - } - } - } -} - -# Create a client that connects to the server -client = Client(config) - -async def main(): - async with client: - # List available tools - tools = await client.list_tools() - print(f"Available tools: {[tool.name for tool in tools]}") - - # Call a tool - response = await client.call_tool( - name="tool_name", - arguments={"arg": "value"} - ) - print(f"Response: {response}") - -if __name__ == "__main__": - asyncio.run(main())`)},className:"text-sm text-blue-600 hover:text-blue-800 cursor-pointer",children:"Copy to clipboard"})})]})]})})]})})}],976883)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/3e395bb55b8572f7.js b/litellm/proxy/_experimental/out/_next/static/chunks/3e395bb55b8572f7.js deleted file mode 100644 index e9b7b892769..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/3e395bb55b8572f7.js +++ /dev/null @@ -1 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,75921,e=>{"use strict";var t=e.i(843476),s=e.i(266027),a=e.i(243652),l=e.i(764205),r=e.i(135214);let i=(0,a.createQueryKeys)("mcpAccessGroups");var n=e.i(500727),o=e.i(199133);e.s(["default",0,({onChange:e,value:a,className:c,accessToken:d,placeholder:u="Select MCP servers",disabled:m=!1})=>{let{data:p=[],isLoading:g}=(0,n.useMCPServers)(),{data:h=[],isLoading:x}=(()=>{let{accessToken:e}=(0,r.default)();return(0,s.useQuery)({queryKey:i.list({}),queryFn:async()=>await (0,l.fetchMCPAccessGroups)(e),enabled:!!e})})(),y=[...h.map(e=>({label:e,value:e,isAccessGroup:!0,searchText:`${e} Access Group`})),...p.map(e=>({label:`${e.server_name||e.server_id} (${e.server_id})`,value:e.server_id,isAccessGroup:!1,searchText:`${e.server_name||e.server_id} ${e.server_id} MCP Server`}))],f=[...a?.servers||[],...a?.accessGroups||[]];return(0,t.jsx)("div",{children:(0,t.jsx)(o.Select,{mode:"multiple",placeholder:u,onChange:t=>{e({servers:t.filter(e=>!h.includes(e)),accessGroups:t.filter(e=>h.includes(e))})},value:f,loading:g||x,className:c,allowClear:!0,showSearch:!0,style:{width:"100%"},disabled:m,filterOption:(e,t)=>(y.find(e=>e.value===t?.value)?.searchText||"").toLowerCase().includes(e.toLowerCase()),children:y.map(e=>(0,t.jsx)(o.Select.Option,{value:e.value,label:e.label,children:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[(0,t.jsx)("span",{style:{display:"inline-block",width:8,height:8,borderRadius:"50%",background:e.isAccessGroup?"#52c41a":"#1890ff",flexShrink:0}}),(0,t.jsx)("span",{style:{flex:1},children:e.label}),(0,t.jsx)("span",{style:{color:e.isAccessGroup?"#52c41a":"#1890ff",fontSize:"12px",fontWeight:500,opacity:.8},children:e.isAccessGroup?"Access Group":"MCP Server"})]})},e.value))})})}],75921)},207082,e=>{"use strict";var t=e.i(619273),s=e.i(266027),a=e.i(243652),l=e.i(764205),r=e.i(135214);let i=(0,a.createQueryKeys)("keys"),n=async(e,t,s,a={})=>{try{let r=(0,l.getProxyBaseUrl)(),i=new URLSearchParams(Object.entries({team_id:a.teamID,project_id:a.projectID,organization_id:a.organizationID,key_alias:a.selectedKeyAlias,key_hash:a.keyHash,user_id:a.userID,page:t,size:s,sort_by:a.sortBy,sort_order:a.sortOrder,expand:a.expand,status:a.status,return_full_object:"true",include_team_keys:"true",include_created_by_keys:"true"}).filter(([,e])=>null!=e).map(([e,t])=>[e,String(t)])),n=`${r?`${r}/key/list`:"/key/list"}?${i}`,o=await fetch(n,{method:"GET",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!o.ok){let e=await o.json(),t=(0,l.deriveErrorMessage)(e);throw(0,l.handleError)(t),Error(t)}let c=await o.json();return console.log("/key/list API Response:",c),c}catch(e){throw console.error("Failed to list keys:",e),e}},o=(0,a.createQueryKeys)("deletedKeys");e.s(["keyKeys",0,i,"useDeletedKeys",0,(e,a,l={})=>{let{accessToken:i}=(0,r.default)();return(0,s.useQuery)({queryKey:o.list({page:e,limit:a,...l}),queryFn:async()=>await n(i,e,a,{...l,status:"deleted"}),enabled:!!i,staleTime:3e4,placeholderData:t.keepPreviousData})},"useKeys",0,(e,a,l={})=>{let{accessToken:o}=(0,r.default)();return(0,s.useQuery)({queryKey:i.list({page:e,limit:a,...l}),queryFn:async()=>await n(o,e,a,l),enabled:!!o,staleTime:3e4,placeholderData:t.keepPreviousData})}])},510674,e=>{"use strict";var t=e.i(266027),s=e.i(243652),a=e.i(764205),l=e.i(708347),r=e.i(135214);let i=(0,s.createQueryKeys)("projects"),n=async e=>{let t=(0,a.getProxyBaseUrl)(),s=`${t}/project/list`,l=await fetch(s,{method:"GET",headers:{[(0,a.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!l.ok){let e=await l.json(),t=(0,a.deriveErrorMessage)(e);throw(0,a.handleError)(t),Error(t)}return l.json()};e.s(["projectKeys",0,i,"useProjects",0,()=>{let{accessToken:e,userRole:s}=(0,r.default)();return(0,t.useQuery)({queryKey:i.list({}),queryFn:async()=>n(e),enabled:!!e&&l.all_admin_roles.includes(s||"")})}])},552130,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(199133),l=e.i(764205);e.s(["default",0,({onChange:e,value:r,className:i,accessToken:n,placeholder:o="Select agents",disabled:c=!1})=>{let[d,u]=(0,s.useState)([]),[m,p]=(0,s.useState)([]),[g,h]=(0,s.useState)(!1);(0,s.useEffect)(()=>{(async()=>{if(n){h(!0);try{let e=await (0,l.getAgentsList)(n),t=e?.agents||[];u(t);let s=new Set;t.forEach(e=>{let t=e.agent_access_groups;t&&Array.isArray(t)&&t.forEach(e=>s.add(e))}),p(Array.from(s))}catch(e){console.error("Error fetching agents:",e)}finally{h(!1)}}})()},[n]);let x=[...m.map(e=>({label:e,value:`group:${e}`,isAccessGroup:!0,searchText:`${e} Access Group`})),...d.map(e=>({label:`${e.agent_name||e.agent_id}`,value:e.agent_id,isAccessGroup:!1,searchText:`${e.agent_name||e.agent_id} ${e.agent_id} Agent`}))],y=[...r?.agents||[],...(r?.accessGroups||[]).map(e=>`group:${e}`)];return(0,t.jsx)("div",{children:(0,t.jsx)(a.Select,{mode:"multiple",placeholder:o,onChange:t=>{e({agents:t.filter(e=>!e.startsWith("group:")),accessGroups:t.filter(e=>e.startsWith("group:")).map(e=>e.replace("group:",""))})},value:y,loading:g,className:i,allowClear:!0,showSearch:!0,style:{width:"100%"},disabled:c,filterOption:(e,t)=>(x.find(e=>e.value===t?.value)?.searchText||"").toLowerCase().includes(e.toLowerCase()),children:x.map(e=>(0,t.jsx)(a.Select.Option,{value:e.value,label:e.label,children:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[(0,t.jsx)("span",{style:{display:"inline-block",width:8,height:8,borderRadius:"50%",background:e.isAccessGroup?"#52c41a":"#722ed1",flexShrink:0}}),(0,t.jsx)("span",{style:{flex:1},children:e.label}),(0,t.jsx)("span",{style:{color:e.isAccessGroup?"#52c41a":"#722ed1",fontSize:"12px",fontWeight:500,opacity:.8},children:e.isAccessGroup?"Access Group":"Agent"})]})},e.value))})})}])},557662,e=>{"use strict";let t="../ui/assets/logos/",s=[{id:"arize",displayName:"Arize",logo:`${t}arize.png`,supports_key_team_logging:!0,dynamic_params:{arize_api_key:"password",arize_space_id:"password"},description:"Arize Logging Integration"},{id:"braintrust",displayName:"Braintrust",logo:`${t}braintrust.png`,supports_key_team_logging:!1,dynamic_params:{braintrust_api_key:"password",braintrust_project_name:"text"},description:"Braintrust Logging Integration"},{id:"custom_callback_api",displayName:"Custom Callback API",logo:`${t}custom.svg`,supports_key_team_logging:!0,dynamic_params:{custom_callback_api_url:"text",custom_callback_api_headers:"text"},description:"Custom Callback API Logging Integration"},{id:"datadog",displayName:"Datadog",logo:`${t}datadog.png`,supports_key_team_logging:!1,dynamic_params:{dd_api_key:"password",dd_site:"text"},description:"Datadog Logging Integration"},{id:"lago",displayName:"Lago",logo:`${t}lago.svg`,supports_key_team_logging:!1,dynamic_params:{lago_api_url:"text",lago_api_key:"password"},description:"Lago Billing Logging Integration"},{id:"langfuse",displayName:"Langfuse",logo:`${t}langfuse.png`,supports_key_team_logging:!0,dynamic_params:{langfuse_public_key:"text",langfuse_secret_key:"password",langfuse_host:"text"},description:"Langfuse v2 Logging Integration"},{id:"langfuse_otel",displayName:"Langfuse OTEL",logo:`${t}langfuse.png`,supports_key_team_logging:!0,dynamic_params:{langfuse_public_key:"text",langfuse_secret_key:"password",langfuse_host:"text"},description:"Langfuse v3 OTEL Logging Integration"},{id:"langsmith",displayName:"LangSmith",logo:`${t}langsmith.png`,supports_key_team_logging:!0,dynamic_params:{langsmith_api_key:"password",langsmith_project:"text",langsmith_base_url:"text",langsmith_sampling_rate:"number"},description:"Langsmith Logging Integration"},{id:"openmeter",displayName:"OpenMeter",logo:`${t}openmeter.png`,supports_key_team_logging:!1,dynamic_params:{openmeter_api_key:"password",openmeter_base_url:"text"},description:"OpenMeter Logging Integration"},{id:"otel",displayName:"Open Telemetry",logo:`${t}otel.png`,supports_key_team_logging:!1,dynamic_params:{otel_endpoint:"text",otel_headers:"text"},description:"OpenTelemetry Logging Integration"},{id:"s3",displayName:"S3",logo:`${t}aws.svg`,supports_key_team_logging:!1,dynamic_params:{s3_bucket_name:"text",aws_access_key_id:"password",aws_secret_access_key:"password",aws_region:"text"},description:"S3 Bucket (AWS) Logging Integration"},{id:"SQS",displayName:"SQS",logo:`${t}aws.svg`,supports_key_team_logging:!1,dynamic_params:{sqs_queue_url:"text",aws_access_key_id:"password",aws_secret_access_key:"password",aws_region:"text"},description:"SQS Queue (AWS) Logging Integration"}],a=s.reduce((e,t)=>(e[t.displayName]=t,e),{}),l=s.reduce((e,t)=>(e[t.displayName]=t.id,e),{}),r=s.reduce((e,t)=>(e[t.id]=t.displayName,e),{});e.s(["callbackInfo",0,a,"callback_map",0,l,"mapDisplayToInternalNames",0,e=>e.map(e=>l[e]||e),"mapInternalToDisplayNames",0,e=>e.map(e=>r[e]||e),"reverse_callback_map",0,r])},9314,263147,e=>{"use strict";var t=e.i(843476),s=e.i(199133),a=e.i(981339),l=e.i(645526),r=e.i(599724),i=e.i(266027),n=e.i(243652),o=e.i(764205),c=e.i(708347),d=e.i(135214);let u=(0,n.createQueryKeys)("accessGroups"),m=async e=>{let t=(0,o.getProxyBaseUrl)(),s=`${t}/v1/access_group`,a=await fetch(s,{method:"GET",headers:{[(0,o.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!a.ok){let e=await a.json(),t=(0,o.deriveErrorMessage)(e);throw(0,o.handleError)(t),Error(t)}return a.json()},p=()=>{let{accessToken:e,userRole:t}=(0,d.default)();return(0,i.useQuery)({queryKey:u.list({}),queryFn:async()=>m(e),enabled:!!e&&c.all_admin_roles.includes(t||"")})};e.s(["accessGroupKeys",0,u,"useAccessGroups",0,p],263147),e.s(["default",0,({value:e,onChange:i,placeholder:n="Select access groups",disabled:o=!1,style:c,className:d,showLabel:u=!1,labelText:m="Access Group",allowClear:g=!0})=>{let{data:h,isLoading:x,isError:y}=p();if(x)return(0,t.jsxs)("div",{children:[u&&(0,t.jsxs)(r.Text,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,t.jsx)(l.TeamOutlined,{className:"mr-2"})," ",m]}),(0,t.jsx)(a.Skeleton.Input,{active:!0,block:!0,style:{height:32,...c}})]});let f=(h??[]).map(e=>({label:(0,t.jsxs)("span",{children:[(0,t.jsx)("span",{className:"font-medium",children:e.access_group_name})," ",(0,t.jsxs)("span",{className:"text-gray-400 text-xs",children:["(",e.access_group_id,")"]})]}),value:e.access_group_id,selectedLabel:e.access_group_name,searchText:`${e.access_group_name} ${e.access_group_id}`}));return(0,t.jsxs)("div",{children:[u&&(0,t.jsxs)(r.Text,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,t.jsx)(l.TeamOutlined,{className:"mr-2"})," ",m]}),(0,t.jsx)(s.Select,{mode:"multiple",value:e,placeholder:n,onChange:i,disabled:o,allowClear:g,showSearch:!0,style:{width:"100%",...c},className:`rounded-md ${d??""}`,notFoundContent:y?(0,t.jsx)("span",{className:"text-red-500",children:"Failed to load access groups"}):"No access groups found",filterOption:(e,t)=>(f.find(e=>e.value===t?.value)?.searchText??"").toLowerCase().includes(e.toLowerCase()),optionLabelProp:"selectedLabel",options:f.map(e=>({label:e.label,value:e.value,selectedLabel:e.selectedLabel}))})]})}],9314)},392110,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(199133),l=e.i(592968),r=e.i(312361),i=e.i(790848),n=e.i(536916),o=e.i(827252),c=e.i(779241);let{Option:d}=a.Select;e.s(["default",0,({form:e,autoRotationEnabled:u,onAutoRotationChange:m,rotationInterval:p,onRotationIntervalChange:g,isCreateMode:h=!1,neverExpire:x=!1,onNeverExpireChange:y})=>{let f=p&&!["7d","30d","90d","180d","365d"].includes(p),[_,j]=(0,s.useState)(f),[b,v]=(0,s.useState)(f?p:""),[w,N]=(0,s.useState)(e?.getFieldValue?.("duration")||"");return(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Key Expiry Settings"}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,t.jsx)("span",{children:"Expire Key"}),(0,t.jsx)(l.Tooltip,{title:"Set when this key should expire. Format: 30s (seconds), 30m (minutes), 30h (hours), 30d (days). Leave empty to keep the current expiry unchanged.",children:(0,t.jsx)(o.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})}),!h&&y&&(0,t.jsx)(n.Checkbox,{checked:x,onChange:t=>{let s=t.target.checked;y(s),s&&(N(""),e&&"function"==typeof e.setFieldValue?e.setFieldValue("duration",""):e&&"function"==typeof e.setFieldsValue&&e.setFieldsValue({duration:""}))},className:"ml-2 text-sm font-normal text-gray-600",children:"Never Expire"})]}),(0,t.jsx)(c.TextInput,{name:"duration",placeholder:h?"e.g., 30d or leave empty to never expire":"e.g., 30d",className:"w-full",value:w,onValueChange:t=>{N(t),e&&"function"==typeof e.setFieldValue?e.setFieldValue("duration",t):e&&"function"==typeof e.setFieldsValue&&e.setFieldsValue({duration:t})},disabled:!h&&x})]})]}),(0,t.jsx)(r.Divider,{}),(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Auto-Rotation Settings"}),(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,t.jsx)("span",{children:"Enable Auto-Rotation"}),(0,t.jsx)(l.Tooltip,{title:"Key will automatically regenerate at the specified interval for enhanced security.",children:(0,t.jsx)(o.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})})]}),(0,t.jsx)(i.Switch,{checked:u,onChange:m,size:"default",className:u?"":"bg-gray-400"})]}),u&&(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,t.jsx)("span",{children:"Rotation Interval"}),(0,t.jsx)(l.Tooltip,{title:"How often the key should be automatically rotated. Choose the interval that best fits your security requirements.",children:(0,t.jsx)(o.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)(a.Select,{value:_?"custom":p,onChange:e=>{"custom"===e?j(!0):(j(!1),v(""),g(e))},className:"w-full",placeholder:"Select interval",children:[(0,t.jsx)(d,{value:"7d",children:"7 days"}),(0,t.jsx)(d,{value:"30d",children:"30 days"}),(0,t.jsx)(d,{value:"90d",children:"90 days"}),(0,t.jsx)(d,{value:"180d",children:"180 days"}),(0,t.jsx)(d,{value:"365d",children:"365 days"}),(0,t.jsx)(d,{value:"custom",children:"Custom interval"})]}),_&&(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(c.TextInput,{value:b,onChange:e=>{let t=e.target.value;v(t),g(t)},placeholder:"e.g., 1s, 5m, 2h, 14d"}),(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"Supported formats: seconds (s), minutes (m), hours (h), days (d)"})]})]})]})]}),u&&(0,t.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."})]})]})}])},533882,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(250980),l=e.i(797672),r=e.i(68155),i=e.i(304967),n=e.i(629569),o=e.i(599724),c=e.i(269200),d=e.i(427612),u=e.i(64848),m=e.i(942232),p=e.i(496020),g=e.i(977572),h=e.i(992619),x=e.i(727749);e.s(["default",0,({accessToken:e,initialModelAliases:y={},onAliasUpdate:f,showExampleConfig:_=!0})=>{let[j,b]=(0,s.useState)([]),[v,w]=(0,s.useState)({aliasName:"",targetModel:""}),[N,k]=(0,s.useState)(null);(0,s.useEffect)(()=>{b(Object.entries(y).map(([e,t],s)=>({id:`${s}-${e}`,aliasName:e,targetModel:t})))},[y]);let S=()=>{if(!N)return;if(!N.aliasName||!N.targetModel)return void x.default.fromBackend("Please provide both alias name and target model");if(j.some(e=>e.id!==N.id&&e.aliasName===N.aliasName))return void x.default.fromBackend("An alias with this name already exists");let e=j.map(e=>e.id===N.id?N:e);b(e),k(null);let t={};e.forEach(e=>{t[e.aliasName]=e.targetModel}),f&&f(t),x.default.success("Alias updated successfully")},C=()=>{k(null)},T=j.reduce((e,t)=>(e[t.aliasName]=t.targetModel,e),{});return(0,t.jsxs)("div",{className:"mt-4",children:[(0,t.jsxs)("div",{className:"mb-6",children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium text-gray-700 mb-2",children:"Add New Alias"}),(0,t.jsxs)("div",{className:"grid grid-cols-3 gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-xs text-gray-500 mb-1",children:"Alias Name"}),(0,t.jsx)("input",{type:"text",value:v.aliasName,onChange:e=>w({...v,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,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-xs text-gray-500 mb-1",children:"Target Model"}),(0,t.jsx)(h.default,{accessToken:e,value:v.targetModel,placeholder:"Select target model",onChange:e=>w({...v,targetModel:e}),showLabel:!1})]}),(0,t.jsx)("div",{className:"flex items-end",children:(0,t.jsxs)("button",{onClick:()=>{if(!v.aliasName||!v.targetModel)return void x.default.fromBackend("Please provide both alias name and target model");if(j.some(e=>e.aliasName===v.aliasName))return void x.default.fromBackend("An alias with this name already exists");let e=[...j,{id:`${Date.now()}-${v.aliasName}`,aliasName:v.aliasName,targetModel:v.targetModel}];b(e),w({aliasName:"",targetModel:""});let t={};e.forEach(e=>{t[e.aliasName]=e.targetModel}),f&&f(t),x.default.success("Alias added successfully")},disabled:!v.aliasName||!v.targetModel,className:`flex items-center px-4 py-2 rounded-md text-sm ${!v.aliasName||!v.targetModel?"bg-gray-300 text-gray-500 cursor-not-allowed":"bg-green-600 text-white hover:bg-green-700"}`,children:[(0,t.jsx)(a.PlusCircleIcon,{className:"w-4 h-4 mr-1"}),"Add Alias"]})})]})]}),(0,t.jsx)(o.Text,{className:"text-sm font-medium text-gray-700 mb-2",children:"Manage Existing Aliases"}),(0,t.jsx)("div",{className:"rounded-lg custom-border relative mb-6",children:(0,t.jsx)("div",{className:"overflow-x-auto",children:(0,t.jsxs)(c.Table,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,t.jsx)(d.TableHead,{children:(0,t.jsxs)(p.TableRow,{children:[(0,t.jsx)(u.TableHeaderCell,{className:"py-1 h-8",children:"Alias Name"}),(0,t.jsx)(u.TableHeaderCell,{className:"py-1 h-8",children:"Target Model"}),(0,t.jsx)(u.TableHeaderCell,{className:"py-1 h-8",children:"Actions"})]})}),(0,t.jsxs)(m.TableBody,{children:[j.map(s=>(0,t.jsx)(p.TableRow,{className:"h-8",children:N&&N.id===s.id?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(g.TableCell,{className:"py-0.5",children:(0,t.jsx)("input",{type:"text",value:N.aliasName,onChange:e=>k({...N,aliasName:e.target.value}),className:"w-full px-2 py-1 border border-gray-300 rounded-md text-sm"})}),(0,t.jsx)(g.TableCell,{className:"py-0.5",children:(0,t.jsx)(h.default,{accessToken:e,value:N.targetModel,onChange:e=>k({...N,targetModel:e}),showLabel:!1,style:{height:"32px"}})}),(0,t.jsx)(g.TableCell,{className:"py-0.5 whitespace-nowrap",children:(0,t.jsxs)("div",{className:"flex space-x-2",children:[(0,t.jsx)("button",{onClick:S,className:"text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded hover:bg-blue-100",children:"Save"}),(0,t.jsx)("button",{onClick:C,className:"text-xs bg-gray-50 text-gray-600 px-2 py-1 rounded hover:bg-gray-100",children:"Cancel"})]})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(g.TableCell,{className:"py-0.5 text-sm text-gray-900",children:s.aliasName}),(0,t.jsx)(g.TableCell,{className:"py-0.5 text-sm text-gray-500",children:s.targetModel}),(0,t.jsx)(g.TableCell,{className:"py-0.5 whitespace-nowrap",children:(0,t.jsxs)("div",{className:"flex space-x-2",children:[(0,t.jsx)("button",{onClick:()=>{k({...s})},className:"text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded hover:bg-blue-100",children:(0,t.jsx)(l.PencilIcon,{className:"w-3 h-3"})}),(0,t.jsx)("button",{onClick:()=>{var e;let t,a;return e=s.id,b(t=j.filter(t=>t.id!==e)),a={},void(t.forEach(e=>{a[e.aliasName]=e.targetModel}),f&&f(a),x.default.success("Alias deleted successfully"))},className:"text-xs bg-red-50 text-red-600 px-2 py-1 rounded hover:bg-red-100",children:(0,t.jsx)(r.TrashIcon,{className:"w-3 h-3"})})]})})]})},s.id)),0===j.length&&(0,t.jsx)(p.TableRow,{children:(0,t.jsx)(g.TableCell,{colSpan:3,className:"py-0.5 text-sm text-gray-500 text-center",children:"No aliases added yet. Add a new alias above."})})]})]})})}),_&&(0,t.jsxs)(i.Card,{children:[(0,t.jsx)(n.Title,{className:"mb-4",children:"Configuration Example"}),(0,t.jsx)(o.Text,{className:"text-gray-600 mb-4",children:"Here's how your current aliases would look in the config:"}),(0,t.jsx)("div",{className:"bg-gray-100 rounded-lg p-4 font-mono text-sm",children:(0,t.jsxs)("div",{className:"text-gray-700",children:["model_aliases:",0===Object.keys(T).length?(0,t.jsxs)("span",{className:"text-gray-500",children:[(0,t.jsx)("br",{}),"  # No aliases configured yet"]}):Object.entries(T).map(([e,s])=>(0,t.jsxs)("span",{children:[(0,t.jsx)("br",{}),'  "',e,'": "',s,'"']},e))]})})]})]})}])},844565,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(199133),l=e.i(764205);e.s(["default",0,({onChange:e,value:r,className:i,accessToken:n,placeholder:o="Select pass through routes",disabled:c=!1,teamId:d})=>{let[u,m]=(0,s.useState)([]),[p,g]=(0,s.useState)(!1);return(0,s.useEffect)(()=>{(async()=>{if(n){g(!0);try{let e=await (0,l.getPassThroughEndpointsCall)(n,d);if(e.endpoints){let t=e.endpoints.flatMap(e=>{let t=e.path,s=e.methods;return s&&s.length>0?s.map(e=>({label:`${e} ${t}`,value:t})):[{label:t,value:t}]});m(t)}}catch(e){console.error("Error fetching pass through routes:",e)}finally{g(!1)}}})()},[n,d]),(0,t.jsx)(a.Select,{mode:"tags",placeholder:o,onChange:e,value:r,loading:p,className:i,allowClear:!0,options:u,optionFilterProp:"label",showSearch:!0,style:{width:"100%"},disabled:c})}])},810757,477386,e=>{"use strict";var t=e.i(271645);let s=t.forwardRef(function(e,s){return t.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:s},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}))});e.s(["CogIcon",0,s],810757);let a=t.forwardRef(function(e,s){return t.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:s},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"}))});e.s(["BanIcon",0,a],477386)},266484,e=>{"use strict";var t=e.i(843476),s=e.i(199133),a=e.i(592968),l=e.i(312361),r=e.i(827252),i=e.i(994388),n=e.i(304967),o=e.i(779241),c=e.i(988297),d=e.i(68155),u=e.i(810757),m=e.i(477386),p=e.i(557662),g=e.i(435451);let{Option:h}=s.Select;e.s(["default",0,({value:e=[],onChange:x,disabledCallbacks:y=[],onDisabledCallbacksChange:f})=>{let _=Object.entries(p.callbackInfo).filter(([e,t])=>t.supports_key_team_logging).map(([e,t])=>e),j=Object.keys(p.callbackInfo),b=e=>{x?.(e)},v=(t,s,a)=>{let l=[...e];if("callback_name"===s){let e=p.callback_map[a]||a;l[t]={...l[t],[s]:e,callback_vars:{}}}else l[t]={...l[t],[s]:a};b(l)},w=(t,s,a)=>{let l=[...e];l[t]={...l[t],callback_vars:{...l[t].callback_vars,[s]:a}},b(l)};return(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)(m.BanIcon,{className:"w-5 h-5 text-red-500"}),(0,t.jsx)("span",{className:"text-base font-semibold text-gray-800",children:"Disabled Callbacks"}),(0,t.jsx)(a.Tooltip,{title:"Select callbacks to disable for this key. Disabled callbacks will not receive any logging data.",children:(0,t.jsx)(r.InfoCircleOutlined,{className:"text-gray-400 cursor-help"})})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{className:"text-sm font-medium text-gray-700",children:"Disabled Callbacks"}),(0,t.jsx)(s.Select,{mode:"multiple",placeholder:"Select callbacks to disable",value:y,onChange:e=>{let t=(0,p.mapDisplayToInternalNames)(e);f?.(t)},style:{width:"100%"},optionLabelProp:"label",children:j.map(e=>{let s=p.callbackInfo[e]?.logo,l=p.callbackInfo[e]?.description;return(0,t.jsx)(h,{value:e,label:e,children:(0,t.jsx)(a.Tooltip,{title:l,placement:"right",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[s&&(0,t.jsx)("img",{src:s,alt:e,className:"w-4 h-4 object-contain",onError:t=>{let s=t.target,a=s.parentElement;if(a){let t=document.createElement("div");t.className="w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",t.textContent=e.charAt(0),a.replaceChild(t,s)}}}),(0,t.jsx)("span",{children:e})]})})},e)})}),(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"Select callbacks that should be disabled for this key. These callbacks will not receive any logging data."})]})]}),(0,t.jsx)(l.Divider,{}),(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)(u.CogIcon,{className:"w-5 h-5 text-blue-500"}),(0,t.jsx)("span",{className:"text-base font-semibold text-gray-800",children:"Logging Integrations"}),(0,t.jsx)(a.Tooltip,{title:"Configure callback logging integrations for this team.",children:(0,t.jsx)(r.InfoCircleOutlined,{className:"text-gray-400 cursor-help"})})]}),(0,t.jsx)(i.Button,{variant:"secondary",onClick:()=>{b([...e,{callback_name:"",callback_type:"success",callback_vars:{}}])},icon:c.PlusIcon,size:"sm",className:"hover:border-blue-400 hover:text-blue-500",type:"button",children:"Add Integration"})]}),(0,t.jsx)("div",{className:"space-y-4",children:e.map((l,c)=>{let u=l.callback_name?Object.entries(p.callback_map).find(([e,t])=>t===l.callback_name)?.[0]:void 0,m=u?p.callbackInfo[u]?.logo:null;return(0,t.jsxs)(n.Card,{className:"border border-gray-200 shadow-sm hover:shadow-md transition-shadow duration-200",decoration:"top",decorationColor:"blue",children:[(0,t.jsxs)("div",{className:"flex justify-between items-start mb-4",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[m&&(0,t.jsx)("img",{src:m,alt:u,className:"w-5 h-5 object-contain"}),(0,t.jsxs)("span",{className:"text-sm font-medium",children:[u||"New Integration"," Configuration"]})]}),(0,t.jsx)(i.Button,{variant:"light",onClick:()=>{b(e.filter((e,t)=>t!==c))},icon:d.TrashIcon,size:"xs",color:"red",className:"hover:bg-red-50",type:"button",children:"Remove"})]}),(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{className:"text-sm font-medium text-gray-700",children:"Integration Type"}),(0,t.jsx)(s.Select,{value:u,placeholder:"Select integration",onChange:e=>v(c,"callback_name",e),className:"w-full",optionLabelProp:"label",children:_.map(e=>{let s=p.callbackInfo[e]?.logo,l=p.callbackInfo[e]?.description;return(0,t.jsx)(h,{value:e,label:e,children:(0,t.jsx)(a.Tooltip,{title:l,placement:"right",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[s&&(0,t.jsx)("img",{src:s,alt:e,className:"w-4 h-4 object-contain",onError:t=>{let s=t.target,a=s.parentElement;if(a){let t=document.createElement("div");t.className="w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",t.textContent=e.charAt(0),a.replaceChild(t,s)}}}),(0,t.jsx)("span",{children:e})]})})},e)})})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{className:"text-sm font-medium text-gray-700",children:"Event Type"}),(0,t.jsxs)(s.Select,{value:l.callback_type,onChange:e=>v(c,"callback_type",e),className:"w-full",children:[(0,t.jsx)(h,{value:"success",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-green-500 rounded-full"}),(0,t.jsx)("span",{children:"Success Only"})]})}),(0,t.jsx)(h,{value:"failure",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-red-500 rounded-full"}),(0,t.jsx)("span",{children:"Failure Only"})]})}),(0,t.jsx)(h,{value:"success_and_failure",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)("span",{children:"Success & Failure"})]})})]})]})]}),((e,s)=>{if(!e.callback_name)return null;let l=Object.entries(p.callback_map).find(([t,s])=>s===e.callback_name)?.[0];if(!l)return null;let i=p.callbackInfo[l]?.dynamic_params||{};return 0===Object.keys(i).length?null:(0,t.jsxs)("div",{className:"mt-6 pt-4 border-t border-gray-100",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2 mb-4",children:[(0,t.jsx)("div",{className:"w-3 h-3 bg-blue-100 rounded-full flex items-center justify-center",children:(0,t.jsx)("div",{className:"w-1.5 h-1.5 bg-blue-500 rounded-full"})}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Integration Parameters"})]}),(0,t.jsx)("div",{className:"grid grid-cols-1 gap-4",children:Object.entries(i).map(([l,i])=>(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 capitalize flex items-center space-x-1",children:[(0,t.jsx)("span",{children:l.replace(/_/g," ")}),(0,t.jsx)(a.Tooltip,{title:`Environment variable reference recommended: os.environ/${l.toUpperCase()}`,children:(0,t.jsx)(r.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})}),"password"===i&&(0,t.jsx)("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-800",children:"Sensitive"}),"number"===i&&(0,t.jsx)("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-800",children:"Number"})]}),"number"===i&&(0,t.jsx)("span",{className:"text-xs text-gray-500",children:"Value must be between 0 and 1"}),"number"===i?(0,t.jsx)(g.default,{step:.01,width:400,placeholder:`os.environ/${l.toUpperCase()}`,value:e.callback_vars[l]||"",onChange:e=>w(s,l,e.target.value)}):(0,t.jsx)(o.TextInput,{type:"password"===i?"password":"text",placeholder:`os.environ/${l.toUpperCase()}`,value:e.callback_vars[l]||"",onChange:e=>w(s,l,e.target.value)})]},l))})]})})(l,c)]})]},c)})}),0===e.length&&(0,t.jsxs)("div",{className:"text-center py-12 text-gray-500 border-2 border-dashed border-gray-200 rounded-lg bg-gray-50/50",children:[(0,t.jsx)(u.CogIcon,{className:"w-12 h-12 text-gray-300 mb-3 mx-auto"}),(0,t.jsx)("div",{className:"text-base font-medium mb-1",children:"No logging integrations configured"}),(0,t.jsx)("div",{className:"text-sm text-gray-400",children:'Click "Add Integration" to configure logging for this team'})]})]})}])},651904,e=>{"use strict";var t=e.i(843476),s=e.i(599724),a=e.i(266484);e.s(["default",0,function({value:e,onChange:l,premiumUser:r=!1,disabledCallbacks:i=[],onDisabledCallbacksChange:n}){return r?(0,t.jsx)(a.default,{value:e,onChange:l,disabledCallbacks:i,onDisabledCallbacksChange:n}):(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex flex-wrap gap-2 mb-3",children:[(0,t.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,t.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,t.jsx)("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-lg",children:(0,t.jsxs)(s.Text,{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,t.jsx)("a",{href:"https://www.litellm.ai/#pricing",target:"_blank",rel:"noopener noreferrer",className:"underline",children:"here"}),"."]})})]})}])},939510,e=>{"use strict";var t=e.i(843476),s=e.i(808613),a=e.i(199133),l=e.i(592968),r=e.i(827252);let{Option:i}=a.Select;e.s(["default",0,({type:e,name:n,showDetailedDescriptions:o=!0,className:c="",initialValue:d=null,form:u,onChange:m})=>{let p=e.toUpperCase(),g=e.toLowerCase(),h=`Select 'guaranteed_throughput' to prevent overallocating ${p} limit when the key belongs to a Team with specific ${p} limits.`;return(0,t.jsx)(s.Form.Item,{label:(0,t.jsxs)("span",{children:[p," Rate Limit Type"," ",(0,t.jsx)(l.Tooltip,{title:h,children:(0,t.jsx)(r.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:n,initialValue:d,className:c,children:(0,t.jsx)(a.Select,{defaultValue:o?"default":void 0,placeholder:"Select rate limit type",style:{width:"100%"},optionLabelProp:o?"label":void 0,onChange:e=>{u&&u.setFieldValue(n,e),m&&m(e)},children:o?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(i,{value:"best_effort_throughput",label:"Default",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Default"}),(0,t.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["Best effort throughput - no error if we're overallocating ",g," (Team/Key Limits checked at runtime)."]})]})}),(0,t.jsx)(i,{value:"guaranteed_throughput",label:"Guaranteed throughput",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Guaranteed throughput"}),(0,t.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["Guaranteed throughput - raise an error if we're overallocating ",g," (also checks model-specific limits)"]})]})}),(0,t.jsx)(i,{value:"dynamic",label:"Dynamic",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Dynamic"}),(0,t.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["If the key has a set ",p," (e.g. 2 ",p,") and there are no 429 errors, it can dynamically exceed the limit when the model being called is not erroring."]})]})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(i,{value:"best_effort_throughput",children:"Best effort throughput"}),(0,t.jsx)(i,{value:"guaranteed_throughput",children:"Guaranteed throughput"}),(0,t.jsx)(i,{value:"dynamic",children:"Dynamic"})]})})})}])},460285,575260,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(404206),l=e.i(723731),r=e.i(653824),i=e.i(881073),n=e.i(197647),o=e.i(764205),c=e.i(158392),d=e.i(419470),u=e.i(689020);let m=(0,s.forwardRef)(({accessToken:e,value:m,onChange:p,modelData:g},h)=>{let[x,y]=(0,s.useState)({routerSettings:{},selectedStrategy:null,enableTagFiltering:!1}),[f,_]=(0,s.useState)([]),[j,b]=(0,s.useState)([]),[v,w]=(0,s.useState)([]),[N,k]=(0,s.useState)([]),[S,C]=(0,s.useState)({}),[T,I]=(0,s.useState)({}),A=(0,s.useRef)(!1),L=(0,s.useRef)(null);(0,s.useEffect)(()=>{let e=m?.router_settings?JSON.stringify({routing_strategy:m.router_settings.routing_strategy,fallbacks:m.router_settings.fallbacks,enable_tag_filtering:m.router_settings.enable_tag_filtering}):null;if(A.current&&e===L.current){A.current=!1;return}if(A.current&&e!==L.current&&(A.current=!1),e!==L.current)if(L.current=e,m?.router_settings){let e=m.router_settings,{fallbacks:t,...s}=e;y({routerSettings:s,selectedStrategy:e.routing_strategy||null,enableTagFiltering:e.enable_tag_filtering??!1});let a=e.fallbacks||[];_(a),b(a&&0!==a.length?a.map((e,t)=>{let[s,a]=Object.entries(e)[0];return{id:(t+1).toString(),primaryModel:s||null,fallbackModels:a||[]}}):[{id:"1",primaryModel:null,fallbackModels:[]}])}else y({routerSettings:{},selectedStrategy:null,enableTagFiltering:!1}),_([]),b([{id:"1",primaryModel:null,fallbackModels:[]}])},[m]),(0,s.useEffect)(()=>{e&&(0,o.getRouterSettingsCall)(e).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}}),C(t);let s=e.fields.find(e=>"routing_strategy"===e.field_name);s?.options&&k(s.options),e.routing_strategy_descriptions&&I(e.routing_strategy_descriptions)}})},[e]),(0,s.useEffect)(()=>{e&&(async()=>{try{let t=await (0,u.fetchAvailableModels)(e);w(t)}catch(e){console.error("Error fetching model info for fallbacks:",e)}})()},[e]);let F=()=>{let e=new Set(["allowed_fails","cooldown_time","num_retries","timeout","retry_after"]),t=new Set(["model_group_alias","retry_policy"]),s=Object.fromEntries(Object.entries({...x.routerSettings,enable_tag_filtering:x.enableTagFiltering,routing_strategy:x.selectedStrategy,fallbacks:f.length>0?f:null}).map(([s,a])=>{if("routing_strategy_args"!==s&&"routing_strategy"!==s&&"enable_tag_filtering"!==s&&"fallbacks"!==s){let l=document.querySelector(`input[name="${s}"]`);if(l&&void 0!==l.value&&""!==l.value){let r=((s,a,l)=>{if(null==a)return l;let r=String(a).trim();if(""===r||"null"===r.toLowerCase())return null;if(e.has(s)){let e=Number(r);return Number.isNaN(e)?l:e}if(t.has(s)){if(""===r)return null;try{return JSON.parse(r)}catch{return l}}return"true"===r.toLowerCase()||"false"!==r.toLowerCase()&&r})(s,l.value,a);return[s,r]}}else if("routing_strategy"===s)return[s,x.selectedStrategy];else if("enable_tag_filtering"===s)return[s,x.enableTagFiltering];else if("fallbacks"===s)return[s,f.length>0?f:null];else if("routing_strategy_args"===s&&"latency-based-routing"===x.selectedStrategy){let e=document.querySelector('input[name="lowest_latency_buffer"]'),t=document.querySelector('input[name="ttl"]'),s={};return e?.value&&(s.lowest_latency_buffer=Number(e.value)),t?.value&&(s.ttl=Number(t.value)),["routing_strategy_args",Object.keys(s).length>0?s:null]}return[s,a]}).filter(e=>null!=e)),a=(e,t=!1)=>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:f.length>0?f: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:x.enableTagFiltering,routing_strategy_args:a(s.routing_strategy_args)}};(0,s.useEffect)(()=>{if(!p)return;let e=setTimeout(()=>{A.current=!0,p({router_settings:F()})},100);return()=>clearTimeout(e)},[x,f]);let M=Array.from(new Set(v.map(e=>e.model_group))).sort();return((0,s.useImperativeHandle)(h,()=>({getValue:()=>({router_settings:F()})})),e)?(0,t.jsx)("div",{className:"w-full",children:(0,t.jsxs)(r.TabGroup,{className:"w-full",children:[(0,t.jsxs)(i.TabList,{variant:"line",defaultValue:"1",className:"px-8 pt-4",children:[(0,t.jsx)(n.Tab,{value:"1",children:"Loadbalancing"}),(0,t.jsx)(n.Tab,{value:"2",children:"Fallbacks"})]}),(0,t.jsxs)(l.TabPanels,{className:"px-8 py-6",children:[(0,t.jsx)(a.TabPanel,{children:(0,t.jsx)(c.default,{value:x,onChange:y,routerFieldsMetadata:S,availableRoutingStrategies:N,routingStrategyDescriptions:T})}),(0,t.jsx)(a.TabPanel,{children:(0,t.jsx)(d.FallbackSelectionForm,{groups:j,onGroupsChange:e=>{b(e),_(e.filter(e=>e.primaryModel&&e.fallbackModels.length>0).map(e=>({[e.primaryModel]:e.fallbackModels})))},availableModels:M,maxGroups:5})})]})]})}):null});m.displayName="RouterSettingsAccordion",e.s(["default",0,m],460285);var p=e.i(199133),g=e.i(482725),h=e.i(56456);e.s(["default",0,({projects:e,value:s,onChange:a,disabled:l,loading:r,teamId:i})=>{let n=i?e?.filter(e=>e.team_id===i):e;return(0,t.jsx)(p.Select,{showSearch:!0,placeholder:"Search or select a project",value:s,onChange:a,disabled:l,loading:r,allowClear:!0,notFoundContent:r?(0,t.jsx)(g.Spin,{indicator:(0,t.jsx)(h.LoadingOutlined,{spin:!0}),size:"small"}):void 0,filterOption:(e,t)=>{if(!t)return!1;let s=n?.find(e=>e.project_id===t.key);if(!s)return!1;let a=e.toLowerCase().trim(),l=(s.project_alias||"").toLowerCase(),r=(s.project_id||"").toLowerCase();return l.includes(a)||r.includes(a)},optionFilterProp:"children",children:!r&&n?.map(e=>(0,t.jsxs)(p.Select.Option,{value:e.project_id,children:[(0,t.jsx)("span",{className:"font-medium",children:e.project_alias||e.project_id})," ",(0,t.jsxs)("span",{className:"text-gray-500",children:["(",e.project_id,")"]})]},e.project_id))})}],575260)},390605,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(764205),l=e.i(599724),r=e.i(482725),i=e.i(536916),n=e.i(995926),o=e.i(500727);e.s(["default",0,({accessToken:e,selectedServers:c,toolPermissions:d,onChange:u,disabled:m=!1})=>{let{data:p=[]}=(0,o.useMCPServers)(),[g,h]=(0,s.useState)({}),[x,y]=(0,s.useState)({}),[f,_]=(0,s.useState)({}),j=(0,s.useMemo)(()=>0===c.length?[]:p.filter(e=>c.includes(e.server_id)),[p,c]),b=async t=>{y(e=>({...e,[t]:!0})),_(e=>({...e,[t]:""}));try{let s=await (0,a.listMCPTools)(e,t);s.error?(_(e=>({...e,[t]:s.message||"Failed to fetch tools"})),h(e=>({...e,[t]:[]}))):h(e=>({...e,[t]:s.tools||[]}))}catch(e){console.error(`Error fetching tools for server ${t}:`,e),_(e=>({...e,[t]:"Failed to fetch tools"})),h(e=>({...e,[t]:[]}))}finally{y(e=>({...e,[t]:!1}))}};return((0,s.useEffect)(()=>{j.forEach(e=>{g[e.server_id]||x[e.server_id]||b(e.server_id)})},[j]),0===c.length)?null:(0,t.jsx)("div",{className:"space-y-4",children:j.map(e=>{let s=e.server_name||e.alias||e.server_id,a=g[e.server_id]||[],o=d[e.server_id]||[],c=x[e.server_id],p=f[e.server_id];return(0,t.jsxs)("div",{className:"border rounded-lg bg-gray-50",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between p-4 border-b bg-white rounded-t-lg",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(l.Text,{className:"font-semibold text-gray-900",children:s}),e.description&&(0,t.jsx)(l.Text,{className:"text-sm text-gray-500",children:e.description})]}),(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("button",{type:"button",className:"text-sm text-blue-600 hover:text-blue-700 font-medium",onClick:()=>{var t;let s;return s=g[t=e.server_id]||[],void u({...d,[t]:s.map(e=>e.name)})},disabled:m||c,children:"Select All"}),(0,t.jsx)("button",{type:"button",className:"text-sm text-blue-600 hover:text-blue-700 font-medium",onClick:()=>{var t;return t=e.server_id,void u({...d,[t]:[]})},disabled:m||c,children:"Deselect All"}),(0,t.jsx)("button",{type:"button",className:"text-gray-400 hover:text-gray-600",onClick:()=>{},children:(0,t.jsx)(n.XIcon,{className:"w-4 h-4"})})]})]}),(0,t.jsxs)("div",{className:"p-4",children:[(0,t.jsx)(l.Text,{className:"text-sm font-medium text-gray-700 mb-3",children:"Available Tools"}),c&&(0,t.jsxs)("div",{className:"flex items-center justify-center py-8",children:[(0,t.jsx)(r.Spin,{size:"large"}),(0,t.jsx)(l.Text,{className:"ml-3 text-gray-500",children:"Loading tools..."})]}),p&&!c&&(0,t.jsxs)("div",{className:"p-4 bg-red-50 border border-red-200 rounded-lg text-center",children:[(0,t.jsx)(l.Text,{className:"text-red-600 font-medium",children:"Unable to load tools"}),(0,t.jsx)(l.Text,{className:"text-sm text-red-500 mt-1",children:p})]}),!c&&!p&&a.length>0&&(0,t.jsx)("div",{className:"space-y-2",children:a.map(s=>{let a=o.includes(s.name);return(0,t.jsxs)("div",{className:"flex items-start gap-2",children:[(0,t.jsx)(i.Checkbox,{checked:a,onChange:()=>{var t,a;let l,r;return t=e.server_id,a=s.name,r=(l=d[t]||[]).includes(a)?l.filter(e=>e!==a):[...l,a],void u({...d,[t]:r})},disabled:m}),(0,t.jsx)("div",{className:"flex-1 min-w-0",children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(l.Text,{className:"font-medium text-gray-900",children:s.name}),(0,t.jsxs)(l.Text,{className:"text-sm text-gray-500",children:["- ",s.description||"No description"]})]})})]},s.name)})}),!c&&!p&&0===a.length&&(0,t.jsx)("div",{className:"text-center py-6",children:(0,t.jsx)(l.Text,{className:"text-gray-500",children:"No tools available"})})]})]},e.server_id)})})}])},702597,364769,e=>{"use strict";var t=e.i(843476),s=e.i(207082),a=e.i(510674),l=e.i(292639),r=e.i(135214),i=e.i(500330),n=e.i(827252),o=e.i(912598),c=e.i(677667),d=e.i(130643),u=e.i(898667),m=e.i(994388),p=e.i(309426),g=e.i(350967),h=e.i(599724),x=e.i(779241),y=e.i(629569),f=e.i(464571),_=e.i(808613),j=e.i(311451),b=e.i(212931),v=e.i(91739),w=e.i(199133),N=e.i(790848),k=e.i(262218),S=e.i(592968),C=e.i(374009),T=e.i(271645),I=e.i(708347),A=e.i(552130),L=e.i(557662),F=e.i(9314),M=e.i(860585),P=e.i(82946),O=e.i(392110),E=e.i(533882),$=e.i(844565),B=e.i(651904),V=e.i(939510),D=e.i(460285),G=e.i(663435),R=e.i(575260),K=e.i(371455),U=e.i(355619),q=e.i(75921),z=e.i(390605),W=e.i(727749),H=e.i(764205),Q=e.i(237016),J=e.i(998573);let Y=({apiKey:e})=>{let[s,a]=(0,T.useState)(!1);return(0,t.jsxs)("div",{children:[(0,t.jsxs)("p",{className:"mb-2",children:["Please save this secret key somewhere safe and accessible. For security reasons,"," ",(0,t.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,t.jsx)("p",{className:"text-sm text-gray-600 mt-3 mb-1",children:"Virtual Key:"}),(0,t.jsx)("div",{style:{background:"#f8f8f8",padding:"10px",borderRadius:"5px",marginBottom:"10px"},children:(0,t.jsx)("pre",{style:{wordWrap:"break-word",whiteSpace:"normal",margin:0},children:e})}),(0,t.jsx)(Q.CopyToClipboard,{text:e,onCopy:()=>{a(!0),J.message.success("Key copied to clipboard"),setTimeout(()=>a(!1),2e3)},children:(0,t.jsx)(f.Button,{type:"primary",style:{marginTop:12},children:s?"Copied!":"Copy Virtual Key"})})]})};e.s(["default",0,Y],364769);var X=e.i(435451),Z=e.i(916940);let{Option:ee}=w.Select,et=async(e,t,s,a)=>{try{if(null===e||null===t)return[];if(null!==s){let l=(await (0,H.modelAvailableCall)(s,e,t,!0,a,!0)).data.map(e=>e.id);return console.log("available_model_names:",l),l}return[]}catch(e){return console.error("Error fetching user models:",e),[]}},es=async(e,t,s,a)=>{try{if(null===e||null===t)return;if(null!==s){let l=(await (0,H.modelAvailableCall)(s,e,t)).data.map(e=>e.id);console.log("available_model_names:",l),a(l)}}catch(e){console.error("Error fetching user models:",e)}};e.s(["default",0,({team:e,teams:Q,data:J,addKey:ea,autoOpenCreate:el,prefillData:er})=>{let{accessToken:ei,userId:en,userRole:eo,premiumUser:ec}=(0,r.default)(),ed=ec||null!=eo&&I.rolesWithWriteAccess.includes(eo),{data:eu,isLoading:em}=(0,a.useProjects)(),{data:ep}=(0,l.useUISettings)(),eg=!!ep?.values?.enable_projects_ui,eh=(0,o.useQueryClient)(),[ex]=_.Form.useForm(),[ey,ef]=(0,T.useState)(!1),[e_,ej]=(0,T.useState)(null),[eb,ev]=(0,T.useState)(null),[ew,eN]=(0,T.useState)([]),[ek,eS]=(0,T.useState)([]),[eC,eT]=(0,T.useState)("you"),[eI,eA]=(0,T.useState)((e=>{let t=[];if(console.log("data:",JSON.stringify(e)),e)for(let s of e)s.metadata&&s.metadata.tags&&t.push(...s.metadata.tags);let s=Array.from(new Set(t)).map(e=>({value:e,label:e}));return console.log("uniqueTags:",s),s})(J)),[eL,eF]=(0,T.useState)(!1),[eM,eP]=(0,T.useState)(null),[eO,eE]=(0,T.useState)([]),[e$,eB]=(0,T.useState)([]),[eV,eD]=(0,T.useState)([]),[eG,eR]=(0,T.useState)([]),[eK,eU]=(0,T.useState)(e),[eq,ez]=(0,T.useState)(null),[eW,eH]=(0,T.useState)(!1),[eQ,eJ]=(0,T.useState)(null),[eY,eX]=(0,T.useState)({}),[eZ,e0]=(0,T.useState)([]),[e1,e2]=(0,T.useState)(!1),[e4,e5]=(0,T.useState)([]),[e3,e6]=(0,T.useState)([]),[e7,e9]=(0,T.useState)("llm_api"),[e8,te]=(0,T.useState)({}),[tt,ts]=(0,T.useState)(!1),[ta,tl]=(0,T.useState)("30d"),[tr,ti]=(0,T.useState)(null),[tn,to]=(0,T.useState)(0),[tc,td]=(0,T.useState)([]),[tu,tm]=(0,T.useState)(null),tp=()=>{ef(!1),ex.resetFields(),eR([]),e6([]),e9("llm_api"),te({}),ts(!1),tl("30d"),ti(null),to(e=>e+1),tm(null),ez(null)},tg=()=>{ef(!1),ej(null),eU(null),ex.resetFields(),eR([]),e6([]),e9("llm_api"),te({}),ts(!1),tl("30d"),ti(null),to(e=>e+1),tm(null),ez(null)};(0,T.useEffect)(()=>{en&&eo&&ei&&es(en,eo,ei,eN)},[ei,en,eo]),(0,T.useEffect)(()=>{ei&&(0,H.getAgentsList)(ei).then(e=>td(e?.agents||[])).catch(()=>td([]))},[ei]),(0,T.useEffect)(()=>{let e=async()=>{try{let e=(await (0,H.getPoliciesList)(ei)).policies.map(e=>e.policy_name);eB(e)}catch(e){console.error("Failed to fetch policies:",e)}},t=async()=>{try{let e=await (0,H.getPromptsList)(ei);eD(e.prompts.map(e=>e.prompt_id))}catch(e){console.error("Failed to fetch prompts:",e)}};(async()=>{try{let e=(await (0,H.getGuardrailsList)(ei)).guardrails.map(e=>e.guardrail_name);eE(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})(),e(),t()},[ei]),(0,T.useEffect)(()=>{(async()=>{try{if(ei){let e=sessionStorage.getItem("possibleUserRoles");if(e)eX(JSON.parse(e));else{let e=await (0,H.getPossibleUserRoles)(ei);sessionStorage.setItem("possibleUserRoles",JSON.stringify(e)),eX(e)}}}catch(e){console.error("Error fetching possible user roles:",e)}})()},[ei]),(0,T.useEffect)(()=>{if(el&&!eL&&Q&&eo&&I.rolesWithWriteAccess.includes(eo)&&(ef(!0),eF(!0),er)){if(er.owned_by&&("another_user"===er.owned_by&&"Admin"!==eo?eT("you"):eT(er.owned_by)),er.team_id){let e=Q?.find(e=>e.team_id===er.team_id)||null;e&&(eU(e),ex.setFieldsValue({team_id:er.team_id}))}er.key_alias&&ex.setFieldsValue({key_alias:er.key_alias}),er.models&&er.models.length>0&&eP(er.models),er.key_type&&(e9(er.key_type),ex.setFieldsValue({key_type:er.key_type}))}},[el,er,Q,eL,ex,eo]);let th=ek.includes("no-default-models")&&!eK,tx=async e=>{try{let t,a=e?.key_alias??"",l=e?.team_id??null;if((J?.filter(e=>e.team_id===l).map(e=>e.key_alias)??[]).includes(a))throw Error(`Key alias ${a} already exists for team with ID ${l}, please provide another key alias`);if(W.default.info("Making API Call"),ef(!0),"you"===eC)e.user_id=en;else if("agent"===eC){if(!tu)return void W.default.fromBackend("Please select an agent");e.agent_id=tu}let r={};try{r=JSON.parse(e.metadata||"{}")}catch(e){console.error("Error parsing metadata:",e)}if("service_account"===eC&&(r.service_account_id=e.key_alias),eG.length>0&&(r={...r,logging:eG.filter(e=>e.callback_name)}),e3.length>0){let e=(0,L.mapDisplayToInternalNames)(e3);r={...r,litellm_disabled_callbacks:e}}if(tt&&(e.auto_rotate=!0,e.rotation_interval=ta),e.duration&&""!==e.duration.trim()||(e.duration=null),e.metadata=JSON.stringify(r),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&&(e.allowed_mcp_servers_and_groups.servers?.length>0||e.allowed_mcp_servers_and_groups.accessGroups?.length>0)){e.object_permission||(e.object_permission={});let{servers:t,accessGroups:s}=e.allowed_mcp_servers_and_groups;t&&t.length>0&&(e.object_permission.mcp_servers=t),s&&s.length>0&&(e.object_permission.mcp_access_groups=s),delete e.allowed_mcp_servers_and_groups}let i=e.mcp_tool_permissions||{};if(Object.keys(i).length>0&&(e.object_permission||(e.object_permission={}),e.object_permission.mcp_tool_permissions=i),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&&(e.allowed_agents_and_groups.agents?.length>0||e.allowed_agents_and_groups.accessGroups?.length>0)){e.object_permission||(e.object_permission={});let{agents:t,accessGroups:s}=e.allowed_agents_and_groups;t&&t.length>0&&(e.object_permission.agents=t),s&&s.length>0&&(e.object_permission.agent_access_groups=s),delete e.allowed_agents_and_groups}Object.keys(e8).length>0&&(e.aliases=JSON.stringify(e8)),tr?.router_settings&&Object.values(tr.router_settings).some(e=>null!=e&&""!==e)&&(e.router_settings=tr.router_settings),t="service_account"===eC?await (0,H.keyCreateServiceAccountCall)(ei,e):await (0,H.keyCreateCall)(ei,en,e),console.log("key create Response:",t),ea(t),eh.invalidateQueries({queryKey:s.keyKeys.lists()}),ej(t.key),ev(t.soft_budget),W.default.success("Virtual Key Created"),ex.resetFields(),localStorage.removeItem("userData"+en)}catch(t){console.log("error in create key:",t);let e=(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: ${e}`;let s=t;try{if(!e||"object"!=typeof e||e instanceof Error){let e=t.match(/\{[\s\S]*\}/);if(e){let t=JSON.parse(e[0]),a=t?.error||t;a?.message&&(s=a.message)}}else{let t=e?.error||e;t?.message&&(s=t.message)}}catch(e){}return t.includes("team_member_permission_error")||s.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: ${e}`})(t);W.default.fromBackend(e)}};(0,T.useEffect)(()=>{if(eq){let e=eu?.find(e=>e.project_id===eq);eS(e?.models??[]),ex.setFieldValue("models",[]);return}en&&eo&&ei&&et(en,eo,ei,eK?.team_id??null).then(e=>{eS(Array.from(new Set([...eK?.models??[],...e])))}),eM||ex.setFieldValue("models",[])},[eK,eq,ei,en,eo,ex]),(0,T.useEffect)(()=>{if(!eM||0===eM.length||!ek||0===ek.length)return;let e=eM.filter(e=>ek.includes(e));e.length>0&&ex.setFieldsValue({models:e}),eP(null)},[eM,ek,ex]),(0,T.useEffect)(()=>{if(!eq||!Q)return;let e=eu?.find(e=>e.project_id===eq);if(!e?.team_id||eK?.team_id===e.team_id)return;let t=Q.find(t=>t.team_id===e.team_id)||null;t&&(eU(t),ex.setFieldValue("team_id",t.team_id))},[Q,eq,eu]);let ty=async e=>{if(!e)return void e0([]);e2(!0);try{let t=new URLSearchParams;if(t.append("user_email",e),null==ei)return;let s=(await (0,H.userFilterUICall)(ei,t)).map(e=>({label:`${e.user_email} (${e.user_id})`,value:e.user_id,user:e}));e0(s)}catch(e){console.error("Error fetching users:",e),W.default.fromBackend("Failed to search for users")}finally{e2(!1)}},tf=(0,T.useCallback)((0,C.default)(e=>ty(e),300),[ei]);return(0,t.jsxs)("div",{children:[eo&&I.rolesWithWriteAccess.includes(eo)&&(0,t.jsx)(m.Button,{className:"mx-auto",onClick:()=>ef(!0),children:"+ Create New Key"}),(0,t.jsx)(b.Modal,{open:ey,width:1e3,footer:null,onOk:tp,onCancel:tg,children:(0,t.jsxs)(_.Form,{form:ex,onFinish:tx,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,t.jsxs)("div",{className:"mb-8",children:[(0,t.jsx)(y.Title,{className:"mb-4",children:"Key Ownership"}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Owned By"," ",(0,t.jsx)(S.Tooltip,{title:"Select who will own this Virtual Key",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),className:"mb-4",children:(0,t.jsxs)(v.Radio.Group,{onChange:e=>eT(e.target.value),value:eC,children:[(0,t.jsx)(v.Radio,{value:"you",children:"You"}),(0,t.jsx)(v.Radio,{value:"service_account",children:"Service Account"}),"Admin"===eo&&(0,t.jsx)(v.Radio,{value:"another_user",children:"Another User"}),(0,t.jsxs)(v.Radio,{value:"agent",children:["Agent ",(0,t.jsx)(k.Tag,{color:"purple",children:"New"})]})]})}),"another_user"===eC&&(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["User ID"," ",(0,t.jsx)(S.Tooltip,{title:"The user who will own this key and be responsible for its usage",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"user_id",className:"mt-4",rules:[{required:"another_user"===eC,message:"Please input the user ID of the user you are assigning the key to"}],children:(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{style:{display:"flex",marginBottom:"8px"},children:[(0,t.jsx)(w.Select,{showSearch:!0,placeholder:"Type email to search for users",filterOption:!1,onSearch:e=>{tf(e)},onSelect:(e,t)=>{let s;return s=t.user,void ex.setFieldsValue({user_id:s.user_id})},options:eZ,loading:e1,allowClear:!0,style:{width:"100%"},notFoundContent:e1?"Searching...":"No users found"}),(0,t.jsx)(f.Button,{onClick:()=>eH(!0),style:{marginLeft:"8px"},children:"Create User"})]}),(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"Search by email to find users"})]})}),"agent"===eC&&(0,t.jsxs)("div",{className:"mt-4 p-4 bg-purple-50 border border-purple-200 rounded-md",children:[(0,t.jsx)("div",{className:"mb-3",children:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700",children:["Select Agent ",(0,t.jsx)("span",{className:"text-red-500",children:"*"})]})}),(0,t.jsx)(w.Select,{showSearch:!0,placeholder:"Select an agent",style:{width:"100%"},value:tu,onChange:e=>tm(e),filterOption:(e,t)=>t?.label?.toLowerCase().includes(e.toLowerCase()),options:tc.map(e=>({label:e.agent_name||e.agent_id,value:e.agent_id}))}),(0,t.jsx)("div",{className:"text-xs text-gray-500 mt-2",children:"This key will be used by the selected agent to make requests to LiteLLM"})]}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Team"," ",(0,t.jsx)(S.Tooltip,{title:"The team this key belongs to, which determines available models and budget limits",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"team_id",initialValue:e?e.team_id:null,className:"mt-4",rules:[{required:"service_account"===eC,message:"Please select a team for the service account"}],help:"service_account"===eC?"required":"",children:(0,t.jsx)(G.default,{teams:Q,disabled:null!==eq,loading:!Q,onChange:e=>{eU(Q?.find(t=>t.team_id===e)||null),ez(null),ex.setFieldValue("project_id",void 0)}})}),eg&&(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Project"," ",(0,t.jsx)(S.Tooltip,{title:"Assign this key to a project. Selecting a project will lock the team to the project's team.",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"project_id",className:"mt-4",children:(0,t.jsx)(R.default,{projects:eu,teamId:eK?.team_id,loading:em||!Q,onChange:e=>{if(!e){ez(null),eU(null),ex.setFieldValue("team_id",void 0);return}ez(e)}})})]}),th&&(0,t.jsx)("div",{className:"mb-8 p-4 bg-blue-50 border border-blue-200 rounded-md",children:(0,t.jsx)(h.Text,{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."})}),!th&&(0,t.jsxs)("div",{className:"mb-8",children:[(0,t.jsx)(y.Title,{className:"mb-4",children:"Key Details"}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["you"===eC||"another_user"===eC?"Key Name":"Service Account ID"," ",(0,t.jsx)(S.Tooltip,{title:"you"===eC||"another_user"===eC?"A descriptive name to identify this key":"Unique identifier for this service account",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"key_alias",rules:[{required:!0,message:`Please input a ${"you"===eC?"key name":"service account ID"}`}],help:"required",children:(0,t.jsx)(x.TextInput,{placeholder:""})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Models"," ",(0,t.jsx)(S.Tooltip,{title:"Select which models this key can access. Choose 'All Team Models' to grant access to all models available to the team. Leave empty to allow access to all models.",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"models",rules:[],help:"management"===e7||"read_only"===e7?"Models field is disabled for this key type":"optional - leave empty to allow access to all models",className:"mt-4",children:(0,t.jsxs)(w.Select,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},disabled:"management"===e7||"read_only"===e7,onChange:e=>{e.includes("all-team-models")&&ex.setFieldsValue({models:["all-team-models"]})},children:[!eq&&(0,t.jsx)(ee,{value:"all-team-models",children:"All Team Models"},"all-team-models"),ek.map(e=>(0,t.jsx)(ee,{value:e,children:(0,U.getModelDisplayName)(e)},e))]})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Key Type"," ",(0,t.jsx)(S.Tooltip,{title:"Select the type of key to determine what routes and operations this key can access",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"key_type",initialValue:"llm_api",className:"mt-4",children:(0,t.jsxs)(w.Select,{defaultValue:"llm_api",placeholder:"Select key type",style:{width:"100%"},optionLabelProp:"label",onChange:e=>{e9(e),("management"===e||"read_only"===e)&&ex.setFieldsValue({models:[]})},children:[(0,t.jsx)(ee,{value:"default",label:"Default",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Default"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call AI APIs + Management routes"})]})}),(0,t.jsx)(ee,{value:"llm_api",label:"AI APIs",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"AI APIs"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call only AI API routes (chat/completions, embeddings, etc.)"})]})}),(0,t.jsx)(ee,{value:"management",label:"Management",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Management"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call only management routes (user/team/key management)"})]})})]})})]}),!th&&(0,t.jsx)("div",{className:"mb-8",children:(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)(y.Title,{className:"m-0",children:"Optional Settings"})}),(0,t.jsxs)(d.AccordionBody,{children:[(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Max Budget (USD)"," ",(0,t.jsx)(S.Tooltip,{title:"Maximum amount in USD this key can spend. When reached, the key will be blocked from making further requests",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"max_budget",help:`Budget cannot exceed team max budget: $${e?.max_budget!==null&&e?.max_budget!==void 0?e?.max_budget:"unlimited"}`,rules:[{validator:async(t,s)=>{if(s&&e&&null!==e.max_budget&&s>e.max_budget)throw Error(`Budget cannot exceed team max budget: $${(0,i.formatNumberWithCommas)(e.max_budget,4)}`)}}],children:(0,t.jsx)(X.default,{step:.01,precision:2,width:200})}),(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Reset Budget"," ",(0,t.jsx)(S.Tooltip,{title:"How often the budget should reset. For example, setting 'daily' will reset the budget every 24 hours",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"budget_duration",help:`Team Reset Budget: ${e?.budget_duration!==null&&e?.budget_duration!==void 0?e?.budget_duration:"None"}`,children:(0,t.jsx)(M.default,{onChange:e=>ex.setFieldValue("budget_duration",e)})}),(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Tokens per minute Limit (TPM)"," ",(0,t.jsx)(S.Tooltip,{title:"Maximum number of tokens this key can process per minute. Helps control usage and costs",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"tpm_limit",help:`TPM cannot exceed team TPM limit: ${e?.tpm_limit!==null&&e?.tpm_limit!==void 0?e?.tpm_limit:"unlimited"}`,rules:[{validator:async(t,s)=>{if(s&&e&&null!==e.tpm_limit&&s>e.tpm_limit)throw Error(`TPM limit cannot exceed team TPM limit: ${e.tpm_limit}`)}}],children:(0,t.jsx)(X.default,{step:1,width:400})}),(0,t.jsx)(V.default,{type:"tpm",name:"tpm_limit_type",className:"mt-4",initialValue:null,form:ex,showDetailedDescriptions:!0}),(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Requests per minute Limit (RPM)"," ",(0,t.jsx)(S.Tooltip,{title:"Maximum number of API requests this key can make per minute. Helps prevent abuse and manage load",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"rpm_limit",help:`RPM cannot exceed team RPM limit: ${e?.rpm_limit!==null&&e?.rpm_limit!==void 0?e?.rpm_limit:"unlimited"}`,rules:[{validator:async(t,s)=>{if(s&&e&&null!==e.rpm_limit&&s>e.rpm_limit)throw Error(`RPM limit cannot exceed team RPM limit: ${e.rpm_limit}`)}}],children:(0,t.jsx)(X.default,{step:1,width:400})}),(0,t.jsx)(V.default,{type:"rpm",name:"rpm_limit_type",className:"mt-4",initialValue:null,form:ex,showDetailedDescriptions:!0}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Guardrails"," ",(0,t.jsx)(S.Tooltip,{title:"Apply safety guardrails to this key to filter content or enforce policies",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",className:"mt-4",help:ed?"Select existing guardrails or enter new ones":"Premium feature - Upgrade to set guardrails by key",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},disabled:!ed,placeholder:ed?"Select or enter guardrails":"Premium feature - Upgrade to set guardrails by key",options:eO.map(e=>({value:e,label:e}))})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Disable Global Guardrails"," ",(0,t.jsx)(S.Tooltip,{title:"When enabled, this key will bypass any guardrails configured to run on every request (global guardrails)",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"disable_global_guardrails",className:"mt-4",valuePropName:"checked",help:ed?"Bypass global guardrails for this key":"Premium feature - Upgrade to disable global guardrails by key",children:(0,t.jsx)(N.Switch,{disabled:!ed,checkedChildren:"Yes",unCheckedChildren:"No"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Policies"," ",(0,t.jsx)(S.Tooltip,{title:"Apply policies to this key to control guardrails and other settings",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/guardrail_policies",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"policies",className:"mt-4",help:ec?"Select existing policies or enter new ones":"Premium feature - Upgrade to set policies by key",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},disabled:!ec,placeholder:ec?"Select or enter policies":"Premium feature - Upgrade to set policies by key",options:e$.map(e=>({value:e,label:e}))})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Prompts"," ",(0,t.jsx)(S.Tooltip,{title:"Allow this key to use specific prompt templates",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/prompt_management",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"prompts",className:"mt-4",help:ec?"Select existing prompts or enter new ones":"Premium feature - Upgrade to set prompts by key",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},disabled:!ec,placeholder:ec?"Select or enter prompts":"Premium feature - Upgrade to set prompts by key",options:eV.map(e=>({value:e,label:e}))})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Access Groups"," ",(0,t.jsx)(S.Tooltip,{title:"Assign access groups to this key. Access groups control which models, MCP servers, and agents this key can use",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"access_group_ids",className:"mt-4",help:"Select access groups to assign to this key",children:(0,t.jsx)(F.default,{placeholder:"Select access groups (optional)"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Pass Through Routes"," ",(0,t.jsx)(S.Tooltip,{title:"Allow this key to use specific pass through routes",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/pass_through",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"allowed_passthrough_routes",className:"mt-4",help:ec?"Select existing pass through routes or enter new ones":"Premium feature - Upgrade to set pass through routes by key",children:(0,t.jsx)($.default,{onChange:e=>ex.setFieldValue("allowed_passthrough_routes",e),value:ex.getFieldValue("allowed_passthrough_routes"),accessToken:ei,placeholder:ec?"Select or enter pass through routes":"Premium feature - Upgrade to set pass through routes by key",disabled:!ec,teamId:eK?eK.team_id:null})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Vector Stores"," ",(0,t.jsx)(S.Tooltip,{title:"Select which vector stores this key can access. If none selected, the key will have access to all available vector stores",children:(0,t.jsx)(n.InfoCircleOutlined,{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,t.jsx)(Z.default,{onChange:e=>ex.setFieldValue("allowed_vector_store_ids",e),value:ex.getFieldValue("allowed_vector_store_ids"),accessToken:ei,placeholder:"Select vector stores (optional)"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Metadata"," ",(0,t.jsx)(S.Tooltip,{title:"JSON object with additional information about this key. Used for tracking or custom logic",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"metadata",className:"mt-4",children:(0,t.jsx)(j.Input.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Tags"," ",(0,t.jsx)(S.Tooltip,{title:"Tags for tracking spend and/or doing tag-based routing. Used for analytics and filtering",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"tags",className:"mt-4",help:"Tags for tracking spend and/or doing tag-based routing.",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},placeholder:"Enter tags",tokenSeparators:[","],options:eI})}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"MCP Settings"})}),(0,t.jsxs)(d.AccordionBody,{children:[(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed MCP Servers"," ",(0,t.jsx)(S.Tooltip,{title:"Select which MCP servers or access groups this key can access",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_mcp_servers_and_groups",help:"Select MCP servers or access groups this key can access",children:(0,t.jsx)(q.default,{onChange:e=>ex.setFieldValue("allowed_mcp_servers_and_groups",e),value:ex.getFieldValue("allowed_mcp_servers_and_groups"),accessToken:ei,placeholder:"Select MCP servers or access groups (optional)"})}),(0,t.jsx)(_.Form.Item,{name:"mcp_tool_permissions",initialValue:{},hidden:!0,children:(0,t.jsx)(j.Input,{type:"hidden"})}),(0,t.jsx)(_.Form.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:()=>(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(z.default,{accessToken:ei,selectedServers:ex.getFieldValue("allowed_mcp_servers_and_groups")?.servers||[],toolPermissions:ex.getFieldValue("mcp_tool_permissions")||{},onChange:e=>ex.setFieldsValue({mcp_tool_permissions:e})})})})]})]}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Agent Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Agents"," ",(0,t.jsx)(S.Tooltip,{title:"Select which agents or access groups this key can access",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_agents_and_groups",help:"Select agents or access groups this key can access",children:(0,t.jsx)(A.default,{onChange:e=>ex.setFieldValue("allowed_agents_and_groups",e),value:ex.getFieldValue("allowed_agents_and_groups"),accessToken:ei,placeholder:"Select agents or access groups (optional)"})})})]}),ec?(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Logging Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(B.default,{value:eG,onChange:eR,premiumUser:!0,disabledCallbacks:e3,onDisabledCallbacksChange:e6})})})]}):(0,t.jsx)(S.Tooltip,{title:(0,t.jsxs)("span",{children:["Key-level logging settings is an enterprise feature, get in touch -",(0,t.jsx)("a",{href:"https://www.litellm.ai/enterprise",target:"_blank",children:"https://www.litellm.ai/enterprise"})]}),placement:"top",children:(0,t.jsxs)("div",{style:{position:"relative"},children:[(0,t.jsx)("div",{style:{opacity:.5},children:(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Logging Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(B.default,{value:eG,onChange:eR,premiumUser:!1,disabledCallbacks:e3,onDisabledCallbacksChange:e6})})})]})}),(0,t.jsx)("div",{style:{position:"absolute",inset:0,cursor:"not-allowed"}})]})}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Router Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4 w-full",children:(0,t.jsx)(D.default,{accessToken:ei||"",value:tr||void 0,onChange:ti,modelData:ew.length>0?{data:ew.map(e=>({model_name:e}))}:void 0},tn)})})]},`router-settings-accordion-${tn}`),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Model Aliases"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsxs)("div",{className:"mt-4",children:[(0,t.jsx)(h.Text,{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,t.jsx)(E.default,{accessToken:ei,initialModelAliases:e8,onAliasUpdate:te,showExampleConfig:!1})]})})]}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Key Lifecycle"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(O.default,{form:ex,autoRotationEnabled:tt,onAutoRotationChange:ts,rotationInterval:ta,onRotationIntervalChange:tl,isCreateMode:!0})})}),(0,t.jsx)(_.Form.Item,{name:"duration",hidden:!0,initialValue:null,children:(0,t.jsx)(j.Input,{})})]}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("b",{children:"Advanced Settings"}),(0,t.jsx)(S.Tooltip,{title:(0,t.jsxs)("span",{children:["Learn more about advanced settings in our"," ",(0,t.jsx)("a",{href:H.proxyBaseUrl?`${H.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,t.jsx)(n.InfoCircleOutlined,{className:"text-gray-400 hover:text-gray-300 cursor-help"})})]})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)(P.default,{schemaComponent:"GenerateKeyRequest",form:ex,excludedFields:["key_alias","team_id","models","duration","metadata","tags","guardrails","max_budget","budget_duration","tpm_limit","rpm_limit"]})})]})]})]})}),(0,t.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,t.jsx)(f.Button,{htmlType:"submit",disabled:th,style:{opacity:th?.5:1},children:"Create Key"})})]})}),eW&&(0,t.jsx)(b.Modal,{title:"Create New User",open:eW,onCancel:()=>eH(!1),footer:null,width:800,children:(0,t.jsx)(K.CreateUserButton,{userID:en,accessToken:ei,teams:Q,possibleUIRoles:eY,onUserCreated:e=>{eJ(e),ex.setFieldsValue({user_id:e}),eH(!1)},isEmbedded:!0})}),e_&&(0,t.jsx)(b.Modal,{open:ey,onOk:tp,onCancel:tg,footer:null,children:(0,t.jsxs)(g.Grid,{numItems:1,className:"gap-2 w-full",children:[(0,t.jsx)(y.Title,{children:"Save your Key"}),(0,t.jsx)(p.Col,{numColSpan:1,children:null!=e_?(0,t.jsx)(Y,{apiKey:e_}):(0,t.jsx)(h.Text,{children:"Key being created, this might take 30s"})})]})})]})},"fetchTeamModels",0,et,"fetchUserModels",0,es],702597)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/4242033bd0f32638.js b/litellm/proxy/_experimental/out/_next/static/chunks/4242033bd0f32638.js new file mode 100644 index 00000000000..b72fc16e355 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/4242033bd0f32638.js @@ -0,0 +1 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,772345,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M168 504.2c1-43.7 10-86.1 26.9-126 17.3-41 42.1-77.7 73.7-109.4S337 212.3 378 195c42.4-17.9 87.4-27 133.9-27s91.5 9.1 133.8 27A341.5 341.5 0 01755 268.8c9.9 9.9 19.2 20.4 27.8 31.4l-60.2 47a8 8 0 003 14.1l175.7 43c5 1.2 9.9-2.6 9.9-7.7l.8-180.9c0-6.7-7.7-10.5-12.9-6.3l-56.4 44.1C765.8 155.1 646.2 92 511.8 92 282.7 92 96.3 275.6 92 503.8a8 8 0 008 8.2h60c4.4 0 7.9-3.5 8-7.8zm756 7.8h-60c-4.4 0-7.9 3.5-8 7.8-1 43.7-10 86.1-26.9 126-17.3 41-42.1 77.8-73.7 109.4A342.45 342.45 0 01512.1 856a342.24 342.24 0 01-243.2-100.8c-9.9-9.9-19.2-20.4-27.8-31.4l60.2-47a8 8 0 00-3-14.1l-175.7-43c-5-1.2-9.9 2.6-9.9 7.7l-.7 181c0 6.7 7.7 10.5 12.9 6.3l56.4-44.1C258.2 868.9 377.8 932 512.2 932c229.2 0 415.5-183.7 419.8-411.8a8 8 0 00-8-8.2z"}}]},name:"sync",theme:"outlined"};var l=e.i(9583),r=a.forwardRef(function(e,r){return a.createElement(l.default,(0,t.default)({},e,{ref:r,icon:s}))});e.s(["SyncOutlined",0,r],772345)},962944,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M848 359.3H627.7L825.8 109c4.1-5.3.4-13-6.3-13H436c-2.8 0-5.5 1.5-6.9 4L170 547.5c-3.1 5.3.7 12 6.9 12h174.4l-89.4 357.6c-1.9 7.8 7.5 13.3 13.3 7.7L853.5 373c5.2-4.9 1.7-13.7-5.5-13.7zM378.2 732.5l60.3-241H281.1l189.6-327.4h224.6L487 427.4h211L378.2 732.5z"}}]},name:"thunderbolt",theme:"outlined"};var l=e.i(9583),r=a.forwardRef(function(e,r){return a.createElement(l.default,(0,t.default)({},e,{ref:r,icon:s}))});e.s(["ThunderboltOutlined",0,r],962944)},11751,e=>{"use strict";function t(e){return""===e?null:e}e.s(["mapEmptyStringToNull",()=>t])},643449,e=>{"use strict";var t=e.i(843476),a=e.i(599724),s=e.i(389083),l=e.i(810757),r=e.i(477386),i=e.i(557662);e.s(["default",0,function({loggingConfigs:e=[],disabledCallbacks:n=[],variant:o="card",className:d=""}){let c=(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(l.CogIcon,{className:"h-4 w-4 text-blue-600"}),(0,t.jsx)(a.Text,{className:"font-semibold text-gray-900",children:"Logging Integrations"}),(0,t.jsx)(s.Badge,{color:"blue",size:"xs",children:e.length})]}),e.length>0?(0,t.jsx)("div",{className:"space-y-3",children:e.map((e,r)=>{var n;let o=(n=e.callback_name,Object.entries(i.callback_map).find(([e,t])=>t===n)?.[0]||n),d=i.callbackInfo[o]?.logo;return(0,t.jsxs)("div",{className:"flex items-center justify-between p-3 rounded-lg bg-blue-50 border border-blue-200",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[d?(0,t.jsx)("img",{src:d,alt:o,className:"w-5 h-5 object-contain"}):(0,t.jsx)(l.CogIcon,{className:"h-5 w-5 text-gray-400"}),(0,t.jsxs)("div",{children:[(0,t.jsx)(a.Text,{className:"font-medium text-blue-800",children:o}),(0,t.jsxs)(a.Text,{className:"text-xs text-blue-600",children:[Object.keys(e.callback_vars).length," parameters configured"]})]})]}),(0,t.jsx)(s.Badge,{color:(e=>{switch(e){case"success":return"green";case"failure":return"red";case"success_and_failure":return"blue";default:return"gray"}})(e.callback_type),size:"sm",children:(e=>{switch(e){case"success":return"Success Only";case"failure":return"Failure Only";case"success_and_failure":return"Success & Failure";default:return e}})(e.callback_type)})]},r)})}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 border border-gray-200",children:[(0,t.jsx)(l.CogIcon,{className:"h-4 w-4 text-gray-400"}),(0,t.jsx)(a.Text,{className:"text-gray-500 text-sm",children:"No logging integrations configured"})]})]}),(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(r.BanIcon,{className:"h-4 w-4 text-red-600"}),(0,t.jsx)(a.Text,{className:"font-semibold text-gray-900",children:"Disabled Callbacks"}),(0,t.jsx)(s.Badge,{color:"red",size:"xs",children:n.length})]}),n.length>0?(0,t.jsx)("div",{className:"space-y-3",children:n.map((e,l)=>{let n=i.reverse_callback_map[e]||e,o=i.callbackInfo[n]?.logo;return(0,t.jsxs)("div",{className:"flex items-center justify-between p-3 rounded-lg bg-red-50 border border-red-200",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[o?(0,t.jsx)("img",{src:o,alt:n,className:"w-5 h-5 object-contain"}):(0,t.jsx)(r.BanIcon,{className:"h-5 w-5 text-gray-400"}),(0,t.jsxs)("div",{children:[(0,t.jsx)(a.Text,{className:"font-medium text-red-800",children:n}),(0,t.jsx)(a.Text,{className:"text-xs text-red-600",children:"Disabled for this key"})]})]}),(0,t.jsx)(s.Badge,{color:"red",size:"sm",children:"Disabled"})]},l)})}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 border border-gray-200",children:[(0,t.jsx)(r.BanIcon,{className:"h-4 w-4 text-gray-400"}),(0,t.jsx)(a.Text,{className:"text-gray-500 text-sm",children:"No callbacks disabled"})]})]})]});return"card"===o?(0,t.jsxs)("div",{className:`bg-white border border-gray-200 rounded-lg p-6 ${d}`,children:[(0,t.jsx)("div",{className:"flex items-center gap-2 mb-6",children:(0,t.jsxs)("div",{children:[(0,t.jsx)(a.Text,{className:"font-semibold text-gray-900",children:"Logging Settings"}),(0,t.jsx)(a.Text,{className:"text-xs text-gray-500",children:"Active logging integrations and disabled callbacks for this key"})]})}),c]}):(0,t.jsxs)("div",{className:`${d}`,children:[(0,t.jsx)(a.Text,{className:"font-medium text-gray-900 mb-3",children:"Logging Settings"}),c]})}])},183588,e=>{"use strict";var t=e.i(843476),a=e.i(266484);e.s(["default",0,({value:e,onChange:s,disabledCallbacks:l=[],onDisabledCallbacksChange:r})=>(0,t.jsx)(a.default,{value:e,onChange:s,disabledCallbacks:l,onDisabledCallbacksChange:r})])},72713,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M880 184H712v-64c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v64H384v-64c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v64H144c-17.7 0-32 14.3-32 32v664c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V216c0-17.7-14.3-32-32-32zm-40 656H184V460h656v380zM184 392V256h128v48c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8v-48h256v48c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8v-48h128v136H184z"}}]},name:"calendar",theme:"outlined"};var l=e.i(9583),r=a.forwardRef(function(e,r){return a.createElement(l.default,(0,t.default)({},e,{ref:r,icon:s}))});e.s(["CalendarOutlined",0,r],72713)},534172,3750,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M866.9 169.9L527.1 54.1C523 52.7 517.5 52 512 52s-11 .7-15.1 2.1L157.1 169.9c-8.3 2.8-15.1 12.4-15.1 21.2v482.4c0 8.8 5.7 20.4 12.6 25.9L499.3 968c3.5 2.7 8 4.1 12.6 4.1s9.2-1.4 12.6-4.1l344.7-268.6c6.9-5.4 12.6-17 12.6-25.9V191.1c.2-8.8-6.6-18.3-14.9-21.2zM810 654.3L512 886.5 214 654.3V226.7l298-101.6 298 101.6v427.6zm-405.8-201c-3-4.1-7.8-6.6-13-6.6H336c-6.5 0-10.3 7.4-6.5 12.7l126.4 174a16.1 16.1 0 0026 0l212.6-292.7c3.8-5.3 0-12.7-6.5-12.7h-55.2c-5.1 0-10 2.5-13 6.6L468.9 542.4l-64.7-89.1z"}}]},name:"safety-certificate",theme:"outlined"};var l=e.i(9583),r=a.forwardRef(function(e,r){return a.createElement(l.default,(0,t.default)({},e,{ref:r,icon:s}))});e.s(["SafetyCertificateOutlined",0,r],534172);let i={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M668.6 320c0-4.4-3.6-8-8-8h-54.5c-3 0-5.8 1.7-7.1 4.4l-84.7 168.8H511l-84.7-168.8a8 8 0 00-7.1-4.4h-55.7c-1.3 0-2.6.3-3.8 1-3.9 2.1-5.3 7-3.2 10.8l103.9 191.6h-57c-4.4 0-8 3.6-8 8v27.1c0 4.4 3.6 8 8 8h76v39h-76c-4.4 0-8 3.6-8 8v27.1c0 4.4 3.6 8 8 8h76V704c0 4.4 3.6 8 8 8h49.9c4.4 0 8-3.6 8-8v-63.5h76.3c4.4 0 8-3.6 8-8v-27.1c0-4.4-3.6-8-8-8h-76.3v-39h76.3c4.4 0 8-3.6 8-8v-27.1c0-4.4-3.6-8-8-8H564l103.7-191.6c.5-1.1.9-2.4.9-3.7zM157.9 504.2a352.7 352.7 0 01103.5-242.4c32.5-32.5 70.3-58.1 112.4-75.9 43.6-18.4 89.9-27.8 137.6-27.8 47.8 0 94.1 9.3 137.6 27.8 42.1 17.8 79.9 43.4 112.4 75.9 10 10 19.3 20.5 27.9 31.4l-50 39.1a8 8 0 003 14.1l156.8 38.3c5 1.2 9.9-2.6 9.9-7.7l.8-161.5c0-6.7-7.7-10.5-12.9-6.3l-47.8 37.4C770.7 146.3 648.6 82 511.5 82 277 82 86.3 270.1 82 503.8a8 8 0 008 8.2h60c4.3 0 7.8-3.5 7.9-7.8zM934 512h-60c-4.3 0-7.9 3.5-8 7.8a352.7 352.7 0 01-103.5 242.4 352.57 352.57 0 01-112.4 75.9c-43.6 18.4-89.9 27.8-137.6 27.8s-94.1-9.3-137.6-27.8a352.57 352.57 0 01-112.4-75.9c-10-10-19.3-20.5-27.9-31.4l49.9-39.1a8 8 0 00-3-14.1l-156.8-38.3c-5-1.2-9.9 2.6-9.9 7.7l-.8 161.7c0 6.7 7.7 10.5 12.9 6.3l47.8-37.4C253.3 877.7 375.4 942 512.5 942 747 942 937.7 753.9 942 520.2a8 8 0 00-8-8.2z"}}]},name:"transaction",theme:"outlined"};var n=a.forwardRef(function(e,s){return a.createElement(l.default,(0,t.default)({},e,{ref:s,icon:i}))});e.s(["TransactionOutlined",0,n],3750)},304911,e=>{"use strict";var t=e.i(843476),a=e.i(262218);let{Text:s}=e.i(898586).Typography;function l({userId:e}){return"default_user_id"===e?(0,t.jsx)(a.Tag,{color:"blue",children:"Default Proxy Admin"}):(0,t.jsx)(s,{children:e})}e.s(["default",()=>l])},784647,505022,721929,e=>{"use strict";var t=e.i(843476),a=e.i(464571),s=e.i(898586),l=e.i(592968),r=e.i(770914),i=e.i(312361),n=e.i(525720),o=e.i(447566),d=e.i(772345),c=e.i(955135),m=e.i(646563),u=e.i(771674),x=e.i(948401),p=e.i(72713),g=e.i(637235),h=e.i(962944),j=e.i(534172),_=e.i(3750),y=e.i(304911);let{Text:b}=s.Typography;function f({label:e,value:a,icon:s,truncate:l=!1,copyable:i=!1,defaultUserIdCheck:n=!1}){let o=!a,d=n&&"default_user_id"===a,c=d?(0,t.jsx)(y.default,{userId:a}):(0,t.jsx)(b,{strong:!0,copyable:!!(i&&!o&&!d)&&{tooltips:[`Copy ${e}`,"Copied!"]},ellipsis:l,style:l?{maxWidth:160,display:"block"}:void 0,children:o?"-":a});return(0,t.jsxs)("div",{children:[(0,t.jsxs)(r.Space,{size:4,children:[(0,t.jsx)(b,{type:"secondary",children:s}),(0,t.jsx)(b,{type:"secondary",style:{fontSize:12,textTransform:"uppercase",letterSpacing:"0.05em"},children:e})]}),(0,t.jsx)("div",{children:c})]})}let{Title:v,Text:N}=s.Typography;function k({data:e,onBack:s,onCreateNew:y,onRegenerate:b,onDelete:k,onResetSpend:T,canModifyKey:w=!0,backButtonText:S="Back to Keys",regenerateDisabled:I=!1,regenerateTooltip:C}){return(0,t.jsxs)("div",{children:[y&&(0,t.jsx)("div",{style:{marginBottom:16},children:(0,t.jsx)(a.Button,{type:"primary",icon:(0,t.jsx)(m.PlusOutlined,{}),onClick:y,children:"Create New Key"})}),(0,t.jsx)("div",{style:{marginBottom:16},children:(0,t.jsx)(a.Button,{type:"text",icon:(0,t.jsx)(o.ArrowLeftOutlined,{}),onClick:s,children:S})}),(0,t.jsxs)(n.Flex,{justify:"space-between",align:"start",style:{marginBottom:20},children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(v,{level:3,copyable:{tooltips:["Copy Key Alias","Copied!"]},style:{margin:0},children:e.keyName}),(0,t.jsxs)(N,{type:"secondary",copyable:{text:e.keyId,tooltips:["Copy Key ID","Copied!"]},children:["Key ID: ",e.keyId]})]}),w&&(0,t.jsxs)(r.Space,{children:[(0,t.jsx)(l.Tooltip,{title:C||"",children:(0,t.jsx)("span",{children:(0,t.jsx)(a.Button,{icon:(0,t.jsx)(d.SyncOutlined,{}),onClick:b,disabled:I,children:"Regenerate Key"})})}),T&&(0,t.jsx)(a.Button,{danger:!0,icon:(0,t.jsx)(_.TransactionOutlined,{}),onClick:T,children:"Reset Spend"}),(0,t.jsx)(a.Button,{danger:!0,icon:(0,t.jsx)(c.DeleteOutlined,{}),onClick:k,children:"Delete Key"})]})]}),(0,t.jsxs)(n.Flex,{align:"stretch",gap:40,style:{marginBottom:40},children:[(0,t.jsxs)(r.Space,{direction:"vertical",size:16,children:[(0,t.jsx)(f,{label:"User Email",value:e.userEmail,icon:(0,t.jsx)(x.MailOutlined,{})}),(0,t.jsx)(f,{label:"User ID",value:e.userId,icon:(0,t.jsx)(u.UserOutlined,{}),truncate:!0,copyable:!0,defaultUserIdCheck:!0})]}),(0,t.jsx)(i.Divider,{type:"vertical",style:{height:"auto"}}),(0,t.jsxs)(r.Space,{direction:"vertical",size:16,children:[(0,t.jsx)(f,{label:"Created At",value:e.createdAt,icon:(0,t.jsx)(p.CalendarOutlined,{})}),(0,t.jsx)(f,{label:"Created By",value:e.createdBy,icon:(0,t.jsx)(j.SafetyCertificateOutlined,{}),truncate:!0,copyable:!0,defaultUserIdCheck:!0})]}),(0,t.jsx)(i.Divider,{type:"vertical",style:{height:"auto"}}),(0,t.jsxs)(r.Space,{direction:"vertical",size:16,children:[(0,t.jsx)(f,{label:"Last Updated",value:e.lastUpdated,icon:(0,t.jsx)(g.ClockCircleOutlined,{})}),(0,t.jsx)(f,{label:"Last Active",value:e.lastActive,icon:(0,t.jsx)(h.ThunderboltOutlined,{})})]})]})]})}e.s(["KeyInfoHeader",()=>k],784647);var T=e.i(599724),w=e.i(389083),S=e.i(278587),I=e.i(271645);let C=I.forwardRef(function(e,t){return I.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:t},e),I.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"}))});e.s(["default",0,({autoRotate:e=!1,rotationInterval:a,lastRotationAt:s,keyRotationAt:l,nextRotationAt:r,variant:i="card",className:n=""})=>{let o=e=>{let t=new Date(e),a=t.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"}),s=t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0});return`${a} at ${s}`},d=(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsx)("div",{className:"space-y-3",children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(S.RefreshIcon,{className:"h-4 w-4 text-blue-600"}),(0,t.jsx)(T.Text,{className:"font-semibold text-gray-900",children:"Auto-Rotation"}),(0,t.jsx)(w.Badge,{color:e?"green":"gray",size:"xs",children:e?"Enabled":"Disabled"}),e&&a&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(T.Text,{className:"text-gray-400",children:"•"}),(0,t.jsxs)(T.Text,{className:"text-sm text-gray-600",children:["Every ",a]})]})]})}),(e||s||l||r)&&(0,t.jsxs)("div",{className:"space-y-3",children:[s&&(0,t.jsxs)("div",{className:"flex items-center gap-2 p-3 bg-gray-50 border border-gray-200 rounded-md",children:[(0,t.jsx)(C,{className:"w-4 h-4 text-gray-500"}),(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsx)(T.Text,{className:"font-medium text-gray-700",children:"Last Rotation"}),(0,t.jsx)(T.Text,{className:"text-sm text-gray-600",children:o(s)})]})]}),(l||r)&&(0,t.jsxs)("div",{className:"flex items-center gap-2 p-3 bg-gray-50 border border-gray-200 rounded-md",children:[(0,t.jsx)(C,{className:"w-4 h-4 text-gray-500"}),(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsx)(T.Text,{className:"font-medium text-gray-700",children:"Next Scheduled Rotation"}),(0,t.jsx)(T.Text,{className:"text-sm text-gray-600",children:o(r||l||"")})]})]}),e&&!s&&!l&&!r&&(0,t.jsxs)("div",{className:"flex items-center gap-2 p-3 bg-gray-50 border border-gray-100 rounded-md",children:[(0,t.jsx)(C,{className:"w-4 h-4 text-gray-500"}),(0,t.jsx)(T.Text,{className:"text-gray-600",children:"No rotation history available"})]})]}),!e&&!s&&!l&&!r&&(0,t.jsxs)("div",{className:"flex items-center gap-2 p-3 bg-gray-50 border border-gray-100 rounded-md",children:[(0,t.jsx)(S.RefreshIcon,{className:"w-4 h-4 text-gray-400"}),(0,t.jsx)(T.Text,{className:"text-gray-600",children:"Auto-rotation is not enabled for this key"})]})]});return"card"===i?(0,t.jsxs)("div",{className:`bg-white border border-gray-200 rounded-lg p-6 ${n}`,children:[(0,t.jsx)("div",{className:"flex items-center gap-2 mb-6",children:(0,t.jsxs)("div",{children:[(0,t.jsx)(T.Text,{className:"font-semibold text-gray-900",children:"Auto-Rotation"}),(0,t.jsx)(T.Text,{className:"text-xs text-gray-500",children:"Automatic key rotation settings and status for this key"})]})}),d]}):(0,t.jsxs)("div",{className:`${n}`,children:[(0,t.jsx)(T.Text,{className:"font-medium text-gray-900 mb-3",children:"Auto-Rotation"}),d]})}],505022);let A=["logging"];e.s(["extractLoggingSettings",0,e=>e&&"object"==typeof e&&Array.isArray(e.logging)?e.logging:[],"formatMetadataForDisplay",0,(e,t=2)=>JSON.stringify(e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([e])=>!A.includes(e))):{},null,t),"stripTagsFromMetadata",0,e=>{if(!e||"object"!=typeof e)return e;let{tags:t,...a}=e;return a}],721929)},65932,690284,e=>{"use strict";var t=e.i(954616),a=e.i(912598),s=e.i(764205),l=e.i(135214),r=e.i(207082);let i=async(e,t)=>{let a=(0,s.getProxyBaseUrl)(),l=`${a?`${a}/key/${t}/reset_spend`:`/key/${t}/reset_spend`}`,r=await fetch(l,{method:"POST",headers:{[(0,s.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({reset_to:0})});if(!r.ok){let e=await r.json(),t=(0,s.deriveErrorMessage)(e);throw(0,s.handleError)(t),Error(t)}return r.json()};e.s(["useResetKeySpend",0,()=>{let{accessToken:e}=(0,l.default)(),s=(0,a.useQueryClient)();return(0,t.useMutation)({mutationFn:async t=>{if(!e)throw Error("Access token is required");return i(e,t)},onSuccess:()=>{s.invalidateQueries({queryKey:r.keyKeys.all})}})}],65932);var n=e.i(843476),o=e.i(994388),d=e.i(309426),c=e.i(350967),m=e.i(599724),u=e.i(779241),x=e.i(629569),p=e.i(808613),g=e.i(28651),h=e.i(212931),j=e.i(439189),_=e.i(497245),y=e.i(96226),b=e.i(435684);function f(e,t){let{years:a=0,months:s=0,weeks:l=0,days:r=0,hours:i=0,minutes:n=0,seconds:o=0}=t,d=(0,b.toDate)(e),c=s||a?(0,_.addMonths)(d,s+12*a):d,m=r||l?(0,j.addDays)(c,r+7*l):c;return(0,y.constructFrom)(e,m.getTime()+1e3*(o+60*(n+60*i)))}var v=e.i(271645),N=e.i(237016),k=e.i(727749);function T({selectedToken:e,visible:t,onClose:a,onKeyUpdate:r}){let{accessToken:i}=(0,l.default)(),[j]=p.Form.useForm(),[_,y]=(0,v.useState)(null),[b,T]=(0,v.useState)(null),[w,S]=(0,v.useState)(null),[I,C]=(0,v.useState)(!1),[A,F]=(0,v.useState)(!1),[L,M]=(0,v.useState)(null);(0,v.useEffect)(()=>{t&&e&&i&&(j.setFieldsValue({key_alias:e.key_alias,max_budget:e.max_budget,tpm_limit:e.tpm_limit,rpm_limit:e.rpm_limit,duration:e.duration||"",grace_period:""}),M(i),F(e.key_name===i))},[t,e,j,i]),(0,v.useEffect)(()=>{t||(y(null),C(!1),F(!1),M(null),j.resetFields())},[t,j]);let R=e=>{if(!e)return null;try{let t,a=new Date;if(e.endsWith("s"))t=f(a,{seconds:parseInt(e)});else if(e.endsWith("h"))t=f(a,{hours:parseInt(e)});else if(e.endsWith("d"))t=f(a,{days:parseInt(e)});else throw Error("Invalid duration format");return t.toLocaleString()}catch(e){return null}};(0,v.useEffect)(()=>{b?.duration?S(R(b.duration)):S(null)},[b?.duration]);let D=async()=>{if(e&&L){C(!0);try{let t=await j.validateFields(),a=await (0,s.regenerateKeyCall)(L,e.token||e.token_id,t);y(a.key),k.default.success("Virtual Key regenerated successfully"),console.log("Full regenerate response:",a);let l={token:a.token||a.key_id||e.token,key_name:a.key,max_budget:t.max_budget,tpm_limit:t.tpm_limit,rpm_limit:t.rpm_limit,expires:t.duration?R(t.duration):e.expires,...a};console.log("Updated key data with new token:",l),r&&r(l),C(!1)}catch(e){console.error("Error regenerating key:",e),k.default.fromBackend(e),C(!1)}}},B=()=>{y(null),C(!1),F(!1),M(null),j.resetFields(),a()};return(0,n.jsx)(h.Modal,{title:"Regenerate Virtual Key",open:t,onCancel:B,footer:_?[(0,n.jsx)(o.Button,{onClick:B,children:"Close"},"close")]:[(0,n.jsx)(o.Button,{onClick:B,className:"mr-2",children:"Cancel"},"cancel"),(0,n.jsx)(o.Button,{onClick:D,disabled:I,children:I?"Regenerating...":"Regenerate"},"regenerate")],children:_?(0,n.jsxs)(c.Grid,{numItems:1,className:"gap-2 w-full",children:[(0,n.jsx)(x.Title,{children:"Regenerated Key"}),(0,n.jsx)(d.Col,{numColSpan:1,children:(0,n.jsxs)("p",{children:["Please replace your old key with the new key generated. For security reasons,"," ",(0,n.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,n.jsxs)(d.Col,{numColSpan:1,children:[(0,n.jsx)(m.Text,{className:"mt-3",children:"Key Alias:"}),(0,n.jsx)("div",{className:"bg-gray-100 p-2 rounded mb-2",children:(0,n.jsx)("pre",{className:"break-words whitespace-normal",children:e?.key_alias||"No alias set"})}),(0,n.jsx)(m.Text,{className:"mt-3",children:"New Virtual Key:"}),(0,n.jsx)("div",{className:"bg-gray-100 p-2 rounded mb-2",children:(0,n.jsx)("pre",{className:"break-words whitespace-normal",children:_})}),(0,n.jsx)(N.CopyToClipboard,{text:_,onCopy:()=>k.default.success("Virtual Key copied to clipboard"),children:(0,n.jsx)(o.Button,{className:"mt-3",children:"Copy Virtual Key"})})]})]}):(0,n.jsxs)(p.Form,{form:j,layout:"vertical",onValuesChange:e=>{"duration"in e&&T(t=>({...t,duration:e.duration}))},children:[(0,n.jsx)(p.Form.Item,{name:"key_alias",label:"Key Alias",children:(0,n.jsx)(u.TextInput,{disabled:!0})}),(0,n.jsx)(p.Form.Item,{name:"max_budget",label:"Max Budget (USD)",children:(0,n.jsx)(g.InputNumber,{step:.01,precision:2,style:{width:"100%"}})}),(0,n.jsx)(p.Form.Item,{name:"tpm_limit",label:"TPM Limit",children:(0,n.jsx)(g.InputNumber,{style:{width:"100%"}})}),(0,n.jsx)(p.Form.Item,{name:"rpm_limit",label:"RPM Limit",children:(0,n.jsx)(g.InputNumber,{style:{width:"100%"}})}),(0,n.jsx)(p.Form.Item,{name:"duration",label:"Expire Key (eg: 30s, 30h, 30d)",className:"mt-8",children:(0,n.jsx)(u.TextInput,{placeholder:""})}),(0,n.jsxs)("div",{className:"mt-2 text-sm text-gray-500",children:["Current expiry: ",e?.expires?new Date(e.expires).toLocaleString():"Never"]}),w&&(0,n.jsxs)("div",{className:"mt-2 text-sm text-green-600",children:["New expiry: ",w]}),(0,n.jsx)(p.Form.Item,{name:"grace_period",label:"Grace Period (eg: 24h, 2d)",tooltip:"Keep the old key valid for this duration after rotation. Both keys work during this period for seamless cutover. Empty = immediate revoke.",className:"mt-8",rules:[{pattern:/^(\d+(s|m|h|d|w|mo))?$/,message:"Must be a duration like 30s, 30m, 24h, 2d, 1w, or 1mo"}],children:(0,n.jsx)(u.TextInput,{placeholder:"e.g. 24h, 2d (empty = immediate revoke)"})}),(0,n.jsx)("div",{className:"mt-2 text-sm text-gray-500",children:"Recommended: 24h to 72h for production keys to allow seamless client migration."})]})})}e.s(["RegenerateKeyModal",()=>T],690284)},20147,e=>{"use strict";var t=e.i(843476),a=e.i(135214),s=e.i(510674),l=e.i(292639),r=e.i(214541),i=e.i(500330),n=e.i(11751),o=e.i(530212),d=e.i(389083),c=e.i(994388),m=e.i(304967),u=e.i(350967),x=e.i(197647),p=e.i(653824),g=e.i(881073),h=e.i(404206),j=e.i(723731),_=e.i(599724),y=e.i(629569),b=e.i(808613),f=e.i(212931),v=e.i(262218),N=e.i(784647),k=e.i(271645),T=e.i(708347),w=e.i(557662),S=e.i(505022),I=e.i(127952),C=e.i(721929),A=e.i(643449),F=e.i(727749),L=e.i(764205),M=e.i(65932),R=e.i(384767),D=e.i(690284),B=e.i(190702),E=e.i(891547),P=e.i(921511),O=e.i(827252),K=e.i(779241),U=e.i(311451),V=e.i(199133),$=e.i(790848),z=e.i(592968),G=e.i(552130),W=e.i(9314),H=e.i(392110),q=e.i(844565),J=e.i(939510),Q=e.i(75921),Y=e.i(390605),X=e.i(702597),Z=e.i(435451),ee=e.i(183588),et=e.i(916940);function ea({keyData:e,onCancel:a,onSubmit:r,teams:i,accessToken:n,userID:o,userRole:d,premiumUser:m=!1}){let u=m||null!=d&&T.rolesWithWriteAccess.includes(d),[x]=b.Form.useForm(),[p,g]=(0,k.useState)([]),[h,j]=(0,k.useState)({}),_=i?.find(t=>t.team_id===e.team_id),[y,f]=(0,k.useState)([]),[v,N]=(0,k.useState)(Array.isArray(e.metadata?.litellm_disabled_callbacks)?(0,w.mapInternalToDisplayNames)(e.metadata.litellm_disabled_callbacks):[]),[S,I]=(0,k.useState)(e.auto_rotate||!1),[A,M]=(0,k.useState)(e.rotation_interval||""),[R,D]=(0,k.useState)(!e.expires),[B,ea]=(0,k.useState)(!1),{data:es}=(0,s.useProjects)(),{data:el}=(0,l.useUISettings)(),er=!!el?.values?.enable_projects_ui,ei=!!e.project_id,en=(()=>{if(!e.project_id)return null;let t=es?.find(t=>t.project_id===e.project_id);return t?.project_alias?`${t.project_alias} (${e.project_id})`:e.project_id})();(0,k.useEffect)(()=>{let t=async()=>{if(o&&d&&n)try{if(null===e.team_id){let e=(await (0,L.modelAvailableCall)(n,o,d)).data.map(e=>e.id);f(e)}else if(_?.team_id){let e=await (0,X.fetchTeamModels)(o,d,n,_.team_id);f(Array.from(new Set([..._.models,...e])))}}catch(e){console.error("Error fetching models:",e)}};(async()=>{if(n)try{let e=await (0,L.getPromptsList)(n);g(e.prompts.map(e=>e.prompt_id))}catch(e){console.error("Failed to fetch prompts:",e)}})(),t()},[o,d,n,_,e.team_id]),(0,k.useEffect)(()=>{x.setFieldValue("disabled_callbacks",v)},[x,v]);let eo=e=>e&&({"24h":"daily","7d":"weekly","30d":"monthly"})[e]||null,ed={...e,token:e.token||e.token_id,budget_duration:eo(e.budget_duration),metadata:(0,C.formatMetadataForDisplay)((0,C.stripTagsFromMetadata)(e.metadata)),guardrails:e.metadata?.guardrails,disable_global_guardrails:e.metadata?.disable_global_guardrails||!1,prompts:e.metadata?.prompts,tags:e.metadata?.tags,vector_stores:e.object_permission?.vector_stores||[],mcp_servers_and_groups:{servers:e.object_permission?.mcp_servers||[],accessGroups:e.object_permission?.mcp_access_groups||[]},mcp_tool_permissions:e.object_permission?.mcp_tool_permissions||{},agents_and_groups:{agents:e.object_permission?.agents||[],accessGroups:e.object_permission?.agent_access_groups||[]},logging_settings:(0,C.extractLoggingSettings)(e.metadata),disabled_callbacks:Array.isArray(e.metadata?.litellm_disabled_callbacks)?(0,w.mapInternalToDisplayNames)(e.metadata.litellm_disabled_callbacks):[],access_group_ids:e.access_group_ids||[],auto_rotate:e.auto_rotate||!1,...e.rotation_interval&&{rotation_interval:e.rotation_interval},allowed_routes:Array.isArray(e.allowed_routes)&&e.allowed_routes.length>0?e.allowed_routes.join(", "):""};(0,k.useEffect)(()=>{x.setFieldsValue({...e,token:e.token||e.token_id,budget_duration:eo(e.budget_duration),metadata:(0,C.formatMetadataForDisplay)((0,C.stripTagsFromMetadata)(e.metadata)),guardrails:e.metadata?.guardrails,disable_global_guardrails:e.metadata?.disable_global_guardrails||!1,prompts:e.metadata?.prompts,tags:e.metadata?.tags,vector_stores:e.object_permission?.vector_stores||[],mcp_servers_and_groups:{servers:e.object_permission?.mcp_servers||[],accessGroups:e.object_permission?.mcp_access_groups||[]},mcp_tool_permissions:e.object_permission?.mcp_tool_permissions||{},logging_settings:(0,C.extractLoggingSettings)(e.metadata),disabled_callbacks:Array.isArray(e.metadata?.litellm_disabled_callbacks)?(0,w.mapInternalToDisplayNames)(e.metadata.litellm_disabled_callbacks):[],access_group_ids:e.access_group_ids||[],auto_rotate:e.auto_rotate||!1,...e.rotation_interval&&{rotation_interval:e.rotation_interval},allowed_routes:Array.isArray(e.allowed_routes)&&e.allowed_routes.length>0?e.allowed_routes.join(", "):""})},[e,x]),(0,k.useEffect)(()=>{x.setFieldValue("auto_rotate",S)},[S,x]),(0,k.useEffect)(()=>{A&&x.setFieldValue("rotation_interval",A)},[A,x]),(0,k.useEffect)(()=>{(async()=>{if(n)try{let e=await (0,L.tagListCall)(n);j(e)}catch(e){F.default.fromBackend("Error fetching tags: "+e)}})()},[n]);let ec=async e=>{try{if(ea(!0),"string"==typeof e.allowed_routes){let t=e.allowed_routes.trim();""===t?e.allowed_routes=[]:e.allowed_routes=t.split(",").map(e=>e.trim()).filter(e=>e.length>0)}R&&(e.duration=null),await r(e)}finally{ea(!1)}};return(0,t.jsxs)(b.Form,{form:x,onFinish:ec,initialValues:ed,layout:"vertical",children:[(0,t.jsx)(b.Form.Item,{label:"Key Alias",name:"key_alias",children:(0,t.jsx)(K.TextInput,{})}),(0,t.jsx)(b.Form.Item,{label:"Models",name:"models",children:(0,t.jsx)(b.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.allowed_routes!==t.allowed_routes||e.models!==t.models,children:({getFieldValue:e,setFieldValue:a})=>{let s=e("allowed_routes")||"",l="string"==typeof s&&""!==s.trim()?s.split(",").map(e=>e.trim()).filter(e=>e.length>0):[],r=l.includes("management_routes")||l.includes("info_routes"),i=e("models")||[];return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(V.Select,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},disabled:r,value:r?[]:i,onChange:e=>a("models",e),children:[y.length>0&&(0,t.jsx)(V.Select.Option,{value:"all-team-models",children:"All Team Models"}),y.map(e=>(0,t.jsx)(V.Select.Option,{value:e,children:e},e))]}),r&&(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Models field is disabled for this key type"})]})}})}),(0,t.jsx)(b.Form.Item,{label:"Key Type",children:(0,t.jsx)(b.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.allowed_routes!==t.allowed_routes,children:({getFieldValue:e,setFieldValue:a})=>{var s;let l=e("allowed_routes")||"",r=(s="string"==typeof l&&""!==l.trim()?l.split(",").map(e=>e.trim()).filter(e=>e.length>0):[])&&0!==s.length?s.includes("llm_api_routes")?"llm_api":s.includes("management_routes")?"management":s.includes("info_routes")?"read_only":"default":"default";return(0,t.jsxs)(V.Select,{placeholder:"Select key type",style:{width:"100%"},optionLabelProp:"label",value:r,onChange:e=>{switch(e){case"default":a("allowed_routes","");break;case"llm_api":a("allowed_routes","llm_api_routes");break;case"management":a("allowed_routes","management_routes"),a("models",[])}},children:[(0,t.jsx)(V.Select.Option,{value:"default",label:"Default",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Default"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call AI APIs + Management routes"})]})}),(0,t.jsx)(V.Select.Option,{value:"llm_api",label:"AI APIs",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"AI APIs"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call only AI API routes (chat/completions, embeddings, etc.)"})]})}),(0,t.jsx)(V.Select.Option,{value:"management",label:"Management",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Management"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call only management routes (user/team/key management)"})]})})]})}})}),(0,t.jsx)(b.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Routes"," ",(0,t.jsx)(z.Tooltip,{title:"List of allowed routes for the key (comma-separated). Can be specific routes (e.g., '/chat/completions') or route patterns (e.g., 'llm_api_routes', 'management_routes', '/keys/*'). Leave empty to allow all routes.",children:(0,t.jsx)(O.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_routes",children:(0,t.jsx)(U.Input,{placeholder:"Enter allowed routes (comma-separated). Special values: llm_api_routes, management_routes. Examples: llm_api_routes, /chat/completions, /keys/*. Leave empty to allow all routes"})}),(0,t.jsx)(b.Form.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,t.jsx)(Z.default,{step:.01,style:{width:"100%"},placeholder:"Enter a numerical value"})}),(0,t.jsx)(b.Form.Item,{label:"Reset Budget",name:"budget_duration",children:(0,t.jsxs)(V.Select,{placeholder:"n/a",children:[(0,t.jsx)(V.Select.Option,{value:"daily",children:"Daily"}),(0,t.jsx)(V.Select.Option,{value:"weekly",children:"Weekly"}),(0,t.jsx)(V.Select.Option,{value:"monthly",children:"Monthly"})]})}),(0,t.jsx)(b.Form.Item,{label:"TPM Limit",name:"tpm_limit",children:(0,t.jsx)(Z.default,{min:0})}),(0,t.jsx)(J.default,{type:"tpm",name:"tpm_limit_type",showDetailedDescriptions:!1}),(0,t.jsx)(b.Form.Item,{label:"RPM Limit",name:"rpm_limit",children:(0,t.jsx)(Z.default,{min:0})}),(0,t.jsx)(J.default,{type:"rpm",name:"rpm_limit_type",showDetailedDescriptions:!1}),(0,t.jsx)(b.Form.Item,{label:"Max Parallel Requests",name:"max_parallel_requests",children:(0,t.jsx)(Z.default,{min:0})}),(0,t.jsx)(b.Form.Item,{label:"Model TPM Limit",name:"model_tpm_limit",children:(0,t.jsx)(U.Input.TextArea,{rows:4,placeholder:'{"gpt-4": 100, "claude-v1": 200}'})}),(0,t.jsx)(b.Form.Item,{label:"Model RPM Limit",name:"model_rpm_limit",children:(0,t.jsx)(U.Input.TextArea,{rows:4,placeholder:'{"gpt-4": 100, "claude-v1": 200}'})}),(0,t.jsx)(b.Form.Item,{label:"Guardrails",name:"guardrails",children:n&&(0,t.jsx)(E.default,{onChange:e=>{x.setFieldValue("guardrails",e)},accessToken:n,disabled:!u})}),(0,t.jsx)(b.Form.Item,{label:(0,t.jsxs)("span",{children:["Disable Global Guardrails"," ",(0,t.jsx)(z.Tooltip,{title:"When enabled, this key will bypass any guardrails configured to run on every request (global guardrails)",children:(0,t.jsx)(O.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"disable_global_guardrails",valuePropName:"checked",children:(0,t.jsx)($.Switch,{disabled:!u,checkedChildren:"Yes",unCheckedChildren:"No"})}),(0,t.jsx)(b.Form.Item,{label:(0,t.jsxs)("span",{children:["Policies"," ",(0,t.jsx)(z.Tooltip,{title:"Apply policies to this key to control guardrails and other settings",children:(0,t.jsx)(O.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"policies",children:n&&(0,t.jsx)(P.default,{onChange:e=>{x.setFieldValue("policies",e)},accessToken:n,disabled:!m})}),(0,t.jsx)(b.Form.Item,{label:"Tags",name:"tags",children:(0,t.jsx)(V.Select,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter tags",options:Object.values(h).map(e=>({value:e.name,label:e.name,title:e.description||e.name}))})}),(0,t.jsx)(b.Form.Item,{label:"Prompts",name:"prompts",children:(0,t.jsx)(z.Tooltip,{title:m?"":"Setting prompts by key is a premium feature",placement:"top",children:(0,t.jsx)(V.Select,{mode:"tags",style:{width:"100%"},disabled:!m,placeholder:m?Array.isArray(e.metadata?.prompts)&&e.metadata.prompts.length>0?`Current: ${e.metadata.prompts.join(", ")}`:"Select or enter prompts":"Premium feature - Upgrade to set prompts by key",options:p.map(e=>({value:e,label:e}))})})}),(0,t.jsx)(b.Form.Item,{label:(0,t.jsxs)("span",{children:["Access Groups"," ",(0,t.jsx)(z.Tooltip,{title:"Assign access groups to this key. Access groups control which models, MCP servers, and agents this key can use",children:(0,t.jsx)(O.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"access_group_ids",children:(0,t.jsx)(W.default,{placeholder:"Select access groups (optional)"})}),(0,t.jsx)(b.Form.Item,{label:"Allowed Pass Through Routes",name:"allowed_passthrough_routes",children:(0,t.jsx)(z.Tooltip,{title:m?"":"Setting allowed pass through routes by key is a premium feature",placement:"top",children:(0,t.jsx)(q.default,{onChange:e=>x.setFieldValue("allowed_passthrough_routes",e),value:x.getFieldValue("allowed_passthrough_routes"),accessToken:n||"",placeholder:m?Array.isArray(e.metadata?.allowed_passthrough_routes)&&e.metadata.allowed_passthrough_routes.length>0?`Current: ${e.metadata.allowed_passthrough_routes.join(", ")}`:"Select or enter allowed pass through routes":"Premium feature - Upgrade to set allowed pass through routes by key",disabled:!m})})}),(0,t.jsx)(b.Form.Item,{label:"Vector Stores",name:"vector_stores",children:(0,t.jsx)(et.default,{onChange:e=>x.setFieldValue("vector_stores",e),value:x.getFieldValue("vector_stores"),accessToken:n||"",placeholder:"Select vector stores"})}),(0,t.jsx)(b.Form.Item,{label:"MCP Servers / Access Groups",name:"mcp_servers_and_groups",children:(0,t.jsx)(Q.default,{onChange:e=>x.setFieldValue("mcp_servers_and_groups",e),value:x.getFieldValue("mcp_servers_and_groups"),accessToken:n||"",placeholder:"Select MCP servers or access groups (optional)"})}),(0,t.jsx)(b.Form.Item,{name:"mcp_tool_permissions",initialValue:{},hidden:!0,children:(0,t.jsx)(U.Input,{type:"hidden"})}),(0,t.jsx)(b.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.mcp_servers_and_groups!==t.mcp_servers_and_groups||e.mcp_tool_permissions!==t.mcp_tool_permissions,children:()=>(0,t.jsx)("div",{className:"mb-6",children:(0,t.jsx)(Y.default,{accessToken:n||"",selectedServers:x.getFieldValue("mcp_servers_and_groups")?.servers||[],toolPermissions:x.getFieldValue("mcp_tool_permissions")||{},onChange:e=>x.setFieldsValue({mcp_tool_permissions:e})})})}),(0,t.jsx)(b.Form.Item,{label:"Agents / Access Groups",name:"agents_and_groups",children:(0,t.jsx)(G.default,{onChange:e=>x.setFieldValue("agents_and_groups",e),value:x.getFieldValue("agents_and_groups"),accessToken:n||"",placeholder:"Select agents or access groups (optional)"})}),(0,t.jsx)(b.Form.Item,{label:"Team ID",name:"team_id",help:er&&ei?"Team is locked because this key belongs to a project":void 0,children:(0,t.jsx)(V.Select,{placeholder:"Select team",showSearch:!0,disabled:er&&ei,style:{width:"100%"},filterOption:(e,t)=>{let a=i?.find(e=>e.team_id===t?.value);return!!a&&(a.team_alias?.toLowerCase().includes(e.toLowerCase())??!1)},children:i?.map(e=>(0,t.jsx)(V.Select.Option,{value:e.team_id,children:`${e.team_alias} (${e.team_id})`},e.team_id))})}),er&&ei&&(0,t.jsx)(b.Form.Item,{label:"Project",children:(0,t.jsx)(U.Input,{value:en??"",disabled:!0})}),(0,t.jsx)(b.Form.Item,{label:"Logging Settings",name:"logging_settings",children:(0,t.jsx)(ee.default,{value:x.getFieldValue("logging_settings"),onChange:e=>x.setFieldValue("logging_settings",e),disabledCallbacks:v,onDisabledCallbacksChange:e=>{N((0,w.mapInternalToDisplayNames)(e)),x.setFieldValue("disabled_callbacks",e)}})}),(0,t.jsx)(b.Form.Item,{label:"Metadata",name:"metadata",children:(0,t.jsx)(U.Input.TextArea,{rows:10})}),(0,t.jsxs)("div",{className:"mb-4",children:[(0,t.jsx)(H.default,{form:x,autoRotationEnabled:S,onAutoRotationChange:I,rotationInterval:A,onRotationIntervalChange:M,neverExpire:R,onNeverExpireChange:D}),(0,t.jsx)(b.Form.Item,{name:"duration",hidden:!0,initialValue:"",children:(0,t.jsx)(U.Input,{})})]}),(0,t.jsx)(b.Form.Item,{name:"token",hidden:!0,children:(0,t.jsx)(U.Input,{})}),(0,t.jsx)(b.Form.Item,{name:"disabled_callbacks",hidden:!0,children:(0,t.jsx)(U.Input,{})}),(0,t.jsx)(b.Form.Item,{name:"auto_rotate",hidden:!0,children:(0,t.jsx)(U.Input,{})}),(0,t.jsx)(b.Form.Item,{name:"rotation_interval",hidden:!0,children:(0,t.jsx)(U.Input,{})}),(0,t.jsx)("div",{className:"sticky z-10 bg-white p-4 border-t border-gray-200 bottom-[-1.5rem] inset-x-[-1.5rem]",children:(0,t.jsxs)("div",{className:"flex justify-end items-center gap-2",children:[(0,t.jsx)(c.Button,{variant:"secondary",onClick:a,disabled:B,children:"Cancel"}),(0,t.jsx)(c.Button,{type:"submit",loading:B,children:"Save Changes"})]})})]})}function es({onClose:e,keyData:E,teams:P,onKeyDataUpdate:O,onDelete:K,backButtonText:U="Back to Keys"}){let V,{accessToken:$,userId:z,userRole:G,premiumUser:W}=(0,a.default)(),H=W||null!=G&&T.rolesWithWriteAccess.includes(G),{teams:q}=(0,r.default)(),{data:J}=(0,s.useProjects)(),{data:Q}=(0,l.useUISettings)(),Y=!!Q?.values?.enable_projects_ui,[X,Z]=(0,k.useState)(!1),[ee]=b.Form.useForm(),[et,es]=(0,k.useState)(!1),[el,er]=(0,k.useState)(!1),[ei,en]=(0,k.useState)(""),[eo,ed]=(0,k.useState)(!1),[ec,em]=(0,k.useState)(!1),{mutate:eu,isPending:ex}=(0,M.useResetKeySpend)(),[ep,eg]=(0,k.useState)(E),[eh,ej]=(0,k.useState)(null),[e_,ey]=(0,k.useState)(!1),[eb,ef]=(0,k.useState)({}),[ev,eN]=(0,k.useState)(!1);if((0,k.useEffect)(()=>{E&&eg(E)},[E]),(0,k.useEffect)(()=>{(async()=>{let e=ep?.metadata?.policies;if(!$||!e||!Array.isArray(e)||0===e.length)return;eN(!0);let t={};try{await Promise.all(e.map(async e=>{try{let a=await (0,L.getPolicyInfoWithGuardrails)($,e);t[e]=a.resolved_guardrails||[]}catch(a){console.error(`Failed to fetch guardrails for policy ${e}:`,a),t[e]=[]}})),ef(t)}catch(e){console.error("Failed to fetch policy guardrails:",e)}finally{eN(!1)}})()},[$,ep?.metadata?.policies]),(0,k.useEffect)(()=>{if(e_){let e=setTimeout(()=>{ey(!1)},5e3);return()=>clearTimeout(e)}},[e_]),!ep)return(0,t.jsxs)("div",{className:"p-4",children:[(0,t.jsx)(c.Button,{icon:o.ArrowLeftIcon,variant:"light",onClick:e,className:"mb-4",children:U}),(0,t.jsx)(_.Text,{children:"Key not found"})]});let ek=async e=>{try{if(!$)return;let t=e.token;if(e.key=t,H||(delete e.guardrails,delete e.prompts),e.max_budget=(0,n.mapEmptyStringToNull)(e.max_budget),void 0!==e.vector_stores&&(e.object_permission={...ep.object_permission,vector_stores:e.vector_stores||[]},delete e.vector_stores),void 0!==e.mcp_servers_and_groups){let{servers:t,accessGroups:a}=e.mcp_servers_and_groups||{servers:[],accessGroups:[]};e.object_permission={...ep.object_permission,mcp_servers:t||[],mcp_access_groups:a||[]},delete e.mcp_servers_and_groups}if(void 0!==e.mcp_tool_permissions){let t=e.mcp_tool_permissions||{};Object.keys(t).length>0&&(e.object_permission={...e.object_permission,mcp_tool_permissions:t}),delete e.mcp_tool_permissions}if(void 0!==e.agents_and_groups){let{agents:t,accessGroups:a}=e.agents_and_groups||{agents:[],accessGroups:[]};e.object_permission={...e.object_permission,agents:t||[],agent_access_groups:a||[]},delete e.agents_and_groups}if(e.max_budget=(0,n.mapEmptyStringToNull)(e.max_budget),e.tpm_limit=(0,n.mapEmptyStringToNull)(e.tpm_limit),e.rpm_limit=(0,n.mapEmptyStringToNull)(e.rpm_limit),e.max_parallel_requests=(0,n.mapEmptyStringToNull)(e.max_parallel_requests),e.metadata&&"string"==typeof e.metadata)try{let t=JSON.parse(e.metadata);"tags"in t&&delete t.tags,e.metadata={...t,...Array.isArray(e.tags)&&e.tags.length>0?{tags:e.tags}:{},...e.guardrails?.length>0?{guardrails:e.guardrails}:{},...Array.isArray(e.logging_settings)&&e.logging_settings.length>0?{logging:e.logging_settings}:{},...e.disabled_callbacks?.length>0?{litellm_disabled_callbacks:(0,w.mapDisplayToInternalNames)(e.disabled_callbacks)}:{}}}catch(e){console.error("Error parsing metadata JSON:",e),F.default.error("Invalid metadata JSON");return}else{let{tags:t,...a}=e.metadata||{};e.metadata={...a,...Array.isArray(e.tags)&&e.tags.length>0?{tags:e.tags}:{},...e.guardrails?.length>0?{guardrails:e.guardrails}:{},...Array.isArray(e.logging_settings)&&e.logging_settings.length>0?{logging:e.logging_settings}:{},...e.disabled_callbacks?.length>0?{litellm_disabled_callbacks:(0,w.mapDisplayToInternalNames)(e.disabled_callbacks)}:{}}}"tags"in e&&delete e.tags,delete e.logging_settings,e.budget_duration&&(e.budget_duration=({daily:"24h",weekly:"7d",monthly:"30d"})[e.budget_duration]);let a=await (0,L.keyUpdateCall)($,e);eg(e=>e?{...e,...a}:void 0),O&&O(a),F.default.success("Key updated successfully"),Z(!1)}catch(e){F.default.fromBackend((0,B.parseErrorMessage)(e)),console.error("Error updating key:",e)}},eT=async()=>{try{if(er(!0),!$)return;await (0,L.keyDeleteCall)($,ep.token||ep.token_id),F.default.success("Key deleted successfully"),K&&K(),e()}catch(e){console.error("Error deleting the key:",e),F.default.fromBackend(e)}finally{er(!1),es(!1),en("")}},ew=e=>{let t=new Date(e),a=t.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"}),s=t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0});return`${a} at ${s}`},eS=(0,T.isProxyAdminRole)(G||"")||q&&(0,T.isUserTeamAdminForSingleTeam)(q?.filter(e=>e.team_id===ep.team_id)[0]?.members_with_roles,z||"")||z===ep.user_id&&"Internal Viewer"!==G,eI=(0,T.isProxyAdminRole)(G||"")||q&&(0,T.isUserTeamAdminForSingleTeam)(q?.filter(e=>e.team_id===ep.team_id)[0]?.members_with_roles,z||"");return(0,t.jsxs)("div",{className:"w-full h-screen p-4",children:[(0,t.jsx)(N.KeyInfoHeader,{data:{keyName:ep.key_alias||"Virtual Key",keyId:ep.token_id||ep.token,userId:ep.user_id||"",userEmail:ep.user_email||"",createdBy:ep.user_email||ep.user_id||"",createdAt:ep.created_at?ew(ep.created_at):"",lastUpdated:ep.updated_at?ew(ep.updated_at):"",lastActive:ep.last_active?ew(ep.last_active):"Never"},onBack:e,onRegenerate:()=>ed(!0),onDelete:()=>es(!0),onResetSpend:eI?()=>em(!0):void 0,canModifyKey:eS,backButtonText:U,regenerateDisabled:!W,regenerateTooltip:W?void 0:"This is a LiteLLM Enterprise feature, and requires a valid key to use."}),(0,t.jsx)(D.RegenerateKeyModal,{selectedToken:ep,visible:eo,onClose:()=>ed(!1),onKeyUpdate:e=>{eg(t=>{if(t)return{...t,...e,created_at:new Date().toLocaleString()}}),ej(new Date),ey(!0),O&&O({...e,created_at:new Date().toLocaleString()})}}),(0,t.jsx)(I.default,{isOpen:et,title:"Delete Key",alertMessage:"This action is irreversible and will immediately revoke access for any applications using this key.",message:"Are you sure you want to delete this Virtual Key?",resourceInformationTitle:"Key Information",resourceInformation:[{label:"Key Alias",value:ep?.key_alias||"-"},{label:"Key ID",value:ep?.token_id||ep?.token||"-",code:!0},{label:"Team ID",value:ep?.team_id||"-",code:!0},{label:"Spend",value:ep?.spend?`$${(0,i.formatNumberWithCommas)(ep.spend,4)}`:"$0.0000"}],onCancel:()=>{es(!1),en("")},onOk:eT,confirmLoading:el,requiredConfirmation:ep?.key_alias}),(0,t.jsxs)(f.Modal,{title:"Reset Key Spend",open:ec,onOk:()=>{eu(ep.token||ep.token_id,{onSuccess:()=>{eg(e=>e?{...e,spend:0}:void 0),O&&O({spend:0}),F.default.success("Key spend reset to $0"),em(!1)},onError:e=>{F.default.fromBackend((0,B.parseErrorMessage)(e)),console.error("Error resetting key spend:",e)}})},onCancel:()=>em(!1),okText:"Reset",okButtonProps:{danger:!0},confirmLoading:ex,children:[(0,t.jsxs)("p",{children:["Reset spend for ",(0,t.jsx)("strong",{children:ep?.key_alias||ep?.token_id||"this key"})," to"," ",(0,t.jsx)("strong",{children:"$0"}),"?"]}),(0,t.jsxs)("p",{style:{color:"#666",fontSize:"0.875rem",marginTop:8},children:["Current spend: ",(0,t.jsxs)("strong",{children:["$",(0,i.formatNumberWithCommas)(ep.spend,4)]}),". Spend history is preserved in logs. This resets the current period spend counter, the same as an automatic budget reset."]})]}),(0,t.jsxs)(p.TabGroup,{children:[(0,t.jsxs)(g.TabList,{className:"mb-4",children:[(0,t.jsx)(x.Tab,{children:"Overview"}),(0,t.jsx)(x.Tab,{children:"Settings"})]}),(0,t.jsxs)(j.TabPanels,{children:[(0,t.jsx)(h.TabPanel,{children:(0,t.jsxs)(u.Grid,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,t.jsxs)(m.Card,{children:[(0,t.jsx)(_.Text,{children:"Spend"}),(0,t.jsxs)("div",{className:"mt-2",children:[(0,t.jsxs)(y.Title,{children:["$",(0,i.formatNumberWithCommas)(ep.spend,4)]}),(0,t.jsxs)(_.Text,{children:["of"," ",null!==ep.max_budget?`$${(0,i.formatNumberWithCommas)(ep.max_budget)}`:"Unlimited"]})]})]}),(0,t.jsxs)(m.Card,{children:[(0,t.jsx)(_.Text,{children:"Rate Limits"}),(0,t.jsxs)("div",{className:"mt-2",children:[(0,t.jsxs)(_.Text,{children:["TPM: ",null!==ep.tpm_limit?ep.tpm_limit:"Unlimited"]}),(0,t.jsxs)(_.Text,{children:["RPM: ",null!==ep.rpm_limit?ep.rpm_limit:"Unlimited"]})]})]}),(0,t.jsxs)(m.Card,{children:[(0,t.jsx)(_.Text,{children:"Models"}),(0,t.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:ep.models&&ep.models.length>0?ep.models.map((e,a)=>(0,t.jsx)(d.Badge,{color:"red",children:e},a)):(0,t.jsx)(_.Text,{children:"No models specified"})})]}),(0,t.jsx)(m.Card,{children:(0,t.jsx)(R.default,{objectPermission:ep.object_permission,variant:"inline",accessToken:$})}),(0,t.jsxs)(m.Card,{children:[(0,t.jsx)(_.Text,{className:"font-medium mb-3",children:"Guardrails"}),Array.isArray(ep.metadata?.guardrails)&&ep.metadata.guardrails.length>0?(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:ep.metadata.guardrails.map((e,a)=>(0,t.jsx)(d.Badge,{color:"blue",children:e},a))}):(0,t.jsx)(_.Text,{className:"text-gray-500",children:"No guardrails configured"}),"boolean"==typeof ep.metadata?.disable_global_guardrails&&!0===ep.metadata.disable_global_guardrails&&(0,t.jsx)("div",{className:"mt-3 pt-3 border-t border-gray-200",children:(0,t.jsx)(d.Badge,{color:"yellow",children:"Global Guardrails Disabled"})})]}),(0,t.jsxs)(m.Card,{children:[(0,t.jsx)(_.Text,{className:"font-medium mb-3",children:"Policies"}),Array.isArray(ep.metadata?.policies)&&ep.metadata.policies.length>0?(0,t.jsx)("div",{className:"space-y-4",children:ep.metadata.policies.map((e,a)=>(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(d.Badge,{color:"purple",children:e}),ev&&(0,t.jsx)(_.Text,{className:"text-xs text-gray-400",children:"Loading guardrails..."})]}),!ev&&eb[e]&&eb[e].length>0&&(0,t.jsxs)("div",{className:"ml-4 pl-3 border-l-2 border-gray-200",children:[(0,t.jsx)(_.Text,{className:"text-xs text-gray-500 mb-1",children:"Resolved Guardrails:"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:eb[e].map((e,a)=>(0,t.jsx)(d.Badge,{color:"blue",size:"xs",children:e},a))})]})]},a))}):(0,t.jsx)(_.Text,{className:"text-gray-500",children:"No policies configured"})]}),(0,t.jsx)(A.default,{loggingConfigs:(0,C.extractLoggingSettings)(ep.metadata),disabledCallbacks:Array.isArray(ep.metadata?.litellm_disabled_callbacks)?(0,w.mapInternalToDisplayNames)(ep.metadata.litellm_disabled_callbacks):[],variant:"card"}),(0,t.jsx)(S.default,{autoRotate:ep.auto_rotate,rotationInterval:ep.rotation_interval,lastRotationAt:ep.last_rotation_at,keyRotationAt:ep.key_rotation_at,nextRotationAt:ep.next_rotation_at,variant:"card"})]})}),(0,t.jsx)(h.TabPanel,{children:(0,t.jsxs)(m.Card,{className:"overflow-y-auto max-h-[65vh]",children:[(0,t.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,t.jsx)(y.Title,{children:"Key Settings"}),!X&&eS&&(0,t.jsx)(c.Button,{onClick:()=>Z(!0),children:"Edit Settings"})]}),X?(0,t.jsx)(ea,{keyData:ep,onCancel:()=>Z(!1),onSubmit:ek,teams:P,accessToken:$,userID:z,userRole:G,premiumUser:W}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Key ID"}),(0,t.jsx)(_.Text,{className:"font-mono",children:ep.token_id||ep.token})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Key Alias"}),(0,t.jsx)(_.Text,{children:ep.key_alias||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Secret Key"}),(0,t.jsx)(_.Text,{className:"font-mono",children:ep.key_name})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Team ID"}),(0,t.jsx)(_.Text,{children:ep.team_id||"Not Set"})]}),Y&&(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Project"}),(0,t.jsx)(_.Text,{children:ep.project_id?(V=J?.find(e=>e.project_id===ep.project_id),V?.project_alias?`${V.project_alias} (${ep.project_id})`:ep.project_id):"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Organization"}),(0,t.jsx)(_.Text,{children:(ep.organization_id??ep.org_id)||"Not Set"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Created"}),(0,t.jsx)(_.Text,{children:ew(ep.created_at)})]}),eh&&(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Last Regenerated"}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(_.Text,{children:ew(eh)}),(0,t.jsx)(d.Badge,{color:"green",size:"xs",children:"Recent"})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Expires"}),(0,t.jsx)(_.Text,{children:ep.expires?ew(ep.expires):"Never"})]}),(0,t.jsx)(S.default,{autoRotate:ep.auto_rotate,rotationInterval:ep.rotation_interval,lastRotationAt:ep.last_rotation_at,keyRotationAt:ep.key_rotation_at,nextRotationAt:ep.next_rotation_at,variant:"inline",className:"pt-4 border-t border-gray-200"}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Spend"}),(0,t.jsxs)(_.Text,{children:["$",(0,i.formatNumberWithCommas)(ep.spend,4)," USD"]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Budget"}),(0,t.jsx)(_.Text,{children:null!==ep.max_budget?`$${(0,i.formatNumberWithCommas)(ep.max_budget,2)}`:"Unlimited"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Tags"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:Array.isArray(ep.metadata?.tags)&&ep.metadata.tags.length>0?ep.metadata.tags.map((e,a)=>(0,t.jsx)("span",{className:"px-2 mr-2 py-1 bg-blue-100 rounded text-xs",children:e},a)):"No tags specified"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Prompts"}),(0,t.jsx)(_.Text,{children:Array.isArray(ep.metadata?.prompts)&&ep.metadata.prompts.length>0?ep.metadata.prompts.map((e,a)=>(0,t.jsx)("span",{className:"px-2 mr-2 py-1 bg-blue-100 rounded text-xs",children:e},a)):"No prompts specified"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Allowed Routes"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:Array.isArray(ep.allowed_routes)&&ep.allowed_routes.length>0?ep.allowed_routes.map((e,a)=>(0,t.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:e},a)):(0,t.jsx)(v.Tag,{color:"green",children:"All routes allowed"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Allowed Pass Through Routes"}),(0,t.jsx)(_.Text,{children:Array.isArray(ep.metadata?.allowed_passthrough_routes)&&ep.metadata.allowed_passthrough_routes.length>0?ep.metadata.allowed_passthrough_routes.map((e,a)=>(0,t.jsx)("span",{className:"px-2 mr-2 py-1 bg-blue-100 rounded text-xs",children:e},a)):"No pass through routes specified"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Disable Global Guardrails"}),(0,t.jsx)(_.Text,{children:ep.metadata?.disable_global_guardrails===!0?(0,t.jsx)(d.Badge,{color:"yellow",children:"Enabled - Global guardrails bypassed"}):(0,t.jsx)(d.Badge,{color:"green",children:"Disabled - Global guardrails active"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Models"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:ep.models&&ep.models.length>0?ep.models.map((e,a)=>(0,t.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:e},a)):(0,t.jsx)(_.Text,{children:"No models specified"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Rate Limits"}),(0,t.jsxs)(_.Text,{children:["TPM: ",null!==ep.tpm_limit?ep.tpm_limit:"Unlimited"]}),(0,t.jsxs)(_.Text,{children:["RPM: ",null!==ep.rpm_limit?ep.rpm_limit:"Unlimited"]}),(0,t.jsxs)(_.Text,{children:["Max Parallel Requests:"," ",null!==ep.max_parallel_requests?ep.max_parallel_requests:"Unlimited"]}),(0,t.jsxs)(_.Text,{children:["Model TPM Limits:"," ",ep.metadata?.model_tpm_limit?JSON.stringify(ep.metadata.model_tpm_limit):"Unlimited"]}),(0,t.jsxs)(_.Text,{children:["Model RPM Limits:"," ",ep.metadata?.model_rpm_limit?JSON.stringify(ep.metadata.model_rpm_limit):"Unlimited"]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Text,{className:"font-medium",children:"Metadata"}),(0,t.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:(0,C.formatMetadataForDisplay)((0,C.stripTagsFromMetadata)(ep.metadata))})]}),(0,t.jsx)(R.default,{objectPermission:ep.object_permission,variant:"inline",className:"pt-4 border-t border-gray-200",accessToken:$}),(0,t.jsx)(A.default,{loggingConfigs:(0,C.extractLoggingSettings)(ep.metadata),disabledCallbacks:Array.isArray(ep.metadata?.litellm_disabled_callbacks)?(0,w.mapInternalToDisplayNames)(ep.metadata.litellm_disabled_callbacks):[],variant:"inline",className:"pt-4 border-t border-gray-200"})]})]})})]})]})]})}e.s(["default",()=>es],20147)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/442ccb8d620e1fa6.js b/litellm/proxy/_experimental/out/_next/static/chunks/442ccb8d620e1fa6.js new file mode 100644 index 00000000000..0d099944026 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/442ccb8d620e1fa6.js @@ -0,0 +1 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,928685,e=>{"use strict";var t=e.i(38953);e.s(["SearchOutlined",()=>t.default])},848725,e=>{"use strict";var t=e.i(271645);let s=t.forwardRef(function(e,s){return t.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:s},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}),t.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.s(["EyeIcon",0,s],848725)},440987,e=>{"use strict";var t=e.i(903446);e.s(["SettingsIcon",()=>t.default])},751904,e=>{"use strict";var t=e.i(401361);e.s(["EditOutlined",()=>t.default])},211576,e=>{"use strict";var t=e.i(131757);e.s(["Col",()=>t.default])},903446,e=>{"use strict";let t=(0,e.i(475254).default)("settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);e.s(["default",()=>t])},844444,e=>{"use strict";var t=e.i(843476),s=e.i(906579),i=e.i(271645),r=e.i(115571);function a(e){let t=t=>{"disableShowNewBadge"===t.key&&e()},s=t=>{let{key:s}=t.detail;"disableShowNewBadge"===s&&e()};return window.addEventListener("storage",t),window.addEventListener(r.LOCAL_STORAGE_EVENT,s),()=>{window.removeEventListener("storage",t),window.removeEventListener(r.LOCAL_STORAGE_EVENT,s)}}function l(){return"true"===(0,r.getLocalStorageItem)("disableShowNewBadge")}function n({children:e,dot:r=!1}){return(0,i.useSyncExternalStore)(a,l)?e?(0,t.jsx)(t.Fragment,{children:e}):null:e?(0,t.jsx)(s.Badge,{color:"blue",count:r?void 0:"New",dot:r,children:e}):(0,t.jsx)(s.Badge,{color:"blue",count:r?void 0:"New",dot:r})}e.s(["default",()=>n],844444)},292335,122520,e=>{"use strict";let t={NONE:"none",API_KEY:"api_key",BEARER_TOKEN:"bearer_token",TOKEN:"token",BASIC:"basic",OAUTH2:"oauth2",AWS_SIGV4:"aws_sigv4"},s={SSE:"sse",HTTP:"http",STDIO:"stdio",OPENAPI:"openapi"};function i(e){if(e instanceof Error)return e.message;if(e&&"object"==typeof e){let t=e.detail;return"string"==typeof t?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e?"string"==typeof e.msg?e.msg:JSON.stringify(e):String(e)).join("; "):t&&"object"==typeof t&&"string"==typeof t.error?t.error:"string"==typeof e.message?e.message:JSON.stringify(e)}return String(e)}e.s(["AUTH_TYPE",0,t,"OAUTH_FLOW",0,{INTERACTIVE:"interactive",M2M:"m2m"},"TRANSPORT",0,s,"handleAuth",0,e=>null==e?t.NONE:e,"handleTransport",0,(e,t)=>null==e?s.SSE:t&&e!==s.STDIO?s.OPENAPI:e],292335),e.s(["extractErrorMessage",()=>i],122520)},995926,e=>{"use strict";var t=e.i(841947);e.s(["XIcon",()=>t.default])},546467,e=>{"use strict";let t=(0,e.i(475254).default)("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"}]]);e.s(["default",()=>t])},988846,e=>{"use strict";var t=e.i(54943);e.s(["SearchIcon",()=>t.default])},328196,e=>{"use strict";var t=e.i(361653);e.s(["AlertCircleIcon",()=>t.default])},302202,e=>{"use strict";let t=(0,e.i(475254).default)("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"}]]);e.s(["ServerIcon",()=>t],302202)},54131,634831,438100,e=>{"use strict";var t=e.i(399219);e.s(["ChevronUpIcon",()=>t.default],54131);var s=e.i(546467);e.s(["ExternalLinkIcon",()=>s.default],634831);let i=(0,e.i(475254).default)("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"}]]);e.s(["KeyIcon",()=>i],438100)},54943,e=>{"use strict";let t=(0,e.i(475254).default)("search",[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]);e.s(["default",()=>t])},987432,e=>{"use strict";e.i(247167);var t=e.i(931067),s=e.i(271645);let i={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M893.3 293.3L730.7 130.7c-7.5-7.5-16.7-13-26.7-16V112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V338.5c0-17-6.7-33.2-18.7-45.2zM384 184h256v104H384V184zm456 656H184V184h136v136c0 17.7 14.3 32 32 32h320c17.7 0 32-14.3 32-32V205.8l136 136V840zM512 442c-79.5 0-144 64.5-144 144s64.5 144 144 144 144-64.5 144-144-64.5-144-144-144zm0 224c-44.2 0-80-35.8-80-80s35.8-80 80-80 80 35.8 80 80-35.8 80-80 80z"}}]},name:"save",theme:"outlined"};var r=e.i(9583),a=s.forwardRef(function(e,a){return s.createElement(r.default,(0,t.default)({},e,{ref:a,icon:i}))});e.s(["SaveOutlined",0,a],987432)},245094,e=>{"use strict";e.i(247167);var t=e.i(931067),s=e.i(271645);let i={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M516 673c0 4.4 3.4 8 7.5 8h185c4.1 0 7.5-3.6 7.5-8v-48c0-4.4-3.4-8-7.5-8h-185c-4.1 0-7.5 3.6-7.5 8v48zm-194.9 6.1l192-161c3.8-3.2 3.8-9.1 0-12.3l-192-160.9A7.95 7.95 0 00308 351v62.7c0 2.4 1 4.6 2.9 6.1L420.7 512l-109.8 92.2a8.1 8.1 0 00-2.9 6.1V673c0 6.8 7.9 10.5 13.1 6.1zM880 112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32zm-40 728H184V184h656v656z"}}]},name:"code",theme:"outlined"};var r=e.i(9583),a=s.forwardRef(function(e,a){return s.createElement(r.default,(0,t.default)({},e,{ref:a,icon:i}))});e.s(["CodeOutlined",0,a],245094)},362024,e=>{"use strict";var t=e.i(988122);e.s(["Collapse",()=>t.default])},245704,e=>{"use strict";e.i(247167);var t=e.i(931067),s=e.i(271645);let i={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"};var r=e.i(9583),a=s.forwardRef(function(e,a){return s.createElement(r.default,(0,t.default)({},e,{ref:a,icon:i}))});e.s(["CheckCircleOutlined",0,a],245704)},596239,e=>{"use strict";e.i(247167);var t=e.i(931067),s=e.i(271645);let i={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M574 665.4a8.03 8.03 0 00-11.3 0L446.5 781.6c-53.8 53.8-144.6 59.5-204 0-59.5-59.5-53.8-150.2 0-204l116.2-116.2c3.1-3.1 3.1-8.2 0-11.3l-39.8-39.8a8.03 8.03 0 00-11.3 0L191.4 526.5c-84.6 84.6-84.6 221.5 0 306s221.5 84.6 306 0l116.2-116.2c3.1-3.1 3.1-8.2 0-11.3L574 665.4zm258.6-474c-84.6-84.6-221.5-84.6-306 0L410.3 307.6a8.03 8.03 0 000 11.3l39.7 39.7c3.1 3.1 8.2 3.1 11.3 0l116.2-116.2c53.8-53.8 144.6-59.5 204 0 59.5 59.5 53.8 150.2 0 204L665.3 562.6a8.03 8.03 0 000 11.3l39.8 39.8c3.1 3.1 8.2 3.1 11.3 0l116.2-116.2c84.5-84.6 84.5-221.5 0-306.1zM610.1 372.3a8.03 8.03 0 00-11.3 0L372.3 598.7a8.03 8.03 0 000 11.3l39.6 39.6c3.1 3.1 8.2 3.1 11.3 0l226.4-226.4c3.1-3.1 3.1-8.2 0-11.3l-39.5-39.6z"}}]},name:"link",theme:"outlined"};var r=e.i(9583),a=s.forwardRef(function(e,a){return s.createElement(r.default,(0,t.default)({},e,{ref:a,icon:i}))});e.s(["LinkOutlined",0,a],596239)},149192,e=>{"use strict";var t=e.i(864517);e.s(["CloseOutlined",()=>t.default])},492030,e=>{"use strict";var t=e.i(121229);e.s(["CheckOutlined",()=>t.default])},458505,e=>{"use strict";e.i(247167);var t=e.i(931067),s=e.i(271645);let i={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"};var r=e.i(9583),a=s.forwardRef(function(e,a){return s.createElement(r.default,(0,t.default)({},e,{ref:a,icon:i}))});e.s(["DollarOutlined",0,a],458505)},611052,e=>{"use strict";var t=e.i(843476),s=e.i(271645),i=e.i(212931),r=e.i(311451),a=e.i(790848),l=e.i(998573),n=e.i(438957);e.i(247167);var o=e.i(931067);let c={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M832 464h-68V240c0-70.7-57.3-128-128-128H388c-70.7 0-128 57.3-128 128v224h-68c-17.7 0-32 14.3-32 32v384c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V496c0-17.7-14.3-32-32-32zM332 240c0-30.9 25.1-56 56-56h248c30.9 0 56 25.1 56 56v224H332V240zm460 600H232V536h560v304zM484 701v53c0 4.4 3.6 8 8 8h40c4.4 0 8-3.6 8-8v-53a48.01 48.01 0 10-56 0z"}}]},name:"lock",theme:"outlined"};var d=e.i(9583),u=s.forwardRef(function(e,t){return s.createElement(d.default,(0,o.default)({},e,{ref:t,icon:c}))}),m=e.i(492030),h=e.i(266537),g=e.i(447566),p=e.i(149192),f=e.i(596239);e.s(["ByokCredentialModal",0,({server:e,open:o,onClose:c,onSuccess:d,accessToken:x})=>{let[v,y]=(0,s.useState)(1),[b,w]=(0,s.useState)(""),[S,j]=(0,s.useState)(!0),[k,N]=(0,s.useState)(!1),C=e.alias||e.server_name||"Service",M=C.charAt(0).toUpperCase(),E=()=>{y(1),w(""),j(!0),N(!1),c()},O=async()=>{if(!b.trim())return void l.message.error("Please enter your API key");N(!0);try{let t=await fetch(`/v1/mcp/server/${e.server_id}/user-credential`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${x}`},body:JSON.stringify({credential:b.trim(),save:S})});if(!t.ok){let e=await t.json();throw Error(e?.detail?.error||"Failed to save credential")}l.message.success(`Connected to ${C}`),d(e.server_id),E()}catch(e){l.message.error(e.message||"Failed to connect")}finally{N(!1)}};return(0,t.jsx)(i.Modal,{open:o,onCancel:E,footer:null,width:480,closeIcon:null,className:"byok-modal",children:(0,t.jsxs)("div",{className:"relative p-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-6",children:[2===v?(0,t.jsxs)("button",{onClick:()=>y(1),className:"flex items-center gap-1 text-gray-500 hover:text-gray-800 text-sm",children:[(0,t.jsx)(g.ArrowLeftOutlined,{})," Back"]}):(0,t.jsx)("div",{}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,t.jsx)("div",{className:`w-2 h-2 rounded-full ${1===v?"bg-blue-500":"bg-gray-300"}`}),(0,t.jsx)("div",{className:`w-2 h-2 rounded-full ${2===v?"bg-blue-500":"bg-gray-300"}`})]}),(0,t.jsx)("button",{onClick:E,className:"text-gray-400 hover:text-gray-600",children:(0,t.jsx)(p.CloseOutlined,{})})]}),1===v?(0,t.jsxs)("div",{className:"text-center",children:[(0,t.jsxs)("div",{className:"flex items-center justify-center gap-3 mb-6",children:[(0,t.jsx)("div",{className:"w-14 h-14 rounded-xl bg-gradient-to-br from-teal-400 to-cyan-600 flex items-center justify-center text-white font-bold text-xl shadow",children:"L"}),(0,t.jsx)(h.ArrowRightOutlined,{className:"text-gray-400 text-lg"}),(0,t.jsx)("div",{className:"w-14 h-14 rounded-xl bg-gradient-to-br from-blue-600 to-indigo-800 flex items-center justify-center text-white font-bold text-xl shadow",children:M})]}),(0,t.jsxs)("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:["Connect ",C]}),(0,t.jsxs)("p",{className:"text-gray-500 mb-6",children:["LiteLLM needs access to ",C," to complete your request."]}),(0,t.jsx)("div",{className:"bg-gray-50 rounded-xl p-4 text-left mb-4",children:(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)("div",{className:"mt-0.5",children:(0,t.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",className:"text-gray-500",children:[(0,t.jsx)("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",stroke:"currentColor",strokeWidth:"2"}),(0,t.jsx)("path",{d:"M8 4v16M16 4v16",stroke:"currentColor",strokeWidth:"2"})]})}),(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{className:"font-semibold text-gray-800 mb-1",children:"How it works"}),(0,t.jsxs)("p",{className:"text-gray-500 text-sm",children:["LiteLLM acts as a secure bridge. Your requests are routed through our MCP client directly to"," ",C,"'s API."]})]})]})}),e.byok_description&&e.byok_description.length>0&&(0,t.jsxs)("div",{className:"bg-gray-50 rounded-xl p-4 text-left mb-6",children:[(0,t.jsxs)("p",{className:"text-xs font-semibold text-gray-500 uppercase tracking-widest mb-3 flex items-center gap-2",children:[(0,t.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",className:"text-green-500",children:[(0,t.jsx)("path",{d:"M12 2L12 22M2 12L22 12",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"}),(0,t.jsx)("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2"})]}),"Requested Access"]}),(0,t.jsx)("ul",{className:"space-y-2",children:e.byok_description.map((e,s)=>(0,t.jsxs)("li",{className:"flex items-center gap-2 text-sm text-gray-700",children:[(0,t.jsx)(m.CheckOutlined,{className:"text-green-500 flex-shrink-0"}),e]},s))})]}),(0,t.jsxs)("button",{onClick:()=>y(2),className:"w-full bg-gray-900 hover:bg-gray-700 text-white font-medium py-3 px-6 rounded-xl flex items-center justify-center gap-2 transition-colors",children:["Continue to Authentication ",(0,t.jsx)(h.ArrowRightOutlined,{})]}),(0,t.jsx)("button",{onClick:E,className:"mt-3 w-full text-gray-400 hover:text-gray-600 text-sm py-2",children:"Cancel"})]}):(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"w-12 h-12 rounded-full bg-blue-50 flex items-center justify-center mb-4",children:(0,t.jsx)(n.KeyOutlined,{className:"text-blue-400 text-xl"})}),(0,t.jsx)("h2",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Provide API Key"}),(0,t.jsxs)("p",{className:"text-gray-500 mb-6",children:["Enter your ",C," API key to authorize this connection."]}),(0,t.jsxs)("div",{className:"mb-4",children:[(0,t.jsxs)("label",{className:"block text-sm font-semibold text-gray-800 mb-2",children:[C," API Key"]}),(0,t.jsx)(r.Input.Password,{placeholder:"Enter your API key",value:b,onChange:e=>w(e.target.value),size:"large",className:"rounded-lg"}),e.byok_api_key_help_url&&(0,t.jsxs)("a",{href:e.byok_api_key_help_url,target:"_blank",rel:"noopener noreferrer",className:"text-blue-500 hover:text-blue-700 text-sm mt-2 flex items-center gap-1",children:["Where do I find my API key? ",(0,t.jsx)(f.LinkOutlined,{})]})]}),(0,t.jsxs)("div",{className:"bg-gray-50 rounded-xl p-4 flex items-center justify-between mb-4",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",className:"text-gray-500",children:(0,t.jsx)("path",{d:"M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z",fill:"currentColor"})}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-800",children:"Save key for future use"})]}),(0,t.jsx)(a.Switch,{checked:S,onChange:j})]}),(0,t.jsxs)("div",{className:"bg-blue-50 rounded-xl p-4 flex items-start gap-3 mb-6",children:[(0,t.jsx)(u,{className:"text-blue-400 mt-0.5 flex-shrink-0"}),(0,t.jsx)("p",{className:"text-sm text-blue-700",children:"Your key is stored securely and transmitted over HTTPS. It is never shared with third parties."})]}),(0,t.jsxs)("button",{onClick:O,disabled:k,className:"w-full bg-blue-500 hover:bg-blue-600 disabled:opacity-60 text-white font-medium py-3 px-6 rounded-xl flex items-center justify-center gap-2 transition-colors",children:[(0,t.jsx)(u,{})," Connect & Authorize"]})]})]})})}],611052)},954616,e=>{"use strict";var t=e.i(271645),s=e.i(114272),i=e.i(540143),r=e.i(915823),a=e.i(619273),l=class extends r.Subscribable{#e;#t=void 0;#s;#i;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#r()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),(0,a.shallowEqualObjects)(this.options,t)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#s,observer:this}),t?.mutationKey&&this.options.mutationKey&&(0,a.hashKey)(t.mutationKey)!==(0,a.hashKey)(this.options.mutationKey)?this.reset():this.#s?.state.status==="pending"&&this.#s.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#s?.removeObserver(this)}onMutationUpdate(e){this.#r(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#s?.removeObserver(this),this.#s=void 0,this.#r(),this.#a()}mutate(e,t){return this.#i=t,this.#s?.removeObserver(this),this.#s=this.#e.getMutationCache().build(this.#e,this.options),this.#s.addObserver(this),this.#s.execute(e)}#r(){let e=this.#s?.state??(0,s.getDefaultState)();this.#t={...e,isPending:"pending"===e.status,isSuccess:"success"===e.status,isError:"error"===e.status,isIdle:"idle"===e.status,mutate:this.mutate,reset:this.reset}}#a(e){i.notifyManager.batch(()=>{if(this.#i&&this.hasListeners()){let t=this.#t.variables,s=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#i.onSuccess?.(e.data,t,s,i)}catch(e){Promise.reject(e)}try{this.#i.onSettled?.(e.data,null,t,s,i)}catch(e){Promise.reject(e)}}else if(e?.type==="error"){try{this.#i.onError?.(e.error,t,s,i)}catch(e){Promise.reject(e)}try{this.#i.onSettled?.(void 0,e.error,t,s,i)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},n=e.i(912598);function o(e,s){let r=(0,n.useQueryClient)(s),[o]=t.useState(()=>new l(r,e));t.useEffect(()=>{o.setOptions(e)},[o,e]);let c=t.useSyncExternalStore(t.useCallback(e=>o.subscribe(i.notifyManager.batchCalls(e)),[o]),()=>o.getCurrentResult(),()=>o.getCurrentResult()),d=t.useCallback((e,t)=>{o.mutate(e,t).catch(a.noop)},[o]);if(c.error&&(0,a.shouldThrowError)(o.options.throwOnError,[c.error]))throw c.error;return{...c,mutate:d,mutateAsync:c.mutate}}e.s(["useMutation",()=>o],954616)},244451,e=>{"use strict";let t;e.i(247167);var s=e.i(271645),i=e.i(343794),r=e.i(242064),a=e.i(763731),l=e.i(174428);let n=80*Math.PI,o=e=>{let{dotClassName:t,style:r,hasCircleCls:a}=e;return s.createElement("circle",{className:(0,i.default)(`${t}-circle`,{[`${t}-circle-bg`]:a}),r:40,cx:50,cy:50,strokeWidth:20,style:r})},c=({percent:e,prefixCls:t})=>{let r=`${t}-dot`,a=`${r}-holder`,c=`${a}-hidden`,[d,u]=s.useState(!1);(0,l.default)(()=>{0!==e&&u(!0)},[0!==e]);let m=Math.max(Math.min(e,100),0);if(!d)return null;let h={strokeDashoffset:`${n/4}`,strokeDasharray:`${n*m/100} ${n*(100-m)/100}`};return s.createElement("span",{className:(0,i.default)(a,`${r}-progress`,m<=0&&c)},s.createElement("svg",{viewBox:"0 0 100 100",role:"progressbar","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":m},s.createElement(o,{dotClassName:r,hasCircleCls:!0}),s.createElement(o,{dotClassName:r,style:h})))};function d(e){let{prefixCls:t,percent:r=0}=e,a=`${t}-dot`,l=`${a}-holder`,n=`${l}-hidden`;return s.createElement(s.Fragment,null,s.createElement("span",{className:(0,i.default)(l,r>0&&n)},s.createElement("span",{className:(0,i.default)(a,`${t}-dot-spin`)},[1,2,3,4].map(e=>s.createElement("i",{className:`${t}-dot-item`,key:e})))),s.createElement(c,{prefixCls:t,percent:r}))}function u(e){var t;let{prefixCls:r,indicator:l,percent:n}=e,o=`${r}-dot`;return l&&s.isValidElement(l)?(0,a.cloneElement)(l,{className:(0,i.default)(null==(t=l.props)?void 0:t.className,o),percent:n}):s.createElement(d,{prefixCls:r,percent:n})}e.i(296059);var m=e.i(694758),h=e.i(183293),g=e.i(246422),p=e.i(838378);let f=new m.Keyframes("antSpinMove",{to:{opacity:1}}),x=new m.Keyframes("antRotate",{to:{transform:"rotate(405deg)"}}),v=(0,g.genStyleHooks)("Spin",e=>(e=>{let{componentCls:t,calc:s}=e;return{[t]:Object.assign(Object.assign({},(0,h.resetComponent)(e)),{position:"absolute",display:"none",color:e.colorPrimary,fontSize:0,textAlign:"center",verticalAlign:"middle",opacity:0,transition:`transform ${e.motionDurationSlow} ${e.motionEaseInOutCirc}`,"&-spinning":{position:"relative",display:"inline-block",opacity:1},[`${t}-text`]:{fontSize:e.fontSize,paddingTop:s(s(e.dotSize).sub(e.fontSize)).div(2).add(2).equal()},"&-fullscreen":{position:"fixed",width:"100vw",height:"100vh",backgroundColor:e.colorBgMask,zIndex:e.zIndexPopupBase,inset:0,display:"flex",alignItems:"center",flexDirection:"column",justifyContent:"center",opacity:0,visibility:"hidden",transition:`all ${e.motionDurationMid}`,"&-show":{opacity:1,visibility:"visible"},[t]:{[`${t}-dot-holder`]:{color:e.colorWhite},[`${t}-text`]:{color:e.colorTextLightSolid}}},"&-nested-loading":{position:"relative",[`> div > ${t}`]:{position:"absolute",top:0,insetInlineStart:0,zIndex:4,display:"block",width:"100%",height:"100%",maxHeight:e.contentHeight,[`${t}-dot`]:{position:"absolute",top:"50%",insetInlineStart:"50%",margin:s(e.dotSize).mul(-1).div(2).equal()},[`${t}-text`]:{position:"absolute",top:"50%",width:"100%",textShadow:`0 1px 2px ${e.colorBgContainer}`},[`&${t}-show-text ${t}-dot`]:{marginTop:s(e.dotSize).div(2).mul(-1).sub(10).equal()},"&-sm":{[`${t}-dot`]:{margin:s(e.dotSizeSM).mul(-1).div(2).equal()},[`${t}-text`]:{paddingTop:s(s(e.dotSizeSM).sub(e.fontSize)).div(2).add(2).equal()},[`&${t}-show-text ${t}-dot`]:{marginTop:s(e.dotSizeSM).div(2).mul(-1).sub(10).equal()}},"&-lg":{[`${t}-dot`]:{margin:s(e.dotSizeLG).mul(-1).div(2).equal()},[`${t}-text`]:{paddingTop:s(s(e.dotSizeLG).sub(e.fontSize)).div(2).add(2).equal()},[`&${t}-show-text ${t}-dot`]:{marginTop:s(e.dotSizeLG).div(2).mul(-1).sub(10).equal()}}},[`${t}-container`]:{position:"relative",transition:`opacity ${e.motionDurationSlow}`,"&::after":{position:"absolute",top:0,insetInlineEnd:0,bottom:0,insetInlineStart:0,zIndex:10,width:"100%",height:"100%",background:e.colorBgContainer,opacity:0,transition:`all ${e.motionDurationSlow}`,content:'""',pointerEvents:"none"}},[`${t}-blur`]:{clear:"both",opacity:.5,userSelect:"none",pointerEvents:"none","&::after":{opacity:.4,pointerEvents:"auto"}}},"&-tip":{color:e.spinDotDefault},[`${t}-dot-holder`]:{width:"1em",height:"1em",fontSize:e.dotSize,display:"inline-block",transition:`transform ${e.motionDurationSlow} ease, opacity ${e.motionDurationSlow} ease`,transformOrigin:"50% 50%",lineHeight:1,color:e.colorPrimary,"&-hidden":{transform:"scale(0.3)",opacity:0}},[`${t}-dot-progress`]:{position:"absolute",inset:0},[`${t}-dot`]:{position:"relative",display:"inline-block",fontSize:e.dotSize,width:"1em",height:"1em","&-item":{position:"absolute",display:"block",width:s(e.dotSize).sub(s(e.marginXXS).div(2)).div(2).equal(),height:s(e.dotSize).sub(s(e.marginXXS).div(2)).div(2).equal(),background:"currentColor",borderRadius:"100%",transform:"scale(0.75)",transformOrigin:"50% 50%",opacity:.3,animationName:f,animationDuration:"1s",animationIterationCount:"infinite",animationTimingFunction:"linear",animationDirection:"alternate","&:nth-child(1)":{top:0,insetInlineStart:0,animationDelay:"0s"},"&:nth-child(2)":{top:0,insetInlineEnd:0,animationDelay:"0.4s"},"&:nth-child(3)":{insetInlineEnd:0,bottom:0,animationDelay:"0.8s"},"&:nth-child(4)":{bottom:0,insetInlineStart:0,animationDelay:"1.2s"}},"&-spin":{transform:"rotate(45deg)",animationName:x,animationDuration:"1.2s",animationIterationCount:"infinite",animationTimingFunction:"linear"},"&-circle":{strokeLinecap:"round",transition:["stroke-dashoffset","stroke-dasharray","stroke","stroke-width","opacity"].map(t=>`${t} ${e.motionDurationSlow} ease`).join(","),fillOpacity:0,stroke:"currentcolor"},"&-circle-bg":{stroke:e.colorFillSecondary}},[`&-sm ${t}-dot`]:{"&, &-holder":{fontSize:e.dotSizeSM}},[`&-sm ${t}-dot-holder`]:{i:{width:s(s(e.dotSizeSM).sub(s(e.marginXXS).div(2))).div(2).equal(),height:s(s(e.dotSizeSM).sub(s(e.marginXXS).div(2))).div(2).equal()}},[`&-lg ${t}-dot`]:{"&, &-holder":{fontSize:e.dotSizeLG}},[`&-lg ${t}-dot-holder`]:{i:{width:s(s(e.dotSizeLG).sub(e.marginXXS)).div(2).equal(),height:s(s(e.dotSizeLG).sub(e.marginXXS)).div(2).equal()}},[`&${t}-show-text ${t}-text`]:{display:"block"}})}})((0,p.mergeToken)(e,{spinDotDefault:e.colorTextDescription})),e=>{let{controlHeightLG:t,controlHeight:s}=e;return{contentHeight:400,dotSize:t/2,dotSizeSM:.35*t,dotSizeLG:s}}),y=[[30,.05],[70,.03],[96,.01]];var b=function(e,t){var s={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&0>t.indexOf(i)&&(s[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,i=Object.getOwnPropertySymbols(e);rt.indexOf(i[r])&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(s[i[r]]=e[i[r]]);return s};let w=e=>{var a;let{prefixCls:l,spinning:n=!0,delay:o=0,className:c,rootClassName:d,size:m="default",tip:h,wrapperClassName:g,style:p,children:f,fullscreen:x=!1,indicator:w,percent:S}=e,j=b(e,["prefixCls","spinning","delay","className","rootClassName","size","tip","wrapperClassName","style","children","fullscreen","indicator","percent"]),{getPrefixCls:k,direction:N,className:C,style:M,indicator:E}=(0,r.useComponentConfig)("spin"),O=k("spin",l),[z,$,I]=v(O),[L,R]=s.useState(()=>n&&(!n||!o||!!Number.isNaN(Number(o)))),T=function(e,t){let[i,r]=s.useState(0),a=s.useRef(null),l="auto"===t;return s.useEffect(()=>(l&&e&&(r(0),a.current=setInterval(()=>{r(e=>{let t=100-e;for(let s=0;s{a.current&&(clearInterval(a.current),a.current=null)}),[l,e]),l?i:t}(L,S);s.useEffect(()=>{if(n){let e=function(e,t,s){var i,r=s||{},a=r.noTrailing,l=void 0!==a&&a,n=r.noLeading,o=void 0!==n&&n,c=r.debounceMode,d=void 0===c?void 0:c,u=!1,m=0;function h(){i&&clearTimeout(i)}function g(){for(var s=arguments.length,r=Array(s),a=0;ae?o?(m=Date.now(),l||(i=setTimeout(d?p:g,e))):g():!0!==l&&(i=setTimeout(d?p:g,void 0===d?e-c:e)))}return g.cancel=function(e){var t=(e||{}).upcomingOnly;h(),u=!(void 0!==t&&t)},g}(o,()=>{R(!0)},{debounceMode:false});return e(),()=>{var t;null==(t=null==e?void 0:e.cancel)||t.call(e)}}R(!1)},[o,n]);let A=s.useMemo(()=>void 0!==f&&!x,[f,x]),P=(0,i.default)(O,C,{[`${O}-sm`]:"small"===m,[`${O}-lg`]:"large"===m,[`${O}-spinning`]:L,[`${O}-show-text`]:!!h,[`${O}-rtl`]:"rtl"===N},c,!x&&d,$,I),D=(0,i.default)(`${O}-container`,{[`${O}-blur`]:L}),B=null!=(a=null!=w?w:E)?a:t,_=Object.assign(Object.assign({},M),p),H=s.createElement("div",Object.assign({},j,{style:_,className:P,"aria-live":"polite","aria-busy":L}),s.createElement(u,{prefixCls:O,indicator:B,percent:T}),h&&(A||x)?s.createElement("div",{className:`${O}-text`},h):null);return z(A?s.createElement("div",Object.assign({},j,{className:(0,i.default)(`${O}-nested-loading`,g,$,I)}),L&&s.createElement("div",{key:"loading"},H),s.createElement("div",{className:D,key:"container"},f)):x?s.createElement("div",{className:(0,i.default)(`${O}-fullscreen`,{[`${O}-fullscreen-show`]:L},d,$,I)},H):H)};w.setDefaultIndicator=e=>{t=e},e.s(["default",0,w],244451)},482725,e=>{"use strict";var t=e.i(244451);e.s(["Spin",()=>t.default])},350967,46757,e=>{"use strict";var t=e.i(290571),s=e.i(444755),i=e.i(673706),r=e.i(271645);let a={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"},l={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"},n={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"},o={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"},d={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"},u={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"},m={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"};e.s(["colSpan",()=>c,"colSpanLg",()=>m,"colSpanMd",()=>u,"colSpanSm",()=>d,"gridCols",()=>a,"gridColsLg",()=>o,"gridColsMd",()=>n,"gridColsSm",()=>l],46757);let h=(0,i.makeClassName)("Grid"),g=(e,t)=>e&&Object.keys(t).includes(String(e))?t[e]:"",p=r.default.forwardRef((e,i)=>{let{numItems:c=1,numItemsSm:d,numItemsMd:u,numItemsLg:m,children:p,className:f}=e,x=(0,t.__rest)(e,["numItems","numItemsSm","numItemsMd","numItemsLg","children","className"]),v=g(c,a),y=g(d,l),b=g(u,n),w=g(m,o),S=(0,s.tremorTwMerge)(v,y,b,w);return r.default.createElement("div",Object.assign({ref:i,className:(0,s.tremorTwMerge)(h("root"),"grid",S,f)},x),p)});p.displayName="Grid",e.s(["Grid",()=>p],350967)},530212,e=>{"use strict";var t=e.i(271645);let s=t.forwardRef(function(e,s){return t.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:s},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10 19l-7-7m0 0l7-7m-7 7h18"}))});e.s(["ArrowLeftIcon",0,s],530212)},646563,e=>{"use strict";var t=e.i(959013);e.s(["PlusOutlined",()=>t.default])},447566,e=>{"use strict";e.i(247167);var t=e.i(931067),s=e.i(271645);let i={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M872 474H286.9l350.2-304c5.6-4.9 2.2-14-5.2-14h-88.5c-3.9 0-7.6 1.4-10.5 3.9L155 487.8a31.96 31.96 0 000 48.3L535.1 866c1.5 1.3 3.3 2 5.2 2h91.5c7.4 0 10.8-9.2 5.2-14L286.9 550H872c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8z"}}]},name:"arrow-left",theme:"outlined"};var r=e.i(9583),a=s.forwardRef(function(e,a){return s.createElement(r.default,(0,t.default)({},e,{ref:a,icon:i}))});e.s(["ArrowLeftOutlined",0,a],447566)},149121,e=>{"use strict";var t=e.i(843476),s=e.i(271645),i=e.i(152990),r=e.i(682830),a=e.i(269200),l=e.i(427612),n=e.i(64848),o=e.i(942232),c=e.i(496020),d=e.i(977572);function u({data:e=[],columns:u,onRowClick:m,renderSubComponent:h,renderChildRows:g,getRowCanExpand:p,isLoading:f=!1,loadingMessage:x="🚅 Loading logs...",noDataMessage:v="No logs found",enableSorting:y=!1}){let b=!!(h||g)&&!!p,[w,S]=(0,s.useState)([]),j=(0,i.useReactTable)({data:e,columns:u,...y&&{state:{sorting:w},onSortingChange:S,enableSortingRemoval:!1},...b&&{getRowCanExpand:p},getRowId:(e,t)=>e?.request_id??String(t),getCoreRowModel:(0,r.getCoreRowModel)(),...y&&{getSortedRowModel:(0,r.getSortedRowModel)()},...b&&{getExpandedRowModel:(0,r.getExpandedRowModel)()}});return(0,t.jsx)("div",{className:"rounded-lg custom-border overflow-x-auto w-full max-w-full box-border",children:(0,t.jsxs)(a.Table,{className:"[&_td]:py-0.5 [&_th]:py-1 table-fixed w-full box-border",style:{minWidth:"400px"},children:[(0,t.jsx)(l.TableHead,{children:j.getHeaderGroups().map(e=>(0,t.jsx)(c.TableRow,{children:e.headers.map(e=>{let s=y&&e.column.getCanSort(),r=e.column.getIsSorted();return(0,t.jsx)(n.TableHeaderCell,{className:`py-1 h-8 ${s?"cursor-pointer select-none hover:bg-gray-50":""}`,onClick:s?e.column.getToggleSortingHandler():void 0,children:e.isPlaceholder?null:(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,i.flexRender)(e.column.columnDef.header,e.getContext()),s&&(0,t.jsx)("span",{className:"text-gray-400",children:"asc"===r?"↑":"desc"===r?"↓":"⇅"})]})},e.id)})},e.id))}),(0,t.jsx)(o.TableBody,{children:f?(0,t.jsx)(c.TableRow,{children:(0,t.jsx)(d.TableCell,{colSpan:u.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:x})})})}):j.getRowModel().rows.length>0?j.getRowModel().rows.map(e=>(0,t.jsxs)(s.Fragment,{children:[(0,t.jsx)(c.TableRow,{className:`h-8 ${m?"cursor-pointer hover:bg-gray-50":""}`,onClick:()=>m?.(e.original),children:e.getVisibleCells().map(e=>(0,t.jsx)(d.TableCell,{className:"py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap",children:(0,i.flexRender)(e.column.columnDef.cell,e.getContext())},e.id))}),b&&e.getIsExpanded()&&g&&g({row:e}),b&&e.getIsExpanded()&&h&&!g&&(0,t.jsx)(c.TableRow,{children:(0,t.jsx)(d.TableCell,{colSpan:e.getVisibleCells().length,className:"p-0",children:(0,t.jsx)("div",{className:"w-full max-w-full overflow-hidden box-border",children:h({row:e})})})})]},e.id)):(0,t.jsx)(c.TableRow,{children:(0,t.jsx)(d.TableCell,{colSpan:u.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:v})})})})})]})})}e.s(["DataTable",()=>u])},91979,e=>{"use strict";e.i(247167);var t=e.i(931067),s=e.i(271645);let i={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"};var r=e.i(9583),a=s.forwardRef(function(e,a){return s.createElement(r.default,(0,t.default)({},e,{ref:a,icon:i}))});e.s(["ReloadOutlined",0,a],91979)},750113,e=>{"use strict";var t=e.i(684024);e.s(["QuestionCircleOutlined",()=>t.default])},564897,e=>{"use strict";e.i(247167);var t=e.i(931067),s=e.i(271645);let i={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"};var r=e.i(9583),a=s.forwardRef(function(e,a){return s.createElement(r.default,(0,t.default)({},e,{ref:a,icon:i}))});e.s(["MinusCircleOutlined",0,a],564897)},178654,621192,e=>{"use strict";let t=e.i(211576).Col;e.s(["Col",0,t],178654);let s=e.i(264042).Row;e.s(["Row",0,s],621192)},338468,e=>{"use strict";var t=e.i(843476);e.i(111790);var s=e.i(280881),i=e.i(135214);e.s(["default",0,()=>{let{accessToken:e,userRole:r,userId:a}=(0,i.default)();return(0,t.jsx)(s.MCPServers,{accessToken:e,userRole:r,userID:a})}])}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/4472ece1be7379b3.js b/litellm/proxy/_experimental/out/_next/static/chunks/4472ece1be7379b3.js new file mode 100644 index 00000000000..6fa196b647a --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/4472ece1be7379b3.js @@ -0,0 +1,8 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,434626,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.createElement("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"}))});e.s(["ExternalLinkIcon",0,l],434626)},902555,e=>{"use strict";var t=e.i(843476),l=e.i(591935),a=e.i(122577),r=e.i(278587),i=e.i(68155),s=e.i(360820),n=e.i(871943),o=e.i(434626),d=e.i(592968),c=e.i(115504),u=e.i(752978);function m({icon:e,onClick:l,className:a,disabled:r,dataTestId:i}){return r?(0,t.jsx)(u.Icon,{icon:e,size:"sm",className:"opacity-50 cursor-not-allowed","data-testid":i}):(0,t.jsx)(u.Icon,{icon:e,size:"sm",onClick:l,className:(0,c.cx)("cursor-pointer",a),"data-testid":i})}let g={Edit:{icon:l.PencilAltIcon,className:"hover:text-blue-600"},Delete:{icon:i.TrashIcon,className:"hover:text-red-600"},Test:{icon:a.PlayIcon,className:"hover:text-blue-600"},Regenerate:{icon:r.RefreshIcon,className:"hover:text-green-600"},Up:{icon:s.ChevronUpIcon,className:"hover:text-blue-600"},Down:{icon:n.ChevronDownIcon,className:"hover:text-blue-600"},Open:{icon:o.ExternalLinkIcon,className:"hover:text-green-600"}};function h({onClick:e,tooltipText:l,disabled:a=!1,disabledTooltipText:r,dataTestId:i,variant:s}){let{icon:n,className:o}=g[s];return(0,t.jsx)(d.Tooltip,{title:a?r:l,children:(0,t.jsx)("span",{children:(0,t.jsx)(m,{icon:n,onClick:e,className:o,disabled:a,dataTestId:i})})})}e.s(["default",()=>h],902555)},122577,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"}),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 12a9 9 0 11-18 0 9 9 0 0118 0z"}))});e.s(["PlayIcon",0,l],122577)},591935,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.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.s(["PencilAltIcon",0,l],591935)},871943,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"}))});e.s(["ChevronDownIcon",0,l],871943)},360820,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 15l7-7 7 7"}))});e.s(["ChevronUpIcon",0,l],360820)},185793,e=>{"use strict";e.i(247167);var t=e.i(271645),l=e.i(343794),a=e.i(242064),r=e.i(529681);let i=e=>{let{prefixCls:a,className:r,style:i,size:s,shape:n}=e,o=(0,l.default)({[`${a}-lg`]:"large"===s,[`${a}-sm`]:"small"===s}),d=(0,l.default)({[`${a}-circle`]:"circle"===n,[`${a}-square`]:"square"===n,[`${a}-round`]:"round"===n}),c=t.useMemo(()=>"number"==typeof s?{width:s,height:s,lineHeight:`${s}px`}:{},[s]);return t.createElement("span",{className:(0,l.default)(a,o,d,r),style:Object.assign(Object.assign({},c),i)})};e.i(296059);var s=e.i(694758),n=e.i(915654),o=e.i(246422),d=e.i(838378);let c=new s.Keyframes("ant-skeleton-loading",{"0%":{backgroundPosition:"100% 50%"},"100%":{backgroundPosition:"0 50%"}}),u=e=>({height:e,lineHeight:(0,n.unit)(e)}),m=e=>Object.assign({width:e},u(e)),g=(e,t)=>Object.assign({width:t(e).mul(5).equal(),minWidth:t(e).mul(5).equal()},u(e)),h=e=>Object.assign({width:e},u(e)),p=(e,t,l)=>{let{skeletonButtonCls:a}=e;return{[`${l}${a}-circle`]:{width:t,minWidth:t,borderRadius:"50%"},[`${l}${a}-round`]:{borderRadius:t}}},f=(e,t)=>Object.assign({width:t(e).mul(2).equal(),minWidth:t(e).mul(2).equal()},u(e)),b=(0,o.genStyleHooks)("Skeleton",e=>{let{componentCls:t,calc:l}=e;return(e=>{let{componentCls:t,skeletonAvatarCls:l,skeletonTitleCls:a,skeletonParagraphCls:r,skeletonButtonCls:i,skeletonInputCls:s,skeletonImageCls:n,controlHeight:o,controlHeightLG:d,controlHeightSM:u,gradientFromColor:b,padding:x,marginSM:v,borderRadius:j,titleHeight:w,blockRadius:k,paragraphLiHeight:C,controlHeightXS:y,paragraphMarginTop:$}=e;return{[t]:{display:"table",width:"100%",[`${t}-header`]:{display:"table-cell",paddingInlineEnd:x,verticalAlign:"top",[l]:Object.assign({display:"inline-block",verticalAlign:"top",background:b},m(o)),[`${l}-circle`]:{borderRadius:"50%"},[`${l}-lg`]:Object.assign({},m(d)),[`${l}-sm`]:Object.assign({},m(u))},[`${t}-content`]:{display:"table-cell",width:"100%",verticalAlign:"top",[a]:{width:"100%",height:w,background:b,borderRadius:k,[`+ ${r}`]:{marginBlockStart:u}},[r]:{padding:0,"> li":{width:"100%",height:C,listStyle:"none",background:b,borderRadius:k,"+ li":{marginBlockStart:y}}},[`${r}> li:last-child:not(:first-child):not(:nth-child(2))`]:{width:"61%"}},[`&-round ${t}-content`]:{[`${a}, ${r} > li`]:{borderRadius:j}}},[`${t}-with-avatar ${t}-content`]:{[a]:{marginBlockStart:v,[`+ ${r}`]:{marginBlockStart:$}}},[`${t}${t}-element`]:Object.assign(Object.assign(Object.assign(Object.assign({display:"inline-block",width:"auto"},(e=>{let{borderRadiusSM:t,skeletonButtonCls:l,controlHeight:a,controlHeightLG:r,controlHeightSM:i,gradientFromColor:s,calc:n}=e;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({[l]:Object.assign({display:"inline-block",verticalAlign:"top",background:s,borderRadius:t,width:n(a).mul(2).equal(),minWidth:n(a).mul(2).equal()},f(a,n))},p(e,a,l)),{[`${l}-lg`]:Object.assign({},f(r,n))}),p(e,r,`${l}-lg`)),{[`${l}-sm`]:Object.assign({},f(i,n))}),p(e,i,`${l}-sm`))})(e)),(e=>{let{skeletonAvatarCls:t,gradientFromColor:l,controlHeight:a,controlHeightLG:r,controlHeightSM:i}=e;return{[t]:Object.assign({display:"inline-block",verticalAlign:"top",background:l},m(a)),[`${t}${t}-circle`]:{borderRadius:"50%"},[`${t}${t}-lg`]:Object.assign({},m(r)),[`${t}${t}-sm`]:Object.assign({},m(i))}})(e)),(e=>{let{controlHeight:t,borderRadiusSM:l,skeletonInputCls:a,controlHeightLG:r,controlHeightSM:i,gradientFromColor:s,calc:n}=e;return{[a]:Object.assign({display:"inline-block",verticalAlign:"top",background:s,borderRadius:l},g(t,n)),[`${a}-lg`]:Object.assign({},g(r,n)),[`${a}-sm`]:Object.assign({},g(i,n))}})(e)),(e=>{let{skeletonImageCls:t,imageSizeBase:l,gradientFromColor:a,borderRadiusSM:r,calc:i}=e;return{[t]:Object.assign(Object.assign({display:"inline-flex",alignItems:"center",justifyContent:"center",verticalAlign:"middle",background:a,borderRadius:r},h(i(l).mul(2).equal())),{[`${t}-path`]:{fill:"#bfbfbf"},[`${t}-svg`]:Object.assign(Object.assign({},h(l)),{maxWidth:i(l).mul(4).equal(),maxHeight:i(l).mul(4).equal()}),[`${t}-svg${t}-svg-circle`]:{borderRadius:"50%"}}),[`${t}${t}-circle`]:{borderRadius:"50%"}}})(e)),[`${t}${t}-block`]:{width:"100%",[i]:{width:"100%"},[s]:{width:"100%"}},[`${t}${t}-active`]:{[` + ${a}, + ${r} > li, + ${l}, + ${i}, + ${s}, + ${n} + `]:Object.assign({},{background:e.skeletonLoadingBackground,backgroundSize:"400% 100%",animationName:c,animationDuration:e.skeletonLoadingMotionDuration,animationTimingFunction:"ease",animationIterationCount:"infinite"})}}})((0,d.mergeToken)(e,{skeletonAvatarCls:`${t}-avatar`,skeletonTitleCls:`${t}-title`,skeletonParagraphCls:`${t}-paragraph`,skeletonButtonCls:`${t}-button`,skeletonInputCls:`${t}-input`,skeletonImageCls:`${t}-image`,imageSizeBase:l(e.controlHeight).mul(1.5).equal(),borderRadius:100,skeletonLoadingBackground:`linear-gradient(90deg, ${e.gradientFromColor} 25%, ${e.gradientToColor} 37%, ${e.gradientFromColor} 63%)`,skeletonLoadingMotionDuration:"1.4s"}))},e=>{let{colorFillContent:t,colorFill:l}=e;return{color:t,colorGradientEnd:l,gradientFromColor:t,gradientToColor:l,titleHeight:e.controlHeight/2,blockRadius:e.borderRadiusSM,paragraphMarginTop:e.marginLG+e.marginXXS,paragraphLiHeight:e.controlHeight/2}},{deprecatedTokens:[["color","gradientFromColor"],["colorGradientEnd","gradientToColor"]]}),x=e=>{let{prefixCls:a,className:r,style:i,rows:s=0}=e,n=Array.from({length:s}).map((l,a)=>t.createElement("li",{key:a,style:{width:((e,t)=>{let{width:l,rows:a=2}=t;return Array.isArray(l)?l[e]:a-1===e?l:void 0})(a,e)}}));return t.createElement("ul",{className:(0,l.default)(a,r),style:i},n)},v=({prefixCls:e,className:a,width:r,style:i})=>t.createElement("h3",{className:(0,l.default)(e,a),style:Object.assign({width:r},i)});function j(e){return e&&"object"==typeof e?e:{}}let w=e=>{let{prefixCls:r,loading:s,className:n,rootClassName:o,style:d,children:c,avatar:u=!1,title:m=!0,paragraph:g=!0,active:h,round:p}=e,{getPrefixCls:f,direction:w,className:k,style:C}=(0,a.useComponentConfig)("skeleton"),y=f("skeleton",r),[$,O,N]=b(y);if(s||!("loading"in e)){let e,a,r=!!u,s=!!m,c=!!g;if(r){let l=Object.assign(Object.assign({prefixCls:`${y}-avatar`},s&&!c?{size:"large",shape:"square"}:{size:"large",shape:"circle"}),j(u));e=t.createElement("div",{className:`${y}-header`},t.createElement(i,Object.assign({},l)))}if(s||c){let e,l;if(s){let l=Object.assign(Object.assign({prefixCls:`${y}-title`},!r&&c?{width:"38%"}:r&&c?{width:"50%"}:{}),j(m));e=t.createElement(v,Object.assign({},l))}if(c){let e,a=Object.assign(Object.assign({prefixCls:`${y}-paragraph`},(e={},r&&s||(e.width="61%"),!r&&s?e.rows=3:e.rows=2,e)),j(g));l=t.createElement(x,Object.assign({},a))}a=t.createElement("div",{className:`${y}-content`},e,l)}let f=(0,l.default)(y,{[`${y}-with-avatar`]:r,[`${y}-active`]:h,[`${y}-rtl`]:"rtl"===w,[`${y}-round`]:p},k,n,o,O,N);return $(t.createElement("div",{className:f,style:Object.assign(Object.assign({},C),d)},e,a))}return null!=c?c:null};w.Button=e=>{let{prefixCls:s,className:n,rootClassName:o,active:d,block:c=!1,size:u="default"}=e,{getPrefixCls:m}=t.useContext(a.ConfigContext),g=m("skeleton",s),[h,p,f]=b(g),x=(0,r.default)(e,["prefixCls"]),v=(0,l.default)(g,`${g}-element`,{[`${g}-active`]:d,[`${g}-block`]:c},n,o,p,f);return h(t.createElement("div",{className:v},t.createElement(i,Object.assign({prefixCls:`${g}-button`,size:u},x))))},w.Avatar=e=>{let{prefixCls:s,className:n,rootClassName:o,active:d,shape:c="circle",size:u="default"}=e,{getPrefixCls:m}=t.useContext(a.ConfigContext),g=m("skeleton",s),[h,p,f]=b(g),x=(0,r.default)(e,["prefixCls","className"]),v=(0,l.default)(g,`${g}-element`,{[`${g}-active`]:d},n,o,p,f);return h(t.createElement("div",{className:v},t.createElement(i,Object.assign({prefixCls:`${g}-avatar`,shape:c,size:u},x))))},w.Input=e=>{let{prefixCls:s,className:n,rootClassName:o,active:d,block:c,size:u="default"}=e,{getPrefixCls:m}=t.useContext(a.ConfigContext),g=m("skeleton",s),[h,p,f]=b(g),x=(0,r.default)(e,["prefixCls"]),v=(0,l.default)(g,`${g}-element`,{[`${g}-active`]:d,[`${g}-block`]:c},n,o,p,f);return h(t.createElement("div",{className:v},t.createElement(i,Object.assign({prefixCls:`${g}-input`,size:u},x))))},w.Image=e=>{let{prefixCls:r,className:i,rootClassName:s,style:n,active:o}=e,{getPrefixCls:d}=t.useContext(a.ConfigContext),c=d("skeleton",r),[u,m,g]=b(c),h=(0,l.default)(c,`${c}-element`,{[`${c}-active`]:o},i,s,m,g);return u(t.createElement("div",{className:h},t.createElement("div",{className:(0,l.default)(`${c}-image`,i),style:n},t.createElement("svg",{viewBox:"0 0 1098 1024",xmlns:"http://www.w3.org/2000/svg",className:`${c}-image-svg`},t.createElement("title",null,"Image placeholder"),t.createElement("path",{d:"M365.714286 329.142857q0 45.714286-32.036571 77.677714t-77.677714 32.036571-77.677714-32.036571-32.036571-77.677714 32.036571-77.677714 77.677714-32.036571 77.677714 32.036571 32.036571 77.677714zM950.857143 548.571429l0 256-804.571429 0 0-109.714286 182.857143-182.857143 91.428571 91.428571 292.571429-292.571429zM1005.714286 146.285714l-914.285714 0q-7.460571 0-12.873143 5.412571t-5.412571 12.873143l0 694.857143q0 7.460571 5.412571 12.873143t12.873143 5.412571l914.285714 0q7.460571 0 12.873143-5.412571t5.412571-12.873143l0-694.857143q0-7.460571-5.412571-12.873143t-12.873143-5.412571zM1097.142857 164.571429l0 694.857143q0 37.741714-26.843429 64.585143t-64.585143 26.843429l-914.285714 0q-37.741714 0-64.585143-26.843429t-26.843429-64.585143l0-694.857143q0-37.741714 26.843429-64.585143t64.585143-26.843429l914.285714 0q37.741714 0 64.585143 26.843429t26.843429 64.585143z",className:`${c}-image-path`})))))},w.Node=e=>{let{prefixCls:r,className:i,rootClassName:s,style:n,active:o,children:d}=e,{getPrefixCls:c}=t.useContext(a.ConfigContext),u=c("skeleton",r),[m,g,h]=b(u),p=(0,l.default)(u,`${u}-element`,{[`${u}-active`]:o},g,i,s,h);return m(t.createElement("div",{className:p},t.createElement("div",{className:(0,l.default)(`${u}-image`,i),style:n},d)))},e.s(["default",0,w],185793)},959013,e=>{"use strict";e.i(247167);var t=e.i(931067),l=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8z"}},{tag:"path",attrs:{d:"M192 474h672q8 0 8 8v60q0 8-8 8H160q-8 0-8-8v-60q0-8 8-8z"}}]},name:"plus",theme:"outlined"};var r=e.i(9583),i=l.forwardRef(function(e,i){return l.createElement(r.default,(0,t.default)({},e,{ref:i,icon:a}))});e.s(["default",0,i],959013)},269200,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("Table"),i=l.default.forwardRef((e,i)=>{let{children:s,className:n}=e,o=(0,t.__rest)(e,["children","className"]);return l.default.createElement("div",{className:(0,a.tremorTwMerge)(r("root"),"overflow-auto",n)},l.default.createElement("table",Object.assign({ref:i,className:(0,a.tremorTwMerge)(r("table"),"w-full text-tremor-default","text-tremor-content","dark:text-dark-tremor-content")},o),s))});i.displayName="Table",e.s(["Table",()=>i],269200)},942232,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("TableBody"),i=l.default.forwardRef((e,i)=>{let{children:s,className:n}=e,o=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("tbody",Object.assign({ref:i,className:(0,a.tremorTwMerge)(r("root"),"align-top divide-y","divide-tremor-border","dark:divide-dark-tremor-border",n)},o),s))});i.displayName="TableBody",e.s(["TableBody",()=>i],942232)},977572,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("TableCell"),i=l.default.forwardRef((e,i)=>{let{children:s,className:n}=e,o=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("td",Object.assign({ref:i,className:(0,a.tremorTwMerge)(r("root"),"align-middle whitespace-nowrap text-left p-4",n)},o),s))});i.displayName="TableCell",e.s(["TableCell",()=>i],977572)},427612,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("TableHead"),i=l.default.forwardRef((e,i)=>{let{children:s,className:n}=e,o=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("thead",Object.assign({ref:i,className:(0,a.tremorTwMerge)(r("root"),"text-left","text-tremor-content","dark:text-dark-tremor-content",n)},o),s))});i.displayName="TableHead",e.s(["TableHead",()=>i],427612)},64848,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("TableHeaderCell"),i=l.default.forwardRef((e,i)=>{let{children:s,className:n}=e,o=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("th",Object.assign({ref:i,className:(0,a.tremorTwMerge)(r("root"),"whitespace-nowrap text-left font-semibold top-0 px-4 py-3.5","text-tremor-content-strong","dark:text-dark-tremor-content-strong",n)},o),s))});i.displayName="TableHeaderCell",e.s(["TableHeaderCell",()=>i],64848)},496020,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("TableRow"),i=l.default.forwardRef((e,i)=>{let{children:s,className:n}=e,o=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("tr",Object.assign({ref:i,className:(0,a.tremorTwMerge)(r("row"),n)},o),s))});i.displayName="TableRow",e.s(["TableRow",()=>i],496020)},68155,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.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.s(["TrashIcon",0,l],68155)},278587,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",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"}))});e.s(["RefreshIcon",0,l],278587)},207670,e=>{"use strict";function t(){for(var e,t,l=0,a="",r=arguments.length;lt,"default",0,t])},907308,e=>{"use strict";var t=e.i(843476),l=e.i(271645),a=e.i(212931),r=e.i(808613),i=e.i(464571),s=e.i(199133),n=e.i(592968),o=e.i(213205),d=e.i(374009),c=e.i(764205);e.s(["default",0,({isVisible:e,onCancel:u,onSubmit:m,accessToken:g,title:h="Add Team Member",roles:p=[{label:"admin",value:"admin",description:"Admin role. Can create team keys, add members, and manage settings."},{label:"user",value:"user",description:"User role. Can view team info, but not manage it."}],defaultRole:f="user",teamId:b})=>{let[x]=r.Form.useForm(),[v,j]=(0,l.useState)([]),[w,k]=(0,l.useState)(!1),[C,y]=(0,l.useState)("user_email"),[$,O]=(0,l.useState)(!1),N=async(e,t)=>{if(!e)return void j([]);k(!0);try{let l=new URLSearchParams;if(l.append(t,e),b&&l.append("team_id",b),null==g)return;let a=(await (0,c.userFilterUICall)(g,l)).map(e=>({label:"user_email"===t?`${e.user_email}`:`${e.user_id}`,value:"user_email"===t?e.user_email:e.user_id,user:e}));j(a)}catch(e){console.error("Error fetching users:",e)}finally{k(!1)}},E=(0,l.useCallback)((0,d.default)((e,t)=>N(e,t),300),[]),T=(e,t)=>{y(t),E(e,t)},_=(e,t)=>{let l=t.user;x.setFieldsValue({user_email:l.user_email,user_id:l.user_id,role:x.getFieldValue("role")})},M=async e=>{O(!0);try{await m(e)}finally{O(!1)}};return(0,t.jsx)(a.Modal,{title:h,open:e,onCancel:()=>{x.resetFields(),j([]),u()},footer:null,width:800,maskClosable:!$,children:(0,t.jsxs)(r.Form,{form:x,onFinish:M,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",initialValues:{role:f},children:[(0,t.jsx)(r.Form.Item,{label:"Email",name:"user_email",className:"mb-4",children:(0,t.jsx)(s.Select,{showSearch:!0,className:"w-full",placeholder:"Search by email",filterOption:!1,onSearch:e=>T(e,"user_email"),onSelect:(e,t)=>_(e,t),options:"user_email"===C?v:[],loading:w,allowClear:!0})}),(0,t.jsx)("div",{className:"text-center mb-4",children:"OR"}),(0,t.jsx)(r.Form.Item,{label:"User ID",name:"user_id",className:"mb-4",children:(0,t.jsx)(s.Select,{showSearch:!0,className:"w-full",placeholder:"Search by user ID",filterOption:!1,onSearch:e=>T(e,"user_id"),onSelect:(e,t)=>_(e,t),options:"user_id"===C?v:[],loading:w,allowClear:!0})}),(0,t.jsx)(r.Form.Item,{label:"Member Role",name:"role",className:"mb-4",children:(0,t.jsx)(s.Select,{defaultValue:f,children:p.map(e=>(0,t.jsx)(s.Select.Option,{value:e.value,children:(0,t.jsxs)(n.Tooltip,{title:e.description,children:[(0,t.jsx)("span",{className:"font-medium",children:e.label}),(0,t.jsxs)("span",{className:"ml-2 text-gray-500 text-sm",children:["- ",e.description]})]})},e.value))})}),(0,t.jsx)("div",{className:"text-right mt-4",children:(0,t.jsx)(i.Button,{type:"primary",htmlType:"submit",icon:(0,t.jsx)(o.UserAddOutlined,{}),loading:$,children:$?"Adding...":"Add Member"})})]})})}])},162386,e=>{"use strict";var t=e.i(843476),l=e.i(625901),a=e.i(109799),r=e.i(785242),i=e.i(738014),s=e.i(199133),n=e.i(981339),o=e.i(592968);let d={label:"All Proxy Models",value:"all-proxy-models"},c={label:"No Default Models",value:"no-default-models"},u=[d,c],m={user:({allProxyModels:e,userModels:t,options:l})=>t&&l?.includeUserModels?t:[],team:({allProxyModels:e,selectedOrganization:t,userModels:l})=>t?t.models.includes(d.value)||0===t.models.length?e:e.filter(e=>t.models.includes(e)):e??[],organization:({allProxyModels:e})=>e,global:({allProxyModels:e})=>e};e.s(["ModelSelect",0,e=>{let{teamID:g,organizationID:h,options:p,context:f,dataTestId:b,value:x=[],onChange:v,style:j}=e,{includeUserModels:w,showAllTeamModelsOption:k,showAllProxyModelsOverride:C,includeSpecialOptions:y}=p||{},{data:$,isLoading:O}=(0,l.useAllProxyModels)(),{data:N,isLoading:E}=(0,r.useTeam)(g),{data:T,isLoading:_}=(0,a.useOrganization)(h),{data:M,isLoading:S}=(0,i.useCurrentUser)(),I=e=>u.some(t=>t.value===e),R=x.some(I),A=T?.models.includes(d.value)||T?.models.length===0;if(O||E||_||S)return(0,t.jsx)(n.Skeleton.Input,{active:!0,block:!0});let{wildcard:F,regular:L}=(e=>{let t=[],l=[];for(let a of e)a.endsWith("/*")?t.push(a):l.push(a);return{wildcard:t,regular:l}})(((e,t,l)=>{let a=Array.from(new Map(e.map(e=>[e.id,e])).values()).map(e=>e.id);if(t.options?.showAllProxyModelsOverride)return a;let r=m[t.context];return r?r({allProxyModels:a,...l,options:t.options}):[]})($?.data??[],e,{selectedTeam:N,selectedOrganization:T,userModels:M?.models}));return(0,t.jsx)(s.Select,{"data-testid":b,value:x,onChange:e=>{let t=e.filter(I);v(t.length>0?[t[t.length-1]]:e)},style:j,options:[y?{label:(0,t.jsx)("span",{children:"Special Options"}),title:"Special Options",options:[...C||A&&y||"global"===f?[{label:(0,t.jsx)("span",{children:"All Proxy Models"}),value:d.value,disabled:x.length>0&&x.some(e=>I(e)&&e!==d.value),key:d.value}]:[],{label:(0,t.jsx)("span",{children:"No Default Models"}),value:c.value,disabled:x.length>0&&x.some(e=>I(e)&&e!==c.value),key:c.value}]}:[],...F.length>0?[{label:(0,t.jsx)("span",{children:"Wildcard Options"}),title:"Wildcard Options",options:F.map(e=>{let l=e.replace("/*",""),a=l.charAt(0).toUpperCase()+l.slice(1);return{label:(0,t.jsx)("span",{children:`All ${a} models`}),value:e,disabled:R}})}]:[],{label:(0,t.jsx)("span",{children:"Models"}),title:"Models",options:L.map(e=>({label:(0,t.jsx)("span",{children:e}),value:e,disabled:R}))}],mode:"multiple",placeholder:"Select Models",allowClear:!0,maxTagCount:"responsive",maxTagPlaceholder:e=>(0,t.jsx)(o.Tooltip,{styles:{root:{pointerEvents:"none"}},title:e.map(({value:e})=>e).join(", "),children:(0,t.jsxs)("span",{children:["+",e.length," more"]})})})}],162386)},276173,e=>{"use strict";var t=e.i(843476),l=e.i(599724),a=e.i(779241),r=e.i(464571),i=e.i(808613),s=e.i(212931),n=e.i(199133),o=e.i(271645),d=e.i(435451);e.s(["default",0,({visible:e,onCancel:c,onSubmit:u,initialData:m,mode:g,config:h})=>{let p,[f]=i.Form.useForm(),[b,x]=(0,o.useState)(!1);console.log("Initial Data:",m),(0,o.useEffect)(()=>{if(e)if("edit"===g&&m){let e={...m,role:m.role||h.defaultRole,max_budget_in_team:m.max_budget_in_team||null,tpm_limit:m.tpm_limit||null,rpm_limit:m.rpm_limit||null};console.log("Setting form values:",e),f.setFieldsValue(e)}else f.resetFields(),f.setFieldsValue({role:h.defaultRole||h.roleOptions[0]?.value})},[e,m,g,f,h.defaultRole,h.roleOptions]);let v=async e=>{try{x(!0);let t=Object.entries(e).reduce((e,[t,l])=>{if("string"==typeof l){let a=l.trim();return""===a&&("max_budget_in_team"===t||"tpm_limit"===t||"rpm_limit"===t)?{...e,[t]:null}:{...e,[t]:a}}return{...e,[t]:l}},{});console.log("Submitting form data:",t),await Promise.resolve(u(t)),f.resetFields()}catch(e){console.error("Form submission error:",e)}finally{x(!1)}};return(0,t.jsx)(s.Modal,{title:h.title||("add"===g?"Add Member":"Edit Member"),open:e,width:1e3,footer:null,onCancel:c,children:(0,t.jsxs)(i.Form,{form:f,onFinish:v,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[h.showEmail&&(0,t.jsx)(i.Form.Item,{label:"Email",name:"user_email",className:"mb-4",rules:[{type:"email",message:"Please enter a valid email!"}],children:(0,t.jsx)(a.TextInput,{placeholder:"user@example.com"})}),h.showEmail&&h.showUserId&&(0,t.jsx)("div",{className:"text-center mb-4",children:(0,t.jsx)(l.Text,{children:"OR"})}),h.showUserId&&(0,t.jsx)(i.Form.Item,{label:"User ID",name:"user_id",className:"mb-4",children:(0,t.jsx)(a.TextInput,{placeholder:"user_123"})}),(0,t.jsx)(i.Form.Item,{label:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{children:"Role"}),"edit"===g&&m&&(0,t.jsxs)("span",{className:"text-gray-500 text-sm",children:["(Current: ",(p=m.role,h.roleOptions.find(e=>e.value===p)?.label||p),")"]})]}),name:"role",className:"mb-4",rules:[{required:!0,message:"Please select a role!"}],children:(0,t.jsx)(n.Select,{children:"edit"===g&&m?[...h.roleOptions.filter(e=>e.value===m.role),...h.roleOptions.filter(e=>e.value!==m.role)].map(e=>(0,t.jsx)(n.Select.Option,{value:e.value,children:e.label},e.value)):h.roleOptions.map(e=>(0,t.jsx)(n.Select.Option,{value:e.value,children:e.label},e.value))})}),h.additionalFields?.map(e=>(0,t.jsx)(i.Form.Item,{label:e.label,name:e.name,className:"mb-4",rules:e.rules,children:(e=>{switch(e.type){case"input":return(0,t.jsx)(a.TextInput,{placeholder:e.placeholder});case"numerical":return(0,t.jsx)(d.default,{step:e.step||1,min:e.min||0,style:{width:"100%"},placeholder:e.placeholder||"Enter a numerical value"});case"select":return(0,t.jsx)(n.Select,{children:e.options?.map(e=>(0,t.jsx)(n.Select.Option,{value:e.value,children:e.label},e.value))});default:return null}})(e)},e.name)),(0,t.jsxs)("div",{className:"text-right mt-6",children:[(0,t.jsx)(r.Button,{onClick:c,className:"mr-2",disabled:b,children:"Cancel"}),(0,t.jsx)(r.Button,{type:"default",htmlType:"submit",loading:b,children:"add"===g?b?"Adding...":"Add Member":b?"Saving...":"Save Changes"})]})]})})}])},294612,e=>{"use strict";var t=e.i(843476),l=e.i(100486),a=e.i(827252),r=e.i(213205),i=e.i(771674),s=e.i(464571),n=e.i(770914),o=e.i(291542),d=e.i(262218),c=e.i(592968),u=e.i(898586),m=e.i(902555);let{Text:g}=u.Typography;function h({members:e,canEdit:u,onEdit:h,onDelete:p,onAddMember:f,roleColumnTitle:b="Role",roleTooltip:x,extraColumns:v=[],showDeleteForMember:j,emptyText:w}){let k=[{title:"User Email",dataIndex:"user_email",key:"user_email",render:e=>(0,t.jsx)(g,{children:e||"-"})},{title:"User ID",dataIndex:"user_id",key:"user_id",render:e=>"default_user_id"===e?(0,t.jsx)(d.Tag,{color:"blue",children:"Default Proxy Admin"}):(0,t.jsx)(g,{children:e||"-"})},{title:x?(0,t.jsxs)(n.Space,{direction:"horizontal",children:[b,(0,t.jsx)(c.Tooltip,{title:x,children:(0,t.jsx)(a.InfoCircleOutlined,{})})]}):b,dataIndex:"role",key:"role",render:e=>(0,t.jsxs)(n.Space,{children:[e?.toLowerCase()==="admin"||e?.toLowerCase()==="org_admin"?(0,t.jsx)(l.CrownOutlined,{}):(0,t.jsx)(i.UserOutlined,{}),(0,t.jsx)(g,{style:{textTransform:"capitalize"},children:e||"-"})]})},...v,{title:"Actions",key:"actions",fixed:"right",width:120,render:(e,l)=>u?(0,t.jsxs)(n.Space,{children:[(0,t.jsx)(m.default,{variant:"Edit",tooltipText:"Edit member",dataTestId:"edit-member",onClick:()=>h(l)}),(!j||j(l))&&(0,t.jsx)(m.default,{variant:"Delete",tooltipText:"Delete member",dataTestId:"delete-member",onClick:()=>p(l)})]}):null}];return(0,t.jsxs)(n.Space,{direction:"vertical",style:{width:"100%"},children:[(0,t.jsxs)("span",{className:"inline-flex text-sm text-gray-700",children:[e.length," Member",1!==e.length?"s":""]}),(0,t.jsx)(o.Table,{columns:k,dataSource:e,rowKey:e=>e.user_id??e.user_email??JSON.stringify(e),pagination:!1,size:"small",scroll:{x:"max-content"},locale:w?{emptyText:w}:void 0}),f&&u&&(0,t.jsx)(s.Button,{icon:(0,t.jsx)(r.UserAddOutlined,{}),type:"primary",onClick:f,children:"Add Member"})]})}e.s(["default",()=>h])}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/46a2cc6389ea6525.js b/litellm/proxy/_experimental/out/_next/static/chunks/46a2cc6389ea6525.js deleted file mode 100644 index 6bf796e59e7..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/46a2cc6389ea6525.js +++ /dev/null @@ -1 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,618566,(e,t,s)=>{t.exports=e.r(976562)},346328,e=>{"use strict";var t=e.i(843476),s=e.i(271645),l=e.i(618566);let i="litellm-mcp-oauth-result",a="litellm-mcp-oauth-return-url",n=()=>{let e=(0,l.useSearchParams)(),n=(0,s.useMemo)(()=>e?{type:"litellm-mcp-oauth",code:e.get("code"),state:e.get("state")}:null,[e]);return(0,s.useEffect)(()=>{if(!n)return;try{window.sessionStorage.setItem(i,JSON.stringify(n)),window.localStorage.setItem(i,JSON.stringify(n))}catch(e){}let e=window.sessionStorage.getItem(a)||window.localStorage.getItem(a)||(()=>{let e=window.location.pathname||"",t=e.indexOf("/ui");if(t>=0){let s=e.slice(0,t+3);return s.endsWith("/")?s:`${s}`}return"/"})();window.location.replace(e)},[n]),(0,t.jsx)("div",{className:"min-h-screen flex items-center justify-center bg-slate-50 p-6",children:(0,t.jsxs)("div",{className:"max-w-lg w-full rounded-lg bg-white shadow-md p-8 text-center space-y-4",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold text-slate-900",children:"LiteLLM MCP OAuth"}),(0,t.jsx)("p",{className:"text-sm text-slate-700",children:"Authorization complete. You may close this window and return to the LiteLLM dashboard."}),(0,t.jsx)("p",{className:"text-xs text-slate-500",children:"If the window does not close automatically, everything is still saved—you can close it manually."})]})})};e.s(["default",0,()=>(0,t.jsx)(s.Suspense,{fallback:(0,t.jsx)("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}),children:(0,t.jsx)(n,{})})])}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/476e3c64fbdd0295.js b/litellm/proxy/_experimental/out/_next/static/chunks/476e3c64fbdd0295.js deleted file mode 100644 index a0294d9a67d..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/476e3c64fbdd0295.js +++ /dev/null @@ -1 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,21548,e=>{"use strict";var t=e.i(616303);e.s(["Empty",()=>t.default])},601236,e=>{e.v(e=>Promise.resolve().then(()=>e(764205)))}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/4c4469911e2f315e.js b/litellm/proxy/_experimental/out/_next/static/chunks/4c4469911e2f315e.js new file mode 100644 index 00000000000..9205cc0354f --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/4c4469911e2f315e.js @@ -0,0 +1 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,9314,263147,e=>{"use strict";var t=e.i(843476),s=e.i(199133),a=e.i(981339),l=e.i(645526),r=e.i(599724),i=e.i(266027),n=e.i(243652),o=e.i(764205),c=e.i(708347),d=e.i(135214);let u=(0,n.createQueryKeys)("accessGroups"),m=async e=>{let t=(0,o.getProxyBaseUrl)(),s=`${t}/v1/access_group`,a=await fetch(s,{method:"GET",headers:{[(0,o.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!a.ok){let e=await a.json(),t=(0,o.deriveErrorMessage)(e);throw(0,o.handleError)(t),Error(t)}return a.json()},p=()=>{let{accessToken:e,userRole:t}=(0,d.default)();return(0,i.useQuery)({queryKey:u.list({}),queryFn:async()=>m(e),enabled:!!e&&c.all_admin_roles.includes(t||"")})};e.s(["accessGroupKeys",0,u,"useAccessGroups",0,p],263147),e.s(["default",0,({value:e,onChange:i,placeholder:n="Select access groups",disabled:o=!1,style:c,className:d,showLabel:u=!1,labelText:m="Access Group",allowClear:g=!0})=>{let{data:h,isLoading:x,isError:y}=p();if(x)return(0,t.jsxs)("div",{children:[u&&(0,t.jsxs)(r.Text,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,t.jsx)(l.TeamOutlined,{className:"mr-2"})," ",m]}),(0,t.jsx)(a.Skeleton.Input,{active:!0,block:!0,style:{height:32,...c}})]});let f=(h??[]).map(e=>({label:(0,t.jsxs)("span",{children:[(0,t.jsx)("span",{className:"font-medium",children:e.access_group_name})," ",(0,t.jsxs)("span",{className:"text-gray-400 text-xs",children:["(",e.access_group_id,")"]})]}),value:e.access_group_id,selectedLabel:e.access_group_name,searchText:`${e.access_group_name} ${e.access_group_id}`}));return(0,t.jsxs)("div",{children:[u&&(0,t.jsxs)(r.Text,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,t.jsx)(l.TeamOutlined,{className:"mr-2"})," ",m]}),(0,t.jsx)(s.Select,{mode:"multiple",value:e,placeholder:n,onChange:i,disabled:o,allowClear:g,showSearch:!0,style:{width:"100%",...c},className:`rounded-md ${d??""}`,notFoundContent:y?(0,t.jsx)("span",{className:"text-red-500",children:"Failed to load access groups"}):"No access groups found",filterOption:(e,t)=>(f.find(e=>e.value===t?.value)?.searchText??"").toLowerCase().includes(e.toLowerCase()),optionLabelProp:"selectedLabel",options:f.map(e=>({label:e.label,value:e.value,selectedLabel:e.selectedLabel}))})]})}],9314)},552130,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(199133),l=e.i(764205);e.s(["default",0,({onChange:e,value:r,className:i,accessToken:n,placeholder:o="Select agents",disabled:c=!1})=>{let[d,u]=(0,s.useState)([]),[m,p]=(0,s.useState)([]),[g,h]=(0,s.useState)(!1);(0,s.useEffect)(()=>{(async()=>{if(n){h(!0);try{let e=await (0,l.getAgentsList)(n),t=e?.agents||[];u(t);let s=new Set;t.forEach(e=>{let t=e.agent_access_groups;t&&Array.isArray(t)&&t.forEach(e=>s.add(e))}),p(Array.from(s))}catch(e){console.error("Error fetching agents:",e)}finally{h(!1)}}})()},[n]);let x=[...m.map(e=>({label:e,value:`group:${e}`,isAccessGroup:!0,searchText:`${e} Access Group`})),...d.map(e=>({label:`${e.agent_name||e.agent_id}`,value:e.agent_id,isAccessGroup:!1,searchText:`${e.agent_name||e.agent_id} ${e.agent_id} Agent`}))],y=[...r?.agents||[],...(r?.accessGroups||[]).map(e=>`group:${e}`)];return(0,t.jsx)("div",{children:(0,t.jsx)(a.Select,{mode:"multiple",placeholder:o,onChange:t=>{e({agents:t.filter(e=>!e.startsWith("group:")),accessGroups:t.filter(e=>e.startsWith("group:")).map(e=>e.replace("group:",""))})},value:y,loading:g,className:i,allowClear:!0,showSearch:!0,style:{width:"100%"},disabled:c,filterOption:(e,t)=>(x.find(e=>e.value===t?.value)?.searchText||"").toLowerCase().includes(e.toLowerCase()),children:x.map(e=>(0,t.jsx)(a.Select.Option,{value:e.value,label:e.label,children:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[(0,t.jsx)("span",{style:{display:"inline-block",width:8,height:8,borderRadius:"50%",background:e.isAccessGroup?"#52c41a":"#722ed1",flexShrink:0}}),(0,t.jsx)("span",{style:{flex:1},children:e.label}),(0,t.jsx)("span",{style:{color:e.isAccessGroup?"#52c41a":"#722ed1",fontSize:"12px",fontWeight:500,opacity:.8},children:e.isAccessGroup?"Access Group":"Agent"})]})},e.value))})})}])},844565,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(199133),l=e.i(764205);e.s(["default",0,({onChange:e,value:r,className:i,accessToken:n,placeholder:o="Select pass through routes",disabled:c=!1,teamId:d})=>{let[u,m]=(0,s.useState)([]),[p,g]=(0,s.useState)(!1);return(0,s.useEffect)(()=>{(async()=>{if(n){g(!0);try{let e=await (0,l.getPassThroughEndpointsCall)(n,d);if(e.endpoints){let t=e.endpoints.flatMap(e=>{let t=e.path,s=e.methods;return s&&s.length>0?s.map(e=>({label:`${e} ${t}`,value:t})):[{label:t,value:t}]});m(t)}}catch(e){console.error("Error fetching pass through routes:",e)}finally{g(!1)}}})()},[n,d]),(0,t.jsx)(a.Select,{mode:"tags",placeholder:o,onChange:e,value:r,loading:p,className:i,allowClear:!0,options:u,optionFilterProp:"label",showSearch:!0,style:{width:"100%"},disabled:c})}])},810757,477386,e=>{"use strict";var t=e.i(271645);let s=t.forwardRef(function(e,s){return t.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:s},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}))});e.s(["CogIcon",0,s],810757);let a=t.forwardRef(function(e,s){return t.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:s},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"}))});e.s(["BanIcon",0,a],477386)},557662,e=>{"use strict";let t="../ui/assets/logos/",s=[{id:"arize",displayName:"Arize",logo:`${t}arize.png`,supports_key_team_logging:!0,dynamic_params:{arize_api_key:"password",arize_space_id:"password"},description:"Arize Logging Integration"},{id:"braintrust",displayName:"Braintrust",logo:`${t}braintrust.png`,supports_key_team_logging:!1,dynamic_params:{braintrust_api_key:"password",braintrust_project_name:"text"},description:"Braintrust Logging Integration"},{id:"custom_callback_api",displayName:"Custom Callback API",logo:`${t}custom.svg`,supports_key_team_logging:!0,dynamic_params:{custom_callback_api_url:"text",custom_callback_api_headers:"text"},description:"Custom Callback API Logging Integration"},{id:"datadog",displayName:"Datadog",logo:`${t}datadog.png`,supports_key_team_logging:!1,dynamic_params:{dd_api_key:"password",dd_site:"text"},description:"Datadog Logging Integration"},{id:"lago",displayName:"Lago",logo:`${t}lago.svg`,supports_key_team_logging:!1,dynamic_params:{lago_api_url:"text",lago_api_key:"password"},description:"Lago Billing Logging Integration"},{id:"langfuse",displayName:"Langfuse",logo:`${t}langfuse.png`,supports_key_team_logging:!0,dynamic_params:{langfuse_public_key:"text",langfuse_secret_key:"password",langfuse_host:"text"},description:"Langfuse v2 Logging Integration"},{id:"langfuse_otel",displayName:"Langfuse OTEL",logo:`${t}langfuse.png`,supports_key_team_logging:!0,dynamic_params:{langfuse_public_key:"text",langfuse_secret_key:"password",langfuse_host:"text"},description:"Langfuse v3 OTEL Logging Integration"},{id:"langsmith",displayName:"LangSmith",logo:`${t}langsmith.png`,supports_key_team_logging:!0,dynamic_params:{langsmith_api_key:"password",langsmith_project:"text",langsmith_base_url:"text",langsmith_sampling_rate:"number"},description:"Langsmith Logging Integration"},{id:"openmeter",displayName:"OpenMeter",logo:`${t}openmeter.png`,supports_key_team_logging:!1,dynamic_params:{openmeter_api_key:"password",openmeter_base_url:"text"},description:"OpenMeter Logging Integration"},{id:"otel",displayName:"Open Telemetry",logo:`${t}otel.png`,supports_key_team_logging:!1,dynamic_params:{otel_endpoint:"text",otel_headers:"text"},description:"OpenTelemetry Logging Integration"},{id:"s3",displayName:"S3",logo:`${t}aws.svg`,supports_key_team_logging:!1,dynamic_params:{s3_bucket_name:"text",aws_access_key_id:"password",aws_secret_access_key:"password",aws_region:"text"},description:"S3 Bucket (AWS) Logging Integration"},{id:"SQS",displayName:"SQS",logo:`${t}aws.svg`,supports_key_team_logging:!1,dynamic_params:{sqs_queue_url:"text",aws_access_key_id:"password",aws_secret_access_key:"password",aws_region:"text"},description:"SQS Queue (AWS) Logging Integration"}],a=s.reduce((e,t)=>(e[t.displayName]=t,e),{}),l=s.reduce((e,t)=>(e[t.displayName]=t.id,e),{}),r=s.reduce((e,t)=>(e[t.id]=t.displayName,e),{});e.s(["callbackInfo",0,a,"callback_map",0,l,"mapDisplayToInternalNames",0,e=>e.map(e=>l[e]||e),"mapInternalToDisplayNames",0,e=>e.map(e=>r[e]||e),"reverse_callback_map",0,r])},75921,e=>{"use strict";var t=e.i(843476),s=e.i(266027),a=e.i(243652),l=e.i(764205),r=e.i(135214);let i=(0,a.createQueryKeys)("mcpAccessGroups");var n=e.i(500727),o=e.i(199133);e.s(["default",0,({onChange:e,value:a,className:c,accessToken:d,placeholder:u="Select MCP servers",disabled:m=!1,teamId:p})=>{let{data:g=[],isLoading:h}=(0,n.useMCPServers)(p),{data:x=[],isLoading:y}=(()=>{let{accessToken:e}=(0,r.default)();return(0,s.useQuery)({queryKey:i.list({}),queryFn:async()=>await (0,l.fetchMCPAccessGroups)(e),enabled:!!e})})(),f=[...x.map(e=>({label:e,value:e,isAccessGroup:!0,searchText:`${e} Access Group`})),...g.map(e=>({label:`${e.server_name||e.server_id} (${e.server_id})`,value:e.server_id,isAccessGroup:!1,searchText:`${e.server_name||e.server_id} ${e.server_id} MCP Server`}))],_=[...a?.servers||[],...a?.accessGroups||[]];return(0,t.jsx)("div",{children:(0,t.jsx)(o.Select,{mode:"multiple",placeholder:u,onChange:t=>{e({servers:t.filter(e=>!x.includes(e)),accessGroups:t.filter(e=>x.includes(e))})},value:_,loading:h||y,className:c,allowClear:!0,showSearch:!0,style:{width:"100%"},disabled:m,filterOption:(e,t)=>(f.find(e=>e.value===t?.value)?.searchText||"").toLowerCase().includes(e.toLowerCase()),children:f.map(e=>(0,t.jsx)(o.Select.Option,{value:e.value,label:e.label,children:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[(0,t.jsx)("span",{style:{display:"inline-block",width:8,height:8,borderRadius:"50%",background:e.isAccessGroup?"#52c41a":"#1890ff",flexShrink:0}}),(0,t.jsx)("span",{style:{flex:1},children:e.label}),(0,t.jsx)("span",{style:{color:e.isAccessGroup?"#52c41a":"#1890ff",fontSize:"12px",fontWeight:500,opacity:.8},children:e.isAccessGroup?"Access Group":"MCP Server"})]})},e.value))})})}],75921)},390605,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(764205),l=e.i(599724),r=e.i(482725),i=e.i(91739),n=e.i(500727),o=e.i(531516),c=e.i(696609);e.s(["default",0,({accessToken:e,selectedServers:d,toolPermissions:u,onChange:m,disabled:p=!1})=>{let{data:g=[]}=(0,n.useMCPServers)(),[h,x]=(0,s.useState)({}),[y,f]=(0,s.useState)({}),[_,j]=(0,s.useState)({}),[b,v]=(0,s.useState)({}),w=(0,s.useRef)(u);(0,s.useEffect)(()=>{w.current=u},[u]);let N=(0,s.useMemo)(()=>0===d.length?[]:g.filter(e=>d.includes(e.server_id)),[g,d]),k=async(e,t)=>{f(t=>({...t,[e]:!0})),j(t=>({...t,[e]:""}));try{let s=await (0,a.listMCPTools)(t,e);if(s.error)j(t=>({...t,[e]:s.message||"Failed to fetch tools"})),x(t=>({...t,[e]:[]}));else{let t=s.tools||[];x(s=>({...s,[e]:t}));let a=w.current;if(!a[e]&&t.length>0){let s=t.filter(e=>"delete"!==(0,c.classifyToolOp)(e.name,e.description||"")).map(e=>e.name);m({...a,[e]:s})}}}catch(t){console.error(`Error fetching tools for server ${e}:`,t),j(t=>({...t,[e]:"Failed to fetch tools"})),x(t=>({...t,[e]:[]}))}finally{f(t=>({...t,[e]:!1}))}};(0,s.useEffect)(()=>{N.forEach(t=>{h[t.server_id]||y[t.server_id]||k(t.server_id,e)})},[N,e]);let S=(e,t)=>{m({...u,[e]:t})};return 0===d.length?null:(0,t.jsx)("div",{className:"space-y-4",children:N.map(e=>{let s=e.server_name||e.alias||e.server_id,a=h[e.server_id]||[],n=u[e.server_id]||[],c=y[e.server_id],d=_[e.server_id],g=b[e.server_id]??"crud";return(0,t.jsxs)("div",{className:"border rounded-lg bg-gray-50",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between p-4 border-b bg-white rounded-t-lg",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(l.Text,{className:"font-semibold text-gray-900",children:s}),e.description&&(0,t.jsx)(l.Text,{className:"text-sm text-gray-500",children:e.description})]}),(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[!p&&a.length>0&&(0,t.jsx)(i.Radio.Group,{value:g,onChange:t=>v(s=>({...s,[e.server_id]:t.target.value})),size:"small",optionType:"button",buttonStyle:"solid",options:[{label:"Risk Groups",value:"crud"},{label:"Flat List",value:"flat"}]}),!p&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("button",{type:"button",className:"text-sm text-blue-600 hover:text-blue-700 font-medium",onClick:()=>{var t;let s;return s=h[t=e.server_id]||[],void m({...u,[t]:s.map(e=>e.name)})},disabled:c,children:"Select All"}),(0,t.jsx)("button",{type:"button",className:"text-sm text-blue-600 hover:text-blue-700 font-medium",onClick:()=>{var t;return t=e.server_id,void m({...u,[t]:[]})},disabled:c,children:"Deselect All"})]})]})]}),(0,t.jsxs)("div",{className:"p-4",children:[c&&(0,t.jsxs)("div",{className:"flex items-center justify-center py-8",children:[(0,t.jsx)(r.Spin,{size:"large"}),(0,t.jsx)(l.Text,{className:"ml-3 text-gray-500",children:"Loading tools..."})]}),d&&!c&&(0,t.jsxs)("div",{className:"p-4 bg-red-50 border border-red-200 rounded-lg text-center",children:[(0,t.jsx)(l.Text,{className:"text-red-600 font-medium",children:"Unable to load tools"}),(0,t.jsx)(l.Text,{className:"text-sm text-red-500 mt-1",children:d})]}),!c&&!d&&a.length>0&&"crud"===g&&(0,t.jsx)(o.default,{tools:a,value:u[e.server_id]?n:void 0,onChange:t=>S(e.server_id,t),readOnly:p}),!c&&!d&&a.length>0&&"flat"===g&&(0,t.jsx)("div",{className:"space-y-2",children:a.map(s=>{let a=n.includes(s.name);return(0,t.jsxs)("div",{className:"flex items-start gap-2",children:[(0,t.jsx)("input",{type:"checkbox",checked:a,onChange:()=>{if(p)return;let t=a?n.filter(e=>e!==s.name):[...n,s.name];S(e.server_id,t)},disabled:p,className:"mt-0.5"}),(0,t.jsx)("div",{className:"flex-1 min-w-0",children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(l.Text,{className:"font-medium text-gray-900",children:s.name}),(0,t.jsxs)(l.Text,{className:"text-sm text-gray-500",children:["- ",s.description||"No description"]})]})})]},s.name)})}),!c&&!d&&0===a.length&&(0,t.jsx)("div",{className:"text-center py-6",children:(0,t.jsx)(l.Text,{className:"text-gray-500",children:"No tools available"})})]})]},e.server_id)})})}])},266484,e=>{"use strict";var t=e.i(843476),s=e.i(199133),a=e.i(592968),l=e.i(312361),r=e.i(827252),i=e.i(994388),n=e.i(304967),o=e.i(779241),c=e.i(988297),d=e.i(68155),u=e.i(810757),m=e.i(477386),p=e.i(557662),g=e.i(435451);let{Option:h}=s.Select;e.s(["default",0,({value:e=[],onChange:x,disabledCallbacks:y=[],onDisabledCallbacksChange:f})=>{let _=Object.entries(p.callbackInfo).filter(([e,t])=>t.supports_key_team_logging).map(([e,t])=>e),j=Object.keys(p.callbackInfo),b=e=>{x?.(e)},v=(t,s,a)=>{let l=[...e];if("callback_name"===s){let e=p.callback_map[a]||a;l[t]={...l[t],[s]:e,callback_vars:{}}}else l[t]={...l[t],[s]:a};b(l)},w=(t,s,a)=>{let l=[...e];l[t]={...l[t],callback_vars:{...l[t].callback_vars,[s]:a}},b(l)};return(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)(m.BanIcon,{className:"w-5 h-5 text-red-500"}),(0,t.jsx)("span",{className:"text-base font-semibold text-gray-800",children:"Disabled Callbacks"}),(0,t.jsx)(a.Tooltip,{title:"Select callbacks to disable for this key. Disabled callbacks will not receive any logging data.",children:(0,t.jsx)(r.InfoCircleOutlined,{className:"text-gray-400 cursor-help"})})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{className:"text-sm font-medium text-gray-700",children:"Disabled Callbacks"}),(0,t.jsx)(s.Select,{mode:"multiple",placeholder:"Select callbacks to disable",value:y,onChange:e=>{let t=(0,p.mapDisplayToInternalNames)(e);f?.(t)},style:{width:"100%"},optionLabelProp:"label",children:j.map(e=>{let s=p.callbackInfo[e]?.logo,l=p.callbackInfo[e]?.description;return(0,t.jsx)(h,{value:e,label:e,children:(0,t.jsx)(a.Tooltip,{title:l,placement:"right",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[s&&(0,t.jsx)("img",{src:s,alt:e,className:"w-4 h-4 object-contain",onError:t=>{let s=t.target,a=s.parentElement;if(a){let t=document.createElement("div");t.className="w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",t.textContent=e.charAt(0),a.replaceChild(t,s)}}}),(0,t.jsx)("span",{children:e})]})})},e)})}),(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"Select callbacks that should be disabled for this key. These callbacks will not receive any logging data."})]})]}),(0,t.jsx)(l.Divider,{}),(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)(u.CogIcon,{className:"w-5 h-5 text-blue-500"}),(0,t.jsx)("span",{className:"text-base font-semibold text-gray-800",children:"Logging Integrations"}),(0,t.jsx)(a.Tooltip,{title:"Configure callback logging integrations for this team.",children:(0,t.jsx)(r.InfoCircleOutlined,{className:"text-gray-400 cursor-help"})})]}),(0,t.jsx)(i.Button,{variant:"secondary",onClick:()=>{b([...e,{callback_name:"",callback_type:"success",callback_vars:{}}])},icon:c.PlusIcon,size:"sm",className:"hover:border-blue-400 hover:text-blue-500",type:"button",children:"Add Integration"})]}),(0,t.jsx)("div",{className:"space-y-4",children:e.map((l,c)=>{let u=l.callback_name?Object.entries(p.callback_map).find(([e,t])=>t===l.callback_name)?.[0]:void 0,m=u?p.callbackInfo[u]?.logo:null;return(0,t.jsxs)(n.Card,{className:"border border-gray-200 shadow-sm hover:shadow-md transition-shadow duration-200",decoration:"top",decorationColor:"blue",children:[(0,t.jsxs)("div",{className:"flex justify-between items-start mb-4",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[m&&(0,t.jsx)("img",{src:m,alt:u,className:"w-5 h-5 object-contain"}),(0,t.jsxs)("span",{className:"text-sm font-medium",children:[u||"New Integration"," Configuration"]})]}),(0,t.jsx)(i.Button,{variant:"light",onClick:()=>{b(e.filter((e,t)=>t!==c))},icon:d.TrashIcon,size:"xs",color:"red",className:"hover:bg-red-50",type:"button",children:"Remove"})]}),(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{className:"text-sm font-medium text-gray-700",children:"Integration Type"}),(0,t.jsx)(s.Select,{value:u,placeholder:"Select integration",onChange:e=>v(c,"callback_name",e),className:"w-full",optionLabelProp:"label",children:_.map(e=>{let s=p.callbackInfo[e]?.logo,l=p.callbackInfo[e]?.description;return(0,t.jsx)(h,{value:e,label:e,children:(0,t.jsx)(a.Tooltip,{title:l,placement:"right",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[s&&(0,t.jsx)("img",{src:s,alt:e,className:"w-4 h-4 object-contain",onError:t=>{let s=t.target,a=s.parentElement;if(a){let t=document.createElement("div");t.className="w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",t.textContent=e.charAt(0),a.replaceChild(t,s)}}}),(0,t.jsx)("span",{children:e})]})})},e)})})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{className:"text-sm font-medium text-gray-700",children:"Event Type"}),(0,t.jsxs)(s.Select,{value:l.callback_type,onChange:e=>v(c,"callback_type",e),className:"w-full",children:[(0,t.jsx)(h,{value:"success",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-green-500 rounded-full"}),(0,t.jsx)("span",{children:"Success Only"})]})}),(0,t.jsx)(h,{value:"failure",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-red-500 rounded-full"}),(0,t.jsx)("span",{children:"Failure Only"})]})}),(0,t.jsx)(h,{value:"success_and_failure",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)("span",{children:"Success & Failure"})]})})]})]})]}),((e,s)=>{if(!e.callback_name)return null;let l=Object.entries(p.callback_map).find(([t,s])=>s===e.callback_name)?.[0];if(!l)return null;let i=p.callbackInfo[l]?.dynamic_params||{};return 0===Object.keys(i).length?null:(0,t.jsxs)("div",{className:"mt-6 pt-4 border-t border-gray-100",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2 mb-4",children:[(0,t.jsx)("div",{className:"w-3 h-3 bg-blue-100 rounded-full flex items-center justify-center",children:(0,t.jsx)("div",{className:"w-1.5 h-1.5 bg-blue-500 rounded-full"})}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Integration Parameters"})]}),(0,t.jsx)("div",{className:"grid grid-cols-1 gap-4",children:Object.entries(i).map(([l,i])=>(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 capitalize flex items-center space-x-1",children:[(0,t.jsx)("span",{children:l.replace(/_/g," ")}),(0,t.jsx)(a.Tooltip,{title:`Environment variable reference recommended: os.environ/${l.toUpperCase()}`,children:(0,t.jsx)(r.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})}),"password"===i&&(0,t.jsx)("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-800",children:"Sensitive"}),"number"===i&&(0,t.jsx)("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-800",children:"Number"})]}),"number"===i&&(0,t.jsx)("span",{className:"text-xs text-gray-500",children:"Value must be between 0 and 1"}),"number"===i?(0,t.jsx)(g.default,{step:.01,width:400,placeholder:`os.environ/${l.toUpperCase()}`,value:e.callback_vars[l]||"",onChange:e=>w(s,l,e.target.value)}):(0,t.jsx)(o.TextInput,{type:"password"===i?"password":"text",placeholder:`os.environ/${l.toUpperCase()}`,value:e.callback_vars[l]||"",onChange:e=>w(s,l,e.target.value)})]},l))})]})})(l,c)]})]},c)})}),0===e.length&&(0,t.jsxs)("div",{className:"text-center py-12 text-gray-500 border-2 border-dashed border-gray-200 rounded-lg bg-gray-50/50",children:[(0,t.jsx)(u.CogIcon,{className:"w-12 h-12 text-gray-300 mb-3 mx-auto"}),(0,t.jsx)("div",{className:"text-base font-medium mb-1",children:"No logging integrations configured"}),(0,t.jsx)("div",{className:"text-sm text-gray-400",children:'Click "Add Integration" to configure logging for this team'})]})]})}])},207082,e=>{"use strict";var t=e.i(619273),s=e.i(266027),a=e.i(243652),l=e.i(764205),r=e.i(135214);let i=(0,a.createQueryKeys)("keys"),n=async(e,t,s,a={})=>{try{let r=(0,l.getProxyBaseUrl)(),i=new URLSearchParams(Object.entries({team_id:a.teamID,project_id:a.projectID,organization_id:a.organizationID,key_alias:a.selectedKeyAlias,key_hash:a.keyHash,user_id:a.userID,page:t,size:s,sort_by:a.sortBy,sort_order:a.sortOrder,expand:a.expand,status:a.status,return_full_object:"true",include_team_keys:"true",include_created_by_keys:"true"}).filter(([,e])=>null!=e).map(([e,t])=>[e,String(t)])),n=`${r?`${r}/key/list`:"/key/list"}?${i}`,o=await fetch(n,{method:"GET",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!o.ok){let e=await o.json(),t=(0,l.deriveErrorMessage)(e);throw(0,l.handleError)(t),Error(t)}let c=await o.json();return console.log("/key/list API Response:",c),c}catch(e){throw console.error("Failed to list keys:",e),e}},o=(0,a.createQueryKeys)("deletedKeys");e.s(["keyKeys",0,i,"useDeletedKeys",0,(e,a,l={})=>{let{accessToken:i}=(0,r.default)();return(0,s.useQuery)({queryKey:o.list({page:e,limit:a,...l}),queryFn:async()=>await n(i,e,a,{...l,status:"deleted"}),enabled:!!i,staleTime:3e4,placeholderData:t.keepPreviousData})},"useKeys",0,(e,a,l={})=>{let{accessToken:o}=(0,r.default)();return(0,s.useQuery)({queryKey:i.list({page:e,limit:a,...l}),queryFn:async()=>await n(o,e,a,l),enabled:!!o,staleTime:3e4,placeholderData:t.keepPreviousData})}])},510674,e=>{"use strict";var t=e.i(266027),s=e.i(243652),a=e.i(764205),l=e.i(708347),r=e.i(135214);let i=(0,s.createQueryKeys)("projects"),n=async e=>{let t=(0,a.getProxyBaseUrl)(),s=`${t}/project/list`,l=await fetch(s,{method:"GET",headers:{[(0,a.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!l.ok){let e=await l.json(),t=(0,a.deriveErrorMessage)(e);throw(0,a.handleError)(t),Error(t)}return l.json()};e.s(["projectKeys",0,i,"useProjects",0,()=>{let{accessToken:e,userRole:s}=(0,r.default)();return(0,t.useQuery)({queryKey:i.list({}),queryFn:async()=>n(e),enabled:!!e&&l.all_admin_roles.includes(s||"")})}])},392110,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(199133),l=e.i(592968),r=e.i(312361),i=e.i(790848),n=e.i(536916),o=e.i(827252),c=e.i(779241);let{Option:d}=a.Select;e.s(["default",0,({form:e,autoRotationEnabled:u,onAutoRotationChange:m,rotationInterval:p,onRotationIntervalChange:g,isCreateMode:h=!1,neverExpire:x=!1,onNeverExpireChange:y})=>{let f=p&&!["7d","30d","90d","180d","365d"].includes(p),[_,j]=(0,s.useState)(f),[b,v]=(0,s.useState)(f?p:""),[w,N]=(0,s.useState)(e?.getFieldValue?.("duration")||"");return(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Key Expiry Settings"}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,t.jsx)("span",{children:"Expire Key"}),(0,t.jsx)(l.Tooltip,{title:"Set when this key should expire. Format: 30s (seconds), 30m (minutes), 30h (hours), 30d (days). Leave empty to keep the current expiry unchanged.",children:(0,t.jsx)(o.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})}),!h&&y&&(0,t.jsx)(n.Checkbox,{checked:x,onChange:t=>{let s=t.target.checked;y(s),s&&(N(""),e&&"function"==typeof e.setFieldValue?e.setFieldValue("duration",""):e&&"function"==typeof e.setFieldsValue&&e.setFieldsValue({duration:""}))},className:"ml-2 text-sm font-normal text-gray-600",children:"Never Expire"})]}),(0,t.jsx)(c.TextInput,{name:"duration",placeholder:h?"e.g., 30d or leave empty to never expire":"e.g., 30d",className:"w-full",value:w,onValueChange:t=>{N(t),e&&"function"==typeof e.setFieldValue?e.setFieldValue("duration",t):e&&"function"==typeof e.setFieldsValue&&e.setFieldsValue({duration:t})},disabled:!h&&x})]})]}),(0,t.jsx)(r.Divider,{}),(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Auto-Rotation Settings"}),(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,t.jsx)("span",{children:"Enable Auto-Rotation"}),(0,t.jsx)(l.Tooltip,{title:"Key will automatically regenerate at the specified interval for enhanced security.",children:(0,t.jsx)(o.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})})]}),(0,t.jsx)(i.Switch,{checked:u,onChange:m,size:"default",className:u?"":"bg-gray-400"})]}),u&&(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,t.jsx)("span",{children:"Rotation Interval"}),(0,t.jsx)(l.Tooltip,{title:"How often the key should be automatically rotated. Choose the interval that best fits your security requirements.",children:(0,t.jsx)(o.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)(a.Select,{value:_?"custom":p,onChange:e=>{"custom"===e?j(!0):(j(!1),v(""),g(e))},className:"w-full",placeholder:"Select interval",children:[(0,t.jsx)(d,{value:"7d",children:"7 days"}),(0,t.jsx)(d,{value:"30d",children:"30 days"}),(0,t.jsx)(d,{value:"90d",children:"90 days"}),(0,t.jsx)(d,{value:"180d",children:"180 days"}),(0,t.jsx)(d,{value:"365d",children:"365 days"}),(0,t.jsx)(d,{value:"custom",children:"Custom interval"})]}),_&&(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(c.TextInput,{value:b,onChange:e=>{let t=e.target.value;v(t),g(t)},placeholder:"e.g., 1s, 5m, 2h, 14d"}),(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"Supported formats: seconds (s), minutes (m), hours (h), days (d)"})]})]})]})]}),u&&(0,t.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."})]})]})}])},939510,e=>{"use strict";var t=e.i(843476),s=e.i(808613),a=e.i(199133),l=e.i(592968),r=e.i(827252);let{Option:i}=a.Select;e.s(["default",0,({type:e,name:n,showDetailedDescriptions:o=!0,className:c="",initialValue:d=null,form:u,onChange:m})=>{let p=e.toUpperCase(),g=e.toLowerCase(),h=`Select 'guaranteed_throughput' to prevent overallocating ${p} limit when the key belongs to a Team with specific ${p} limits.`;return(0,t.jsx)(s.Form.Item,{label:(0,t.jsxs)("span",{children:[p," Rate Limit Type"," ",(0,t.jsx)(l.Tooltip,{title:h,children:(0,t.jsx)(r.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:n,initialValue:d,className:c,children:(0,t.jsx)(a.Select,{defaultValue:o?"default":void 0,placeholder:"Select rate limit type",style:{width:"100%"},optionLabelProp:o?"label":void 0,onChange:e=>{u&&u.setFieldValue(n,e),m&&m(e)},children:o?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(i,{value:"best_effort_throughput",label:"Default",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Default"}),(0,t.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["Best effort throughput - no error if we're overallocating ",g," (Team/Key Limits checked at runtime)."]})]})}),(0,t.jsx)(i,{value:"guaranteed_throughput",label:"Guaranteed throughput",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Guaranteed throughput"}),(0,t.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["Guaranteed throughput - raise an error if we're overallocating ",g," (also checks model-specific limits)"]})]})}),(0,t.jsx)(i,{value:"dynamic",label:"Dynamic",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Dynamic"}),(0,t.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["If the key has a set ",p," (e.g. 2 ",p,") and there are no 429 errors, it can dynamically exceed the limit when the model being called is not erroring."]})]})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(i,{value:"best_effort_throughput",children:"Best effort throughput"}),(0,t.jsx)(i,{value:"guaranteed_throughput",children:"Guaranteed throughput"}),(0,t.jsx)(i,{value:"dynamic",children:"Dynamic"})]})})})}])},533882,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(250980),l=e.i(797672),r=e.i(68155),i=e.i(304967),n=e.i(629569),o=e.i(599724),c=e.i(269200),d=e.i(427612),u=e.i(64848),m=e.i(942232),p=e.i(496020),g=e.i(977572),h=e.i(992619),x=e.i(727749);e.s(["default",0,({accessToken:e,initialModelAliases:y={},onAliasUpdate:f,showExampleConfig:_=!0})=>{let[j,b]=(0,s.useState)([]),[v,w]=(0,s.useState)({aliasName:"",targetModel:""}),[N,k]=(0,s.useState)(null);(0,s.useEffect)(()=>{b(Object.entries(y).map(([e,t],s)=>({id:`${s}-${e}`,aliasName:e,targetModel:t})))},[y]);let S=()=>{if(!N)return;if(!N.aliasName||!N.targetModel)return void x.default.fromBackend("Please provide both alias name and target model");if(j.some(e=>e.id!==N.id&&e.aliasName===N.aliasName))return void x.default.fromBackend("An alias with this name already exists");let e=j.map(e=>e.id===N.id?N:e);b(e),k(null);let t={};e.forEach(e=>{t[e.aliasName]=e.targetModel}),f&&f(t),x.default.success("Alias updated successfully")},C=()=>{k(null)},T=j.reduce((e,t)=>(e[t.aliasName]=t.targetModel,e),{});return(0,t.jsxs)("div",{className:"mt-4",children:[(0,t.jsxs)("div",{className:"mb-6",children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium text-gray-700 mb-2",children:"Add New Alias"}),(0,t.jsxs)("div",{className:"grid grid-cols-3 gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-xs text-gray-500 mb-1",children:"Alias Name"}),(0,t.jsx)("input",{type:"text",value:v.aliasName,onChange:e=>w({...v,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,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-xs text-gray-500 mb-1",children:"Target Model"}),(0,t.jsx)(h.default,{accessToken:e,value:v.targetModel,placeholder:"Select target model",onChange:e=>w({...v,targetModel:e}),showLabel:!1})]}),(0,t.jsx)("div",{className:"flex items-end",children:(0,t.jsxs)("button",{onClick:()=>{if(!v.aliasName||!v.targetModel)return void x.default.fromBackend("Please provide both alias name and target model");if(j.some(e=>e.aliasName===v.aliasName))return void x.default.fromBackend("An alias with this name already exists");let e=[...j,{id:`${Date.now()}-${v.aliasName}`,aliasName:v.aliasName,targetModel:v.targetModel}];b(e),w({aliasName:"",targetModel:""});let t={};e.forEach(e=>{t[e.aliasName]=e.targetModel}),f&&f(t),x.default.success("Alias added successfully")},disabled:!v.aliasName||!v.targetModel,className:`flex items-center px-4 py-2 rounded-md text-sm ${!v.aliasName||!v.targetModel?"bg-gray-300 text-gray-500 cursor-not-allowed":"bg-green-600 text-white hover:bg-green-700"}`,children:[(0,t.jsx)(a.PlusCircleIcon,{className:"w-4 h-4 mr-1"}),"Add Alias"]})})]})]}),(0,t.jsx)(o.Text,{className:"text-sm font-medium text-gray-700 mb-2",children:"Manage Existing Aliases"}),(0,t.jsx)("div",{className:"rounded-lg custom-border relative mb-6",children:(0,t.jsx)("div",{className:"overflow-x-auto",children:(0,t.jsxs)(c.Table,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,t.jsx)(d.TableHead,{children:(0,t.jsxs)(p.TableRow,{children:[(0,t.jsx)(u.TableHeaderCell,{className:"py-1 h-8",children:"Alias Name"}),(0,t.jsx)(u.TableHeaderCell,{className:"py-1 h-8",children:"Target Model"}),(0,t.jsx)(u.TableHeaderCell,{className:"py-1 h-8",children:"Actions"})]})}),(0,t.jsxs)(m.TableBody,{children:[j.map(s=>(0,t.jsx)(p.TableRow,{className:"h-8",children:N&&N.id===s.id?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(g.TableCell,{className:"py-0.5",children:(0,t.jsx)("input",{type:"text",value:N.aliasName,onChange:e=>k({...N,aliasName:e.target.value}),className:"w-full px-2 py-1 border border-gray-300 rounded-md text-sm"})}),(0,t.jsx)(g.TableCell,{className:"py-0.5",children:(0,t.jsx)(h.default,{accessToken:e,value:N.targetModel,onChange:e=>k({...N,targetModel:e}),showLabel:!1,style:{height:"32px"}})}),(0,t.jsx)(g.TableCell,{className:"py-0.5 whitespace-nowrap",children:(0,t.jsxs)("div",{className:"flex space-x-2",children:[(0,t.jsx)("button",{onClick:S,className:"text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded hover:bg-blue-100",children:"Save"}),(0,t.jsx)("button",{onClick:C,className:"text-xs bg-gray-50 text-gray-600 px-2 py-1 rounded hover:bg-gray-100",children:"Cancel"})]})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(g.TableCell,{className:"py-0.5 text-sm text-gray-900",children:s.aliasName}),(0,t.jsx)(g.TableCell,{className:"py-0.5 text-sm text-gray-500",children:s.targetModel}),(0,t.jsx)(g.TableCell,{className:"py-0.5 whitespace-nowrap",children:(0,t.jsxs)("div",{className:"flex space-x-2",children:[(0,t.jsx)("button",{onClick:()=>{k({...s})},className:"text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded hover:bg-blue-100",children:(0,t.jsx)(l.PencilIcon,{className:"w-3 h-3"})}),(0,t.jsx)("button",{onClick:()=>{var e;let t,a;return e=s.id,b(t=j.filter(t=>t.id!==e)),a={},void(t.forEach(e=>{a[e.aliasName]=e.targetModel}),f&&f(a),x.default.success("Alias deleted successfully"))},className:"text-xs bg-red-50 text-red-600 px-2 py-1 rounded hover:bg-red-100",children:(0,t.jsx)(r.TrashIcon,{className:"w-3 h-3"})})]})})]})},s.id)),0===j.length&&(0,t.jsx)(p.TableRow,{children:(0,t.jsx)(g.TableCell,{colSpan:3,className:"py-0.5 text-sm text-gray-500 text-center",children:"No aliases added yet. Add a new alias above."})})]})]})})}),_&&(0,t.jsxs)(i.Card,{children:[(0,t.jsx)(n.Title,{className:"mb-4",children:"Configuration Example"}),(0,t.jsx)(o.Text,{className:"text-gray-600 mb-4",children:"Here's how your current aliases would look in the config:"}),(0,t.jsx)("div",{className:"bg-gray-100 rounded-lg p-4 font-mono text-sm",children:(0,t.jsxs)("div",{className:"text-gray-700",children:["model_aliases:",0===Object.keys(T).length?(0,t.jsxs)("span",{className:"text-gray-500",children:[(0,t.jsx)("br",{}),"  # No aliases configured yet"]}):Object.entries(T).map(([e,s])=>(0,t.jsxs)("span",{children:[(0,t.jsx)("br",{}),'  "',e,'": "',s,'"']},e))]})})]})]})}])},651904,e=>{"use strict";var t=e.i(843476),s=e.i(599724),a=e.i(266484);e.s(["default",0,function({value:e,onChange:l,premiumUser:r=!1,disabledCallbacks:i=[],onDisabledCallbacksChange:n}){return r?(0,t.jsx)(a.default,{value:e,onChange:l,disabledCallbacks:i,onDisabledCallbacksChange:n}):(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex flex-wrap gap-2 mb-3",children:[(0,t.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,t.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,t.jsx)("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-lg",children:(0,t.jsxs)(s.Text,{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,t.jsx)("a",{href:"https://www.litellm.ai/#pricing",target:"_blank",rel:"noopener noreferrer",className:"underline",children:"here"}),"."]})})]})}])},460285,575260,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(404206),l=e.i(723731),r=e.i(653824),i=e.i(881073),n=e.i(197647),o=e.i(764205),c=e.i(158392),d=e.i(419470),u=e.i(689020);let m=(0,s.forwardRef)(({accessToken:e,value:m,onChange:p,modelData:g},h)=>{let[x,y]=(0,s.useState)({routerSettings:{},selectedStrategy:null,enableTagFiltering:!1}),[f,_]=(0,s.useState)([]),[j,b]=(0,s.useState)([]),[v,w]=(0,s.useState)([]),[N,k]=(0,s.useState)([]),[S,C]=(0,s.useState)({}),[T,I]=(0,s.useState)({}),A=(0,s.useRef)(!1),L=(0,s.useRef)(null);(0,s.useEffect)(()=>{let e=m?.router_settings?JSON.stringify({routing_strategy:m.router_settings.routing_strategy,fallbacks:m.router_settings.fallbacks,enable_tag_filtering:m.router_settings.enable_tag_filtering}):null;if(A.current&&e===L.current){A.current=!1;return}if(A.current&&e!==L.current&&(A.current=!1),e!==L.current)if(L.current=e,m?.router_settings){let e=m.router_settings,{fallbacks:t,...s}=e;y({routerSettings:s,selectedStrategy:e.routing_strategy||null,enableTagFiltering:e.enable_tag_filtering??!1});let a=e.fallbacks||[];_(a),b(a&&0!==a.length?a.map((e,t)=>{let[s,a]=Object.entries(e)[0];return{id:(t+1).toString(),primaryModel:s||null,fallbackModels:a||[]}}):[{id:"1",primaryModel:null,fallbackModels:[]}])}else y({routerSettings:{},selectedStrategy:null,enableTagFiltering:!1}),_([]),b([{id:"1",primaryModel:null,fallbackModels:[]}])},[m]),(0,s.useEffect)(()=>{e&&(0,o.getRouterSettingsCall)(e).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}}),C(t);let s=e.fields.find(e=>"routing_strategy"===e.field_name);s?.options&&k(s.options),e.routing_strategy_descriptions&&I(e.routing_strategy_descriptions)}})},[e]),(0,s.useEffect)(()=>{e&&(async()=>{try{let t=await (0,u.fetchAvailableModels)(e);w(t)}catch(e){console.error("Error fetching model info for fallbacks:",e)}})()},[e]);let F=()=>{let e=new Set(["allowed_fails","cooldown_time","num_retries","timeout","retry_after"]),t=new Set(["model_group_alias","retry_policy"]),s=Object.fromEntries(Object.entries({...x.routerSettings,enable_tag_filtering:x.enableTagFiltering,routing_strategy:x.selectedStrategy,fallbacks:f.length>0?f:null}).map(([s,a])=>{if("routing_strategy_args"!==s&&"routing_strategy"!==s&&"enable_tag_filtering"!==s&&"fallbacks"!==s){let l=document.querySelector(`input[name="${s}"]`);if(l&&void 0!==l.value&&""!==l.value){let r=((s,a,l)=>{if(null==a)return l;let r=String(a).trim();if(""===r||"null"===r.toLowerCase())return null;if(e.has(s)){let e=Number(r);return Number.isNaN(e)?l:e}if(t.has(s)){if(""===r)return null;try{return JSON.parse(r)}catch{return l}}return"true"===r.toLowerCase()||"false"!==r.toLowerCase()&&r})(s,l.value,a);return[s,r]}}else if("routing_strategy"===s)return[s,x.selectedStrategy];else if("enable_tag_filtering"===s)return[s,x.enableTagFiltering];else if("fallbacks"===s)return[s,f.length>0?f:null];else if("routing_strategy_args"===s&&"latency-based-routing"===x.selectedStrategy){let e=document.querySelector('input[name="lowest_latency_buffer"]'),t=document.querySelector('input[name="ttl"]'),s={};return e?.value&&(s.lowest_latency_buffer=Number(e.value)),t?.value&&(s.ttl=Number(t.value)),["routing_strategy_args",Object.keys(s).length>0?s:null]}return[s,a]}).filter(e=>null!=e)),a=(e,t=!1)=>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:f.length>0?f: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:x.enableTagFiltering,routing_strategy_args:a(s.routing_strategy_args)}};(0,s.useEffect)(()=>{if(!p)return;let e=setTimeout(()=>{A.current=!0,p({router_settings:F()})},100);return()=>clearTimeout(e)},[x,f]);let M=Array.from(new Set(v.map(e=>e.model_group))).sort();return((0,s.useImperativeHandle)(h,()=>({getValue:()=>({router_settings:F()})})),e)?(0,t.jsx)("div",{className:"w-full",children:(0,t.jsxs)(r.TabGroup,{className:"w-full",children:[(0,t.jsxs)(i.TabList,{variant:"line",defaultValue:"1",className:"px-8 pt-4",children:[(0,t.jsx)(n.Tab,{value:"1",children:"Loadbalancing"}),(0,t.jsx)(n.Tab,{value:"2",children:"Fallbacks"})]}),(0,t.jsxs)(l.TabPanels,{className:"px-8 py-6",children:[(0,t.jsx)(a.TabPanel,{children:(0,t.jsx)(c.default,{value:x,onChange:y,routerFieldsMetadata:S,availableRoutingStrategies:N,routingStrategyDescriptions:T})}),(0,t.jsx)(a.TabPanel,{children:(0,t.jsx)(d.FallbackSelectionForm,{groups:j,onGroupsChange:e=>{b(e),_(e.filter(e=>e.primaryModel&&e.fallbackModels.length>0).map(e=>({[e.primaryModel]:e.fallbackModels})))},availableModels:M,maxGroups:5})})]})]})}):null});m.displayName="RouterSettingsAccordion",e.s(["default",0,m],460285);var p=e.i(199133),g=e.i(482725),h=e.i(56456);e.s(["default",0,({projects:e,value:s,onChange:a,disabled:l,loading:r,teamId:i})=>{let n=i?e?.filter(e=>e.team_id===i):e;return(0,t.jsx)(p.Select,{showSearch:!0,placeholder:"Search or select a project",value:s,onChange:a,disabled:l,loading:r,allowClear:!0,notFoundContent:r?(0,t.jsx)(g.Spin,{indicator:(0,t.jsx)(h.LoadingOutlined,{spin:!0}),size:"small"}):void 0,filterOption:(e,t)=>{if(!t)return!1;let s=n?.find(e=>e.project_id===t.key);if(!s)return!1;let a=e.toLowerCase().trim(),l=(s.project_alias||"").toLowerCase(),r=(s.project_id||"").toLowerCase();return l.includes(a)||r.includes(a)},optionFilterProp:"children",children:!r&&n?.map(e=>(0,t.jsxs)(p.Select.Option,{value:e.project_id,children:[(0,t.jsx)("span",{className:"font-medium",children:e.project_alias||e.project_id})," ",(0,t.jsxs)("span",{className:"text-gray-500",children:["(",e.project_id,")"]})]},e.project_id))})}],575260)},702597,364769,e=>{"use strict";var t=e.i(843476),s=e.i(207082),a=e.i(510674),l=e.i(292639),r=e.i(135214),i=e.i(500330),n=e.i(827252),o=e.i(912598),c=e.i(677667),d=e.i(130643),u=e.i(898667),m=e.i(994388),p=e.i(309426),g=e.i(350967),h=e.i(599724),x=e.i(779241),y=e.i(629569),f=e.i(464571),_=e.i(808613),j=e.i(311451),b=e.i(212931),v=e.i(91739),w=e.i(199133),N=e.i(790848),k=e.i(262218),S=e.i(592968),C=e.i(374009),T=e.i(271645),I=e.i(708347),A=e.i(552130),L=e.i(557662),F=e.i(9314),M=e.i(860585),O=e.i(82946),P=e.i(392110),E=e.i(533882),$=e.i(844565),V=e.i(651904),B=e.i(939510),G=e.i(460285),R=e.i(663435),D=e.i(575260),K=e.i(371455),U=e.i(355619),q=e.i(75921),z=e.i(390605),W=e.i(727749),H=e.i(764205),Q=e.i(237016),J=e.i(998573);let Y=({apiKey:e})=>{let[s,a]=(0,T.useState)(!1);return(0,t.jsxs)("div",{children:[(0,t.jsxs)("p",{className:"mb-2",children:["Please save this secret key somewhere safe and accessible. For security reasons,"," ",(0,t.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,t.jsx)("p",{className:"text-sm text-gray-600 mt-3 mb-1",children:"Virtual Key:"}),(0,t.jsx)("div",{style:{background:"#f8f8f8",padding:"10px",borderRadius:"5px",marginBottom:"10px"},children:(0,t.jsx)("pre",{style:{wordWrap:"break-word",whiteSpace:"normal",margin:0},children:e})}),(0,t.jsx)(Q.CopyToClipboard,{text:e,onCopy:()=>{a(!0),J.message.success("Key copied to clipboard"),setTimeout(()=>a(!1),2e3)},children:(0,t.jsx)(f.Button,{type:"primary",style:{marginTop:12},children:s?"Copied!":"Copy Virtual Key"})})]})};e.s(["default",0,Y],364769);var X=e.i(435451),Z=e.i(916940);let{Option:ee}=w.Select,et=async(e,t,s,a)=>{try{if(null===e||null===t)return[];if(null!==s){let l=(await (0,H.modelAvailableCall)(s,e,t,!0,a,!0)).data.map(e=>e.id);return console.log("available_model_names:",l),l}return[]}catch(e){return console.error("Error fetching user models:",e),[]}},es=async(e,t,s,a)=>{try{if(null===e||null===t)return;if(null!==s){let l=(await (0,H.modelAvailableCall)(s,e,t)).data.map(e=>e.id);console.log("available_model_names:",l),a(l)}}catch(e){console.error("Error fetching user models:",e)}};e.s(["default",0,({team:e,teams:Q,data:J,addKey:ea,autoOpenCreate:el,prefillData:er})=>{let{accessToken:ei,userId:en,userRole:eo,premiumUser:ec}=(0,r.default)(),ed=ec||null!=eo&&I.rolesWithWriteAccess.includes(eo),{data:eu,isLoading:em}=(0,a.useProjects)(),{data:ep}=(0,l.useUISettings)(),eg=!!ep?.values?.enable_projects_ui,eh=(0,o.useQueryClient)(),[ex]=_.Form.useForm(),[ey,ef]=(0,T.useState)(!1),[e_,ej]=(0,T.useState)(null),[eb,ev]=(0,T.useState)(null),[ew,eN]=(0,T.useState)([]),[ek,eS]=(0,T.useState)([]),[eC,eT]=(0,T.useState)("you"),[eI,eA]=(0,T.useState)((e=>{let t=[];if(console.log("data:",JSON.stringify(e)),e)for(let s of e)s.metadata&&s.metadata.tags&&t.push(...s.metadata.tags);let s=Array.from(new Set(t)).map(e=>({value:e,label:e}));return console.log("uniqueTags:",s),s})(J)),[eL,eF]=(0,T.useState)(!1),[eM,eO]=(0,T.useState)(null),[eP,eE]=(0,T.useState)([]),[e$,eV]=(0,T.useState)([]),[eB,eG]=(0,T.useState)([]),[eR,eD]=(0,T.useState)([]),[eK,eU]=(0,T.useState)(e),[eq,ez]=(0,T.useState)(null),[eW,eH]=(0,T.useState)(!1),[eQ,eJ]=(0,T.useState)(null),[eY,eX]=(0,T.useState)({}),[eZ,e0]=(0,T.useState)([]),[e1,e2]=(0,T.useState)(!1),[e4,e5]=(0,T.useState)([]),[e3,e6]=(0,T.useState)([]),[e7,e9]=(0,T.useState)("llm_api"),[e8,te]=(0,T.useState)({}),[tt,ts]=(0,T.useState)(!1),[ta,tl]=(0,T.useState)("30d"),[tr,ti]=(0,T.useState)(null),[tn,to]=(0,T.useState)(0),[tc,td]=(0,T.useState)([]),[tu,tm]=(0,T.useState)(null),tp=()=>{ef(!1),ex.resetFields(),eD([]),e6([]),e9("llm_api"),te({}),ts(!1),tl("30d"),ti(null),to(e=>e+1),tm(null),ez(null)},tg=()=>{ef(!1),ej(null),eU(null),ex.resetFields(),eD([]),e6([]),e9("llm_api"),te({}),ts(!1),tl("30d"),ti(null),to(e=>e+1),tm(null),ez(null)};(0,T.useEffect)(()=>{en&&eo&&ei&&es(en,eo,ei,eN)},[ei,en,eo]),(0,T.useEffect)(()=>{ei&&(0,H.getAgentsList)(ei).then(e=>td(e?.agents||[])).catch(()=>td([]))},[ei]),(0,T.useEffect)(()=>{let e=async()=>{try{let e=(await (0,H.getPoliciesList)(ei)).policies.map(e=>e.policy_name);eV(e)}catch(e){console.error("Failed to fetch policies:",e)}},t=async()=>{try{let e=await (0,H.getPromptsList)(ei);eG(e.prompts.map(e=>e.prompt_id))}catch(e){console.error("Failed to fetch prompts:",e)}};(async()=>{try{let e=(await (0,H.getGuardrailsList)(ei)).guardrails.map(e=>e.guardrail_name);eE(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})(),e(),t()},[ei]),(0,T.useEffect)(()=>{(async()=>{try{if(ei){let e=sessionStorage.getItem("possibleUserRoles");if(e)eX(JSON.parse(e));else{let e=await (0,H.getPossibleUserRoles)(ei);sessionStorage.setItem("possibleUserRoles",JSON.stringify(e)),eX(e)}}}catch(e){console.error("Error fetching possible user roles:",e)}})()},[ei]),(0,T.useEffect)(()=>{if(el&&!eL&&Q&&eo&&I.rolesWithWriteAccess.includes(eo)&&(ef(!0),eF(!0),er)){if(er.owned_by&&("another_user"===er.owned_by&&"Admin"!==eo?eT("you"):eT(er.owned_by)),er.team_id){let e=Q?.find(e=>e.team_id===er.team_id)||null;e&&(eU(e),ex.setFieldsValue({team_id:er.team_id}))}er.key_alias&&ex.setFieldsValue({key_alias:er.key_alias}),er.models&&er.models.length>0&&eO(er.models),er.key_type&&(e9(er.key_type),ex.setFieldsValue({key_type:er.key_type}))}},[el,er,Q,eL,ex,eo]);let th=ek.includes("no-default-models")&&!eK,tx=async e=>{try{let t,a=e?.key_alias??"",l=e?.team_id??null;if((J?.filter(e=>e.team_id===l).map(e=>e.key_alias)??[]).includes(a))throw Error(`Key alias ${a} already exists for team with ID ${l}, please provide another key alias`);if(W.default.info("Making API Call"),ef(!0),"you"===eC)e.user_id=en;else if("agent"===eC){if(!tu)return void W.default.fromBackend("Please select an agent");e.agent_id=tu}let r={};try{r=JSON.parse(e.metadata||"{}")}catch(e){console.error("Error parsing metadata:",e)}if("service_account"===eC&&(r.service_account_id=e.key_alias),eR.length>0&&(r={...r,logging:eR.filter(e=>e.callback_name)}),e3.length>0){let e=(0,L.mapDisplayToInternalNames)(e3);r={...r,litellm_disabled_callbacks:e}}if(tt&&(e.auto_rotate=!0,e.rotation_interval=ta),e.duration&&""!==e.duration.trim()||(e.duration=null),e.metadata=JSON.stringify(r),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&&(e.allowed_mcp_servers_and_groups.servers?.length>0||e.allowed_mcp_servers_and_groups.accessGroups?.length>0)){e.object_permission||(e.object_permission={});let{servers:t,accessGroups:s}=e.allowed_mcp_servers_and_groups;t&&t.length>0&&(e.object_permission.mcp_servers=t),s&&s.length>0&&(e.object_permission.mcp_access_groups=s),delete e.allowed_mcp_servers_and_groups}let i=e.mcp_tool_permissions||{};if(Object.keys(i).length>0&&(e.object_permission||(e.object_permission={}),e.object_permission.mcp_tool_permissions=i),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&&(e.allowed_agents_and_groups.agents?.length>0||e.allowed_agents_and_groups.accessGroups?.length>0)){e.object_permission||(e.object_permission={});let{agents:t,accessGroups:s}=e.allowed_agents_and_groups;t&&t.length>0&&(e.object_permission.agents=t),s&&s.length>0&&(e.object_permission.agent_access_groups=s),delete e.allowed_agents_and_groups}Object.keys(e8).length>0&&(e.aliases=JSON.stringify(e8)),tr?.router_settings&&Object.values(tr.router_settings).some(e=>null!=e&&""!==e)&&(e.router_settings=tr.router_settings),t="service_account"===eC?await (0,H.keyCreateServiceAccountCall)(ei,e):await (0,H.keyCreateCall)(ei,en,e),console.log("key create Response:",t),ea(t),eh.invalidateQueries({queryKey:s.keyKeys.lists()}),ej(t.key),ev(t.soft_budget),W.default.success("Virtual Key Created"),ex.resetFields(),localStorage.removeItem("userData"+en)}catch(t){console.log("error in create key:",t);let e=(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: ${e}`;let s=t;try{if(!e||"object"!=typeof e||e instanceof Error){let e=t.match(/\{[\s\S]*\}/);if(e){let t=JSON.parse(e[0]),a=t?.error||t;a?.message&&(s=a.message)}}else{let t=e?.error||e;t?.message&&(s=t.message)}}catch(e){}return t.includes("team_member_permission_error")||s.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: ${e}`})(t);W.default.fromBackend(e)}};(0,T.useEffect)(()=>{if(eq){let e=eu?.find(e=>e.project_id===eq);eS(e?.models??[]),ex.setFieldValue("models",[]);return}en&&eo&&ei&&et(en,eo,ei,eK?.team_id??null).then(e=>{eS(Array.from(new Set([...eK?.models??[],...e])))}),eM||ex.setFieldValue("models",[]),ex.setFieldValue("allowed_mcp_servers_and_groups",{servers:[],accessGroups:[]})},[eK,eq,ei,en,eo,ex]),(0,T.useEffect)(()=>{if(!eM||0===eM.length||!ek||0===ek.length)return;let e=eM.filter(e=>ek.includes(e));e.length>0&&ex.setFieldsValue({models:e}),eO(null)},[eM,ek,ex]),(0,T.useEffect)(()=>{if(!eq||!Q)return;let e=eu?.find(e=>e.project_id===eq);if(!e?.team_id||eK?.team_id===e.team_id)return;let t=Q.find(t=>t.team_id===e.team_id)||null;t&&(eU(t),ex.setFieldValue("team_id",t.team_id))},[Q,eq,eu]);let ty=async e=>{if(!e)return void e0([]);e2(!0);try{let t=new URLSearchParams;if(t.append("user_email",e),null==ei)return;let s=(await (0,H.userFilterUICall)(ei,t)).map(e=>({label:`${e.user_email} (${e.user_id})`,value:e.user_id,user:e}));e0(s)}catch(e){console.error("Error fetching users:",e),W.default.fromBackend("Failed to search for users")}finally{e2(!1)}},tf=(0,T.useCallback)((0,C.default)(e=>ty(e),300),[ei]);return(0,t.jsxs)("div",{children:[eo&&I.rolesWithWriteAccess.includes(eo)&&(0,t.jsx)(m.Button,{className:"mx-auto",onClick:()=>ef(!0),children:"+ Create New Key"}),(0,t.jsx)(b.Modal,{open:ey,width:1e3,footer:null,onOk:tp,onCancel:tg,children:(0,t.jsxs)(_.Form,{form:ex,onFinish:tx,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,t.jsxs)("div",{className:"mb-8",children:[(0,t.jsx)(y.Title,{className:"mb-4",children:"Key Ownership"}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Owned By"," ",(0,t.jsx)(S.Tooltip,{title:"Select who will own this Virtual Key",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),className:"mb-4",children:(0,t.jsxs)(v.Radio.Group,{onChange:e=>eT(e.target.value),value:eC,children:[(0,t.jsx)(v.Radio,{value:"you",children:"You"}),(0,t.jsx)(v.Radio,{value:"service_account",children:"Service Account"}),"Admin"===eo&&(0,t.jsx)(v.Radio,{value:"another_user",children:"Another User"}),(0,t.jsxs)(v.Radio,{value:"agent",children:["Agent ",(0,t.jsx)(k.Tag,{color:"purple",children:"New"})]})]})}),"another_user"===eC&&(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["User ID"," ",(0,t.jsx)(S.Tooltip,{title:"The user who will own this key and be responsible for its usage",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"user_id",className:"mt-4",rules:[{required:"another_user"===eC,message:"Please input the user ID of the user you are assigning the key to"}],children:(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{style:{display:"flex",marginBottom:"8px"},children:[(0,t.jsx)(w.Select,{showSearch:!0,placeholder:"Type email to search for users",filterOption:!1,onSearch:e=>{tf(e)},onSelect:(e,t)=>{let s;return s=t.user,void ex.setFieldsValue({user_id:s.user_id})},options:eZ,loading:e1,allowClear:!0,style:{width:"100%"},notFoundContent:e1?"Searching...":"No users found"}),(0,t.jsx)(f.Button,{onClick:()=>eH(!0),style:{marginLeft:"8px"},children:"Create User"})]}),(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"Search by email to find users"})]})}),"agent"===eC&&(0,t.jsxs)("div",{className:"mt-4 p-4 bg-purple-50 border border-purple-200 rounded-md",children:[(0,t.jsx)("div",{className:"mb-3",children:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700",children:["Select Agent ",(0,t.jsx)("span",{className:"text-red-500",children:"*"})]})}),(0,t.jsx)(w.Select,{showSearch:!0,placeholder:"Select an agent",style:{width:"100%"},value:tu,onChange:e=>tm(e),filterOption:(e,t)=>t?.label?.toLowerCase().includes(e.toLowerCase()),options:tc.map(e=>({label:e.agent_name||e.agent_id,value:e.agent_id}))}),(0,t.jsx)("div",{className:"text-xs text-gray-500 mt-2",children:"This key will be used by the selected agent to make requests to LiteLLM"})]}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Team"," ",(0,t.jsx)(S.Tooltip,{title:"The team this key belongs to, which determines available models and budget limits",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"team_id",initialValue:e?e.team_id:null,className:"mt-4",rules:[{required:"service_account"===eC,message:"Please select a team for the service account"}],help:"service_account"===eC?"required":"",children:(0,t.jsx)(R.default,{teams:Q,disabled:null!==eq,loading:!Q,onChange:e=>{eU(Q?.find(t=>t.team_id===e)||null),ez(null),ex.setFieldValue("project_id",void 0)}})}),eg&&(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Project"," ",(0,t.jsx)(S.Tooltip,{title:"Assign this key to a project. Selecting a project will lock the team to the project's team.",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"project_id",className:"mt-4",children:(0,t.jsx)(D.default,{projects:eu,teamId:eK?.team_id,loading:em||!Q,onChange:e=>{if(!e){ez(null),eU(null),ex.setFieldValue("team_id",void 0);return}ez(e)}})})]}),th&&(0,t.jsx)("div",{className:"mb-8 p-4 bg-blue-50 border border-blue-200 rounded-md",children:(0,t.jsx)(h.Text,{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."})}),!th&&(0,t.jsxs)("div",{className:"mb-8",children:[(0,t.jsx)(y.Title,{className:"mb-4",children:"Key Details"}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["you"===eC||"another_user"===eC?"Key Name":"Service Account ID"," ",(0,t.jsx)(S.Tooltip,{title:"you"===eC||"another_user"===eC?"A descriptive name to identify this key":"Unique identifier for this service account",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"key_alias",rules:[{required:!0,message:`Please input a ${"you"===eC?"key name":"service account ID"}`}],help:"required",children:(0,t.jsx)(x.TextInput,{placeholder:""})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Models"," ",(0,t.jsx)(S.Tooltip,{title:"Select which models this key can access. Choose 'All Team Models' to grant access to all models available to the team. Leave empty to allow access to all models.",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"models",rules:[],help:"management"===e7||"read_only"===e7?"Models field is disabled for this key type":"optional - leave empty to allow access to all models",className:"mt-4",children:(0,t.jsxs)(w.Select,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},disabled:"management"===e7||"read_only"===e7,onChange:e=>{e.includes("all-team-models")&&ex.setFieldsValue({models:["all-team-models"]})},children:[!eq&&(0,t.jsx)(ee,{value:"all-team-models",children:"All Team Models"},"all-team-models"),ek.map(e=>(0,t.jsx)(ee,{value:e,children:(0,U.getModelDisplayName)(e)},e))]})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Key Type"," ",(0,t.jsx)(S.Tooltip,{title:"Select the type of key to determine what routes and operations this key can access",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"key_type",initialValue:"llm_api",className:"mt-4",children:(0,t.jsxs)(w.Select,{defaultValue:"llm_api",placeholder:"Select key type",style:{width:"100%"},optionLabelProp:"label",onChange:e=>{e9(e),("management"===e||"read_only"===e)&&ex.setFieldsValue({models:[]})},children:[(0,t.jsx)(ee,{value:"default",label:"Default",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Default"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call AI APIs + Management routes"})]})}),(0,t.jsx)(ee,{value:"llm_api",label:"AI APIs",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"AI APIs"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call only AI API routes (chat/completions, embeddings, etc.)"})]})}),(0,t.jsx)(ee,{value:"management",label:"Management",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Management"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call only management routes (user/team/key management)"})]})})]})})]}),!th&&(0,t.jsx)("div",{className:"mb-8",children:(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)(y.Title,{className:"m-0",children:"Optional Settings"})}),(0,t.jsxs)(d.AccordionBody,{children:[(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Max Budget (USD)"," ",(0,t.jsx)(S.Tooltip,{title:"Maximum amount in USD this key can spend. When reached, the key will be blocked from making further requests",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"max_budget",help:`Budget cannot exceed team max budget: $${e?.max_budget!==null&&e?.max_budget!==void 0?e?.max_budget:"unlimited"}`,rules:[{validator:async(t,s)=>{if(s&&e&&null!==e.max_budget&&s>e.max_budget)throw Error(`Budget cannot exceed team max budget: $${(0,i.formatNumberWithCommas)(e.max_budget,4)}`)}}],children:(0,t.jsx)(X.default,{step:.01,precision:2,width:200})}),(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Reset Budget"," ",(0,t.jsx)(S.Tooltip,{title:"How often the budget should reset. For example, setting 'daily' will reset the budget every 24 hours",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"budget_duration",help:`Team Reset Budget: ${e?.budget_duration!==null&&e?.budget_duration!==void 0?e?.budget_duration:"None"}`,children:(0,t.jsx)(M.default,{onChange:e=>ex.setFieldValue("budget_duration",e)})}),(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Tokens per minute Limit (TPM)"," ",(0,t.jsx)(S.Tooltip,{title:"Maximum number of tokens this key can process per minute. Helps control usage and costs",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"tpm_limit",help:`TPM cannot exceed team TPM limit: ${e?.tpm_limit!==null&&e?.tpm_limit!==void 0?e?.tpm_limit:"unlimited"}`,rules:[{validator:async(t,s)=>{if(s&&e&&null!==e.tpm_limit&&s>e.tpm_limit)throw Error(`TPM limit cannot exceed team TPM limit: ${e.tpm_limit}`)}}],children:(0,t.jsx)(X.default,{step:1,width:400})}),(0,t.jsx)(B.default,{type:"tpm",name:"tpm_limit_type",className:"mt-4",initialValue:null,form:ex,showDetailedDescriptions:!0}),(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Requests per minute Limit (RPM)"," ",(0,t.jsx)(S.Tooltip,{title:"Maximum number of API requests this key can make per minute. Helps prevent abuse and manage load",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"rpm_limit",help:`RPM cannot exceed team RPM limit: ${e?.rpm_limit!==null&&e?.rpm_limit!==void 0?e?.rpm_limit:"unlimited"}`,rules:[{validator:async(t,s)=>{if(s&&e&&null!==e.rpm_limit&&s>e.rpm_limit)throw Error(`RPM limit cannot exceed team RPM limit: ${e.rpm_limit}`)}}],children:(0,t.jsx)(X.default,{step:1,width:400})}),(0,t.jsx)(B.default,{type:"rpm",name:"rpm_limit_type",className:"mt-4",initialValue:null,form:ex,showDetailedDescriptions:!0}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Guardrails"," ",(0,t.jsx)(S.Tooltip,{title:"Apply safety guardrails to this key to filter content or enforce policies",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",className:"mt-4",help:ed?"Select existing guardrails or enter new ones":"Premium feature - Upgrade to set guardrails by key",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},disabled:!ed,placeholder:ed?"Select or enter guardrails":"Premium feature - Upgrade to set guardrails by key",options:eP.map(e=>({value:e,label:e}))})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Disable Global Guardrails"," ",(0,t.jsx)(S.Tooltip,{title:"When enabled, this key will bypass any guardrails configured to run on every request (global guardrails)",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"disable_global_guardrails",className:"mt-4",valuePropName:"checked",help:ed?"Bypass global guardrails for this key":"Premium feature - Upgrade to disable global guardrails by key",children:(0,t.jsx)(N.Switch,{disabled:!ed,checkedChildren:"Yes",unCheckedChildren:"No"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Policies"," ",(0,t.jsx)(S.Tooltip,{title:"Apply policies to this key to control guardrails and other settings",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/guardrail_policies",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"policies",className:"mt-4",help:ec?"Select existing policies or enter new ones":"Premium feature - Upgrade to set policies by key",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},disabled:!ec,placeholder:ec?"Select or enter policies":"Premium feature - Upgrade to set policies by key",options:e$.map(e=>({value:e,label:e}))})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Prompts"," ",(0,t.jsx)(S.Tooltip,{title:"Allow this key to use specific prompt templates",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/prompt_management",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"prompts",className:"mt-4",help:ec?"Select existing prompts or enter new ones":"Premium feature - Upgrade to set prompts by key",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},disabled:!ec,placeholder:ec?"Select or enter prompts":"Premium feature - Upgrade to set prompts by key",options:eB.map(e=>({value:e,label:e}))})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Access Groups"," ",(0,t.jsx)(S.Tooltip,{title:"Assign access groups to this key. Access groups control which models, MCP servers, and agents this key can use",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"access_group_ids",className:"mt-4",help:"Select access groups to assign to this key",children:(0,t.jsx)(F.default,{placeholder:"Select access groups (optional)"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Pass Through Routes"," ",(0,t.jsx)(S.Tooltip,{title:"Allow this key to use specific pass through routes",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/pass_through",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"allowed_passthrough_routes",className:"mt-4",help:ec?"Select existing pass through routes or enter new ones":"Premium feature - Upgrade to set pass through routes by key",children:(0,t.jsx)($.default,{onChange:e=>ex.setFieldValue("allowed_passthrough_routes",e),value:ex.getFieldValue("allowed_passthrough_routes"),accessToken:ei,placeholder:ec?"Select or enter pass through routes":"Premium feature - Upgrade to set pass through routes by key",disabled:!ec,teamId:eK?eK.team_id:null})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Vector Stores"," ",(0,t.jsx)(S.Tooltip,{title:"Select which vector stores this key can access. If none selected, the key will have access to all available vector stores",children:(0,t.jsx)(n.InfoCircleOutlined,{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,t.jsx)(Z.default,{onChange:e=>ex.setFieldValue("allowed_vector_store_ids",e),value:ex.getFieldValue("allowed_vector_store_ids"),accessToken:ei,placeholder:"Select vector stores (optional)"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Metadata"," ",(0,t.jsx)(S.Tooltip,{title:"JSON object with additional information about this key. Used for tracking or custom logic",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"metadata",className:"mt-4",children:(0,t.jsx)(j.Input.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Tags"," ",(0,t.jsx)(S.Tooltip,{title:"Tags for tracking spend and/or doing tag-based routing. Used for analytics and filtering",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"tags",className:"mt-4",help:"Tags for tracking spend and/or doing tag-based routing.",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},placeholder:"Enter tags",tokenSeparators:[","],options:eI})}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"MCP Settings"})}),(0,t.jsxs)(d.AccordionBody,{children:[(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed MCP Servers"," ",(0,t.jsx)(S.Tooltip,{title:"Select which MCP servers or access groups this key can access",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_mcp_servers_and_groups",help:"Select MCP servers or access groups this key can access",children:(0,t.jsx)(q.default,{onChange:e=>ex.setFieldValue("allowed_mcp_servers_and_groups",e),value:ex.getFieldValue("allowed_mcp_servers_and_groups"),accessToken:ei,teamId:eK?.team_id??null,placeholder:"Select MCP servers or access groups (optional)"})}),(0,t.jsx)(_.Form.Item,{name:"mcp_tool_permissions",initialValue:{},hidden:!0,children:(0,t.jsx)(j.Input,{type:"hidden"})}),(0,t.jsx)(_.Form.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:()=>(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(z.default,{accessToken:ei,selectedServers:ex.getFieldValue("allowed_mcp_servers_and_groups")?.servers||[],toolPermissions:ex.getFieldValue("mcp_tool_permissions")||{},onChange:e=>ex.setFieldsValue({mcp_tool_permissions:e})})})})]})]}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Agent Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Agents"," ",(0,t.jsx)(S.Tooltip,{title:"Select which agents or access groups this key can access",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_agents_and_groups",help:"Select agents or access groups this key can access",children:(0,t.jsx)(A.default,{onChange:e=>ex.setFieldValue("allowed_agents_and_groups",e),value:ex.getFieldValue("allowed_agents_and_groups"),accessToken:ei,placeholder:"Select agents or access groups (optional)"})})})]}),ec?(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Logging Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(V.default,{value:eR,onChange:eD,premiumUser:!0,disabledCallbacks:e3,onDisabledCallbacksChange:e6})})})]}):(0,t.jsx)(S.Tooltip,{title:(0,t.jsxs)("span",{children:["Key-level logging settings is an enterprise feature, get in touch -",(0,t.jsx)("a",{href:"https://www.litellm.ai/enterprise",target:"_blank",children:"https://www.litellm.ai/enterprise"})]}),placement:"top",children:(0,t.jsxs)("div",{style:{position:"relative"},children:[(0,t.jsx)("div",{style:{opacity:.5},children:(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Logging Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(V.default,{value:eR,onChange:eD,premiumUser:!1,disabledCallbacks:e3,onDisabledCallbacksChange:e6})})})]})}),(0,t.jsx)("div",{style:{position:"absolute",inset:0,cursor:"not-allowed"}})]})}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Router Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4 w-full",children:(0,t.jsx)(G.default,{accessToken:ei||"",value:tr||void 0,onChange:ti,modelData:ew.length>0?{data:ew.map(e=>({model_name:e}))}:void 0},tn)})})]},`router-settings-accordion-${tn}`),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Model Aliases"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsxs)("div",{className:"mt-4",children:[(0,t.jsx)(h.Text,{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,t.jsx)(E.default,{accessToken:ei,initialModelAliases:e8,onAliasUpdate:te,showExampleConfig:!1})]})})]}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Key Lifecycle"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(P.default,{form:ex,autoRotationEnabled:tt,onAutoRotationChange:ts,rotationInterval:ta,onRotationIntervalChange:tl,isCreateMode:!0})})}),(0,t.jsx)(_.Form.Item,{name:"duration",hidden:!0,initialValue:null,children:(0,t.jsx)(j.Input,{})})]}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("b",{children:"Advanced Settings"}),(0,t.jsx)(S.Tooltip,{title:(0,t.jsxs)("span",{children:["Learn more about advanced settings in our"," ",(0,t.jsx)("a",{href:H.proxyBaseUrl?`${H.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,t.jsx)(n.InfoCircleOutlined,{className:"text-gray-400 hover:text-gray-300 cursor-help"})})]})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)(O.default,{schemaComponent:"GenerateKeyRequest",form:ex,excludedFields:["key_alias","team_id","models","duration","metadata","tags","guardrails","max_budget","budget_duration","tpm_limit","rpm_limit"]})})]})]})]})}),(0,t.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,t.jsx)(f.Button,{htmlType:"submit",disabled:th,style:{opacity:th?.5:1},children:"Create Key"})})]})}),eW&&(0,t.jsx)(b.Modal,{title:"Create New User",open:eW,onCancel:()=>eH(!1),footer:null,width:800,children:(0,t.jsx)(K.CreateUserButton,{userID:en,accessToken:ei,teams:Q,possibleUIRoles:eY,onUserCreated:e=>{eJ(e),ex.setFieldsValue({user_id:e}),eH(!1)},isEmbedded:!0})}),e_&&(0,t.jsx)(b.Modal,{open:ey,onOk:tp,onCancel:tg,footer:null,children:(0,t.jsxs)(g.Grid,{numItems:1,className:"gap-2 w-full",children:[(0,t.jsx)(y.Title,{children:"Save your Key"}),(0,t.jsx)(p.Col,{numColSpan:1,children:null!=e_?(0,t.jsx)(Y,{apiKey:e_}):(0,t.jsx)(h.Text,{children:"Key being created, this might take 30s"})})]})})]})},"fetchTeamModels",0,et,"fetchUserModels",0,es],702597)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/4d3d997560b322ca.js b/litellm/proxy/_experimental/out/_next/static/chunks/4d3d997560b322ca.js deleted file mode 100644 index c5a2e17ab26..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/4d3d997560b322ca.js +++ /dev/null @@ -1,13 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,245704,e=>{"use strict";e.i(247167);var t=e.i(931067),n=e.i(271645);let 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"};var r=e.i(9583),l=n.forwardRef(function(e,l){return n.createElement(r.default,(0,t.default)({},e,{ref:l,icon:a}))});e.s(["CheckCircleOutlined",0,l],245704)},245094,e=>{"use strict";e.i(247167);var t=e.i(931067),n=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M516 673c0 4.4 3.4 8 7.5 8h185c4.1 0 7.5-3.6 7.5-8v-48c0-4.4-3.4-8-7.5-8h-185c-4.1 0-7.5 3.6-7.5 8v48zm-194.9 6.1l192-161c3.8-3.2 3.8-9.1 0-12.3l-192-160.9A7.95 7.95 0 00308 351v62.7c0 2.4 1 4.6 2.9 6.1L420.7 512l-109.8 92.2a8.1 8.1 0 00-2.9 6.1V673c0 6.8 7.9 10.5 13.1 6.1zM880 112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32zm-40 728H184V184h656v656z"}}]},name:"code",theme:"outlined"};var r=e.i(9583),l=n.forwardRef(function(e,l){return n.createElement(r.default,(0,t.default)({},e,{ref:l,icon:a}))});e.s(["CodeOutlined",0,l],245094)},266537,e=>{"use strict";e.i(247167);var t=e.i(931067),n=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M869 487.8L491.2 159.9c-2.9-2.5-6.6-3.9-10.5-3.9h-88.5c-7.4 0-10.8 9.2-5.2 14l350.2 304H152c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h585.1L386.9 854c-5.6 4.9-2.2 14 5.2 14h91.5c1.9 0 3.8-.7 5.2-2L869 536.2a32.07 32.07 0 000-48.4z"}}]},name:"arrow-right",theme:"outlined"};var r=e.i(9583),l=n.forwardRef(function(e,l){return n.createElement(r.default,(0,t.default)({},e,{ref:l,icon:a}))});e.s(["ArrowRightOutlined",0,l],266537)},850627,e=>{"use strict";e.i(247167);var t=e.i(271645),n=e.i(343794),a=e.i(209428),r=e.i(211577),l=e.i(8211),o=e.i(410160),u=e.i(392221),i=e.i(175066),c=e.i(914949),s=e.i(929123),d=e.i(883110),f=e.i(931067),v=e.i(703923),g=e.i(174080);function m(e,t,n,a){var r=(t-n)/(a-n),l={};switch(e){case"rtl":l.right="".concat(100*r,"%"),l.transform="translateX(50%)";break;case"btt":l.bottom="".concat(100*r,"%"),l.transform="translateY(50%)";break;case"ttb":l.top="".concat(100*r,"%"),l.transform="translateY(-50%)";break;default:l.left="".concat(100*r,"%"),l.transform="translateX(-50%)"}return l}function h(e,t){return Array.isArray(e)?e[t]:e}var b=e.i(404948),p=t.createContext({min:0,max:0,direction:"ltr",step:1,includedStart:0,includedEnd:0,tabIndex:0,keyboard:!0,styles:{},classNames:{}}),C=t.createContext({}),k=["prefixCls","value","valueIndex","onStartMove","onDelete","style","render","dragging","draggingDelete","onOffsetChange","onChangeComplete","onFocus","onMouseEnter"],x=t.forwardRef(function(e,l){var o,u=e.prefixCls,i=e.value,c=e.valueIndex,s=e.onStartMove,d=e.onDelete,g=e.style,C=e.render,x=e.dragging,y=e.draggingDelete,E=e.onOffsetChange,S=e.onChangeComplete,$=e.onFocus,w=e.onMouseEnter,M=(0,v.default)(e,k),O=t.useContext(p),B=O.min,R=O.max,D=O.direction,H=O.disabled,j=O.keyboard,P=O.range,F=O.tabIndex,N=O.ariaLabelForHandle,I=O.ariaLabelledByForHandle,L=O.ariaRequired,T=O.ariaValueTextFormatterForHandle,A=O.styles,q=O.classNames,z="".concat(u,"-handle"),V=function(e){H||s(e,c)},W=m(D,i,B,R),X={};null!==c&&(X={tabIndex:H?null:h(F,c),role:"slider","aria-valuemin":B,"aria-valuemax":R,"aria-valuenow":i,"aria-disabled":H,"aria-label":h(N,c),"aria-labelledby":h(I,c),"aria-required":h(L,c),"aria-valuetext":null==(o=h(T,c))?void 0:o(i),"aria-orientation":"ltr"===D||"rtl"===D?"horizontal":"vertical",onMouseDown:V,onTouchStart:V,onFocus:function(e){null==$||$(e,c)},onMouseEnter:function(e){w(e,c)},onKeyDown:function(e){if(!H&&j){var t=null;switch(e.which||e.keyCode){case b.default.LEFT:t="ltr"===D||"btt"===D?-1:1;break;case b.default.RIGHT:t="ltr"===D||"btt"===D?1:-1;break;case b.default.UP:t="ttb"!==D?1:-1;break;case b.default.DOWN:t="ttb"!==D?-1:1;break;case b.default.HOME:t="min";break;case b.default.END:t="max";break;case b.default.PAGE_UP:t=2;break;case b.default.PAGE_DOWN:t=-2;break;case b.default.BACKSPACE:case b.default.DELETE:null==d||d(c)}null!==t&&(e.preventDefault(),E(t,c))}},onKeyUp:function(e){switch(e.which||e.keyCode){case b.default.LEFT:case b.default.RIGHT:case b.default.UP:case b.default.DOWN:case b.default.HOME:case b.default.END:case b.default.PAGE_UP:case b.default.PAGE_DOWN:null==S||S()}}});var G=t.createElement("div",(0,f.default)({ref:l,className:(0,n.default)(z,(0,r.default)((0,r.default)((0,r.default)({},"".concat(z,"-").concat(c+1),null!==c&&P),"".concat(z,"-dragging"),x),"".concat(z,"-dragging-delete"),y),q.handle),style:(0,a.default)((0,a.default)((0,a.default)({},W),g),A.handle)},X,M));return C&&(G=C(G,{index:c,prefixCls:u,value:i,dragging:x,draggingDelete:y})),G}),y=["prefixCls","style","onStartMove","onOffsetChange","values","handleRender","activeHandleRender","draggingIndex","draggingDelete","onFocus"],E=t.forwardRef(function(e,n){var r=e.prefixCls,l=e.style,o=e.onStartMove,i=e.onOffsetChange,c=e.values,s=e.handleRender,d=e.activeHandleRender,m=e.draggingIndex,b=e.draggingDelete,p=e.onFocus,C=(0,v.default)(e,y),k=t.useRef({}),E=t.useState(!1),S=(0,u.default)(E,2),$=S[0],w=S[1],M=t.useState(-1),O=(0,u.default)(M,2),B=O[0],R=O[1],D=function(e){R(e),w(!0)};t.useImperativeHandle(n,function(){return{focus:function(e){var t;null==(t=k.current[e])||t.focus()},hideHelp:function(){(0,g.flushSync)(function(){w(!1)})}}});var H=(0,a.default)({prefixCls:r,onStartMove:o,onOffsetChange:i,render:s,onFocus:function(e,t){D(t),null==p||p(e)},onMouseEnter:function(e,t){D(t)}},C);return t.createElement(t.Fragment,null,c.map(function(e,n){var a=m===n;return t.createElement(x,(0,f.default)({ref:function(e){e?k.current[n]=e:delete k.current[n]},dragging:a,draggingDelete:a&&b,style:h(l,n),key:n,value:e,valueIndex:n},H))}),d&&$&&t.createElement(x,(0,f.default)({key:"a11y"},H,{value:c[B],valueIndex:null,dragging:-1!==m,draggingDelete:b,render:d,style:{pointerEvents:"none"},tabIndex:null,"aria-hidden":!0})))});let S=function(e){var l=e.prefixCls,o=e.style,u=e.children,i=e.value,c=e.onClick,s=t.useContext(p),d=s.min,f=s.max,v=s.direction,g=s.includedStart,h=s.includedEnd,b=s.included,C="".concat(l,"-text"),k=m(v,i,d,f);return t.createElement("span",{className:(0,n.default)(C,(0,r.default)({},"".concat(C,"-active"),b&&g<=i&&i<=h)),style:(0,a.default)((0,a.default)({},k),o),onMouseDown:function(e){e.stopPropagation()},onClick:function(){c(i)}},u)},$=function(e){var n=e.prefixCls,a=e.marks,r=e.onClick,l="".concat(n,"-mark");return a.length?t.createElement("div",{className:l},a.map(function(e){var n=e.value,a=e.style,o=e.label;return t.createElement(S,{key:n,prefixCls:l,style:a,value:n,onClick:r},o)})):null},w=function(e){var l=e.prefixCls,o=e.value,u=e.style,i=e.activeStyle,c=t.useContext(p),s=c.min,d=c.max,f=c.direction,v=c.included,g=c.includedStart,h=c.includedEnd,b="".concat(l,"-dot"),C=v&&g<=o&&o<=h,k=(0,a.default)((0,a.default)({},m(f,o,s,d)),"function"==typeof u?u(o):u);return C&&(k=(0,a.default)((0,a.default)({},k),"function"==typeof i?i(o):i)),t.createElement("span",{className:(0,n.default)(b,(0,r.default)({},"".concat(b,"-active"),C)),style:k})},M=function(e){var n=e.prefixCls,a=e.marks,r=e.dots,l=e.style,o=e.activeStyle,u=t.useContext(p),i=u.min,c=u.max,s=u.step,d=t.useMemo(function(){var e=new Set;if(a.forEach(function(t){e.add(t.value)}),r&&null!==s)for(var t=i;t<=c;)e.add(t),t+=s;return Array.from(e)},[i,c,s,r,a]);return t.createElement("div",{className:"".concat(n,"-step")},d.map(function(e){return t.createElement(w,{prefixCls:n,key:e,value:e,style:l,activeStyle:o})}))},O=function(e){var l=e.prefixCls,o=e.style,u=e.start,i=e.end,c=e.index,s=e.onStartMove,d=e.replaceCls,f=t.useContext(p),v=f.direction,g=f.min,m=f.max,h=f.disabled,b=f.range,C=f.classNames,k="".concat(l,"-track"),x=(u-g)/(m-g),y=(i-g)/(m-g),E=function(e){!h&&s&&s(e,-1)},S={};switch(v){case"rtl":S.right="".concat(100*x,"%"),S.width="".concat(100*y-100*x,"%");break;case"btt":S.bottom="".concat(100*x,"%"),S.height="".concat(100*y-100*x,"%");break;case"ttb":S.top="".concat(100*x,"%"),S.height="".concat(100*y-100*x,"%");break;default:S.left="".concat(100*x,"%"),S.width="".concat(100*y-100*x,"%")}var $=d||(0,n.default)(k,(0,r.default)((0,r.default)({},"".concat(k,"-").concat(c+1),null!==c&&b),"".concat(l,"-track-draggable"),s),C.track);return t.createElement("div",{className:$,style:(0,a.default)((0,a.default)({},S),o),onMouseDown:E,onTouchStart:E})},B=function(e){var r=e.prefixCls,l=e.style,o=e.values,u=e.startPoint,i=e.onStartMove,c=t.useContext(p),s=c.included,d=c.range,f=c.min,v=c.styles,g=c.classNames,m=t.useMemo(function(){if(!d){if(0===o.length)return[];var e=null!=u?u:f,t=o[0];return[{start:Math.min(e,t),end:Math.max(e,t)}]}for(var n=[],a=0;a130&&g=0&&en},[en,eN]),eL=t.useMemo(function(){return Object.keys(ev||{}).map(function(e){var n=ev[e],a={value:Number(e)};return n&&"object"===(0,o.default)(n)&&!t.isValidElement(n)&&("label"in n||"style"in n)?(a.style=n.style,a.label=n.label):a.label=n,a}).filter(function(e){var t=e.label;return t||"number"==typeof t}).sort(function(e,t){return e.value-t.value})},[ev]),eT=(v=void 0===ee||ee,g=t.useCallback(function(e){return Math.max(eP,Math.min(eF,e))},[eP,eF]),m=t.useCallback(function(e){if(null!==eN){var t=eP+Math.round((g(e)-eP)/eN)*eN,n=function(e){return(String(e).split(".")[1]||"").length},a=Math.max(n(eN),n(eF),n(eP)),r=Number(t.toFixed(a));return eP<=r&&r<=eF?r:null}return null},[eN,eP,eF,g]),h=t.useCallback(function(e){var t=g(e),n=eL.map(function(e){return e.value});null!==eN&&n.push(m(e)),n.push(eP,eF);var a=n[0],r=eF-eP;return n.forEach(function(e){var n=Math.abs(t-e);n<=r&&(a=e,r=n)}),a},[eP,eF,eL,eN,g,m]),b=function e(t,n,a){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unit";if("number"==typeof n){var o,u=t[a],i=u+n,c=[];eL.forEach(function(e){c.push(e.value)}),c.push(eP,eF),c.push(m(u));var s=n>0?1:-1;"unit"===r?c.push(m(u+s*eN)):c.push(m(i)),c=c.filter(function(e){return null!==e}).filter(function(e){return n<0?e<=u:e>=u}),"unit"===r&&(c=c.filter(function(e){return e!==u}));var d="unit"===r?u:i,f=Math.abs((o=c[0])-d);if(c.forEach(function(e){var t=Math.abs(e-d);t1){var v=(0,l.default)(t);return v[a]=o,e(v,n-s,a,r)}return o}return"min"===n?eP:"max"===n?eF:void 0},C=function(e,t,n){var a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unit",r=e[n],l=b(e,t,n,a);return{value:l,changed:l!==r}},k=function(e){return null===eI&&0===e||"number"==typeof eI&&e3&&void 0!==arguments[3]?arguments[3]:"unit",r=e.map(h),l=r[n],o=b(r,t,n,a);if(r[n]=o,!1===v){var u=eI||0;n>0&&r[n-1]!==l&&(r[n]=Math.max(r[n],r[n-1]+u)),n0;d-=1)for(var f=!0;k(r[d]-r[d-1])&&f;){var g=C(r,-1,d-1);r[d-1]=g.value,f=g.changed}for(var m=r.length-1;m>0;m-=1)for(var p=!0;k(r[m]-r[m-1])&&p;){var x=C(r,-1,m-1);r[m-1]=x.value,p=x.changed}for(var y=0;y=0?K+1:2;for(a=a.slice(0,o);a.length=0&&eS.current.focus(e)}e5(null)},[e8]);var e9=t.useMemo(function(){return(!eD||null!==eN)&&eD},[eD,eN]),te=(0,i.default)(function(e,t){e4(e,t),null==J||J(eU(eY))}),tt=-1!==eZ;t.useEffect(function(){if(!tt){var e=eY.lastIndexOf(e0);eS.current.focus(e)}},[tt]);var tn=t.useMemo(function(){return(0,l.default)(e2).sort(function(e,t){return e-t})},[e2]),ta=t.useMemo(function(){return eB?[tn[0],tn[tn.length-1]]:[eP,tn[0]]},[tn,eB,eP]),tr=(0,u.default)(ta,2),tl=tr[0],to=tr[1];t.useImperativeHandle(f,function(){return{focus:function(){eS.current.focus(0)},blur:function(){var e,t=document.activeElement;null!=(e=e$.current)&&e.contains(t)&&(null==t||t.blur())}}}),t.useEffect(function(){I&&eS.current.focus(0)},[]);var tu=t.useMemo(function(){return{min:eP,max:eF,direction:ew,disabled:P,keyboard:N,step:eN,included:eo,includedStart:tl,includedEnd:to,range:eB,tabIndex:eC,ariaLabelForHandle:ek,ariaLabelledByForHandle:ex,ariaRequired:ey,ariaValueTextFormatterForHandle:eE,styles:R||{},classNames:O||{}}},[eP,eF,ew,P,N,eN,eo,tl,to,eB,eC,ek,ex,ey,eE,R,O]);return t.createElement(p.Provider,{value:tu},t.createElement("div",{ref:e$,className:(0,n.default)(y,S,(0,r.default)((0,r.default)((0,r.default)((0,r.default)({},"".concat(y,"-disabled"),P),"".concat(y,"-vertical"),er),"".concat(y,"-horizontal"),!er),"".concat(y,"-with-marks"),eL.length)),style:w,onMouseDown:function(e){e.preventDefault();var t,n=e$.current.getBoundingClientRect(),a=n.width,r=n.height,l=n.left,o=n.top,u=n.bottom,i=n.right,c=e.clientX,s=e.clientY;switch(ew){case"btt":t=(u-s)/r;break;case"ttb":t=(s-o)/r;break;case"rtl":t=(i-c)/a;break;default:t=(c-l)/a}e3(eq(eP+t*(eF-eP)),e)},id:D},t.createElement("div",{className:(0,n.default)("".concat(y,"-rail"),null==O?void 0:O.rail),style:(0,a.default)((0,a.default)({},es),null==R?void 0:R.rail)}),!1!==eb&&t.createElement(B,{prefixCls:y,style:ei,values:eY,startPoint:eu,onStartMove:e9?te:void 0}),t.createElement(M,{prefixCls:y,marks:eL,dots:eg,style:ed,activeStyle:ef}),t.createElement(E,{ref:eS,prefixCls:y,style:ec,values:e2,draggingIndex:eZ,draggingDelete:e1,onStartMove:te,onOffsetChange:function(e,t){if(!P){var n=ez(eY,e,t);null==J||J(eU(eY)),eK(n.values),e5(n.value)}},onFocus:L,onBlur:T,handleRender:em,activeHandleRender:eh,onChangeComplete:e_,onDelete:eR?function(e){if(!P&&eR&&!(eY.length<=eH)){var t=(0,l.default)(eY);t.splice(e,1),null==J||J(eU(t)),eK(t);var n=Math.max(0,e-1);eS.current.hideHelp(),eS.current.focus(n)}}:void 0}),t.createElement($,{prefixCls:y,marks:eL,onClick:e3})))}),P=e.i(963188),F=e.i(937328);let N=(0,t.createContext)({});var I=e.i(611935),L=e.i(491816);let T=t.forwardRef((e,n)=>{let{open:a,draggingDelete:r,value:l}=e,o=(0,t.useRef)(null),u=a&&!r,i=(0,t.useRef)(null);function c(){P.default.cancel(i.current),i.current=null}return t.useEffect(()=>(u?i.current=(0,P.default)(()=>{var e;null==(e=o.current)||e.forceAlign(),i.current=null}):c(),c),[u,e.title,l]),t.createElement(L.default,Object.assign({ref:(0,I.composeRef)(o,n)},e,{open:u}))});e.i(296059);var A=e.i(915654);e.i(262370);var q=e.i(135551),z=e.i(183293),V=e.i(246422),W=e.i(838378);let X=(e,t)=>{let{componentCls:n,railSize:a,handleSize:r,dotSize:l,marginFull:o,calc:u}=e,i=t?"width":"height",c=t?"height":"width",s=t?"insetBlockStart":"insetInlineStart",d=t?"top":"insetInlineStart",f=u(a).mul(3).sub(r).div(2).equal(),v=u(r).sub(a).div(2).equal(),g=t?{borderWidth:`${(0,A.unit)(v)} 0`,transform:`translateY(${(0,A.unit)(u(v).mul(-1).equal())})`}:{borderWidth:`0 ${(0,A.unit)(v)}`,transform:`translateX(${(0,A.unit)(e.calc(v).mul(-1).equal())})`};return{[t?"paddingBlock":"paddingInline"]:a,[c]:u(a).mul(3).equal(),[`${n}-rail`]:{[i]:"100%",[c]:a},[`${n}-track,${n}-tracks`]:{[c]:a},[`${n}-track-draggable`]:Object.assign({},g),[`${n}-handle`]:{[s]:f},[`${n}-mark`]:{insetInlineStart:0,top:0,[d]:u(a).mul(3).add(t?0:o).equal(),[i]:"100%"},[`${n}-step`]:{insetInlineStart:0,top:0,[d]:a,[i]:"100%",[c]:a},[`${n}-dot`]:{position:"absolute",[s]:u(a).sub(l).div(2).equal()}}},G=(0,V.genStyleHooks)("Slider",e=>{let t=(0,W.mergeToken)(e,{marginPart:e.calc(e.controlHeight).sub(e.controlSize).div(2).equal(),marginFull:e.calc(e.controlSize).div(2).equal(),marginPartWithMark:e.calc(e.controlHeightLG).sub(e.controlSize).equal()});return[(e=>{let{componentCls:t,antCls:n,controlSize:a,dotSize:r,marginFull:l,marginPart:o,colorFillContentHover:u,handleColorDisabled:i,calc:c,handleSize:s,handleSizeHover:d,handleActiveColor:f,handleActiveOutlineColor:v,handleLineWidth:g,handleLineWidthHover:m,motionDurationMid:h}=e;return{[t]:Object.assign(Object.assign({},(0,z.resetComponent)(e)),{position:"relative",height:a,margin:`${(0,A.unit)(o)} ${(0,A.unit)(l)}`,padding:0,cursor:"pointer",touchAction:"none","&-vertical":{margin:`${(0,A.unit)(l)} ${(0,A.unit)(o)}`},[`${t}-rail`]:{position:"absolute",backgroundColor:e.railBg,borderRadius:e.borderRadiusXS,transition:`background-color ${h}`},[`${t}-track,${t}-tracks`]:{position:"absolute",transition:`background-color ${h}`},[`${t}-track`]:{backgroundColor:e.trackBg,borderRadius:e.borderRadiusXS},[`${t}-track-draggable`]:{boxSizing:"content-box",backgroundClip:"content-box",border:"solid rgba(0,0,0,0)"},"&:hover":{[`${t}-rail`]:{backgroundColor:e.railHoverBg},[`${t}-track`]:{backgroundColor:e.trackHoverBg},[`${t}-dot`]:{borderColor:u},[`${t}-handle::after`]:{boxShadow:`0 0 0 ${(0,A.unit)(g)} ${e.colorPrimaryBorderHover}`},[`${t}-dot-active`]:{borderColor:e.dotActiveBorderColor}},[`${t}-handle`]:{position:"absolute",width:s,height:s,outline:"none",userSelect:"none","&-dragging-delete":{opacity:0},"&::before":{content:'""',position:"absolute",insetInlineStart:c(g).mul(-1).equal(),insetBlockStart:c(g).mul(-1).equal(),width:c(s).add(c(g).mul(2)).equal(),height:c(s).add(c(g).mul(2)).equal(),backgroundColor:"transparent"},"&::after":{content:'""',position:"absolute",insetBlockStart:0,insetInlineStart:0,width:s,height:s,backgroundColor:e.colorBgElevated,boxShadow:`0 0 0 ${(0,A.unit)(g)} ${e.handleColor}`,outline:"0px solid transparent",borderRadius:"50%",cursor:"pointer",transition:` - inset-inline-start ${h}, - inset-block-start ${h}, - width ${h}, - height ${h}, - box-shadow ${h}, - outline ${h} - `},"&:hover, &:active, &:focus":{"&::before":{insetInlineStart:c(d).sub(s).div(2).add(m).mul(-1).equal(),insetBlockStart:c(d).sub(s).div(2).add(m).mul(-1).equal(),width:c(d).add(c(m).mul(2)).equal(),height:c(d).add(c(m).mul(2)).equal()},"&::after":{boxShadow:`0 0 0 ${(0,A.unit)(m)} ${f}`,outline:`6px solid ${v}`,width:d,height:d,insetInlineStart:e.calc(s).sub(d).div(2).equal(),insetBlockStart:e.calc(s).sub(d).div(2).equal()}}},[`&-lock ${t}-handle`]:{"&::before, &::after":{transition:"none"}},[`${t}-mark`]:{position:"absolute",fontSize:e.fontSize},[`${t}-mark-text`]:{position:"absolute",display:"inline-block",color:e.colorTextDescription,textAlign:"center",wordBreak:"keep-all",cursor:"pointer",userSelect:"none","&-active":{color:e.colorText}},[`${t}-step`]:{position:"absolute",background:"transparent",pointerEvents:"none"},[`${t}-dot`]:{position:"absolute",width:r,height:r,backgroundColor:e.colorBgElevated,border:`${(0,A.unit)(g)} solid ${e.dotBorderColor}`,borderRadius:"50%",cursor:"pointer",transition:`border-color ${e.motionDurationSlow}`,pointerEvents:"auto","&-active":{borderColor:e.dotActiveBorderColor}},[`&${t}-disabled`]:{cursor:"not-allowed",[`${t}-rail`]:{backgroundColor:`${e.railBg} !important`},[`${t}-track`]:{backgroundColor:`${e.trackBgDisabled} !important`},[` - ${t}-dot - `]:{backgroundColor:e.colorBgElevated,borderColor:e.trackBgDisabled,boxShadow:"none",cursor:"not-allowed"},[`${t}-handle::after`]:{backgroundColor:e.colorBgElevated,cursor:"not-allowed",width:s,height:s,boxShadow:`0 0 0 ${(0,A.unit)(g)} ${i}`,insetInlineStart:0,insetBlockStart:0},[` - ${t}-mark-text, - ${t}-dot - `]:{cursor:"not-allowed !important"}},[`&-tooltip ${n}-tooltip-inner`]:{minWidth:"unset"}})}})(t),(e=>{let{componentCls:t,marginPartWithMark:n}=e;return{[`${t}-horizontal`]:Object.assign(Object.assign({},X(e,!0)),{[`&${t}-with-marks`]:{marginBottom:n}})}})(t),(e=>{let{componentCls:t}=e;return{[`${t}-vertical`]:Object.assign(Object.assign({},X(e,!1)),{height:"100%"})}})(t)]},e=>{let t=e.controlHeightLG/4,n=e.controlHeightSM/2,a=e.lineWidth+1,r=e.lineWidth+1.5,l=e.colorPrimary,o=new q.FastColor(l).setA(.2).toRgbString();return{controlSize:t,railSize:4,handleSize:t,handleSizeHover:n,dotSize:8,handleLineWidth:a,handleLineWidthHover:r,railBg:e.colorFillTertiary,railHoverBg:e.colorFillSecondary,trackBg:e.colorPrimaryBorder,trackHoverBg:e.colorPrimaryBorderHover,handleColor:e.colorPrimaryBorder,handleActiveColor:l,handleActiveOutlineColor:o,handleColorDisabled:new q.FastColor(e.colorTextDisabled).onBackground(e.colorBgContainer).toHexString(),dotBorderColor:e.colorBorderSecondary,dotActiveBorderColor:e.colorPrimaryBorder,trackBgDisabled:e.colorBgContainerDisabled}});function Y(){let[e,n]=t.useState(!1),a=t.useRef(null),r=()=>{P.default.cancel(a.current)};return t.useEffect(()=>r,[]),[e,e=>{r(),e?n(e):a.current=(0,P.default)(()=>{n(e)})}]}var U=e.i(242064),K=function(e,t){var n={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(n[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,a=Object.getOwnPropertySymbols(e);rt.indexOf(a[r])&&Object.prototype.propertyIsEnumerable.call(e,a[r])&&(n[a[r]]=e[a[r]]);return n};let _=t.default.forwardRef((e,a)=>{let{prefixCls:r,range:l,className:o,rootClassName:u,style:i,disabled:c,tooltipPrefixCls:s,tipFormatter:d,tooltipVisible:f,getTooltipPopupContainer:v,tooltipPlacement:g,tooltip:m={},onChangeComplete:h,classNames:b,styles:p}=e,C=K(e,["prefixCls","range","className","rootClassName","style","disabled","tooltipPrefixCls","tipFormatter","tooltipVisible","getTooltipPopupContainer","tooltipPlacement","tooltip","onChangeComplete","classNames","styles"]),{vertical:k}=e,{getPrefixCls:x,direction:y,className:E,style:S,classNames:$,styles:w,getPopupContainer:M}=(0,U.useComponentConfig)("slider"),O=t.default.useContext(F.default),{handleRender:B,direction:R}=t.default.useContext(N),D="rtl"===(R||y),[H,I]=Y(),[L,A]=Y(),q=Object.assign({},m),{open:z,placement:V,getPopupContainer:W,prefixCls:X,formatter:_}=q,J=null!=z?z:f,Q=(H||L)&&!1!==J,Z=_||null===_?_:d||null===d?d:e=>"number"==typeof e?e.toString():"",[ee,et]=Y(),en=(e,t)=>e||(t?D?"left":"right":"top"),ea=x("slider",r),[er,el,eo]=G(ea),eu=(0,n.default)(o,E,$.root,null==b?void 0:b.root,u,{[`${ea}-rtl`]:D,[`${ea}-lock`]:ee},el,eo);D&&!C.vertical&&(C.reverse=!C.reverse),t.default.useEffect(()=>{let e=()=>{(0,P.default)(()=>{A(!1)},1)};return document.addEventListener("mouseup",e),()=>{document.removeEventListener("mouseup",e)}},[]);let ei=l&&!J,ec=B||((e,n)=>{let{index:a}=n,r=e.props;function l(e,t,n){var a,l;n&&(null==(a=C[e])||a.call(C,t)),null==(l=r[e])||l.call(r,t)}let o=Object.assign(Object.assign({},r),{onMouseEnter:e=>{I(!0),l("onMouseEnter",e)},onMouseLeave:e=>{I(!1),l("onMouseLeave",e)},onMouseDown:e=>{A(!0),et(!0),l("onMouseDown",e)},onFocus:e=>{var t;A(!0),null==(t=C.onFocus)||t.call(C,e),l("onFocus",e,!0)},onBlur:e=>{var t;A(!1),null==(t=C.onBlur)||t.call(C,e),l("onBlur",e,!0)}}),u=t.default.cloneElement(e,o),i=(!!J||Q)&&null!==Z;return ei?u:t.default.createElement(T,Object.assign({},q,{prefixCls:x("tooltip",null!=X?X:s),title:Z?Z(n.value):"",value:n.value,open:i,placement:en(null!=V?V:g,k),key:a,classNames:{root:`${ea}-tooltip`},getPopupContainer:W||v||M}),u)}),es=ei?(e,n)=>{let a=t.default.cloneElement(e,{style:Object.assign(Object.assign({},e.props.style),{visibility:"hidden"})});return t.default.createElement(T,Object.assign({},q,{prefixCls:x("tooltip",null!=X?X:s),title:Z?Z(n.value):"",open:null!==Z&&Q,placement:en(null!=V?V:g,k),key:"tooltip",classNames:{root:`${ea}-tooltip`},getPopupContainer:W||v||M,draggingDelete:n.draggingDelete}),a)}:void 0,ed=Object.assign(Object.assign(Object.assign(Object.assign({},w.root),S),null==p?void 0:p.root),i),ef=Object.assign(Object.assign({},w.tracks),null==p?void 0:p.tracks),ev=(0,n.default)($.tracks,null==b?void 0:b.tracks);return er(t.default.createElement(j,Object.assign({},C,{classNames:Object.assign({handle:(0,n.default)($.handle,null==b?void 0:b.handle),rail:(0,n.default)($.rail,null==b?void 0:b.rail),track:(0,n.default)($.track,null==b?void 0:b.track)},ev?{tracks:ev}:{}),styles:Object.assign({handle:Object.assign(Object.assign({},w.handle),null==p?void 0:p.handle),rail:Object.assign(Object.assign({},w.rail),null==p?void 0:p.rail),track:Object.assign(Object.assign({},w.track),null==p?void 0:p.track)},Object.keys(ef).length?{tracks:ef}:{}),step:C.step,range:l,className:eu,style:ed,disabled:null!=c?c:O,ref:a,prefixCls:ea,handleRender:ec,activeHandleRender:es,onChangeComplete:e=>{null==h||h(e),et(!1)}})))});e.s(["Slider",0,_],850627)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/4e4d0f466b5c1780.js b/litellm/proxy/_experimental/out/_next/static/chunks/4e4d0f466b5c1780.js deleted file mode 100644 index 8bb598f14e8..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/4e4d0f466b5c1780.js +++ /dev/null @@ -1,598 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,602073,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let s={icon:{tag:"svg",attrs:{viewBox:"0 0 1024 1024",focusable:"false"},children:[{tag:"path",attrs:{d:"M512 64L128 192v384c0 212.1 171.9 384 384 384s384-171.9 384-384V192L512 64zm312 512c0 172.3-139.7 312-312 312S200 748.3 200 576V246l312-110 312 110v330z"}},{tag:"path",attrs:{d:"M378.4 475.1a35.91 35.91 0 00-50.9 0 35.91 35.91 0 000 50.9l129.4 129.4 2.1 2.1a33.98 33.98 0 0048.1 0L730.6 434a33.98 33.98 0 000-48.1l-2.8-2.8a33.98 33.98 0 00-48.1 0L483 579.7 378.4 475.1z"}}]},name:"safety",theme:"outlined"};var r=e.i(9583),i=a.forwardRef(function(e,i){return a.createElement(r.default,(0,t.default)({},e,{ref:i,icon:s}))});e.s(["SafetyOutlined",0,i],602073)},818581,(e,t,a)=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0}),Object.defineProperty(a,"useMergedRef",{enumerable:!0,get:function(){return r}});let s=e.r(271645);function r(e,t){let a=(0,s.useRef)(null),r=(0,s.useRef)(null);return(0,s.useCallback)(s=>{if(null===s){let e=a.current;e&&(a.current=null,e());let t=r.current;t&&(r.current=null,t())}else e&&(a.current=i(e,s)),t&&(r.current=i(t,s))},[e,t])}function i(e,t){if("function"!=typeof e)return e.current=t,()=>{e.current=null};{let a=e(t);return"function"==typeof a?a:()=>e(null)}}("function"==typeof a.default||"object"==typeof a.default&&null!==a.default)&&void 0===a.default.__esModule&&(Object.defineProperty(a.default,"__esModule",{value:!0}),Object.assign(a.default,a),t.exports=a.default)},62478,e=>{"use strict";var t=e.i(764205);let a=async e=>{if(!e)return null;try{return await (0,t.getProxyUISettings)(e)}catch(e){return console.error("Error fetching proxy settings:",e),null}};e.s(["fetchProxySettings",0,a])},190272,785913,e=>{"use strict";var t,a,s=((t={}).AUDIO_SPEECH="audio_speech",t.AUDIO_TRANSCRIPTION="audio_transcription",t.IMAGE_GENERATION="image_generation",t.VIDEO_GENERATION="video_generation",t.CHAT="chat",t.RESPONSES="responses",t.IMAGE_EDITS="image_edits",t.ANTHROPIC_MESSAGES="anthropic_messages",t.EMBEDDING="embedding",t),r=((a={}).IMAGE="image",a.VIDEO="video",a.CHAT="chat",a.RESPONSES="responses",a.IMAGE_EDITS="image_edits",a.ANTHROPIC_MESSAGES="anthropic_messages",a.EMBEDDINGS="embeddings",a.SPEECH="speech",a.TRANSCRIPTION="transcription",a.A2A_AGENTS="a2a_agents",a.MCP="mcp",a.REALTIME="realtime",a);let i={image_generation:"image",video_generation:"video",chat:"chat",responses:"responses",image_edits:"image_edits",anthropic_messages:"anthropic_messages",audio_speech:"speech",audio_transcription:"transcription",embedding:"embeddings"};e.s(["EndpointType",()=>r,"getEndpointType",0,e=>{if(console.log("getEndpointType:",e),Object.values(s).includes(e)){let t=i[e];return console.log("endpointType:",t),t}return"chat"}],785913),e.s(["generateCodeSnippet",0,e=>{let t,{apiKeySource:a,accessToken:s,apiKey:i,inputMessage:l,chatHistory:n,selectedTags:o,selectedVectorStores:c,selectedGuardrails:d,selectedPolicies:m,selectedMCPServers:p,mcpServers:u,mcpServerToolRestrictions:g,selectedVoice:x,endpointType:h,selectedModel:_,selectedSdk:f,proxySettings:b}=e,v="session"===a?s:i,j=window.location.origin,A=b?.LITELLM_UI_API_DOC_BASE_URL;A&&A.trim()?j=A:b?.PROXY_BASE_URL&&(j=b.PROXY_BASE_URL);let y=l||"Your prompt here",N=y.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n"),T=n.filter(e=>!e.isImage).map(({role:e,content:t})=>({role:e,content:t})),C={};o.length>0&&(C.tags=o),c.length>0&&(C.vector_stores=c),d.length>0&&(C.guardrails=d),m.length>0&&(C.policies=m);let S=_||"your-model-name",I="azure"===f?`import openai - -client = openai.AzureOpenAI( - api_key="${v||"YOUR_LITELLM_API_KEY"}", - azure_endpoint="${j}", - api_version="2024-02-01" -)`:`import openai - -client = openai.OpenAI( - api_key="${v||"YOUR_LITELLM_API_KEY"}", - base_url="${j}" -)`;switch(h){case r.CHAT:{let e=Object.keys(C).length>0,a="";if(e){let e=JSON.stringify({metadata:C},null,2).split("\n").map(e=>" ".repeat(4)+e).join("\n").trim();a=`, - extra_body=${e}`}let s=T.length>0?T:[{role:"user",content:y}];t=` -import base64 - -# Helper function to encode images to base64 -def encode_image(image_path): - with open(image_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode('utf-8') - -# Example with text only -response = client.chat.completions.create( - model="${S}", - messages=${JSON.stringify(s,null,4)}${a} -) - -print(response) - -# Example with image or PDF (uncomment and provide file path to use) -# base64_file = encode_image("path/to/your/file.jpg") # or .pdf -# response_with_file = client.chat.completions.create( -# model="${S}", -# messages=[ -# { -# "role": "user", -# "content": [ -# { -# "type": "text", -# "text": "${N}" -# }, -# { -# "type": "image_url", -# "image_url": { -# "url": f"data:image/jpeg;base64,{base64_file}" # or data:application/pdf;base64,{base64_file} -# } -# } -# ] -# } -# ]${a} -# ) -# print(response_with_file) -`;break}case r.RESPONSES:{let e=Object.keys(C).length>0,a="";if(e){let e=JSON.stringify({metadata:C},null,2).split("\n").map(e=>" ".repeat(4)+e).join("\n").trim();a=`, - extra_body=${e}`}let s=T.length>0?T:[{role:"user",content:y}];t=` -import base64 - -# Helper function to encode images to base64 -def encode_image(image_path): - with open(image_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode('utf-8') - -# Example with text only -response = client.responses.create( - model="${S}", - input=${JSON.stringify(s,null,4)}${a} -) - -print(response.output_text) - -# Example with image or PDF (uncomment and provide file path to use) -# base64_file = encode_image("path/to/your/file.jpg") # or .pdf -# response_with_file = client.responses.create( -# model="${S}", -# input=[ -# { -# "role": "user", -# "content": [ -# {"type": "input_text", "text": "${N}"}, -# { -# "type": "input_image", -# "image_url": f"data:image/jpeg;base64,{base64_file}", # or data:application/pdf;base64,{base64_file} -# }, -# ], -# } -# ]${a} -# ) -# print(response_with_file.output_text) -`;break}case r.IMAGE:t="azure"===f?` -# NOTE: The Azure SDK does not have a direct equivalent to the multi-modal 'responses.create' method shown for OpenAI. -# This snippet uses 'client.images.generate' and will create a new image based on your prompt. -# It does not use the uploaded image, as 'client.images.generate' does not support image inputs in this context. -import os -import requests -import json -import time -from PIL import Image - -result = client.images.generate( - model="${S}", - prompt="${l}", - n=1 -) - -json_response = json.loads(result.model_dump_json()) - -# Set the directory for the stored image -image_dir = os.path.join(os.curdir, 'images') - -# If the directory doesn't exist, create it -if not os.path.isdir(image_dir): - os.mkdir(image_dir) - -# Initialize the image path -image_filename = f"generated_image_{int(time.time())}.png" -image_path = os.path.join(image_dir, image_filename) - -try: - # Retrieve the generated image - if json_response.get("data") && len(json_response["data"]) > 0 && json_response["data"][0].get("url"): - image_url = json_response["data"][0]["url"] - generated_image = requests.get(image_url).content - with open(image_path, "wb") as image_file: - image_file.write(generated_image) - - print(f"Image saved to {image_path}") - # Display the image - image = Image.open(image_path) - image.show() - else: - print("Could not find image URL in response.") - print("Full response:", json_response) -except Exception as e: - print(f"An error occurred: {e}") - print("Full response:", json_response) -`:` -import base64 -import os -import time -import json -from PIL import Image -import requests - -# Helper function to encode images to base64 -def encode_image(image_path): - with open(image_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode('utf-8') - -# Helper function to create a file (simplified for this example) -def create_file(image_path): - # In a real implementation, this would upload the file to OpenAI - # For this example, we'll just return a placeholder ID - return f"file_{os.path.basename(image_path).replace('.', '_')}" - -# The prompt entered by the user -prompt = "${N}" - -# Encode images to base64 -base64_image1 = encode_image("body-lotion.png") -base64_image2 = encode_image("soap.png") - -# Create file IDs -file_id1 = create_file("body-lotion.png") -file_id2 = create_file("incense-kit.png") - -response = client.responses.create( - model="${S}", - input=[ - { - "role": "user", - "content": [ - {"type": "input_text", "text": prompt}, - { - "type": "input_image", - "image_url": f"data:image/jpeg;base64,{base64_image1}", - }, - { - "type": "input_image", - "image_url": f"data:image/jpeg;base64,{base64_image2}", - }, - { - "type": "input_image", - "file_id": file_id1, - }, - { - "type": "input_image", - "file_id": file_id2, - } - ], - } - ], - tools=[{"type": "image_generation"}], -) - -# Process the response -image_generation_calls = [ - output - for output in response.output - if output.type == "image_generation_call" -] - -image_data = [output.result for output in image_generation_calls] - -if image_data: - image_base64 = image_data[0] - image_filename = f"edited_image_{int(time.time())}.png" - with open(image_filename, "wb") as f: - f.write(base64.b64decode(image_base64)) - print(f"Image saved to {image_filename}") -else: - # If no image is generated, there might be a text response with an explanation - text_response = [output.text for output in response.output if hasattr(output, 'text')] - if text_response: - print("No image generated. Model response:") - print("\\n".join(text_response)) - else: - print("No image data found in response.") - print("Full response for debugging:") - print(response) -`;break;case r.IMAGE_EDITS:t="azure"===f?` -import base64 -import os -import time -import json -from PIL import Image -import requests - -# Helper function to encode images to base64 -def encode_image(image_path): - with open(image_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode('utf-8') - -# The prompt entered by the user -prompt = "${N}" - -# Encode images to base64 -base64_image1 = encode_image("body-lotion.png") -base64_image2 = encode_image("soap.png") - -# Create file IDs -file_id1 = create_file("body-lotion.png") -file_id2 = create_file("incense-kit.png") - -response = client.responses.create( - model="${S}", - input=[ - { - "role": "user", - "content": [ - {"type": "input_text", "text": prompt}, - { - "type": "input_image", - "image_url": f"data:image/jpeg;base64,{base64_image1}", - }, - { - "type": "input_image", - "image_url": f"data:image/jpeg;base64,{base64_image2}", - }, - { - "type": "input_image", - "file_id": file_id1, - }, - { - "type": "input_image", - "file_id": file_id2, - } - ], - } - ], - tools=[{"type": "image_generation"}], -) - -# Process the response -image_generation_calls = [ - output - for output in response.output - if output.type == "image_generation_call" -] - -image_data = [output.result for output in image_generation_calls] - -if image_data: - image_base64 = image_data[0] - image_filename = f"edited_image_{int(time.time())}.png" - with open(image_filename, "wb") as f: - f.write(base64.b64decode(image_base64)) - print(f"Image saved to {image_filename}") -else: - # If no image is generated, there might be a text response with an explanation - text_response = [output.text for output in response.output if hasattr(output, 'text')] - if text_response: - print("No image generated. Model response:") - print("\\n".join(text_response)) - else: - print("No image data found in response.") - print("Full response for debugging:") - print(response) -`:` -import base64 -import os -import time - -# Helper function to encode images to base64 -def encode_image(image_path): - with open(image_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode('utf-8') - -# Helper function to create a file (simplified for this example) -def create_file(image_path): - # In a real implementation, this would upload the file to OpenAI - # For this example, we'll just return a placeholder ID - return f"file_{os.path.basename(image_path).replace('.', '_')}" - -# The prompt entered by the user -prompt = "${N}" - -# Encode images to base64 -base64_image1 = encode_image("body-lotion.png") -base64_image2 = encode_image("soap.png") - -# Create file IDs -file_id1 = create_file("body-lotion.png") -file_id2 = create_file("incense-kit.png") - -response = client.responses.create( - model="${S}", - input=[ - { - "role": "user", - "content": [ - {"type": "input_text", "text": prompt}, - { - "type": "input_image", - "image_url": f"data:image/jpeg;base64,{base64_image1}", - }, - { - "type": "input_image", - "image_url": f"data:image/jpeg;base64,{base64_image2}", - }, - { - "type": "input_image", - "file_id": file_id1, - }, - { - "type": "input_image", - "file_id": file_id2, - } - ], - } - ], - tools=[{"type": "image_generation"}], -) - -# Process the response -image_generation_calls = [ - output - for output in response.output - if output.type == "image_generation_call" -] - -image_data = [output.result for output in image_generation_calls] - -if image_data: - image_base64 = image_data[0] - image_filename = f"edited_image_{int(time.time())}.png" - with open(image_filename, "wb") as f: - f.write(base64.b64decode(image_base64)) - print(f"Image saved to {image_filename}") -else: - # If no image is generated, there might be a text response with an explanation - text_response = [output.text for output in response.output if hasattr(output, 'text')] - if text_response: - print("No image generated. Model response:") - print("\\n".join(text_response)) - else: - print("No image data found in response.") - print("Full response for debugging:") - print(response) -`;break;case r.EMBEDDINGS:t=` -response = client.embeddings.create( - input="${l||"Your string here"}", - model="${S}", - encoding_format="base64" # or "float" -) - -print(response.data[0].embedding) -`;break;case r.TRANSCRIPTION:t=` -# Open the audio file -audio_file = open("path/to/your/audio/file.mp3", "rb") - -# Make the transcription request -response = client.audio.transcriptions.create( - model="${S}", - file=audio_file${l?`, - prompt="${l.replace(/"/g,'\\"')}"`:""} -) - -print(response.text) -`;break;case r.SPEECH:t=` -# Make the text-to-speech request -response = client.audio.speech.create( - model="${S}", - input="${l||"Your text to convert to speech here"}", - voice="${x}" # Options: alloy, ash, ballad, coral, echo, fable, nova, onyx, sage, shimmer -) - -# Save the audio to a file -output_filename = "output_speech.mp3" -response.stream_to_file(output_filename) -print(f"Audio saved to {output_filename}") - -# Optional: Customize response format and speed -# response = client.audio.speech.create( -# model="${S}", -# input="${l||"Your text to convert to speech here"}", -# voice="alloy", -# response_format="mp3", # Options: mp3, opus, aac, flac, wav, pcm -# speed=1.0 # Range: 0.25 to 4.0 -# ) -# response.stream_to_file("output_speech.mp3") -`;break;default:t="\n# Code generation for this endpoint is not implemented yet."}return`${I} -${t}`}],190272)},879664,e=>{"use strict";let t=(0,e.i(475254).default)("info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]);e.s(["default",()=>t])},916925,e=>{"use strict";var t,a=((t={}).A2A_Agent="A2A Agent",t.AI21="Ai21",t.AI21_CHAT="Ai21 Chat",t.AIML="AI/ML API",t.AIOHTTP_OPENAI="Aiohttp Openai",t.Anthropic="Anthropic",t.ANTHROPIC_TEXT="Anthropic Text",t.AssemblyAI="AssemblyAI",t.AUTO_ROUTER="Auto Router",t.Bedrock="Amazon Bedrock",t.BedrockMantle="Amazon Bedrock Mantle",t.SageMaker="AWS SageMaker",t.Azure="Azure",t.Azure_AI_Studio="Azure AI Foundry (Studio)",t.AZURE_TEXT="Azure Text",t.BASETEN="Baseten",t.BYTEZ="Bytez",t.Cerebras="Cerebras",t.CLARIFAI="Clarifai",t.CLOUDFLARE="Cloudflare",t.CODESTRAL="Codestral",t.Cohere="Cohere",t.COHERE_CHAT="Cohere Chat",t.COMETAPI="Cometapi",t.COMPACTIFAI="Compactifai",t.Cursor="Cursor",t.Dashscope="Dashscope",t.Databricks="Databricks (Qwen API)",t.DATAROBOT="Datarobot",t.DeepInfra="DeepInfra",t.Deepgram="Deepgram",t.Deepseek="Deepseek",t.DOCKER_MODEL_RUNNER="Docker Model Runner",t.DOTPROMPT="Dotprompt",t.ElevenLabs="ElevenLabs",t.EMPOWER="Empower",t.FalAI="Fal AI",t.FEATHERLESS_AI="Featherless Ai",t.FireworksAI="Fireworks AI",t.FRIENDLIAI="Friendliai",t.GALADRIEL="Galadriel",t.GITHUB_COPILOT="Github Copilot",t.Google_AI_Studio="Google AI Studio",t.GradientAI="GradientAI",t.Groq="Groq",t.HEROKU="Heroku",t.Hosted_Vllm="vllm",t.HUGGINGFACE="Huggingface",t.HYPERBOLIC="Hyperbolic",t.Infinity="Infinity",t.JinaAI="Jina AI",t.LAMBDA_AI="Lambda Ai",t.LEMONADE="Lemonade",t.LLAMAFILE="Llamafile",t.LM_STUDIO="Lm Studio",t.LLAMA="Meta Llama",t.MARITALK="Maritalk",t.MiniMax="MiniMax",t.MistralAI="Mistral AI",t.MOONSHOT="Moonshot",t.MORPH="Morph",t.NEBIUS="Nebius",t.NLP_CLOUD="Nlp Cloud",t.NOVITA="Novita",t.NSCALE="Nscale",t.NVIDIA_NIM="Nvidia Nim",t.Ollama="Ollama",t.OLLAMA_CHAT="Ollama Chat",t.OOBABOOGA="Oobabooga",t.OpenAI="OpenAI",t.OPENAI_LIKE="Openai Like",t.OpenAI_Compatible="OpenAI-Compatible Endpoints (Together AI, etc.)",t.OpenAI_Text="OpenAI Text Completion",t.OpenAI_Text_Compatible="OpenAI-Compatible Text Completion Models (Together AI, etc.)",t.Openrouter="Openrouter",t.Oracle="Oracle Cloud Infrastructure (OCI)",t.OVHCLOUD="Ovhcloud",t.Perplexity="Perplexity",t.PETALS="Petals",t.PG_VECTOR="Pg Vector",t.PREDIBASE="Predibase",t.RECRAFT="Recraft",t.REPLICATE="Replicate",t.RunwayML="RunwayML",t.SAGEMAKER_LEGACY="Sagemaker",t.Sambanova="Sambanova",t.SAP="SAP Generative AI Hub",t.Snowflake="Snowflake",t.TEXT_COMPLETION_CODESTRAL="Text-Completion-Codestral",t.TogetherAI="TogetherAI",t.TOPAZ="Topaz",t.Triton="Triton",t.V0="V0",t.VERCEL_AI_GATEWAY="Vercel Ai Gateway",t.Vertex_AI="Vertex AI (Anthropic, Gemini, etc.)",t.VERTEX_AI_BETA="Vertex Ai Beta",t.VLLM="Vllm",t.VolcEngine="VolcEngine",t.Voyage="Voyage AI",t.WANDB="Wandb",t.WATSONX="Watsonx",t.WATSONX_TEXT="Watsonx Text",t.xAI="xAI",t.XINFERENCE="Xinference",t);let s={A2A_Agent:"a2a_agent",AI21:"ai21",AI21_CHAT:"ai21_chat",AIML:"aiml",AIOHTTP_OPENAI:"aiohttp_openai",Anthropic:"anthropic",ANTHROPIC_TEXT:"anthropic_text",AssemblyAI:"assemblyai",AUTO_ROUTER:"auto_router",Azure:"azure",Azure_AI_Studio:"azure_ai",AZURE_TEXT:"azure_text",BASETEN:"baseten",Bedrock:"bedrock",BedrockMantle:"bedrock_mantle",BYTEZ:"bytez",Cerebras:"cerebras",CLARIFAI:"clarifai",CLOUDFLARE:"cloudflare",CODESTRAL:"codestral",Cohere:"cohere",COHERE_CHAT:"cohere_chat",COMETAPI:"cometapi",COMPACTIFAI:"compactifai",Cursor:"cursor",Dashscope:"dashscope",Databricks:"databricks",DATAROBOT:"datarobot",DeepInfra:"deepinfra",Deepgram:"deepgram",Deepseek:"deepseek",DOCKER_MODEL_RUNNER:"docker_model_runner",DOTPROMPT:"dotprompt",ElevenLabs:"elevenlabs",EMPOWER:"empower",FalAI:"fal_ai",FEATHERLESS_AI:"featherless_ai",FireworksAI:"fireworks_ai",FRIENDLIAI:"friendliai",GALADRIEL:"galadriel",GITHUB_COPILOT:"github_copilot",Google_AI_Studio:"gemini",GradientAI:"gradient_ai",Groq:"groq",HEROKU:"heroku",Hosted_Vllm:"hosted_vllm",HUGGINGFACE:"huggingface",HYPERBOLIC:"hyperbolic",Infinity:"infinity",JinaAI:"jina_ai",LAMBDA_AI:"lambda_ai",LEMONADE:"lemonade",LLAMAFILE:"llamafile",LLAMA:"meta_llama",LM_STUDIO:"lm_studio",MARITALK:"maritalk",MiniMax:"minimax",MistralAI:"mistral",MOONSHOT:"moonshot",MORPH:"morph",NEBIUS:"nebius",NLP_CLOUD:"nlp_cloud",NOVITA:"novita",NSCALE:"nscale",NVIDIA_NIM:"nvidia_nim",Ollama:"ollama",OLLAMA_CHAT:"ollama_chat",OOBABOOGA:"oobabooga",OpenAI:"openai",OPENAI_LIKE:"openai_like",OpenAI_Compatible:"openai",OpenAI_Text:"text-completion-openai",OpenAI_Text_Compatible:"text-completion-openai",Openrouter:"openrouter",Oracle:"oci",OVHCLOUD:"ovhcloud",Perplexity:"perplexity",PETALS:"petals",PG_VECTOR:"pg_vector",PREDIBASE:"predibase",RECRAFT:"recraft",REPLICATE:"replicate",RunwayML:"runwayml",SAGEMAKER_LEGACY:"sagemaker",SageMaker:"sagemaker_chat",Sambanova:"sambanova",SAP:"sap",Snowflake:"snowflake",TEXT_COMPLETION_CODESTRAL:"text-completion-codestral",TogetherAI:"together_ai",TOPAZ:"topaz",Triton:"triton",V0:"v0",VERCEL_AI_GATEWAY:"vercel_ai_gateway",Vertex_AI:"vertex_ai",VERTEX_AI_BETA:"vertex_ai_beta",VLLM:"vllm",VolcEngine:"volcengine",Voyage:"voyage",WANDB:"wandb",WATSONX:"watsonx",WATSONX_TEXT:"watsonx_text",xAI:"xai",XINFERENCE:"xinference"},r="../ui/assets/logos/",i={"A2A Agent":`${r}a2a_agent.png`,Ai21:`${r}ai21.svg`,"Ai21 Chat":`${r}ai21.svg`,"AI/ML API":`${r}aiml_api.svg`,"Aiohttp Openai":`${r}openai_small.svg`,Anthropic:`${r}anthropic.svg`,"Anthropic Text":`${r}anthropic.svg`,AssemblyAI:`${r}assemblyai_small.png`,Azure:`${r}microsoft_azure.svg`,"Azure AI Foundry (Studio)":`${r}microsoft_azure.svg`,"Azure Text":`${r}microsoft_azure.svg`,Baseten:`${r}baseten.svg`,"Amazon Bedrock":`${r}bedrock.svg`,"Amazon Bedrock Mantle":`${r}bedrock.svg`,"AWS SageMaker":`${r}bedrock.svg`,Cerebras:`${r}cerebras.svg`,Cloudflare:`${r}cloudflare.svg`,Codestral:`${r}mistral.svg`,Cohere:`${r}cohere.svg`,"Cohere Chat":`${r}cohere.svg`,Cometapi:`${r}cometapi.svg`,Cursor:`${r}cursor.svg`,"Databricks (Qwen API)":`${r}databricks.svg`,Dashscope:`${r}dashscope.svg`,Deepseek:`${r}deepseek.svg`,Deepgram:`${r}deepgram.png`,DeepInfra:`${r}deepinfra.png`,ElevenLabs:`${r}elevenlabs.png`,"Fal AI":`${r}fal_ai.jpg`,"Featherless Ai":`${r}featherless.svg`,"Fireworks AI":`${r}fireworks.svg`,Friendliai:`${r}friendli.svg`,"Github Copilot":`${r}github_copilot.svg`,"Google AI Studio":`${r}google.svg`,GradientAI:`${r}gradientai.svg`,Groq:`${r}groq.svg`,vllm:`${r}vllm.png`,Huggingface:`${r}huggingface.svg`,Hyperbolic:`${r}hyperbolic.svg`,Infinity:`${r}infinity.png`,"Jina AI":`${r}jina.png`,"Lambda Ai":`${r}lambda.svg`,"Lm Studio":`${r}lmstudio.svg`,"Meta Llama":`${r}meta_llama.svg`,MiniMax:`${r}minimax.svg`,"Mistral AI":`${r}mistral.svg`,Moonshot:`${r}moonshot.svg`,Morph:`${r}morph.svg`,Nebius:`${r}nebius.svg`,Novita:`${r}novita.svg`,"Nvidia Nim":`${r}nvidia_nim.svg`,Ollama:`${r}ollama.svg`,"Ollama Chat":`${r}ollama.svg`,Oobabooga:`${r}openai_small.svg`,OpenAI:`${r}openai_small.svg`,"Openai Like":`${r}openai_small.svg`,"OpenAI Text Completion":`${r}openai_small.svg`,"OpenAI-Compatible Text Completion Models (Together AI, etc.)":`${r}openai_small.svg`,"OpenAI-Compatible Endpoints (Together AI, etc.)":`${r}openai_small.svg`,Openrouter:`${r}openrouter.svg`,"Oracle Cloud Infrastructure (OCI)":`${r}oracle.svg`,Perplexity:`${r}perplexity-ai.svg`,Recraft:`${r}recraft.svg`,Replicate:`${r}replicate.svg`,RunwayML:`${r}runwayml.png`,Sagemaker:`${r}bedrock.svg`,Sambanova:`${r}sambanova.svg`,"SAP Generative AI Hub":`${r}sap.png`,Snowflake:`${r}snowflake.svg`,"Text-Completion-Codestral":`${r}mistral.svg`,TogetherAI:`${r}togetherai.svg`,Topaz:`${r}topaz.svg`,Triton:`${r}nvidia_triton.png`,V0:`${r}v0.svg`,"Vercel Ai Gateway":`${r}vercel.svg`,"Vertex AI (Anthropic, Gemini, etc.)":`${r}google.svg`,"Vertex Ai Beta":`${r}google.svg`,Vllm:`${r}vllm.png`,VolcEngine:`${r}volcengine.png`,"Voyage AI":`${r}voyage.webp`,Watsonx:`${r}watsonx.svg`,"Watsonx Text":`${r}watsonx.svg`,xAI:`${r}xai.svg`,Xinference:`${r}xinference.svg`};e.s(["Providers",()=>a,"getPlaceholder",0,e=>{if("AI/ML API"===e)return"aiml/flux-pro/v1.1";if("Vertex AI (Anthropic, Gemini, etc.)"===e)return"gemini-pro";if("Anthropic"==e)return"claude-3-opus";if("Amazon Bedrock"==e)return"claude-3-opus";if("AWS SageMaker"==e)return"sagemaker/jumpstart-dft-meta-textgeneration-llama-2-7b";else if("Google AI Studio"==e)return"gemini-pro";else if("Azure AI Foundry (Studio)"==e)return"azure_ai/command-r-plus";else if("Azure"==e)return"my-deployment";else if("Oracle Cloud Infrastructure (OCI)"==e)return"oci/xai.grok-4";else if("Snowflake"==e)return"snowflake/mistral-7b";else if("Voyage AI"==e)return"voyage/";else if("Jina AI"==e)return"jina_ai/";else if("VolcEngine"==e)return"volcengine/";else if("DeepInfra"==e)return"deepinfra/";else if("Fal AI"==e)return"fal_ai/fal-ai/flux-pro/v1.1-ultra";else if("RunwayML"==e)return"runwayml/gen4_turbo";else if("Watsonx"===e)return"watsonx/ibm/granite-3-3-8b-instruct";else if("Cursor"===e)return"cursor/claude-4-sonnet";else return"gpt-3.5-turbo"},"getProviderLogoAndName",0,e=>{if(!e)return{logo:"",displayName:"-"};if("gemini"===e.toLowerCase()){let e="Google AI Studio";return{logo:i[e],displayName:e}}let t=Object.keys(s).find(t=>s[t].toLowerCase()===e.toLowerCase());if(!t)return{logo:"",displayName:e};let r=a[t];return{logo:i[r],displayName:r}},"getProviderModels",0,(e,t)=>{console.log(`Provider key: ${e}`);let a=s[e];console.log(`Provider mapped to: ${a}`);let r=[];return e&&"object"==typeof t&&(Object.entries(t).forEach(([e,t])=>{if(null!==t&&"object"==typeof t&&"litellm_provider"in t){let s=t.litellm_provider;(s===a||"string"==typeof s&&s.includes(a))&&r.push(e)}}),"Cohere"==e&&(console.log("Adding cohere chat models"),Object.entries(t).forEach(([e,t])=>{null!==t&&"object"==typeof t&&"litellm_provider"in t&&"cohere_chat"===t.litellm_provider&&r.push(e)})),"AWS SageMaker"==e&&(console.log("Adding sagemaker chat models"),Object.entries(t).forEach(([e,t])=>{null!==t&&"object"==typeof t&&"litellm_provider"in t&&"sagemaker_chat"===t.litellm_provider&&r.push(e)}))),r},"providerLogoMap",0,i,"provider_map",0,s])},798496,e=>{"use strict";var t=e.i(843476),a=e.i(152990),s=e.i(682830),r=e.i(271645),i=e.i(269200),l=e.i(427612),n=e.i(64848),o=e.i(942232),c=e.i(496020),d=e.i(977572),m=e.i(94629),p=e.i(360820),u=e.i(871943);function g({data:e=[],columns:g,isLoading:x=!1,defaultSorting:h=[],pagination:_,onPaginationChange:f,enablePagination:b=!1}){let[v,j]=r.default.useState(h),[A]=r.default.useState("onChange"),[y,N]=r.default.useState({}),[T,C]=r.default.useState({}),S=(0,a.useReactTable)({data:e,columns:g,state:{sorting:v,columnSizing:y,columnVisibility:T,...b&&_?{pagination:_}:{}},columnResizeMode:A,onSortingChange:j,onColumnSizingChange:N,onColumnVisibilityChange:C,...b&&f?{onPaginationChange:f}:{},getCoreRowModel:(0,s.getCoreRowModel)(),getSortedRowModel:(0,s.getSortedRowModel)(),...b?{getPaginationRowModel:(0,s.getPaginationRowModel)()}:{},enableSorting:!0,enableColumnResizing:!0,defaultColumn:{minSize:40,maxSize:500}});return(0,t.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,t.jsx)("div",{className:"overflow-x-auto",children:(0,t.jsx)("div",{className:"relative min-w-full",children:(0,t.jsxs)(i.Table,{className:"[&_td]:py-2 [&_th]:py-2",style:{width:S.getTotalSize(),minWidth:"100%",tableLayout:"fixed"},children:[(0,t.jsx)(l.TableHead,{children:S.getHeaderGroups().map(e=>(0,t.jsx)(c.TableRow,{children:e.headers.map(e=>(0,t.jsxs)(n.TableHeaderCell,{className:`py-1 h-8 relative ${"actions"===e.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)] w-[120px] ml-8":""} ${e.column.columnDef.meta?.className||""}`,style:{width:"actions"===e.id?120:e.getSize(),position:"actions"===e.id?"sticky":"relative",right:"actions"===e.id?0:"auto"},onClick:e.column.getCanSort()?e.column.getToggleSortingHandler():void 0,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,a.flexRender)(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)(p.ChevronUpIcon,{className:"h-4 w-4 text-blue-500"}),desc:(0,t.jsx)(u.ChevronDownIcon,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,t.jsx)(m.SwitchVerticalIcon,{className:"h-4 w-4 text-gray-400"})})]}),e.column.getCanResize()&&(0,t.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 ${e.column.getIsResizing()?"bg-blue-500":"hover:bg-blue-200"}`})]},e.id))},e.id))}),(0,t.jsx)(o.TableBody,{children:x?(0,t.jsx)(c.TableRow,{children:(0,t.jsx)(d.TableCell,{colSpan:g.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:"🚅 Loading models..."})})})}):S.getRowModel().rows.length>0?S.getRowModel().rows.map(e=>(0,t.jsx)(c.TableRow,{children:e.getVisibleCells().map(e=>(0,t.jsx)(d.TableCell,{className:`py-0.5 overflow-hidden ${"actions"===e.column.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)] w-[120px] ml-8":""} ${e.column.columnDef.meta?.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,a.flexRender)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,t.jsx)(c.TableRow,{children:(0,t.jsx)(d.TableCell,{colSpan:g.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:"No models found"})})})})})]})})})})}e.s(["ModelDataTable",()=>g])},976883,174886,e=>{"use strict";var t=e.i(843476),a=e.i(275144),s=e.i(434626),r=e.i(271645);let i=r.forwardRef(function(e,t){return r.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:t},e),r.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"}))});var l=e.i(994388),n=e.i(304967),o=e.i(599724),c=e.i(629569),d=e.i(212931),m=e.i(199133),p=e.i(653496),u=e.i(262218),g=e.i(592968),x=e.i(991124);e.s(["Copy",()=>x.default],174886);var x=x,h=e.i(879664),h=h,_=e.i(798496),f=e.i(727749),b=e.i(402874),v=e.i(764205),j=e.i(190272),A=e.i(785913),y=e.i(916925);let{TabPane:N}=p.Tabs;e.s(["default",0,({accessToken:e,isEmbedded:T=!1})=>{let C,S,I,w,E,O,M,[k,L]=(0,r.useState)(null),[R,P]=(0,r.useState)(null),[$,D]=(0,r.useState)(null),[z,H]=(0,r.useState)("LiteLLM Gateway"),[G,F]=(0,r.useState)(null),[U,B]=(0,r.useState)(""),[V,K]=(0,r.useState)({}),[W,X]=(0,r.useState)(!0),[q,Y]=(0,r.useState)(!0),[J,Z]=(0,r.useState)(!0),[Q,ee]=(0,r.useState)(""),[et,ea]=(0,r.useState)(""),[es,er]=(0,r.useState)(""),[ei,el]=(0,r.useState)([]),[en,eo]=(0,r.useState)([]),[ec,ed]=(0,r.useState)([]),[em,ep]=(0,r.useState)([]),[eu,eg]=(0,r.useState)([]),[ex,eh]=(0,r.useState)("I'm alive! ✓"),[e_,ef]=(0,r.useState)(!1),[eb,ev]=(0,r.useState)(!1),[ej,eA]=(0,r.useState)(!1),[ey,eN]=(0,r.useState)(null),[eT,eC]=(0,r.useState)(null),[eS,eI]=(0,r.useState)(null),[ew,eE]=(0,r.useState)({}),[eO,eM]=(0,r.useState)("models");(0,r.useEffect)(()=>{(async()=>{try{await (0,v.getUiConfig)()}catch(e){console.error("Failed to get UI config:",e)}let e=async()=>{try{X(!0);let e=await (0,v.modelHubPublicModelsCall)();console.log("ModelHubData:",e),L(e)}catch(e){console.error("There was an error fetching the public model data",e),eh("Service unavailable")}finally{X(!1)}},t=async()=>{try{Y(!0);let e=await (0,v.agentHubPublicModelsCall)();console.log("AgentHubData:",e),P(e)}catch(e){console.error("There was an error fetching the public agent data",e)}finally{Y(!1)}},a=async()=>{try{Z(!0);let e=await (0,v.mcpHubPublicServersCall)();console.log("MCPHubData:",e),D(e)}catch(e){console.error("There was an error fetching the public MCP server data",e)}finally{Z(!1)}};(async()=>{let e=await (0,v.getPublicModelHubInfo)();console.log("Public Model Hub Info:",e),H(e.docs_title),F(e.custom_docs_description),B(e.litellm_version),K(e.useful_links||{})})(),e(),t(),a()})()},[]),(0,r.useEffect)(()=>{},[Q,ei,en,ec]);let ek=(0,r.useMemo)(()=>{if(!k||!Array.isArray(k))return[];let e=k;if(Q.trim()){let t=Q.toLowerCase(),a=t.split(/\s+/),s=k.filter(e=>{let s=e.model_group.toLowerCase();return!!s.includes(t)||a.every(e=>s.includes(e))});s.length>0&&(e=s.sort((e,a)=>{let s=e.model_group.toLowerCase(),r=a.model_group.toLowerCase(),i=1e3*(s===t),l=1e3*(r===t),n=100*!!s.startsWith(t),o=100*!!r.startsWith(t),c=50*!!t.split(/\s+/).every(e=>s.includes(e)),d=50*!!t.split(/\s+/).every(e=>r.includes(e)),m=s.length;return l+o+d+(1e3-r.length)-(i+n+c+(1e3-m))}))}return e.filter(e=>{let t=0===ei.length||ei.some(t=>e.providers.includes(t)),a=0===en.length||en.includes(e.mode||""),s=0===ec.length||Object.entries(e).filter(([e,t])=>e.startsWith("supports_")&&!0===t).some(([e])=>{let t=e.replace(/^supports_/,"").split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");return ec.includes(t)});return t&&a&&s})},[k,Q,ei,en,ec]),eL=(0,r.useMemo)(()=>{if(!R||!Array.isArray(R))return[];let e=R;if(et.trim()){let t=et.toLowerCase(),a=t.split(/\s+/);e=(e=R.filter(e=>{let s=e.name.toLowerCase(),r=e.description.toLowerCase();return!!(s.includes(t)||r.includes(t))||a.every(e=>s.includes(e)||r.includes(e))})).sort((e,a)=>{let s=e.name.toLowerCase(),r=a.name.toLowerCase(),i=1e3*(s===t),l=1e3*(r===t),n=100*!!s.startsWith(t),o=100*!!r.startsWith(t),c=i+n+(1e3-s.length);return l+o+(1e3-r.length)-c})}return e.filter(e=>0===em.length||e.skills?.some(e=>e.tags?.some(e=>em.includes(e))))},[R,et,em]),eR=(0,r.useMemo)(()=>{if(!$||!Array.isArray($))return[];let e=$;if(es.trim()){let t=es.toLowerCase(),a=t.split(/\s+/);e=(e=$.filter(e=>{let s=e.server_name.toLowerCase(),r=(e.mcp_info?.description||"").toLowerCase();return!!(s.includes(t)||r.includes(t))||a.every(e=>s.includes(e)||r.includes(e))})).sort((e,a)=>{let s=e.server_name.toLowerCase(),r=a.server_name.toLowerCase(),i=1e3*(s===t),l=1e3*(r===t),n=100*!!s.startsWith(t),o=100*!!r.startsWith(t),c=i+n+(1e3-s.length);return l+o+(1e3-r.length)-c})}return e.filter(e=>0===eu.length||eu.includes(e.transport))},[$,es,eu]),eP=e=>{navigator.clipboard.writeText(e),f.default.success("Copied to clipboard!")},e$=e=>e.replace(/^supports_/,"").split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" "),eD=e=>`$${(1e6*e).toFixed(4)}`,ez=e=>e?e>=1e3?`${(e/1e3).toFixed(0)}K`:e.toString():"N/A";return(0,t.jsx)(a.ThemeProvider,{accessToken:e,children:(0,t.jsxs)("div",{className:T?"w-full":"min-h-screen bg-white",children:[!T&&(0,t.jsx)(b.default,{userID:null,userEmail:null,userRole:null,premiumUser:!1,setProxySettings:eE,proxySettings:ew,accessToken:e||null,isPublicPage:!0,isDarkMode:!1,toggleDarkMode:()=>{}}),(0,t.jsxs)("div",{className:T?"w-full p-6":"w-full px-8 py-12",children:[T&&(0,t.jsx)("div",{className:"mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg",children:(0,t.jsx)("p",{className:"text-sm text-gray-700",children:"These are models, agents, and MCP servers your proxy admin has indicated are available in your company."})}),!T&&(0,t.jsxs)(n.Card,{className:"mb-10 p-8 bg-white border border-gray-200 rounded-lg shadow-sm",children:[(0,t.jsx)(c.Title,{className:"text-2xl font-semibold mb-6 text-gray-900",children:"About"}),(0,t.jsx)("p",{className:"text-gray-700 mb-6 text-base leading-relaxed",children:G||"Proxy Server to call 100+ LLMs in the OpenAI format."}),(0,t.jsx)("div",{className:"flex items-center space-x-3 text-sm text-gray-600",children:(0,t.jsxs)("span",{className:"flex items-center",children:[(0,t.jsx)("span",{className:"w-4 h-4 mr-2",children:"🔧"}),"Built with litellm: v",U]})})]}),V&&Object.keys(V).length>0&&(0,t.jsxs)(n.Card,{className:"mb-10 p-8 bg-white border border-gray-200 rounded-lg shadow-sm",children:[(0,t.jsx)(c.Title,{className:"text-2xl font-semibold mb-6 text-gray-900",children:"Useful Links"}),(0,t.jsx)("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:Object.entries(V||{}).map(([e,t])=>({title:e,url:"string"==typeof t?t:t.url,index:"string"==typeof t?0:t.index??0})).sort((e,t)=>e.index-t.index).map(({title:e,url:a})=>(0,t.jsxs)("button",{onClick:()=>window.open(a,"_blank"),className:"flex items-center space-x-3 text-blue-600 hover:text-blue-800 transition-colors p-3 rounded-lg hover:bg-blue-50 border border-gray-200",children:[(0,t.jsx)(s.ExternalLinkIcon,{className:"w-4 h-4"}),(0,t.jsx)(o.Text,{className:"text-sm font-medium",children:e})]},e))})]}),!T&&(0,t.jsxs)(n.Card,{className:"mb-10 p-8 bg-white border border-gray-200 rounded-lg shadow-sm",children:[(0,t.jsx)(c.Title,{className:"text-2xl font-semibold mb-6 text-gray-900",children:"Health and Endpoint Status"}),(0,t.jsx)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:(0,t.jsxs)(o.Text,{className:"text-green-600 font-medium text-sm",children:["Service status: ",ex]})})]}),(0,t.jsx)(n.Card,{className:"p-8 bg-white border border-gray-200 rounded-lg shadow-sm",children:(0,t.jsxs)(p.Tabs,{activeKey:eO,onChange:eM,size:"large",className:"public-hub-tabs",children:[(0,t.jsxs)(N,{tab:"Model Hub",children:[(0,t.jsx)("div",{className:"flex justify-between items-center mb-8",children:(0,t.jsx)(c.Title,{className:"text-2xl font-semibold text-gray-900",children:"Available Models"})}),(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8 p-6 bg-gray-50 rounded-lg border border-gray-200",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2 mb-3",children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium text-gray-700",children:"Search Models:"}),(0,t.jsx)(g.Tooltip,{title:"Smart search with relevance ranking - finds models containing your search terms, ranked by relevance. Try searching 'xai grok-4', 'claude-4', 'gpt-4', or 'sonnet'",placement:"top",children:(0,t.jsx)(h.default,{className:"w-4 h-4 text-gray-400 cursor-help"})})]}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(i,{className:"w-4 h-4 text-gray-400 absolute left-3 top-1/2 transform -translate-y-1/2"}),(0,t.jsx)("input",{type:"text",placeholder:"Search model names... (smart search enabled)",value:Q,onChange:e=>ee(e.target.value),className:"border border-gray-300 rounded-lg pl-10 pr-4 py-2 w-full text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white"})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium mb-3 text-gray-700",children:"Provider:"}),(0,t.jsx)(m.Select,{mode:"multiple",value:ei,onChange:e=>el(e),placeholder:"Select providers",className:"w-full",size:"large",allowClear:!0,optionRender:e=>{let{logo:a}=(0,y.getProviderLogoAndName)(e.value);return(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[a&&(0,t.jsx)("img",{src:a,alt:e.label,className:"w-5 h-5 flex-shrink-0 object-contain",onError:e=>{e.target.style.display="none"}}),(0,t.jsx)("span",{className:"capitalize",children:e.label})]})},children:k&&Array.isArray(k)&&(C=new Set,k.forEach(e=>{e.providers.forEach(e=>C.add(e))}),Array.from(C)).map(e=>(0,t.jsx)(m.Select.Option,{value:e,children:e},e))})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium mb-3 text-gray-700",children:"Mode:"}),(0,t.jsx)(m.Select,{mode:"multiple",value:en,onChange:e=>eo(e),placeholder:"Select modes",className:"w-full",size:"large",allowClear:!0,children:k&&Array.isArray(k)&&(S=new Set,k.forEach(e=>{e.mode&&S.add(e.mode)}),Array.from(S)).map(e=>(0,t.jsx)(m.Select.Option,{value:e,children:e},e))})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium mb-3 text-gray-700",children:"Features:"}),(0,t.jsx)(m.Select,{mode:"multiple",value:ec,onChange:e=>ed(e),placeholder:"Select features",className:"w-full",size:"large",allowClear:!0,children:k&&Array.isArray(k)&&(I=new Set,k.forEach(e=>{Object.entries(e).filter(([e,t])=>e.startsWith("supports_")&&!0===t).forEach(([e])=>{let t=e.replace(/^supports_/,"").split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");I.add(t)})}),Array.from(I).sort()).map(e=>(0,t.jsx)(m.Select.Option,{value:e,children:e},e))})]})]}),(0,t.jsx)(_.ModelDataTable,{columns:[{header:"Model Name",accessorKey:"model_group",enableSorting:!0,cell:({row:e})=>(0,t.jsx)("div",{className:"overflow-hidden",children:(0,t.jsx)(g.Tooltip,{title:e.original.model_group,children:(0,t.jsx)(l.Button,{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",onClick:()=>{eN(e.original),ef(!0)},children:e.original.model_group})})}),size:150},{header:"Providers",accessorKey:"providers",enableSorting:!0,cell:({row:e})=>{let a=e.original.providers;return(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:a.map(e=>{let{logo:a}=(0,y.getProviderLogoAndName)(e);return(0,t.jsxs)("div",{className:"flex items-center space-x-1 px-2 py-1 bg-gray-100 rounded text-xs",children:[a&&(0,t.jsx)("img",{src:a,alt:e,className:"w-3 h-3 flex-shrink-0 object-contain",onError:e=>{e.target.style.display="none"}}),(0,t.jsx)("span",{className:"capitalize",children:e})]},e)})})},size:120},{header:"Mode",accessorKey:"mode",enableSorting:!0,cell:({row:e})=>{let a=e.original.mode;return(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("span",{children:(e=>{switch(e?.toLowerCase()){case"chat":return"💬";case"rerank":return"🔄";case"embedding":return"📄";default:return"🤖"}})(a||"")}),(0,t.jsx)(o.Text,{children:a||"Chat"})]})},size:100},{header:"Max Input",accessorKey:"max_input_tokens",enableSorting:!0,cell:({row:e})=>(0,t.jsx)(o.Text,{className:"text-center",children:ez(e.original.max_input_tokens)}),size:100,meta:{className:"text-center"}},{header:"Max Output",accessorKey:"max_output_tokens",enableSorting:!0,cell:({row:e})=>(0,t.jsx)(o.Text,{className:"text-center",children:ez(e.original.max_output_tokens)}),size:100,meta:{className:"text-center"}},{header:"Input $/1M",accessorKey:"input_cost_per_token",enableSorting:!0,cell:({row:e})=>{let a=e.original.input_cost_per_token;return(0,t.jsx)(o.Text,{className:"text-center",children:a?eD(a):"Free"})},size:100,meta:{className:"text-center"}},{header:"Output $/1M",accessorKey:"output_cost_per_token",enableSorting:!0,cell:({row:e})=>{let a=e.original.output_cost_per_token;return(0,t.jsx)(o.Text,{className:"text-center",children:a?eD(a):"Free"})},size:100,meta:{className:"text-center"}},{header:"Features",accessorKey:"supports_vision",enableSorting:!1,cell:({row:e})=>{let a=Object.entries(e.original).filter(([e,t])=>e.startsWith("supports_")&&!0===t).map(([e])=>e$(e));return 0===a.length?(0,t.jsx)(o.Text,{className:"text-gray-400",children:"-"}):1===a.length?(0,t.jsx)("div",{className:"h-6 flex items-center",children:(0,t.jsx)(u.Tag,{color:"blue",className:"text-xs",children:a[0]})}):(0,t.jsxs)("div",{className:"h-6 flex items-center space-x-1",children:[(0,t.jsx)(u.Tag,{color:"blue",className:"text-xs",children:a[0]}),(0,t.jsx)(g.Tooltip,{title:(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("div",{className:"font-medium",children:"All Features:"}),a.map((e,a)=>(0,t.jsxs)("div",{className:"text-xs",children:["• ",e]},a))]}),trigger:"click",placement:"topLeft",children:(0,t.jsxs)("span",{className:"text-xs text-blue-600 cursor-pointer hover:text-blue-800 hover:underline",onClick:e=>e.stopPropagation(),children:["+",a.length-1]})})]})},size:120},{header:"Health Status",accessorKey:"health_status",enableSorting:!0,cell:({row:e})=>{let a=e.original,s="healthy"===a.health_status?"green":"unhealthy"===a.health_status?"red":"default",r=a.health_response_time?`Response Time: ${Number(a.health_response_time).toFixed(2)}ms`:"N/A",i=a.health_checked_at?`Last Checked: ${new Date(a.health_checked_at).toLocaleString()}`:"N/A";return(0,t.jsx)(g.Tooltip,{title:(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{children:r}),(0,t.jsx)("div",{children:i})]}),children:(0,t.jsx)(u.Tag,{color:s,children:(0,t.jsx)("span",{className:"capitalize",children:a.health_status??"Unknown"})},a.model_group)})},size:100},{header:"Limits",accessorKey:"rpm",enableSorting:!0,cell:({row:e})=>{var a,s;let r,i=e.original;return(0,t.jsx)(o.Text,{className:"text-xs text-gray-600",children:(a=i.rpm,s=i.tpm,r=[],a&&r.push(`RPM: ${a.toLocaleString()}`),s&&r.push(`TPM: ${s.toLocaleString()}`),r.length>0?r.join(", "):"N/A")})},size:150}],data:ek,isLoading:W,defaultSorting:[{id:"model_group",desc:!1}]}),(0,t.jsx)("div",{className:"mt-8 text-center",children:(0,t.jsxs)(o.Text,{className:"text-sm text-gray-600",children:["Showing ",ek.length," of ",k?.length||0," models"]})})]},"models"),R&&Array.isArray(R)&&R.length>0&&(0,t.jsxs)(N,{tab:"Agent Hub",children:[(0,t.jsx)("div",{className:"flex justify-between items-center mb-8",children:(0,t.jsx)(c.Title,{className:"text-2xl font-semibold text-gray-900",children:"Available Agents"})}),(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6 mb-8 p-6 bg-gray-50 rounded-lg border border-gray-200",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2 mb-3",children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium text-gray-700",children:"Search Agents:"}),(0,t.jsx)(g.Tooltip,{title:"Search agents by name or description",placement:"top",children:(0,t.jsx)(h.default,{className:"w-4 h-4 text-gray-400 cursor-help"})})]}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(i,{className:"w-4 h-4 text-gray-400 absolute left-3 top-1/2 transform -translate-y-1/2"}),(0,t.jsx)("input",{type:"text",placeholder:"Search agent names or descriptions...",value:et,onChange:e=>ea(e.target.value),className:"border border-gray-300 rounded-lg pl-10 pr-4 py-2 w-full text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white"})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium mb-3 text-gray-700",children:"Skills:"}),(0,t.jsx)(m.Select,{mode:"multiple",value:em,onChange:e=>ep(e),placeholder:"Select skills",className:"w-full",size:"large",allowClear:!0,children:R&&Array.isArray(R)&&(w=new Set,R.forEach(e=>{e.skills?.forEach(e=>{e.tags?.forEach(e=>w.add(e))})}),Array.from(w).sort()).map(e=>(0,t.jsx)(m.Select.Option,{value:e,children:e},e))})]})]}),(0,t.jsx)(_.ModelDataTable,{columns:[{header:"Agent Name",accessorKey:"name",enableSorting:!0,cell:({row:e})=>(0,t.jsx)("div",{className:"overflow-hidden",children:(0,t.jsx)(g.Tooltip,{title:e.original.name,children:(0,t.jsx)(l.Button,{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",onClick:()=>{eC(e.original),ev(!0)},children:e.original.name})})}),size:150},{header:"Description",accessorKey:"description",enableSorting:!1,cell:({row:e})=>{let a=e.original.description,s=a.length>80?a.substring(0,80)+"...":a;return(0,t.jsx)(g.Tooltip,{title:a,children:(0,t.jsx)(o.Text,{className:"text-sm text-gray-700",children:s})})},size:250},{header:"Version",accessorKey:"version",enableSorting:!0,cell:({row:e})=>(0,t.jsx)(o.Text,{className:"text-sm",children:e.original.version}),size:80},{header:"Provider",accessorKey:"provider",enableSorting:!1,cell:({row:e})=>{let a=e.original.provider;return a?(0,t.jsx)("div",{className:"text-sm",children:(0,t.jsx)(o.Text,{className:"font-medium",children:a.organization})}):(0,t.jsx)(o.Text,{className:"text-gray-400",children:"-"})},size:120},{header:"Skills",accessorKey:"skills",enableSorting:!1,cell:({row:e})=>{let a=e.original.skills||[];return 0===a.length?(0,t.jsx)(o.Text,{className:"text-gray-400",children:"-"}):1===a.length?(0,t.jsx)("div",{className:"h-6 flex items-center",children:(0,t.jsx)(u.Tag,{color:"purple",className:"text-xs",children:a[0].name})}):(0,t.jsxs)("div",{className:"h-6 flex items-center space-x-1",children:[(0,t.jsx)(u.Tag,{color:"purple",className:"text-xs",children:a[0].name}),(0,t.jsx)(g.Tooltip,{title:(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("div",{className:"font-medium",children:"All Skills:"}),a.map((e,a)=>(0,t.jsxs)("div",{className:"text-xs",children:["• ",e.name]},a))]}),trigger:"click",placement:"topLeft",children:(0,t.jsxs)("span",{className:"text-xs text-purple-600 cursor-pointer hover:text-purple-800 hover:underline",onClick:e=>e.stopPropagation(),children:["+",a.length-1]})})]})},size:150},{header:"Capabilities",accessorKey:"capabilities",enableSorting:!1,cell:({row:e})=>{let a=Object.entries(e.original.capabilities||{}).filter(([e,t])=>!0===t).map(([e])=>e);return 0===a.length?(0,t.jsx)(o.Text,{className:"text-gray-400",children:"-"}):(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:a.map(e=>(0,t.jsx)(u.Tag,{color:"green",className:"text-xs capitalize",children:e},e))})},size:150}],data:eL,isLoading:q,defaultSorting:[{id:"name",desc:!1}]}),(0,t.jsx)("div",{className:"mt-8 text-center",children:(0,t.jsxs)(o.Text,{className:"text-sm text-gray-600",children:["Showing ",eL.length," of ",R?.length||0," agents"]})})]},"agents"),$&&Array.isArray($)&&$.length>0&&(0,t.jsxs)(N,{tab:"MCP Hub",children:[(0,t.jsx)("div",{className:"flex justify-between items-center mb-8",children:(0,t.jsx)(c.Title,{className:"text-2xl font-semibold text-gray-900",children:"Available MCP Servers"})}),(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6 mb-8 p-6 bg-gray-50 rounded-lg border border-gray-200",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2 mb-3",children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium text-gray-700",children:"Search MCP Servers:"}),(0,t.jsx)(g.Tooltip,{title:"Search MCP servers by name or description",placement:"top",children:(0,t.jsx)(h.default,{className:"w-4 h-4 text-gray-400 cursor-help"})})]}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(i,{className:"w-4 h-4 text-gray-400 absolute left-3 top-1/2 transform -translate-y-1/2"}),(0,t.jsx)("input",{type:"text",placeholder:"Search MCP server names or descriptions...",value:es,onChange:e=>er(e.target.value),className:"border border-gray-300 rounded-lg pl-10 pr-4 py-2 w-full text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white"})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium mb-3 text-gray-700",children:"Transport:"}),(0,t.jsx)(m.Select,{mode:"multiple",value:eu,onChange:e=>eg(e),placeholder:"Select transport types",className:"w-full",size:"large",allowClear:!0,children:$&&Array.isArray($)&&(E=new Set,$.forEach(e=>{e.transport&&E.add(e.transport)}),Array.from(E).sort()).map(e=>(0,t.jsx)(m.Select.Option,{value:e,children:e},e))})]})]}),(0,t.jsx)(_.ModelDataTable,{columns:[{header:"Server Name",accessorKey:"server_name",enableSorting:!0,cell:({row:e})=>(0,t.jsx)("div",{className:"overflow-hidden",children:(0,t.jsx)(g.Tooltip,{title:e.original.server_name,children:(0,t.jsx)(l.Button,{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",onClick:()=>{eI(e.original),eA(!0)},children:e.original.server_name})})}),size:150},{header:"Description",accessorKey:"mcp_info.description",enableSorting:!1,cell:({row:e})=>{let a=e.original.mcp_info?.description||"-",s=a.length>80?a.substring(0,80)+"...":a;return(0,t.jsx)(g.Tooltip,{title:a,children:(0,t.jsx)(o.Text,{className:"text-sm text-gray-700",children:s})})},size:250},{header:"URL",accessorKey:"url",enableSorting:!1,cell:({row:e})=>{let a=e.original.url,s=a.length>40?a.substring(0,40)+"...":a;return(0,t.jsx)(g.Tooltip,{title:a,children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)(o.Text,{className:"text-xs font-mono",children:s}),(0,t.jsx)(x.default,{onClick:()=>eP(a),className:"cursor-pointer text-gray-500 hover:text-blue-500 w-3 h-3"})]})})},size:200},{header:"Transport",accessorKey:"transport",enableSorting:!0,cell:({row:e})=>{let a=e.original.transport;return(0,t.jsx)(u.Tag,{color:"blue",className:"text-xs uppercase",children:a})},size:100},{header:"Auth Type",accessorKey:"auth_type",enableSorting:!0,cell:({row:e})=>{let a=e.original.auth_type;return(0,t.jsx)(u.Tag,{color:"none"===a?"gray":"green",className:"text-xs capitalize",children:a})},size:100}],data:eR,isLoading:J,defaultSorting:[{id:"server_name",desc:!1}]}),(0,t.jsx)("div",{className:"mt-8 text-center",children:(0,t.jsxs)(o.Text,{className:"text-sm text-gray-600",children:["Showing ",eR.length," of ",$?.length||0," MCP servers"]})})]},"mcp")]})})]}),(0,t.jsx)(d.Modal,{title:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("span",{children:ey?.model_group||"Model Details"}),ey&&(0,t.jsx)(g.Tooltip,{title:"Copy model name",children:(0,t.jsx)(x.default,{onClick:()=>eP(ey.model_group),className:"cursor-pointer text-gray-500 hover:text-blue-500 w-4 h-4"})})]}),width:1e3,open:e_,footer:null,onOk:()=>{ef(!1),eN(null)},onCancel:()=>{ef(!1),eN(null)},children:ey&&(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Model Overview"}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-4 mb-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Model Name:"}),(0,t.jsx)(o.Text,{children:ey.model_group})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Mode:"}),(0,t.jsx)(o.Text,{children:ey.mode||"Not specified"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Providers:"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-1 mt-1",children:ey.providers.map(e=>{let{logo:a}=(0,y.getProviderLogoAndName)(e);return(0,t.jsx)(u.Tag,{color:"blue",children:(0,t.jsxs)("div",{className:"flex items-center space-x-1",children:[a&&(0,t.jsx)("img",{src:a,alt:e,className:"w-3 h-3 flex-shrink-0 object-contain",onError:e=>{e.target.style.display="none"}}),(0,t.jsx)("span",{className:"capitalize",children:e})]})},e)})})]})]}),ey.model_group.includes("*")&&(0,t.jsx)("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 mb-4",children:(0,t.jsxs)("div",{className:"flex items-start space-x-2",children:[(0,t.jsx)(h.default,{className:"w-4 h-4 text-blue-600 mt-0.5 flex-shrink-0"}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium text-blue-900 mb-2",children:"Wildcard Routing"}),(0,t.jsxs)(o.Text,{className:"text-sm text-blue-800 mb-2",children:["This model uses wildcard routing. You can pass any value where you see the"," ",(0,t.jsx)("code",{className:"bg-blue-100 px-1 py-0.5 rounded text-xs",children:"*"})," symbol."]}),(0,t.jsxs)(o.Text,{className:"text-sm text-blue-800",children:["For example, with"," ",(0,t.jsx)("code",{className:"bg-blue-100 px-1 py-0.5 rounded text-xs",children:ey.model_group}),", you can use any string (",(0,t.jsx)("code",{className:"bg-blue-100 px-1 py-0.5 rounded text-xs",children:ey.model_group.replace("*","my-custom-value")}),") that matches this pattern."]})]})]})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Token & Cost Information"}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Max Input Tokens:"}),(0,t.jsx)(o.Text,{children:ey.max_input_tokens?.toLocaleString()||"Not specified"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Max Output Tokens:"}),(0,t.jsx)(o.Text,{children:ey.max_output_tokens?.toLocaleString()||"Not specified"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Input Cost per 1M Tokens:"}),(0,t.jsx)(o.Text,{children:ey.input_cost_per_token?eD(ey.input_cost_per_token):"Not specified"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Output Cost per 1M Tokens:"}),(0,t.jsx)(o.Text,{children:ey.output_cost_per_token?eD(ey.output_cost_per_token):"Not specified"})]})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Capabilities"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:(O=Object.entries(ey).filter(([e,t])=>e.startsWith("supports_")&&!0===t).map(([e])=>e),M=["green","blue","purple","orange","red","yellow"],0===O.length?(0,t.jsx)(o.Text,{className:"text-gray-500",children:"No special capabilities listed"}):O.map((e,a)=>(0,t.jsx)(u.Tag,{color:M[a%M.length],children:e$(e)},e)))})]}),(ey.tpm||ey.rpm)&&(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Rate Limits"}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-4",children:[ey.tpm&&(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Tokens per Minute:"}),(0,t.jsx)(o.Text,{children:ey.tpm.toLocaleString()})]}),ey.rpm&&(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Requests per Minute:"}),(0,t.jsx)(o.Text,{children:ey.rpm.toLocaleString()})]})]})]}),ey.supported_openai_params&&(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Supported OpenAI Parameters"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:ey.supported_openai_params.map(e=>(0,t.jsx)(u.Tag,{color:"green",children:e},e))})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Usage Example"}),(0,t.jsx)("div",{className:"bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto",children:(0,t.jsx)("pre",{className:"text-sm",children:(0,j.generateCodeSnippet)({apiKeySource:"custom",accessToken:null,apiKey:"your_api_key",inputMessage:"Hello, how are you?",chatHistory:[{role:"user",content:"Hello, how are you?",isImage:!1}],selectedTags:[],selectedVectorStores:[],selectedGuardrails:[],selectedPolicies:[],selectedMCPServers:[],endpointType:(0,A.getEndpointType)(ey.mode||"chat"),selectedModel:ey.model_group,selectedSdk:"openai"})})}),(0,t.jsx)("div",{className:"mt-2 text-right",children:(0,t.jsx)("button",{onClick:()=>{eP((0,j.generateCodeSnippet)({apiKeySource:"custom",accessToken:null,apiKey:"your_api_key",inputMessage:"Hello, how are you?",chatHistory:[{role:"user",content:"Hello, how are you?",isImage:!1}],selectedTags:[],selectedVectorStores:[],selectedGuardrails:[],selectedPolicies:[],selectedMCPServers:[],endpointType:(0,A.getEndpointType)(ey.mode||"chat"),selectedModel:ey.model_group,selectedSdk:"openai"}))},className:"text-sm text-blue-600 hover:text-blue-800 cursor-pointer",children:"Copy to clipboard"})})]})]})}),(0,t.jsx)(d.Modal,{title:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("span",{children:eT?.name||"Agent Details"}),eT&&(0,t.jsx)(g.Tooltip,{title:"Copy agent name",children:(0,t.jsx)(x.default,{onClick:()=>eP(eT.name),className:"cursor-pointer text-gray-500 hover:text-blue-500 w-4 h-4"})})]}),width:1e3,open:eb,footer:null,onOk:()=>{ev(!1),eC(null)},onCancel:()=>{ev(!1),eC(null)},children:eT&&(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Agent Overview"}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-4 mb-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Name:"}),(0,t.jsx)(o.Text,{children:eT.name})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Version:"}),(0,t.jsx)(o.Text,{children:eT.version})]}),(0,t.jsxs)("div",{className:"col-span-2",children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Description:"}),(0,t.jsx)(o.Text,{children:eT.description})]}),eT.url&&(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"URL:"}),(0,t.jsx)("a",{href:eT.url,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 text-sm break-all",children:eT.url})]})]})]}),eT.capabilities&&(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Capabilities"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:Object.entries(eT.capabilities).filter(([e,t])=>!0===t).map(([e])=>(0,t.jsx)(u.Tag,{color:"green",className:"capitalize",children:e},e))})]}),eT.skills&&eT.skills.length>0&&(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Skills"}),(0,t.jsx)("div",{className:"space-y-4",children:eT.skills.map((e,a)=>(0,t.jsxs)("div",{className:"border border-gray-200 rounded-lg p-4",children:[(0,t.jsx)("div",{className:"flex items-start justify-between mb-2",children:(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium text-base",children:e.name}),(0,t.jsx)(o.Text,{className:"text-sm text-gray-600",children:e.description})]})}),e.tags&&e.tags.length>0&&(0,t.jsx)("div",{className:"flex flex-wrap gap-1 mt-2",children:e.tags.map(e=>(0,t.jsx)(u.Tag,{color:"purple",className:"text-xs",children:e},e))})]},a))})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Input/Output Modes"}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Input Modes:"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-1 mt-1",children:eT.defaultInputModes?.map(e=>(0,t.jsx)(u.Tag,{color:"blue",children:e},e))})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Output Modes:"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-1 mt-1",children:eT.defaultOutputModes?.map(e=>(0,t.jsx)(u.Tag,{color:"blue",children:e},e))})]})]})]}),eT.documentationUrl&&(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Documentation"}),(0,t.jsxs)("a",{href:eT.documentationUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 flex items-center space-x-2",children:[(0,t.jsx)(s.ExternalLinkIcon,{className:"w-4 h-4"}),(0,t.jsx)("span",{children:"View Documentation"})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Usage Example (A2A Protocol)"}),(0,t.jsxs)("div",{className:"mb-4",children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium mb-2 text-gray-700",children:"Step 1: Retrieve Agent Card"}),(0,t.jsx)("div",{className:"bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto",children:(0,t.jsx)("pre",{className:"text-xs",children:`base_url = '${eT.url}' - -resolver = A2ACardResolver( - httpx_client=httpx_client, - base_url=base_url, - # agent_card_path uses default, extended_agent_card_path also uses default -) - -# Fetch Public Agent Card and Initialize Client -final_agent_card_to_use: AgentCard | None = None -_public_card = ( - await resolver.get_agent_card() -) # Fetches from default public path - \`/agents/{agent_id}/\` -final_agent_card_to_use = _public_card - -if _public_card.supports_authenticated_extended_card: - try: - auth_headers_dict = { - 'Authorization': 'Bearer dummy-token-for-extended-card' - } - _extended_card = await resolver.get_agent_card( - relative_card_path=EXTENDED_AGENT_CARD_PATH, - http_kwargs={'headers': auth_headers_dict}, - ) - final_agent_card_to_use = ( - _extended_card # Update to use the extended card - ) - except Exception as e_extended: - logger.warning( - f'Failed to fetch extended agent card: {e_extended}. Will proceed with public card.', - exc_info=True, - )`})}),(0,t.jsx)("div",{className:"mt-2 text-right",children:(0,t.jsx)("button",{onClick:()=>{eP(`from a2a.client import A2ACardResolver, A2AClient -from a2a.types import ( - AgentCard, - MessageSendParams, - SendMessageRequest, - SendStreamingMessageRequest, -) -from a2a.utils.constants import ( - AGENT_CARD_WELL_KNOWN_PATH, - EXTENDED_AGENT_CARD_PATH, -) - -base_url = '${eT.url}' - -resolver = A2ACardResolver( - httpx_client=httpx_client, - base_url=base_url, - # agent_card_path uses default, extended_agent_card_path also uses default -) - -# Fetch Public Agent Card and Initialize Client -final_agent_card_to_use: AgentCard | None = None -_public_card = ( - await resolver.get_agent_card() -) # Fetches from default public path - \`/agents/{agent_id}/\` -final_agent_card_to_use = _public_card - -if _public_card.supports_authenticated_extended_card: - try: - auth_headers_dict = { - 'Authorization': 'Bearer dummy-token-for-extended-card' - } - _extended_card = await resolver.get_agent_card( - relative_card_path=EXTENDED_AGENT_CARD_PATH, - http_kwargs={'headers': auth_headers_dict}, - ) - final_agent_card_to_use = ( - _extended_card # Update to use the extended card - ) - except Exception as e_extended: - logger.warning( - f'Failed to fetch extended agent card: {e_extended}. Will proceed with public card.', - exc_info=True, - )`)},className:"text-sm text-blue-600 hover:text-blue-800 cursor-pointer",children:"Copy to clipboard"})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium mb-2 text-gray-700",children:"Step 2: Call the Agent"}),(0,t.jsx)("div",{className:"bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto",children:(0,t.jsx)("pre",{className:"text-xs",children:`client = A2AClient( - httpx_client=httpx_client, agent_card=final_agent_card_to_use -) - -send_message_payload: dict[str, Any] = { - 'message': { - 'role': 'user', - 'parts': [ - {'kind': 'text', 'text': 'how much is 10 USD in INR?'} - ], - 'messageId': uuid4().hex, - }, -} -request = SendMessageRequest( - id=str(uuid4()), params=MessageSendParams(**send_message_payload) -) - -response = await client.send_message(request) -print(response.model_dump(mode='json', exclude_none=True))`})}),(0,t.jsx)("div",{className:"mt-2 text-right",children:(0,t.jsx)("button",{onClick:()=>{eP(`client = A2AClient( - httpx_client=httpx_client, agent_card=final_agent_card_to_use -) - -send_message_payload: dict[str, Any] = { - 'message': { - 'role': 'user', - 'parts': [ - {'kind': 'text', 'text': 'how much is 10 USD in INR?'} - ], - 'messageId': uuid4().hex, - }, -} -request = SendMessageRequest( - id=str(uuid4()), params=MessageSendParams(**send_message_payload) -) - -response = await client.send_message(request) -print(response.model_dump(mode='json', exclude_none=True))`)},className:"text-sm text-blue-600 hover:text-blue-800 cursor-pointer",children:"Copy to clipboard"})})]})]})]})}),(0,t.jsx)(d.Modal,{title:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("span",{children:eS?.server_name||"MCP Server Details"}),eS&&(0,t.jsx)(g.Tooltip,{title:"Copy server name",children:(0,t.jsx)(x.default,{onClick:()=>eP(eS.server_name),className:"cursor-pointer text-gray-500 hover:text-blue-500 w-4 h-4"})})]}),width:1e3,open:ej,footer:null,onOk:()=>{eA(!1),eI(null)},onCancel:()=>{eA(!1),eI(null)},children:eS&&(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Server Overview"}),(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-4 mb-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Server Name:"}),(0,t.jsx)(o.Text,{children:eS.server_name})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Transport:"}),(0,t.jsx)(u.Tag,{color:"blue",children:eS.transport})]}),eS.alias&&(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Alias:"}),(0,t.jsx)(o.Text,{children:eS.alias})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Auth Type:"}),(0,t.jsx)(u.Tag,{color:"none"===eS.auth_type?"gray":"green",children:eS.auth_type})]}),(0,t.jsxs)("div",{className:"col-span-2",children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"Description:"}),(0,t.jsx)(o.Text,{children:eS.mcp_info?.description||"-"})]}),(0,t.jsxs)("div",{className:"col-span-2",children:[(0,t.jsx)(o.Text,{className:"font-medium",children:"URL:"}),(0,t.jsxs)("a",{href:eS.url,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 text-sm break-all flex items-center space-x-2",children:[(0,t.jsx)("span",{children:eS.url}),(0,t.jsx)(s.ExternalLinkIcon,{className:"w-4 h-4"})]})]})]})]}),eS.mcp_info&&Object.keys(eS.mcp_info).length>0&&(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Additional Information"}),(0,t.jsx)("div",{className:"bg-gray-50 p-4 rounded-lg",children:(0,t.jsx)("pre",{className:"text-xs overflow-x-auto",children:JSON.stringify(eS.mcp_info,null,2)})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(o.Text,{className:"text-lg font-semibold mb-4",children:"Usage Example"}),(0,t.jsx)("div",{className:"bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto",children:(0,t.jsx)("pre",{className:"text-sm",children:`# Using MCP Server with Python FastMCP - -from fastmcp import Client -import asyncio - -# Standard MCP configuration -config = { - "mcpServers": { - "${eS.server_name}": { - "url": "http://localhost:4000/${eS.server_name}/mcp", - "headers": { - "x-litellm-api-key": "Bearer sk-1234" - } - } - } -} - -# Create a client that connects to the server -client = Client(config) - -async def main(): - async with client: - # List available tools - tools = await client.list_tools() - print(f"Available tools: {[tool.name for tool in tools]}") - - # Call a tool - response = await client.call_tool( - name="tool_name", - arguments={"arg": "value"} - ) - print(f"Response: {response}") - -if __name__ == "__main__": - asyncio.run(main())`})}),(0,t.jsx)("div",{className:"mt-2 text-right",children:(0,t.jsx)("button",{onClick:()=>{eP(`# Using MCP Server with Python FastMCP - -from fastmcp import Client -import asyncio - -# Standard MCP configuration -config = { - "mcpServers": { - "${eS.server_name}": { - "url": "http://localhost:4000/${eS.server_name}/mcp", - "headers": { - "x-litellm-api-key": "Bearer sk-1234" - } - } - } -} - -# Create a client that connects to the server -client = Client(config) - -async def main(): - async with client: - # List available tools - tools = await client.list_tools() - print(f"Available tools: {[tool.name for tool in tools]}") - - # Call a tool - response = await client.call_tool( - name="tool_name", - arguments={"arg": "value"} - ) - print(f"Response: {response}") - -if __name__ == "__main__": - asyncio.run(main())`)},className:"text-sm text-blue-600 hover:text-blue-800 cursor-pointer",children:"Copy to clipboard"})})]})]})})]})})}],976883)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/503ca4764960a7c8.js b/litellm/proxy/_experimental/out/_next/static/chunks/503ca4764960a7c8.js new file mode 100644 index 00000000000..59f6d5bd212 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/503ca4764960a7c8.js @@ -0,0 +1,7 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,270345,e=>{"use strict";var t=e.i(764205);let r=async(e,r,a,l)=>"Admin"!=a&&"Admin Viewer"!=a?await (0,t.teamListCall)(e,l?.organization_id||null,r):await (0,t.teamListCall)(e,l?.organization_id||null);e.s(["fetchTeams",0,r])},519756,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={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"};var l=e.i(9583),n=r.forwardRef(function(e,n){return r.createElement(l.default,(0,t.default)({},e,{ref:n,icon:a}))});e.s(["UploadOutlined",0,n],519756)},981339,e=>{"use strict";var t=e.i(185793);e.s(["Skeleton",()=>t.default])},500330,e=>{"use strict";var t=e.i(727749);function r(e,t){let r=structuredClone(e);for(let[e,a]of Object.entries(t))e in r&&(r[e]=a);return r}let a=(e,t=0,r=!1,a=!0)=>{if(null==e||!Number.isFinite(e)||0===e&&!a)return"-";let l={minimumFractionDigits:t,maximumFractionDigits:t};if(!r)return e.toLocaleString("en-US",l);let n=e<0?"-":"",s=Math.abs(e),o=s,i="";return s>=1e6?(o=s/1e6,i="M"):s>=1e3&&(o=s/1e3,i="K"),`${n}${o.toLocaleString("en-US",l)}${i}`},l=async(e,r="Copied to clipboard")=>{if(!e)return!1;if(!navigator||!navigator.clipboard||!navigator.clipboard.writeText)return n(e,r);try{return await navigator.clipboard.writeText(e),t.default.success(r),!0}catch(t){return console.error("Clipboard API failed: ",t),n(e,r)}},n=(e,r)=>{try{let a=document.createElement("textarea");a.value=e,a.style.position="fixed",a.style.left="-999999px",a.style.top="-999999px",a.setAttribute("readonly",""),document.body.appendChild(a),a.focus(),a.select();let l=document.execCommand("copy");if(document.body.removeChild(a),l)return t.default.success(r),!0;throw Error("execCommand failed")}catch(e){return t.default.fromBackend("Failed to copy to clipboard"),console.error("Failed to copy: ",e),!1}};e.s(["copyToClipboard",0,l,"formatNumberWithCommas",0,a,"getSpendString",0,(e,t=6)=>{if(null==e||!Number.isFinite(e)||0===e)return"-";let r=a(e,t,!1,!1);if(0===Number(r.replace(/,/g,""))){let e=(1/10**t).toFixed(t);return`< $${e}`}return`$${r}`},"updateExistingKeys",()=>r])},743151,(e,t,r)=>{"use strict";function a(e){return(a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}Object.defineProperty(r,"__esModule",{value:!0}),r.CopyToClipboard=void 0;var l=o(e.r(271645)),n=o(e.r(844343)),s=["text","onCopy","options","children"];function o(e){return e&&e.__esModule?e:{default:e}}function i(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,a)}return r}function c(e){for(var t=1;t=0||(l[r]=e[r]);return l}(e,t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(l[r]=e[r])}return l}(e,s),a=l.default.Children.only(t);return l.default.cloneElement(a,c(c({},r),{},{onClick:this.onClick}))}}],function(e,t){for(var r=0;r{"use strict";var a=e.r(743151).CopyToClipboard;a.CopyToClipboard=a,t.exports=a},109799,e=>{"use strict";var t=e.i(135214),r=e.i(764205),a=e.i(266027),l=e.i(912598);let n=(0,e.i(243652).createQueryKeys)("organizations");e.s(["useOrganization",0,e=>{let s=(0,l.useQueryClient)(),{accessToken:o}=(0,t.default)();return(0,a.useQuery)({queryKey:n.detail(e),enabled:!!(o&&e),queryFn:async()=>{if(!o||!e)throw Error("Missing auth or teamId");return(0,r.organizationInfoCall)(o,e)},initialData:()=>{if(!e)return;let t=s.getQueryData(n.list({}));return t?.find(t=>t.organization_id===e)}})},"useOrganizations",0,()=>{let{accessToken:e,userId:l,userRole:s}=(0,t.default)();return(0,a.useQuery)({queryKey:n.list({}),queryFn:async()=>await (0,r.organizationListCall)(e),enabled:!!(e&&l&&s)})}])},309426,e=>{"use strict";var t=e.i(290571),r=e.i(444755),a=e.i(673706),l=e.i(271645),n=e.i(46757);let s=(0,a.makeClassName)("Col"),o=l.default.forwardRef((e,a)=>{let o,i,c,d,{numColSpan:u=1,numColSpanSm:m,numColSpanMd:g,numColSpanLg:f,children:p,className:h}=e,x=(0,t.__rest)(e,["numColSpan","numColSpanSm","numColSpanMd","numColSpanLg","children","className"]),b=(e,t)=>e&&Object.keys(t).includes(String(e))?t[e]:"";return l.default.createElement("div",Object.assign({ref:a,className:(0,r.tremorTwMerge)(s("root"),(o=b(u,n.colSpan),i=b(m,n.colSpanSm),c=b(g,n.colSpanMd),d=b(f,n.colSpanLg),(0,r.tremorTwMerge)(o,i,c,d)),h)},x),p)});o.displayName="Col",e.s(["Col",()=>o],309426)},988297,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 4v16m8-8H4"}))});e.s(["PlusIcon",0,r],988297)},797672,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"}))});e.s(["PencilIcon",0,r],797672)},992619,e=>{"use strict";var t=e.i(843476),r=e.i(271645),a=e.i(779241),l=e.i(599724),n=e.i(199133),s=e.i(983561),o=e.i(689020);e.s(["default",0,({accessToken:e,value:i,placeholder:c="Select a Model",onChange:d,disabled:u=!1,style:m,className:g,showLabel:f=!0,labelText:p="Select Model"})=>{let[h,x]=(0,r.useState)(i),[b,y]=(0,r.useState)(!1),[v,w]=(0,r.useState)([]),k=(0,r.useRef)(null);return(0,r.useEffect)(()=>{x(i)},[i]),(0,r.useEffect)(()=>{e&&(async()=>{try{let t=await (0,o.fetchAvailableModels)(e);console.log("Fetched models for selector:",t),t.length>0&&w(t)}catch(e){console.error("Error fetching model info:",e)}})()},[e]),(0,t.jsxs)("div",{children:[f&&(0,t.jsxs)(l.Text,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,t.jsx)(s.RobotOutlined,{className:"mr-2"})," ",p]}),(0,t.jsx)(n.Select,{value:h,placeholder:c,onChange:e=>{"custom"===e?(y(!0),x(void 0)):(y(!1),x(e),d&&d(e))},options:[...Array.from(new Set(v.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%",...m},showSearch:!0,className:`rounded-md ${g||""}`,disabled:u}),b&&(0,t.jsx)(a.TextInput,{className:"mt-2",placeholder:"Enter custom model name",onValueChange:e=>{k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{x(e),d&&d(e)},500)},disabled:u})]})}])},409797,e=>{"use strict";var t=e.i(631171);e.s(["ChevronDownIcon",()=>t.default])},91739,e=>{"use strict";var t=e.i(544195);e.s(["Radio",()=>t.default])},500727,696609,531516,e=>{"use strict";var t=e.i(266027),r=e.i(243652),a=e.i(764205),l=e.i(135214);let n=(0,r.createQueryKeys)("mcpServers");e.s(["useMCPServers",0,e=>{let{accessToken:r}=(0,l.default)();return(0,t.useQuery)({queryKey:n.list(e?{filters:{teamId:e}}:void 0),queryFn:async()=>await (0,a.fetchMCPServers)(r,e),enabled:!!r})}],500727);var s=e.i(843476),o=e.i(271645),i=e.i(536916),c=e.i(599724),d=e.i(409797),u=e.i(246349),u=u;let m=/\b(delete|remove|destroy|purge|drop|erase|unlink)\b/i,g=/\b(create|add|insert|new|post|submit|register|make|generate|write|upload)\b/i,f=/\b(update|edit|modify|change|patch|put|set|rename|move|transform)\b/i,p=/\b(get|read|list|fetch|search|find|query|retrieve|show|view|check|describe|info)\b/i;function h(e,t=""){let r=e.toLowerCase();if(p.test(r))return"read";if(m.test(r))return"delete";if(f.test(r))return"update";if(g.test(r))return"create";if(t){let e=t.toLowerCase();if(p.test(e))return"read";if(m.test(e))return"delete";if(f.test(e))return"update";if(g.test(e))return"create"}return"unknown"}function x(e){let t={read:[],create:[],update:[],delete:[],unknown:[]};for(let r of e)t[h(r.name,r.description)].push(r);return t}let b={read:{label:"Read",description:"Safe operations — fetch, list, search. No side effects.",risk:"low"},create:{label:"Create",description:"Add new resources — insert, upload, register.",risk:"medium"},update:{label:"Update",description:"Modify existing resources — edit, patch, rename.",risk:"medium"},delete:{label:"Delete",description:"Destructive operations — remove, purge, destroy.",risk:"high"},unknown:{label:"Other",description:"Operations that could not be automatically classified.",risk:"unknown"}};e.s(["CRUD_GROUP_META",0,b,"classifyToolOp",()=>h,"groupToolsByCrud",()=>x],696609);let y=["read","create","update","delete","unknown"],v={low:"bg-green-100 text-green-800",medium:"bg-yellow-100 text-yellow-800",high:"bg-red-100 text-red-800 font-semibold",unknown:"bg-gray-100 text-gray-700"},w={read:"border-green-200",create:"border-blue-200",update:"border-yellow-200",delete:"border-red-300",unknown:"border-gray-200"},k={read:"bg-green-50",create:"bg-blue-50",update:"bg-yellow-50",delete:"bg-red-50",unknown:"bg-gray-50"};e.s(["default",0,({tools:e,value:t,onChange:r,readOnly:a=!1,searchFilter:l=""})=>{let[n,m]=(0,o.useState)({read:!1,create:!1,update:!1,delete:!1,unknown:!0}),g=(0,o.useMemo)(()=>x(e),[e]),f=(0,o.useMemo)(()=>new Set(void 0===t?e.map(e=>e.name):t),[t,e]),p=e=>{if(a)return;let t=new Set(f);t.has(e)?t.delete(e):t.add(e),r(Array.from(t))};return 0===e.length?null:(0,s.jsx)("div",{className:"space-y-3",children:y.map(e=>{let t,o=g[e];if(0===o.length)return null;if(l){let e=l.toLowerCase();if(!o.some(t=>t.name.toLowerCase().includes(e)||(t.description??"").toLowerCase().includes(e)))return null}let h=b[e],x=(t=g[e]).length>0&&t.every(e=>f.has(e.name)),y=(e=>{let t=g[e];if(0===t.length)return!1;let r=t.filter(e=>f.has(e.name)).length;return r>0&&r{m(t=>({...t,[e]:!t[e]}))},children:[C?(0,s.jsx)(u.default,{className:"w-4 h-4 text-gray-500 flex-shrink-0"}):(0,s.jsx)(d.ChevronDownIcon,{className:"w-4 h-4 text-gray-500 flex-shrink-0"}),(0,s.jsx)("span",{className:"font-semibold text-gray-900 text-sm",children:h.label}),(0,s.jsx)("span",{className:`text-xs px-2 py-0.5 rounded-full ${v[h.risk]}`,children:"high"===h.risk?"High Risk":"medium"===h.risk?"Medium Risk":"low"===h.risk?"Safe":"Unclassified"}),(0,s.jsxs)("span",{className:"text-xs text-gray-500 ml-1",children:[o.filter(e=>f.has(e.name)).length,"/",o.length," allowed"]})]}),!a&&(0,s.jsxs)("div",{className:"flex items-center gap-2 ml-4",children:[(0,s.jsx)(c.Text,{className:"text-xs text-gray-500",children:x?"All on":y?"Partial":"All off"}),(0,s.jsx)(i.Checkbox,{checked:x,indeterminate:y,onChange:t=>((e,t)=>{if(a)return;let l=new Set(f);for(let r of g[e])t?l.add(r.name):l.delete(r.name);r(Array.from(l))})(e,t.target.checked),onClick:e=>e.stopPropagation()})]})]}),!C&&(0,s.jsx)("div",{className:"px-4 pt-2 pb-1 text-xs text-gray-500 bg-white border-b border-gray-100",children:h.description}),!C&&(0,s.jsx)("div",{className:"bg-white divide-y divide-gray-50",children:o.filter(e=>!l||e.name.toLowerCase().includes(l.toLowerCase())||(e.description??"").toLowerCase().includes(l.toLowerCase())).map(e=>{let t,r=(t=e.name,f.has(t));return(0,s.jsxs)("div",{className:`flex items-start gap-3 px-4 py-2.5 transition-colors hover:bg-gray-50 ${!a?"cursor-pointer":""} ${r?"":"opacity-60"}`,onClick:()=>p(e.name),children:[(0,s.jsx)(i.Checkbox,{checked:r,onChange:()=>p(e.name),disabled:a,onClick:e=>e.stopPropagation()}),(0,s.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,s.jsx)(c.Text,{className:"font-medium text-gray-900 text-sm",children:e.name}),e.description&&(0,s.jsx)(c.Text,{className:"text-xs text-gray-500 mt-0.5 leading-snug",children:e.description})]}),(0,s.jsx)("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${r?"bg-green-100 text-green-700":"bg-gray-100 text-gray-500"}`,children:r?"on":"off"})]},e.name)})})]},e)})})}],531516)},361653,e=>{"use strict";let t=(0,e.i(475254).default)("circle-alert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);e.s(["default",()=>t])},603908,e=>{"use strict";let t=(0,e.i(475254).default)("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);e.s(["default",()=>t])},841947,e=>{"use strict";let t=(0,e.i(475254).default)("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);e.s(["default",()=>t])},793130,e=>{"use strict";var t=e.i(290571),r=e.i(429427),a=e.i(371330),l=e.i(271645),n=e.i(394487),s=e.i(503269),o=e.i(214520),i=e.i(746725),c=e.i(914189),d=e.i(144279),u=e.i(294316),m=e.i(601893),g=e.i(140721),f=e.i(942803),p=e.i(233538),h=e.i(694421),x=e.i(700020),b=e.i(35889),y=e.i(998348),v=e.i(722678);let w=(0,l.createContext)(null);w.displayName="GroupContext";let k=l.Fragment,C=Object.assign((0,x.forwardRefWithAs)(function(e,t){var k;let C=(0,l.useId)(),j=(0,f.useProvidedId)(),N=(0,m.useDisabled)(),{id:S=j||`headlessui-switch-${C}`,disabled:M=N||!1,checked:T,defaultChecked:O,onChange:E,name:P,value:$,form:_,autoFocus:R=!1,...L}=e,z=(0,l.useContext)(w),[B,D]=(0,l.useState)(null),F=(0,l.useRef)(null),I=(0,u.useSyncRefs)(F,t,null===z?null:z.setSwitch,D),A=(0,o.useDefaultValue)(O),[H,q]=(0,s.useControllable)(T,E,null!=A&&A),V=(0,i.useDisposables)(),[G,K]=(0,l.useState)(!1),X=(0,c.useEvent)(()=>{K(!0),null==q||q(!H),V.nextFrame(()=>{K(!1)})}),W=(0,c.useEvent)(e=>{if((0,p.isDisabledReactIssue7711)(e.currentTarget))return e.preventDefault();e.preventDefault(),X()}),U=(0,c.useEvent)(e=>{e.key===y.Keys.Space?(e.preventDefault(),X()):e.key===y.Keys.Enter&&(0,h.attemptSubmit)(e.currentTarget)}),Y=(0,c.useEvent)(e=>e.preventDefault()),Q=(0,v.useLabelledBy)(),J=(0,b.useDescribedBy)(),{isFocusVisible:Z,focusProps:ee}=(0,r.useFocusRing)({autoFocus:R}),{isHovered:et,hoverProps:er}=(0,a.useHover)({isDisabled:M}),{pressed:ea,pressProps:el}=(0,n.useActivePress)({disabled:M}),en=(0,l.useMemo)(()=>({checked:H,disabled:M,hover:et,focus:Z,active:ea,autofocus:R,changing:G}),[H,et,Z,ea,M,G,R]),es=(0,x.mergeProps)({id:S,ref:I,role:"switch",type:(0,d.useResolveButtonType)(e,B),tabIndex:-1===e.tabIndex?0:null!=(k=e.tabIndex)?k:0,"aria-checked":H,"aria-labelledby":Q,"aria-describedby":J,disabled:M||void 0,autoFocus:R,onClick:W,onKeyUp:U,onKeyPress:Y},ee,er,el),eo=(0,l.useCallback)(()=>{if(void 0!==A)return null==q?void 0:q(A)},[q,A]),ei=(0,x.useRender)();return l.default.createElement(l.default.Fragment,null,null!=P&&l.default.createElement(g.FormFields,{disabled:M,data:{[P]:$||"on"},overrides:{type:"checkbox",checked:H},form:_,onReset:eo}),ei({ourProps:es,theirProps:L,slot:en,defaultTag:"button",name:"Switch"}))}),{Group:function(e){var t;let[r,a]=(0,l.useState)(null),[n,s]=(0,v.useLabels)(),[o,i]=(0,b.useDescriptions)(),c=(0,l.useMemo)(()=>({switch:r,setSwitch:a}),[r,a]),d=(0,x.useRender)();return l.default.createElement(i,{name:"Switch.Description",value:o},l.default.createElement(s,{name:"Switch.Label",value:n,props:{htmlFor:null==(t=c.switch)?void 0:t.id,onClick(e){r&&(e.currentTarget instanceof HTMLLabelElement&&e.preventDefault(),r.click(),r.focus({preventScroll:!0}))}}},l.default.createElement(w.Provider,{value:c},d({ourProps:{},theirProps:e,slot:{},defaultTag:k,name:"Switch.Group"}))))},Label:v.Label,Description:b.Description});var j=e.i(888288),N=e.i(95779),S=e.i(444755),M=e.i(673706),T=e.i(829087);let O=(0,M.makeClassName)("Switch"),E=l.default.forwardRef((e,r)=>{let{checked:a,defaultChecked:n=!1,onChange:s,color:o,name:i,error:c,errorMessage:d,disabled:u,required:m,tooltip:g,id:f}=e,p=(0,t.__rest)(e,["checked","defaultChecked","onChange","color","name","error","errorMessage","disabled","required","tooltip","id"]),h={bgColor:o?(0,M.getColorClassNames)(o,N.colorPalette.background).bgColor:"bg-tremor-brand dark:bg-dark-tremor-brand",ringColor:o?(0,M.getColorClassNames)(o,N.colorPalette.ring).ringColor:"ring-tremor-brand-muted dark:ring-dark-tremor-brand-muted"},[x,b]=(0,j.default)(n,a),[y,v]=(0,l.useState)(!1),{tooltipProps:w,getReferenceProps:k}=(0,T.useTooltip)(300);return l.default.createElement("div",{className:"flex flex-row items-center justify-start"},l.default.createElement(T.default,Object.assign({text:g},w)),l.default.createElement("div",Object.assign({ref:(0,M.mergeRefs)([r,w.refs.setReference]),className:(0,S.tremorTwMerge)(O("root"),"flex flex-row relative h-5")},p,k),l.default.createElement("input",{type:"checkbox",className:(0,S.tremorTwMerge)(O("input"),"absolute w-5 h-5 cursor-pointer left-0 top-0 opacity-0"),name:i,required:m,checked:x,onChange:e=>{e.preventDefault()}}),l.default.createElement(C,{checked:x,onChange:e=>{b(e),null==s||s(e)},disabled:u,className:(0,S.tremorTwMerge)(O("switch"),"w-10 h-5 group relative inline-flex shrink-0 cursor-pointer items-center justify-center rounded-tremor-full","focus:outline-none",u?"cursor-not-allowed":""),onFocus:()=>v(!0),onBlur:()=>v(!1),id:f},l.default.createElement("span",{className:(0,S.tremorTwMerge)(O("sr-only"),"sr-only")},"Switch ",x?"on":"off"),l.default.createElement("span",{"aria-hidden":"true",className:(0,S.tremorTwMerge)(O("background"),x?h.bgColor:"bg-tremor-border dark:bg-dark-tremor-border","pointer-events-none absolute mx-auto h-3 w-9 rounded-tremor-full transition-colors duration-100 ease-in-out")}),l.default.createElement("span",{"aria-hidden":"true",className:(0,S.tremorTwMerge)(O("round"),x?(0,S.tremorTwMerge)(h.bgColor,"translate-x-5 border-tremor-background dark:border-dark-tremor-background"):"translate-x-0 bg-tremor-border dark:bg-dark-tremor-border border-tremor-background dark:border-dark-tremor-background","pointer-events-none absolute left-0 inline-block h-5 w-5 transform rounded-tremor-full border-2 shadow-tremor-input duration-100 ease-in-out transition",y?(0,S.tremorTwMerge)("ring-2",h.ringColor):"")}))),c&&d?l.default.createElement("p",{className:(0,S.tremorTwMerge)(O("errorMessage"),"text-sm text-red-500 mt-1 ")},d):null)});E.displayName="Switch",e.s(["Switch",()=>E],793130)},158392,419470,e=>{"use strict";var t=e.i(843476),r=e.i(779241);let a={ttl:3600,lowest_latency_buffer:0},l=({routingStrategyArgs:e})=>{let 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,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"max-w-3xl",children:[(0,t.jsx)("h3",{className:"text-sm font-medium text-gray-900",children:"Latency-Based Configuration"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Fine-tune latency-based routing behavior"})]}),(0,t.jsx)("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2 xl:grid-cols-3",children:Object.entries(e||a).map(([e,a])=>(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsxs)("label",{className:"block",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:e.replace(/_/g," ")}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-2",children:l[e]||""}),(0,t.jsx)(r.TextInput,{name:e,defaultValue:"object"==typeof a?JSON.stringify(a,null,2):a?.toString(),className:"font-mono text-sm w-full"})]})},e))})]}),(0,t.jsx)("div",{className:"border-t border-gray-200"})]})},n=({routerSettings:e,routerFieldsMetadata:a})=>(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"max-w-3xl",children:[(0,t.jsx)("h3",{className:"text-sm font-medium text-gray-900",children:"Reliability & Retries"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Configure retry logic and failure handling"})]}),(0,t.jsx)("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2 xl:grid-cols-3",children:Object.entries(e).filter(([e,t])=>"fallbacks"!=e&&"context_window_fallbacks"!=e&&"routing_strategy_args"!=e&&"routing_strategy"!=e&&"enable_tag_filtering"!=e).map(([e,l])=>(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsxs)("label",{className:"block",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:a[e]?.ui_field_name||e}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-2",children:a[e]?.field_description||""}),(0,t.jsx)(r.TextInput,{name:e,defaultValue:null==l||"null"===l?"":"object"==typeof l?JSON.stringify(l,null,2):l?.toString()||"",placeholder:"—",className:"font-mono text-sm w-full"})]})},e))})]});var s=e.i(199133);let o=({selectedStrategy:e,availableStrategies:r,routingStrategyDescriptions:a,routerFieldsMetadata:l,onStrategyChange:n})=>(0,t.jsxs)("div",{className:"space-y-2 max-w-3xl",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:l.routing_strategy?.ui_field_name||"Routing Strategy"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-2",children:l.routing_strategy?.field_description||""})]}),(0,t.jsx)("div",{className:"routing-strategy-select max-w-3xl",children:(0,t.jsx)(s.Select,{value:e,onChange:n,style:{width:"100%"},size:"large",children:r.map(e=>(0,t.jsx)(s.Select.Option,{value:e,label:e,children:(0,t.jsxs)("div",{className:"flex flex-col gap-0.5 py-1",children:[(0,t.jsx)("span",{className:"font-mono text-sm font-medium",children:e}),a[e]&&(0,t.jsx)("span",{className:"text-xs text-gray-500 font-normal",children:a[e]})]})},e))})})]});var i=e.i(793130);let c=({enabled:e,routerFieldsMetadata:r,onToggle:a})=>(0,t.jsx)("div",{className:"space-y-3 max-w-3xl",children:(0,t.jsxs)("div",{className:"flex items-start justify-between",children:[(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsx)("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:r.enable_tag_filtering?.ui_field_name||"Enable Tag Filtering"}),(0,t.jsxs)("p",{className:"text-xs text-gray-500 mt-0.5",children:[r.enable_tag_filtering?.field_description||"",r.enable_tag_filtering?.link&&(0,t.jsxs)(t.Fragment,{children:[" ",(0,t.jsx)("a",{href:r.enable_tag_filtering.link,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"Learn more"})]})]})]}),(0,t.jsx)(i.Switch,{checked:e,onChange:a,className:"ml-4"})]})});e.s(["default",0,({value:e,onChange:r,routerFieldsMetadata:a,availableRoutingStrategies:s,routingStrategyDescriptions:i})=>(0,t.jsxs)("div",{className:"w-full space-y-8 py-2",children:[(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"max-w-3xl",children:[(0,t.jsx)("h3",{className:"text-sm font-medium text-gray-900",children:"Routing Settings"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Configure how requests are routed to deployments"})]}),s.length>0&&(0,t.jsx)(o,{selectedStrategy:e.selectedStrategy||e.routerSettings.routing_strategy||null,availableStrategies:s,routingStrategyDescriptions:i,routerFieldsMetadata:a,onStrategyChange:t=>{r({...e,selectedStrategy:t})}}),(0,t.jsx)(c,{enabled:e.enableTagFiltering,routerFieldsMetadata:a,onToggle:t=>{r({...e,enableTagFiltering:t})}})]}),(0,t.jsx)("div",{className:"border-t border-gray-200"}),"latency-based-routing"===e.selectedStrategy&&(0,t.jsx)(l,{routingStrategyArgs:e.routerSettings.routing_strategy_args}),(0,t.jsx)(n,{routerSettings:e.routerSettings,routerFieldsMetadata:a})]})],158392);var d=e.i(994388),u=e.i(998573),m=e.i(653496),g=e.i(107233),f=e.i(271645),p=e.i(592968),h=e.i(361653),h=h;let x=(0,e.i(475254).default)("arrow-down",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);var b=e.i(37727);function y({group:e,onChange:r,availableModels:a,maxFallbacks:l}){let n=a.filter(t=>t!==e.primaryModel),o=e.fallbackModels.length{let a=[...e.fallbackModels];a.includes(t)&&(a=a.filter(e=>e!==t)),r({...e,primaryModel:t,fallbackModels:a})},showSearch:!0,filterOption:(e,t)=>(t?.label??"").toLowerCase().includes(e.toLowerCase()),options:a.map(e=>({label:e,value:e}))}),!e.primaryModel&&(0,t.jsxs)("div",{className:"mt-2 flex items-center gap-2 text-amber-600 text-xs bg-amber-50 p-2 rounded",children:[(0,t.jsx)(h.default,{className:"w-4 h-4"}),(0,t.jsx)("span",{children:"Select a model to begin configuring fallbacks"})]})]}),(0,t.jsx)("div",{className:"flex items-center justify-center -my-4 z-10",children:(0,t.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,t.jsx)(x,{className:"w-4 h-4"}),"IF FAILS, TRY..."]})}),(0,t.jsxs)("div",{className:`transition-opacity duration-300 ${!e.primaryModel?"opacity-50 pointer-events-none":"opacity-100"}`,children:[(0,t.jsxs)("label",{className:"block text-sm font-semibold text-gray-700 mb-2",children:["Fallback Chain ",(0,t.jsx)("span",{className:"text-red-500",children:"*"}),(0,t.jsxs)("span",{className:"text-xs text-gray-500 font-normal ml-2",children:["(Max ",l," fallbacks at a time)"]})]}),(0,t.jsxs)("div",{className:"bg-gray-50 rounded-xl p-4 border border-gray-200",children:[(0,t.jsxs)("div",{className:"mb-4",children:[(0,t.jsx)(s.Select,{mode:"multiple",className:"w-full",size:"large",placeholder:o?"Select fallback models to add...":`Maximum ${l} fallbacks reached`,value:e.fallbackModels,onChange:t=>{let a=t.slice(0,l);r({...e,fallbackModels:a})},disabled:!e.primaryModel,options:n.map(e=>({label:e,value:e})),optionRender:(r,a)=>{let l=e.fallbackModels.includes(r.value),n=l?e.fallbackModels.indexOf(r.value)+1:null;return(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[l&&null!==n&&(0,t.jsx)("span",{className:"flex items-center justify-center w-5 h-5 rounded bg-indigo-100 text-indigo-600 text-xs font-bold",children:n}),(0,t.jsx)("span",{children:r.label})]})},maxTagCount:"responsive",maxTagPlaceholder:e=>(0,t.jsx)(p.Tooltip,{styles:{root:{pointerEvents:"none"}},title:e.map(({value:e})=>e).join(", "),children:(0,t.jsxs)("span",{children:["+",e.length," more"]})}),showSearch:!0,filterOption:(e,t)=>(t?.label??"").toLowerCase().includes(e.toLowerCase())}),(0,t.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. (${e.fallbackModels.length}/${l} used)`:`Maximum ${l} fallbacks reached. Remove some to add more.`})]}),(0,t.jsx)("div",{className:"space-y-2 min-h-[100px]",children:0===e.fallbackModels.length?(0,t.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,t.jsx)("span",{className:"text-sm",children:"No fallback models selected"}),(0,t.jsx)("span",{className:"text-xs mt-1",children:"Add models from the dropdown above"})]}):e.fallbackModels.map((a,l)=>(0,t.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,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.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,t.jsx)("span",{className:"text-xs font-bold",children:l+1})}),(0,t.jsx)("div",{children:(0,t.jsx)("span",{className:"font-medium text-gray-800",children:a})})]}),(0,t.jsx)("button",{type:"button",onClick:()=>{let t;return t=e.fallbackModels.filter((e,t)=>t!==l),void r({...e,fallbackModels:t})},className:"opacity-0 group-hover:opacity-100 transition-opacity text-gray-400 hover:text-red-500 p-1",children:(0,t.jsx)(b.X,{className:"w-4 h-4"})})]},`${a}-${l}`))})]})]})]})}function v({groups:e,onGroupsChange:r,availableModels:a,maxFallbacks:l=10,maxGroups:n=5}){let[s,o]=(0,f.useState)(e.length>0?e[0].id:"1");(0,f.useEffect)(()=>{e.length>0?e.some(e=>e.id===s)||o(e[0].id):o("1")},[e]);let i=()=>{if(e.length>=n)return;let t=Date.now().toString();r([...e,{id:t,primaryModel:null,fallbackModels:[]}]),o(t)},c=t=>{r(e.map(e=>e.id===t.id?t:e))},p=e.map((r,n)=>{let s=r.primaryModel?r.primaryModel:`Group ${n+1}`;return{key:r.id,label:s,closable:e.length>1,children:(0,t.jsx)(y,{group:r,onChange:c,availableModels:a,maxFallbacks:l})}});return 0===e.length?(0,t.jsxs)("div",{className:"text-center py-12 bg-gray-50 rounded-lg border border-dashed border-gray-300",children:[(0,t.jsx)("p",{className:"text-gray-500 mb-4",children:"No fallback groups configured"}),(0,t.jsx)(d.Button,{variant:"primary",onClick:i,icon:()=>(0,t.jsx)(g.Plus,{className:"w-4 h-4"}),children:"Create First Group"})]}):(0,t.jsx)(m.Tabs,{type:"editable-card",activeKey:s,onChange:o,onEdit:(t,a)=>{"add"===a?i():"remove"===a&&e.length>1&&(t=>{if(1===e.length)return u.message.warning("At least one group is required");let a=e.filter(e=>e.id!==t);r(a),s===t&&a.length>0&&o(a[a.length-1].id)})(t)},items:p,className:"fallback-tabs",tabBarStyle:{marginBottom:0},hideAdd:e.length>=n})}e.s(["FallbackSelectionForm",()=>v],419470)},653496,e=>{"use strict";var t=e.i(721369);e.s(["Tabs",()=>t.default])},599724,936325,e=>{"use strict";var t=e.i(95779),r=e.i(444755),a=e.i(673706),l=e.i(271645);let n=l.default.forwardRef((e,n)=>{let{color:s,className:o,children:i}=e;return l.default.createElement("p",{ref:n,className:(0,r.tremorTwMerge)("text-tremor-default",s?(0,a.getColorClassNames)(s,t.colorPalette.text).textColor:(0,r.tremorTwMerge)("text-tremor-content","dark:text-dark-tremor-content"),o)},i)});n.displayName="Text",e.s(["default",()=>n],936325),e.s(["Text",()=>n],599724)},994388,e=>{"use strict";var t=e.i(290571),r=e.i(829087),a=e.i(271645);let l=["preEnter","entering","entered","preExit","exiting","exited","unmounted"],n=e=>({_s:e,status:l[e],isEnter:e<3,isMounted:6!==e,isResolved:2===e||e>4}),s=e=>e?6:5,o=(e,t,r,a,l)=>{clearTimeout(a.current);let s=n(e);t(s),r.current=s,l&&l({current:s})};var i=e.i(480731),c=e.i(444755),d=e.i(673706);let u=e=>{var r=(0,t.__rest)(e,[]);return a.default.createElement("svg",Object.assign({},r,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"}),a.default.createElement("path",{fill:"none",d:"M0 0h24v24H0z"}),a.default.createElement("path",{d:"M18.364 5.636L16.95 7.05A7 7 0 1 0 19 12h2a9 9 0 1 1-2.636-6.364z"}))};var m=e.i(95779);let g={xs:{height:"h-4",width:"w-4"},sm:{height:"h-5",width:"w-5"},md:{height:"h-5",width:"w-5"},lg:{height:"h-6",width:"w-6"},xl:{height:"h-6",width:"w-6"}},f=(e,t)=>{switch(e){case"primary":return{textColor:t?(0,d.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",hoverTextColor:t?(0,d.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",bgColor:t?(0,d.getColorClassNames)(t,m.colorPalette.background).bgColor:"bg-tremor-brand dark:bg-dark-tremor-brand",hoverBgColor:t?(0,d.getColorClassNames)(t,m.colorPalette.darkBackground).hoverBgColor:"hover:bg-tremor-brand-emphasis dark:hover:bg-dark-tremor-brand-emphasis",borderColor:t?(0,d.getColorClassNames)(t,m.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",hoverBorderColor:t?(0,d.getColorClassNames)(t,m.colorPalette.darkBorder).hoverBorderColor:"hover:border-tremor-brand-emphasis dark:hover:border-dark-tremor-brand-emphasis"};case"secondary":return{textColor:t?(0,d.getColorClassNames)(t,m.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,d.getColorClassNames)(t,m.colorPalette.text).textColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,d.getColorClassNames)("transparent").bgColor,hoverBgColor:t?(0,c.tremorTwMerge)((0,d.getColorClassNames)(t,m.colorPalette.background).hoverBgColor,"hover:bg-opacity-20 dark:hover:bg-opacity-20"):"hover:bg-tremor-brand-faint dark:hover:bg-dark-tremor-brand-faint",borderColor:t?(0,d.getColorClassNames)(t,m.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand"};case"light":return{textColor:t?(0,d.getColorClassNames)(t,m.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,d.getColorClassNames)(t,m.colorPalette.darkText).hoverTextColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,d.getColorClassNames)("transparent").bgColor,borderColor:"",hoverBorderColor:""}}},p=(0,d.makeClassName)("Button"),h=({loading:e,iconSize:t,iconPosition:r,Icon:l,needMargin:n,transitionStatus:s})=>{let o=n?r===i.HorizontalPositions.Left?(0,c.tremorTwMerge)("-ml-1","mr-1.5"):(0,c.tremorTwMerge)("-mr-1","ml-1.5"):"",d=(0,c.tremorTwMerge)("w-0 h-0"),m={default:d,entering:d,entered:t,exiting:t,exited:d};return e?a.default.createElement(u,{className:(0,c.tremorTwMerge)(p("icon"),"animate-spin shrink-0",o,m.default,m[s]),style:{transition:"width 150ms"}}):a.default.createElement(l,{className:(0,c.tremorTwMerge)(p("icon"),"shrink-0",t,o)})},x=a.default.forwardRef((e,l)=>{let{icon:u,iconPosition:m=i.HorizontalPositions.Left,size:x=i.Sizes.SM,color:b,variant:y="primary",disabled:v,loading:w=!1,loadingText:k,children:C,tooltip:j,className:N}=e,S=(0,t.__rest)(e,["icon","iconPosition","size","color","variant","disabled","loading","loadingText","children","tooltip","className"]),M=w||v,T=void 0!==u||w,O=w&&k,E=!(!C&&!O),P=(0,c.tremorTwMerge)(g[x].height,g[x].width),$="light"!==y?(0,c.tremorTwMerge)("rounded-tremor-default border","shadow-tremor-input","dark:shadow-dark-tremor-input"):"",_=f(y,b),R=("light"!==y?{xs:{paddingX:"px-2.5",paddingY:"py-1.5",fontSize:"text-xs"},sm:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-sm"},md:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-md"},lg:{paddingX:"px-4",paddingY:"py-2.5",fontSize:"text-lg"},xl:{paddingX:"px-4",paddingY:"py-3",fontSize:"text-xl"}}:{xs:{paddingX:"",paddingY:"",fontSize:"text-xs"},sm:{paddingX:"",paddingY:"",fontSize:"text-sm"},md:{paddingX:"",paddingY:"",fontSize:"text-md"},lg:{paddingX:"",paddingY:"",fontSize:"text-lg"},xl:{paddingX:"",paddingY:"",fontSize:"text-xl"}})[x],{tooltipProps:L,getReferenceProps:z}=(0,r.useTooltip)(300),[B,D]=(({enter:e=!0,exit:t=!0,preEnter:r,preExit:l,timeout:i,initialEntered:c,mountOnEnter:d,unmountOnExit:u,onStateChange:m}={})=>{let[g,f]=(0,a.useState)(()=>n(c?2:s(d))),p=(0,a.useRef)(g),h=(0,a.useRef)(0),[x,b]="object"==typeof i?[i.enter,i.exit]:[i,i],y=(0,a.useCallback)(()=>{let e=((e,t)=>{switch(e){case 1:case 0:return 2;case 4:case 3:return s(t)}})(p.current._s,u);e&&o(e,f,p,h,m)},[m,u]);return[g,(0,a.useCallback)(a=>{let n=e=>{switch(o(e,f,p,h,m),e){case 1:x>=0&&(h.current=((...e)=>setTimeout(...e))(y,x));break;case 4:b>=0&&(h.current=((...e)=>setTimeout(...e))(y,b));break;case 0:case 3:h.current=((...e)=>setTimeout(...e))(()=>{isNaN(document.body.offsetTop)||n(e+1)},0)}},i=p.current.isEnter;"boolean"!=typeof a&&(a=!i),a?i||n(e?+!r:2):i&&n(t?l?3:4:s(u))},[y,m,e,t,r,l,x,b,u]),y]})({timeout:50});return(0,a.useEffect)(()=>{D(w)},[w]),a.default.createElement("button",Object.assign({ref:(0,d.mergeRefs)([l,L.refs.setReference]),className:(0,c.tremorTwMerge)(p("root"),"shrink-0 inline-flex justify-center items-center group font-medium outline-none",$,R.paddingX,R.paddingY,R.fontSize,_.textColor,_.bgColor,_.borderColor,_.hoverBorderColor,M?"opacity-50 cursor-not-allowed":(0,c.tremorTwMerge)(f(y,b).hoverTextColor,f(y,b).hoverBgColor,f(y,b).hoverBorderColor),N),disabled:M},z,S),a.default.createElement(r.default,Object.assign({text:j},L)),T&&m!==i.HorizontalPositions.Right?a.default.createElement(h,{loading:w,iconSize:P,iconPosition:m,Icon:u,transitionStatus:B.status,needMargin:E}):null,O||C?a.default.createElement("span",{className:(0,c.tremorTwMerge)(p("text"),"text-tremor-default whitespace-nowrap")},O?k:C):null,T&&m===i.HorizontalPositions.Right?a.default.createElement(h,{loading:w,iconSize:P,iconPosition:m,Icon:u,transitionStatus:B.status,needMargin:E}):null)});x.displayName="Button",e.s(["Button",()=>x],994388)},304967,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(480731),l=e.i(95779),n=e.i(444755),s=e.i(673706);let o=(0,s.makeClassName)("Card"),i=r.default.forwardRef((e,i)=>{let{decoration:c="",decorationColor:d,children:u,className:m}=e,g=(0,t.__rest)(e,["decoration","decorationColor","children","className"]);return r.default.createElement("div",Object.assign({ref:i,className:(0,n.tremorTwMerge)(o("root"),"relative w-full text-left ring-1 rounded-tremor-default p-6","bg-tremor-background ring-tremor-ring shadow-tremor-card","dark:bg-dark-tremor-background dark:ring-dark-tremor-ring dark:shadow-dark-tremor-card",d?(0,s.getColorClassNames)(d,l.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",(e=>{if(!e)return"";switch(e){case a.HorizontalPositions.Left:return"border-l-4";case a.VerticalPositions.Top:return"border-t-4";case a.HorizontalPositions.Right:return"border-r-4";case a.VerticalPositions.Bottom:return"border-b-4";default:return""}})(c),m)},g),u)});i.displayName="Card",e.s(["Card",()=>i],304967)},629569,e=>{"use strict";var t=e.i(290571),r=e.i(95779),a=e.i(444755),l=e.i(673706),n=e.i(271645);let s=n.default.forwardRef((e,s)=>{let{color:o,children:i,className:c}=e,d=(0,t.__rest)(e,["color","children","className"]);return n.default.createElement("p",Object.assign({ref:s,className:(0,a.tremorTwMerge)("font-medium text-tremor-title",o?(0,l.getColorClassNames)(o,r.colorPalette.darkText).textColor:"text-tremor-content-strong dark:text-dark-tremor-content-strong",c)},d),i)});s.displayName="Title",e.s(["Title",()=>s],629569)},91874,e=>{"use strict";var t=e.i(931067),r=e.i(209428),a=e.i(211577),l=e.i(392221),n=e.i(703923),s=e.i(343794),o=e.i(914949),i=e.i(271645),c=["prefixCls","className","style","checked","disabled","defaultChecked","type","title","onChange"],d=(0,i.forwardRef)(function(e,d){var u=e.prefixCls,m=void 0===u?"rc-checkbox":u,g=e.className,f=e.style,p=e.checked,h=e.disabled,x=e.defaultChecked,b=e.type,y=void 0===b?"checkbox":b,v=e.title,w=e.onChange,k=(0,n.default)(e,c),C=(0,i.useRef)(null),j=(0,i.useRef)(null),N=(0,o.default)(void 0!==x&&x,{value:p}),S=(0,l.default)(N,2),M=S[0],T=S[1];(0,i.useImperativeHandle)(d,function(){return{focus:function(e){var t;null==(t=C.current)||t.focus(e)},blur:function(){var e;null==(e=C.current)||e.blur()},input:C.current,nativeElement:j.current}});var O=(0,s.default)(m,g,(0,a.default)((0,a.default)({},"".concat(m,"-checked"),M),"".concat(m,"-disabled"),h));return i.createElement("span",{className:O,title:v,style:f,ref:j},i.createElement("input",(0,t.default)({},k,{className:"".concat(m,"-input"),ref:C,onChange:function(t){h||("checked"in e||T(t.target.checked),null==w||w({target:(0,r.default)((0,r.default)({},e),{},{type:y,checked:t.target.checked}),stopPropagation:function(){t.stopPropagation()},preventDefault:function(){t.preventDefault()},nativeEvent:t.nativeEvent}))},disabled:h,checked:!!M,type:y})),i.createElement("span",{className:"".concat(m,"-inner")}))});e.s(["default",0,d])},421512,236836,e=>{"use strict";let t=e.i(271645).default.createContext(null);e.s(["default",0,t],421512),e.i(296059);var r=e.i(915654),a=e.i(183293),l=e.i(246422),n=e.i(838378);function s(e,t){return(e=>{let{checkboxCls:t}=e,l=`${t}-wrapper`;return[{[`${t}-group`]:Object.assign(Object.assign({},(0,a.resetComponent)(e)),{display:"inline-flex",flexWrap:"wrap",columnGap:e.marginXS,[`> ${e.antCls}-row`]:{flex:1}}),[l]:Object.assign(Object.assign({},(0,a.resetComponent)(e)),{display:"inline-flex",alignItems:"baseline",cursor:"pointer","&:after":{display:"inline-block",width:0,overflow:"hidden",content:"'\\a0'"},[`& + ${l}`]:{marginInlineStart:0},[`&${l}-in-form-item`]:{'input[type="checkbox"]':{width:14,height:14}}}),[t]:Object.assign(Object.assign({},(0,a.resetComponent)(e)),{position:"relative",whiteSpace:"nowrap",lineHeight:1,cursor:"pointer",borderRadius:e.borderRadiusSM,alignSelf:"center",[`${t}-input`]:{position:"absolute",inset:0,zIndex:1,cursor:"pointer",opacity:0,margin:0,[`&:focus-visible + ${t}-inner`]:(0,a.genFocusOutline)(e)},[`${t}-inner`]:{boxSizing:"border-box",display:"block",width:e.checkboxSize,height:e.checkboxSize,direction:"ltr",backgroundColor:e.colorBgContainer,border:`${(0,r.unit)(e.lineWidth)} ${e.lineType} ${e.colorBorder}`,borderRadius:e.borderRadiusSM,borderCollapse:"separate",transition:`all ${e.motionDurationSlow}`,"&:after":{boxSizing:"border-box",position:"absolute",top:"50%",insetInlineStart:"25%",display:"table",width:e.calc(e.checkboxSize).div(14).mul(5).equal(),height:e.calc(e.checkboxSize).div(14).mul(8).equal(),border:`${(0,r.unit)(e.lineWidthBold)} solid ${e.colorWhite}`,borderTop:0,borderInlineStart:0,transform:"rotate(45deg) scale(0) translate(-50%,-50%)",opacity:0,content:'""',transition:`all ${e.motionDurationFast} ${e.motionEaseInBack}, opacity ${e.motionDurationFast}`}},"& + span":{paddingInlineStart:e.paddingXS,paddingInlineEnd:e.paddingXS}})},{[` + ${l}:not(${l}-disabled), + ${t}:not(${t}-disabled) + `]:{[`&:hover ${t}-inner`]:{borderColor:e.colorPrimary}},[`${l}:not(${l}-disabled)`]:{[`&:hover ${t}-checked:not(${t}-disabled) ${t}-inner`]:{backgroundColor:e.colorPrimaryHover,borderColor:"transparent"},[`&:hover ${t}-checked:not(${t}-disabled):after`]:{borderColor:e.colorPrimaryHover}}},{[`${t}-checked`]:{[`${t}-inner`]:{backgroundColor:e.colorPrimary,borderColor:e.colorPrimary,"&:after":{opacity:1,transform:"rotate(45deg) scale(1) translate(-50%,-50%)",transition:`all ${e.motionDurationMid} ${e.motionEaseOutBack} ${e.motionDurationFast}`}}},[` + ${l}-checked:not(${l}-disabled), + ${t}-checked:not(${t}-disabled) + `]:{[`&:hover ${t}-inner`]:{backgroundColor:e.colorPrimaryHover,borderColor:"transparent"}}},{[t]:{"&-indeterminate":{"&":{[`${t}-inner`]:{backgroundColor:`${e.colorBgContainer}`,borderColor:`${e.colorBorder}`,"&:after":{top:"50%",insetInlineStart:"50%",width:e.calc(e.fontSizeLG).div(2).equal(),height:e.calc(e.fontSizeLG).div(2).equal(),backgroundColor:e.colorPrimary,border:0,transform:"translate(-50%, -50%) scale(1)",opacity:1,content:'""'}},[`&:hover ${t}-inner`]:{backgroundColor:`${e.colorBgContainer}`,borderColor:`${e.colorPrimary}`}}}}},{[`${l}-disabled`]:{cursor:"not-allowed"},[`${t}-disabled`]:{[`&, ${t}-input`]:{cursor:"not-allowed",pointerEvents:"none"},[`${t}-inner`]:{background:e.colorBgContainerDisabled,borderColor:e.colorBorder,"&:after":{borderColor:e.colorTextDisabled}},"&:after":{display:"none"},"& + span":{color:e.colorTextDisabled},[`&${t}-indeterminate ${t}-inner::after`]:{background:e.colorTextDisabled}}}]})((0,n.mergeToken)(t,{checkboxCls:`.${e}`,checkboxSize:t.controlInteractiveSize}))}let o=(0,l.genStyleHooks)("Checkbox",(e,{prefixCls:t})=>[s(t,e)]);e.s(["default",0,o,"getStyle",()=>s],236836)},681216,e=>{"use strict";var t=e.i(271645),r=e.i(963188);function a(e){let a=t.default.useRef(null),l=()=>{r.default.cancel(a.current),a.current=null};return[()=>{l(),a.current=(0,r.default)(()=>{a.current=null})},t=>{a.current&&(t.stopPropagation(),l()),null==e||e(t)}]}e.s(["default",()=>a])},374276,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),a=e.i(91874),l=e.i(611935),n=e.i(121872),s=e.i(26905),o=e.i(242064),i=e.i(937328),c=e.i(321883),d=e.i(62139),u=e.i(421512),m=e.i(236836),g=e.i(681216),f=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var l=0,a=Object.getOwnPropertySymbols(e);lt.indexOf(a[l])&&Object.prototype.propertyIsEnumerable.call(e,a[l])&&(r[a[l]]=e[a[l]]);return r};let p=t.forwardRef((e,p)=>{var h;let{prefixCls:x,className:b,rootClassName:y,children:v,indeterminate:w=!1,style:k,onMouseEnter:C,onMouseLeave:j,skipGroup:N=!1,disabled:S}=e,M=f(e,["prefixCls","className","rootClassName","children","indeterminate","style","onMouseEnter","onMouseLeave","skipGroup","disabled"]),{getPrefixCls:T,direction:O,checkbox:E}=t.useContext(o.ConfigContext),P=t.useContext(u.default),{isFormItemInput:$}=t.useContext(d.FormItemInputContext),_=t.useContext(i.default),R=null!=(h=(null==P?void 0:P.disabled)||S)?h:_,L=t.useRef(M.value),z=t.useRef(null),B=(0,l.composeRef)(p,z);t.useEffect(()=>{null==P||P.registerValue(M.value)},[]),t.useEffect(()=>{if(!N)return M.value!==L.current&&(null==P||P.cancelValue(L.current),null==P||P.registerValue(M.value),L.current=M.value),()=>null==P?void 0:P.cancelValue(M.value)},[M.value]),t.useEffect(()=>{var e;(null==(e=z.current)?void 0:e.input)&&(z.current.input.indeterminate=w)},[w]);let D=T("checkbox",x),F=(0,c.default)(D),[I,A,H]=(0,m.default)(D,F),q=Object.assign({},M);P&&!N&&(q.onChange=(...e)=>{M.onChange&&M.onChange.apply(M,e),P.toggleOption&&P.toggleOption({label:v,value:M.value})},q.name=P.name,q.checked=P.value.includes(M.value));let V=(0,r.default)(`${D}-wrapper`,{[`${D}-rtl`]:"rtl"===O,[`${D}-wrapper-checked`]:q.checked,[`${D}-wrapper-disabled`]:R,[`${D}-wrapper-in-form-item`]:$},null==E?void 0:E.className,b,y,H,F,A),G=(0,r.default)({[`${D}-indeterminate`]:w},s.TARGET_CLS,A),[K,X]=(0,g.default)(q.onClick);return I(t.createElement(n.default,{component:"Checkbox",disabled:R},t.createElement("label",{className:V,style:Object.assign(Object.assign({},null==E?void 0:E.style),k),onMouseEnter:C,onMouseLeave:j,onClick:K},t.createElement(a.default,Object.assign({},q,{onClick:X,prefixCls:D,className:G,disabled:R,ref:B})),null!=v&&t.createElement("span",{className:`${D}-label`},v))))});var h=e.i(8211),x=e.i(529681),b=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var l=0,a=Object.getOwnPropertySymbols(e);lt.indexOf(a[l])&&Object.prototype.propertyIsEnumerable.call(e,a[l])&&(r[a[l]]=e[a[l]]);return r};let y=t.forwardRef((e,a)=>{let{defaultValue:l,children:n,options:s=[],prefixCls:i,className:d,rootClassName:g,style:f,onChange:y}=e,v=b(e,["defaultValue","children","options","prefixCls","className","rootClassName","style","onChange"]),{getPrefixCls:w,direction:k}=t.useContext(o.ConfigContext),[C,j]=t.useState(v.value||l||[]),[N,S]=t.useState([]);t.useEffect(()=>{"value"in v&&j(v.value||[])},[v.value]);let M=t.useMemo(()=>s.map(e=>"string"==typeof e||"number"==typeof e?{label:e,value:e}:e),[s]),T=e=>{S(t=>t.filter(t=>t!==e))},O=e=>{S(t=>[].concat((0,h.default)(t),[e]))},E=e=>{let t=C.indexOf(e.value),r=(0,h.default)(C);-1===t?r.push(e.value):r.splice(t,1),"value"in v||j(r),null==y||y(r.filter(e=>N.includes(e)).sort((e,t)=>M.findIndex(t=>t.value===e)-M.findIndex(e=>e.value===t)))},P=w("checkbox",i),$=`${P}-group`,_=(0,c.default)(P),[R,L,z]=(0,m.default)(P,_),B=(0,x.default)(v,["value","disabled"]),D=s.length?M.map(e=>t.createElement(p,{prefixCls:P,key:e.value.toString(),disabled:"disabled"in e?e.disabled:v.disabled,value:e.value,checked:C.includes(e.value),onChange:e.onChange,className:(0,r.default)(`${$}-item`,e.className),style:e.style,title:e.title,id:e.id,required:e.required},e.label)):n,F=t.useMemo(()=>({toggleOption:E,value:C,disabled:v.disabled,name:v.name,registerValue:O,cancelValue:T}),[E,C,v.disabled,v.name,O,T]),I=(0,r.default)($,{[`${$}-rtl`]:"rtl"===k},d,g,z,_,L);return R(t.createElement("div",Object.assign({className:I,style:f},B,{ref:a}),t.createElement(u.default.Provider,{value:F},D)))});p.Group=y,p.__ANT_CHECKBOX=!0,e.s(["default",0,p],374276)},536916,e=>{"use strict";var t=e.i(374276);e.s(["Checkbox",()=>t.default])},292639,e=>{"use strict";var t=e.i(764205),r=e.i(266027);let a=(0,e.i(243652).createQueryKeys)("uiSettings");e.s(["useUISettings",0,()=>(0,r.useQuery)({queryKey:a.list({}),queryFn:async()=>await (0,t.getUiSettings)(),staleTime:36e5,gcTime:36e5})])},250980,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v3m0 0v3m0-3h3m-3 0H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z"}))});e.s(["PlusCircleIcon",0,r],250980)},502547,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"}))});e.s(["ChevronRightIcon",0,r],502547)},384767,e=>{"use strict";var t=e.i(843476),r=e.i(599724),a=e.i(271645),l=e.i(389083);let n=a.forwardRef(function(e,t){return a.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:t},e),a.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4m0 5c0 2.21-3.582 4-8 4s-8-1.79-8-4"}))});var s=e.i(764205);let o=function({vectorStores:e,accessToken:o}){let[i,c]=(0,a.useState)([]);return(0,a.useEffect)(()=>{(async()=>{if(o&&0!==e.length)try{let e=await (0,s.vectorStoreListCall)(o);e.data&&c(e.data.map(e=>({vector_store_id:e.vector_store_id,vector_store_name:e.vector_store_name})))}catch(e){console.error("Error fetching vector stores:",e)}})()},[o,e.length]),(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(n,{className:"h-4 w-4 text-blue-600"}),(0,t.jsx)(r.Text,{className:"font-semibold text-gray-900",children:"Vector Stores"}),(0,t.jsx)(l.Badge,{color:"blue",size:"xs",children:e.length})]}),e.length>0?(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:e.map((e,r)=>{let a;return(0,t.jsx)("div",{className:"inline-flex items-center px-3 py-1.5 rounded-lg bg-blue-50 border border-blue-200 text-blue-800 text-sm font-medium",children:(a=i.find(t=>t.vector_store_id===e))?`${a.vector_store_name||a.vector_store_id} (${a.vector_store_id})`:e},r)})}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 border border-gray-200",children:[(0,t.jsx)(n,{className:"h-4 w-4 text-gray-400"}),(0,t.jsx)(r.Text,{className:"text-gray-500 text-sm",children:"No vector stores configured"})]})]})},i=a.forwardRef(function(e,t){return a.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:t},e),a.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01"}))});var c=e.i(871943),d=e.i(502547),u=e.i(592968);let m=function({mcpServers:n,mcpAccessGroups:o=[],mcpToolPermissions:m={},accessToken:g}){let[f,p]=(0,a.useState)([]),[h,x]=(0,a.useState)([]),[b,y]=(0,a.useState)(new Set);(0,a.useEffect)(()=>{(async()=>{if(g&&n.length>0)try{let e=await (0,s.fetchMCPServers)(g);e&&Array.isArray(e)?p(e):e.data&&Array.isArray(e.data)&&p(e.data)}catch(e){console.error("Error fetching MCP servers:",e)}})()},[g,n.length]),(0,a.useEffect)(()=>{(async()=>{if(g&&o.length>0)try{let t=await e.A(601236).then(e=>e.fetchMCPAccessGroups(g));x(Array.isArray(t)?t:t.data||[])}catch(e){console.error("Error fetching MCP access groups:",e)}})()},[g,o.length]);let v=[...n.map(e=>({type:"server",value:e})),...o.map(e=>({type:"accessGroup",value:e}))],w=v.length;return(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(i,{className:"h-4 w-4 text-blue-600"}),(0,t.jsx)(r.Text,{className:"font-semibold text-gray-900",children:"MCP Servers"}),(0,t.jsx)(l.Badge,{color:"blue",size:"xs",children:w})]}),w>0?(0,t.jsx)("div",{className:"max-h-[400px] overflow-y-auto space-y-2 pr-1",children:v.map((e,r)=>{let a="server"===e.type?m[e.value]:void 0,l=a&&a.length>0,n=b.has(e.value);return(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{onClick:()=>{var t;return l&&(t=e.value,void y(e=>{let r=new Set(e);return r.has(t)?r.delete(t):r.add(t),r}))},className:`flex items-center gap-3 py-2 px-3 rounded-lg border border-gray-200 transition-all ${l?"cursor-pointer hover:bg-gray-50 hover:border-gray-300":"bg-white"}`,children:[(0,t.jsx)("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:"server"===e.type?(0,t.jsx)(u.Tooltip,{title:`Full ID: ${e.value}`,placement:"top",children:(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 min-w-0",children:[(0,t.jsx)("span",{className:"inline-block w-1.5 h-1.5 bg-blue-500 rounded-full flex-shrink-0"}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-900 truncate",children:(e=>{let t=f.find(t=>t.server_id===e);if(t){let r=e.length>7?`${e.slice(0,3)}...${e.slice(-4)}`:e;return`${t.alias} (${r})`}return e})(e.value)})]})}):(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 min-w-0",children:[(0,t.jsx)("span",{className:"inline-block w-1.5 h-1.5 bg-green-500 rounded-full flex-shrink-0"}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-900 truncate",children:e.value}),(0,t.jsx)("span",{className:"ml-1 px-1.5 py-0.5 text-[9px] font-semibold text-green-600 bg-green-50 border border-green-200 rounded uppercase tracking-wide flex-shrink-0",children:"Group"})]})}),l&&(0,t.jsxs)("div",{className:"flex items-center gap-1 flex-shrink-0 whitespace-nowrap",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-gray-600",children:a.length}),(0,t.jsx)("span",{className:"text-xs text-gray-500",children:1===a.length?"tool":"tools"}),n?(0,t.jsx)(c.ChevronDownIcon,{className:"h-3.5 w-3.5 text-gray-400 ml-0.5"}):(0,t.jsx)(d.ChevronRightIcon,{className:"h-3.5 w-3.5 text-gray-400 ml-0.5"})]})]}),l&&n&&(0,t.jsx)("div",{className:"ml-4 pl-4 border-l-2 border-blue-200 pb-1",children:(0,t.jsx)("div",{className:"flex flex-wrap gap-1.5",children:a.map((e,r)=>(0,t.jsx)("span",{className:"inline-flex items-center px-2.5 py-1 rounded-lg bg-blue-50 border border-blue-200 text-blue-800 text-xs font-medium",children:e},r))})})]},r)})}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 border border-gray-200",children:[(0,t.jsx)(i,{className:"h-4 w-4 text-gray-400"}),(0,t.jsx)(r.Text,{className:"text-gray-500 text-sm",children:"No MCP servers or access groups configured"})]})]})},g=a.forwardRef(function(e,t){return a.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:t},e),a.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"}))}),f=function({agents:e,agentAccessGroups:n=[],accessToken:o}){let[i,c]=(0,a.useState)([]);(0,a.useEffect)(()=>{(async()=>{if(o&&e.length>0)try{let e=await (0,s.getAgentsList)(o);e&&e.agents&&Array.isArray(e.agents)&&c(e.agents)}catch(e){console.error("Error fetching agents:",e)}})()},[o,e.length]);let d=[...e.map(e=>({type:"agent",value:e})),...n.map(e=>({type:"accessGroup",value:e}))],m=d.length;return(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(g,{className:"h-4 w-4 text-purple-600"}),(0,t.jsx)(r.Text,{className:"font-semibold text-gray-900",children:"Agents"}),(0,t.jsx)(l.Badge,{color:"purple",size:"xs",children:m})]}),m>0?(0,t.jsx)("div",{className:"max-h-[400px] overflow-y-auto space-y-2 pr-1",children:d.map((e,r)=>(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsx)("div",{className:"flex items-center gap-3 py-2 px-3 rounded-lg border border-gray-200 bg-white",children:(0,t.jsx)("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:"agent"===e.type?(0,t.jsx)(u.Tooltip,{title:`Full ID: ${e.value}`,placement:"top",children:(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 min-w-0",children:[(0,t.jsx)("span",{className:"inline-block w-1.5 h-1.5 bg-purple-500 rounded-full flex-shrink-0"}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-900 truncate",children:(e=>{let t=i.find(t=>t.agent_id===e);if(t){let r=e.length>7?`${e.slice(0,3)}...${e.slice(-4)}`:e;return`${t.agent_name} (${r})`}return e})(e.value)})]})}):(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 min-w-0",children:[(0,t.jsx)("span",{className:"inline-block w-1.5 h-1.5 bg-green-500 rounded-full flex-shrink-0"}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-900 truncate",children:e.value}),(0,t.jsx)("span",{className:"ml-1 px-1.5 py-0.5 text-[9px] font-semibold text-green-600 bg-green-50 border border-green-200 rounded uppercase tracking-wide flex-shrink-0",children:"Group"})]})})})},r))}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 border border-gray-200",children:[(0,t.jsx)(g,{className:"h-4 w-4 text-gray-400"}),(0,t.jsx)(r.Text,{className:"text-gray-500 text-sm",children:"No agents or access groups configured"})]})]})};e.s(["default",0,function({objectPermission:e,variant:a="card",className:l="",accessToken:n}){let s=e?.vector_stores||[],i=e?.mcp_servers||[],c=e?.mcp_access_groups||[],d=e?.mcp_tool_permissions||{},u=e?.agents||[],g=e?.agent_access_groups||[],p=(0,t.jsxs)("div",{className:"card"===a?"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6":"space-y-4",children:[(0,t.jsx)(o,{vectorStores:s,accessToken:n}),(0,t.jsx)(m,{mcpServers:i,mcpAccessGroups:c,mcpToolPermissions:d,accessToken:n}),(0,t.jsx)(f,{agents:u,agentAccessGroups:g,accessToken:n})]});return"card"===a?(0,t.jsxs)("div",{className:`bg-white border border-gray-200 rounded-lg p-6 ${l}`,children:[(0,t.jsx)("div",{className:"flex items-center gap-2 mb-6",children:(0,t.jsxs)("div",{children:[(0,t.jsx)(r.Text,{className:"font-semibold text-gray-900",children:"Object Permissions"}),(0,t.jsx)(r.Text,{className:"text-xs text-gray-500",children:"Access control for Vector Stores and MCP Servers"})]})}),p]}):(0,t.jsxs)("div",{className:`${l}`,children:[(0,t.jsx)(r.Text,{className:"font-medium text-gray-900 mb-3",children:"Object Permissions"}),p]})}],384767)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/531dc633eecbb64f.js b/litellm/proxy/_experimental/out/_next/static/chunks/531dc633eecbb64f.js new file mode 100644 index 00000000000..8ed318457c7 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/531dc633eecbb64f.js @@ -0,0 +1,8 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,162386,e=>{"use strict";var t=e.i(843476),l=e.i(625901),a=e.i(109799),r=e.i(785242),i=e.i(738014),s=e.i(199133),n=e.i(981339),o=e.i(592968);let d={label:"All Proxy Models",value:"all-proxy-models"},c={label:"No Default Models",value:"no-default-models"},u=[d,c],m={user:({allProxyModels:e,userModels:t,options:l})=>t&&l?.includeUserModels?t:[],team:({allProxyModels:e,selectedOrganization:t,userModels:l})=>t?t.models.includes(d.value)||0===t.models.length?e:e.filter(e=>t.models.includes(e)):e??[],organization:({allProxyModels:e})=>e,global:({allProxyModels:e})=>e};e.s(["ModelSelect",0,e=>{let{teamID:h,organizationID:g,options:f,context:p,dataTestId:b,value:v=[],onChange:x,style:y}=e,{includeUserModels:j,showAllTeamModelsOption:w,showAllProxyModelsOverride:k,includeSpecialOptions:C}=f||{},{data:O,isLoading:$}=(0,l.useAllProxyModels)(),{data:N,isLoading:E}=(0,r.useTeam)(h),{data:T,isLoading:_}=(0,a.useOrganization)(g),{data:M,isLoading:I}=(0,i.useCurrentUser)(),S=e=>u.some(t=>t.value===e),R=v.some(S),P=T?.models.includes(d.value)||T?.models.length===0;if($||E||_||I)return(0,t.jsx)(n.Skeleton.Input,{active:!0,block:!0});let{wildcard:q,regular:A}=(e=>{let t=[],l=[];for(let a of e)a.endsWith("/*")?t.push(a):l.push(a);return{wildcard:t,regular:l}})(((e,t,l)=>{let a=Array.from(new Map(e.map(e=>[e.id,e])).values()).map(e=>e.id);if(t.options?.showAllProxyModelsOverride)return a;let r=m[t.context];return r?r({allProxyModels:a,...l,options:t.options}):[]})(O?.data??[],e,{selectedTeam:N,selectedOrganization:T,userModels:M?.models}));return(0,t.jsx)(s.Select,{"data-testid":b,value:v,onChange:e=>{let t=e.filter(S);x(t.length>0?[t[t.length-1]]:e)},style:y,options:[C?{label:(0,t.jsx)("span",{children:"Special Options"}),title:"Special Options",options:[...k||P&&C||"global"===p?[{label:(0,t.jsx)("span",{children:"All Proxy Models"}),value:d.value,disabled:v.length>0&&v.some(e=>S(e)&&e!==d.value),key:d.value}]:[],{label:(0,t.jsx)("span",{children:"No Default Models"}),value:c.value,disabled:v.length>0&&v.some(e=>S(e)&&e!==c.value),key:c.value}]}:[],...q.length>0?[{label:(0,t.jsx)("span",{children:"Wildcard Options"}),title:"Wildcard Options",options:q.map(e=>{let l=e.replace("/*",""),a=l.charAt(0).toUpperCase()+l.slice(1);return{label:(0,t.jsx)("span",{children:`All ${a} models`}),value:e,disabled:R}})}]:[],{label:(0,t.jsx)("span",{children:"Models"}),title:"Models",options:A.map(e=>({label:(0,t.jsx)("span",{children:e}),value:e,disabled:R}))}],mode:"multiple",placeholder:"Select Models",allowClear:!0,maxTagCount:"responsive",maxTagPlaceholder:e=>(0,t.jsx)(o.Tooltip,{styles:{root:{pointerEvents:"none"}},title:e.map(({value:e})=>e).join(", "),children:(0,t.jsxs)("span",{children:["+",e.length," more"]})})})}],162386)},294612,e=>{"use strict";var t=e.i(843476),l=e.i(100486),a=e.i(827252),r=e.i(213205),i=e.i(771674),s=e.i(464571),n=e.i(770914),o=e.i(291542),d=e.i(262218),c=e.i(592968),u=e.i(898586),m=e.i(902555);let{Text:h}=u.Typography;function g({members:e,canEdit:u,onEdit:g,onDelete:f,onAddMember:p,roleColumnTitle:b="Role",roleTooltip:v,extraColumns:x=[],showDeleteForMember:y,emptyText:j}){let w=[{title:"User Email",dataIndex:"user_email",key:"user_email",render:e=>(0,t.jsx)(h,{children:e||"-"})},{title:"User ID",dataIndex:"user_id",key:"user_id",render:e=>"default_user_id"===e?(0,t.jsx)(d.Tag,{color:"blue",children:"Default Proxy Admin"}):(0,t.jsx)(h,{children:e||"-"})},{title:v?(0,t.jsxs)(n.Space,{direction:"horizontal",children:[b,(0,t.jsx)(c.Tooltip,{title:v,children:(0,t.jsx)(a.InfoCircleOutlined,{})})]}):b,dataIndex:"role",key:"role",render:e=>(0,t.jsxs)(n.Space,{children:[e?.toLowerCase()==="admin"||e?.toLowerCase()==="org_admin"?(0,t.jsx)(l.CrownOutlined,{}):(0,t.jsx)(i.UserOutlined,{}),(0,t.jsx)(h,{style:{textTransform:"capitalize"},children:e||"-"})]})},...x,{title:"Actions",key:"actions",fixed:"right",width:120,render:(e,l)=>u?(0,t.jsxs)(n.Space,{children:[(0,t.jsx)(m.default,{variant:"Edit",tooltipText:"Edit member",dataTestId:"edit-member",onClick:()=>g(l)}),(!y||y(l))&&(0,t.jsx)(m.default,{variant:"Delete",tooltipText:"Delete member",dataTestId:"delete-member",onClick:()=>f(l)})]}):null}];return(0,t.jsxs)(n.Space,{direction:"vertical",style:{width:"100%"},children:[(0,t.jsxs)("span",{className:"inline-flex text-sm text-gray-700",children:[e.length," Member",1!==e.length?"s":""]}),(0,t.jsx)(o.Table,{columns:w,dataSource:e,rowKey:e=>e.user_id??e.user_email??JSON.stringify(e),pagination:!1,size:"small",scroll:{x:"max-content"},locale:j?{emptyText:j}:void 0}),p&&u&&(0,t.jsx)(s.Button,{icon:(0,t.jsx)(r.UserAddOutlined,{}),type:"primary",onClick:p,children:"Add Member"})]})}e.s(["default",()=>g])},907308,e=>{"use strict";var t=e.i(843476),l=e.i(271645),a=e.i(212931),r=e.i(808613),i=e.i(464571),s=e.i(199133),n=e.i(592968),o=e.i(213205),d=e.i(374009),c=e.i(764205);e.s(["default",0,({isVisible:e,onCancel:u,onSubmit:m,accessToken:h,title:g="Add Team Member",roles:f=[{label:"admin",value:"admin",description:"Admin role. Can create team keys, add members, and manage settings."},{label:"user",value:"user",description:"User role. Can view team info, but not manage it."}],defaultRole:p="user",teamId:b})=>{let[v]=r.Form.useForm(),[x,y]=(0,l.useState)([]),[j,w]=(0,l.useState)(!1),[k,C]=(0,l.useState)("user_email"),[O,$]=(0,l.useState)(!1),N=async(e,t)=>{if(!e)return void y([]);w(!0);try{let l=new URLSearchParams;if(l.append(t,e),b&&l.append("team_id",b),null==h)return;let a=(await (0,c.userFilterUICall)(h,l)).map(e=>({label:"user_email"===t?`${e.user_email}`:`${e.user_id}`,value:"user_email"===t?e.user_email:e.user_id,user:e}));y(a)}catch(e){console.error("Error fetching users:",e)}finally{w(!1)}},E=(0,l.useCallback)((0,d.default)((e,t)=>N(e,t),300),[]),T=(e,t)=>{C(t),E(e,t)},_=(e,t)=>{let l=t.user;v.setFieldsValue({user_email:l.user_email,user_id:l.user_id,role:v.getFieldValue("role")})},M=async e=>{$(!0);try{await m(e)}finally{$(!1)}};return(0,t.jsx)(a.Modal,{title:g,open:e,onCancel:()=>{v.resetFields(),y([]),u()},footer:null,width:800,maskClosable:!O,children:(0,t.jsxs)(r.Form,{form:v,onFinish:M,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",initialValues:{role:p},children:[(0,t.jsx)(r.Form.Item,{label:"Email",name:"user_email",className:"mb-4",children:(0,t.jsx)(s.Select,{showSearch:!0,className:"w-full",placeholder:"Search by email",filterOption:!1,onSearch:e=>T(e,"user_email"),onSelect:(e,t)=>_(e,t),options:"user_email"===k?x:[],loading:j,allowClear:!0})}),(0,t.jsx)("div",{className:"text-center mb-4",children:"OR"}),(0,t.jsx)(r.Form.Item,{label:"User ID",name:"user_id",className:"mb-4",children:(0,t.jsx)(s.Select,{showSearch:!0,className:"w-full",placeholder:"Search by user ID",filterOption:!1,onSearch:e=>T(e,"user_id"),onSelect:(e,t)=>_(e,t),options:"user_id"===k?x:[],loading:j,allowClear:!0})}),(0,t.jsx)(r.Form.Item,{label:"Member Role",name:"role",className:"mb-4",children:(0,t.jsx)(s.Select,{defaultValue:p,children:f.map(e=>(0,t.jsx)(s.Select.Option,{value:e.value,children:(0,t.jsxs)(n.Tooltip,{title:e.description,children:[(0,t.jsx)("span",{className:"font-medium",children:e.label}),(0,t.jsxs)("span",{className:"ml-2 text-gray-500 text-sm",children:["- ",e.description]})]})},e.value))})}),(0,t.jsx)("div",{className:"text-right mt-4",children:(0,t.jsx)(i.Button,{type:"primary",htmlType:"submit",icon:(0,t.jsx)(o.UserAddOutlined,{}),loading:O,children:O?"Adding...":"Add Member"})})]})})}])},276173,e=>{"use strict";var t=e.i(843476),l=e.i(599724),a=e.i(779241),r=e.i(464571),i=e.i(808613),s=e.i(212931),n=e.i(199133),o=e.i(271645),d=e.i(435451);e.s(["default",0,({visible:e,onCancel:c,onSubmit:u,initialData:m,mode:h,config:g})=>{let f,[p]=i.Form.useForm(),[b,v]=(0,o.useState)(!1);console.log("Initial Data:",m),(0,o.useEffect)(()=>{if(e)if("edit"===h&&m){let e={...m,role:m.role||g.defaultRole,max_budget_in_team:m.max_budget_in_team||null,tpm_limit:m.tpm_limit||null,rpm_limit:m.rpm_limit||null};console.log("Setting form values:",e),p.setFieldsValue(e)}else p.resetFields(),p.setFieldsValue({role:g.defaultRole||g.roleOptions[0]?.value})},[e,m,h,p,g.defaultRole,g.roleOptions]);let x=async e=>{try{v(!0);let t=Object.entries(e).reduce((e,[t,l])=>{if("string"==typeof l){let a=l.trim();return""===a&&("max_budget_in_team"===t||"tpm_limit"===t||"rpm_limit"===t)?{...e,[t]:null}:{...e,[t]:a}}return{...e,[t]:l}},{});console.log("Submitting form data:",t),await Promise.resolve(u(t)),p.resetFields()}catch(e){console.error("Form submission error:",e)}finally{v(!1)}};return(0,t.jsx)(s.Modal,{title:g.title||("add"===h?"Add Member":"Edit Member"),open:e,width:1e3,footer:null,onCancel:c,children:(0,t.jsxs)(i.Form,{form:p,onFinish:x,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[g.showEmail&&(0,t.jsx)(i.Form.Item,{label:"Email",name:"user_email",className:"mb-4",rules:[{type:"email",message:"Please enter a valid email!"}],children:(0,t.jsx)(a.TextInput,{placeholder:"user@example.com"})}),g.showEmail&&g.showUserId&&(0,t.jsx)("div",{className:"text-center mb-4",children:(0,t.jsx)(l.Text,{children:"OR"})}),g.showUserId&&(0,t.jsx)(i.Form.Item,{label:"User ID",name:"user_id",className:"mb-4",children:(0,t.jsx)(a.TextInput,{placeholder:"user_123"})}),(0,t.jsx)(i.Form.Item,{label:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{children:"Role"}),"edit"===h&&m&&(0,t.jsxs)("span",{className:"text-gray-500 text-sm",children:["(Current: ",(f=m.role,g.roleOptions.find(e=>e.value===f)?.label||f),")"]})]}),name:"role",className:"mb-4",rules:[{required:!0,message:"Please select a role!"}],children:(0,t.jsx)(n.Select,{children:"edit"===h&&m?[...g.roleOptions.filter(e=>e.value===m.role),...g.roleOptions.filter(e=>e.value!==m.role)].map(e=>(0,t.jsx)(n.Select.Option,{value:e.value,children:e.label},e.value)):g.roleOptions.map(e=>(0,t.jsx)(n.Select.Option,{value:e.value,children:e.label},e.value))})}),g.additionalFields?.map(e=>(0,t.jsx)(i.Form.Item,{label:e.label,name:e.name,className:"mb-4",rules:e.rules,children:(e=>{switch(e.type){case"input":return(0,t.jsx)(a.TextInput,{placeholder:e.placeholder});case"numerical":return(0,t.jsx)(d.default,{step:e.step||1,min:e.min||0,style:{width:"100%"},placeholder:e.placeholder||"Enter a numerical value"});case"select":return(0,t.jsx)(n.Select,{children:e.options?.map(e=>(0,t.jsx)(n.Select.Option,{value:e.value,children:e.label},e.value))});default:return null}})(e)},e.name)),(0,t.jsxs)("div",{className:"text-right mt-6",children:[(0,t.jsx)(r.Button,{onClick:c,className:"mr-2",disabled:b,children:"Cancel"}),(0,t.jsx)(r.Button,{type:"default",htmlType:"submit",loading:b,children:"add"===h?b?"Adding...":"Add Member":b?"Saving...":"Save Changes"})]})]})})}])},434626,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.createElement("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"}))});e.s(["ExternalLinkIcon",0,l],434626)},902555,e=>{"use strict";var t=e.i(843476),l=e.i(591935),a=e.i(122577),r=e.i(278587),i=e.i(68155),s=e.i(360820),n=e.i(871943),o=e.i(434626),d=e.i(592968),c=e.i(115504),u=e.i(752978);function m({icon:e,onClick:l,className:a,disabled:r,dataTestId:i}){return r?(0,t.jsx)(u.Icon,{icon:e,size:"sm",className:"opacity-50 cursor-not-allowed","data-testid":i}):(0,t.jsx)(u.Icon,{icon:e,size:"sm",onClick:l,className:(0,c.cx)("cursor-pointer",a),"data-testid":i})}let h={Edit:{icon:l.PencilAltIcon,className:"hover:text-blue-600"},Delete:{icon:i.TrashIcon,className:"hover:text-red-600"},Test:{icon:a.PlayIcon,className:"hover:text-blue-600"},Regenerate:{icon:r.RefreshIcon,className:"hover:text-green-600"},Up:{icon:s.ChevronUpIcon,className:"hover:text-blue-600"},Down:{icon:n.ChevronDownIcon,className:"hover:text-blue-600"},Open:{icon:o.ExternalLinkIcon,className:"hover:text-green-600"}};function g({onClick:e,tooltipText:l,disabled:a=!1,disabledTooltipText:r,dataTestId:i,variant:s}){let{icon:n,className:o}=h[s];return(0,t.jsx)(d.Tooltip,{title:a?r:l,children:(0,t.jsx)("span",{children:(0,t.jsx)(m,{icon:n,onClick:e,className:o,disabled:a,dataTestId:i})})})}e.s(["default",()=>g],902555)},122577,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"}),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 12a9 9 0 11-18 0 9 9 0 0118 0z"}))});e.s(["PlayIcon",0,l],122577)},591935,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.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.s(["PencilAltIcon",0,l],591935)},871943,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"}))});e.s(["ChevronDownIcon",0,l],871943)},360820,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 15l7-7 7 7"}))});e.s(["ChevronUpIcon",0,l],360820)},185793,e=>{"use strict";e.i(247167);var t=e.i(271645),l=e.i(343794),a=e.i(242064),r=e.i(529681);let i=e=>{let{prefixCls:a,className:r,style:i,size:s,shape:n}=e,o=(0,l.default)({[`${a}-lg`]:"large"===s,[`${a}-sm`]:"small"===s}),d=(0,l.default)({[`${a}-circle`]:"circle"===n,[`${a}-square`]:"square"===n,[`${a}-round`]:"round"===n}),c=t.useMemo(()=>"number"==typeof s?{width:s,height:s,lineHeight:`${s}px`}:{},[s]);return t.createElement("span",{className:(0,l.default)(a,o,d,r),style:Object.assign(Object.assign({},c),i)})};e.i(296059);var s=e.i(694758),n=e.i(915654),o=e.i(246422),d=e.i(838378);let c=new s.Keyframes("ant-skeleton-loading",{"0%":{backgroundPosition:"100% 50%"},"100%":{backgroundPosition:"0 50%"}}),u=e=>({height:e,lineHeight:(0,n.unit)(e)}),m=e=>Object.assign({width:e},u(e)),h=(e,t)=>Object.assign({width:t(e).mul(5).equal(),minWidth:t(e).mul(5).equal()},u(e)),g=e=>Object.assign({width:e},u(e)),f=(e,t,l)=>{let{skeletonButtonCls:a}=e;return{[`${l}${a}-circle`]:{width:t,minWidth:t,borderRadius:"50%"},[`${l}${a}-round`]:{borderRadius:t}}},p=(e,t)=>Object.assign({width:t(e).mul(2).equal(),minWidth:t(e).mul(2).equal()},u(e)),b=(0,o.genStyleHooks)("Skeleton",e=>{let{componentCls:t,calc:l}=e;return(e=>{let{componentCls:t,skeletonAvatarCls:l,skeletonTitleCls:a,skeletonParagraphCls:r,skeletonButtonCls:i,skeletonInputCls:s,skeletonImageCls:n,controlHeight:o,controlHeightLG:d,controlHeightSM:u,gradientFromColor:b,padding:v,marginSM:x,borderRadius:y,titleHeight:j,blockRadius:w,paragraphLiHeight:k,controlHeightXS:C,paragraphMarginTop:O}=e;return{[t]:{display:"table",width:"100%",[`${t}-header`]:{display:"table-cell",paddingInlineEnd:v,verticalAlign:"top",[l]:Object.assign({display:"inline-block",verticalAlign:"top",background:b},m(o)),[`${l}-circle`]:{borderRadius:"50%"},[`${l}-lg`]:Object.assign({},m(d)),[`${l}-sm`]:Object.assign({},m(u))},[`${t}-content`]:{display:"table-cell",width:"100%",verticalAlign:"top",[a]:{width:"100%",height:j,background:b,borderRadius:w,[`+ ${r}`]:{marginBlockStart:u}},[r]:{padding:0,"> li":{width:"100%",height:k,listStyle:"none",background:b,borderRadius:w,"+ li":{marginBlockStart:C}}},[`${r}> li:last-child:not(:first-child):not(:nth-child(2))`]:{width:"61%"}},[`&-round ${t}-content`]:{[`${a}, ${r} > li`]:{borderRadius:y}}},[`${t}-with-avatar ${t}-content`]:{[a]:{marginBlockStart:x,[`+ ${r}`]:{marginBlockStart:O}}},[`${t}${t}-element`]:Object.assign(Object.assign(Object.assign(Object.assign({display:"inline-block",width:"auto"},(e=>{let{borderRadiusSM:t,skeletonButtonCls:l,controlHeight:a,controlHeightLG:r,controlHeightSM:i,gradientFromColor:s,calc:n}=e;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({[l]:Object.assign({display:"inline-block",verticalAlign:"top",background:s,borderRadius:t,width:n(a).mul(2).equal(),minWidth:n(a).mul(2).equal()},p(a,n))},f(e,a,l)),{[`${l}-lg`]:Object.assign({},p(r,n))}),f(e,r,`${l}-lg`)),{[`${l}-sm`]:Object.assign({},p(i,n))}),f(e,i,`${l}-sm`))})(e)),(e=>{let{skeletonAvatarCls:t,gradientFromColor:l,controlHeight:a,controlHeightLG:r,controlHeightSM:i}=e;return{[t]:Object.assign({display:"inline-block",verticalAlign:"top",background:l},m(a)),[`${t}${t}-circle`]:{borderRadius:"50%"},[`${t}${t}-lg`]:Object.assign({},m(r)),[`${t}${t}-sm`]:Object.assign({},m(i))}})(e)),(e=>{let{controlHeight:t,borderRadiusSM:l,skeletonInputCls:a,controlHeightLG:r,controlHeightSM:i,gradientFromColor:s,calc:n}=e;return{[a]:Object.assign({display:"inline-block",verticalAlign:"top",background:s,borderRadius:l},h(t,n)),[`${a}-lg`]:Object.assign({},h(r,n)),[`${a}-sm`]:Object.assign({},h(i,n))}})(e)),(e=>{let{skeletonImageCls:t,imageSizeBase:l,gradientFromColor:a,borderRadiusSM:r,calc:i}=e;return{[t]:Object.assign(Object.assign({display:"inline-flex",alignItems:"center",justifyContent:"center",verticalAlign:"middle",background:a,borderRadius:r},g(i(l).mul(2).equal())),{[`${t}-path`]:{fill:"#bfbfbf"},[`${t}-svg`]:Object.assign(Object.assign({},g(l)),{maxWidth:i(l).mul(4).equal(),maxHeight:i(l).mul(4).equal()}),[`${t}-svg${t}-svg-circle`]:{borderRadius:"50%"}}),[`${t}${t}-circle`]:{borderRadius:"50%"}}})(e)),[`${t}${t}-block`]:{width:"100%",[i]:{width:"100%"},[s]:{width:"100%"}},[`${t}${t}-active`]:{[` + ${a}, + ${r} > li, + ${l}, + ${i}, + ${s}, + ${n} + `]:Object.assign({},{background:e.skeletonLoadingBackground,backgroundSize:"400% 100%",animationName:c,animationDuration:e.skeletonLoadingMotionDuration,animationTimingFunction:"ease",animationIterationCount:"infinite"})}}})((0,d.mergeToken)(e,{skeletonAvatarCls:`${t}-avatar`,skeletonTitleCls:`${t}-title`,skeletonParagraphCls:`${t}-paragraph`,skeletonButtonCls:`${t}-button`,skeletonInputCls:`${t}-input`,skeletonImageCls:`${t}-image`,imageSizeBase:l(e.controlHeight).mul(1.5).equal(),borderRadius:100,skeletonLoadingBackground:`linear-gradient(90deg, ${e.gradientFromColor} 25%, ${e.gradientToColor} 37%, ${e.gradientFromColor} 63%)`,skeletonLoadingMotionDuration:"1.4s"}))},e=>{let{colorFillContent:t,colorFill:l}=e;return{color:t,colorGradientEnd:l,gradientFromColor:t,gradientToColor:l,titleHeight:e.controlHeight/2,blockRadius:e.borderRadiusSM,paragraphMarginTop:e.marginLG+e.marginXXS,paragraphLiHeight:e.controlHeight/2}},{deprecatedTokens:[["color","gradientFromColor"],["colorGradientEnd","gradientToColor"]]}),v=e=>{let{prefixCls:a,className:r,style:i,rows:s=0}=e,n=Array.from({length:s}).map((l,a)=>t.createElement("li",{key:a,style:{width:((e,t)=>{let{width:l,rows:a=2}=t;return Array.isArray(l)?l[e]:a-1===e?l:void 0})(a,e)}}));return t.createElement("ul",{className:(0,l.default)(a,r),style:i},n)},x=({prefixCls:e,className:a,width:r,style:i})=>t.createElement("h3",{className:(0,l.default)(e,a),style:Object.assign({width:r},i)});function y(e){return e&&"object"==typeof e?e:{}}let j=e=>{let{prefixCls:r,loading:s,className:n,rootClassName:o,style:d,children:c,avatar:u=!1,title:m=!0,paragraph:h=!0,active:g,round:f}=e,{getPrefixCls:p,direction:j,className:w,style:k}=(0,a.useComponentConfig)("skeleton"),C=p("skeleton",r),[O,$,N]=b(C);if(s||!("loading"in e)){let e,a,r=!!u,s=!!m,c=!!h;if(r){let l=Object.assign(Object.assign({prefixCls:`${C}-avatar`},s&&!c?{size:"large",shape:"square"}:{size:"large",shape:"circle"}),y(u));e=t.createElement("div",{className:`${C}-header`},t.createElement(i,Object.assign({},l)))}if(s||c){let e,l;if(s){let l=Object.assign(Object.assign({prefixCls:`${C}-title`},!r&&c?{width:"38%"}:r&&c?{width:"50%"}:{}),y(m));e=t.createElement(x,Object.assign({},l))}if(c){let e,a=Object.assign(Object.assign({prefixCls:`${C}-paragraph`},(e={},r&&s||(e.width="61%"),!r&&s?e.rows=3:e.rows=2,e)),y(h));l=t.createElement(v,Object.assign({},a))}a=t.createElement("div",{className:`${C}-content`},e,l)}let p=(0,l.default)(C,{[`${C}-with-avatar`]:r,[`${C}-active`]:g,[`${C}-rtl`]:"rtl"===j,[`${C}-round`]:f},w,n,o,$,N);return O(t.createElement("div",{className:p,style:Object.assign(Object.assign({},k),d)},e,a))}return null!=c?c:null};j.Button=e=>{let{prefixCls:s,className:n,rootClassName:o,active:d,block:c=!1,size:u="default"}=e,{getPrefixCls:m}=t.useContext(a.ConfigContext),h=m("skeleton",s),[g,f,p]=b(h),v=(0,r.default)(e,["prefixCls"]),x=(0,l.default)(h,`${h}-element`,{[`${h}-active`]:d,[`${h}-block`]:c},n,o,f,p);return g(t.createElement("div",{className:x},t.createElement(i,Object.assign({prefixCls:`${h}-button`,size:u},v))))},j.Avatar=e=>{let{prefixCls:s,className:n,rootClassName:o,active:d,shape:c="circle",size:u="default"}=e,{getPrefixCls:m}=t.useContext(a.ConfigContext),h=m("skeleton",s),[g,f,p]=b(h),v=(0,r.default)(e,["prefixCls","className"]),x=(0,l.default)(h,`${h}-element`,{[`${h}-active`]:d},n,o,f,p);return g(t.createElement("div",{className:x},t.createElement(i,Object.assign({prefixCls:`${h}-avatar`,shape:c,size:u},v))))},j.Input=e=>{let{prefixCls:s,className:n,rootClassName:o,active:d,block:c,size:u="default"}=e,{getPrefixCls:m}=t.useContext(a.ConfigContext),h=m("skeleton",s),[g,f,p]=b(h),v=(0,r.default)(e,["prefixCls"]),x=(0,l.default)(h,`${h}-element`,{[`${h}-active`]:d,[`${h}-block`]:c},n,o,f,p);return g(t.createElement("div",{className:x},t.createElement(i,Object.assign({prefixCls:`${h}-input`,size:u},v))))},j.Image=e=>{let{prefixCls:r,className:i,rootClassName:s,style:n,active:o}=e,{getPrefixCls:d}=t.useContext(a.ConfigContext),c=d("skeleton",r),[u,m,h]=b(c),g=(0,l.default)(c,`${c}-element`,{[`${c}-active`]:o},i,s,m,h);return u(t.createElement("div",{className:g},t.createElement("div",{className:(0,l.default)(`${c}-image`,i),style:n},t.createElement("svg",{viewBox:"0 0 1098 1024",xmlns:"http://www.w3.org/2000/svg",className:`${c}-image-svg`},t.createElement("title",null,"Image placeholder"),t.createElement("path",{d:"M365.714286 329.142857q0 45.714286-32.036571 77.677714t-77.677714 32.036571-77.677714-32.036571-32.036571-77.677714 32.036571-77.677714 77.677714-32.036571 77.677714 32.036571 32.036571 77.677714zM950.857143 548.571429l0 256-804.571429 0 0-109.714286 182.857143-182.857143 91.428571 91.428571 292.571429-292.571429zM1005.714286 146.285714l-914.285714 0q-7.460571 0-12.873143 5.412571t-5.412571 12.873143l0 694.857143q0 7.460571 5.412571 12.873143t12.873143 5.412571l914.285714 0q7.460571 0 12.873143-5.412571t5.412571-12.873143l0-694.857143q0-7.460571-5.412571-12.873143t-12.873143-5.412571zM1097.142857 164.571429l0 694.857143q0 37.741714-26.843429 64.585143t-64.585143 26.843429l-914.285714 0q-37.741714 0-64.585143-26.843429t-26.843429-64.585143l0-694.857143q0-37.741714 26.843429-64.585143t64.585143-26.843429l914.285714 0q37.741714 0 64.585143 26.843429t26.843429 64.585143z",className:`${c}-image-path`})))))},j.Node=e=>{let{prefixCls:r,className:i,rootClassName:s,style:n,active:o,children:d}=e,{getPrefixCls:c}=t.useContext(a.ConfigContext),u=c("skeleton",r),[m,h,g]=b(u),f=(0,l.default)(u,`${u}-element`,{[`${u}-active`]:o},h,i,s,g);return m(t.createElement("div",{className:f},t.createElement("div",{className:(0,l.default)(`${u}-image`,i),style:n},d)))},e.s(["default",0,j],185793)},959013,e=>{"use strict";e.i(247167);var t=e.i(931067),l=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8z"}},{tag:"path",attrs:{d:"M192 474h672q8 0 8 8v60q0 8-8 8H160q-8 0-8-8v-60q0-8 8-8z"}}]},name:"plus",theme:"outlined"};var r=e.i(9583),i=l.forwardRef(function(e,i){return l.createElement(r.default,(0,t.default)({},e,{ref:i,icon:a}))});e.s(["default",0,i],959013)},269200,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("Table"),i=l.default.forwardRef((e,i)=>{let{children:s,className:n}=e,o=(0,t.__rest)(e,["children","className"]);return l.default.createElement("div",{className:(0,a.tremorTwMerge)(r("root"),"overflow-auto",n)},l.default.createElement("table",Object.assign({ref:i,className:(0,a.tremorTwMerge)(r("table"),"w-full text-tremor-default","text-tremor-content","dark:text-dark-tremor-content")},o),s))});i.displayName="Table",e.s(["Table",()=>i],269200)},942232,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("TableBody"),i=l.default.forwardRef((e,i)=>{let{children:s,className:n}=e,o=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("tbody",Object.assign({ref:i,className:(0,a.tremorTwMerge)(r("root"),"align-top divide-y","divide-tremor-border","dark:divide-dark-tremor-border",n)},o),s))});i.displayName="TableBody",e.s(["TableBody",()=>i],942232)},977572,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("TableCell"),i=l.default.forwardRef((e,i)=>{let{children:s,className:n}=e,o=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("td",Object.assign({ref:i,className:(0,a.tremorTwMerge)(r("root"),"align-middle whitespace-nowrap text-left p-4",n)},o),s))});i.displayName="TableCell",e.s(["TableCell",()=>i],977572)},427612,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("TableHead"),i=l.default.forwardRef((e,i)=>{let{children:s,className:n}=e,o=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("thead",Object.assign({ref:i,className:(0,a.tremorTwMerge)(r("root"),"text-left","text-tremor-content","dark:text-dark-tremor-content",n)},o),s))});i.displayName="TableHead",e.s(["TableHead",()=>i],427612)},64848,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("TableHeaderCell"),i=l.default.forwardRef((e,i)=>{let{children:s,className:n}=e,o=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("th",Object.assign({ref:i,className:(0,a.tremorTwMerge)(r("root"),"whitespace-nowrap text-left font-semibold top-0 px-4 py-3.5","text-tremor-content-strong","dark:text-dark-tremor-content-strong",n)},o),s))});i.displayName="TableHeaderCell",e.s(["TableHeaderCell",()=>i],64848)},496020,e=>{"use strict";var t=e.i(290571),l=e.i(271645),a=e.i(444755);let r=(0,e.i(673706).makeClassName)("TableRow"),i=l.default.forwardRef((e,i)=>{let{children:s,className:n}=e,o=(0,t.__rest)(e,["children","className"]);return l.default.createElement(l.default.Fragment,null,l.default.createElement("tr",Object.assign({ref:i,className:(0,a.tremorTwMerge)(r("row"),n)},o),s))});i.displayName="TableRow",e.s(["TableRow",()=>i],496020)},68155,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.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.s(["TrashIcon",0,l],68155)},278587,e=>{"use strict";var t=e.i(271645);let l=t.forwardRef(function(e,l){return t.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:l},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",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"}))});e.s(["RefreshIcon",0,l],278587)},207670,e=>{"use strict";function t(){for(var e,t,l=0,a="",r=arguments.length;lt,"default",0,t])},625901,e=>{"use strict";var t=e.i(266027),l=e.i(621482),a=e.i(243652),r=e.i(764205),i=e.i(135214);let s=(0,a.createQueryKeys)("models"),n=(0,a.createQueryKeys)("modelHub"),o=(0,a.createQueryKeys)("allProxyModels");(0,a.createQueryKeys)("selectedTeamModels");let d=(0,a.createQueryKeys)("infiniteModels");e.s(["useAllProxyModels",0,()=>{let{accessToken:e,userId:l,userRole:a}=(0,i.default)();return(0,t.useQuery)({queryKey:o.list({}),queryFn:async()=>await (0,r.modelAvailableCall)(e,l,a,!0,null,!0,!1,"expand"),enabled:!!(e&&l&&a)})},"useInfiniteModelInfo",0,(e=50,t)=>{let{accessToken:a,userId:s,userRole:n}=(0,i.default)();return(0,l.useInfiniteQuery)({queryKey:d.list({filters:{...s&&{userId:s},...n&&{userRole:n},size:e,...t&&{search:t}}}),queryFn:async({pageParam:l})=>await (0,r.modelInfoCall)(a,s,n,l,e,t),initialPageParam:1,getNextPageParam:e=>{if(e.current_page{let{accessToken:e}=(0,i.default)();return(0,t.useQuery)({queryKey:n.list({}),queryFn:async()=>await (0,r.modelHubCall)(e),enabled:!!e})},"useModelsInfo",0,(e=1,l=50,a,n,o,d,c)=>{let{accessToken:u,userId:m,userRole:h}=(0,i.default)();return(0,t.useQuery)({queryKey:s.list({filters:{...m&&{userId:m},...h&&{userRole:h},page:e,size:l,...a&&{search:a},...n&&{modelId:n},...o&&{teamId:o},...d&&{sortBy:d},...c&&{sortOrder:c}}}),queryFn:async()=>await (0,r.modelInfoCall)(u,m,h,e,l,a,n,o,d,c),enabled:!!(u&&m&&h)})}])},621482,e=>{"use strict";var t=e.i(869230),l=e.i(992571),a=class extends t.QueryObserver{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){super.setOptions({...e,behavior:(0,l.infiniteQueryBehavior)()})}getOptimisticResult(e){return e.behavior=(0,l.infiniteQueryBehavior)(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:a}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:s,isError:n,isRefetchError:o}=r,d=a.fetchMeta?.fetchMore?.direction,c=n&&"forward"===d,u=i&&"forward"===d,m=n&&"backward"===d,h=i&&"backward"===d;return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:(0,l.hasNextPage)(t,a.data),hasPreviousPage:(0,l.hasPreviousPage)(t,a.data),isFetchNextPageError:c,isFetchingNextPage:u,isFetchPreviousPageError:m,isFetchingPreviousPage:h,isRefetchError:o&&!c&&!m,isRefetching:s&&!u&&!h}}},r=e.i(469637);function i(e,t){return(0,r.useBaseQuery)(e,a,t)}e.s(["useInfiniteQuery",()=>i],621482)},785242,e=>{"use strict";var t=e.i(619273),l=e.i(266027),a=e.i(912598),r=e.i(135214),i=e.i(270345),s=e.i(243652),n=e.i(764205);let o=(0,s.createQueryKeys)("teams"),d=async(e,t,l,a={})=>{try{let r=(0,n.getProxyBaseUrl)(),i=new URLSearchParams(Object.entries({team_id:a.teamID,organization_id:a.organizationID,team_alias:a.team_alias,user_id:a.userID,page:t,page_size:l,sort_by:a.sortBy,sort_order:a.sortOrder,status:"deleted"}).filter(([,e])=>null!=e).map(([e,t])=>[e,String(t)])),s=`${r?`${r}/v2/team/list`:"/v2/team/list"}?${i}`,o=await fetch(s,{method:"GET",headers:{[(0,n.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!o.ok){let e=await o.json(),t=(0,n.deriveErrorMessage)(e);throw(0,n.handleError)(t),Error(t)}let d=await o.json();if(console.log("/team/list?status=deleted API Response:",d),d&&"object"==typeof d&&"teams"in d)return d.teams;return d}catch(e){throw console.error("Failed to list deleted teams:",e),e}},c=(0,s.createQueryKeys)("deletedTeams");e.s(["useDeletedTeams",0,(e,a,i={})=>{let{accessToken:s}=(0,r.default)();return(0,l.useQuery)({queryKey:c.list({page:e,limit:a,...i}),queryFn:async()=>await d(s,e,a,i),enabled:!!s,staleTime:3e4,placeholderData:t.keepPreviousData})},"useTeam",0,e=>{let{accessToken:t}=(0,r.default)(),i=(0,a.useQueryClient)();return(0,l.useQuery)({queryKey:o.detail(e),enabled:!!(t&&e),queryFn:async()=>{if(!t||!e)throw Error("Missing auth or teamId");return(0,n.teamInfoCall)(t,e)},initialData:()=>{if(!e)return;let t=i.getQueryData(o.list({}));return t?.find(t=>t.team_id===e)}})},"useTeams",0,()=>{let{accessToken:e,userId:t,userRole:a}=(0,r.default)();return(0,l.useQuery)({queryKey:o.list({}),queryFn:async()=>await (0,i.fetchTeams)(e,t,a,null),enabled:!!e})}])},738014,e=>{"use strict";var t=e.i(135214),l=e.i(764205),a=e.i(266027);let r=(0,e.i(243652).createQueryKeys)("users");e.s(["useCurrentUser",0,()=>{let{accessToken:e,userId:i,userRole:s}=(0,t.default)();return(0,a.useQuery)({queryKey:r.detail(i),queryFn:async()=>{let t=await (0,l.userInfoCall)(e,i,s,!1,null,null);return console.log(`userInfo: ${JSON.stringify(t)}`),t.user_info},enabled:!!(e&&i&&s)})}])}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/55c8ff5e9c6d1e1d.js b/litellm/proxy/_experimental/out/_next/static/chunks/55c8ff5e9c6d1e1d.js new file mode 100644 index 00000000000..9b0e7c6f6d9 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/55c8ff5e9c6d1e1d.js @@ -0,0 +1 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,166406,e=>{"use strict";var t=e.i(190144);e.s(["CopyOutlined",()=>t.default])},916925,e=>{"use strict";var t,r=((t={}).A2A_Agent="A2A Agent",t.AI21="Ai21",t.AI21_CHAT="Ai21 Chat",t.AIML="AI/ML API",t.AIOHTTP_OPENAI="Aiohttp Openai",t.Anthropic="Anthropic",t.ANTHROPIC_TEXT="Anthropic Text",t.AssemblyAI="AssemblyAI",t.AUTO_ROUTER="Auto Router",t.Bedrock="Amazon Bedrock",t.BedrockMantle="Amazon Bedrock Mantle",t.SageMaker="AWS SageMaker",t.Azure="Azure",t.Azure_AI_Studio="Azure AI Foundry (Studio)",t.AZURE_TEXT="Azure Text",t.BASETEN="Baseten",t.BYTEZ="Bytez",t.Cerebras="Cerebras",t.CLARIFAI="Clarifai",t.CLOUDFLARE="Cloudflare",t.CODESTRAL="Codestral",t.Cohere="Cohere",t.COHERE_CHAT="Cohere Chat",t.COMETAPI="Cometapi",t.COMPACTIFAI="Compactifai",t.Cursor="Cursor",t.Dashscope="Dashscope",t.Databricks="Databricks (Qwen API)",t.DATAROBOT="Datarobot",t.DeepInfra="DeepInfra",t.Deepgram="Deepgram",t.Deepseek="Deepseek",t.DOCKER_MODEL_RUNNER="Docker Model Runner",t.DOTPROMPT="Dotprompt",t.ElevenLabs="ElevenLabs",t.EMPOWER="Empower",t.FalAI="Fal AI",t.FEATHERLESS_AI="Featherless Ai",t.FireworksAI="Fireworks AI",t.FRIENDLIAI="Friendliai",t.GALADRIEL="Galadriel",t.GITHUB_COPILOT="Github Copilot",t.Google_AI_Studio="Google AI Studio",t.GradientAI="GradientAI",t.Groq="Groq",t.HEROKU="Heroku",t.Hosted_Vllm="vllm",t.HUGGINGFACE="Huggingface",t.HYPERBOLIC="Hyperbolic",t.Infinity="Infinity",t.JinaAI="Jina AI",t.LAMBDA_AI="Lambda Ai",t.LEMONADE="Lemonade",t.LLAMAFILE="Llamafile",t.LM_STUDIO="Lm Studio",t.LLAMA="Meta Llama",t.MARITALK="Maritalk",t.MiniMax="MiniMax",t.MistralAI="Mistral AI",t.MOONSHOT="Moonshot",t.MORPH="Morph",t.NEBIUS="Nebius",t.NLP_CLOUD="Nlp Cloud",t.NOVITA="Novita",t.NSCALE="Nscale",t.NVIDIA_NIM="Nvidia Nim",t.Ollama="Ollama",t.OLLAMA_CHAT="Ollama Chat",t.OOBABOOGA="Oobabooga",t.OpenAI="OpenAI",t.OPENAI_LIKE="Openai Like",t.OpenAI_Compatible="OpenAI-Compatible Endpoints (Together AI, etc.)",t.OpenAI_Text="OpenAI Text Completion",t.OpenAI_Text_Compatible="OpenAI-Compatible Text Completion Models (Together AI, etc.)",t.Openrouter="Openrouter",t.Oracle="Oracle Cloud Infrastructure (OCI)",t.OVHCLOUD="Ovhcloud",t.Perplexity="Perplexity",t.PETALS="Petals",t.PG_VECTOR="Pg Vector",t.PREDIBASE="Predibase",t.RECRAFT="Recraft",t.REPLICATE="Replicate",t.RunwayML="RunwayML",t.SAGEMAKER_LEGACY="Sagemaker",t.Sambanova="Sambanova",t.SAP="SAP Generative AI Hub",t.Snowflake="Snowflake",t.TEXT_COMPLETION_CODESTRAL="Text-Completion-Codestral",t.TogetherAI="TogetherAI",t.TOPAZ="Topaz",t.Triton="Triton",t.V0="V0",t.VERCEL_AI_GATEWAY="Vercel Ai Gateway",t.Vertex_AI="Vertex AI (Anthropic, Gemini, etc.)",t.VERTEX_AI_BETA="Vertex Ai Beta",t.VLLM="Vllm",t.VolcEngine="VolcEngine",t.Voyage="Voyage AI",t.WANDB="Wandb",t.WATSONX="Watsonx",t.WATSONX_TEXT="Watsonx Text",t.xAI="xAI",t.XINFERENCE="Xinference",t);let n={A2A_Agent:"a2a_agent",AI21:"ai21",AI21_CHAT:"ai21_chat",AIML:"aiml",AIOHTTP_OPENAI:"aiohttp_openai",Anthropic:"anthropic",ANTHROPIC_TEXT:"anthropic_text",AssemblyAI:"assemblyai",AUTO_ROUTER:"auto_router",Azure:"azure",Azure_AI_Studio:"azure_ai",AZURE_TEXT:"azure_text",BASETEN:"baseten",Bedrock:"bedrock",BedrockMantle:"bedrock_mantle",BYTEZ:"bytez",Cerebras:"cerebras",CLARIFAI:"clarifai",CLOUDFLARE:"cloudflare",CODESTRAL:"codestral",Cohere:"cohere",COHERE_CHAT:"cohere_chat",COMETAPI:"cometapi",COMPACTIFAI:"compactifai",Cursor:"cursor",Dashscope:"dashscope",Databricks:"databricks",DATAROBOT:"datarobot",DeepInfra:"deepinfra",Deepgram:"deepgram",Deepseek:"deepseek",DOCKER_MODEL_RUNNER:"docker_model_runner",DOTPROMPT:"dotprompt",ElevenLabs:"elevenlabs",EMPOWER:"empower",FalAI:"fal_ai",FEATHERLESS_AI:"featherless_ai",FireworksAI:"fireworks_ai",FRIENDLIAI:"friendliai",GALADRIEL:"galadriel",GITHUB_COPILOT:"github_copilot",Google_AI_Studio:"gemini",GradientAI:"gradient_ai",Groq:"groq",HEROKU:"heroku",Hosted_Vllm:"hosted_vllm",HUGGINGFACE:"huggingface",HYPERBOLIC:"hyperbolic",Infinity:"infinity",JinaAI:"jina_ai",LAMBDA_AI:"lambda_ai",LEMONADE:"lemonade",LLAMAFILE:"llamafile",LLAMA:"meta_llama",LM_STUDIO:"lm_studio",MARITALK:"maritalk",MiniMax:"minimax",MistralAI:"mistral",MOONSHOT:"moonshot",MORPH:"morph",NEBIUS:"nebius",NLP_CLOUD:"nlp_cloud",NOVITA:"novita",NSCALE:"nscale",NVIDIA_NIM:"nvidia_nim",Ollama:"ollama",OLLAMA_CHAT:"ollama_chat",OOBABOOGA:"oobabooga",OpenAI:"openai",OPENAI_LIKE:"openai_like",OpenAI_Compatible:"openai",OpenAI_Text:"text-completion-openai",OpenAI_Text_Compatible:"text-completion-openai",Openrouter:"openrouter",Oracle:"oci",OVHCLOUD:"ovhcloud",Perplexity:"perplexity",PETALS:"petals",PG_VECTOR:"pg_vector",PREDIBASE:"predibase",RECRAFT:"recraft",REPLICATE:"replicate",RunwayML:"runwayml",SAGEMAKER_LEGACY:"sagemaker",SageMaker:"sagemaker_chat",Sambanova:"sambanova",SAP:"sap",Snowflake:"snowflake",TEXT_COMPLETION_CODESTRAL:"text-completion-codestral",TogetherAI:"together_ai",TOPAZ:"topaz",Triton:"triton",V0:"v0",VERCEL_AI_GATEWAY:"vercel_ai_gateway",Vertex_AI:"vertex_ai",VERTEX_AI_BETA:"vertex_ai_beta",VLLM:"vllm",VolcEngine:"volcengine",Voyage:"voyage",WANDB:"wandb",WATSONX:"watsonx",WATSONX_TEXT:"watsonx_text",xAI:"xai",XINFERENCE:"xinference"},a="../ui/assets/logos/",o={"A2A Agent":`${a}a2a_agent.png`,Ai21:`${a}ai21.svg`,"Ai21 Chat":`${a}ai21.svg`,"AI/ML API":`${a}aiml_api.svg`,"Aiohttp Openai":`${a}openai_small.svg`,Anthropic:`${a}anthropic.svg`,"Anthropic Text":`${a}anthropic.svg`,AssemblyAI:`${a}assemblyai_small.png`,Azure:`${a}microsoft_azure.svg`,"Azure AI Foundry (Studio)":`${a}microsoft_azure.svg`,"Azure Text":`${a}microsoft_azure.svg`,Baseten:`${a}baseten.svg`,"Amazon Bedrock":`${a}bedrock.svg`,"Amazon Bedrock Mantle":`${a}bedrock.svg`,"AWS SageMaker":`${a}bedrock.svg`,Cerebras:`${a}cerebras.svg`,Cloudflare:`${a}cloudflare.svg`,Codestral:`${a}mistral.svg`,Cohere:`${a}cohere.svg`,"Cohere Chat":`${a}cohere.svg`,Cometapi:`${a}cometapi.svg`,Cursor:`${a}cursor.svg`,"Databricks (Qwen API)":`${a}databricks.svg`,Dashscope:`${a}dashscope.svg`,Deepseek:`${a}deepseek.svg`,Deepgram:`${a}deepgram.png`,DeepInfra:`${a}deepinfra.png`,ElevenLabs:`${a}elevenlabs.png`,"Fal AI":`${a}fal_ai.jpg`,"Featherless Ai":`${a}featherless.svg`,"Fireworks AI":`${a}fireworks.svg`,Friendliai:`${a}friendli.svg`,"Github Copilot":`${a}github_copilot.svg`,"Google AI Studio":`${a}google.svg`,GradientAI:`${a}gradientai.svg`,Groq:`${a}groq.svg`,vllm:`${a}vllm.png`,Huggingface:`${a}huggingface.svg`,Hyperbolic:`${a}hyperbolic.svg`,Infinity:`${a}infinity.png`,"Jina AI":`${a}jina.png`,"Lambda Ai":`${a}lambda.svg`,"Lm Studio":`${a}lmstudio.svg`,"Meta Llama":`${a}meta_llama.svg`,MiniMax:`${a}minimax.svg`,"Mistral AI":`${a}mistral.svg`,Moonshot:`${a}moonshot.svg`,Morph:`${a}morph.svg`,Nebius:`${a}nebius.svg`,Novita:`${a}novita.svg`,"Nvidia Nim":`${a}nvidia_nim.svg`,Ollama:`${a}ollama.svg`,"Ollama Chat":`${a}ollama.svg`,Oobabooga:`${a}openai_small.svg`,OpenAI:`${a}openai_small.svg`,"Openai Like":`${a}openai_small.svg`,"OpenAI Text Completion":`${a}openai_small.svg`,"OpenAI-Compatible Text Completion Models (Together AI, etc.)":`${a}openai_small.svg`,"OpenAI-Compatible Endpoints (Together AI, etc.)":`${a}openai_small.svg`,Openrouter:`${a}openrouter.svg`,"Oracle Cloud Infrastructure (OCI)":`${a}oracle.svg`,Perplexity:`${a}perplexity-ai.svg`,Recraft:`${a}recraft.svg`,Replicate:`${a}replicate.svg`,RunwayML:`${a}runwayml.png`,Sagemaker:`${a}bedrock.svg`,Sambanova:`${a}sambanova.svg`,"SAP Generative AI Hub":`${a}sap.png`,Snowflake:`${a}snowflake.svg`,"Text-Completion-Codestral":`${a}mistral.svg`,TogetherAI:`${a}togetherai.svg`,Topaz:`${a}topaz.svg`,Triton:`${a}nvidia_triton.png`,V0:`${a}v0.svg`,"Vercel Ai Gateway":`${a}vercel.svg`,"Vertex AI (Anthropic, Gemini, etc.)":`${a}google.svg`,"Vertex Ai Beta":`${a}google.svg`,Vllm:`${a}vllm.png`,VolcEngine:`${a}volcengine.png`,"Voyage AI":`${a}voyage.webp`,Watsonx:`${a}watsonx.svg`,"Watsonx Text":`${a}watsonx.svg`,xAI:`${a}xai.svg`,Xinference:`${a}xinference.svg`};e.s(["Providers",()=>r,"getPlaceholder",0,e=>{if("AI/ML API"===e)return"aiml/flux-pro/v1.1";if("Vertex AI (Anthropic, Gemini, etc.)"===e)return"gemini-pro";if("Anthropic"==e)return"claude-3-opus";if("Amazon Bedrock"==e)return"claude-3-opus";if("AWS SageMaker"==e)return"sagemaker/jumpstart-dft-meta-textgeneration-llama-2-7b";else if("Google AI Studio"==e)return"gemini-pro";else if("Azure AI Foundry (Studio)"==e)return"azure_ai/command-r-plus";else if("Azure"==e)return"my-deployment";else if("Oracle Cloud Infrastructure (OCI)"==e)return"oci/xai.grok-4";else if("Snowflake"==e)return"snowflake/mistral-7b";else if("Voyage AI"==e)return"voyage/";else if("Jina AI"==e)return"jina_ai/";else if("VolcEngine"==e)return"volcengine/";else if("DeepInfra"==e)return"deepinfra/";else if("Fal AI"==e)return"fal_ai/fal-ai/flux-pro/v1.1-ultra";else if("RunwayML"==e)return"runwayml/gen4_turbo";else if("Watsonx"===e)return"watsonx/ibm/granite-3-3-8b-instruct";else if("Cursor"===e)return"cursor/claude-4-sonnet";else return"gpt-3.5-turbo"},"getProviderLogoAndName",0,e=>{if(!e)return{logo:"",displayName:"-"};if("gemini"===e.toLowerCase()){let e="Google AI Studio";return{logo:o[e],displayName:e}}let t=Object.keys(n).find(t=>n[t].toLowerCase()===e.toLowerCase());if(!t)return{logo:"",displayName:e};let a=r[t];return{logo:o[a],displayName:a}},"getProviderModels",0,(e,t)=>{console.log(`Provider key: ${e}`);let r=n[e];console.log(`Provider mapped to: ${r}`);let a=[];return e&&"object"==typeof t&&(Object.entries(t).forEach(([e,t])=>{if(null!==t&&"object"==typeof t&&"litellm_provider"in t){let n=t.litellm_provider;(n===r||"string"==typeof n&&n.includes(r))&&a.push(e)}}),"Cohere"==e&&(console.log("Adding cohere chat models"),Object.entries(t).forEach(([e,t])=>{null!==t&&"object"==typeof t&&"litellm_provider"in t&&"cohere_chat"===t.litellm_provider&&a.push(e)})),"AWS SageMaker"==e&&(console.log("Adding sagemaker chat models"),Object.entries(t).forEach(([e,t])=>{null!==t&&"object"==typeof t&&"litellm_provider"in t&&"sagemaker_chat"===t.litellm_provider&&a.push(e)}))),a},"providerLogoMap",0,o,"provider_map",0,n])},21548,e=>{"use strict";var t=e.i(616303);e.s(["Empty",()=>t.default])},798496,e=>{"use strict";var t=e.i(843476),r=e.i(152990),n=e.i(682830),a=e.i(271645),o=e.i(269200),i=e.i(427612),l=e.i(64848),s=e.i(942232),c=e.i(496020),u=e.i(977572),d=e.i(94629),m=e.i(360820),p=e.i(871943);function h({data:e=[],columns:h,isLoading:f=!1,defaultSorting:g=[],pagination:v,onPaginationChange:b,enablePagination:y=!1,onRowClick:A}){let[x,_]=a.default.useState(g),[C]=a.default.useState("onChange"),[w,S]=a.default.useState({}),[E,I]=a.default.useState({}),T=(0,r.useReactTable)({data:e,columns:h,state:{sorting:x,columnSizing:w,columnVisibility:E,...y&&v?{pagination:v}:{}},columnResizeMode:C,onSortingChange:_,onColumnSizingChange:S,onColumnVisibilityChange:I,...y&&b?{onPaginationChange:b}:{},getCoreRowModel:(0,n.getCoreRowModel)(),getSortedRowModel:(0,n.getSortedRowModel)(),...y?{getPaginationRowModel:(0,n.getPaginationRowModel)()}:{},enableSorting:!0,enableColumnResizing:!0,defaultColumn:{minSize:40,maxSize:500}});return(0,t.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,t.jsx)("div",{className:"overflow-x-auto",children:(0,t.jsx)("div",{className:"relative min-w-full",children:(0,t.jsxs)(o.Table,{className:"[&_td]:py-2 [&_th]:py-2",style:{width:T.getTotalSize(),minWidth:"100%",tableLayout:"fixed"},children:[(0,t.jsx)(i.TableHead,{children:T.getHeaderGroups().map(e=>(0,t.jsx)(c.TableRow,{children:e.headers.map(e=>(0,t.jsxs)(l.TableHeaderCell,{className:`py-1 h-8 relative ${"actions"===e.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)] w-[120px] ml-8":""} ${e.column.columnDef.meta?.className||""}`,style:{width:"actions"===e.id?120:e.getSize(),position:"actions"===e.id?"sticky":"relative",right:"actions"===e.id?0:"auto"},onClick:e.column.getCanSort()?e.column.getToggleSortingHandler():void 0,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,r.flexRender)(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)(m.ChevronUpIcon,{className:"h-4 w-4 text-blue-500"}),desc:(0,t.jsx)(p.ChevronDownIcon,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,t.jsx)(d.SwitchVerticalIcon,{className:"h-4 w-4 text-gray-400"})})]}),e.column.getCanResize()&&(0,t.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 ${e.column.getIsResizing()?"bg-blue-500":"hover:bg-blue-200"}`})]},e.id))},e.id))}),(0,t.jsx)(s.TableBody,{children:f?(0,t.jsx)(c.TableRow,{children:(0,t.jsx)(u.TableCell,{colSpan:h.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:"🚅 Loading models..."})})})}):T.getRowModel().rows.length>0?T.getRowModel().rows.map(e=>(0,t.jsx)(c.TableRow,{onClick:()=>A?.(e.original),className:A?"cursor-pointer hover:bg-gray-50":"",children:e.getVisibleCells().map(e=>(0,t.jsx)(u.TableCell,{className:`py-0.5 overflow-hidden ${"actions"===e.column.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)] w-[120px] ml-8":""} ${e.column.columnDef.meta?.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,r.flexRender)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,t.jsx)(c.TableRow,{children:(0,t.jsx)(u.TableCell,{colSpan:h.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:"No models found"})})})})})]})})})})}e.s(["ModelDataTable",()=>h])},240647,e=>{"use strict";var t=e.i(286612);e.s(["RightOutlined",()=>t.default])},362024,e=>{"use strict";var t=e.i(988122);e.s(["Collapse",()=>t.default])},516015,(e,t,r)=>{},898547,(e,t,r)=>{var n=e.i(247167);e.r(516015);var a=e.r(271645),o=a&&"object"==typeof a&&"default"in a?a:{default:a},i=void 0!==n.default&&n.default.env&&!0,l=function(e){return"[object String]"===Object.prototype.toString.call(e)},s=function(){function e(e){var t=void 0===e?{}:e,r=t.name,n=void 0===r?"stylesheet":r,a=t.optimizeForSpeed,o=void 0===a?i:a;c(l(n),"`name` must be a string"),this._name=n,this._deletedRulePlaceholder="#"+n+"-deleted-rule____{}",c("boolean"==typeof o,"`optimizeForSpeed` must be a boolean"),this._optimizeForSpeed=o,this._serverSheet=void 0,this._tags=[],this._injected=!1,this._rulesCount=0;var s="u">typeof window&&document.querySelector('meta[property="csp-nonce"]');this._nonce=s?s.getAttribute("content"):null}var t,r=e.prototype;return r.setOptimizeForSpeed=function(e){c("boolean"==typeof e,"`setOptimizeForSpeed` accepts a boolean"),c(0===this._rulesCount,"optimizeForSpeed cannot be when rules have already been inserted"),this.flush(),this._optimizeForSpeed=e,this.inject()},r.isOptimizeForSpeed=function(){return this._optimizeForSpeed},r.inject=function(){var e=this;if(c(!this._injected,"sheet already injected"),this._injected=!0,"u">typeof window&&this._optimizeForSpeed){this._tags[0]=this.makeStyleTag(this._name),this._optimizeForSpeed="insertRule"in this.getSheet(),this._optimizeForSpeed||(i||console.warn("StyleSheet: optimizeForSpeed mode not supported falling back to standard mode."),this.flush(),this._injected=!0);return}this._serverSheet={cssRules:[],insertRule:function(t,r){return"number"==typeof r?e._serverSheet.cssRules[r]={cssText:t}:e._serverSheet.cssRules.push({cssText:t}),r},deleteRule:function(t){e._serverSheet.cssRules[t]=null}}},r.getSheetForTag=function(e){if(e.sheet)return e.sheet;for(var t=0;ttypeof window?this.getSheet():this._serverSheet;if(t.trim()||(t=this._deletedRulePlaceholder),!r.cssRules[e])return e;r.deleteRule(e);try{r.insertRule(t,e)}catch(n){i||console.warn("StyleSheet: illegal rule: \n\n"+t+"\n\nSee https://stackoverflow.com/q/20007992 for more info"),r.insertRule(this._deletedRulePlaceholder,e)}}else{var n=this._tags[e];c(n,"old rule at index `"+e+"` not found"),n.textContent=t}return e},r.deleteRule=function(e){if("u"typeof window?(this._tags.forEach(function(e){return e&&e.parentNode.removeChild(e)}),this._tags=[]):this._serverSheet.cssRules=[]},r.cssRules=function(){var e=this;return"u">>0},d={};function m(e,t){if(!t)return"jsx-"+e;var r=String(t),n=e+r;return d[n]||(d[n]="jsx-"+u(e+"-"+r)),d[n]}function p(e,t){"u"typeof window&&!this._fromServer&&(this._fromServer=this.selectFromServer(),this._instancesCounts=Object.keys(this._fromServer).reduce(function(e,t){return e[t]=0,e},{}));var r=this.getIdAndRules(e),n=r.styleId,a=r.rules;if(n in this._instancesCounts){this._instancesCounts[n]+=1;return}var o=a.map(function(e){return t._sheet.insertRule(e)}).filter(function(e){return -1!==e});this._indices[n]=o,this._instancesCounts[n]=1},t.remove=function(e){var t=this,r=this.getIdAndRules(e).styleId;if(function(e,t){if(!e)throw Error("StyleSheetRegistry: "+t+".")}(r in this._instancesCounts,"styleId: `"+r+"` not found"),this._instancesCounts[r]-=1,this._instancesCounts[r]<1){var n=this._fromServer&&this._fromServer[r];n?(n.parentNode.removeChild(n),delete this._fromServer[r]):(this._indices[r].forEach(function(e){return t._sheet.deleteRule(e)}),delete this._indices[r]),delete this._instancesCounts[r]}},t.update=function(e,t){this.add(t),this.remove(e)},t.flush=function(){this._sheet.flush(),this._sheet.inject(),this._fromServer=void 0,this._indices={},this._instancesCounts={}},t.cssRules=function(){var e=this,t=this._fromServer?Object.keys(this._fromServer).map(function(t){return[t,e._fromServer[t]]}):[],r=this._sheet.cssRules();return t.concat(Object.keys(this._indices).map(function(t){return[t,e._indices[t].map(function(e){return r[e].cssText}).join(e._optimizeForSpeed?"":"\n")]}).filter(function(e){return!!e[1]}))},t.styles=function(e){var t,r;return t=this.cssRules(),void 0===(r=e)&&(r={}),t.map(function(e){var t=e[0],n=e[1];return o.default.createElement("style",{id:"__"+t,key:"__"+t,nonce:r.nonce?r.nonce:void 0,dangerouslySetInnerHTML:{__html:n}})})},t.getIdAndRules=function(e){var t=e.children,r=e.dynamic,n=e.id;if(r){var a=m(n,r);return{styleId:a,rules:Array.isArray(t)?t.map(function(e){return p(a,e)}):[p(a,t)]}}return{styleId:m(n),rules:Array.isArray(t)?t:[t]}},t.selectFromServer=function(){return Array.prototype.slice.call(document.querySelectorAll('[id^="__jsx-"]')).reduce(function(e,t){return e[t.id.slice(2)]=t,e},{})},e}(),f=a.createContext(null);function g(){return new h}function v(){return a.useContext(f)}f.displayName="StyleSheetContext";var b=o.default.useInsertionEffect||o.default.useLayoutEffect,y="u">typeof window?g():void 0;function A(e){var t=y||v();return t&&("u"{t.exports=e.r(898547).style},883552,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(562901),n=e.i(343794),a=e.i(914949),o=e.i(529681),i=e.i(242064),l=e.i(829672),s=e.i(285781),c=e.i(836938),u=e.i(920228),d=e.i(62405),m=e.i(408850),p=e.i(87414),h=e.i(310730);let f=(0,e.i(246422).genStyleHooks)("Popconfirm",e=>(e=>{let{componentCls:t,iconCls:r,antCls:n,zIndexPopup:a,colorText:o,colorWarning:i,marginXXS:l,marginXS:s,fontSize:c,fontWeightStrong:u,colorTextHeading:d}=e;return{[t]:{zIndex:a,[`&${n}-popover`]:{fontSize:c},[`${t}-message`]:{marginBottom:s,display:"flex",flexWrap:"nowrap",alignItems:"start",[`> ${t}-message-icon ${r}`]:{color:i,fontSize:c,lineHeight:1,marginInlineEnd:s},[`${t}-title`]:{fontWeight:u,color:d,"&:only-child":{fontWeight:"normal"}},[`${t}-description`]:{marginTop:l,color:o}},[`${t}-buttons`]:{textAlign:"end",whiteSpace:"nowrap",button:{marginInlineStart:s}}}}})(e),e=>{let{zIndexPopupBase:t}=e;return{zIndexPopup:t+60}},{resetStyle:!1});var g=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&0>t.indexOf(n)&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var a=0,n=Object.getOwnPropertySymbols(e);at.indexOf(n[a])&&Object.prototype.propertyIsEnumerable.call(e,n[a])&&(r[n[a]]=e[n[a]]);return r};let v=e=>{let{prefixCls:n,okButtonProps:a,cancelButtonProps:o,title:l,description:h,cancelText:f,okText:g,okType:v="primary",icon:b=t.createElement(r.default,null),showCancel:y=!0,close:A,onConfirm:x,onCancel:_,onPopupClick:C}=e,{getPrefixCls:w}=t.useContext(i.ConfigContext),[S]=(0,m.useLocale)("Popconfirm",p.default.Popconfirm),E=(0,c.getRenderPropValue)(l),I=(0,c.getRenderPropValue)(h);return t.createElement("div",{className:`${n}-inner-content`,onClick:C},t.createElement("div",{className:`${n}-message`},b&&t.createElement("span",{className:`${n}-message-icon`},b),t.createElement("div",{className:`${n}-message-text`},E&&t.createElement("div",{className:`${n}-title`},E),I&&t.createElement("div",{className:`${n}-description`},I))),t.createElement("div",{className:`${n}-buttons`},y&&t.createElement(u.default,Object.assign({onClick:_,size:"small"},o),f||(null==S?void 0:S.cancelText)),t.createElement(s.default,{buttonProps:Object.assign(Object.assign({size:"small"},(0,d.convertLegacyProps)(v)),a),actionFn:x,close:A,prefixCls:w("btn"),quitOnNullishReturnValue:!0,emitEvent:!0},g||(null==S?void 0:S.okText))))};var b=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&0>t.indexOf(n)&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var a=0,n=Object.getOwnPropertySymbols(e);at.indexOf(n[a])&&Object.prototype.propertyIsEnumerable.call(e,n[a])&&(r[n[a]]=e[n[a]]);return r};let y=t.forwardRef((e,s)=>{var c,u;let{prefixCls:d,placement:m="top",trigger:p="click",okType:h="primary",icon:g=t.createElement(r.default,null),children:y,overlayClassName:A,onOpenChange:x,onVisibleChange:_,overlayStyle:C,styles:w,classNames:S}=e,E=b(e,["prefixCls","placement","trigger","okType","icon","children","overlayClassName","onOpenChange","onVisibleChange","overlayStyle","styles","classNames"]),{getPrefixCls:I,className:T,style:O,classNames:R,styles:N}=(0,i.useComponentConfig)("popconfirm"),[M,k]=(0,a.default)(!1,{value:null!=(c=e.open)?c:e.visible,defaultValue:null!=(u=e.defaultOpen)?u:e.defaultVisible}),L=(e,t)=>{k(e,!0),null==_||_(e),null==x||x(e,t)},j=I("popconfirm",d),$=(0,n.default)(j,T,A,R.root,null==S?void 0:S.root),P=(0,n.default)(R.body,null==S?void 0:S.body),[z]=f(j);return z(t.createElement(l.default,Object.assign({},(0,o.default)(E,["title"]),{trigger:p,placement:m,onOpenChange:(t,r)=>{let{disabled:n=!1}=e;n||L(t,r)},open:M,ref:s,classNames:{root:$,body:P},styles:{root:Object.assign(Object.assign(Object.assign(Object.assign({},N.root),O),C),null==w?void 0:w.root),body:Object.assign(Object.assign({},N.body),null==w?void 0:w.body)},content:t.createElement(v,Object.assign({okType:h,icon:g},e,{prefixCls:j,close:e=>{L(!1,e)},onConfirm:t=>{var r;return null==(r=e.onConfirm)?void 0:r.call(void 0,t)},onCancel:t=>{var r;L(!1,t),null==(r=e.onCancel)||r.call(void 0,t)}})),"data-popover-inject":!0}),y))});y._InternalPanelDoNotUseOrYouWillBeFired=e=>{let{prefixCls:r,placement:a,className:o,style:l}=e,s=g(e,["prefixCls","placement","className","style"]),{getPrefixCls:c}=t.useContext(i.ConfigContext),u=c("popconfirm",r),[d]=f(u);return d(t.createElement(h.default,{placement:a,className:(0,n.default)(u,o),style:l,content:t.createElement(v,Object.assign({prefixCls:u},s))}))},e.s(["Popconfirm",0,y],883552)},368670,e=>{"use strict";var t=e.i(764205),r=e.i(266027);let n=(0,e.i(243652).createQueryKeys)("modelCostMap");e.s(["useModelCostMap",0,()=>(0,r.useQuery)({queryKey:n.list({}),queryFn:async()=>await (0,t.modelCostMap)(),staleTime:6e4,gcTime:6e4})])},178654,621192,e=>{"use strict";let t=e.i(211576).Col;e.s(["Col",0,t],178654);let r=e.i(264042).Row;e.s(["Row",0,r],621192)},564897,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let n={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"};var a=e.i(9583),o=r.forwardRef(function(e,o){return r.createElement(a.default,(0,t.default)({},e,{ref:o,icon:n}))});e.s(["MinusCircleOutlined",0,o],564897)},750113,e=>{"use strict";var t=e.i(684024);e.s(["QuestionCircleOutlined",()=>t.default])},475647,286536,77705,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let n={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M696 480H544V328c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v152H328c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8h152v152c0 4.4 3.6 8 8 8h48c4.4 0 8-3.6 8-8V544h152c4.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:"plus-circle",theme:"outlined"};var a=e.i(9583),o=r.forwardRef(function(e,o){return r.createElement(a.default,(0,t.default)({},e,{ref:o,icon:n}))});e.s(["PlusCircleOutlined",0,o],475647);var i=e.i(475254);let l=(0,i.default)("eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);e.s(["Eye",()=>l],286536);let s=(0,i.default)("eye-off",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);e.s(["EyeOff",()=>s],77705)},987432,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let n={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M893.3 293.3L730.7 130.7c-7.5-7.5-16.7-13-26.7-16V112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V338.5c0-17-6.7-33.2-18.7-45.2zM384 184h256v104H384V184zm456 656H184V184h136v136c0 17.7 14.3 32 32 32h320c17.7 0 32-14.3 32-32V205.8l136 136V840zM512 442c-79.5 0-144 64.5-144 144s64.5 144 144 144 144-64.5 144-144-64.5-144-144-144zm0 224c-44.2 0-80-35.8-80-80s35.8-80 80-80 80 35.8 80 80-35.8 80-80 80z"}}]},name:"save",theme:"outlined"};var a=e.i(9583),o=r.forwardRef(function(e,o){return r.createElement(a.default,(0,t.default)({},e,{ref:o,icon:n}))});e.s(["SaveOutlined",0,o],987432)},211576,e=>{"use strict";var t=e.i(131757);e.s(["Col",()=>t.default])},724154,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let n={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-372 0-89 31.3-170.8 83.5-234.8l523.3 523.3C682.8 852.7 601 884 512 884zm288.5-137.2L277.2 223.5C341.2 171.3 423 140 512 140c205.4 0 372 166.6 372 372 0 89-31.3 170.8-83.5 234.8z"}}]},name:"stop",theme:"outlined"};var a=e.i(9583),o=r.forwardRef(function(e,o){return r.createElement(a.default,(0,t.default)({},e,{ref:o,icon:n}))});e.s(["StopOutlined",0,o],724154)},446891,836991,153472,e=>{"use strict";var t,r,n=e.i(843476),a=e.i(464571),o=e.i(326373),i=e.i(94629),l=e.i(360820),s=e.i(871943),c=e.i(271645);let u=c.forwardRef(function(e,t){return c.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:t},e),c.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"}))});e.s(["XIcon",0,u],836991),e.s(["TableHeaderSortDropdown",0,({sortState:e,onSortChange:t})=>{let r=[{key:"asc",label:"Ascending",icon:(0,n.jsx)(l.ChevronUpIcon,{className:"h-4 w-4"})},{key:"desc",label:"Descending",icon:(0,n.jsx)(s.ChevronDownIcon,{className:"h-4 w-4"})},{key:"reset",label:"Reset",icon:(0,n.jsx)(u,{className:"h-4 w-4"})}];return(0,n.jsx)(o.Dropdown,{menu:{items:r,onClick:({key:e})=>{"asc"===e?t("asc"):"desc"===e?t("desc"):"reset"===e&&t(!1)},selectable:!0,selectedKeys:e?[e]:[]},trigger:["click"],autoAdjustOverflow:!0,children:(0,n.jsx)(a.Button,{type:"text",onClick:e=>e.stopPropagation(),icon:"asc"===e?(0,n.jsx)(l.ChevronUpIcon,{className:"h-4 w-4"}):"desc"===e?(0,n.jsx)(s.ChevronDownIcon,{className:"h-4 w-4"}):(0,n.jsx)(i.SwitchVerticalIcon,{className:"h-4 w-4"}),className:e?"text-blue-500 hover:text-blue-600":"text-gray-400 hover:text-blue-500"})})}],446891);var d=e.i(266027),m=e.i(954616),p=e.i(243652),h=e.i(135214),f=e.i(764205),g=((t={}).GENERAL_SETTINGS="general_settings",t),v=((r={}).MAXIMUM_SPEND_LOGS_RETENTION_PERIOD="maximum_spend_logs_retention_period",r);let b=async(e,t)=>{try{let r=f.proxyBaseUrl?`${f.proxyBaseUrl}/config/list?config_type=${t}`:`/config/list?config_type=${t}`,n=await fetch(r,{method:"GET",headers:{[(0,f.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!n.ok){let e=await n.json(),t=(0,f.deriveErrorMessage)(e);throw(0,f.handleError)(t),Error(t)}return await n.json()}catch(e){throw console.error(`Failed to get proxy config for ${t}:`,e),e}},y=(0,p.createQueryKeys)("proxyConfig"),A=async(e,t)=>{try{let r=f.proxyBaseUrl?`${f.proxyBaseUrl}/config/field/delete`:"/config/field/delete",n=await fetch(r,{method:"POST",headers:{[(0,f.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let e=await n.json(),t=(0,f.deriveErrorMessage)(e);throw(0,f.handleError)(t),Error(t)}return await n.json()}catch(e){throw console.error(`Failed to delete proxy config field ${t.field_name}:`,e),e}};e.s(["ConfigType",()=>g,"GeneralSettingsFieldName",()=>v,"useDeleteProxyConfigField",0,()=>{let{accessToken:e}=(0,h.default)();return(0,m.useMutation)({mutationFn:async t=>{if(!e)throw Error("Access token is required");return await A(e,t)}})},"useProxyConfig",0,e=>{let{accessToken:t}=(0,h.default)();return(0,d.useQuery)({queryKey:y.list({filters:{configType:e}}),queryFn:async()=>await b(t,e),enabled:!!t})}],153472)},418371,e=>{"use strict";var t=e.i(843476),r=e.i(271645),n=e.i(916925);e.s(["ProviderLogo",0,({provider:e,className:a="w-4 h-4"})=>{let[o,i]=(0,r.useState)(!1),{logo:l}=(0,n.getProviderLogoAndName)(e);return o||!l?(0,t.jsx)("div",{className:`${a} rounded-full bg-gray-200 flex items-center justify-center text-xs`,children:e?.charAt(0)||"-"}):(0,t.jsx)("img",{src:l,alt:`${e} logo`,className:a,onError:()=>i(!0)})}])},149121,e=>{"use strict";var t=e.i(843476),r=e.i(271645),n=e.i(152990),a=e.i(682830),o=e.i(269200),i=e.i(427612),l=e.i(64848),s=e.i(942232),c=e.i(496020),u=e.i(977572);function d({data:e=[],columns:d,onRowClick:m,renderSubComponent:p,renderChildRows:h,getRowCanExpand:f,isLoading:g=!1,loadingMessage:v="🚅 Loading logs...",noDataMessage:b="No logs found",enableSorting:y=!1}){let A=!!(p||h)&&!!f,[x,_]=(0,r.useState)([]),C=(0,n.useReactTable)({data:e,columns:d,...y&&{state:{sorting:x},onSortingChange:_,enableSortingRemoval:!1},...A&&{getRowCanExpand:f},getRowId:(e,t)=>e?.request_id??String(t),getCoreRowModel:(0,a.getCoreRowModel)(),...y&&{getSortedRowModel:(0,a.getSortedRowModel)()},...A&&{getExpandedRowModel:(0,a.getExpandedRowModel)()}});return(0,t.jsx)("div",{className:"rounded-lg custom-border overflow-x-auto w-full max-w-full box-border",children:(0,t.jsxs)(o.Table,{className:"[&_td]:py-0.5 [&_th]:py-1 table-fixed w-full box-border",style:{minWidth:"400px"},children:[(0,t.jsx)(i.TableHead,{children:C.getHeaderGroups().map(e=>(0,t.jsx)(c.TableRow,{children:e.headers.map(e=>{let r=y&&e.column.getCanSort(),a=e.column.getIsSorted();return(0,t.jsx)(l.TableHeaderCell,{className:`py-1 h-8 ${r?"cursor-pointer select-none hover:bg-gray-50":""}`,onClick:r?e.column.getToggleSortingHandler():void 0,children:e.isPlaceholder?null:(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,n.flexRender)(e.column.columnDef.header,e.getContext()),r&&(0,t.jsx)("span",{className:"text-gray-400",children:"asc"===a?"↑":"desc"===a?"↓":"⇅"})]})},e.id)})},e.id))}),(0,t.jsx)(s.TableBody,{children:g?(0,t.jsx)(c.TableRow,{children:(0,t.jsx)(u.TableCell,{colSpan:d.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:v})})})}):C.getRowModel().rows.length>0?C.getRowModel().rows.map(e=>(0,t.jsxs)(r.Fragment,{children:[(0,t.jsx)(c.TableRow,{className:`h-8 ${m?"cursor-pointer hover:bg-gray-50":""}`,onClick:()=>m?.(e.original),children:e.getVisibleCells().map(e=>(0,t.jsx)(u.TableCell,{className:"py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap",children:(0,n.flexRender)(e.column.columnDef.cell,e.getContext())},e.id))}),A&&e.getIsExpanded()&&h&&h({row:e}),A&&e.getIsExpanded()&&p&&!h&&(0,t.jsx)(c.TableRow,{children:(0,t.jsx)(u.TableCell,{colSpan:e.getVisibleCells().length,className:"p-0",children:(0,t.jsx)("div",{className:"w-full max-w-full overflow-hidden box-border",children:p({row:e})})})})]},e.id)):(0,t.jsx)(c.TableRow,{children:(0,t.jsx)(u.TableCell,{colSpan:d.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:b})})})})})]})})}e.s(["DataTable",()=>d])},37091,e=>{"use strict";var t=e.i(290571),r=e.i(95779),n=e.i(444755),a=e.i(673706),o=e.i(271645);let i=o.default.forwardRef((e,i)=>{let{color:l,children:s,className:c}=e,u=(0,t.__rest)(e,["color","children","className"]);return o.default.createElement("p",Object.assign({ref:i,className:(0,n.tremorTwMerge)(l?(0,a.getColorClassNames)(l,r.colorPalette.lightText).textColor:"text-tremor-content-emphasis dark:text-dark-tremor-content-emphasis",c)},u),s)});i.displayName="Subtitle",e.s(["Subtitle",()=>i],37091)},757440,e=>{"use strict";var t=e.i(290571),r=e.i(271645);let n=e=>{var n=(0,t.__rest)(e,[]);return r.default.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"},n),r.default.createElement("path",{d:"M11.9999 13.1714L16.9497 8.22168L18.3639 9.63589L11.9999 15.9999L5.63599 9.63589L7.0502 8.22168L11.9999 13.1714Z"}))};e.s(["default",()=>n])},446428,854056,e=>{"use strict";let t;var r=e.i(290571),n=e.i(271645);let a=e=>{var t=(0,r.__rest)(e,[]);return n.default.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"},t),n.default.createElement("path",{d:"M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 10.5858L9.17157 7.75736L7.75736 9.17157L10.5858 12L7.75736 14.8284L9.17157 16.2426L12 13.4142L14.8284 16.2426L16.2426 14.8284L13.4142 12L16.2426 9.17157L14.8284 7.75736L12 10.5858Z"}))};e.s(["default",()=>a],446428);var o=e.i(746725),i=e.i(914189),l=e.i(553521),s=e.i(835696),c=e.i(941444),u=e.i(178677),d=e.i(294316),m=e.i(83733),p=e.i(233137),h=e.i(732607),f=e.i(397701),g=e.i(700020);function v(e){var t;return!!(e.enter||e.enterFrom||e.enterTo||e.leave||e.leaveFrom||e.leaveTo)||(null!=(t=e.as)?t:C)!==n.Fragment||1===n.default.Children.count(e.children)}let b=(0,n.createContext)(null);b.displayName="TransitionContext";var y=((t=y||{}).Visible="visible",t.Hidden="hidden",t);let A=(0,n.createContext)(null);function x(e){return"children"in e?x(e.children):e.current.filter(({el:e})=>null!==e.current).filter(({state:e})=>"visible"===e).length>0}function _(e,t){let r=(0,c.useLatestValue)(e),a=(0,n.useRef)([]),s=(0,l.useIsMounted)(),u=(0,o.useDisposables)(),d=(0,i.useEvent)((e,t=g.RenderStrategy.Hidden)=>{let n=a.current.findIndex(({el:t})=>t===e);-1!==n&&((0,f.match)(t,{[g.RenderStrategy.Unmount](){a.current.splice(n,1)},[g.RenderStrategy.Hidden](){a.current[n].state="hidden"}}),u.microTask(()=>{var e;!x(a)&&s.current&&(null==(e=r.current)||e.call(r))}))}),m=(0,i.useEvent)(e=>{let t=a.current.find(({el:t})=>t===e);return t?"visible"!==t.state&&(t.state="visible"):a.current.push({el:e,state:"visible"}),()=>d(e,g.RenderStrategy.Unmount)}),p=(0,n.useRef)([]),h=(0,n.useRef)(Promise.resolve()),v=(0,n.useRef)({enter:[],leave:[]}),b=(0,i.useEvent)((e,r,n)=>{p.current.splice(0),t&&(t.chains.current[r]=t.chains.current[r].filter(([t])=>t!==e)),null==t||t.chains.current[r].push([e,new Promise(e=>{p.current.push(e)})]),null==t||t.chains.current[r].push([e,new Promise(e=>{Promise.all(v.current[r].map(([e,t])=>t)).then(()=>e())})]),"enter"===r?h.current=h.current.then(()=>null==t?void 0:t.wait.current).then(()=>n(r)):n(r)}),y=(0,i.useEvent)((e,t,r)=>{Promise.all(v.current[t].splice(0).map(([e,t])=>t)).then(()=>{var e;null==(e=p.current.shift())||e()}).then(()=>r(t))});return(0,n.useMemo)(()=>({children:a,register:m,unregister:d,onStart:b,onStop:y,wait:h,chains:v}),[m,d,a,b,y,v,h])}A.displayName="NestingContext";let C=n.Fragment,w=g.RenderFeatures.RenderStrategy,S=(0,g.forwardRefWithAs)(function(e,t){let{show:r,appear:a=!1,unmount:o=!0,...l}=e,c=(0,n.useRef)(null),m=v(e),h=(0,d.useSyncRefs)(...m?[c,t]:null===t?[]:[t]);(0,u.useServerHandoffComplete)();let f=(0,p.useOpenClosed)();if(void 0===r&&null!==f&&(r=(f&p.State.Open)===p.State.Open),void 0===r)throw Error("A is used but it is missing a `show={true | false}` prop.");let[y,C]=(0,n.useState)(r?"visible":"hidden"),S=_(()=>{r||C("hidden")}),[I,T]=(0,n.useState)(!0),O=(0,n.useRef)([r]);(0,s.useIsoMorphicEffect)(()=>{!1!==I&&O.current[O.current.length-1]!==r&&(O.current.push(r),T(!1))},[O,r]);let R=(0,n.useMemo)(()=>({show:r,appear:a,initial:I}),[r,a,I]);(0,s.useIsoMorphicEffect)(()=>{r?C("visible"):x(S)||null===c.current||C("hidden")},[r,S]);let N={unmount:o},M=(0,i.useEvent)(()=>{var t;I&&T(!1),null==(t=e.beforeEnter)||t.call(e)}),k=(0,i.useEvent)(()=>{var t;I&&T(!1),null==(t=e.beforeLeave)||t.call(e)}),L=(0,g.useRender)();return n.default.createElement(A.Provider,{value:S},n.default.createElement(b.Provider,{value:R},L({ourProps:{...N,as:n.Fragment,children:n.default.createElement(E,{ref:h,...N,...l,beforeEnter:M,beforeLeave:k})},theirProps:{},defaultTag:n.Fragment,features:w,visible:"visible"===y,name:"Transition"})))}),E=(0,g.forwardRefWithAs)(function(e,t){var r,a;let{transition:o=!0,beforeEnter:l,afterEnter:c,beforeLeave:y,afterLeave:S,enter:E,enterFrom:I,enterTo:T,entered:O,leave:R,leaveFrom:N,leaveTo:M,...k}=e,[L,j]=(0,n.useState)(null),$=(0,n.useRef)(null),P=v(e),z=(0,d.useSyncRefs)(...P?[$,t,j]:null===t?[]:[t]),F=null==(r=k.unmount)||r?g.RenderStrategy.Unmount:g.RenderStrategy.Hidden,{show:D,appear:V,initial:H}=function(){let e=(0,n.useContext)(b);if(null===e)throw Error("A is used but it is missing a parent or .");return e}(),[B,G]=(0,n.useState)(D?"visible":"hidden"),U=function(){let e=(0,n.useContext)(A);if(null===e)throw Error("A is used but it is missing a parent or .");return e}(),{register:W,unregister:q}=U;(0,s.useIsoMorphicEffect)(()=>W($),[W,$]),(0,s.useIsoMorphicEffect)(()=>{if(F===g.RenderStrategy.Hidden&&$.current)return D&&"visible"!==B?void G("visible"):(0,f.match)(B,{hidden:()=>q($),visible:()=>W($)})},[B,$,W,q,D,F]);let X=(0,u.useServerHandoffComplete)();(0,s.useIsoMorphicEffect)(()=>{if(P&&X&&"visible"===B&&null===$.current)throw Error("Did you forget to passthrough the `ref` to the actual DOM node?")},[$,B,X,P]);let K=H&&!V,Y=V&&D&&H,Z=(0,n.useRef)(!1),Q=_(()=>{Z.current||(G("hidden"),q($))},U),J=(0,i.useEvent)(e=>{Z.current=!0,Q.onStart($,e?"enter":"leave",e=>{"enter"===e?null==l||l():"leave"===e&&(null==y||y())})}),ee=(0,i.useEvent)(e=>{let t=e?"enter":"leave";Z.current=!1,Q.onStop($,t,e=>{"enter"===e?null==c||c():"leave"===e&&(null==S||S())}),"leave"!==t||x(Q)||(G("hidden"),q($))});(0,n.useEffect)(()=>{P&&o||(J(D),ee(D))},[D,P,o]);let et=!(!o||!P||!X||K),[,er]=(0,m.useTransition)(et,L,D,{start:J,end:ee}),en=(0,g.compact)({ref:z,className:(null==(a=(0,h.classNames)(k.className,Y&&E,Y&&I,er.enter&&E,er.enter&&er.closed&&I,er.enter&&!er.closed&&T,er.leave&&R,er.leave&&!er.closed&&N,er.leave&&er.closed&&M,!er.transition&&D&&O))?void 0:a.trim())||void 0,...(0,m.transitionDataAttributes)(er)}),ea=0;"visible"===B&&(ea|=p.State.Open),"hidden"===B&&(ea|=p.State.Closed),er.enter&&(ea|=p.State.Opening),er.leave&&(ea|=p.State.Closing);let eo=(0,g.useRender)();return n.default.createElement(A.Provider,{value:Q},n.default.createElement(p.OpenClosedProvider,{value:ea},eo({ourProps:en,theirProps:k,defaultTag:C,features:w,visible:"visible"===B,name:"Transition.Child"})))}),I=(0,g.forwardRefWithAs)(function(e,t){let r=null!==(0,n.useContext)(b),a=null!==(0,p.useOpenClosed)();return n.default.createElement(n.default.Fragment,null,!r&&a?n.default.createElement(S,{ref:t,...e}):n.default.createElement(E,{ref:t,...e}))}),T=Object.assign(S,{Child:I,Root:S});e.s(["Transition",()=>T],854056)},206929,e=>{"use strict";var t=e.i(290571),r=e.i(757440),n=e.i(271645),a=e.i(446428),o=e.i(444755),i=e.i(673706),l=e.i(103471),s=e.i(495470),c=e.i(854056),u=e.i(888288);let d=(0,i.makeClassName)("Select"),m=n.default.forwardRef((e,i)=>{let{defaultValue:m="",value:p,onValueChange:h,placeholder:f="Select...",disabled:g=!1,icon:v,enableClear:b=!1,required:y,children:A,name:x,error:_=!1,errorMessage:C,className:w,id:S}=e,E=(0,t.__rest)(e,["defaultValue","value","onValueChange","placeholder","disabled","icon","enableClear","required","children","name","error","errorMessage","className","id"]),I=(0,n.useRef)(null),T=n.Children.toArray(A),[O,R]=(0,u.default)(m,p),N=(0,n.useMemo)(()=>{let e=n.default.Children.toArray(A).filter(n.isValidElement);return(0,l.constructValueToNameMapping)(e)},[A]);return n.default.createElement("div",{className:(0,o.tremorTwMerge)("w-full min-w-[10rem] text-tremor-default",w)},n.default.createElement("div",{className:"relative"},n.default.createElement("select",{title:"select-hidden",required:y,className:(0,o.tremorTwMerge)("h-full w-full absolute left-0 top-0 -z-10 opacity-0"),value:O,onChange:e=>{e.preventDefault()},name:x,disabled:g,id:S,onFocus:()=>{let e=I.current;e&&e.focus()}},n.default.createElement("option",{className:"hidden",value:"",disabled:!0,hidden:!0},f),T.map(e=>{let t=e.props.value,r=e.props.children;return n.default.createElement("option",{className:"hidden",key:t,value:t},r)})),n.default.createElement(s.Listbox,Object.assign({as:"div",ref:i,defaultValue:O,value:O,onChange:e=>{null==h||h(e),R(e)},disabled:g,id:S},E),({value:e})=>{var t;return n.default.createElement(n.default.Fragment,null,n.default.createElement(s.ListboxButton,{ref:I,className:(0,o.tremorTwMerge)("w-full outline-none text-left whitespace-nowrap truncate rounded-tremor-default focus:ring-2 transition duration-100 border pr-8 py-2","border-tremor-border shadow-tremor-input focus:border-tremor-brand-subtle focus:ring-tremor-brand-muted","dark:border-dark-tremor-border dark:shadow-dark-tremor-input dark:focus:border-dark-tremor-brand-subtle dark:focus:ring-dark-tremor-brand-muted",v?"pl-10":"pl-3",(0,l.getSelectButtonColors)((0,l.hasValue)(e),g,_))},v&&n.default.createElement("span",{className:(0,o.tremorTwMerge)("absolute inset-y-0 left-0 flex items-center ml-px pl-2.5")},n.default.createElement(v,{className:(0,o.tremorTwMerge)(d("Icon"),"flex-none h-5 w-5","text-tremor-content-subtle","dark:text-dark-tremor-content-subtle")})),n.default.createElement("span",{className:"w-[90%] block truncate"},e&&null!=(t=N.get(e))?t:f),n.default.createElement("span",{className:(0,o.tremorTwMerge)("absolute inset-y-0 right-0 flex items-center mr-3")},n.default.createElement(r.default,{className:(0,o.tremorTwMerge)(d("arrowDownIcon"),"flex-none h-5 w-5","text-tremor-content-subtle","dark:text-dark-tremor-content-subtle")}))),b&&O?n.default.createElement("button",{type:"button",className:(0,o.tremorTwMerge)("absolute inset-y-0 right-0 flex items-center mr-8"),onClick:e=>{e.preventDefault(),R(""),null==h||h("")}},n.default.createElement(a.default,{className:(0,o.tremorTwMerge)(d("clearIcon"),"flex-none h-4 w-4","text-tremor-content-subtle","dark:text-dark-tremor-content-subtle")})):null,n.default.createElement(c.Transition,{enter:"transition ease duration-100 transform",enterFrom:"opacity-0 -translate-y-4",enterTo:"opacity-100 translate-y-0",leave:"transition ease duration-100 transform",leaveFrom:"opacity-100 translate-y-0",leaveTo:"opacity-0 -translate-y-4"},n.default.createElement(s.ListboxOptions,{anchor:"bottom start",className:(0,o.tremorTwMerge)("z-10 w-[var(--button-width)] divide-y overflow-y-auto outline-none rounded-tremor-default max-h-[228px] border [--anchor-gap:4px]","bg-tremor-background border-tremor-border divide-tremor-border shadow-tremor-dropdown","dark:bg-dark-tremor-background dark:border-dark-tremor-border dark:divide-dark-tremor-border dark:shadow-dark-tremor-dropdown")},A)))})),_&&C?n.default.createElement("p",{className:(0,o.tremorTwMerge)("errorMessage","text-sm text-rose-500 mt-1")},C):null)});m.displayName="Select",e.s(["Select",()=>m],206929)},502275,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"}))});e.s(["InformationCircleIcon",0,r],502275)},664307,e=>{"use strict";var t=e.i(843476),r=e.i(135214),n=e.i(214541),a=e.i(271645),o=e.i(161059);e.s(["default",0,()=>{let{token:e,premiumUser:i}=(0,r.default)(),[l,s]=(0,a.useState)([]),{teams:c}=(0,n.default)();return(0,t.jsx)(o.default,{token:e,modelData:{data:[]},keys:l,setModelData:()=>{},premiumUser:i,teams:c})}])},601236,e=>{e.v(e=>Promise.resolve().then(()=>e(764205)))}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/563e61c7d2b8aec8.js b/litellm/proxy/_experimental/out/_next/static/chunks/563e61c7d2b8aec8.js deleted file mode 100644 index e4bab7ed898..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/563e61c7d2b8aec8.js +++ /dev/null @@ -1,14 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,91874,e=>{"use strict";var t=e.i(931067),r=e.i(209428),a=e.i(211577),l=e.i(392221),o=e.i(703923),n=e.i(343794),i=e.i(914949),s=e.i(271645),d=["prefixCls","className","style","checked","disabled","defaultChecked","type","title","onChange"],c=(0,s.forwardRef)(function(e,c){var u=e.prefixCls,m=void 0===u?"rc-checkbox":u,g=e.className,f=e.style,b=e.checked,p=e.disabled,h=e.defaultChecked,C=e.type,v=void 0===C?"checkbox":C,k=e.title,x=e.onChange,w=(0,o.default)(e,d),$=(0,s.useRef)(null),y=(0,s.useRef)(null),N=(0,i.default)(void 0!==h&&h,{value:b}),O=(0,l.default)(N,2),E=O[0],j=O[1];(0,s.useImperativeHandle)(c,function(){return{focus:function(e){var t;null==(t=$.current)||t.focus(e)},blur:function(){var e;null==(e=$.current)||e.blur()},input:$.current,nativeElement:y.current}});var T=(0,n.default)(m,g,(0,a.default)((0,a.default)({},"".concat(m,"-checked"),E),"".concat(m,"-disabled"),p));return s.createElement("span",{className:T,title:k,style:f,ref:y},s.createElement("input",(0,t.default)({},w,{className:"".concat(m,"-input"),ref:$,onChange:function(t){p||("checked"in e||j(t.target.checked),null==x||x({target:(0,r.default)((0,r.default)({},e),{},{type:v,checked:t.target.checked}),stopPropagation:function(){t.stopPropagation()},preventDefault:function(){t.preventDefault()},nativeEvent:t.nativeEvent}))},disabled:p,checked:!!E,type:v})),s.createElement("span",{className:"".concat(m,"-inner")}))});e.s(["default",0,c])},421512,236836,e=>{"use strict";let t=e.i(271645).default.createContext(null);e.s(["default",0,t],421512),e.i(296059);var r=e.i(915654),a=e.i(183293),l=e.i(246422),o=e.i(838378);function n(e,t){return(e=>{let{checkboxCls:t}=e,l=`${t}-wrapper`;return[{[`${t}-group`]:Object.assign(Object.assign({},(0,a.resetComponent)(e)),{display:"inline-flex",flexWrap:"wrap",columnGap:e.marginXS,[`> ${e.antCls}-row`]:{flex:1}}),[l]:Object.assign(Object.assign({},(0,a.resetComponent)(e)),{display:"inline-flex",alignItems:"baseline",cursor:"pointer","&:after":{display:"inline-block",width:0,overflow:"hidden",content:"'\\a0'"},[`& + ${l}`]:{marginInlineStart:0},[`&${l}-in-form-item`]:{'input[type="checkbox"]':{width:14,height:14}}}),[t]:Object.assign(Object.assign({},(0,a.resetComponent)(e)),{position:"relative",whiteSpace:"nowrap",lineHeight:1,cursor:"pointer",borderRadius:e.borderRadiusSM,alignSelf:"center",[`${t}-input`]:{position:"absolute",inset:0,zIndex:1,cursor:"pointer",opacity:0,margin:0,[`&:focus-visible + ${t}-inner`]:(0,a.genFocusOutline)(e)},[`${t}-inner`]:{boxSizing:"border-box",display:"block",width:e.checkboxSize,height:e.checkboxSize,direction:"ltr",backgroundColor:e.colorBgContainer,border:`${(0,r.unit)(e.lineWidth)} ${e.lineType} ${e.colorBorder}`,borderRadius:e.borderRadiusSM,borderCollapse:"separate",transition:`all ${e.motionDurationSlow}`,"&:after":{boxSizing:"border-box",position:"absolute",top:"50%",insetInlineStart:"25%",display:"table",width:e.calc(e.checkboxSize).div(14).mul(5).equal(),height:e.calc(e.checkboxSize).div(14).mul(8).equal(),border:`${(0,r.unit)(e.lineWidthBold)} solid ${e.colorWhite}`,borderTop:0,borderInlineStart:0,transform:"rotate(45deg) scale(0) translate(-50%,-50%)",opacity:0,content:'""',transition:`all ${e.motionDurationFast} ${e.motionEaseInBack}, opacity ${e.motionDurationFast}`}},"& + span":{paddingInlineStart:e.paddingXS,paddingInlineEnd:e.paddingXS}})},{[` - ${l}:not(${l}-disabled), - ${t}:not(${t}-disabled) - `]:{[`&:hover ${t}-inner`]:{borderColor:e.colorPrimary}},[`${l}:not(${l}-disabled)`]:{[`&:hover ${t}-checked:not(${t}-disabled) ${t}-inner`]:{backgroundColor:e.colorPrimaryHover,borderColor:"transparent"},[`&:hover ${t}-checked:not(${t}-disabled):after`]:{borderColor:e.colorPrimaryHover}}},{[`${t}-checked`]:{[`${t}-inner`]:{backgroundColor:e.colorPrimary,borderColor:e.colorPrimary,"&:after":{opacity:1,transform:"rotate(45deg) scale(1) translate(-50%,-50%)",transition:`all ${e.motionDurationMid} ${e.motionEaseOutBack} ${e.motionDurationFast}`}}},[` - ${l}-checked:not(${l}-disabled), - ${t}-checked:not(${t}-disabled) - `]:{[`&:hover ${t}-inner`]:{backgroundColor:e.colorPrimaryHover,borderColor:"transparent"}}},{[t]:{"&-indeterminate":{"&":{[`${t}-inner`]:{backgroundColor:`${e.colorBgContainer}`,borderColor:`${e.colorBorder}`,"&:after":{top:"50%",insetInlineStart:"50%",width:e.calc(e.fontSizeLG).div(2).equal(),height:e.calc(e.fontSizeLG).div(2).equal(),backgroundColor:e.colorPrimary,border:0,transform:"translate(-50%, -50%) scale(1)",opacity:1,content:'""'}},[`&:hover ${t}-inner`]:{backgroundColor:`${e.colorBgContainer}`,borderColor:`${e.colorPrimary}`}}}}},{[`${l}-disabled`]:{cursor:"not-allowed"},[`${t}-disabled`]:{[`&, ${t}-input`]:{cursor:"not-allowed",pointerEvents:"none"},[`${t}-inner`]:{background:e.colorBgContainerDisabled,borderColor:e.colorBorder,"&:after":{borderColor:e.colorTextDisabled}},"&:after":{display:"none"},"& + span":{color:e.colorTextDisabled},[`&${t}-indeterminate ${t}-inner::after`]:{background:e.colorTextDisabled}}}]})((0,o.mergeToken)(t,{checkboxCls:`.${e}`,checkboxSize:t.controlInteractiveSize}))}let i=(0,l.genStyleHooks)("Checkbox",(e,{prefixCls:t})=>[n(t,e)]);e.s(["default",0,i,"getStyle",()=>n],236836)},681216,e=>{"use strict";var t=e.i(271645),r=e.i(963188);function a(e){let a=t.default.useRef(null),l=()=>{r.default.cancel(a.current),a.current=null};return[()=>{l(),a.current=(0,r.default)(()=>{a.current=null})},t=>{a.current&&(t.stopPropagation(),l()),null==e||e(t)}]}e.s(["default",()=>a])},374276,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),a=e.i(91874),l=e.i(611935),o=e.i(121872),n=e.i(26905),i=e.i(242064),s=e.i(937328),d=e.i(321883),c=e.i(62139),u=e.i(421512),m=e.i(236836),g=e.i(681216),f=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var l=0,a=Object.getOwnPropertySymbols(e);lt.indexOf(a[l])&&Object.prototype.propertyIsEnumerable.call(e,a[l])&&(r[a[l]]=e[a[l]]);return r};let b=t.forwardRef((e,b)=>{var p;let{prefixCls:h,className:C,rootClassName:v,children:k,indeterminate:x=!1,style:w,onMouseEnter:$,onMouseLeave:y,skipGroup:N=!1,disabled:O}=e,E=f(e,["prefixCls","className","rootClassName","children","indeterminate","style","onMouseEnter","onMouseLeave","skipGroup","disabled"]),{getPrefixCls:j,direction:T,checkbox:S}=t.useContext(i.ConfigContext),R=t.useContext(u.default),{isFormItemInput:M}=t.useContext(c.FormItemInputContext),P=t.useContext(s.default),z=null!=(p=(null==R?void 0:R.disabled)||O)?p:P,B=t.useRef(E.value),q=t.useRef(null),H=(0,l.composeRef)(b,q);t.useEffect(()=>{null==R||R.registerValue(E.value)},[]),t.useEffect(()=>{if(!N)return E.value!==B.current&&(null==R||R.cancelValue(B.current),null==R||R.registerValue(E.value),B.current=E.value),()=>null==R?void 0:R.cancelValue(E.value)},[E.value]),t.useEffect(()=>{var e;(null==(e=q.current)?void 0:e.input)&&(q.current.input.indeterminate=x)},[x]);let I=j("checkbox",h),L=(0,d.default)(I),[_,A,X]=(0,m.default)(I,L),D=Object.assign({},E);R&&!N&&(D.onChange=(...e)=>{E.onChange&&E.onChange.apply(E,e),R.toggleOption&&R.toggleOption({label:k,value:E.value})},D.name=R.name,D.checked=R.value.includes(E.value));let F=(0,r.default)(`${I}-wrapper`,{[`${I}-rtl`]:"rtl"===T,[`${I}-wrapper-checked`]:D.checked,[`${I}-wrapper-disabled`]:z,[`${I}-wrapper-in-form-item`]:M},null==S?void 0:S.className,C,v,X,L,A),W=(0,r.default)({[`${I}-indeterminate`]:x},n.TARGET_CLS,A),[Y,G]=(0,g.default)(D.onClick);return _(t.createElement(o.default,{component:"Checkbox",disabled:z},t.createElement("label",{className:F,style:Object.assign(Object.assign({},null==S?void 0:S.style),w),onMouseEnter:$,onMouseLeave:y,onClick:Y},t.createElement(a.default,Object.assign({},D,{onClick:G,prefixCls:I,className:W,disabled:z,ref:H})),null!=k&&t.createElement("span",{className:`${I}-label`},k))))});var p=e.i(8211),h=e.i(529681),C=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var l=0,a=Object.getOwnPropertySymbols(e);lt.indexOf(a[l])&&Object.prototype.propertyIsEnumerable.call(e,a[l])&&(r[a[l]]=e[a[l]]);return r};let v=t.forwardRef((e,a)=>{let{defaultValue:l,children:o,options:n=[],prefixCls:s,className:c,rootClassName:g,style:f,onChange:v}=e,k=C(e,["defaultValue","children","options","prefixCls","className","rootClassName","style","onChange"]),{getPrefixCls:x,direction:w}=t.useContext(i.ConfigContext),[$,y]=t.useState(k.value||l||[]),[N,O]=t.useState([]);t.useEffect(()=>{"value"in k&&y(k.value||[])},[k.value]);let E=t.useMemo(()=>n.map(e=>"string"==typeof e||"number"==typeof e?{label:e,value:e}:e),[n]),j=e=>{O(t=>t.filter(t=>t!==e))},T=e=>{O(t=>[].concat((0,p.default)(t),[e]))},S=e=>{let t=$.indexOf(e.value),r=(0,p.default)($);-1===t?r.push(e.value):r.splice(t,1),"value"in k||y(r),null==v||v(r.filter(e=>N.includes(e)).sort((e,t)=>E.findIndex(t=>t.value===e)-E.findIndex(e=>e.value===t)))},R=x("checkbox",s),M=`${R}-group`,P=(0,d.default)(R),[z,B,q]=(0,m.default)(R,P),H=(0,h.default)(k,["value","disabled"]),I=n.length?E.map(e=>t.createElement(b,{prefixCls:R,key:e.value.toString(),disabled:"disabled"in e?e.disabled:k.disabled,value:e.value,checked:$.includes(e.value),onChange:e.onChange,className:(0,r.default)(`${M}-item`,e.className),style:e.style,title:e.title,id:e.id,required:e.required},e.label)):o,L=t.useMemo(()=>({toggleOption:S,value:$,disabled:k.disabled,name:k.name,registerValue:T,cancelValue:j}),[S,$,k.disabled,k.name,T,j]),_=(0,r.default)(M,{[`${M}-rtl`]:"rtl"===w},c,g,q,P,B);return z(t.createElement("div",Object.assign({className:_,style:f},H,{ref:a}),t.createElement(u.default.Provider,{value:L},I)))});b.Group=v,b.__ANT_CHECKBOX=!0,e.s(["default",0,b],374276)},536916,e=>{"use strict";var t=e.i(374276);e.s(["Checkbox",()=>t.default])},185793,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),a=e.i(242064),l=e.i(529681);let o=e=>{let{prefixCls:a,className:l,style:o,size:n,shape:i}=e,s=(0,r.default)({[`${a}-lg`]:"large"===n,[`${a}-sm`]:"small"===n}),d=(0,r.default)({[`${a}-circle`]:"circle"===i,[`${a}-square`]:"square"===i,[`${a}-round`]:"round"===i}),c=t.useMemo(()=>"number"==typeof n?{width:n,height:n,lineHeight:`${n}px`}:{},[n]);return t.createElement("span",{className:(0,r.default)(a,s,d,l),style:Object.assign(Object.assign({},c),o)})};e.i(296059);var n=e.i(694758),i=e.i(915654),s=e.i(246422),d=e.i(838378);let c=new n.Keyframes("ant-skeleton-loading",{"0%":{backgroundPosition:"100% 50%"},"100%":{backgroundPosition:"0 50%"}}),u=e=>({height:e,lineHeight:(0,i.unit)(e)}),m=e=>Object.assign({width:e},u(e)),g=(e,t)=>Object.assign({width:t(e).mul(5).equal(),minWidth:t(e).mul(5).equal()},u(e)),f=e=>Object.assign({width:e},u(e)),b=(e,t,r)=>{let{skeletonButtonCls:a}=e;return{[`${r}${a}-circle`]:{width:t,minWidth:t,borderRadius:"50%"},[`${r}${a}-round`]:{borderRadius:t}}},p=(e,t)=>Object.assign({width:t(e).mul(2).equal(),minWidth:t(e).mul(2).equal()},u(e)),h=(0,s.genStyleHooks)("Skeleton",e=>{let{componentCls:t,calc:r}=e;return(e=>{let{componentCls:t,skeletonAvatarCls:r,skeletonTitleCls:a,skeletonParagraphCls:l,skeletonButtonCls:o,skeletonInputCls:n,skeletonImageCls:i,controlHeight:s,controlHeightLG:d,controlHeightSM:u,gradientFromColor:h,padding:C,marginSM:v,borderRadius:k,titleHeight:x,blockRadius:w,paragraphLiHeight:$,controlHeightXS:y,paragraphMarginTop:N}=e;return{[t]:{display:"table",width:"100%",[`${t}-header`]:{display:"table-cell",paddingInlineEnd:C,verticalAlign:"top",[r]:Object.assign({display:"inline-block",verticalAlign:"top",background:h},m(s)),[`${r}-circle`]:{borderRadius:"50%"},[`${r}-lg`]:Object.assign({},m(d)),[`${r}-sm`]:Object.assign({},m(u))},[`${t}-content`]:{display:"table-cell",width:"100%",verticalAlign:"top",[a]:{width:"100%",height:x,background:h,borderRadius:w,[`+ ${l}`]:{marginBlockStart:u}},[l]:{padding:0,"> li":{width:"100%",height:$,listStyle:"none",background:h,borderRadius:w,"+ li":{marginBlockStart:y}}},[`${l}> li:last-child:not(:first-child):not(:nth-child(2))`]:{width:"61%"}},[`&-round ${t}-content`]:{[`${a}, ${l} > li`]:{borderRadius:k}}},[`${t}-with-avatar ${t}-content`]:{[a]:{marginBlockStart:v,[`+ ${l}`]:{marginBlockStart:N}}},[`${t}${t}-element`]:Object.assign(Object.assign(Object.assign(Object.assign({display:"inline-block",width:"auto"},(e=>{let{borderRadiusSM:t,skeletonButtonCls:r,controlHeight:a,controlHeightLG:l,controlHeightSM:o,gradientFromColor:n,calc:i}=e;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({[r]:Object.assign({display:"inline-block",verticalAlign:"top",background:n,borderRadius:t,width:i(a).mul(2).equal(),minWidth:i(a).mul(2).equal()},p(a,i))},b(e,a,r)),{[`${r}-lg`]:Object.assign({},p(l,i))}),b(e,l,`${r}-lg`)),{[`${r}-sm`]:Object.assign({},p(o,i))}),b(e,o,`${r}-sm`))})(e)),(e=>{let{skeletonAvatarCls:t,gradientFromColor:r,controlHeight:a,controlHeightLG:l,controlHeightSM:o}=e;return{[t]:Object.assign({display:"inline-block",verticalAlign:"top",background:r},m(a)),[`${t}${t}-circle`]:{borderRadius:"50%"},[`${t}${t}-lg`]:Object.assign({},m(l)),[`${t}${t}-sm`]:Object.assign({},m(o))}})(e)),(e=>{let{controlHeight:t,borderRadiusSM:r,skeletonInputCls:a,controlHeightLG:l,controlHeightSM:o,gradientFromColor:n,calc:i}=e;return{[a]:Object.assign({display:"inline-block",verticalAlign:"top",background:n,borderRadius:r},g(t,i)),[`${a}-lg`]:Object.assign({},g(l,i)),[`${a}-sm`]:Object.assign({},g(o,i))}})(e)),(e=>{let{skeletonImageCls:t,imageSizeBase:r,gradientFromColor:a,borderRadiusSM:l,calc:o}=e;return{[t]:Object.assign(Object.assign({display:"inline-flex",alignItems:"center",justifyContent:"center",verticalAlign:"middle",background:a,borderRadius:l},f(o(r).mul(2).equal())),{[`${t}-path`]:{fill:"#bfbfbf"},[`${t}-svg`]:Object.assign(Object.assign({},f(r)),{maxWidth:o(r).mul(4).equal(),maxHeight:o(r).mul(4).equal()}),[`${t}-svg${t}-svg-circle`]:{borderRadius:"50%"}}),[`${t}${t}-circle`]:{borderRadius:"50%"}}})(e)),[`${t}${t}-block`]:{width:"100%",[o]:{width:"100%"},[n]:{width:"100%"}},[`${t}${t}-active`]:{[` - ${a}, - ${l} > li, - ${r}, - ${o}, - ${n}, - ${i} - `]:Object.assign({},{background:e.skeletonLoadingBackground,backgroundSize:"400% 100%",animationName:c,animationDuration:e.skeletonLoadingMotionDuration,animationTimingFunction:"ease",animationIterationCount:"infinite"})}}})((0,d.mergeToken)(e,{skeletonAvatarCls:`${t}-avatar`,skeletonTitleCls:`${t}-title`,skeletonParagraphCls:`${t}-paragraph`,skeletonButtonCls:`${t}-button`,skeletonInputCls:`${t}-input`,skeletonImageCls:`${t}-image`,imageSizeBase:r(e.controlHeight).mul(1.5).equal(),borderRadius:100,skeletonLoadingBackground:`linear-gradient(90deg, ${e.gradientFromColor} 25%, ${e.gradientToColor} 37%, ${e.gradientFromColor} 63%)`,skeletonLoadingMotionDuration:"1.4s"}))},e=>{let{colorFillContent:t,colorFill:r}=e;return{color:t,colorGradientEnd:r,gradientFromColor:t,gradientToColor:r,titleHeight:e.controlHeight/2,blockRadius:e.borderRadiusSM,paragraphMarginTop:e.marginLG+e.marginXXS,paragraphLiHeight:e.controlHeight/2}},{deprecatedTokens:[["color","gradientFromColor"],["colorGradientEnd","gradientToColor"]]}),C=e=>{let{prefixCls:a,className:l,style:o,rows:n=0}=e,i=Array.from({length:n}).map((r,a)=>t.createElement("li",{key:a,style:{width:((e,t)=>{let{width:r,rows:a=2}=t;return Array.isArray(r)?r[e]:a-1===e?r:void 0})(a,e)}}));return t.createElement("ul",{className:(0,r.default)(a,l),style:o},i)},v=({prefixCls:e,className:a,width:l,style:o})=>t.createElement("h3",{className:(0,r.default)(e,a),style:Object.assign({width:l},o)});function k(e){return e&&"object"==typeof e?e:{}}let x=e=>{let{prefixCls:l,loading:n,className:i,rootClassName:s,style:d,children:c,avatar:u=!1,title:m=!0,paragraph:g=!0,active:f,round:b}=e,{getPrefixCls:p,direction:x,className:w,style:$}=(0,a.useComponentConfig)("skeleton"),y=p("skeleton",l),[N,O,E]=h(y);if(n||!("loading"in e)){let e,a,l=!!u,n=!!m,c=!!g;if(l){let r=Object.assign(Object.assign({prefixCls:`${y}-avatar`},n&&!c?{size:"large",shape:"square"}:{size:"large",shape:"circle"}),k(u));e=t.createElement("div",{className:`${y}-header`},t.createElement(o,Object.assign({},r)))}if(n||c){let e,r;if(n){let r=Object.assign(Object.assign({prefixCls:`${y}-title`},!l&&c?{width:"38%"}:l&&c?{width:"50%"}:{}),k(m));e=t.createElement(v,Object.assign({},r))}if(c){let e,a=Object.assign(Object.assign({prefixCls:`${y}-paragraph`},(e={},l&&n||(e.width="61%"),!l&&n?e.rows=3:e.rows=2,e)),k(g));r=t.createElement(C,Object.assign({},a))}a=t.createElement("div",{className:`${y}-content`},e,r)}let p=(0,r.default)(y,{[`${y}-with-avatar`]:l,[`${y}-active`]:f,[`${y}-rtl`]:"rtl"===x,[`${y}-round`]:b},w,i,s,O,E);return N(t.createElement("div",{className:p,style:Object.assign(Object.assign({},$),d)},e,a))}return null!=c?c:null};x.Button=e=>{let{prefixCls:n,className:i,rootClassName:s,active:d,block:c=!1,size:u="default"}=e,{getPrefixCls:m}=t.useContext(a.ConfigContext),g=m("skeleton",n),[f,b,p]=h(g),C=(0,l.default)(e,["prefixCls"]),v=(0,r.default)(g,`${g}-element`,{[`${g}-active`]:d,[`${g}-block`]:c},i,s,b,p);return f(t.createElement("div",{className:v},t.createElement(o,Object.assign({prefixCls:`${g}-button`,size:u},C))))},x.Avatar=e=>{let{prefixCls:n,className:i,rootClassName:s,active:d,shape:c="circle",size:u="default"}=e,{getPrefixCls:m}=t.useContext(a.ConfigContext),g=m("skeleton",n),[f,b,p]=h(g),C=(0,l.default)(e,["prefixCls","className"]),v=(0,r.default)(g,`${g}-element`,{[`${g}-active`]:d},i,s,b,p);return f(t.createElement("div",{className:v},t.createElement(o,Object.assign({prefixCls:`${g}-avatar`,shape:c,size:u},C))))},x.Input=e=>{let{prefixCls:n,className:i,rootClassName:s,active:d,block:c,size:u="default"}=e,{getPrefixCls:m}=t.useContext(a.ConfigContext),g=m("skeleton",n),[f,b,p]=h(g),C=(0,l.default)(e,["prefixCls"]),v=(0,r.default)(g,`${g}-element`,{[`${g}-active`]:d,[`${g}-block`]:c},i,s,b,p);return f(t.createElement("div",{className:v},t.createElement(o,Object.assign({prefixCls:`${g}-input`,size:u},C))))},x.Image=e=>{let{prefixCls:l,className:o,rootClassName:n,style:i,active:s}=e,{getPrefixCls:d}=t.useContext(a.ConfigContext),c=d("skeleton",l),[u,m,g]=h(c),f=(0,r.default)(c,`${c}-element`,{[`${c}-active`]:s},o,n,m,g);return u(t.createElement("div",{className:f},t.createElement("div",{className:(0,r.default)(`${c}-image`,o),style:i},t.createElement("svg",{viewBox:"0 0 1098 1024",xmlns:"http://www.w3.org/2000/svg",className:`${c}-image-svg`},t.createElement("title",null,"Image placeholder"),t.createElement("path",{d:"M365.714286 329.142857q0 45.714286-32.036571 77.677714t-77.677714 32.036571-77.677714-32.036571-32.036571-77.677714 32.036571-77.677714 77.677714-32.036571 77.677714 32.036571 32.036571 77.677714zM950.857143 548.571429l0 256-804.571429 0 0-109.714286 182.857143-182.857143 91.428571 91.428571 292.571429-292.571429zM1005.714286 146.285714l-914.285714 0q-7.460571 0-12.873143 5.412571t-5.412571 12.873143l0 694.857143q0 7.460571 5.412571 12.873143t12.873143 5.412571l914.285714 0q7.460571 0 12.873143-5.412571t5.412571-12.873143l0-694.857143q0-7.460571-5.412571-12.873143t-12.873143-5.412571zM1097.142857 164.571429l0 694.857143q0 37.741714-26.843429 64.585143t-64.585143 26.843429l-914.285714 0q-37.741714 0-64.585143-26.843429t-26.843429-64.585143l0-694.857143q0-37.741714 26.843429-64.585143t64.585143-26.843429l914.285714 0q37.741714 0 64.585143 26.843429t26.843429 64.585143z",className:`${c}-image-path`})))))},x.Node=e=>{let{prefixCls:l,className:o,rootClassName:n,style:i,active:s,children:d}=e,{getPrefixCls:c}=t.useContext(a.ConfigContext),u=c("skeleton",l),[m,g,f]=h(u),b=(0,r.default)(u,`${u}-element`,{[`${u}-active`]:s},g,o,n,f);return m(t.createElement("div",{className:b},t.createElement("div",{className:(0,r.default)(`${u}-image`,o),style:i},d)))},e.s(["default",0,x],185793)},959013,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8z"}},{tag:"path",attrs:{d:"M192 474h672q8 0 8 8v60q0 8-8 8H160q-8 0-8-8v-60q0-8 8-8z"}}]},name:"plus",theme:"outlined"};var l=e.i(9583),o=r.forwardRef(function(e,o){return r.createElement(l.default,(0,t.default)({},e,{ref:o,icon:a}))});e.s(["default",0,o],959013)},599724,936325,e=>{"use strict";var t=e.i(95779),r=e.i(444755),a=e.i(673706),l=e.i(271645);let o=l.default.forwardRef((e,o)=>{let{color:n,className:i,children:s}=e;return l.default.createElement("p",{ref:o,className:(0,r.tremorTwMerge)("text-tremor-default",n?(0,a.getColorClassNames)(n,t.colorPalette.text).textColor:(0,r.tremorTwMerge)("text-tremor-content","dark:text-dark-tremor-content"),i)},s)});o.displayName="Text",e.s(["default",()=>o],936325),e.s(["Text",()=>o],599724)},994388,e=>{"use strict";var t=e.i(290571),r=e.i(829087),a=e.i(271645);let l=["preEnter","entering","entered","preExit","exiting","exited","unmounted"],o=e=>({_s:e,status:l[e],isEnter:e<3,isMounted:6!==e,isResolved:2===e||e>4}),n=e=>e?6:5,i=(e,t,r,a,l)=>{clearTimeout(a.current);let n=o(e);t(n),r.current=n,l&&l({current:n})};var s=e.i(480731),d=e.i(444755),c=e.i(673706);let u=e=>{var r=(0,t.__rest)(e,[]);return a.default.createElement("svg",Object.assign({},r,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"}),a.default.createElement("path",{fill:"none",d:"M0 0h24v24H0z"}),a.default.createElement("path",{d:"M18.364 5.636L16.95 7.05A7 7 0 1 0 19 12h2a9 9 0 1 1-2.636-6.364z"}))};var m=e.i(95779);let g={xs:{height:"h-4",width:"w-4"},sm:{height:"h-5",width:"w-5"},md:{height:"h-5",width:"w-5"},lg:{height:"h-6",width:"w-6"},xl:{height:"h-6",width:"w-6"}},f=(e,t)=>{switch(e){case"primary":return{textColor:t?(0,c.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",hoverTextColor:t?(0,c.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",bgColor:t?(0,c.getColorClassNames)(t,m.colorPalette.background).bgColor:"bg-tremor-brand dark:bg-dark-tremor-brand",hoverBgColor:t?(0,c.getColorClassNames)(t,m.colorPalette.darkBackground).hoverBgColor:"hover:bg-tremor-brand-emphasis dark:hover:bg-dark-tremor-brand-emphasis",borderColor:t?(0,c.getColorClassNames)(t,m.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",hoverBorderColor:t?(0,c.getColorClassNames)(t,m.colorPalette.darkBorder).hoverBorderColor:"hover:border-tremor-brand-emphasis dark:hover:border-dark-tremor-brand-emphasis"};case"secondary":return{textColor:t?(0,c.getColorClassNames)(t,m.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,c.getColorClassNames)(t,m.colorPalette.text).textColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,c.getColorClassNames)("transparent").bgColor,hoverBgColor:t?(0,d.tremorTwMerge)((0,c.getColorClassNames)(t,m.colorPalette.background).hoverBgColor,"hover:bg-opacity-20 dark:hover:bg-opacity-20"):"hover:bg-tremor-brand-faint dark:hover:bg-dark-tremor-brand-faint",borderColor:t?(0,c.getColorClassNames)(t,m.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand"};case"light":return{textColor:t?(0,c.getColorClassNames)(t,m.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,c.getColorClassNames)(t,m.colorPalette.darkText).hoverTextColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,c.getColorClassNames)("transparent").bgColor,borderColor:"",hoverBorderColor:""}}},b=(0,c.makeClassName)("Button"),p=({loading:e,iconSize:t,iconPosition:r,Icon:l,needMargin:o,transitionStatus:n})=>{let i=o?r===s.HorizontalPositions.Left?(0,d.tremorTwMerge)("-ml-1","mr-1.5"):(0,d.tremorTwMerge)("-mr-1","ml-1.5"):"",c=(0,d.tremorTwMerge)("w-0 h-0"),m={default:c,entering:c,entered:t,exiting:t,exited:c};return e?a.default.createElement(u,{className:(0,d.tremorTwMerge)(b("icon"),"animate-spin shrink-0",i,m.default,m[n]),style:{transition:"width 150ms"}}):a.default.createElement(l,{className:(0,d.tremorTwMerge)(b("icon"),"shrink-0",t,i)})},h=a.default.forwardRef((e,l)=>{let{icon:u,iconPosition:m=s.HorizontalPositions.Left,size:h=s.Sizes.SM,color:C,variant:v="primary",disabled:k,loading:x=!1,loadingText:w,children:$,tooltip:y,className:N}=e,O=(0,t.__rest)(e,["icon","iconPosition","size","color","variant","disabled","loading","loadingText","children","tooltip","className"]),E=x||k,j=void 0!==u||x,T=x&&w,S=!(!$&&!T),R=(0,d.tremorTwMerge)(g[h].height,g[h].width),M="light"!==v?(0,d.tremorTwMerge)("rounded-tremor-default border","shadow-tremor-input","dark:shadow-dark-tremor-input"):"",P=f(v,C),z=("light"!==v?{xs:{paddingX:"px-2.5",paddingY:"py-1.5",fontSize:"text-xs"},sm:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-sm"},md:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-md"},lg:{paddingX:"px-4",paddingY:"py-2.5",fontSize:"text-lg"},xl:{paddingX:"px-4",paddingY:"py-3",fontSize:"text-xl"}}:{xs:{paddingX:"",paddingY:"",fontSize:"text-xs"},sm:{paddingX:"",paddingY:"",fontSize:"text-sm"},md:{paddingX:"",paddingY:"",fontSize:"text-md"},lg:{paddingX:"",paddingY:"",fontSize:"text-lg"},xl:{paddingX:"",paddingY:"",fontSize:"text-xl"}})[h],{tooltipProps:B,getReferenceProps:q}=(0,r.useTooltip)(300),[H,I]=(({enter:e=!0,exit:t=!0,preEnter:r,preExit:l,timeout:s,initialEntered:d,mountOnEnter:c,unmountOnExit:u,onStateChange:m}={})=>{let[g,f]=(0,a.useState)(()=>o(d?2:n(c))),b=(0,a.useRef)(g),p=(0,a.useRef)(0),[h,C]="object"==typeof s?[s.enter,s.exit]:[s,s],v=(0,a.useCallback)(()=>{let e=((e,t)=>{switch(e){case 1:case 0:return 2;case 4:case 3:return n(t)}})(b.current._s,u);e&&i(e,f,b,p,m)},[m,u]);return[g,(0,a.useCallback)(a=>{let o=e=>{switch(i(e,f,b,p,m),e){case 1:h>=0&&(p.current=((...e)=>setTimeout(...e))(v,h));break;case 4:C>=0&&(p.current=((...e)=>setTimeout(...e))(v,C));break;case 0:case 3:p.current=((...e)=>setTimeout(...e))(()=>{isNaN(document.body.offsetTop)||o(e+1)},0)}},s=b.current.isEnter;"boolean"!=typeof a&&(a=!s),a?s||o(e?+!r:2):s&&o(t?l?3:4:n(u))},[v,m,e,t,r,l,h,C,u]),v]})({timeout:50});return(0,a.useEffect)(()=>{I(x)},[x]),a.default.createElement("button",Object.assign({ref:(0,c.mergeRefs)([l,B.refs.setReference]),className:(0,d.tremorTwMerge)(b("root"),"shrink-0 inline-flex justify-center items-center group font-medium outline-none",M,z.paddingX,z.paddingY,z.fontSize,P.textColor,P.bgColor,P.borderColor,P.hoverBorderColor,E?"opacity-50 cursor-not-allowed":(0,d.tremorTwMerge)(f(v,C).hoverTextColor,f(v,C).hoverBgColor,f(v,C).hoverBorderColor),N),disabled:E},q,O),a.default.createElement(r.default,Object.assign({text:y},B)),j&&m!==s.HorizontalPositions.Right?a.default.createElement(p,{loading:x,iconSize:R,iconPosition:m,Icon:u,transitionStatus:H.status,needMargin:S}):null,T||$?a.default.createElement("span",{className:(0,d.tremorTwMerge)(b("text"),"text-tremor-default whitespace-nowrap")},T?w:$):null,j&&m===s.HorizontalPositions.Right?a.default.createElement(p,{loading:x,iconSize:R,iconPosition:m,Icon:u,transitionStatus:H.status,needMargin:S}):null)});h.displayName="Button",e.s(["Button",()=>h],994388)},304967,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(480731),l=e.i(95779),o=e.i(444755),n=e.i(673706);let i=(0,n.makeClassName)("Card"),s=r.default.forwardRef((e,s)=>{let{decoration:d="",decorationColor:c,children:u,className:m}=e,g=(0,t.__rest)(e,["decoration","decorationColor","children","className"]);return r.default.createElement("div",Object.assign({ref:s,className:(0,o.tremorTwMerge)(i("root"),"relative w-full text-left ring-1 rounded-tremor-default p-6","bg-tremor-background ring-tremor-ring shadow-tremor-card","dark:bg-dark-tremor-background dark:ring-dark-tremor-ring dark:shadow-dark-tremor-card",c?(0,n.getColorClassNames)(c,l.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",(e=>{if(!e)return"";switch(e){case a.HorizontalPositions.Left:return"border-l-4";case a.VerticalPositions.Top:return"border-t-4";case a.HorizontalPositions.Right:return"border-r-4";case a.VerticalPositions.Bottom:return"border-b-4";default:return""}})(d),m)},g),u)});s.displayName="Card",e.s(["Card",()=>s],304967)},269200,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let l=(0,e.i(673706).makeClassName)("Table"),o=r.default.forwardRef((e,o)=>{let{children:n,className:i}=e,s=(0,t.__rest)(e,["children","className"]);return r.default.createElement("div",{className:(0,a.tremorTwMerge)(l("root"),"overflow-auto",i)},r.default.createElement("table",Object.assign({ref:o,className:(0,a.tremorTwMerge)(l("table"),"w-full text-tremor-default","text-tremor-content","dark:text-dark-tremor-content")},s),n))});o.displayName="Table",e.s(["Table",()=>o],269200)},942232,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let l=(0,e.i(673706).makeClassName)("TableBody"),o=r.default.forwardRef((e,o)=>{let{children:n,className:i}=e,s=(0,t.__rest)(e,["children","className"]);return r.default.createElement(r.default.Fragment,null,r.default.createElement("tbody",Object.assign({ref:o,className:(0,a.tremorTwMerge)(l("root"),"align-top divide-y","divide-tremor-border","dark:divide-dark-tremor-border",i)},s),n))});o.displayName="TableBody",e.s(["TableBody",()=>o],942232)},977572,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let l=(0,e.i(673706).makeClassName)("TableCell"),o=r.default.forwardRef((e,o)=>{let{children:n,className:i}=e,s=(0,t.__rest)(e,["children","className"]);return r.default.createElement(r.default.Fragment,null,r.default.createElement("td",Object.assign({ref:o,className:(0,a.tremorTwMerge)(l("root"),"align-middle whitespace-nowrap text-left p-4",i)},s),n))});o.displayName="TableCell",e.s(["TableCell",()=>o],977572)},427612,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let l=(0,e.i(673706).makeClassName)("TableHead"),o=r.default.forwardRef((e,o)=>{let{children:n,className:i}=e,s=(0,t.__rest)(e,["children","className"]);return r.default.createElement(r.default.Fragment,null,r.default.createElement("thead",Object.assign({ref:o,className:(0,a.tremorTwMerge)(l("root"),"text-left","text-tremor-content","dark:text-dark-tremor-content",i)},s),n))});o.displayName="TableHead",e.s(["TableHead",()=>o],427612)},64848,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let l=(0,e.i(673706).makeClassName)("TableHeaderCell"),o=r.default.forwardRef((e,o)=>{let{children:n,className:i}=e,s=(0,t.__rest)(e,["children","className"]);return r.default.createElement(r.default.Fragment,null,r.default.createElement("th",Object.assign({ref:o,className:(0,a.tremorTwMerge)(l("root"),"whitespace-nowrap text-left font-semibold top-0 px-4 py-3.5","text-tremor-content-strong","dark:text-dark-tremor-content-strong",i)},s),n))});o.displayName="TableHeaderCell",e.s(["TableHeaderCell",()=>o],64848)},496020,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(444755);let l=(0,e.i(673706).makeClassName)("TableRow"),o=r.default.forwardRef((e,o)=>{let{children:n,className:i}=e,s=(0,t.__rest)(e,["children","className"]);return r.default.createElement(r.default.Fragment,null,r.default.createElement("tr",Object.assign({ref:o,className:(0,a.tremorTwMerge)(l("row"),i)},s),n))});o.displayName="TableRow",e.s(["TableRow",()=>o],496020)},68155,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.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.s(["TrashIcon",0,r],68155)},360820,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 15l7-7 7 7"}))});e.s(["ChevronUpIcon",0,r],360820)},871943,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"}))});e.s(["ChevronDownIcon",0,r],871943)},278587,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",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"}))});e.s(["RefreshIcon",0,r],278587)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/575cc1c8ef6c4319.js b/litellm/proxy/_experimental/out/_next/static/chunks/575cc1c8ef6c4319.js new file mode 100644 index 00000000000..f15feb8bcde --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/575cc1c8ef6c4319.js @@ -0,0 +1 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,928685,e=>{"use strict";var t=e.i(38953);e.s(["SearchOutlined",()=>t.default])},700514,e=>{"use strict";var t=e.i(271645);e.s(["defaultPageSize",0,25,"useBaseUrl",0,()=>{let[e,r]=(0,t.useState)("http://localhost:4000");return(0,t.useEffect)(()=>{{let{protocol:e,host:t}=window.location;r(`${e}//${t}`)}},[]),e}])},688511,823429,e=>{"use strict";let t=(0,e.i(475254).default)("square-pen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]]);e.s(["default",()=>t],823429),e.s(["Edit",()=>t],688511)},844444,e=>{"use strict";var t=e.i(843476),r=e.i(906579),a=e.i(271645),o=e.i(115571);function n(e){let t=t=>{"disableShowNewBadge"===t.key&&e()},r=t=>{let{key:r}=t.detail;"disableShowNewBadge"===r&&e()};return window.addEventListener("storage",t),window.addEventListener(o.LOCAL_STORAGE_EVENT,r),()=>{window.removeEventListener("storage",t),window.removeEventListener(o.LOCAL_STORAGE_EVENT,r)}}function i(){return"true"===(0,o.getLocalStorageItem)("disableShowNewBadge")}function s({children:e,dot:o=!1}){return(0,a.useSyncExternalStore)(n,i)?e?(0,t.jsx)(t.Fragment,{children:e}):null:e?(0,t.jsx)(r.Badge,{color:"blue",count:o?void 0:"New",dot:o,children:e}):(0,t.jsx)(r.Badge,{color:"blue",count:o?void 0:"New",dot:o})}e.s(["default",()=>s],844444)},366283,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(95779),o=e.i(444755),n=e.i(673706);let i=(0,n.makeClassName)("Callout"),s=r.default.forwardRef((e,s)=>{let{title:l,icon:c,color:u,className:d,children:m}=e,f=(0,t.__rest)(e,["title","icon","color","className","children"]);return r.default.createElement("div",Object.assign({ref:s,className:(0,o.tremorTwMerge)(i("root"),"flex flex-col overflow-hidden rounded-tremor-default text-tremor-default border-l-4 py-3 pr-3 pl-4",u?(0,o.tremorTwMerge)((0,n.getColorClassNames)(u,a.colorPalette.background).bgColor,(0,n.getColorClassNames)(u,a.colorPalette.darkBorder).borderColor,(0,n.getColorClassNames)(u,a.colorPalette.darkText).textColor,"dark:bg-opacity-10 bg-opacity-10"):(0,o.tremorTwMerge)("bg-tremor-brand-faint border-tremor-brand-emphasis text-tremor-brand-emphasis","dark:bg-dark-tremor-brand-muted/70 dark:border-dark-tremor-brand-emphasis dark:text-dark-tremor-brand-emphasis"),d)},f),r.default.createElement("div",{className:(0,o.tremorTwMerge)(i("header"),"flex items-start")},c?r.default.createElement(c,{className:(0,o.tremorTwMerge)(i("icon"),"flex-none h-5 w-5 mr-1.5")}):null,r.default.createElement("h4",{className:(0,o.tremorTwMerge)(i("title"),"font-semibold")},l)),r.default.createElement("p",{className:(0,o.tremorTwMerge)(i("body"),"overflow-y-auto",m?"mt-2":"")},m))});s.displayName="Callout",e.s(["Callout",()=>s],366283)},475647,286536,77705,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M696 480H544V328c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v152H328c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8h152v152c0 4.4 3.6 8 8 8h48c4.4 0 8-3.6 8-8V544h152c4.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:"plus-circle",theme:"outlined"};var o=e.i(9583),n=r.forwardRef(function(e,n){return r.createElement(o.default,(0,t.default)({},e,{ref:n,icon:a}))});e.s(["PlusCircleOutlined",0,n],475647);var i=e.i(475254);let s=(0,i.default)("eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);e.s(["Eye",()=>s],286536);let l=(0,i.default)("eye-off",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);e.s(["EyeOff",()=>l],77705)},727612,e=>{"use strict";let t=(0,e.i(475254).default)("trash-2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);e.s(["Trash2",()=>t],727612)},918549,e=>{"use strict";let t=(0,e.i(475254).default)("shield",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]]);e.s(["default",()=>t])},166406,e=>{"use strict";var t=e.i(190144);e.s(["CopyOutlined",()=>t.default])},362024,e=>{"use strict";var t=e.i(988122);e.s(["Collapse",()=>t.default])},596239,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M574 665.4a8.03 8.03 0 00-11.3 0L446.5 781.6c-53.8 53.8-144.6 59.5-204 0-59.5-59.5-53.8-150.2 0-204l116.2-116.2c3.1-3.1 3.1-8.2 0-11.3l-39.8-39.8a8.03 8.03 0 00-11.3 0L191.4 526.5c-84.6 84.6-84.6 221.5 0 306s221.5 84.6 306 0l116.2-116.2c3.1-3.1 3.1-8.2 0-11.3L574 665.4zm258.6-474c-84.6-84.6-221.5-84.6-306 0L410.3 307.6a8.03 8.03 0 000 11.3l39.7 39.7c3.1 3.1 8.2 3.1 11.3 0l116.2-116.2c53.8-53.8 144.6-59.5 204 0 59.5 59.5 53.8 150.2 0 204L665.3 562.6a8.03 8.03 0 000 11.3l39.8 39.8c3.1 3.1 8.2 3.1 11.3 0l116.2-116.2c84.5-84.6 84.5-221.5 0-306.1zM610.1 372.3a8.03 8.03 0 00-11.3 0L372.3 598.7a8.03 8.03 0 000 11.3l39.6 39.6c3.1 3.1 8.2 3.1 11.3 0l226.4-226.4c3.1-3.1 3.1-8.2 0-11.3l-39.5-39.6z"}}]},name:"link",theme:"outlined"};var o=e.i(9583),n=r.forwardRef(function(e,n){return r.createElement(o.default,(0,t.default)({},e,{ref:n,icon:a}))});e.s(["LinkOutlined",0,n],596239)},98919,e=>{"use strict";var t=e.i(918549);e.s(["Shield",()=>t.default])},114600,e=>{"use strict";var t=e.i(290571),r=e.i(444755),a=e.i(673706),o=e.i(271645);let n=(0,a.makeClassName)("Divider"),i=o.default.forwardRef((e,a)=>{let{className:i,children:s}=e,l=(0,t.__rest)(e,["className","children"]);return o.default.createElement("div",Object.assign({ref:a,className:(0,r.tremorTwMerge)(n("root"),"w-full mx-auto my-6 flex justify-between gap-3 items-center text-tremor-default","text-tremor-content","dark:text-dark-tremor-content",i)},l),s?o.default.createElement(o.default.Fragment,null,o.default.createElement("div",{className:(0,r.tremorTwMerge)("w-full h-[1px] bg-tremor-border dark:bg-dark-tremor-border")}),o.default.createElement("div",{className:(0,r.tremorTwMerge)("text-inherit whitespace-nowrap")},s),o.default.createElement("div",{className:(0,r.tremorTwMerge)("w-full h-[1px] bg-tremor-border dark:bg-dark-tremor-border")})):o.default.createElement("div",{className:(0,r.tremorTwMerge)("w-full h-[1px] bg-tremor-border dark:bg-dark-tremor-border")}))});i.displayName="Divider",e.s(["Divider",()=>i],114600)},21548,e=>{"use strict";var t=e.i(616303);e.s(["Empty",()=>t.default])},906579,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),a=e.i(361275),o=e.i(702779),n=e.i(763731),i=e.i(242064);e.i(296059);var s=e.i(915654),l=e.i(694758),c=e.i(183293),u=e.i(403541),d=e.i(246422),m=e.i(838378);let f=new l.Keyframes("antStatusProcessing",{"0%":{transform:"scale(0.8)",opacity:.5},"100%":{transform:"scale(2.4)",opacity:0}}),b=new l.Keyframes("antZoomBadgeIn",{"0%":{transform:"scale(0) translate(50%, -50%)",opacity:0},"100%":{transform:"scale(1) translate(50%, -50%)"}}),p=new l.Keyframes("antZoomBadgeOut",{"0%":{transform:"scale(1) translate(50%, -50%)"},"100%":{transform:"scale(0) translate(50%, -50%)",opacity:0}}),g=new l.Keyframes("antNoWrapperZoomBadgeIn",{"0%":{transform:"scale(0)",opacity:0},"100%":{transform:"scale(1)"}}),h=new l.Keyframes("antNoWrapperZoomBadgeOut",{"0%":{transform:"scale(1)"},"100%":{transform:"scale(0)",opacity:0}}),y=new l.Keyframes("antBadgeLoadingCircle",{"0%":{transformOrigin:"50%"},"100%":{transform:"translate(50%, -50%) rotate(360deg)",transformOrigin:"50%"}}),v=e=>{let{fontHeight:t,lineWidth:r,marginXS:a,colorBorderBg:o}=e,n=e.colorTextLightSolid,i=e.colorError,s=e.colorErrorHover;return(0,m.mergeToken)(e,{badgeFontHeight:t,badgeShadowSize:r,badgeTextColor:n,badgeColor:i,badgeColorHover:s,badgeShadowColor:o,badgeProcessingDuration:"1.2s",badgeRibbonOffset:a,badgeRibbonCornerTransform:"scaleY(0.75)",badgeRibbonCornerFilter:"brightness(75%)"})},w=e=>{let{fontSize:t,lineHeight:r,fontSizeSM:a,lineWidth:o}=e;return{indicatorZIndex:"auto",indicatorHeight:Math.round(t*r)-2*o,indicatorHeightSM:t,dotSize:a/2,textFontSize:a,textFontSizeSM:a,textFontWeight:"normal",statusSize:a/2}},O=(0,d.genStyleHooks)("Badge",e=>(e=>{let{componentCls:t,iconCls:r,antCls:a,badgeShadowSize:o,textFontSize:n,textFontSizeSM:i,statusSize:l,dotSize:d,textFontWeight:m,indicatorHeight:v,indicatorHeightSM:w,marginXS:O,calc:$}=e,x=`${a}-scroll-number`,C=(0,u.genPresetColor)(e,(e,{darkColor:r})=>({[`&${t} ${t}-color-${e}`]:{background:r,[`&:not(${t}-count)`]:{color:r},"a:hover &":{background:r}}}));return{[t]:Object.assign(Object.assign(Object.assign(Object.assign({},(0,c.resetComponent)(e)),{position:"relative",display:"inline-block",width:"fit-content",lineHeight:1,[`${t}-count`]:{display:"inline-flex",justifyContent:"center",zIndex:e.indicatorZIndex,minWidth:v,height:v,color:e.badgeTextColor,fontWeight:m,fontSize:n,lineHeight:(0,s.unit)(v),whiteSpace:"nowrap",textAlign:"center",background:e.badgeColor,borderRadius:$(v).div(2).equal(),boxShadow:`0 0 0 ${(0,s.unit)(o)} ${e.badgeShadowColor}`,transition:`background ${e.motionDurationMid}`,a:{color:e.badgeTextColor},"a:hover":{color:e.badgeTextColor},"a:hover &":{background:e.badgeColorHover}},[`${t}-count-sm`]:{minWidth:w,height:w,fontSize:i,lineHeight:(0,s.unit)(w),borderRadius:$(w).div(2).equal()},[`${t}-multiple-words`]:{padding:`0 ${(0,s.unit)(e.paddingXS)}`,bdi:{unicodeBidi:"plaintext"}},[`${t}-dot`]:{zIndex:e.indicatorZIndex,width:d,minWidth:d,height:d,background:e.badgeColor,borderRadius:"100%",boxShadow:`0 0 0 ${(0,s.unit)(o)} ${e.badgeShadowColor}`},[`${t}-count, ${t}-dot, ${x}-custom-component`]:{position:"absolute",top:0,insetInlineEnd:0,transform:"translate(50%, -50%)",transformOrigin:"100% 0%",[`&${r}-spin`]:{animationName:y,animationDuration:"1s",animationIterationCount:"infinite",animationTimingFunction:"linear"}},[`&${t}-status`]:{lineHeight:"inherit",verticalAlign:"baseline",[`${t}-status-dot`]:{position:"relative",top:-1,display:"inline-block",width:l,height:l,verticalAlign:"middle",borderRadius:"50%"},[`${t}-status-success`]:{backgroundColor:e.colorSuccess},[`${t}-status-processing`]:{overflow:"visible",color:e.colorInfo,backgroundColor:e.colorInfo,borderColor:"currentcolor","&::after":{position:"absolute",top:0,insetInlineStart:0,width:"100%",height:"100%",borderWidth:o,borderStyle:"solid",borderColor:"inherit",borderRadius:"50%",animationName:f,animationDuration:e.badgeProcessingDuration,animationIterationCount:"infinite",animationTimingFunction:"ease-in-out",content:'""'}},[`${t}-status-default`]:{backgroundColor:e.colorTextPlaceholder},[`${t}-status-error`]:{backgroundColor:e.colorError},[`${t}-status-warning`]:{backgroundColor:e.colorWarning},[`${t}-status-text`]:{marginInlineStart:O,color:e.colorText,fontSize:e.fontSize}}}),C),{[`${t}-zoom-appear, ${t}-zoom-enter`]:{animationName:b,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack,animationFillMode:"both"},[`${t}-zoom-leave`]:{animationName:p,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack,animationFillMode:"both"},[`&${t}-not-a-wrapper`]:{[`${t}-zoom-appear, ${t}-zoom-enter`]:{animationName:g,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack},[`${t}-zoom-leave`]:{animationName:h,animationDuration:e.motionDurationSlow,animationTimingFunction:e.motionEaseOutBack},[`&:not(${t}-status)`]:{verticalAlign:"middle"},[`${x}-custom-component, ${t}-count`]:{transform:"none"},[`${x}-custom-component, ${x}`]:{position:"relative",top:"auto",display:"block",transformOrigin:"50% 50%"}},[x]:{overflow:"hidden",transition:`all ${e.motionDurationMid} ${e.motionEaseOutBack}`,[`${x}-only`]:{position:"relative",display:"inline-block",height:v,transition:`all ${e.motionDurationSlow} ${e.motionEaseOutBack}`,WebkitTransformStyle:"preserve-3d",WebkitBackfaceVisibility:"hidden",[`> p${x}-only-unit`]:{height:v,margin:0,WebkitTransformStyle:"preserve-3d",WebkitBackfaceVisibility:"hidden"}},[`${x}-symbol`]:{verticalAlign:"top"}},"&-rtl":{direction:"rtl",[`${t}-count, ${t}-dot, ${x}-custom-component`]:{transform:"translate(-50%, -50%)"}}})}})(v(e)),w),$=(0,d.genStyleHooks)(["Badge","Ribbon"],e=>(e=>{let{antCls:t,badgeFontHeight:r,marginXS:a,badgeRibbonOffset:o,calc:n}=e,i=`${t}-ribbon`,l=`${t}-ribbon-wrapper`,d=(0,u.genPresetColor)(e,(e,{darkColor:t})=>({[`&${i}-color-${e}`]:{background:t,color:t}}));return{[l]:{position:"relative"},[i]:Object.assign(Object.assign(Object.assign(Object.assign({},(0,c.resetComponent)(e)),{position:"absolute",top:a,padding:`0 ${(0,s.unit)(e.paddingXS)}`,color:e.colorPrimary,lineHeight:(0,s.unit)(r),whiteSpace:"nowrap",backgroundColor:e.colorPrimary,borderRadius:e.borderRadiusSM,[`${i}-text`]:{color:e.badgeTextColor},[`${i}-corner`]:{position:"absolute",top:"100%",width:o,height:o,color:"currentcolor",border:`${(0,s.unit)(n(o).div(2).equal())} solid`,transform:e.badgeRibbonCornerTransform,transformOrigin:"top",filter:e.badgeRibbonCornerFilter}}),d),{[`&${i}-placement-end`]:{insetInlineEnd:n(o).mul(-1).equal(),borderEndEndRadius:0,[`${i}-corner`]:{insetInlineEnd:0,borderInlineEndColor:"transparent",borderBlockEndColor:"transparent"}},[`&${i}-placement-start`]:{insetInlineStart:n(o).mul(-1).equal(),borderEndStartRadius:0,[`${i}-corner`]:{insetInlineStart:0,borderBlockEndColor:"transparent",borderInlineStartColor:"transparent"}},"&-rtl":{direction:"rtl"}})}})(v(e)),w),x=e=>{let a,{prefixCls:o,value:n,current:i,offset:s=0}=e;return s&&(a={position:"absolute",top:`${s}00%`,left:0}),t.createElement("span",{style:a,className:(0,r.default)(`${o}-only-unit`,{current:i})},n)},C=e=>{let r,a,{prefixCls:o,count:n,value:i}=e,s=Number(i),l=Math.abs(n),[c,u]=t.useState(s),[d,m]=t.useState(l),f=()=>{u(s),m(l)};if(t.useEffect(()=>{let e=setTimeout(f,1e3);return()=>clearTimeout(e)},[s]),c===s||Number.isNaN(s)||Number.isNaN(c))r=[t.createElement(x,Object.assign({},e,{key:s,current:!0}))],a={transition:"none"};else{r=[];let o=s+10,n=[];for(let e=s;e<=o;e+=1)n.push(e);let i=de%10===c);r=(i<0?n.slice(0,u+1):n.slice(u)).map((r,a)=>t.createElement(x,Object.assign({},e,{key:r,value:r%10,offset:i<0?a-u:a,current:a===u}))),a={transform:`translateY(${-function(e,t,r){let a=e,o=0;for(;(a+10)%10!==t;)a+=r,o+=r;return o}(c,s,i)}00%)`}}return t.createElement("span",{className:`${o}-only`,style:a,onTransitionEnd:f},r)};var E=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,a=Object.getOwnPropertySymbols(e);ot.indexOf(a[o])&&Object.prototype.propertyIsEnumerable.call(e,a[o])&&(r[a[o]]=e[a[o]]);return r};let k=t.forwardRef((e,a)=>{let{prefixCls:o,count:s,className:l,motionClassName:c,style:u,title:d,show:m,component:f="sup",children:b}=e,p=E(e,["prefixCls","count","className","motionClassName","style","title","show","component","children"]),{getPrefixCls:g}=t.useContext(i.ConfigContext),h=g("scroll-number",o),y=Object.assign(Object.assign({},p),{"data-show":m,style:u,className:(0,r.default)(h,l,c),title:d}),v=s;if(s&&Number(s)%1==0){let e=String(s).split("");v=t.createElement("bdi",null,e.map((r,a)=>t.createElement(C,{prefixCls:h,count:Number(s),value:r,key:e.length-a})))}return((null==u?void 0:u.borderColor)&&(y.style=Object.assign(Object.assign({},u),{boxShadow:`0 0 0 1px ${u.borderColor} inset`})),b)?(0,n.cloneElement)(b,e=>({className:(0,r.default)(`${h}-custom-component`,null==e?void 0:e.className,c)})):t.createElement(f,Object.assign({},y,{ref:a}),v)});var S=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,a=Object.getOwnPropertySymbols(e);ot.indexOf(a[o])&&Object.prototype.propertyIsEnumerable.call(e,a[o])&&(r[a[o]]=e[a[o]]);return r};let j=t.forwardRef((e,s)=>{var l,c,u,d,m;let{prefixCls:f,scrollNumberPrefixCls:b,children:p,status:g,text:h,color:y,count:v=null,overflowCount:w=99,dot:$=!1,size:x="default",title:C,offset:E,style:j,className:N,rootClassName:M,classNames:T,styles:R,showZero:P=!1}=e,I=S(e,["prefixCls","scrollNumberPrefixCls","children","status","text","color","count","overflowCount","dot","size","title","offset","style","className","rootClassName","classNames","styles","showZero"]),{getPrefixCls:z,direction:B,badge:D}=t.useContext(i.ConfigContext),L=z("badge",f),[F,K,H]=O(L),_=v>w?`${w}+`:v,A="0"===_||0===_||"0"===h||0===h,W=null===v||A&&!P,q=(null!=g||null!=y)&&W,G=null!=g||!A,V=$&&!A,Q=V?"":_,U=(0,t.useMemo)(()=>((null==Q||""===Q)&&(null==h||""===h)||A&&!P)&&!V,[Q,A,P,V,h]),Z=(0,t.useRef)(v);U||(Z.current=v);let X=Z.current,Y=(0,t.useRef)(Q);U||(Y.current=Q);let J=Y.current,ee=(0,t.useRef)(V);U||(ee.current=V);let et=(0,t.useMemo)(()=>{if(!E)return Object.assign(Object.assign({},null==D?void 0:D.style),j);let e={marginTop:E[1]};return"rtl"===B?e.left=Number.parseInt(E[0],10):e.right=-Number.parseInt(E[0],10),Object.assign(Object.assign(Object.assign({},e),null==D?void 0:D.style),j)},[B,E,j,null==D?void 0:D.style]),er=null!=C?C:"string"==typeof X||"number"==typeof X?X:void 0,ea=!U&&(0===h?P:!!h&&!0!==h),eo=ea?t.createElement("span",{className:`${L}-status-text`},h):null,en=X&&"object"==typeof X?(0,n.cloneElement)(X,e=>({style:Object.assign(Object.assign({},et),e.style)})):void 0,ei=(0,o.isPresetColor)(y,!1),es=(0,r.default)(null==T?void 0:T.indicator,null==(l=null==D?void 0:D.classNames)?void 0:l.indicator,{[`${L}-status-dot`]:q,[`${L}-status-${g}`]:!!g,[`${L}-color-${y}`]:ei}),el={};y&&!ei&&(el.color=y,el.background=y);let ec=(0,r.default)(L,{[`${L}-status`]:q,[`${L}-not-a-wrapper`]:!p,[`${L}-rtl`]:"rtl"===B},N,M,null==D?void 0:D.className,null==(c=null==D?void 0:D.classNames)?void 0:c.root,null==T?void 0:T.root,K,H);if(!p&&q&&(h||G||!W)){let e=et.color;return F(t.createElement("span",Object.assign({},I,{className:ec,style:Object.assign(Object.assign(Object.assign({},null==R?void 0:R.root),null==(u=null==D?void 0:D.styles)?void 0:u.root),et)}),t.createElement("span",{className:es,style:Object.assign(Object.assign(Object.assign({},null==R?void 0:R.indicator),null==(d=null==D?void 0:D.styles)?void 0:d.indicator),el)}),ea&&t.createElement("span",{style:{color:e},className:`${L}-status-text`},h)))}return F(t.createElement("span",Object.assign({ref:s},I,{className:ec,style:Object.assign(Object.assign({},null==(m=null==D?void 0:D.styles)?void 0:m.root),null==R?void 0:R.root)}),p,t.createElement(a.default,{visible:!U,motionName:`${L}-zoom`,motionAppear:!1,motionDeadline:1e3},({className:e})=>{var a,o;let n=z("scroll-number",b),i=ee.current,s=(0,r.default)(null==T?void 0:T.indicator,null==(a=null==D?void 0:D.classNames)?void 0:a.indicator,{[`${L}-dot`]:i,[`${L}-count`]:!i,[`${L}-count-sm`]:"small"===x,[`${L}-multiple-words`]:!i&&J&&J.toString().length>1,[`${L}-status-${g}`]:!!g,[`${L}-color-${y}`]:ei}),l=Object.assign(Object.assign(Object.assign({},null==R?void 0:R.indicator),null==(o=null==D?void 0:D.styles)?void 0:o.indicator),et);return y&&!ei&&((l=l||{}).background=y),t.createElement(k,{prefixCls:n,show:!U,motionClassName:e,className:s,count:J,title:er,style:l,key:"scrollNumber"},en)}),eo))});j.Ribbon=e=>{let{className:a,prefixCls:n,style:s,color:l,children:c,text:u,placement:d="end",rootClassName:m}=e,{getPrefixCls:f,direction:b}=t.useContext(i.ConfigContext),p=f("ribbon",n),g=`${p}-wrapper`,[h,y,v]=$(p,g),w=(0,o.isPresetColor)(l,!1),O=(0,r.default)(p,`${p}-placement-${d}`,{[`${p}-rtl`]:"rtl"===b,[`${p}-color-${l}`]:w},a),x={},C={};return l&&!w&&(x.background=l,C.color=l),h(t.createElement("div",{className:(0,r.default)(g,m,y,v)},c,t.createElement("div",{className:(0,r.default)(O,y),style:Object.assign(Object.assign({},x),s)},t.createElement("span",{className:`${p}-text`},u),t.createElement("div",{className:`${p}-corner`,style:C}))))},e.s(["Badge",0,j],906579)},954616,e=>{"use strict";var t=e.i(271645),r=e.i(114272),a=e.i(540143),o=e.i(915823),n=e.i(619273),i=class extends o.Subscribable{#e;#t=void 0;#r;#a;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#o()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),(0,n.shallowEqualObjects)(this.options,t)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#r,observer:this}),t?.mutationKey&&this.options.mutationKey&&(0,n.hashKey)(t.mutationKey)!==(0,n.hashKey)(this.options.mutationKey)?this.reset():this.#r?.state.status==="pending"&&this.#r.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#r?.removeObserver(this)}onMutationUpdate(e){this.#o(),this.#n(e)}getCurrentResult(){return this.#t}reset(){this.#r?.removeObserver(this),this.#r=void 0,this.#o(),this.#n()}mutate(e,t){return this.#a=t,this.#r?.removeObserver(this),this.#r=this.#e.getMutationCache().build(this.#e,this.options),this.#r.addObserver(this),this.#r.execute(e)}#o(){let e=this.#r?.state??(0,r.getDefaultState)();this.#t={...e,isPending:"pending"===e.status,isSuccess:"success"===e.status,isError:"error"===e.status,isIdle:"idle"===e.status,mutate:this.mutate,reset:this.reset}}#n(e){a.notifyManager.batch(()=>{if(this.#a&&this.hasListeners()){let t=this.#t.variables,r=this.#t.context,a={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#a.onSuccess?.(e.data,t,r,a)}catch(e){Promise.reject(e)}try{this.#a.onSettled?.(e.data,null,t,r,a)}catch(e){Promise.reject(e)}}else if(e?.type==="error"){try{this.#a.onError?.(e.error,t,r,a)}catch(e){Promise.reject(e)}try{this.#a.onSettled?.(void 0,e.error,t,r,a)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},s=e.i(912598);function l(e,r){let o=(0,s.useQueryClient)(r),[l]=t.useState(()=>new i(o,e));t.useEffect(()=>{l.setOptions(e)},[l,e]);let c=t.useSyncExternalStore(t.useCallback(e=>l.subscribe(a.notifyManager.batchCalls(e)),[l]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),u=t.useCallback((e,t)=>{l.mutate(e,t).catch(n.noop)},[l]);if(c.error&&(0,n.shouldThrowError)(l.options.throwOnError,[c.error]))throw c.error;return{...c,mutate:u,mutateAsync:c.mutate}}e.s(["useMutation",()=>l],954616)},525720,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),a=e.i(529681),o=e.i(908286),n=e.i(242064),i=e.i(246422),s=e.i(838378);let l=["wrap","nowrap","wrap-reverse"],c=["flex-start","flex-end","start","end","center","space-between","space-around","space-evenly","stretch","normal","left","right"],u=["center","start","end","flex-start","flex-end","self-start","self-end","baseline","normal","stretch"],d=function(e,t){let a,o,n;return(0,r.default)(Object.assign(Object.assign(Object.assign({},(a=!0===t.wrap?"wrap":t.wrap,{[`${e}-wrap-${a}`]:a&&l.includes(a)})),(o={},u.forEach(r=>{o[`${e}-align-${r}`]=t.align===r}),o[`${e}-align-stretch`]=!t.align&&!!t.vertical,o)),(n={},c.forEach(r=>{n[`${e}-justify-${r}`]=t.justify===r}),n)))},m=(0,i.genStyleHooks)("Flex",e=>{let{paddingXS:t,padding:r,paddingLG:a}=e,o=(0,s.mergeToken)(e,{flexGapSM:t,flexGap:r,flexGapLG:a});return[(e=>{let{componentCls:t}=e;return{[t]:{display:"flex",margin:0,padding:0,"&-vertical":{flexDirection:"column"},"&-rtl":{direction:"rtl"},"&:empty":{display:"none"}}}})(o),(e=>{let{componentCls:t}=e;return{[t]:{"&-gap-small":{gap:e.flexGapSM},"&-gap-middle":{gap:e.flexGap},"&-gap-large":{gap:e.flexGapLG}}}})(o),(e=>{let{componentCls:t}=e,r={};return l.forEach(e=>{r[`${t}-wrap-${e}`]={flexWrap:e}}),r})(o),(e=>{let{componentCls:t}=e,r={};return u.forEach(e=>{r[`${t}-align-${e}`]={alignItems:e}}),r})(o),(e=>{let{componentCls:t}=e,r={};return c.forEach(e=>{r[`${t}-justify-${e}`]={justifyContent:e}}),r})(o)]},()=>({}),{resetStyle:!1});var f=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,a=Object.getOwnPropertySymbols(e);ot.indexOf(a[o])&&Object.prototype.propertyIsEnumerable.call(e,a[o])&&(r[a[o]]=e[a[o]]);return r};let b=t.default.forwardRef((e,i)=>{let{prefixCls:s,rootClassName:l,className:c,style:u,flex:b,gap:p,vertical:g=!1,component:h="div",children:y}=e,v=f(e,["prefixCls","rootClassName","className","style","flex","gap","vertical","component","children"]),{flex:w,direction:O,getPrefixCls:$}=t.default.useContext(n.ConfigContext),x=$("flex",s),[C,E,k]=m(x),S=null!=g?g:null==w?void 0:w.vertical,j=(0,r.default)(c,l,null==w?void 0:w.className,x,E,k,d(x,e),{[`${x}-rtl`]:"rtl"===O,[`${x}-gap-${p}`]:(0,o.isPresetSize)(p),[`${x}-vertical`]:S}),N=Object.assign(Object.assign({},null==w?void 0:w.style),u);return b&&(N.flex=b),p&&!(0,o.isPresetSize)(p)&&(N.gap=p),C(t.default.createElement(h,Object.assign({ref:i,className:j,style:N},(0,a.default)(v,["justify","wrap","align"])),y))});e.s(["Flex",0,b],525720)},785242,e=>{"use strict";var t=e.i(619273),r=e.i(266027),a=e.i(912598),o=e.i(135214),n=e.i(270345),i=e.i(243652),s=e.i(764205);let l=(0,i.createQueryKeys)("teams"),c=async(e,t,r,a={})=>{try{let o=(0,s.getProxyBaseUrl)(),n=new URLSearchParams(Object.entries({team_id:a.teamID,organization_id:a.organizationID,team_alias:a.team_alias,user_id:a.userID,page:t,page_size:r,sort_by:a.sortBy,sort_order:a.sortOrder,status:"deleted"}).filter(([,e])=>null!=e).map(([e,t])=>[e,String(t)])),i=`${o?`${o}/v2/team/list`:"/v2/team/list"}?${n}`,l=await fetch(i,{method:"GET",headers:{[(0,s.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!l.ok){let e=await l.json(),t=(0,s.deriveErrorMessage)(e);throw(0,s.handleError)(t),Error(t)}let c=await l.json();if(console.log("/team/list?status=deleted API Response:",c),c&&"object"==typeof c&&"teams"in c)return c.teams;return c}catch(e){throw console.error("Failed to list deleted teams:",e),e}},u=(0,i.createQueryKeys)("deletedTeams");e.s(["useDeletedTeams",0,(e,a,n={})=>{let{accessToken:i}=(0,o.default)();return(0,r.useQuery)({queryKey:u.list({page:e,limit:a,...n}),queryFn:async()=>await c(i,e,a,n),enabled:!!i,staleTime:3e4,placeholderData:t.keepPreviousData})},"useTeam",0,e=>{let{accessToken:t}=(0,o.default)(),n=(0,a.useQueryClient)();return(0,r.useQuery)({queryKey:l.detail(e),enabled:!!(t&&e),queryFn:async()=>{if(!t||!e)throw Error("Missing auth or teamId");return(0,s.teamInfoCall)(t,e)},initialData:()=>{if(!e)return;let t=n.getQueryData(l.list({}));return t?.find(t=>t.team_id===e)}})},"useTeams",0,()=>{let{accessToken:e,userId:t,userRole:a}=(0,o.default)();return(0,r.useQuery)({queryKey:l.list({}),queryFn:async()=>await (0,n.fetchTeams)(e,t,a,null),enabled:!!e})}])},514236,e=>{"use strict";var t=e.i(843476),r=e.i(105278);e.s(["default",0,()=>(0,t.jsx)(r.default,{})])}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/5841a113d7359c44.js b/litellm/proxy/_experimental/out/_next/static/chunks/5841a113d7359c44.js deleted file mode 100644 index 7af0a9a5d96..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/5841a113d7359c44.js +++ /dev/null @@ -1,7 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,270345,e=>{"use strict";var t=e.i(764205);let r=async(e,r,a,l)=>"Admin"!=a&&"Admin Viewer"!=a?await (0,t.teamListCall)(e,l?.organization_id||null,r):await (0,t.teamListCall)(e,l?.organization_id||null);e.s(["fetchTeams",0,r])},519756,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={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"};var l=e.i(9583),o=r.forwardRef(function(e,o){return r.createElement(l.default,(0,t.default)({},e,{ref:o,icon:a}))});e.s(["UploadOutlined",0,o],519756)},981339,e=>{"use strict";var t=e.i(185793);e.s(["Skeleton",()=>t.default])},500330,e=>{"use strict";var t=e.i(727749);function r(e,t){let r=structuredClone(e);for(let[e,a]of Object.entries(t))e in r&&(r[e]=a);return r}let a=(e,t=0,r=!1,a=!0)=>{if(null==e||!Number.isFinite(e)||0===e&&!a)return"-";let l={minimumFractionDigits:t,maximumFractionDigits:t};if(!r)return e.toLocaleString("en-US",l);let o=e<0?"-":"",s=Math.abs(e),n=s,i="";return s>=1e6?(n=s/1e6,i="M"):s>=1e3&&(n=s/1e3,i="K"),`${o}${n.toLocaleString("en-US",l)}${i}`},l=async(e,r="Copied to clipboard")=>{if(!e)return!1;if(!navigator||!navigator.clipboard||!navigator.clipboard.writeText)return o(e,r);try{return await navigator.clipboard.writeText(e),t.default.success(r),!0}catch(t){return console.error("Clipboard API failed: ",t),o(e,r)}},o=(e,r)=>{try{let a=document.createElement("textarea");a.value=e,a.style.position="fixed",a.style.left="-999999px",a.style.top="-999999px",a.setAttribute("readonly",""),document.body.appendChild(a),a.focus(),a.select();let l=document.execCommand("copy");if(document.body.removeChild(a),l)return t.default.success(r),!0;throw Error("execCommand failed")}catch(e){return t.default.fromBackend("Failed to copy to clipboard"),console.error("Failed to copy: ",e),!1}};e.s(["copyToClipboard",0,l,"formatNumberWithCommas",0,a,"getSpendString",0,(e,t=6)=>{if(null==e||!Number.isFinite(e)||0===e)return"-";let r=a(e,t,!1,!1);if(0===Number(r.replace(/,/g,""))){let e=(1/10**t).toFixed(t);return`< $${e}`}return`$${r}`},"updateExistingKeys",()=>r])},743151,(e,t,r)=>{"use strict";function a(e){return(a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}Object.defineProperty(r,"__esModule",{value:!0}),r.CopyToClipboard=void 0;var l=n(e.r(271645)),o=n(e.r(844343)),s=["text","onCopy","options","children"];function n(e){return e&&e.__esModule?e:{default:e}}function i(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,a)}return r}function c(e){for(var t=1;t=0||(l[r]=e[r]);return l}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(l[r]=e[r])}return l}(e,s),a=l.default.Children.only(t);return l.default.cloneElement(a,c(c({},r),{},{onClick:this.onClick}))}}],function(e,t){for(var r=0;r{"use strict";var a=e.r(743151).CopyToClipboard;a.CopyToClipboard=a,t.exports=a},995926,e=>{"use strict";var t=e.i(841947);e.s(["XIcon",()=>t.default])},91739,e=>{"use strict";var t=e.i(544195);e.s(["Radio",()=>t.default])},988297,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 4v16m8-8H4"}))});e.s(["PlusIcon",0,r],988297)},500727,e=>{"use strict";var t=e.i(266027),r=e.i(243652),a=e.i(764205),l=e.i(135214);let o=(0,r.createQueryKeys)("mcpServers");e.s(["useMCPServers",0,()=>{let{accessToken:e}=(0,l.default)();return(0,t.useQuery)({queryKey:o.list({}),queryFn:async()=>await (0,a.fetchMCPServers)(e),enabled:!!e})}])},797672,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"}))});e.s(["PencilIcon",0,r],797672)},992619,e=>{"use strict";var t=e.i(843476),r=e.i(271645),a=e.i(779241),l=e.i(599724),o=e.i(199133),s=e.i(983561),n=e.i(689020);e.s(["default",0,({accessToken:e,value:i,placeholder:c="Select a Model",onChange:d,disabled:u=!1,style:m,className:g,showLabel:p=!0,labelText:f="Select Model"})=>{let[h,x]=(0,r.useState)(i),[b,v]=(0,r.useState)(!1),[y,w]=(0,r.useState)([]),C=(0,r.useRef)(null);return(0,r.useEffect)(()=>{x(i)},[i]),(0,r.useEffect)(()=>{e&&(async()=>{try{let t=await (0,n.fetchAvailableModels)(e);console.log("Fetched models for selector:",t),t.length>0&&w(t)}catch(e){console.error("Error fetching model info:",e)}})()},[e]),(0,t.jsxs)("div",{children:[p&&(0,t.jsxs)(l.Text,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,t.jsx)(s.RobotOutlined,{className:"mr-2"})," ",f]}),(0,t.jsx)(o.Select,{value:h,placeholder:c,onChange:e=>{"custom"===e?(v(!0),x(void 0)):(v(!1),x(e),d&&d(e))},options:[...Array.from(new Set(y.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%",...m},showSearch:!0,className:`rounded-md ${g||""}`,disabled:u}),b&&(0,t.jsx)(a.TextInput,{className:"mt-2",placeholder:"Enter custom model name",onValueChange:e=>{C.current&&clearTimeout(C.current),C.current=setTimeout(()=>{x(e),d&&d(e)},500)},disabled:u})]})}])},309426,e=>{"use strict";var t=e.i(290571),r=e.i(444755),a=e.i(673706),l=e.i(271645),o=e.i(46757);let s=(0,a.makeClassName)("Col"),n=l.default.forwardRef((e,a)=>{let n,i,c,d,{numColSpan:u=1,numColSpanSm:m,numColSpanMd:g,numColSpanLg:p,children:f,className:h}=e,x=(0,t.__rest)(e,["numColSpan","numColSpanSm","numColSpanMd","numColSpanLg","children","className"]),b=(e,t)=>e&&Object.keys(t).includes(String(e))?t[e]:"";return l.default.createElement("div",Object.assign({ref:a,className:(0,r.tremorTwMerge)(s("root"),(n=b(u,o.colSpan),i=b(m,o.colSpanSm),c=b(g,o.colSpanMd),d=b(p,o.colSpanLg),(0,r.tremorTwMerge)(n,i,c,d)),h)},x),f)});n.displayName="Col",e.s(["Col",()=>n],309426)},793130,e=>{"use strict";var t=e.i(290571),r=e.i(429427),a=e.i(371330),l=e.i(271645),o=e.i(394487),s=e.i(503269),n=e.i(214520),i=e.i(746725),c=e.i(914189),d=e.i(144279),u=e.i(294316),m=e.i(601893),g=e.i(140721),p=e.i(942803),f=e.i(233538),h=e.i(694421),x=e.i(700020),b=e.i(35889),v=e.i(998348),y=e.i(722678);let w=(0,l.createContext)(null);w.displayName="GroupContext";let C=l.Fragment,k=Object.assign((0,x.forwardRefWithAs)(function(e,t){var C;let k=(0,l.useId)(),j=(0,p.useProvidedId)(),N=(0,m.useDisabled)(),{id:S=j||`headlessui-switch-${k}`,disabled:M=N||!1,checked:T,defaultChecked:E,onChange:O,name:P,value:_,form:$,autoFocus:R=!1,...z}=e,B=(0,l.useContext)(w),[L,F]=(0,l.useState)(null),I=(0,l.useRef)(null),D=(0,u.useSyncRefs)(I,t,null===B?null:B.setSwitch,F),A=(0,n.useDefaultValue)(E),[H,V]=(0,s.useControllable)(T,O,null!=A&&A),G=(0,i.useDisposables)(),[X,q]=(0,l.useState)(!1),K=(0,c.useEvent)(()=>{q(!0),null==V||V(!H),G.nextFrame(()=>{q(!1)})}),W=(0,c.useEvent)(e=>{if((0,f.isDisabledReactIssue7711)(e.currentTarget))return e.preventDefault();e.preventDefault(),K()}),Y=(0,c.useEvent)(e=>{e.key===v.Keys.Space?(e.preventDefault(),K()):e.key===v.Keys.Enter&&(0,h.attemptSubmit)(e.currentTarget)}),U=(0,c.useEvent)(e=>e.preventDefault()),Q=(0,y.useLabelledBy)(),J=(0,b.useDescribedBy)(),{isFocusVisible:Z,focusProps:ee}=(0,r.useFocusRing)({autoFocus:R}),{isHovered:et,hoverProps:er}=(0,a.useHover)({isDisabled:M}),{pressed:ea,pressProps:el}=(0,o.useActivePress)({disabled:M}),eo=(0,l.useMemo)(()=>({checked:H,disabled:M,hover:et,focus:Z,active:ea,autofocus:R,changing:X}),[H,et,Z,ea,M,X,R]),es=(0,x.mergeProps)({id:S,ref:D,role:"switch",type:(0,d.useResolveButtonType)(e,L),tabIndex:-1===e.tabIndex?0:null!=(C=e.tabIndex)?C:0,"aria-checked":H,"aria-labelledby":Q,"aria-describedby":J,disabled:M||void 0,autoFocus:R,onClick:W,onKeyUp:Y,onKeyPress:U},ee,er,el),en=(0,l.useCallback)(()=>{if(void 0!==A)return null==V?void 0:V(A)},[V,A]),ei=(0,x.useRender)();return l.default.createElement(l.default.Fragment,null,null!=P&&l.default.createElement(g.FormFields,{disabled:M,data:{[P]:_||"on"},overrides:{type:"checkbox",checked:H},form:$,onReset:en}),ei({ourProps:es,theirProps:z,slot:eo,defaultTag:"button",name:"Switch"}))}),{Group:function(e){var t;let[r,a]=(0,l.useState)(null),[o,s]=(0,y.useLabels)(),[n,i]=(0,b.useDescriptions)(),c=(0,l.useMemo)(()=>({switch:r,setSwitch:a}),[r,a]),d=(0,x.useRender)();return l.default.createElement(i,{name:"Switch.Description",value:n},l.default.createElement(s,{name:"Switch.Label",value:o,props:{htmlFor:null==(t=c.switch)?void 0:t.id,onClick(e){r&&(e.currentTarget instanceof HTMLLabelElement&&e.preventDefault(),r.click(),r.focus({preventScroll:!0}))}}},l.default.createElement(w.Provider,{value:c},d({ourProps:{},theirProps:e,slot:{},defaultTag:C,name:"Switch.Group"}))))},Label:y.Label,Description:b.Description});var j=e.i(888288),N=e.i(95779),S=e.i(444755),M=e.i(673706),T=e.i(829087);let E=(0,M.makeClassName)("Switch"),O=l.default.forwardRef((e,r)=>{let{checked:a,defaultChecked:o=!1,onChange:s,color:n,name:i,error:c,errorMessage:d,disabled:u,required:m,tooltip:g,id:p}=e,f=(0,t.__rest)(e,["checked","defaultChecked","onChange","color","name","error","errorMessage","disabled","required","tooltip","id"]),h={bgColor:n?(0,M.getColorClassNames)(n,N.colorPalette.background).bgColor:"bg-tremor-brand dark:bg-dark-tremor-brand",ringColor:n?(0,M.getColorClassNames)(n,N.colorPalette.ring).ringColor:"ring-tremor-brand-muted dark:ring-dark-tremor-brand-muted"},[x,b]=(0,j.default)(o,a),[v,y]=(0,l.useState)(!1),{tooltipProps:w,getReferenceProps:C}=(0,T.useTooltip)(300);return l.default.createElement("div",{className:"flex flex-row items-center justify-start"},l.default.createElement(T.default,Object.assign({text:g},w)),l.default.createElement("div",Object.assign({ref:(0,M.mergeRefs)([r,w.refs.setReference]),className:(0,S.tremorTwMerge)(E("root"),"flex flex-row relative h-5")},f,C),l.default.createElement("input",{type:"checkbox",className:(0,S.tremorTwMerge)(E("input"),"absolute w-5 h-5 cursor-pointer left-0 top-0 opacity-0"),name:i,required:m,checked:x,onChange:e=>{e.preventDefault()}}),l.default.createElement(k,{checked:x,onChange:e=>{b(e),null==s||s(e)},disabled:u,className:(0,S.tremorTwMerge)(E("switch"),"w-10 h-5 group relative inline-flex shrink-0 cursor-pointer items-center justify-center rounded-tremor-full","focus:outline-none",u?"cursor-not-allowed":""),onFocus:()=>y(!0),onBlur:()=>y(!1),id:p},l.default.createElement("span",{className:(0,S.tremorTwMerge)(E("sr-only"),"sr-only")},"Switch ",x?"on":"off"),l.default.createElement("span",{"aria-hidden":"true",className:(0,S.tremorTwMerge)(E("background"),x?h.bgColor:"bg-tremor-border dark:bg-dark-tremor-border","pointer-events-none absolute mx-auto h-3 w-9 rounded-tremor-full transition-colors duration-100 ease-in-out")}),l.default.createElement("span",{"aria-hidden":"true",className:(0,S.tremorTwMerge)(E("round"),x?(0,S.tremorTwMerge)(h.bgColor,"translate-x-5 border-tremor-background dark:border-dark-tremor-background"):"translate-x-0 bg-tremor-border dark:bg-dark-tremor-border border-tremor-background dark:border-dark-tremor-background","pointer-events-none absolute left-0 inline-block h-5 w-5 transform rounded-tremor-full border-2 shadow-tremor-input duration-100 ease-in-out transition",v?(0,S.tremorTwMerge)("ring-2",h.ringColor):"")}))),c&&d?l.default.createElement("p",{className:(0,S.tremorTwMerge)(E("errorMessage"),"text-sm text-red-500 mt-1 ")},d):null)});O.displayName="Switch",e.s(["Switch",()=>O],793130)},361653,e=>{"use strict";let t=(0,e.i(475254).default)("circle-alert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);e.s(["default",()=>t])},603908,e=>{"use strict";let t=(0,e.i(475254).default)("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);e.s(["default",()=>t])},841947,e=>{"use strict";let t=(0,e.i(475254).default)("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);e.s(["default",()=>t])},107233,37727,e=>{"use strict";var t=e.i(603908);e.s(["Plus",()=>t.default],107233);var r=e.i(841947);e.s(["X",()=>r.default],37727)},158392,419470,e=>{"use strict";var t=e.i(843476),r=e.i(779241);let a={ttl:3600,lowest_latency_buffer:0},l=({routingStrategyArgs:e})=>{let 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,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"max-w-3xl",children:[(0,t.jsx)("h3",{className:"text-sm font-medium text-gray-900",children:"Latency-Based Configuration"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Fine-tune latency-based routing behavior"})]}),(0,t.jsx)("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2 xl:grid-cols-3",children:Object.entries(e||a).map(([e,a])=>(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsxs)("label",{className:"block",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:e.replace(/_/g," ")}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-2",children:l[e]||""}),(0,t.jsx)(r.TextInput,{name:e,defaultValue:"object"==typeof a?JSON.stringify(a,null,2):a?.toString(),className:"font-mono text-sm w-full"})]})},e))})]}),(0,t.jsx)("div",{className:"border-t border-gray-200"})]})},o=({routerSettings:e,routerFieldsMetadata:a})=>(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"max-w-3xl",children:[(0,t.jsx)("h3",{className:"text-sm font-medium text-gray-900",children:"Reliability & Retries"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Configure retry logic and failure handling"})]}),(0,t.jsx)("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2 xl:grid-cols-3",children:Object.entries(e).filter(([e,t])=>"fallbacks"!=e&&"context_window_fallbacks"!=e&&"routing_strategy_args"!=e&&"routing_strategy"!=e&&"enable_tag_filtering"!=e).map(([e,l])=>(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsxs)("label",{className:"block",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:a[e]?.ui_field_name||e}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-2",children:a[e]?.field_description||""}),(0,t.jsx)(r.TextInput,{name:e,defaultValue:null==l||"null"===l?"":"object"==typeof l?JSON.stringify(l,null,2):l?.toString()||"",placeholder:"—",className:"font-mono text-sm w-full"})]})},e))})]});var s=e.i(199133);let n=({selectedStrategy:e,availableStrategies:r,routingStrategyDescriptions:a,routerFieldsMetadata:l,onStrategyChange:o})=>(0,t.jsxs)("div",{className:"space-y-2 max-w-3xl",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:l.routing_strategy?.ui_field_name||"Routing Strategy"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-0.5 mb-2",children:l.routing_strategy?.field_description||""})]}),(0,t.jsx)("div",{className:"routing-strategy-select max-w-3xl",children:(0,t.jsx)(s.Select,{value:e,onChange:o,style:{width:"100%"},size:"large",children:r.map(e=>(0,t.jsx)(s.Select.Option,{value:e,label:e,children:(0,t.jsxs)("div",{className:"flex flex-col gap-0.5 py-1",children:[(0,t.jsx)("span",{className:"font-mono text-sm font-medium",children:e}),a[e]&&(0,t.jsx)("span",{className:"text-xs text-gray-500 font-normal",children:a[e]})]})},e))})})]});var i=e.i(793130);let c=({enabled:e,routerFieldsMetadata:r,onToggle:a})=>(0,t.jsx)("div",{className:"space-y-3 max-w-3xl",children:(0,t.jsxs)("div",{className:"flex items-start justify-between",children:[(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsx)("label",{className:"text-xs font-medium text-gray-700 uppercase tracking-wide",children:r.enable_tag_filtering?.ui_field_name||"Enable Tag Filtering"}),(0,t.jsxs)("p",{className:"text-xs text-gray-500 mt-0.5",children:[r.enable_tag_filtering?.field_description||"",r.enable_tag_filtering?.link&&(0,t.jsxs)(t.Fragment,{children:[" ",(0,t.jsx)("a",{href:r.enable_tag_filtering.link,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"Learn more"})]})]})]}),(0,t.jsx)(i.Switch,{checked:e,onChange:a,className:"ml-4"})]})});e.s(["default",0,({value:e,onChange:r,routerFieldsMetadata:a,availableRoutingStrategies:s,routingStrategyDescriptions:i})=>(0,t.jsxs)("div",{className:"w-full space-y-8 py-2",children:[(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"max-w-3xl",children:[(0,t.jsx)("h3",{className:"text-sm font-medium text-gray-900",children:"Routing Settings"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Configure how requests are routed to deployments"})]}),s.length>0&&(0,t.jsx)(n,{selectedStrategy:e.selectedStrategy||e.routerSettings.routing_strategy||null,availableStrategies:s,routingStrategyDescriptions:i,routerFieldsMetadata:a,onStrategyChange:t=>{r({...e,selectedStrategy:t})}}),(0,t.jsx)(c,{enabled:e.enableTagFiltering,routerFieldsMetadata:a,onToggle:t=>{r({...e,enableTagFiltering:t})}})]}),(0,t.jsx)("div",{className:"border-t border-gray-200"}),"latency-based-routing"===e.selectedStrategy&&(0,t.jsx)(l,{routingStrategyArgs:e.routerSettings.routing_strategy_args}),(0,t.jsx)(o,{routerSettings:e.routerSettings,routerFieldsMetadata:a})]})],158392);var d=e.i(994388),u=e.i(998573),m=e.i(653496),g=e.i(107233),p=e.i(271645),f=e.i(592968),h=e.i(361653),h=h;let x=(0,e.i(475254).default)("arrow-down",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);var b=e.i(37727);function v({group:e,onChange:r,availableModels:a,maxFallbacks:l}){let o=a.filter(t=>t!==e.primaryModel),n=e.fallbackModels.length{let a=[...e.fallbackModels];a.includes(t)&&(a=a.filter(e=>e!==t)),r({...e,primaryModel:t,fallbackModels:a})},showSearch:!0,filterOption:(e,t)=>(t?.label??"").toLowerCase().includes(e.toLowerCase()),options:a.map(e=>({label:e,value:e}))}),!e.primaryModel&&(0,t.jsxs)("div",{className:"mt-2 flex items-center gap-2 text-amber-600 text-xs bg-amber-50 p-2 rounded",children:[(0,t.jsx)(h.default,{className:"w-4 h-4"}),(0,t.jsx)("span",{children:"Select a model to begin configuring fallbacks"})]})]}),(0,t.jsx)("div",{className:"flex items-center justify-center -my-4 z-10",children:(0,t.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,t.jsx)(x,{className:"w-4 h-4"}),"IF FAILS, TRY..."]})}),(0,t.jsxs)("div",{className:`transition-opacity duration-300 ${!e.primaryModel?"opacity-50 pointer-events-none":"opacity-100"}`,children:[(0,t.jsxs)("label",{className:"block text-sm font-semibold text-gray-700 mb-2",children:["Fallback Chain ",(0,t.jsx)("span",{className:"text-red-500",children:"*"}),(0,t.jsxs)("span",{className:"text-xs text-gray-500 font-normal ml-2",children:["(Max ",l," fallbacks at a time)"]})]}),(0,t.jsxs)("div",{className:"bg-gray-50 rounded-xl p-4 border border-gray-200",children:[(0,t.jsxs)("div",{className:"mb-4",children:[(0,t.jsx)(s.Select,{mode:"multiple",className:"w-full",size:"large",placeholder:n?"Select fallback models to add...":`Maximum ${l} fallbacks reached`,value:e.fallbackModels,onChange:t=>{let a=t.slice(0,l);r({...e,fallbackModels:a})},disabled:!e.primaryModel,options:o.map(e=>({label:e,value:e})),optionRender:(r,a)=>{let l=e.fallbackModels.includes(r.value),o=l?e.fallbackModels.indexOf(r.value)+1:null;return(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[l&&null!==o&&(0,t.jsx)("span",{className:"flex items-center justify-center w-5 h-5 rounded bg-indigo-100 text-indigo-600 text-xs font-bold",children:o}),(0,t.jsx)("span",{children:r.label})]})},maxTagCount:"responsive",maxTagPlaceholder:e=>(0,t.jsx)(f.Tooltip,{styles:{root:{pointerEvents:"none"}},title:e.map(({value:e})=>e).join(", "),children:(0,t.jsxs)("span",{children:["+",e.length," more"]})}),showSearch:!0,filterOption:(e,t)=>(t?.label??"").toLowerCase().includes(e.toLowerCase())}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1 ml-1",children:n?`Search and select multiple models. Selected models will appear below in order. (${e.fallbackModels.length}/${l} used)`:`Maximum ${l} fallbacks reached. Remove some to add more.`})]}),(0,t.jsx)("div",{className:"space-y-2 min-h-[100px]",children:0===e.fallbackModels.length?(0,t.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,t.jsx)("span",{className:"text-sm",children:"No fallback models selected"}),(0,t.jsx)("span",{className:"text-xs mt-1",children:"Add models from the dropdown above"})]}):e.fallbackModels.map((a,l)=>(0,t.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,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.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,t.jsx)("span",{className:"text-xs font-bold",children:l+1})}),(0,t.jsx)("div",{children:(0,t.jsx)("span",{className:"font-medium text-gray-800",children:a})})]}),(0,t.jsx)("button",{type:"button",onClick:()=>{let t;return t=e.fallbackModels.filter((e,t)=>t!==l),void r({...e,fallbackModels:t})},className:"opacity-0 group-hover:opacity-100 transition-opacity text-gray-400 hover:text-red-500 p-1",children:(0,t.jsx)(b.X,{className:"w-4 h-4"})})]},`${a}-${l}`))})]})]})]})}function y({groups:e,onGroupsChange:r,availableModels:a,maxFallbacks:l=10,maxGroups:o=5}){let[s,n]=(0,p.useState)(e.length>0?e[0].id:"1");(0,p.useEffect)(()=>{e.length>0?e.some(e=>e.id===s)||n(e[0].id):n("1")},[e]);let i=()=>{if(e.length>=o)return;let t=Date.now().toString();r([...e,{id:t,primaryModel:null,fallbackModels:[]}]),n(t)},c=t=>{r(e.map(e=>e.id===t.id?t:e))},f=e.map((r,o)=>{let s=r.primaryModel?r.primaryModel:`Group ${o+1}`;return{key:r.id,label:s,closable:e.length>1,children:(0,t.jsx)(v,{group:r,onChange:c,availableModels:a,maxFallbacks:l})}});return 0===e.length?(0,t.jsxs)("div",{className:"text-center py-12 bg-gray-50 rounded-lg border border-dashed border-gray-300",children:[(0,t.jsx)("p",{className:"text-gray-500 mb-4",children:"No fallback groups configured"}),(0,t.jsx)(d.Button,{variant:"primary",onClick:i,icon:()=>(0,t.jsx)(g.Plus,{className:"w-4 h-4"}),children:"Create First Group"})]}):(0,t.jsx)(m.Tabs,{type:"editable-card",activeKey:s,onChange:n,onEdit:(t,a)=>{"add"===a?i():"remove"===a&&e.length>1&&(t=>{if(1===e.length)return u.message.warning("At least one group is required");let a=e.filter(e=>e.id!==t);r(a),s===t&&a.length>0&&n(a[a.length-1].id)})(t)},items:f,className:"fallback-tabs",tabBarStyle:{marginBottom:0},hideAdd:e.length>=o})}e.s(["FallbackSelectionForm",()=>y],419470)},653496,e=>{"use strict";var t=e.i(721369);e.s(["Tabs",()=>t.default])},599724,936325,e=>{"use strict";var t=e.i(95779),r=e.i(444755),a=e.i(673706),l=e.i(271645);let o=l.default.forwardRef((e,o)=>{let{color:s,className:n,children:i}=e;return l.default.createElement("p",{ref:o,className:(0,r.tremorTwMerge)("text-tremor-default",s?(0,a.getColorClassNames)(s,t.colorPalette.text).textColor:(0,r.tremorTwMerge)("text-tremor-content","dark:text-dark-tremor-content"),n)},i)});o.displayName="Text",e.s(["default",()=>o],936325),e.s(["Text",()=>o],599724)},994388,e=>{"use strict";var t=e.i(290571),r=e.i(829087),a=e.i(271645);let l=["preEnter","entering","entered","preExit","exiting","exited","unmounted"],o=e=>({_s:e,status:l[e],isEnter:e<3,isMounted:6!==e,isResolved:2===e||e>4}),s=e=>e?6:5,n=(e,t,r,a,l)=>{clearTimeout(a.current);let s=o(e);t(s),r.current=s,l&&l({current:s})};var i=e.i(480731),c=e.i(444755),d=e.i(673706);let u=e=>{var r=(0,t.__rest)(e,[]);return a.default.createElement("svg",Object.assign({},r,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"}),a.default.createElement("path",{fill:"none",d:"M0 0h24v24H0z"}),a.default.createElement("path",{d:"M18.364 5.636L16.95 7.05A7 7 0 1 0 19 12h2a9 9 0 1 1-2.636-6.364z"}))};var m=e.i(95779);let g={xs:{height:"h-4",width:"w-4"},sm:{height:"h-5",width:"w-5"},md:{height:"h-5",width:"w-5"},lg:{height:"h-6",width:"w-6"},xl:{height:"h-6",width:"w-6"}},p=(e,t)=>{switch(e){case"primary":return{textColor:t?(0,d.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",hoverTextColor:t?(0,d.getColorClassNames)("white").textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",bgColor:t?(0,d.getColorClassNames)(t,m.colorPalette.background).bgColor:"bg-tremor-brand dark:bg-dark-tremor-brand",hoverBgColor:t?(0,d.getColorClassNames)(t,m.colorPalette.darkBackground).hoverBgColor:"hover:bg-tremor-brand-emphasis dark:hover:bg-dark-tremor-brand-emphasis",borderColor:t?(0,d.getColorClassNames)(t,m.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",hoverBorderColor:t?(0,d.getColorClassNames)(t,m.colorPalette.darkBorder).hoverBorderColor:"hover:border-tremor-brand-emphasis dark:hover:border-dark-tremor-brand-emphasis"};case"secondary":return{textColor:t?(0,d.getColorClassNames)(t,m.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,d.getColorClassNames)(t,m.colorPalette.text).textColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,d.getColorClassNames)("transparent").bgColor,hoverBgColor:t?(0,c.tremorTwMerge)((0,d.getColorClassNames)(t,m.colorPalette.background).hoverBgColor,"hover:bg-opacity-20 dark:hover:bg-opacity-20"):"hover:bg-tremor-brand-faint dark:hover:bg-dark-tremor-brand-faint",borderColor:t?(0,d.getColorClassNames)(t,m.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand"};case"light":return{textColor:t?(0,d.getColorClassNames)(t,m.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",hoverTextColor:t?(0,d.getColorClassNames)(t,m.colorPalette.darkText).hoverTextColor:"hover:text-tremor-brand-emphasis dark:hover:text-dark-tremor-brand-emphasis",bgColor:(0,d.getColorClassNames)("transparent").bgColor,borderColor:"",hoverBorderColor:""}}},f=(0,d.makeClassName)("Button"),h=({loading:e,iconSize:t,iconPosition:r,Icon:l,needMargin:o,transitionStatus:s})=>{let n=o?r===i.HorizontalPositions.Left?(0,c.tremorTwMerge)("-ml-1","mr-1.5"):(0,c.tremorTwMerge)("-mr-1","ml-1.5"):"",d=(0,c.tremorTwMerge)("w-0 h-0"),m={default:d,entering:d,entered:t,exiting:t,exited:d};return e?a.default.createElement(u,{className:(0,c.tremorTwMerge)(f("icon"),"animate-spin shrink-0",n,m.default,m[s]),style:{transition:"width 150ms"}}):a.default.createElement(l,{className:(0,c.tremorTwMerge)(f("icon"),"shrink-0",t,n)})},x=a.default.forwardRef((e,l)=>{let{icon:u,iconPosition:m=i.HorizontalPositions.Left,size:x=i.Sizes.SM,color:b,variant:v="primary",disabled:y,loading:w=!1,loadingText:C,children:k,tooltip:j,className:N}=e,S=(0,t.__rest)(e,["icon","iconPosition","size","color","variant","disabled","loading","loadingText","children","tooltip","className"]),M=w||y,T=void 0!==u||w,E=w&&C,O=!(!k&&!E),P=(0,c.tremorTwMerge)(g[x].height,g[x].width),_="light"!==v?(0,c.tremorTwMerge)("rounded-tremor-default border","shadow-tremor-input","dark:shadow-dark-tremor-input"):"",$=p(v,b),R=("light"!==v?{xs:{paddingX:"px-2.5",paddingY:"py-1.5",fontSize:"text-xs"},sm:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-sm"},md:{paddingX:"px-4",paddingY:"py-2",fontSize:"text-md"},lg:{paddingX:"px-4",paddingY:"py-2.5",fontSize:"text-lg"},xl:{paddingX:"px-4",paddingY:"py-3",fontSize:"text-xl"}}:{xs:{paddingX:"",paddingY:"",fontSize:"text-xs"},sm:{paddingX:"",paddingY:"",fontSize:"text-sm"},md:{paddingX:"",paddingY:"",fontSize:"text-md"},lg:{paddingX:"",paddingY:"",fontSize:"text-lg"},xl:{paddingX:"",paddingY:"",fontSize:"text-xl"}})[x],{tooltipProps:z,getReferenceProps:B}=(0,r.useTooltip)(300),[L,F]=(({enter:e=!0,exit:t=!0,preEnter:r,preExit:l,timeout:i,initialEntered:c,mountOnEnter:d,unmountOnExit:u,onStateChange:m}={})=>{let[g,p]=(0,a.useState)(()=>o(c?2:s(d))),f=(0,a.useRef)(g),h=(0,a.useRef)(0),[x,b]="object"==typeof i?[i.enter,i.exit]:[i,i],v=(0,a.useCallback)(()=>{let e=((e,t)=>{switch(e){case 1:case 0:return 2;case 4:case 3:return s(t)}})(f.current._s,u);e&&n(e,p,f,h,m)},[m,u]);return[g,(0,a.useCallback)(a=>{let o=e=>{switch(n(e,p,f,h,m),e){case 1:x>=0&&(h.current=((...e)=>setTimeout(...e))(v,x));break;case 4:b>=0&&(h.current=((...e)=>setTimeout(...e))(v,b));break;case 0:case 3:h.current=((...e)=>setTimeout(...e))(()=>{isNaN(document.body.offsetTop)||o(e+1)},0)}},i=f.current.isEnter;"boolean"!=typeof a&&(a=!i),a?i||o(e?+!r:2):i&&o(t?l?3:4:s(u))},[v,m,e,t,r,l,x,b,u]),v]})({timeout:50});return(0,a.useEffect)(()=>{F(w)},[w]),a.default.createElement("button",Object.assign({ref:(0,d.mergeRefs)([l,z.refs.setReference]),className:(0,c.tremorTwMerge)(f("root"),"shrink-0 inline-flex justify-center items-center group font-medium outline-none",_,R.paddingX,R.paddingY,R.fontSize,$.textColor,$.bgColor,$.borderColor,$.hoverBorderColor,M?"opacity-50 cursor-not-allowed":(0,c.tremorTwMerge)(p(v,b).hoverTextColor,p(v,b).hoverBgColor,p(v,b).hoverBorderColor),N),disabled:M},B,S),a.default.createElement(r.default,Object.assign({text:j},z)),T&&m!==i.HorizontalPositions.Right?a.default.createElement(h,{loading:w,iconSize:P,iconPosition:m,Icon:u,transitionStatus:L.status,needMargin:O}):null,E||k?a.default.createElement("span",{className:(0,c.tremorTwMerge)(f("text"),"text-tremor-default whitespace-nowrap")},E?C:k):null,T&&m===i.HorizontalPositions.Right?a.default.createElement(h,{loading:w,iconSize:P,iconPosition:m,Icon:u,transitionStatus:L.status,needMargin:O}):null)});x.displayName="Button",e.s(["Button",()=>x],994388)},304967,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(480731),l=e.i(95779),o=e.i(444755),s=e.i(673706);let n=(0,s.makeClassName)("Card"),i=r.default.forwardRef((e,i)=>{let{decoration:c="",decorationColor:d,children:u,className:m}=e,g=(0,t.__rest)(e,["decoration","decorationColor","children","className"]);return r.default.createElement("div",Object.assign({ref:i,className:(0,o.tremorTwMerge)(n("root"),"relative w-full text-left ring-1 rounded-tremor-default p-6","bg-tremor-background ring-tremor-ring shadow-tremor-card","dark:bg-dark-tremor-background dark:ring-dark-tremor-ring dark:shadow-dark-tremor-card",d?(0,s.getColorClassNames)(d,l.colorPalette.border).borderColor:"border-tremor-brand dark:border-dark-tremor-brand",(e=>{if(!e)return"";switch(e){case a.HorizontalPositions.Left:return"border-l-4";case a.VerticalPositions.Top:return"border-t-4";case a.HorizontalPositions.Right:return"border-r-4";case a.VerticalPositions.Bottom:return"border-b-4";default:return""}})(c),m)},g),u)});i.displayName="Card",e.s(["Card",()=>i],304967)},629569,e=>{"use strict";var t=e.i(290571),r=e.i(95779),a=e.i(444755),l=e.i(673706),o=e.i(271645);let s=o.default.forwardRef((e,s)=>{let{color:n,children:i,className:c}=e,d=(0,t.__rest)(e,["color","children","className"]);return o.default.createElement("p",Object.assign({ref:s,className:(0,a.tremorTwMerge)("font-medium text-tremor-title",n?(0,l.getColorClassNames)(n,r.colorPalette.darkText).textColor:"text-tremor-content-strong dark:text-dark-tremor-content-strong",c)},d),i)});s.displayName="Title",e.s(["Title",()=>s],629569)},91874,e=>{"use strict";var t=e.i(931067),r=e.i(209428),a=e.i(211577),l=e.i(392221),o=e.i(703923),s=e.i(343794),n=e.i(914949),i=e.i(271645),c=["prefixCls","className","style","checked","disabled","defaultChecked","type","title","onChange"],d=(0,i.forwardRef)(function(e,d){var u=e.prefixCls,m=void 0===u?"rc-checkbox":u,g=e.className,p=e.style,f=e.checked,h=e.disabled,x=e.defaultChecked,b=e.type,v=void 0===b?"checkbox":b,y=e.title,w=e.onChange,C=(0,o.default)(e,c),k=(0,i.useRef)(null),j=(0,i.useRef)(null),N=(0,n.default)(void 0!==x&&x,{value:f}),S=(0,l.default)(N,2),M=S[0],T=S[1];(0,i.useImperativeHandle)(d,function(){return{focus:function(e){var t;null==(t=k.current)||t.focus(e)},blur:function(){var e;null==(e=k.current)||e.blur()},input:k.current,nativeElement:j.current}});var E=(0,s.default)(m,g,(0,a.default)((0,a.default)({},"".concat(m,"-checked"),M),"".concat(m,"-disabled"),h));return i.createElement("span",{className:E,title:y,style:p,ref:j},i.createElement("input",(0,t.default)({},C,{className:"".concat(m,"-input"),ref:k,onChange:function(t){h||("checked"in e||T(t.target.checked),null==w||w({target:(0,r.default)((0,r.default)({},e),{},{type:v,checked:t.target.checked}),stopPropagation:function(){t.stopPropagation()},preventDefault:function(){t.preventDefault()},nativeEvent:t.nativeEvent}))},disabled:h,checked:!!M,type:v})),i.createElement("span",{className:"".concat(m,"-inner")}))});e.s(["default",0,d])},421512,236836,e=>{"use strict";let t=e.i(271645).default.createContext(null);e.s(["default",0,t],421512),e.i(296059);var r=e.i(915654),a=e.i(183293),l=e.i(246422),o=e.i(838378);function s(e,t){return(e=>{let{checkboxCls:t}=e,l=`${t}-wrapper`;return[{[`${t}-group`]:Object.assign(Object.assign({},(0,a.resetComponent)(e)),{display:"inline-flex",flexWrap:"wrap",columnGap:e.marginXS,[`> ${e.antCls}-row`]:{flex:1}}),[l]:Object.assign(Object.assign({},(0,a.resetComponent)(e)),{display:"inline-flex",alignItems:"baseline",cursor:"pointer","&:after":{display:"inline-block",width:0,overflow:"hidden",content:"'\\a0'"},[`& + ${l}`]:{marginInlineStart:0},[`&${l}-in-form-item`]:{'input[type="checkbox"]':{width:14,height:14}}}),[t]:Object.assign(Object.assign({},(0,a.resetComponent)(e)),{position:"relative",whiteSpace:"nowrap",lineHeight:1,cursor:"pointer",borderRadius:e.borderRadiusSM,alignSelf:"center",[`${t}-input`]:{position:"absolute",inset:0,zIndex:1,cursor:"pointer",opacity:0,margin:0,[`&:focus-visible + ${t}-inner`]:(0,a.genFocusOutline)(e)},[`${t}-inner`]:{boxSizing:"border-box",display:"block",width:e.checkboxSize,height:e.checkboxSize,direction:"ltr",backgroundColor:e.colorBgContainer,border:`${(0,r.unit)(e.lineWidth)} ${e.lineType} ${e.colorBorder}`,borderRadius:e.borderRadiusSM,borderCollapse:"separate",transition:`all ${e.motionDurationSlow}`,"&:after":{boxSizing:"border-box",position:"absolute",top:"50%",insetInlineStart:"25%",display:"table",width:e.calc(e.checkboxSize).div(14).mul(5).equal(),height:e.calc(e.checkboxSize).div(14).mul(8).equal(),border:`${(0,r.unit)(e.lineWidthBold)} solid ${e.colorWhite}`,borderTop:0,borderInlineStart:0,transform:"rotate(45deg) scale(0) translate(-50%,-50%)",opacity:0,content:'""',transition:`all ${e.motionDurationFast} ${e.motionEaseInBack}, opacity ${e.motionDurationFast}`}},"& + span":{paddingInlineStart:e.paddingXS,paddingInlineEnd:e.paddingXS}})},{[` - ${l}:not(${l}-disabled), - ${t}:not(${t}-disabled) - `]:{[`&:hover ${t}-inner`]:{borderColor:e.colorPrimary}},[`${l}:not(${l}-disabled)`]:{[`&:hover ${t}-checked:not(${t}-disabled) ${t}-inner`]:{backgroundColor:e.colorPrimaryHover,borderColor:"transparent"},[`&:hover ${t}-checked:not(${t}-disabled):after`]:{borderColor:e.colorPrimaryHover}}},{[`${t}-checked`]:{[`${t}-inner`]:{backgroundColor:e.colorPrimary,borderColor:e.colorPrimary,"&:after":{opacity:1,transform:"rotate(45deg) scale(1) translate(-50%,-50%)",transition:`all ${e.motionDurationMid} ${e.motionEaseOutBack} ${e.motionDurationFast}`}}},[` - ${l}-checked:not(${l}-disabled), - ${t}-checked:not(${t}-disabled) - `]:{[`&:hover ${t}-inner`]:{backgroundColor:e.colorPrimaryHover,borderColor:"transparent"}}},{[t]:{"&-indeterminate":{"&":{[`${t}-inner`]:{backgroundColor:`${e.colorBgContainer}`,borderColor:`${e.colorBorder}`,"&:after":{top:"50%",insetInlineStart:"50%",width:e.calc(e.fontSizeLG).div(2).equal(),height:e.calc(e.fontSizeLG).div(2).equal(),backgroundColor:e.colorPrimary,border:0,transform:"translate(-50%, -50%) scale(1)",opacity:1,content:'""'}},[`&:hover ${t}-inner`]:{backgroundColor:`${e.colorBgContainer}`,borderColor:`${e.colorPrimary}`}}}}},{[`${l}-disabled`]:{cursor:"not-allowed"},[`${t}-disabled`]:{[`&, ${t}-input`]:{cursor:"not-allowed",pointerEvents:"none"},[`${t}-inner`]:{background:e.colorBgContainerDisabled,borderColor:e.colorBorder,"&:after":{borderColor:e.colorTextDisabled}},"&:after":{display:"none"},"& + span":{color:e.colorTextDisabled},[`&${t}-indeterminate ${t}-inner::after`]:{background:e.colorTextDisabled}}}]})((0,o.mergeToken)(t,{checkboxCls:`.${e}`,checkboxSize:t.controlInteractiveSize}))}let n=(0,l.genStyleHooks)("Checkbox",(e,{prefixCls:t})=>[s(t,e)]);e.s(["default",0,n,"getStyle",()=>s],236836)},681216,e=>{"use strict";var t=e.i(271645),r=e.i(963188);function a(e){let a=t.default.useRef(null),l=()=>{r.default.cancel(a.current),a.current=null};return[()=>{l(),a.current=(0,r.default)(()=>{a.current=null})},t=>{a.current&&(t.stopPropagation(),l()),null==e||e(t)}]}e.s(["default",()=>a])},374276,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),a=e.i(91874),l=e.i(611935),o=e.i(121872),s=e.i(26905),n=e.i(242064),i=e.i(937328),c=e.i(321883),d=e.i(62139),u=e.i(421512),m=e.i(236836),g=e.i(681216),p=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var l=0,a=Object.getOwnPropertySymbols(e);lt.indexOf(a[l])&&Object.prototype.propertyIsEnumerable.call(e,a[l])&&(r[a[l]]=e[a[l]]);return r};let f=t.forwardRef((e,f)=>{var h;let{prefixCls:x,className:b,rootClassName:v,children:y,indeterminate:w=!1,style:C,onMouseEnter:k,onMouseLeave:j,skipGroup:N=!1,disabled:S}=e,M=p(e,["prefixCls","className","rootClassName","children","indeterminate","style","onMouseEnter","onMouseLeave","skipGroup","disabled"]),{getPrefixCls:T,direction:E,checkbox:O}=t.useContext(n.ConfigContext),P=t.useContext(u.default),{isFormItemInput:_}=t.useContext(d.FormItemInputContext),$=t.useContext(i.default),R=null!=(h=(null==P?void 0:P.disabled)||S)?h:$,z=t.useRef(M.value),B=t.useRef(null),L=(0,l.composeRef)(f,B);t.useEffect(()=>{null==P||P.registerValue(M.value)},[]),t.useEffect(()=>{if(!N)return M.value!==z.current&&(null==P||P.cancelValue(z.current),null==P||P.registerValue(M.value),z.current=M.value),()=>null==P?void 0:P.cancelValue(M.value)},[M.value]),t.useEffect(()=>{var e;(null==(e=B.current)?void 0:e.input)&&(B.current.input.indeterminate=w)},[w]);let F=T("checkbox",x),I=(0,c.default)(F),[D,A,H]=(0,m.default)(F,I),V=Object.assign({},M);P&&!N&&(V.onChange=(...e)=>{M.onChange&&M.onChange.apply(M,e),P.toggleOption&&P.toggleOption({label:y,value:M.value})},V.name=P.name,V.checked=P.value.includes(M.value));let G=(0,r.default)(`${F}-wrapper`,{[`${F}-rtl`]:"rtl"===E,[`${F}-wrapper-checked`]:V.checked,[`${F}-wrapper-disabled`]:R,[`${F}-wrapper-in-form-item`]:_},null==O?void 0:O.className,b,v,H,I,A),X=(0,r.default)({[`${F}-indeterminate`]:w},s.TARGET_CLS,A),[q,K]=(0,g.default)(V.onClick);return D(t.createElement(o.default,{component:"Checkbox",disabled:R},t.createElement("label",{className:G,style:Object.assign(Object.assign({},null==O?void 0:O.style),C),onMouseEnter:k,onMouseLeave:j,onClick:q},t.createElement(a.default,Object.assign({},V,{onClick:K,prefixCls:F,className:X,disabled:R,ref:L})),null!=y&&t.createElement("span",{className:`${F}-label`},y))))});var h=e.i(8211),x=e.i(529681),b=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var l=0,a=Object.getOwnPropertySymbols(e);lt.indexOf(a[l])&&Object.prototype.propertyIsEnumerable.call(e,a[l])&&(r[a[l]]=e[a[l]]);return r};let v=t.forwardRef((e,a)=>{let{defaultValue:l,children:o,options:s=[],prefixCls:i,className:d,rootClassName:g,style:p,onChange:v}=e,y=b(e,["defaultValue","children","options","prefixCls","className","rootClassName","style","onChange"]),{getPrefixCls:w,direction:C}=t.useContext(n.ConfigContext),[k,j]=t.useState(y.value||l||[]),[N,S]=t.useState([]);t.useEffect(()=>{"value"in y&&j(y.value||[])},[y.value]);let M=t.useMemo(()=>s.map(e=>"string"==typeof e||"number"==typeof e?{label:e,value:e}:e),[s]),T=e=>{S(t=>t.filter(t=>t!==e))},E=e=>{S(t=>[].concat((0,h.default)(t),[e]))},O=e=>{let t=k.indexOf(e.value),r=(0,h.default)(k);-1===t?r.push(e.value):r.splice(t,1),"value"in y||j(r),null==v||v(r.filter(e=>N.includes(e)).sort((e,t)=>M.findIndex(t=>t.value===e)-M.findIndex(e=>e.value===t)))},P=w("checkbox",i),_=`${P}-group`,$=(0,c.default)(P),[R,z,B]=(0,m.default)(P,$),L=(0,x.default)(y,["value","disabled"]),F=s.length?M.map(e=>t.createElement(f,{prefixCls:P,key:e.value.toString(),disabled:"disabled"in e?e.disabled:y.disabled,value:e.value,checked:k.includes(e.value),onChange:e.onChange,className:(0,r.default)(`${_}-item`,e.className),style:e.style,title:e.title,id:e.id,required:e.required},e.label)):o,I=t.useMemo(()=>({toggleOption:O,value:k,disabled:y.disabled,name:y.name,registerValue:E,cancelValue:T}),[O,k,y.disabled,y.name,E,T]),D=(0,r.default)(_,{[`${_}-rtl`]:"rtl"===C},d,g,B,$,z);return R(t.createElement("div",Object.assign({className:D,style:p},L,{ref:a}),t.createElement(u.default.Provider,{value:I},F)))});f.Group=v,f.__ANT_CHECKBOX=!0,e.s(["default",0,f],374276)},536916,e=>{"use strict";var t=e.i(374276);e.s(["Checkbox",()=>t.default])},292639,e=>{"use strict";var t=e.i(764205),r=e.i(266027);let a=(0,e.i(243652).createQueryKeys)("uiSettings");e.s(["useUISettings",0,()=>(0,r.useQuery)({queryKey:a.list({}),queryFn:async()=>await (0,t.getUiSettings)(),staleTime:36e5,gcTime:36e5})])},250980,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v3m0 0v3m0-3h3m-3 0H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z"}))});e.s(["PlusCircleIcon",0,r],250980)},502547,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"}))});e.s(["ChevronRightIcon",0,r],502547)},384767,e=>{"use strict";var t=e.i(843476),r=e.i(599724),a=e.i(271645),l=e.i(389083);let o=a.forwardRef(function(e,t){return a.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:t},e),a.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4m0 5c0 2.21-3.582 4-8 4s-8-1.79-8-4"}))});var s=e.i(764205);let n=function({vectorStores:e,accessToken:n}){let[i,c]=(0,a.useState)([]);return(0,a.useEffect)(()=>{(async()=>{if(n&&0!==e.length)try{let e=await (0,s.vectorStoreListCall)(n);e.data&&c(e.data.map(e=>({vector_store_id:e.vector_store_id,vector_store_name:e.vector_store_name})))}catch(e){console.error("Error fetching vector stores:",e)}})()},[n,e.length]),(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(o,{className:"h-4 w-4 text-blue-600"}),(0,t.jsx)(r.Text,{className:"font-semibold text-gray-900",children:"Vector Stores"}),(0,t.jsx)(l.Badge,{color:"blue",size:"xs",children:e.length})]}),e.length>0?(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:e.map((e,r)=>{let a;return(0,t.jsx)("div",{className:"inline-flex items-center px-3 py-1.5 rounded-lg bg-blue-50 border border-blue-200 text-blue-800 text-sm font-medium",children:(a=i.find(t=>t.vector_store_id===e))?`${a.vector_store_name||a.vector_store_id} (${a.vector_store_id})`:e},r)})}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 border border-gray-200",children:[(0,t.jsx)(o,{className:"h-4 w-4 text-gray-400"}),(0,t.jsx)(r.Text,{className:"text-gray-500 text-sm",children:"No vector stores configured"})]})]})},i=a.forwardRef(function(e,t){return a.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:t},e),a.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01"}))});var c=e.i(871943),d=e.i(502547),u=e.i(592968);let m=function({mcpServers:o,mcpAccessGroups:n=[],mcpToolPermissions:m={},accessToken:g}){let[p,f]=(0,a.useState)([]),[h,x]=(0,a.useState)([]),[b,v]=(0,a.useState)(new Set);(0,a.useEffect)(()=>{(async()=>{if(g&&o.length>0)try{let e=await (0,s.fetchMCPServers)(g);e&&Array.isArray(e)?f(e):e.data&&Array.isArray(e.data)&&f(e.data)}catch(e){console.error("Error fetching MCP servers:",e)}})()},[g,o.length]),(0,a.useEffect)(()=>{(async()=>{if(g&&n.length>0)try{let t=await e.A(601236).then(e=>e.fetchMCPAccessGroups(g));x(Array.isArray(t)?t:t.data||[])}catch(e){console.error("Error fetching MCP access groups:",e)}})()},[g,n.length]);let y=[...o.map(e=>({type:"server",value:e})),...n.map(e=>({type:"accessGroup",value:e}))],w=y.length;return(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(i,{className:"h-4 w-4 text-blue-600"}),(0,t.jsx)(r.Text,{className:"font-semibold text-gray-900",children:"MCP Servers"}),(0,t.jsx)(l.Badge,{color:"blue",size:"xs",children:w})]}),w>0?(0,t.jsx)("div",{className:"max-h-[400px] overflow-y-auto space-y-2 pr-1",children:y.map((e,r)=>{let a="server"===e.type?m[e.value]:void 0,l=a&&a.length>0,o=b.has(e.value);return(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{onClick:()=>{var t;return l&&(t=e.value,void v(e=>{let r=new Set(e);return r.has(t)?r.delete(t):r.add(t),r}))},className:`flex items-center gap-3 py-2 px-3 rounded-lg border border-gray-200 transition-all ${l?"cursor-pointer hover:bg-gray-50 hover:border-gray-300":"bg-white"}`,children:[(0,t.jsx)("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:"server"===e.type?(0,t.jsx)(u.Tooltip,{title:`Full ID: ${e.value}`,placement:"top",children:(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 min-w-0",children:[(0,t.jsx)("span",{className:"inline-block w-1.5 h-1.5 bg-blue-500 rounded-full flex-shrink-0"}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-900 truncate",children:(e=>{let t=p.find(t=>t.server_id===e);if(t){let r=e.length>7?`${e.slice(0,3)}...${e.slice(-4)}`:e;return`${t.alias} (${r})`}return e})(e.value)})]})}):(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 min-w-0",children:[(0,t.jsx)("span",{className:"inline-block w-1.5 h-1.5 bg-green-500 rounded-full flex-shrink-0"}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-900 truncate",children:e.value}),(0,t.jsx)("span",{className:"ml-1 px-1.5 py-0.5 text-[9px] font-semibold text-green-600 bg-green-50 border border-green-200 rounded uppercase tracking-wide flex-shrink-0",children:"Group"})]})}),l&&(0,t.jsxs)("div",{className:"flex items-center gap-1 flex-shrink-0 whitespace-nowrap",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-gray-600",children:a.length}),(0,t.jsx)("span",{className:"text-xs text-gray-500",children:1===a.length?"tool":"tools"}),o?(0,t.jsx)(c.ChevronDownIcon,{className:"h-3.5 w-3.5 text-gray-400 ml-0.5"}):(0,t.jsx)(d.ChevronRightIcon,{className:"h-3.5 w-3.5 text-gray-400 ml-0.5"})]})]}),l&&o&&(0,t.jsx)("div",{className:"ml-4 pl-4 border-l-2 border-blue-200 pb-1",children:(0,t.jsx)("div",{className:"flex flex-wrap gap-1.5",children:a.map((e,r)=>(0,t.jsx)("span",{className:"inline-flex items-center px-2.5 py-1 rounded-lg bg-blue-50 border border-blue-200 text-blue-800 text-xs font-medium",children:e},r))})})]},r)})}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 border border-gray-200",children:[(0,t.jsx)(i,{className:"h-4 w-4 text-gray-400"}),(0,t.jsx)(r.Text,{className:"text-gray-500 text-sm",children:"No MCP servers or access groups configured"})]})]})},g=a.forwardRef(function(e,t){return a.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:t},e),a.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"}))}),p=function({agents:e,agentAccessGroups:o=[],accessToken:n}){let[i,c]=(0,a.useState)([]);(0,a.useEffect)(()=>{(async()=>{if(n&&e.length>0)try{let e=await (0,s.getAgentsList)(n);e&&e.agents&&Array.isArray(e.agents)&&c(e.agents)}catch(e){console.error("Error fetching agents:",e)}})()},[n,e.length]);let d=[...e.map(e=>({type:"agent",value:e})),...o.map(e=>({type:"accessGroup",value:e}))],m=d.length;return(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(g,{className:"h-4 w-4 text-purple-600"}),(0,t.jsx)(r.Text,{className:"font-semibold text-gray-900",children:"Agents"}),(0,t.jsx)(l.Badge,{color:"purple",size:"xs",children:m})]}),m>0?(0,t.jsx)("div",{className:"max-h-[400px] overflow-y-auto space-y-2 pr-1",children:d.map((e,r)=>(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsx)("div",{className:"flex items-center gap-3 py-2 px-3 rounded-lg border border-gray-200 bg-white",children:(0,t.jsx)("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:"agent"===e.type?(0,t.jsx)(u.Tooltip,{title:`Full ID: ${e.value}`,placement:"top",children:(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 min-w-0",children:[(0,t.jsx)("span",{className:"inline-block w-1.5 h-1.5 bg-purple-500 rounded-full flex-shrink-0"}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-900 truncate",children:(e=>{let t=i.find(t=>t.agent_id===e);if(t){let r=e.length>7?`${e.slice(0,3)}...${e.slice(-4)}`:e;return`${t.agent_name} (${r})`}return e})(e.value)})]})}):(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 min-w-0",children:[(0,t.jsx)("span",{className:"inline-block w-1.5 h-1.5 bg-green-500 rounded-full flex-shrink-0"}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-900 truncate",children:e.value}),(0,t.jsx)("span",{className:"ml-1 px-1.5 py-0.5 text-[9px] font-semibold text-green-600 bg-green-50 border border-green-200 rounded uppercase tracking-wide flex-shrink-0",children:"Group"})]})})})},r))}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-50 border border-gray-200",children:[(0,t.jsx)(g,{className:"h-4 w-4 text-gray-400"}),(0,t.jsx)(r.Text,{className:"text-gray-500 text-sm",children:"No agents or access groups configured"})]})]})};e.s(["default",0,function({objectPermission:e,variant:a="card",className:l="",accessToken:o}){let s=e?.vector_stores||[],i=e?.mcp_servers||[],c=e?.mcp_access_groups||[],d=e?.mcp_tool_permissions||{},u=e?.agents||[],g=e?.agent_access_groups||[],f=(0,t.jsxs)("div",{className:"card"===a?"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6":"space-y-4",children:[(0,t.jsx)(n,{vectorStores:s,accessToken:o}),(0,t.jsx)(m,{mcpServers:i,mcpAccessGroups:c,mcpToolPermissions:d,accessToken:o}),(0,t.jsx)(p,{agents:u,agentAccessGroups:g,accessToken:o})]});return"card"===a?(0,t.jsxs)("div",{className:`bg-white border border-gray-200 rounded-lg p-6 ${l}`,children:[(0,t.jsx)("div",{className:"flex items-center gap-2 mb-6",children:(0,t.jsxs)("div",{children:[(0,t.jsx)(r.Text,{className:"font-semibold text-gray-900",children:"Object Permissions"}),(0,t.jsx)(r.Text,{className:"text-xs text-gray-500",children:"Access control for Vector Stores and MCP Servers"})]})}),f]}):(0,t.jsxs)("div",{className:`${l}`,children:[(0,t.jsx)(r.Text,{className:"font-medium text-gray-900 mb-3",children:"Object Permissions"}),f]})}],384767)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/43dc4975b83e2635.js b/litellm/proxy/_experimental/out/_next/static/chunks/591e3b6fbe6e4d4a.js similarity index 51% rename from litellm/proxy/_experimental/out/_next/static/chunks/43dc4975b83e2635.js rename to litellm/proxy/_experimental/out/_next/static/chunks/591e3b6fbe6e4d4a.js index fa929b0c6a6..e79c30fd92a 100644 --- a/litellm/proxy/_experimental/out/_next/static/chunks/43dc4975b83e2635.js +++ b/litellm/proxy/_experimental/out/_next/static/chunks/591e3b6fbe6e4d4a.js @@ -1 +1 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,207082,e=>{"use strict";var t=e.i(619273),s=e.i(266027),a=e.i(243652),l=e.i(764205),r=e.i(135214);let i=(0,a.createQueryKeys)("keys"),n=async(e,t,s,a={})=>{try{let r=(0,l.getProxyBaseUrl)(),i=new URLSearchParams(Object.entries({team_id:a.teamID,project_id:a.projectID,organization_id:a.organizationID,key_alias:a.selectedKeyAlias,key_hash:a.keyHash,user_id:a.userID,page:t,size:s,sort_by:a.sortBy,sort_order:a.sortOrder,expand:a.expand,status:a.status,return_full_object:"true",include_team_keys:"true",include_created_by_keys:"true"}).filter(([,e])=>null!=e).map(([e,t])=>[e,String(t)])),n=`${r?`${r}/key/list`:"/key/list"}?${i}`,o=await fetch(n,{method:"GET",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!o.ok){let e=await o.json(),t=(0,l.deriveErrorMessage)(e);throw(0,l.handleError)(t),Error(t)}let c=await o.json();return console.log("/key/list API Response:",c),c}catch(e){throw console.error("Failed to list keys:",e),e}},o=(0,a.createQueryKeys)("deletedKeys");e.s(["keyKeys",0,i,"useDeletedKeys",0,(e,a,l={})=>{let{accessToken:i}=(0,r.default)();return(0,s.useQuery)({queryKey:o.list({page:e,limit:a,...l}),queryFn:async()=>await n(i,e,a,{...l,status:"deleted"}),enabled:!!i,staleTime:3e4,placeholderData:t.keepPreviousData})},"useKeys",0,(e,a,l={})=>{let{accessToken:o}=(0,r.default)();return(0,s.useQuery)({queryKey:i.list({page:e,limit:a,...l}),queryFn:async()=>await n(o,e,a,l),enabled:!!o,staleTime:3e4,placeholderData:t.keepPreviousData})}])},510674,e=>{"use strict";var t=e.i(266027),s=e.i(243652),a=e.i(764205),l=e.i(708347),r=e.i(135214);let i=(0,s.createQueryKeys)("projects"),n=async e=>{let t=(0,a.getProxyBaseUrl)(),s=`${t}/project/list`,l=await fetch(s,{method:"GET",headers:{[(0,a.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!l.ok){let e=await l.json(),t=(0,a.deriveErrorMessage)(e);throw(0,a.handleError)(t),Error(t)}return l.json()};e.s(["projectKeys",0,i,"useProjects",0,()=>{let{accessToken:e,userRole:s}=(0,r.default)();return(0,t.useQuery)({queryKey:i.list({}),queryFn:async()=>n(e),enabled:!!e&&l.all_admin_roles.includes(s||"")})}])},552130,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(199133),l=e.i(764205);e.s(["default",0,({onChange:e,value:r,className:i,accessToken:n,placeholder:o="Select agents",disabled:c=!1})=>{let[d,u]=(0,s.useState)([]),[m,p]=(0,s.useState)([]),[g,h]=(0,s.useState)(!1);(0,s.useEffect)(()=>{(async()=>{if(n){h(!0);try{let e=await (0,l.getAgentsList)(n),t=e?.agents||[];u(t);let s=new Set;t.forEach(e=>{let t=e.agent_access_groups;t&&Array.isArray(t)&&t.forEach(e=>s.add(e))}),p(Array.from(s))}catch(e){console.error("Error fetching agents:",e)}finally{h(!1)}}})()},[n]);let x=[...m.map(e=>({label:e,value:`group:${e}`,isAccessGroup:!0,searchText:`${e} Access Group`})),...d.map(e=>({label:`${e.agent_name||e.agent_id}`,value:e.agent_id,isAccessGroup:!1,searchText:`${e.agent_name||e.agent_id} ${e.agent_id} Agent`}))],y=[...r?.agents||[],...(r?.accessGroups||[]).map(e=>`group:${e}`)];return(0,t.jsx)("div",{children:(0,t.jsx)(a.Select,{mode:"multiple",placeholder:o,onChange:t=>{e({agents:t.filter(e=>!e.startsWith("group:")),accessGroups:t.filter(e=>e.startsWith("group:")).map(e=>e.replace("group:",""))})},value:y,loading:g,className:i,allowClear:!0,showSearch:!0,style:{width:"100%"},disabled:c,filterOption:(e,t)=>(x.find(e=>e.value===t?.value)?.searchText||"").toLowerCase().includes(e.toLowerCase()),children:x.map(e=>(0,t.jsx)(a.Select.Option,{value:e.value,label:e.label,children:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[(0,t.jsx)("span",{style:{display:"inline-block",width:8,height:8,borderRadius:"50%",background:e.isAccessGroup?"#52c41a":"#722ed1",flexShrink:0}}),(0,t.jsx)("span",{style:{flex:1},children:e.label}),(0,t.jsx)("span",{style:{color:e.isAccessGroup?"#52c41a":"#722ed1",fontSize:"12px",fontWeight:500,opacity:.8},children:e.isAccessGroup?"Access Group":"Agent"})]})},e.value))})})}])},557662,e=>{"use strict";let t="../ui/assets/logos/",s=[{id:"arize",displayName:"Arize",logo:`${t}arize.png`,supports_key_team_logging:!0,dynamic_params:{arize_api_key:"password",arize_space_id:"password"},description:"Arize Logging Integration"},{id:"braintrust",displayName:"Braintrust",logo:`${t}braintrust.png`,supports_key_team_logging:!1,dynamic_params:{braintrust_api_key:"password",braintrust_project_name:"text"},description:"Braintrust Logging Integration"},{id:"custom_callback_api",displayName:"Custom Callback API",logo:`${t}custom.svg`,supports_key_team_logging:!0,dynamic_params:{custom_callback_api_url:"text",custom_callback_api_headers:"text"},description:"Custom Callback API Logging Integration"},{id:"datadog",displayName:"Datadog",logo:`${t}datadog.png`,supports_key_team_logging:!1,dynamic_params:{dd_api_key:"password",dd_site:"text"},description:"Datadog Logging Integration"},{id:"lago",displayName:"Lago",logo:`${t}lago.svg`,supports_key_team_logging:!1,dynamic_params:{lago_api_url:"text",lago_api_key:"password"},description:"Lago Billing Logging Integration"},{id:"langfuse",displayName:"Langfuse",logo:`${t}langfuse.png`,supports_key_team_logging:!0,dynamic_params:{langfuse_public_key:"text",langfuse_secret_key:"password",langfuse_host:"text"},description:"Langfuse v2 Logging Integration"},{id:"langfuse_otel",displayName:"Langfuse OTEL",logo:`${t}langfuse.png`,supports_key_team_logging:!0,dynamic_params:{langfuse_public_key:"text",langfuse_secret_key:"password",langfuse_host:"text"},description:"Langfuse v3 OTEL Logging Integration"},{id:"langsmith",displayName:"LangSmith",logo:`${t}langsmith.png`,supports_key_team_logging:!0,dynamic_params:{langsmith_api_key:"password",langsmith_project:"text",langsmith_base_url:"text",langsmith_sampling_rate:"number"},description:"Langsmith Logging Integration"},{id:"openmeter",displayName:"OpenMeter",logo:`${t}openmeter.png`,supports_key_team_logging:!1,dynamic_params:{openmeter_api_key:"password",openmeter_base_url:"text"},description:"OpenMeter Logging Integration"},{id:"otel",displayName:"Open Telemetry",logo:`${t}otel.png`,supports_key_team_logging:!1,dynamic_params:{otel_endpoint:"text",otel_headers:"text"},description:"OpenTelemetry Logging Integration"},{id:"s3",displayName:"S3",logo:`${t}aws.svg`,supports_key_team_logging:!1,dynamic_params:{s3_bucket_name:"text",aws_access_key_id:"password",aws_secret_access_key:"password",aws_region:"text"},description:"S3 Bucket (AWS) Logging Integration"},{id:"SQS",displayName:"SQS",logo:`${t}aws.svg`,supports_key_team_logging:!1,dynamic_params:{sqs_queue_url:"text",aws_access_key_id:"password",aws_secret_access_key:"password",aws_region:"text"},description:"SQS Queue (AWS) Logging Integration"}],a=s.reduce((e,t)=>(e[t.displayName]=t,e),{}),l=s.reduce((e,t)=>(e[t.displayName]=t.id,e),{}),r=s.reduce((e,t)=>(e[t.id]=t.displayName,e),{});e.s(["callbackInfo",0,a,"callback_map",0,l,"mapDisplayToInternalNames",0,e=>e.map(e=>l[e]||e),"mapInternalToDisplayNames",0,e=>e.map(e=>r[e]||e),"reverse_callback_map",0,r])},9314,263147,e=>{"use strict";var t=e.i(843476),s=e.i(199133),a=e.i(981339),l=e.i(645526),r=e.i(599724),i=e.i(266027),n=e.i(243652),o=e.i(764205),c=e.i(708347),d=e.i(135214);let u=(0,n.createQueryKeys)("accessGroups"),m=async e=>{let t=(0,o.getProxyBaseUrl)(),s=`${t}/v1/access_group`,a=await fetch(s,{method:"GET",headers:{[(0,o.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!a.ok){let e=await a.json(),t=(0,o.deriveErrorMessage)(e);throw(0,o.handleError)(t),Error(t)}return a.json()},p=()=>{let{accessToken:e,userRole:t}=(0,d.default)();return(0,i.useQuery)({queryKey:u.list({}),queryFn:async()=>m(e),enabled:!!e&&c.all_admin_roles.includes(t||"")})};e.s(["accessGroupKeys",0,u,"useAccessGroups",0,p],263147),e.s(["default",0,({value:e,onChange:i,placeholder:n="Select access groups",disabled:o=!1,style:c,className:d,showLabel:u=!1,labelText:m="Access Group",allowClear:g=!0})=>{let{data:h,isLoading:x,isError:y}=p();if(x)return(0,t.jsxs)("div",{children:[u&&(0,t.jsxs)(r.Text,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,t.jsx)(l.TeamOutlined,{className:"mr-2"})," ",m]}),(0,t.jsx)(a.Skeleton.Input,{active:!0,block:!0,style:{height:32,...c}})]});let f=(h??[]).map(e=>({label:(0,t.jsxs)("span",{children:[(0,t.jsx)("span",{className:"font-medium",children:e.access_group_name})," ",(0,t.jsxs)("span",{className:"text-gray-400 text-xs",children:["(",e.access_group_id,")"]})]}),value:e.access_group_id,selectedLabel:e.access_group_name,searchText:`${e.access_group_name} ${e.access_group_id}`}));return(0,t.jsxs)("div",{children:[u&&(0,t.jsxs)(r.Text,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,t.jsx)(l.TeamOutlined,{className:"mr-2"})," ",m]}),(0,t.jsx)(s.Select,{mode:"multiple",value:e,placeholder:n,onChange:i,disabled:o,allowClear:g,showSearch:!0,style:{width:"100%",...c},className:`rounded-md ${d??""}`,notFoundContent:y?(0,t.jsx)("span",{className:"text-red-500",children:"Failed to load access groups"}):"No access groups found",filterOption:(e,t)=>(f.find(e=>e.value===t?.value)?.searchText??"").toLowerCase().includes(e.toLowerCase()),optionLabelProp:"selectedLabel",options:f.map(e=>({label:e.label,value:e.value,selectedLabel:e.selectedLabel}))})]})}],9314)},392110,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(199133),l=e.i(592968),r=e.i(312361),i=e.i(790848),n=e.i(536916),o=e.i(827252),c=e.i(779241);let{Option:d}=a.Select;e.s(["default",0,({form:e,autoRotationEnabled:u,onAutoRotationChange:m,rotationInterval:p,onRotationIntervalChange:g,isCreateMode:h=!1,neverExpire:x=!1,onNeverExpireChange:y})=>{let f=p&&!["7d","30d","90d","180d","365d"].includes(p),[_,j]=(0,s.useState)(f),[b,v]=(0,s.useState)(f?p:""),[w,N]=(0,s.useState)(e?.getFieldValue?.("duration")||"");return(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Key Expiry Settings"}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,t.jsx)("span",{children:"Expire Key"}),(0,t.jsx)(l.Tooltip,{title:"Set when this key should expire. Format: 30s (seconds), 30m (minutes), 30h (hours), 30d (days). Leave empty to keep the current expiry unchanged.",children:(0,t.jsx)(o.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})}),!h&&y&&(0,t.jsx)(n.Checkbox,{checked:x,onChange:t=>{let s=t.target.checked;y(s),s&&(N(""),e&&"function"==typeof e.setFieldValue?e.setFieldValue("duration",""):e&&"function"==typeof e.setFieldsValue&&e.setFieldsValue({duration:""}))},className:"ml-2 text-sm font-normal text-gray-600",children:"Never Expire"})]}),(0,t.jsx)(c.TextInput,{name:"duration",placeholder:h?"e.g., 30d or leave empty to never expire":"e.g., 30d",className:"w-full",value:w,onValueChange:t=>{N(t),e&&"function"==typeof e.setFieldValue?e.setFieldValue("duration",t):e&&"function"==typeof e.setFieldsValue&&e.setFieldsValue({duration:t})},disabled:!h&&x})]})]}),(0,t.jsx)(r.Divider,{}),(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Auto-Rotation Settings"}),(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,t.jsx)("span",{children:"Enable Auto-Rotation"}),(0,t.jsx)(l.Tooltip,{title:"Key will automatically regenerate at the specified interval for enhanced security.",children:(0,t.jsx)(o.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})})]}),(0,t.jsx)(i.Switch,{checked:u,onChange:m,size:"default",className:u?"":"bg-gray-400"})]}),u&&(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,t.jsx)("span",{children:"Rotation Interval"}),(0,t.jsx)(l.Tooltip,{title:"How often the key should be automatically rotated. Choose the interval that best fits your security requirements.",children:(0,t.jsx)(o.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)(a.Select,{value:_?"custom":p,onChange:e=>{"custom"===e?j(!0):(j(!1),v(""),g(e))},className:"w-full",placeholder:"Select interval",children:[(0,t.jsx)(d,{value:"7d",children:"7 days"}),(0,t.jsx)(d,{value:"30d",children:"30 days"}),(0,t.jsx)(d,{value:"90d",children:"90 days"}),(0,t.jsx)(d,{value:"180d",children:"180 days"}),(0,t.jsx)(d,{value:"365d",children:"365 days"}),(0,t.jsx)(d,{value:"custom",children:"Custom interval"})]}),_&&(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(c.TextInput,{value:b,onChange:e=>{let t=e.target.value;v(t),g(t)},placeholder:"e.g., 1s, 5m, 2h, 14d"}),(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"Supported formats: seconds (s), minutes (m), hours (h), days (d)"})]})]})]})]}),u&&(0,t.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."})]})]})}])},533882,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(250980),l=e.i(797672),r=e.i(68155),i=e.i(304967),n=e.i(629569),o=e.i(599724),c=e.i(269200),d=e.i(427612),u=e.i(64848),m=e.i(942232),p=e.i(496020),g=e.i(977572),h=e.i(992619),x=e.i(727749);e.s(["default",0,({accessToken:e,initialModelAliases:y={},onAliasUpdate:f,showExampleConfig:_=!0})=>{let[j,b]=(0,s.useState)([]),[v,w]=(0,s.useState)({aliasName:"",targetModel:""}),[N,k]=(0,s.useState)(null);(0,s.useEffect)(()=>{b(Object.entries(y).map(([e,t],s)=>({id:`${s}-${e}`,aliasName:e,targetModel:t})))},[y]);let S=()=>{if(!N)return;if(!N.aliasName||!N.targetModel)return void x.default.fromBackend("Please provide both alias name and target model");if(j.some(e=>e.id!==N.id&&e.aliasName===N.aliasName))return void x.default.fromBackend("An alias with this name already exists");let e=j.map(e=>e.id===N.id?N:e);b(e),k(null);let t={};e.forEach(e=>{t[e.aliasName]=e.targetModel}),f&&f(t),x.default.success("Alias updated successfully")},C=()=>{k(null)},T=j.reduce((e,t)=>(e[t.aliasName]=t.targetModel,e),{});return(0,t.jsxs)("div",{className:"mt-4",children:[(0,t.jsxs)("div",{className:"mb-6",children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium text-gray-700 mb-2",children:"Add New Alias"}),(0,t.jsxs)("div",{className:"grid grid-cols-3 gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-xs text-gray-500 mb-1",children:"Alias Name"}),(0,t.jsx)("input",{type:"text",value:v.aliasName,onChange:e=>w({...v,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,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-xs text-gray-500 mb-1",children:"Target Model"}),(0,t.jsx)(h.default,{accessToken:e,value:v.targetModel,placeholder:"Select target model",onChange:e=>w({...v,targetModel:e}),showLabel:!1})]}),(0,t.jsx)("div",{className:"flex items-end",children:(0,t.jsxs)("button",{onClick:()=>{if(!v.aliasName||!v.targetModel)return void x.default.fromBackend("Please provide both alias name and target model");if(j.some(e=>e.aliasName===v.aliasName))return void x.default.fromBackend("An alias with this name already exists");let e=[...j,{id:`${Date.now()}-${v.aliasName}`,aliasName:v.aliasName,targetModel:v.targetModel}];b(e),w({aliasName:"",targetModel:""});let t={};e.forEach(e=>{t[e.aliasName]=e.targetModel}),f&&f(t),x.default.success("Alias added successfully")},disabled:!v.aliasName||!v.targetModel,className:`flex items-center px-4 py-2 rounded-md text-sm ${!v.aliasName||!v.targetModel?"bg-gray-300 text-gray-500 cursor-not-allowed":"bg-green-600 text-white hover:bg-green-700"}`,children:[(0,t.jsx)(a.PlusCircleIcon,{className:"w-4 h-4 mr-1"}),"Add Alias"]})})]})]}),(0,t.jsx)(o.Text,{className:"text-sm font-medium text-gray-700 mb-2",children:"Manage Existing Aliases"}),(0,t.jsx)("div",{className:"rounded-lg custom-border relative mb-6",children:(0,t.jsx)("div",{className:"overflow-x-auto",children:(0,t.jsxs)(c.Table,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,t.jsx)(d.TableHead,{children:(0,t.jsxs)(p.TableRow,{children:[(0,t.jsx)(u.TableHeaderCell,{className:"py-1 h-8",children:"Alias Name"}),(0,t.jsx)(u.TableHeaderCell,{className:"py-1 h-8",children:"Target Model"}),(0,t.jsx)(u.TableHeaderCell,{className:"py-1 h-8",children:"Actions"})]})}),(0,t.jsxs)(m.TableBody,{children:[j.map(s=>(0,t.jsx)(p.TableRow,{className:"h-8",children:N&&N.id===s.id?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(g.TableCell,{className:"py-0.5",children:(0,t.jsx)("input",{type:"text",value:N.aliasName,onChange:e=>k({...N,aliasName:e.target.value}),className:"w-full px-2 py-1 border border-gray-300 rounded-md text-sm"})}),(0,t.jsx)(g.TableCell,{className:"py-0.5",children:(0,t.jsx)(h.default,{accessToken:e,value:N.targetModel,onChange:e=>k({...N,targetModel:e}),showLabel:!1,style:{height:"32px"}})}),(0,t.jsx)(g.TableCell,{className:"py-0.5 whitespace-nowrap",children:(0,t.jsxs)("div",{className:"flex space-x-2",children:[(0,t.jsx)("button",{onClick:S,className:"text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded hover:bg-blue-100",children:"Save"}),(0,t.jsx)("button",{onClick:C,className:"text-xs bg-gray-50 text-gray-600 px-2 py-1 rounded hover:bg-gray-100",children:"Cancel"})]})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(g.TableCell,{className:"py-0.5 text-sm text-gray-900",children:s.aliasName}),(0,t.jsx)(g.TableCell,{className:"py-0.5 text-sm text-gray-500",children:s.targetModel}),(0,t.jsx)(g.TableCell,{className:"py-0.5 whitespace-nowrap",children:(0,t.jsxs)("div",{className:"flex space-x-2",children:[(0,t.jsx)("button",{onClick:()=>{k({...s})},className:"text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded hover:bg-blue-100",children:(0,t.jsx)(l.PencilIcon,{className:"w-3 h-3"})}),(0,t.jsx)("button",{onClick:()=>{var e;let t,a;return e=s.id,b(t=j.filter(t=>t.id!==e)),a={},void(t.forEach(e=>{a[e.aliasName]=e.targetModel}),f&&f(a),x.default.success("Alias deleted successfully"))},className:"text-xs bg-red-50 text-red-600 px-2 py-1 rounded hover:bg-red-100",children:(0,t.jsx)(r.TrashIcon,{className:"w-3 h-3"})})]})})]})},s.id)),0===j.length&&(0,t.jsx)(p.TableRow,{children:(0,t.jsx)(g.TableCell,{colSpan:3,className:"py-0.5 text-sm text-gray-500 text-center",children:"No aliases added yet. Add a new alias above."})})]})]})})}),_&&(0,t.jsxs)(i.Card,{children:[(0,t.jsx)(n.Title,{className:"mb-4",children:"Configuration Example"}),(0,t.jsx)(o.Text,{className:"text-gray-600 mb-4",children:"Here's how your current aliases would look in the config:"}),(0,t.jsx)("div",{className:"bg-gray-100 rounded-lg p-4 font-mono text-sm",children:(0,t.jsxs)("div",{className:"text-gray-700",children:["model_aliases:",0===Object.keys(T).length?(0,t.jsxs)("span",{className:"text-gray-500",children:[(0,t.jsx)("br",{}),"  # No aliases configured yet"]}):Object.entries(T).map(([e,s])=>(0,t.jsxs)("span",{children:[(0,t.jsx)("br",{}),'  "',e,'": "',s,'"']},e))]})})]})]})}])},844565,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(199133),l=e.i(764205);e.s(["default",0,({onChange:e,value:r,className:i,accessToken:n,placeholder:o="Select pass through routes",disabled:c=!1,teamId:d})=>{let[u,m]=(0,s.useState)([]),[p,g]=(0,s.useState)(!1);return(0,s.useEffect)(()=>{(async()=>{if(n){g(!0);try{let e=await (0,l.getPassThroughEndpointsCall)(n,d);if(e.endpoints){let t=e.endpoints.flatMap(e=>{let t=e.path,s=e.methods;return s&&s.length>0?s.map(e=>({label:`${e} ${t}`,value:t})):[{label:t,value:t}]});m(t)}}catch(e){console.error("Error fetching pass through routes:",e)}finally{g(!1)}}})()},[n,d]),(0,t.jsx)(a.Select,{mode:"tags",placeholder:o,onChange:e,value:r,loading:p,className:i,allowClear:!0,options:u,optionFilterProp:"label",showSearch:!0,style:{width:"100%"},disabled:c})}])},810757,477386,e=>{"use strict";var t=e.i(271645);let s=t.forwardRef(function(e,s){return t.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:s},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}))});e.s(["CogIcon",0,s],810757);let a=t.forwardRef(function(e,s){return t.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:s},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"}))});e.s(["BanIcon",0,a],477386)},266484,e=>{"use strict";var t=e.i(843476),s=e.i(199133),a=e.i(592968),l=e.i(312361),r=e.i(827252),i=e.i(994388),n=e.i(304967),o=e.i(779241),c=e.i(988297),d=e.i(68155),u=e.i(810757),m=e.i(477386),p=e.i(557662),g=e.i(435451);let{Option:h}=s.Select;e.s(["default",0,({value:e=[],onChange:x,disabledCallbacks:y=[],onDisabledCallbacksChange:f})=>{let _=Object.entries(p.callbackInfo).filter(([e,t])=>t.supports_key_team_logging).map(([e,t])=>e),j=Object.keys(p.callbackInfo),b=e=>{x?.(e)},v=(t,s,a)=>{let l=[...e];if("callback_name"===s){let e=p.callback_map[a]||a;l[t]={...l[t],[s]:e,callback_vars:{}}}else l[t]={...l[t],[s]:a};b(l)},w=(t,s,a)=>{let l=[...e];l[t]={...l[t],callback_vars:{...l[t].callback_vars,[s]:a}},b(l)};return(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)(m.BanIcon,{className:"w-5 h-5 text-red-500"}),(0,t.jsx)("span",{className:"text-base font-semibold text-gray-800",children:"Disabled Callbacks"}),(0,t.jsx)(a.Tooltip,{title:"Select callbacks to disable for this key. Disabled callbacks will not receive any logging data.",children:(0,t.jsx)(r.InfoCircleOutlined,{className:"text-gray-400 cursor-help"})})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{className:"text-sm font-medium text-gray-700",children:"Disabled Callbacks"}),(0,t.jsx)(s.Select,{mode:"multiple",placeholder:"Select callbacks to disable",value:y,onChange:e=>{let t=(0,p.mapDisplayToInternalNames)(e);f?.(t)},style:{width:"100%"},optionLabelProp:"label",children:j.map(e=>{let s=p.callbackInfo[e]?.logo,l=p.callbackInfo[e]?.description;return(0,t.jsx)(h,{value:e,label:e,children:(0,t.jsx)(a.Tooltip,{title:l,placement:"right",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[s&&(0,t.jsx)("img",{src:s,alt:e,className:"w-4 h-4 object-contain",onError:t=>{let s=t.target,a=s.parentElement;if(a){let t=document.createElement("div");t.className="w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",t.textContent=e.charAt(0),a.replaceChild(t,s)}}}),(0,t.jsx)("span",{children:e})]})})},e)})}),(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"Select callbacks that should be disabled for this key. These callbacks will not receive any logging data."})]})]}),(0,t.jsx)(l.Divider,{}),(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)(u.CogIcon,{className:"w-5 h-5 text-blue-500"}),(0,t.jsx)("span",{className:"text-base font-semibold text-gray-800",children:"Logging Integrations"}),(0,t.jsx)(a.Tooltip,{title:"Configure callback logging integrations for this team.",children:(0,t.jsx)(r.InfoCircleOutlined,{className:"text-gray-400 cursor-help"})})]}),(0,t.jsx)(i.Button,{variant:"secondary",onClick:()=>{b([...e,{callback_name:"",callback_type:"success",callback_vars:{}}])},icon:c.PlusIcon,size:"sm",className:"hover:border-blue-400 hover:text-blue-500",type:"button",children:"Add Integration"})]}),(0,t.jsx)("div",{className:"space-y-4",children:e.map((l,c)=>{let u=l.callback_name?Object.entries(p.callback_map).find(([e,t])=>t===l.callback_name)?.[0]:void 0,m=u?p.callbackInfo[u]?.logo:null;return(0,t.jsxs)(n.Card,{className:"border border-gray-200 shadow-sm hover:shadow-md transition-shadow duration-200",decoration:"top",decorationColor:"blue",children:[(0,t.jsxs)("div",{className:"flex justify-between items-start mb-4",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[m&&(0,t.jsx)("img",{src:m,alt:u,className:"w-5 h-5 object-contain"}),(0,t.jsxs)("span",{className:"text-sm font-medium",children:[u||"New Integration"," Configuration"]})]}),(0,t.jsx)(i.Button,{variant:"light",onClick:()=>{b(e.filter((e,t)=>t!==c))},icon:d.TrashIcon,size:"xs",color:"red",className:"hover:bg-red-50",type:"button",children:"Remove"})]}),(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{className:"text-sm font-medium text-gray-700",children:"Integration Type"}),(0,t.jsx)(s.Select,{value:u,placeholder:"Select integration",onChange:e=>v(c,"callback_name",e),className:"w-full",optionLabelProp:"label",children:_.map(e=>{let s=p.callbackInfo[e]?.logo,l=p.callbackInfo[e]?.description;return(0,t.jsx)(h,{value:e,label:e,children:(0,t.jsx)(a.Tooltip,{title:l,placement:"right",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[s&&(0,t.jsx)("img",{src:s,alt:e,className:"w-4 h-4 object-contain",onError:t=>{let s=t.target,a=s.parentElement;if(a){let t=document.createElement("div");t.className="w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",t.textContent=e.charAt(0),a.replaceChild(t,s)}}}),(0,t.jsx)("span",{children:e})]})})},e)})})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{className:"text-sm font-medium text-gray-700",children:"Event Type"}),(0,t.jsxs)(s.Select,{value:l.callback_type,onChange:e=>v(c,"callback_type",e),className:"w-full",children:[(0,t.jsx)(h,{value:"success",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-green-500 rounded-full"}),(0,t.jsx)("span",{children:"Success Only"})]})}),(0,t.jsx)(h,{value:"failure",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-red-500 rounded-full"}),(0,t.jsx)("span",{children:"Failure Only"})]})}),(0,t.jsx)(h,{value:"success_and_failure",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)("span",{children:"Success & Failure"})]})})]})]})]}),((e,s)=>{if(!e.callback_name)return null;let l=Object.entries(p.callback_map).find(([t,s])=>s===e.callback_name)?.[0];if(!l)return null;let i=p.callbackInfo[l]?.dynamic_params||{};return 0===Object.keys(i).length?null:(0,t.jsxs)("div",{className:"mt-6 pt-4 border-t border-gray-100",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2 mb-4",children:[(0,t.jsx)("div",{className:"w-3 h-3 bg-blue-100 rounded-full flex items-center justify-center",children:(0,t.jsx)("div",{className:"w-1.5 h-1.5 bg-blue-500 rounded-full"})}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Integration Parameters"})]}),(0,t.jsx)("div",{className:"grid grid-cols-1 gap-4",children:Object.entries(i).map(([l,i])=>(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 capitalize flex items-center space-x-1",children:[(0,t.jsx)("span",{children:l.replace(/_/g," ")}),(0,t.jsx)(a.Tooltip,{title:`Environment variable reference recommended: os.environ/${l.toUpperCase()}`,children:(0,t.jsx)(r.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})}),"password"===i&&(0,t.jsx)("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-800",children:"Sensitive"}),"number"===i&&(0,t.jsx)("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-800",children:"Number"})]}),"number"===i&&(0,t.jsx)("span",{className:"text-xs text-gray-500",children:"Value must be between 0 and 1"}),"number"===i?(0,t.jsx)(g.default,{step:.01,width:400,placeholder:`os.environ/${l.toUpperCase()}`,value:e.callback_vars[l]||"",onChange:e=>w(s,l,e.target.value)}):(0,t.jsx)(o.TextInput,{type:"password"===i?"password":"text",placeholder:`os.environ/${l.toUpperCase()}`,value:e.callback_vars[l]||"",onChange:e=>w(s,l,e.target.value)})]},l))})]})})(l,c)]})]},c)})}),0===e.length&&(0,t.jsxs)("div",{className:"text-center py-12 text-gray-500 border-2 border-dashed border-gray-200 rounded-lg bg-gray-50/50",children:[(0,t.jsx)(u.CogIcon,{className:"w-12 h-12 text-gray-300 mb-3 mx-auto"}),(0,t.jsx)("div",{className:"text-base font-medium mb-1",children:"No logging integrations configured"}),(0,t.jsx)("div",{className:"text-sm text-gray-400",children:'Click "Add Integration" to configure logging for this team'})]})]})}])},651904,e=>{"use strict";var t=e.i(843476),s=e.i(599724),a=e.i(266484);e.s(["default",0,function({value:e,onChange:l,premiumUser:r=!1,disabledCallbacks:i=[],onDisabledCallbacksChange:n}){return r?(0,t.jsx)(a.default,{value:e,onChange:l,disabledCallbacks:i,onDisabledCallbacksChange:n}):(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex flex-wrap gap-2 mb-3",children:[(0,t.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,t.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,t.jsx)("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-lg",children:(0,t.jsxs)(s.Text,{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,t.jsx)("a",{href:"https://www.litellm.ai/#pricing",target:"_blank",rel:"noopener noreferrer",className:"underline",children:"here"}),"."]})})]})}])},939510,e=>{"use strict";var t=e.i(843476),s=e.i(808613),a=e.i(199133),l=e.i(592968),r=e.i(827252);let{Option:i}=a.Select;e.s(["default",0,({type:e,name:n,showDetailedDescriptions:o=!0,className:c="",initialValue:d=null,form:u,onChange:m})=>{let p=e.toUpperCase(),g=e.toLowerCase(),h=`Select 'guaranteed_throughput' to prevent overallocating ${p} limit when the key belongs to a Team with specific ${p} limits.`;return(0,t.jsx)(s.Form.Item,{label:(0,t.jsxs)("span",{children:[p," Rate Limit Type"," ",(0,t.jsx)(l.Tooltip,{title:h,children:(0,t.jsx)(r.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:n,initialValue:d,className:c,children:(0,t.jsx)(a.Select,{defaultValue:o?"default":void 0,placeholder:"Select rate limit type",style:{width:"100%"},optionLabelProp:o?"label":void 0,onChange:e=>{u&&u.setFieldValue(n,e),m&&m(e)},children:o?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(i,{value:"best_effort_throughput",label:"Default",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Default"}),(0,t.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["Best effort throughput - no error if we're overallocating ",g," (Team/Key Limits checked at runtime)."]})]})}),(0,t.jsx)(i,{value:"guaranteed_throughput",label:"Guaranteed throughput",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Guaranteed throughput"}),(0,t.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["Guaranteed throughput - raise an error if we're overallocating ",g," (also checks model-specific limits)"]})]})}),(0,t.jsx)(i,{value:"dynamic",label:"Dynamic",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Dynamic"}),(0,t.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["If the key has a set ",p," (e.g. 2 ",p,") and there are no 429 errors, it can dynamically exceed the limit when the model being called is not erroring."]})]})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(i,{value:"best_effort_throughput",children:"Best effort throughput"}),(0,t.jsx)(i,{value:"guaranteed_throughput",children:"Guaranteed throughput"}),(0,t.jsx)(i,{value:"dynamic",children:"Dynamic"})]})})})}])},460285,575260,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(404206),l=e.i(723731),r=e.i(653824),i=e.i(881073),n=e.i(197647),o=e.i(764205),c=e.i(158392),d=e.i(419470),u=e.i(689020);let m=(0,s.forwardRef)(({accessToken:e,value:m,onChange:p,modelData:g},h)=>{let[x,y]=(0,s.useState)({routerSettings:{},selectedStrategy:null,enableTagFiltering:!1}),[f,_]=(0,s.useState)([]),[j,b]=(0,s.useState)([]),[v,w]=(0,s.useState)([]),[N,k]=(0,s.useState)([]),[S,C]=(0,s.useState)({}),[T,I]=(0,s.useState)({}),A=(0,s.useRef)(!1),L=(0,s.useRef)(null);(0,s.useEffect)(()=>{let e=m?.router_settings?JSON.stringify({routing_strategy:m.router_settings.routing_strategy,fallbacks:m.router_settings.fallbacks,enable_tag_filtering:m.router_settings.enable_tag_filtering}):null;if(A.current&&e===L.current){A.current=!1;return}if(A.current&&e!==L.current&&(A.current=!1),e!==L.current)if(L.current=e,m?.router_settings){let e=m.router_settings,{fallbacks:t,...s}=e;y({routerSettings:s,selectedStrategy:e.routing_strategy||null,enableTagFiltering:e.enable_tag_filtering??!1});let a=e.fallbacks||[];_(a),b(a&&0!==a.length?a.map((e,t)=>{let[s,a]=Object.entries(e)[0];return{id:(t+1).toString(),primaryModel:s||null,fallbackModels:a||[]}}):[{id:"1",primaryModel:null,fallbackModels:[]}])}else y({routerSettings:{},selectedStrategy:null,enableTagFiltering:!1}),_([]),b([{id:"1",primaryModel:null,fallbackModels:[]}])},[m]),(0,s.useEffect)(()=>{e&&(0,o.getRouterSettingsCall)(e).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}}),C(t);let s=e.fields.find(e=>"routing_strategy"===e.field_name);s?.options&&k(s.options),e.routing_strategy_descriptions&&I(e.routing_strategy_descriptions)}})},[e]),(0,s.useEffect)(()=>{e&&(async()=>{try{let t=await (0,u.fetchAvailableModels)(e);w(t)}catch(e){console.error("Error fetching model info for fallbacks:",e)}})()},[e]);let F=()=>{let e=new Set(["allowed_fails","cooldown_time","num_retries","timeout","retry_after"]),t=new Set(["model_group_alias","retry_policy"]),s=Object.fromEntries(Object.entries({...x.routerSettings,enable_tag_filtering:x.enableTagFiltering,routing_strategy:x.selectedStrategy,fallbacks:f.length>0?f:null}).map(([s,a])=>{if("routing_strategy_args"!==s&&"routing_strategy"!==s&&"enable_tag_filtering"!==s&&"fallbacks"!==s){let l=document.querySelector(`input[name="${s}"]`);if(l&&void 0!==l.value&&""!==l.value){let r=((s,a,l)=>{if(null==a)return l;let r=String(a).trim();if(""===r||"null"===r.toLowerCase())return null;if(e.has(s)){let e=Number(r);return Number.isNaN(e)?l:e}if(t.has(s)){if(""===r)return null;try{return JSON.parse(r)}catch{return l}}return"true"===r.toLowerCase()||"false"!==r.toLowerCase()&&r})(s,l.value,a);return[s,r]}}else if("routing_strategy"===s)return[s,x.selectedStrategy];else if("enable_tag_filtering"===s)return[s,x.enableTagFiltering];else if("fallbacks"===s)return[s,f.length>0?f:null];else if("routing_strategy_args"===s&&"latency-based-routing"===x.selectedStrategy){let e=document.querySelector('input[name="lowest_latency_buffer"]'),t=document.querySelector('input[name="ttl"]'),s={};return e?.value&&(s.lowest_latency_buffer=Number(e.value)),t?.value&&(s.ttl=Number(t.value)),["routing_strategy_args",Object.keys(s).length>0?s:null]}return[s,a]}).filter(e=>null!=e)),a=(e,t=!1)=>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:f.length>0?f: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:x.enableTagFiltering,routing_strategy_args:a(s.routing_strategy_args)}};(0,s.useEffect)(()=>{if(!p)return;let e=setTimeout(()=>{A.current=!0,p({router_settings:F()})},100);return()=>clearTimeout(e)},[x,f]);let M=Array.from(new Set(v.map(e=>e.model_group))).sort();return((0,s.useImperativeHandle)(h,()=>({getValue:()=>({router_settings:F()})})),e)?(0,t.jsx)("div",{className:"w-full",children:(0,t.jsxs)(r.TabGroup,{className:"w-full",children:[(0,t.jsxs)(i.TabList,{variant:"line",defaultValue:"1",className:"px-8 pt-4",children:[(0,t.jsx)(n.Tab,{value:"1",children:"Loadbalancing"}),(0,t.jsx)(n.Tab,{value:"2",children:"Fallbacks"})]}),(0,t.jsxs)(l.TabPanels,{className:"px-8 py-6",children:[(0,t.jsx)(a.TabPanel,{children:(0,t.jsx)(c.default,{value:x,onChange:y,routerFieldsMetadata:S,availableRoutingStrategies:N,routingStrategyDescriptions:T})}),(0,t.jsx)(a.TabPanel,{children:(0,t.jsx)(d.FallbackSelectionForm,{groups:j,onGroupsChange:e=>{b(e),_(e.filter(e=>e.primaryModel&&e.fallbackModels.length>0).map(e=>({[e.primaryModel]:e.fallbackModels})))},availableModels:M,maxGroups:5})})]})]})}):null});m.displayName="RouterSettingsAccordion",e.s(["default",0,m],460285);var p=e.i(199133),g=e.i(482725),h=e.i(56456);e.s(["default",0,({projects:e,value:s,onChange:a,disabled:l,loading:r,teamId:i})=>{let n=i?e?.filter(e=>e.team_id===i):e;return(0,t.jsx)(p.Select,{showSearch:!0,placeholder:"Search or select a project",value:s,onChange:a,disabled:l,loading:r,allowClear:!0,notFoundContent:r?(0,t.jsx)(g.Spin,{indicator:(0,t.jsx)(h.LoadingOutlined,{spin:!0}),size:"small"}):void 0,filterOption:(e,t)=>{if(!t)return!1;let s=n?.find(e=>e.project_id===t.key);if(!s)return!1;let a=e.toLowerCase().trim(),l=(s.project_alias||"").toLowerCase(),r=(s.project_id||"").toLowerCase();return l.includes(a)||r.includes(a)},optionFilterProp:"children",children:!r&&n?.map(e=>(0,t.jsxs)(p.Select.Option,{value:e.project_id,children:[(0,t.jsx)("span",{className:"font-medium",children:e.project_alias||e.project_id})," ",(0,t.jsxs)("span",{className:"text-gray-500",children:["(",e.project_id,")"]})]},e.project_id))})}],575260)},75921,e=>{"use strict";var t=e.i(843476),s=e.i(266027),a=e.i(243652),l=e.i(764205),r=e.i(135214);let i=(0,a.createQueryKeys)("mcpAccessGroups");var n=e.i(500727),o=e.i(199133);e.s(["default",0,({onChange:e,value:a,className:c,accessToken:d,placeholder:u="Select MCP servers",disabled:m=!1})=>{let{data:p=[],isLoading:g}=(0,n.useMCPServers)(),{data:h=[],isLoading:x}=(()=>{let{accessToken:e}=(0,r.default)();return(0,s.useQuery)({queryKey:i.list({}),queryFn:async()=>await (0,l.fetchMCPAccessGroups)(e),enabled:!!e})})(),y=[...h.map(e=>({label:e,value:e,isAccessGroup:!0,searchText:`${e} Access Group`})),...p.map(e=>({label:`${e.server_name||e.server_id} (${e.server_id})`,value:e.server_id,isAccessGroup:!1,searchText:`${e.server_name||e.server_id} ${e.server_id} MCP Server`}))],f=[...a?.servers||[],...a?.accessGroups||[]];return(0,t.jsx)("div",{children:(0,t.jsx)(o.Select,{mode:"multiple",placeholder:u,onChange:t=>{e({servers:t.filter(e=>!h.includes(e)),accessGroups:t.filter(e=>h.includes(e))})},value:f,loading:g||x,className:c,allowClear:!0,showSearch:!0,style:{width:"100%"},disabled:m,filterOption:(e,t)=>(y.find(e=>e.value===t?.value)?.searchText||"").toLowerCase().includes(e.toLowerCase()),children:y.map(e=>(0,t.jsx)(o.Select.Option,{value:e.value,label:e.label,children:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[(0,t.jsx)("span",{style:{display:"inline-block",width:8,height:8,borderRadius:"50%",background:e.isAccessGroup?"#52c41a":"#1890ff",flexShrink:0}}),(0,t.jsx)("span",{style:{flex:1},children:e.label}),(0,t.jsx)("span",{style:{color:e.isAccessGroup?"#52c41a":"#1890ff",fontSize:"12px",fontWeight:500,opacity:.8},children:e.isAccessGroup?"Access Group":"MCP Server"})]})},e.value))})})}],75921)},390605,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(764205),l=e.i(599724),r=e.i(482725),i=e.i(536916),n=e.i(995926),o=e.i(500727);e.s(["default",0,({accessToken:e,selectedServers:c,toolPermissions:d,onChange:u,disabled:m=!1})=>{let{data:p=[]}=(0,o.useMCPServers)(),[g,h]=(0,s.useState)({}),[x,y]=(0,s.useState)({}),[f,_]=(0,s.useState)({}),j=(0,s.useMemo)(()=>0===c.length?[]:p.filter(e=>c.includes(e.server_id)),[p,c]),b=async t=>{y(e=>({...e,[t]:!0})),_(e=>({...e,[t]:""}));try{let s=await (0,a.listMCPTools)(e,t);s.error?(_(e=>({...e,[t]:s.message||"Failed to fetch tools"})),h(e=>({...e,[t]:[]}))):h(e=>({...e,[t]:s.tools||[]}))}catch(e){console.error(`Error fetching tools for server ${t}:`,e),_(e=>({...e,[t]:"Failed to fetch tools"})),h(e=>({...e,[t]:[]}))}finally{y(e=>({...e,[t]:!1}))}};return((0,s.useEffect)(()=>{j.forEach(e=>{g[e.server_id]||x[e.server_id]||b(e.server_id)})},[j]),0===c.length)?null:(0,t.jsx)("div",{className:"space-y-4",children:j.map(e=>{let s=e.server_name||e.alias||e.server_id,a=g[e.server_id]||[],o=d[e.server_id]||[],c=x[e.server_id],p=f[e.server_id];return(0,t.jsxs)("div",{className:"border rounded-lg bg-gray-50",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between p-4 border-b bg-white rounded-t-lg",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(l.Text,{className:"font-semibold text-gray-900",children:s}),e.description&&(0,t.jsx)(l.Text,{className:"text-sm text-gray-500",children:e.description})]}),(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("button",{type:"button",className:"text-sm text-blue-600 hover:text-blue-700 font-medium",onClick:()=>{var t;let s;return s=g[t=e.server_id]||[],void u({...d,[t]:s.map(e=>e.name)})},disabled:m||c,children:"Select All"}),(0,t.jsx)("button",{type:"button",className:"text-sm text-blue-600 hover:text-blue-700 font-medium",onClick:()=>{var t;return t=e.server_id,void u({...d,[t]:[]})},disabled:m||c,children:"Deselect All"}),(0,t.jsx)("button",{type:"button",className:"text-gray-400 hover:text-gray-600",onClick:()=>{},children:(0,t.jsx)(n.XIcon,{className:"w-4 h-4"})})]})]}),(0,t.jsxs)("div",{className:"p-4",children:[(0,t.jsx)(l.Text,{className:"text-sm font-medium text-gray-700 mb-3",children:"Available Tools"}),c&&(0,t.jsxs)("div",{className:"flex items-center justify-center py-8",children:[(0,t.jsx)(r.Spin,{size:"large"}),(0,t.jsx)(l.Text,{className:"ml-3 text-gray-500",children:"Loading tools..."})]}),p&&!c&&(0,t.jsxs)("div",{className:"p-4 bg-red-50 border border-red-200 rounded-lg text-center",children:[(0,t.jsx)(l.Text,{className:"text-red-600 font-medium",children:"Unable to load tools"}),(0,t.jsx)(l.Text,{className:"text-sm text-red-500 mt-1",children:p})]}),!c&&!p&&a.length>0&&(0,t.jsx)("div",{className:"space-y-2",children:a.map(s=>{let a=o.includes(s.name);return(0,t.jsxs)("div",{className:"flex items-start gap-2",children:[(0,t.jsx)(i.Checkbox,{checked:a,onChange:()=>{var t,a;let l,r;return t=e.server_id,a=s.name,r=(l=d[t]||[]).includes(a)?l.filter(e=>e!==a):[...l,a],void u({...d,[t]:r})},disabled:m}),(0,t.jsx)("div",{className:"flex-1 min-w-0",children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(l.Text,{className:"font-medium text-gray-900",children:s.name}),(0,t.jsxs)(l.Text,{className:"text-sm text-gray-500",children:["- ",s.description||"No description"]})]})})]},s.name)})}),!c&&!p&&0===a.length&&(0,t.jsx)("div",{className:"text-center py-6",children:(0,t.jsx)(l.Text,{className:"text-gray-500",children:"No tools available"})})]})]},e.server_id)})})}])},702597,364769,e=>{"use strict";var t=e.i(843476),s=e.i(207082),a=e.i(510674),l=e.i(292639),r=e.i(135214),i=e.i(500330),n=e.i(827252),o=e.i(912598),c=e.i(677667),d=e.i(130643),u=e.i(898667),m=e.i(994388),p=e.i(309426),g=e.i(350967),h=e.i(599724),x=e.i(779241),y=e.i(629569),f=e.i(464571),_=e.i(808613),j=e.i(311451),b=e.i(212931),v=e.i(91739),w=e.i(199133),N=e.i(790848),k=e.i(262218),S=e.i(592968),C=e.i(374009),T=e.i(271645),I=e.i(708347),A=e.i(552130),L=e.i(557662),F=e.i(9314),M=e.i(860585),P=e.i(82946),O=e.i(392110),E=e.i(533882),$=e.i(844565),B=e.i(651904),V=e.i(939510),D=e.i(460285),G=e.i(663435),R=e.i(575260),K=e.i(371455),U=e.i(355619),q=e.i(75921),z=e.i(390605),W=e.i(727749),H=e.i(764205),Q=e.i(237016),J=e.i(998573);let Y=({apiKey:e})=>{let[s,a]=(0,T.useState)(!1);return(0,t.jsxs)("div",{children:[(0,t.jsxs)("p",{className:"mb-2",children:["Please save this secret key somewhere safe and accessible. For security reasons,"," ",(0,t.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,t.jsx)("p",{className:"text-sm text-gray-600 mt-3 mb-1",children:"Virtual Key:"}),(0,t.jsx)("div",{style:{background:"#f8f8f8",padding:"10px",borderRadius:"5px",marginBottom:"10px"},children:(0,t.jsx)("pre",{style:{wordWrap:"break-word",whiteSpace:"normal",margin:0},children:e})}),(0,t.jsx)(Q.CopyToClipboard,{text:e,onCopy:()=>{a(!0),J.message.success("Key copied to clipboard"),setTimeout(()=>a(!1),2e3)},children:(0,t.jsx)(f.Button,{type:"primary",style:{marginTop:12},children:s?"Copied!":"Copy Virtual Key"})})]})};e.s(["default",0,Y],364769);var X=e.i(435451),Z=e.i(916940);let{Option:ee}=w.Select,et=async(e,t,s,a)=>{try{if(null===e||null===t)return[];if(null!==s){let l=(await (0,H.modelAvailableCall)(s,e,t,!0,a,!0)).data.map(e=>e.id);return console.log("available_model_names:",l),l}return[]}catch(e){return console.error("Error fetching user models:",e),[]}},es=async(e,t,s,a)=>{try{if(null===e||null===t)return;if(null!==s){let l=(await (0,H.modelAvailableCall)(s,e,t)).data.map(e=>e.id);console.log("available_model_names:",l),a(l)}}catch(e){console.error("Error fetching user models:",e)}};e.s(["default",0,({team:e,teams:Q,data:J,addKey:ea,autoOpenCreate:el,prefillData:er})=>{let{accessToken:ei,userId:en,userRole:eo,premiumUser:ec}=(0,r.default)(),ed=ec||null!=eo&&I.rolesWithWriteAccess.includes(eo),{data:eu,isLoading:em}=(0,a.useProjects)(),{data:ep}=(0,l.useUISettings)(),eg=!!ep?.values?.enable_projects_ui,eh=(0,o.useQueryClient)(),[ex]=_.Form.useForm(),[ey,ef]=(0,T.useState)(!1),[e_,ej]=(0,T.useState)(null),[eb,ev]=(0,T.useState)(null),[ew,eN]=(0,T.useState)([]),[ek,eS]=(0,T.useState)([]),[eC,eT]=(0,T.useState)("you"),[eI,eA]=(0,T.useState)((e=>{let t=[];if(console.log("data:",JSON.stringify(e)),e)for(let s of e)s.metadata&&s.metadata.tags&&t.push(...s.metadata.tags);let s=Array.from(new Set(t)).map(e=>({value:e,label:e}));return console.log("uniqueTags:",s),s})(J)),[eL,eF]=(0,T.useState)(!1),[eM,eP]=(0,T.useState)(null),[eO,eE]=(0,T.useState)([]),[e$,eB]=(0,T.useState)([]),[eV,eD]=(0,T.useState)([]),[eG,eR]=(0,T.useState)([]),[eK,eU]=(0,T.useState)(e),[eq,ez]=(0,T.useState)(null),[eW,eH]=(0,T.useState)(!1),[eQ,eJ]=(0,T.useState)(null),[eY,eX]=(0,T.useState)({}),[eZ,e0]=(0,T.useState)([]),[e1,e2]=(0,T.useState)(!1),[e4,e5]=(0,T.useState)([]),[e3,e6]=(0,T.useState)([]),[e7,e9]=(0,T.useState)("llm_api"),[e8,te]=(0,T.useState)({}),[tt,ts]=(0,T.useState)(!1),[ta,tl]=(0,T.useState)("30d"),[tr,ti]=(0,T.useState)(null),[tn,to]=(0,T.useState)(0),[tc,td]=(0,T.useState)([]),[tu,tm]=(0,T.useState)(null),tp=()=>{ef(!1),ex.resetFields(),eR([]),e6([]),e9("llm_api"),te({}),ts(!1),tl("30d"),ti(null),to(e=>e+1),tm(null),ez(null)},tg=()=>{ef(!1),ej(null),eU(null),ex.resetFields(),eR([]),e6([]),e9("llm_api"),te({}),ts(!1),tl("30d"),ti(null),to(e=>e+1),tm(null),ez(null)};(0,T.useEffect)(()=>{en&&eo&&ei&&es(en,eo,ei,eN)},[ei,en,eo]),(0,T.useEffect)(()=>{ei&&(0,H.getAgentsList)(ei).then(e=>td(e?.agents||[])).catch(()=>td([]))},[ei]),(0,T.useEffect)(()=>{let e=async()=>{try{let e=(await (0,H.getPoliciesList)(ei)).policies.map(e=>e.policy_name);eB(e)}catch(e){console.error("Failed to fetch policies:",e)}},t=async()=>{try{let e=await (0,H.getPromptsList)(ei);eD(e.prompts.map(e=>e.prompt_id))}catch(e){console.error("Failed to fetch prompts:",e)}};(async()=>{try{let e=(await (0,H.getGuardrailsList)(ei)).guardrails.map(e=>e.guardrail_name);eE(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})(),e(),t()},[ei]),(0,T.useEffect)(()=>{(async()=>{try{if(ei){let e=sessionStorage.getItem("possibleUserRoles");if(e)eX(JSON.parse(e));else{let e=await (0,H.getPossibleUserRoles)(ei);sessionStorage.setItem("possibleUserRoles",JSON.stringify(e)),eX(e)}}}catch(e){console.error("Error fetching possible user roles:",e)}})()},[ei]),(0,T.useEffect)(()=>{if(el&&!eL&&Q&&eo&&I.rolesWithWriteAccess.includes(eo)&&(ef(!0),eF(!0),er)){if(er.owned_by&&("another_user"===er.owned_by&&"Admin"!==eo?eT("you"):eT(er.owned_by)),er.team_id){let e=Q?.find(e=>e.team_id===er.team_id)||null;e&&(eU(e),ex.setFieldsValue({team_id:er.team_id}))}er.key_alias&&ex.setFieldsValue({key_alias:er.key_alias}),er.models&&er.models.length>0&&eP(er.models),er.key_type&&(e9(er.key_type),ex.setFieldsValue({key_type:er.key_type}))}},[el,er,Q,eL,ex,eo]);let th=ek.includes("no-default-models")&&!eK,tx=async e=>{try{let t,a=e?.key_alias??"",l=e?.team_id??null;if((J?.filter(e=>e.team_id===l).map(e=>e.key_alias)??[]).includes(a))throw Error(`Key alias ${a} already exists for team with ID ${l}, please provide another key alias`);if(W.default.info("Making API Call"),ef(!0),"you"===eC)e.user_id=en;else if("agent"===eC){if(!tu)return void W.default.fromBackend("Please select an agent");e.agent_id=tu}let r={};try{r=JSON.parse(e.metadata||"{}")}catch(e){console.error("Error parsing metadata:",e)}if("service_account"===eC&&(r.service_account_id=e.key_alias),eG.length>0&&(r={...r,logging:eG.filter(e=>e.callback_name)}),e3.length>0){let e=(0,L.mapDisplayToInternalNames)(e3);r={...r,litellm_disabled_callbacks:e}}if(tt&&(e.auto_rotate=!0,e.rotation_interval=ta),e.duration&&""!==e.duration.trim()||(e.duration=null),e.metadata=JSON.stringify(r),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&&(e.allowed_mcp_servers_and_groups.servers?.length>0||e.allowed_mcp_servers_and_groups.accessGroups?.length>0)){e.object_permission||(e.object_permission={});let{servers:t,accessGroups:s}=e.allowed_mcp_servers_and_groups;t&&t.length>0&&(e.object_permission.mcp_servers=t),s&&s.length>0&&(e.object_permission.mcp_access_groups=s),delete e.allowed_mcp_servers_and_groups}let i=e.mcp_tool_permissions||{};if(Object.keys(i).length>0&&(e.object_permission||(e.object_permission={}),e.object_permission.mcp_tool_permissions=i),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&&(e.allowed_agents_and_groups.agents?.length>0||e.allowed_agents_and_groups.accessGroups?.length>0)){e.object_permission||(e.object_permission={});let{agents:t,accessGroups:s}=e.allowed_agents_and_groups;t&&t.length>0&&(e.object_permission.agents=t),s&&s.length>0&&(e.object_permission.agent_access_groups=s),delete e.allowed_agents_and_groups}Object.keys(e8).length>0&&(e.aliases=JSON.stringify(e8)),tr?.router_settings&&Object.values(tr.router_settings).some(e=>null!=e&&""!==e)&&(e.router_settings=tr.router_settings),t="service_account"===eC?await (0,H.keyCreateServiceAccountCall)(ei,e):await (0,H.keyCreateCall)(ei,en,e),console.log("key create Response:",t),ea(t),eh.invalidateQueries({queryKey:s.keyKeys.lists()}),ej(t.key),ev(t.soft_budget),W.default.success("Virtual Key Created"),ex.resetFields(),localStorage.removeItem("userData"+en)}catch(t){console.log("error in create key:",t);let e=(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: ${e}`;let s=t;try{if(!e||"object"!=typeof e||e instanceof Error){let e=t.match(/\{[\s\S]*\}/);if(e){let t=JSON.parse(e[0]),a=t?.error||t;a?.message&&(s=a.message)}}else{let t=e?.error||e;t?.message&&(s=t.message)}}catch(e){}return t.includes("team_member_permission_error")||s.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: ${e}`})(t);W.default.fromBackend(e)}};(0,T.useEffect)(()=>{if(eq){let e=eu?.find(e=>e.project_id===eq);eS(e?.models??[]),ex.setFieldValue("models",[]);return}en&&eo&&ei&&et(en,eo,ei,eK?.team_id??null).then(e=>{eS(Array.from(new Set([...eK?.models??[],...e])))}),eM||ex.setFieldValue("models",[])},[eK,eq,ei,en,eo,ex]),(0,T.useEffect)(()=>{if(!eM||0===eM.length||!ek||0===ek.length)return;let e=eM.filter(e=>ek.includes(e));e.length>0&&ex.setFieldsValue({models:e}),eP(null)},[eM,ek,ex]),(0,T.useEffect)(()=>{if(!eq||!Q)return;let e=eu?.find(e=>e.project_id===eq);if(!e?.team_id||eK?.team_id===e.team_id)return;let t=Q.find(t=>t.team_id===e.team_id)||null;t&&(eU(t),ex.setFieldValue("team_id",t.team_id))},[Q,eq,eu]);let ty=async e=>{if(!e)return void e0([]);e2(!0);try{let t=new URLSearchParams;if(t.append("user_email",e),null==ei)return;let s=(await (0,H.userFilterUICall)(ei,t)).map(e=>({label:`${e.user_email} (${e.user_id})`,value:e.user_id,user:e}));e0(s)}catch(e){console.error("Error fetching users:",e),W.default.fromBackend("Failed to search for users")}finally{e2(!1)}},tf=(0,T.useCallback)((0,C.default)(e=>ty(e),300),[ei]);return(0,t.jsxs)("div",{children:[eo&&I.rolesWithWriteAccess.includes(eo)&&(0,t.jsx)(m.Button,{className:"mx-auto",onClick:()=>ef(!0),children:"+ Create New Key"}),(0,t.jsx)(b.Modal,{open:ey,width:1e3,footer:null,onOk:tp,onCancel:tg,children:(0,t.jsxs)(_.Form,{form:ex,onFinish:tx,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,t.jsxs)("div",{className:"mb-8",children:[(0,t.jsx)(y.Title,{className:"mb-4",children:"Key Ownership"}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Owned By"," ",(0,t.jsx)(S.Tooltip,{title:"Select who will own this Virtual Key",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),className:"mb-4",children:(0,t.jsxs)(v.Radio.Group,{onChange:e=>eT(e.target.value),value:eC,children:[(0,t.jsx)(v.Radio,{value:"you",children:"You"}),(0,t.jsx)(v.Radio,{value:"service_account",children:"Service Account"}),"Admin"===eo&&(0,t.jsx)(v.Radio,{value:"another_user",children:"Another User"}),(0,t.jsxs)(v.Radio,{value:"agent",children:["Agent ",(0,t.jsx)(k.Tag,{color:"purple",children:"New"})]})]})}),"another_user"===eC&&(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["User ID"," ",(0,t.jsx)(S.Tooltip,{title:"The user who will own this key and be responsible for its usage",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"user_id",className:"mt-4",rules:[{required:"another_user"===eC,message:"Please input the user ID of the user you are assigning the key to"}],children:(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{style:{display:"flex",marginBottom:"8px"},children:[(0,t.jsx)(w.Select,{showSearch:!0,placeholder:"Type email to search for users",filterOption:!1,onSearch:e=>{tf(e)},onSelect:(e,t)=>{let s;return s=t.user,void ex.setFieldsValue({user_id:s.user_id})},options:eZ,loading:e1,allowClear:!0,style:{width:"100%"},notFoundContent:e1?"Searching...":"No users found"}),(0,t.jsx)(f.Button,{onClick:()=>eH(!0),style:{marginLeft:"8px"},children:"Create User"})]}),(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"Search by email to find users"})]})}),"agent"===eC&&(0,t.jsxs)("div",{className:"mt-4 p-4 bg-purple-50 border border-purple-200 rounded-md",children:[(0,t.jsx)("div",{className:"mb-3",children:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700",children:["Select Agent ",(0,t.jsx)("span",{className:"text-red-500",children:"*"})]})}),(0,t.jsx)(w.Select,{showSearch:!0,placeholder:"Select an agent",style:{width:"100%"},value:tu,onChange:e=>tm(e),filterOption:(e,t)=>t?.label?.toLowerCase().includes(e.toLowerCase()),options:tc.map(e=>({label:e.agent_name||e.agent_id,value:e.agent_id}))}),(0,t.jsx)("div",{className:"text-xs text-gray-500 mt-2",children:"This key will be used by the selected agent to make requests to LiteLLM"})]}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Team"," ",(0,t.jsx)(S.Tooltip,{title:"The team this key belongs to, which determines available models and budget limits",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"team_id",initialValue:e?e.team_id:null,className:"mt-4",rules:[{required:"service_account"===eC,message:"Please select a team for the service account"}],help:"service_account"===eC?"required":"",children:(0,t.jsx)(G.default,{teams:Q,disabled:null!==eq,loading:!Q,onChange:e=>{eU(Q?.find(t=>t.team_id===e)||null),ez(null),ex.setFieldValue("project_id",void 0)}})}),eg&&(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Project"," ",(0,t.jsx)(S.Tooltip,{title:"Assign this key to a project. Selecting a project will lock the team to the project's team.",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"project_id",className:"mt-4",children:(0,t.jsx)(R.default,{projects:eu,teamId:eK?.team_id,loading:em||!Q,onChange:e=>{if(!e){ez(null),eU(null),ex.setFieldValue("team_id",void 0);return}ez(e)}})})]}),th&&(0,t.jsx)("div",{className:"mb-8 p-4 bg-blue-50 border border-blue-200 rounded-md",children:(0,t.jsx)(h.Text,{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."})}),!th&&(0,t.jsxs)("div",{className:"mb-8",children:[(0,t.jsx)(y.Title,{className:"mb-4",children:"Key Details"}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["you"===eC||"another_user"===eC?"Key Name":"Service Account ID"," ",(0,t.jsx)(S.Tooltip,{title:"you"===eC||"another_user"===eC?"A descriptive name to identify this key":"Unique identifier for this service account",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"key_alias",rules:[{required:!0,message:`Please input a ${"you"===eC?"key name":"service account ID"}`}],help:"required",children:(0,t.jsx)(x.TextInput,{placeholder:""})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Models"," ",(0,t.jsx)(S.Tooltip,{title:"Select which models this key can access. Choose 'All Team Models' to grant access to all models available to the team. Leave empty to allow access to all models.",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"models",rules:[],help:"management"===e7||"read_only"===e7?"Models field is disabled for this key type":"optional - leave empty to allow access to all models",className:"mt-4",children:(0,t.jsxs)(w.Select,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},disabled:"management"===e7||"read_only"===e7,onChange:e=>{e.includes("all-team-models")&&ex.setFieldsValue({models:["all-team-models"]})},children:[!eq&&(0,t.jsx)(ee,{value:"all-team-models",children:"All Team Models"},"all-team-models"),ek.map(e=>(0,t.jsx)(ee,{value:e,children:(0,U.getModelDisplayName)(e)},e))]})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Key Type"," ",(0,t.jsx)(S.Tooltip,{title:"Select the type of key to determine what routes and operations this key can access",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"key_type",initialValue:"llm_api",className:"mt-4",children:(0,t.jsxs)(w.Select,{defaultValue:"llm_api",placeholder:"Select key type",style:{width:"100%"},optionLabelProp:"label",onChange:e=>{e9(e),("management"===e||"read_only"===e)&&ex.setFieldsValue({models:[]})},children:[(0,t.jsx)(ee,{value:"default",label:"Default",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Default"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call AI APIs + Management routes"})]})}),(0,t.jsx)(ee,{value:"llm_api",label:"AI APIs",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"AI APIs"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call only AI API routes (chat/completions, embeddings, etc.)"})]})}),(0,t.jsx)(ee,{value:"management",label:"Management",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Management"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call only management routes (user/team/key management)"})]})})]})})]}),!th&&(0,t.jsx)("div",{className:"mb-8",children:(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)(y.Title,{className:"m-0",children:"Optional Settings"})}),(0,t.jsxs)(d.AccordionBody,{children:[(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Max Budget (USD)"," ",(0,t.jsx)(S.Tooltip,{title:"Maximum amount in USD this key can spend. When reached, the key will be blocked from making further requests",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"max_budget",help:`Budget cannot exceed team max budget: $${e?.max_budget!==null&&e?.max_budget!==void 0?e?.max_budget:"unlimited"}`,rules:[{validator:async(t,s)=>{if(s&&e&&null!==e.max_budget&&s>e.max_budget)throw Error(`Budget cannot exceed team max budget: $${(0,i.formatNumberWithCommas)(e.max_budget,4)}`)}}],children:(0,t.jsx)(X.default,{step:.01,precision:2,width:200})}),(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Reset Budget"," ",(0,t.jsx)(S.Tooltip,{title:"How often the budget should reset. For example, setting 'daily' will reset the budget every 24 hours",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"budget_duration",help:`Team Reset Budget: ${e?.budget_duration!==null&&e?.budget_duration!==void 0?e?.budget_duration:"None"}`,children:(0,t.jsx)(M.default,{onChange:e=>ex.setFieldValue("budget_duration",e)})}),(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Tokens per minute Limit (TPM)"," ",(0,t.jsx)(S.Tooltip,{title:"Maximum number of tokens this key can process per minute. Helps control usage and costs",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"tpm_limit",help:`TPM cannot exceed team TPM limit: ${e?.tpm_limit!==null&&e?.tpm_limit!==void 0?e?.tpm_limit:"unlimited"}`,rules:[{validator:async(t,s)=>{if(s&&e&&null!==e.tpm_limit&&s>e.tpm_limit)throw Error(`TPM limit cannot exceed team TPM limit: ${e.tpm_limit}`)}}],children:(0,t.jsx)(X.default,{step:1,width:400})}),(0,t.jsx)(V.default,{type:"tpm",name:"tpm_limit_type",className:"mt-4",initialValue:null,form:ex,showDetailedDescriptions:!0}),(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Requests per minute Limit (RPM)"," ",(0,t.jsx)(S.Tooltip,{title:"Maximum number of API requests this key can make per minute. Helps prevent abuse and manage load",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"rpm_limit",help:`RPM cannot exceed team RPM limit: ${e?.rpm_limit!==null&&e?.rpm_limit!==void 0?e?.rpm_limit:"unlimited"}`,rules:[{validator:async(t,s)=>{if(s&&e&&null!==e.rpm_limit&&s>e.rpm_limit)throw Error(`RPM limit cannot exceed team RPM limit: ${e.rpm_limit}`)}}],children:(0,t.jsx)(X.default,{step:1,width:400})}),(0,t.jsx)(V.default,{type:"rpm",name:"rpm_limit_type",className:"mt-4",initialValue:null,form:ex,showDetailedDescriptions:!0}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Guardrails"," ",(0,t.jsx)(S.Tooltip,{title:"Apply safety guardrails to this key to filter content or enforce policies",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",className:"mt-4",help:ed?"Select existing guardrails or enter new ones":"Premium feature - Upgrade to set guardrails by key",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},disabled:!ed,placeholder:ed?"Select or enter guardrails":"Premium feature - Upgrade to set guardrails by key",options:eO.map(e=>({value:e,label:e}))})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Disable Global Guardrails"," ",(0,t.jsx)(S.Tooltip,{title:"When enabled, this key will bypass any guardrails configured to run on every request (global guardrails)",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"disable_global_guardrails",className:"mt-4",valuePropName:"checked",help:ed?"Bypass global guardrails for this key":"Premium feature - Upgrade to disable global guardrails by key",children:(0,t.jsx)(N.Switch,{disabled:!ed,checkedChildren:"Yes",unCheckedChildren:"No"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Policies"," ",(0,t.jsx)(S.Tooltip,{title:"Apply policies to this key to control guardrails and other settings",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/guardrail_policies",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"policies",className:"mt-4",help:ec?"Select existing policies or enter new ones":"Premium feature - Upgrade to set policies by key",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},disabled:!ec,placeholder:ec?"Select or enter policies":"Premium feature - Upgrade to set policies by key",options:e$.map(e=>({value:e,label:e}))})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Prompts"," ",(0,t.jsx)(S.Tooltip,{title:"Allow this key to use specific prompt templates",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/prompt_management",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"prompts",className:"mt-4",help:ec?"Select existing prompts or enter new ones":"Premium feature - Upgrade to set prompts by key",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},disabled:!ec,placeholder:ec?"Select or enter prompts":"Premium feature - Upgrade to set prompts by key",options:eV.map(e=>({value:e,label:e}))})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Access Groups"," ",(0,t.jsx)(S.Tooltip,{title:"Assign access groups to this key. Access groups control which models, MCP servers, and agents this key can use",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"access_group_ids",className:"mt-4",help:"Select access groups to assign to this key",children:(0,t.jsx)(F.default,{placeholder:"Select access groups (optional)"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Pass Through Routes"," ",(0,t.jsx)(S.Tooltip,{title:"Allow this key to use specific pass through routes",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/pass_through",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"allowed_passthrough_routes",className:"mt-4",help:ec?"Select existing pass through routes or enter new ones":"Premium feature - Upgrade to set pass through routes by key",children:(0,t.jsx)($.default,{onChange:e=>ex.setFieldValue("allowed_passthrough_routes",e),value:ex.getFieldValue("allowed_passthrough_routes"),accessToken:ei,placeholder:ec?"Select or enter pass through routes":"Premium feature - Upgrade to set pass through routes by key",disabled:!ec,teamId:eK?eK.team_id:null})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Vector Stores"," ",(0,t.jsx)(S.Tooltip,{title:"Select which vector stores this key can access. If none selected, the key will have access to all available vector stores",children:(0,t.jsx)(n.InfoCircleOutlined,{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,t.jsx)(Z.default,{onChange:e=>ex.setFieldValue("allowed_vector_store_ids",e),value:ex.getFieldValue("allowed_vector_store_ids"),accessToken:ei,placeholder:"Select vector stores (optional)"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Metadata"," ",(0,t.jsx)(S.Tooltip,{title:"JSON object with additional information about this key. Used for tracking or custom logic",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"metadata",className:"mt-4",children:(0,t.jsx)(j.Input.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Tags"," ",(0,t.jsx)(S.Tooltip,{title:"Tags for tracking spend and/or doing tag-based routing. Used for analytics and filtering",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"tags",className:"mt-4",help:"Tags for tracking spend and/or doing tag-based routing.",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},placeholder:"Enter tags",tokenSeparators:[","],options:eI})}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"MCP Settings"})}),(0,t.jsxs)(d.AccordionBody,{children:[(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed MCP Servers"," ",(0,t.jsx)(S.Tooltip,{title:"Select which MCP servers or access groups this key can access",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_mcp_servers_and_groups",help:"Select MCP servers or access groups this key can access",children:(0,t.jsx)(q.default,{onChange:e=>ex.setFieldValue("allowed_mcp_servers_and_groups",e),value:ex.getFieldValue("allowed_mcp_servers_and_groups"),accessToken:ei,placeholder:"Select MCP servers or access groups (optional)"})}),(0,t.jsx)(_.Form.Item,{name:"mcp_tool_permissions",initialValue:{},hidden:!0,children:(0,t.jsx)(j.Input,{type:"hidden"})}),(0,t.jsx)(_.Form.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:()=>(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(z.default,{accessToken:ei,selectedServers:ex.getFieldValue("allowed_mcp_servers_and_groups")?.servers||[],toolPermissions:ex.getFieldValue("mcp_tool_permissions")||{},onChange:e=>ex.setFieldsValue({mcp_tool_permissions:e})})})})]})]}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Agent Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Agents"," ",(0,t.jsx)(S.Tooltip,{title:"Select which agents or access groups this key can access",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_agents_and_groups",help:"Select agents or access groups this key can access",children:(0,t.jsx)(A.default,{onChange:e=>ex.setFieldValue("allowed_agents_and_groups",e),value:ex.getFieldValue("allowed_agents_and_groups"),accessToken:ei,placeholder:"Select agents or access groups (optional)"})})})]}),ec?(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Logging Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(B.default,{value:eG,onChange:eR,premiumUser:!0,disabledCallbacks:e3,onDisabledCallbacksChange:e6})})})]}):(0,t.jsx)(S.Tooltip,{title:(0,t.jsxs)("span",{children:["Key-level logging settings is an enterprise feature, get in touch -",(0,t.jsx)("a",{href:"https://www.litellm.ai/enterprise",target:"_blank",children:"https://www.litellm.ai/enterprise"})]}),placement:"top",children:(0,t.jsxs)("div",{style:{position:"relative"},children:[(0,t.jsx)("div",{style:{opacity:.5},children:(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Logging Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(B.default,{value:eG,onChange:eR,premiumUser:!1,disabledCallbacks:e3,onDisabledCallbacksChange:e6})})})]})}),(0,t.jsx)("div",{style:{position:"absolute",inset:0,cursor:"not-allowed"}})]})}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Router Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4 w-full",children:(0,t.jsx)(D.default,{accessToken:ei||"",value:tr||void 0,onChange:ti,modelData:ew.length>0?{data:ew.map(e=>({model_name:e}))}:void 0},tn)})})]},`router-settings-accordion-${tn}`),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Model Aliases"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsxs)("div",{className:"mt-4",children:[(0,t.jsx)(h.Text,{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,t.jsx)(E.default,{accessToken:ei,initialModelAliases:e8,onAliasUpdate:te,showExampleConfig:!1})]})})]}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Key Lifecycle"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(O.default,{form:ex,autoRotationEnabled:tt,onAutoRotationChange:ts,rotationInterval:ta,onRotationIntervalChange:tl,isCreateMode:!0})})}),(0,t.jsx)(_.Form.Item,{name:"duration",hidden:!0,initialValue:null,children:(0,t.jsx)(j.Input,{})})]}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("b",{children:"Advanced Settings"}),(0,t.jsx)(S.Tooltip,{title:(0,t.jsxs)("span",{children:["Learn more about advanced settings in our"," ",(0,t.jsx)("a",{href:H.proxyBaseUrl?`${H.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,t.jsx)(n.InfoCircleOutlined,{className:"text-gray-400 hover:text-gray-300 cursor-help"})})]})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)(P.default,{schemaComponent:"GenerateKeyRequest",form:ex,excludedFields:["key_alias","team_id","models","duration","metadata","tags","guardrails","max_budget","budget_duration","tpm_limit","rpm_limit"]})})]})]})]})}),(0,t.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,t.jsx)(f.Button,{htmlType:"submit",disabled:th,style:{opacity:th?.5:1},children:"Create Key"})})]})}),eW&&(0,t.jsx)(b.Modal,{title:"Create New User",open:eW,onCancel:()=>eH(!1),footer:null,width:800,children:(0,t.jsx)(K.CreateUserButton,{userID:en,accessToken:ei,teams:Q,possibleUIRoles:eY,onUserCreated:e=>{eJ(e),ex.setFieldsValue({user_id:e}),eH(!1)},isEmbedded:!0})}),e_&&(0,t.jsx)(b.Modal,{open:ey,onOk:tp,onCancel:tg,footer:null,children:(0,t.jsxs)(g.Grid,{numItems:1,className:"gap-2 w-full",children:[(0,t.jsx)(y.Title,{children:"Save your Key"}),(0,t.jsx)(p.Col,{numColSpan:1,children:null!=e_?(0,t.jsx)(Y,{apiKey:e_}):(0,t.jsx)(h.Text,{children:"Key being created, this might take 30s"})})]})})]})},"fetchTeamModels",0,et,"fetchUserModels",0,es],702597)}]); \ No newline at end of file +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,207082,e=>{"use strict";var t=e.i(619273),s=e.i(266027),a=e.i(243652),l=e.i(764205),r=e.i(135214);let i=(0,a.createQueryKeys)("keys"),n=async(e,t,s,a={})=>{try{let r=(0,l.getProxyBaseUrl)(),i=new URLSearchParams(Object.entries({team_id:a.teamID,project_id:a.projectID,organization_id:a.organizationID,key_alias:a.selectedKeyAlias,key_hash:a.keyHash,user_id:a.userID,page:t,size:s,sort_by:a.sortBy,sort_order:a.sortOrder,expand:a.expand,status:a.status,return_full_object:"true",include_team_keys:"true",include_created_by_keys:"true"}).filter(([,e])=>null!=e).map(([e,t])=>[e,String(t)])),n=`${r?`${r}/key/list`:"/key/list"}?${i}`,o=await fetch(n,{method:"GET",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!o.ok){let e=await o.json(),t=(0,l.deriveErrorMessage)(e);throw(0,l.handleError)(t),Error(t)}let c=await o.json();return console.log("/key/list API Response:",c),c}catch(e){throw console.error("Failed to list keys:",e),e}},o=(0,a.createQueryKeys)("deletedKeys");e.s(["keyKeys",0,i,"useDeletedKeys",0,(e,a,l={})=>{let{accessToken:i}=(0,r.default)();return(0,s.useQuery)({queryKey:o.list({page:e,limit:a,...l}),queryFn:async()=>await n(i,e,a,{...l,status:"deleted"}),enabled:!!i,staleTime:3e4,placeholderData:t.keepPreviousData})},"useKeys",0,(e,a,l={})=>{let{accessToken:o}=(0,r.default)();return(0,s.useQuery)({queryKey:i.list({page:e,limit:a,...l}),queryFn:async()=>await n(o,e,a,l),enabled:!!o,staleTime:3e4,placeholderData:t.keepPreviousData})}])},510674,e=>{"use strict";var t=e.i(266027),s=e.i(243652),a=e.i(764205),l=e.i(708347),r=e.i(135214);let i=(0,s.createQueryKeys)("projects"),n=async e=>{let t=(0,a.getProxyBaseUrl)(),s=`${t}/project/list`,l=await fetch(s,{method:"GET",headers:{[(0,a.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!l.ok){let e=await l.json(),t=(0,a.deriveErrorMessage)(e);throw(0,a.handleError)(t),Error(t)}return l.json()};e.s(["projectKeys",0,i,"useProjects",0,()=>{let{accessToken:e,userRole:s}=(0,r.default)();return(0,t.useQuery)({queryKey:i.list({}),queryFn:async()=>n(e),enabled:!!e&&l.all_admin_roles.includes(s||"")})}])},552130,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(199133),l=e.i(764205);e.s(["default",0,({onChange:e,value:r,className:i,accessToken:n,placeholder:o="Select agents",disabled:c=!1})=>{let[d,u]=(0,s.useState)([]),[m,p]=(0,s.useState)([]),[g,h]=(0,s.useState)(!1);(0,s.useEffect)(()=>{(async()=>{if(n){h(!0);try{let e=await (0,l.getAgentsList)(n),t=e?.agents||[];u(t);let s=new Set;t.forEach(e=>{let t=e.agent_access_groups;t&&Array.isArray(t)&&t.forEach(e=>s.add(e))}),p(Array.from(s))}catch(e){console.error("Error fetching agents:",e)}finally{h(!1)}}})()},[n]);let x=[...m.map(e=>({label:e,value:`group:${e}`,isAccessGroup:!0,searchText:`${e} Access Group`})),...d.map(e=>({label:`${e.agent_name||e.agent_id}`,value:e.agent_id,isAccessGroup:!1,searchText:`${e.agent_name||e.agent_id} ${e.agent_id} Agent`}))],y=[...r?.agents||[],...(r?.accessGroups||[]).map(e=>`group:${e}`)];return(0,t.jsx)("div",{children:(0,t.jsx)(a.Select,{mode:"multiple",placeholder:o,onChange:t=>{e({agents:t.filter(e=>!e.startsWith("group:")),accessGroups:t.filter(e=>e.startsWith("group:")).map(e=>e.replace("group:",""))})},value:y,loading:g,className:i,allowClear:!0,showSearch:!0,style:{width:"100%"},disabled:c,filterOption:(e,t)=>(x.find(e=>e.value===t?.value)?.searchText||"").toLowerCase().includes(e.toLowerCase()),children:x.map(e=>(0,t.jsx)(a.Select.Option,{value:e.value,label:e.label,children:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[(0,t.jsx)("span",{style:{display:"inline-block",width:8,height:8,borderRadius:"50%",background:e.isAccessGroup?"#52c41a":"#722ed1",flexShrink:0}}),(0,t.jsx)("span",{style:{flex:1},children:e.label}),(0,t.jsx)("span",{style:{color:e.isAccessGroup?"#52c41a":"#722ed1",fontSize:"12px",fontWeight:500,opacity:.8},children:e.isAccessGroup?"Access Group":"Agent"})]})},e.value))})})}])},557662,e=>{"use strict";let t="../ui/assets/logos/",s=[{id:"arize",displayName:"Arize",logo:`${t}arize.png`,supports_key_team_logging:!0,dynamic_params:{arize_api_key:"password",arize_space_id:"password"},description:"Arize Logging Integration"},{id:"braintrust",displayName:"Braintrust",logo:`${t}braintrust.png`,supports_key_team_logging:!1,dynamic_params:{braintrust_api_key:"password",braintrust_project_name:"text"},description:"Braintrust Logging Integration"},{id:"custom_callback_api",displayName:"Custom Callback API",logo:`${t}custom.svg`,supports_key_team_logging:!0,dynamic_params:{custom_callback_api_url:"text",custom_callback_api_headers:"text"},description:"Custom Callback API Logging Integration"},{id:"datadog",displayName:"Datadog",logo:`${t}datadog.png`,supports_key_team_logging:!1,dynamic_params:{dd_api_key:"password",dd_site:"text"},description:"Datadog Logging Integration"},{id:"lago",displayName:"Lago",logo:`${t}lago.svg`,supports_key_team_logging:!1,dynamic_params:{lago_api_url:"text",lago_api_key:"password"},description:"Lago Billing Logging Integration"},{id:"langfuse",displayName:"Langfuse",logo:`${t}langfuse.png`,supports_key_team_logging:!0,dynamic_params:{langfuse_public_key:"text",langfuse_secret_key:"password",langfuse_host:"text"},description:"Langfuse v2 Logging Integration"},{id:"langfuse_otel",displayName:"Langfuse OTEL",logo:`${t}langfuse.png`,supports_key_team_logging:!0,dynamic_params:{langfuse_public_key:"text",langfuse_secret_key:"password",langfuse_host:"text"},description:"Langfuse v3 OTEL Logging Integration"},{id:"langsmith",displayName:"LangSmith",logo:`${t}langsmith.png`,supports_key_team_logging:!0,dynamic_params:{langsmith_api_key:"password",langsmith_project:"text",langsmith_base_url:"text",langsmith_sampling_rate:"number"},description:"Langsmith Logging Integration"},{id:"openmeter",displayName:"OpenMeter",logo:`${t}openmeter.png`,supports_key_team_logging:!1,dynamic_params:{openmeter_api_key:"password",openmeter_base_url:"text"},description:"OpenMeter Logging Integration"},{id:"otel",displayName:"Open Telemetry",logo:`${t}otel.png`,supports_key_team_logging:!1,dynamic_params:{otel_endpoint:"text",otel_headers:"text"},description:"OpenTelemetry Logging Integration"},{id:"s3",displayName:"S3",logo:`${t}aws.svg`,supports_key_team_logging:!1,dynamic_params:{s3_bucket_name:"text",aws_access_key_id:"password",aws_secret_access_key:"password",aws_region:"text"},description:"S3 Bucket (AWS) Logging Integration"},{id:"SQS",displayName:"SQS",logo:`${t}aws.svg`,supports_key_team_logging:!1,dynamic_params:{sqs_queue_url:"text",aws_access_key_id:"password",aws_secret_access_key:"password",aws_region:"text"},description:"SQS Queue (AWS) Logging Integration"}],a=s.reduce((e,t)=>(e[t.displayName]=t,e),{}),l=s.reduce((e,t)=>(e[t.displayName]=t.id,e),{}),r=s.reduce((e,t)=>(e[t.id]=t.displayName,e),{});e.s(["callbackInfo",0,a,"callback_map",0,l,"mapDisplayToInternalNames",0,e=>e.map(e=>l[e]||e),"mapInternalToDisplayNames",0,e=>e.map(e=>r[e]||e),"reverse_callback_map",0,r])},9314,263147,e=>{"use strict";var t=e.i(843476),s=e.i(199133),a=e.i(981339),l=e.i(645526),r=e.i(599724),i=e.i(266027),n=e.i(243652),o=e.i(764205),c=e.i(708347),d=e.i(135214);let u=(0,n.createQueryKeys)("accessGroups"),m=async e=>{let t=(0,o.getProxyBaseUrl)(),s=`${t}/v1/access_group`,a=await fetch(s,{method:"GET",headers:{[(0,o.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(!a.ok){let e=await a.json(),t=(0,o.deriveErrorMessage)(e);throw(0,o.handleError)(t),Error(t)}return a.json()},p=()=>{let{accessToken:e,userRole:t}=(0,d.default)();return(0,i.useQuery)({queryKey:u.list({}),queryFn:async()=>m(e),enabled:!!e&&c.all_admin_roles.includes(t||"")})};e.s(["accessGroupKeys",0,u,"useAccessGroups",0,p],263147),e.s(["default",0,({value:e,onChange:i,placeholder:n="Select access groups",disabled:o=!1,style:c,className:d,showLabel:u=!1,labelText:m="Access Group",allowClear:g=!0})=>{let{data:h,isLoading:x,isError:y}=p();if(x)return(0,t.jsxs)("div",{children:[u&&(0,t.jsxs)(r.Text,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,t.jsx)(l.TeamOutlined,{className:"mr-2"})," ",m]}),(0,t.jsx)(a.Skeleton.Input,{active:!0,block:!0,style:{height:32,...c}})]});let f=(h??[]).map(e=>({label:(0,t.jsxs)("span",{children:[(0,t.jsx)("span",{className:"font-medium",children:e.access_group_name})," ",(0,t.jsxs)("span",{className:"text-gray-400 text-xs",children:["(",e.access_group_id,")"]})]}),value:e.access_group_id,selectedLabel:e.access_group_name,searchText:`${e.access_group_name} ${e.access_group_id}`}));return(0,t.jsxs)("div",{children:[u&&(0,t.jsxs)(r.Text,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,t.jsx)(l.TeamOutlined,{className:"mr-2"})," ",m]}),(0,t.jsx)(s.Select,{mode:"multiple",value:e,placeholder:n,onChange:i,disabled:o,allowClear:g,showSearch:!0,style:{width:"100%",...c},className:`rounded-md ${d??""}`,notFoundContent:y?(0,t.jsx)("span",{className:"text-red-500",children:"Failed to load access groups"}):"No access groups found",filterOption:(e,t)=>(f.find(e=>e.value===t?.value)?.searchText??"").toLowerCase().includes(e.toLowerCase()),optionLabelProp:"selectedLabel",options:f.map(e=>({label:e.label,value:e.value,selectedLabel:e.selectedLabel}))})]})}],9314)},392110,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(199133),l=e.i(592968),r=e.i(312361),i=e.i(790848),n=e.i(536916),o=e.i(827252),c=e.i(779241);let{Option:d}=a.Select;e.s(["default",0,({form:e,autoRotationEnabled:u,onAutoRotationChange:m,rotationInterval:p,onRotationIntervalChange:g,isCreateMode:h=!1,neverExpire:x=!1,onNeverExpireChange:y})=>{let f=p&&!["7d","30d","90d","180d","365d"].includes(p),[_,j]=(0,s.useState)(f),[b,v]=(0,s.useState)(f?p:""),[w,N]=(0,s.useState)(e?.getFieldValue?.("duration")||"");return(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Key Expiry Settings"}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,t.jsx)("span",{children:"Expire Key"}),(0,t.jsx)(l.Tooltip,{title:"Set when this key should expire. Format: 30s (seconds), 30m (minutes), 30h (hours), 30d (days). Leave empty to keep the current expiry unchanged.",children:(0,t.jsx)(o.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})}),!h&&y&&(0,t.jsx)(n.Checkbox,{checked:x,onChange:t=>{let s=t.target.checked;y(s),s&&(N(""),e&&"function"==typeof e.setFieldValue?e.setFieldValue("duration",""):e&&"function"==typeof e.setFieldsValue&&e.setFieldsValue({duration:""}))},className:"ml-2 text-sm font-normal text-gray-600",children:"Never Expire"})]}),(0,t.jsx)(c.TextInput,{name:"duration",placeholder:h?"e.g., 30d or leave empty to never expire":"e.g., 30d",className:"w-full",value:w,onValueChange:t=>{N(t),e&&"function"==typeof e.setFieldValue?e.setFieldValue("duration",t):e&&"function"==typeof e.setFieldsValue&&e.setFieldsValue({duration:t})},disabled:!h&&x})]})]}),(0,t.jsx)(r.Divider,{}),(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Auto-Rotation Settings"}),(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,t.jsx)("span",{children:"Enable Auto-Rotation"}),(0,t.jsx)(l.Tooltip,{title:"Key will automatically regenerate at the specified interval for enhanced security.",children:(0,t.jsx)(o.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})})]}),(0,t.jsx)(i.Switch,{checked:u,onChange:m,size:"default",className:u?"":"bg-gray-400"})]}),u&&(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 flex items-center space-x-1",children:[(0,t.jsx)("span",{children:"Rotation Interval"}),(0,t.jsx)(l.Tooltip,{title:"How often the key should be automatically rotated. Choose the interval that best fits your security requirements.",children:(0,t.jsx)(o.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)(a.Select,{value:_?"custom":p,onChange:e=>{"custom"===e?j(!0):(j(!1),v(""),g(e))},className:"w-full",placeholder:"Select interval",children:[(0,t.jsx)(d,{value:"7d",children:"7 days"}),(0,t.jsx)(d,{value:"30d",children:"30 days"}),(0,t.jsx)(d,{value:"90d",children:"90 days"}),(0,t.jsx)(d,{value:"180d",children:"180 days"}),(0,t.jsx)(d,{value:"365d",children:"365 days"}),(0,t.jsx)(d,{value:"custom",children:"Custom interval"})]}),_&&(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(c.TextInput,{value:b,onChange:e=>{let t=e.target.value;v(t),g(t)},placeholder:"e.g., 1s, 5m, 2h, 14d"}),(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"Supported formats: seconds (s), minutes (m), hours (h), days (d)"})]})]})]})]}),u&&(0,t.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."})]})]})}])},533882,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(250980),l=e.i(797672),r=e.i(68155),i=e.i(304967),n=e.i(629569),o=e.i(599724),c=e.i(269200),d=e.i(427612),u=e.i(64848),m=e.i(942232),p=e.i(496020),g=e.i(977572),h=e.i(992619),x=e.i(727749);e.s(["default",0,({accessToken:e,initialModelAliases:y={},onAliasUpdate:f,showExampleConfig:_=!0})=>{let[j,b]=(0,s.useState)([]),[v,w]=(0,s.useState)({aliasName:"",targetModel:""}),[N,k]=(0,s.useState)(null);(0,s.useEffect)(()=>{b(Object.entries(y).map(([e,t],s)=>({id:`${s}-${e}`,aliasName:e,targetModel:t})))},[y]);let S=()=>{if(!N)return;if(!N.aliasName||!N.targetModel)return void x.default.fromBackend("Please provide both alias name and target model");if(j.some(e=>e.id!==N.id&&e.aliasName===N.aliasName))return void x.default.fromBackend("An alias with this name already exists");let e=j.map(e=>e.id===N.id?N:e);b(e),k(null);let t={};e.forEach(e=>{t[e.aliasName]=e.targetModel}),f&&f(t),x.default.success("Alias updated successfully")},C=()=>{k(null)},T=j.reduce((e,t)=>(e[t.aliasName]=t.targetModel,e),{});return(0,t.jsxs)("div",{className:"mt-4",children:[(0,t.jsxs)("div",{className:"mb-6",children:[(0,t.jsx)(o.Text,{className:"text-sm font-medium text-gray-700 mb-2",children:"Add New Alias"}),(0,t.jsxs)("div",{className:"grid grid-cols-3 gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-xs text-gray-500 mb-1",children:"Alias Name"}),(0,t.jsx)("input",{type:"text",value:v.aliasName,onChange:e=>w({...v,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,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-xs text-gray-500 mb-1",children:"Target Model"}),(0,t.jsx)(h.default,{accessToken:e,value:v.targetModel,placeholder:"Select target model",onChange:e=>w({...v,targetModel:e}),showLabel:!1})]}),(0,t.jsx)("div",{className:"flex items-end",children:(0,t.jsxs)("button",{onClick:()=>{if(!v.aliasName||!v.targetModel)return void x.default.fromBackend("Please provide both alias name and target model");if(j.some(e=>e.aliasName===v.aliasName))return void x.default.fromBackend("An alias with this name already exists");let e=[...j,{id:`${Date.now()}-${v.aliasName}`,aliasName:v.aliasName,targetModel:v.targetModel}];b(e),w({aliasName:"",targetModel:""});let t={};e.forEach(e=>{t[e.aliasName]=e.targetModel}),f&&f(t),x.default.success("Alias added successfully")},disabled:!v.aliasName||!v.targetModel,className:`flex items-center px-4 py-2 rounded-md text-sm ${!v.aliasName||!v.targetModel?"bg-gray-300 text-gray-500 cursor-not-allowed":"bg-green-600 text-white hover:bg-green-700"}`,children:[(0,t.jsx)(a.PlusCircleIcon,{className:"w-4 h-4 mr-1"}),"Add Alias"]})})]})]}),(0,t.jsx)(o.Text,{className:"text-sm font-medium text-gray-700 mb-2",children:"Manage Existing Aliases"}),(0,t.jsx)("div",{className:"rounded-lg custom-border relative mb-6",children:(0,t.jsx)("div",{className:"overflow-x-auto",children:(0,t.jsxs)(c.Table,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,t.jsx)(d.TableHead,{children:(0,t.jsxs)(p.TableRow,{children:[(0,t.jsx)(u.TableHeaderCell,{className:"py-1 h-8",children:"Alias Name"}),(0,t.jsx)(u.TableHeaderCell,{className:"py-1 h-8",children:"Target Model"}),(0,t.jsx)(u.TableHeaderCell,{className:"py-1 h-8",children:"Actions"})]})}),(0,t.jsxs)(m.TableBody,{children:[j.map(s=>(0,t.jsx)(p.TableRow,{className:"h-8",children:N&&N.id===s.id?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(g.TableCell,{className:"py-0.5",children:(0,t.jsx)("input",{type:"text",value:N.aliasName,onChange:e=>k({...N,aliasName:e.target.value}),className:"w-full px-2 py-1 border border-gray-300 rounded-md text-sm"})}),(0,t.jsx)(g.TableCell,{className:"py-0.5",children:(0,t.jsx)(h.default,{accessToken:e,value:N.targetModel,onChange:e=>k({...N,targetModel:e}),showLabel:!1,style:{height:"32px"}})}),(0,t.jsx)(g.TableCell,{className:"py-0.5 whitespace-nowrap",children:(0,t.jsxs)("div",{className:"flex space-x-2",children:[(0,t.jsx)("button",{onClick:S,className:"text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded hover:bg-blue-100",children:"Save"}),(0,t.jsx)("button",{onClick:C,className:"text-xs bg-gray-50 text-gray-600 px-2 py-1 rounded hover:bg-gray-100",children:"Cancel"})]})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(g.TableCell,{className:"py-0.5 text-sm text-gray-900",children:s.aliasName}),(0,t.jsx)(g.TableCell,{className:"py-0.5 text-sm text-gray-500",children:s.targetModel}),(0,t.jsx)(g.TableCell,{className:"py-0.5 whitespace-nowrap",children:(0,t.jsxs)("div",{className:"flex space-x-2",children:[(0,t.jsx)("button",{onClick:()=>{k({...s})},className:"text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded hover:bg-blue-100",children:(0,t.jsx)(l.PencilIcon,{className:"w-3 h-3"})}),(0,t.jsx)("button",{onClick:()=>{var e;let t,a;return e=s.id,b(t=j.filter(t=>t.id!==e)),a={},void(t.forEach(e=>{a[e.aliasName]=e.targetModel}),f&&f(a),x.default.success("Alias deleted successfully"))},className:"text-xs bg-red-50 text-red-600 px-2 py-1 rounded hover:bg-red-100",children:(0,t.jsx)(r.TrashIcon,{className:"w-3 h-3"})})]})})]})},s.id)),0===j.length&&(0,t.jsx)(p.TableRow,{children:(0,t.jsx)(g.TableCell,{colSpan:3,className:"py-0.5 text-sm text-gray-500 text-center",children:"No aliases added yet. Add a new alias above."})})]})]})})}),_&&(0,t.jsxs)(i.Card,{children:[(0,t.jsx)(n.Title,{className:"mb-4",children:"Configuration Example"}),(0,t.jsx)(o.Text,{className:"text-gray-600 mb-4",children:"Here's how your current aliases would look in the config:"}),(0,t.jsx)("div",{className:"bg-gray-100 rounded-lg p-4 font-mono text-sm",children:(0,t.jsxs)("div",{className:"text-gray-700",children:["model_aliases:",0===Object.keys(T).length?(0,t.jsxs)("span",{className:"text-gray-500",children:[(0,t.jsx)("br",{}),"  # No aliases configured yet"]}):Object.entries(T).map(([e,s])=>(0,t.jsxs)("span",{children:[(0,t.jsx)("br",{}),'  "',e,'": "',s,'"']},e))]})})]})]})}])},844565,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(199133),l=e.i(764205);e.s(["default",0,({onChange:e,value:r,className:i,accessToken:n,placeholder:o="Select pass through routes",disabled:c=!1,teamId:d})=>{let[u,m]=(0,s.useState)([]),[p,g]=(0,s.useState)(!1);return(0,s.useEffect)(()=>{(async()=>{if(n){g(!0);try{let e=await (0,l.getPassThroughEndpointsCall)(n,d);if(e.endpoints){let t=e.endpoints.flatMap(e=>{let t=e.path,s=e.methods;return s&&s.length>0?s.map(e=>({label:`${e} ${t}`,value:t})):[{label:t,value:t}]});m(t)}}catch(e){console.error("Error fetching pass through routes:",e)}finally{g(!1)}}})()},[n,d]),(0,t.jsx)(a.Select,{mode:"tags",placeholder:o,onChange:e,value:r,loading:p,className:i,allowClear:!0,options:u,optionFilterProp:"label",showSearch:!0,style:{width:"100%"},disabled:c})}])},810757,477386,e=>{"use strict";var t=e.i(271645);let s=t.forwardRef(function(e,s){return t.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:s},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}))});e.s(["CogIcon",0,s],810757);let a=t.forwardRef(function(e,s){return t.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:s},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"}))});e.s(["BanIcon",0,a],477386)},266484,e=>{"use strict";var t=e.i(843476),s=e.i(199133),a=e.i(592968),l=e.i(312361),r=e.i(827252),i=e.i(994388),n=e.i(304967),o=e.i(779241),c=e.i(988297),d=e.i(68155),u=e.i(810757),m=e.i(477386),p=e.i(557662),g=e.i(435451);let{Option:h}=s.Select;e.s(["default",0,({value:e=[],onChange:x,disabledCallbacks:y=[],onDisabledCallbacksChange:f})=>{let _=Object.entries(p.callbackInfo).filter(([e,t])=>t.supports_key_team_logging).map(([e,t])=>e),j=Object.keys(p.callbackInfo),b=e=>{x?.(e)},v=(t,s,a)=>{let l=[...e];if("callback_name"===s){let e=p.callback_map[a]||a;l[t]={...l[t],[s]:e,callback_vars:{}}}else l[t]={...l[t],[s]:a};b(l)},w=(t,s,a)=>{let l=[...e];l[t]={...l[t],callback_vars:{...l[t].callback_vars,[s]:a}},b(l)};return(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)(m.BanIcon,{className:"w-5 h-5 text-red-500"}),(0,t.jsx)("span",{className:"text-base font-semibold text-gray-800",children:"Disabled Callbacks"}),(0,t.jsx)(a.Tooltip,{title:"Select callbacks to disable for this key. Disabled callbacks will not receive any logging data.",children:(0,t.jsx)(r.InfoCircleOutlined,{className:"text-gray-400 cursor-help"})})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{className:"text-sm font-medium text-gray-700",children:"Disabled Callbacks"}),(0,t.jsx)(s.Select,{mode:"multiple",placeholder:"Select callbacks to disable",value:y,onChange:e=>{let t=(0,p.mapDisplayToInternalNames)(e);f?.(t)},style:{width:"100%"},optionLabelProp:"label",children:j.map(e=>{let s=p.callbackInfo[e]?.logo,l=p.callbackInfo[e]?.description;return(0,t.jsx)(h,{value:e,label:e,children:(0,t.jsx)(a.Tooltip,{title:l,placement:"right",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[s&&(0,t.jsx)("img",{src:s,alt:e,className:"w-4 h-4 object-contain",onError:t=>{let s=t.target,a=s.parentElement;if(a){let t=document.createElement("div");t.className="w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",t.textContent=e.charAt(0),a.replaceChild(t,s)}}}),(0,t.jsx)("span",{children:e})]})})},e)})}),(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"Select callbacks that should be disabled for this key. These callbacks will not receive any logging data."})]})]}),(0,t.jsx)(l.Divider,{}),(0,t.jsxs)("div",{className:"flex justify-between items-center",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)(u.CogIcon,{className:"w-5 h-5 text-blue-500"}),(0,t.jsx)("span",{className:"text-base font-semibold text-gray-800",children:"Logging Integrations"}),(0,t.jsx)(a.Tooltip,{title:"Configure callback logging integrations for this team.",children:(0,t.jsx)(r.InfoCircleOutlined,{className:"text-gray-400 cursor-help"})})]}),(0,t.jsx)(i.Button,{variant:"secondary",onClick:()=>{b([...e,{callback_name:"",callback_type:"success",callback_vars:{}}])},icon:c.PlusIcon,size:"sm",className:"hover:border-blue-400 hover:text-blue-500",type:"button",children:"Add Integration"})]}),(0,t.jsx)("div",{className:"space-y-4",children:e.map((l,c)=>{let u=l.callback_name?Object.entries(p.callback_map).find(([e,t])=>t===l.callback_name)?.[0]:void 0,m=u?p.callbackInfo[u]?.logo:null;return(0,t.jsxs)(n.Card,{className:"border border-gray-200 shadow-sm hover:shadow-md transition-shadow duration-200",decoration:"top",decorationColor:"blue",children:[(0,t.jsxs)("div",{className:"flex justify-between items-start mb-4",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[m&&(0,t.jsx)("img",{src:m,alt:u,className:"w-5 h-5 object-contain"}),(0,t.jsxs)("span",{className:"text-sm font-medium",children:[u||"New Integration"," Configuration"]})]}),(0,t.jsx)(i.Button,{variant:"light",onClick:()=>{b(e.filter((e,t)=>t!==c))},icon:d.TrashIcon,size:"xs",color:"red",className:"hover:bg-red-50",type:"button",children:"Remove"})]}),(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{className:"text-sm font-medium text-gray-700",children:"Integration Type"}),(0,t.jsx)(s.Select,{value:u,placeholder:"Select integration",onChange:e=>v(c,"callback_name",e),className:"w-full",optionLabelProp:"label",children:_.map(e=>{let s=p.callbackInfo[e]?.logo,l=p.callbackInfo[e]?.description;return(0,t.jsx)(h,{value:e,label:e,children:(0,t.jsx)(a.Tooltip,{title:l,placement:"right",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[s&&(0,t.jsx)("img",{src:s,alt:e,className:"w-4 h-4 object-contain",onError:t=>{let s=t.target,a=s.parentElement;if(a){let t=document.createElement("div");t.className="w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",t.textContent=e.charAt(0),a.replaceChild(t,s)}}}),(0,t.jsx)("span",{children:e})]})})},e)})})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{className:"text-sm font-medium text-gray-700",children:"Event Type"}),(0,t.jsxs)(s.Select,{value:l.callback_type,onChange:e=>v(c,"callback_type",e),className:"w-full",children:[(0,t.jsx)(h,{value:"success",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-green-500 rounded-full"}),(0,t.jsx)("span",{children:"Success Only"})]})}),(0,t.jsx)(h,{value:"failure",children:(0,t.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,t.jsx)("div",{className:"w-2 h-2 bg-red-500 rounded-full"}),(0,t.jsx)("span",{children:"Failure Only"})]})}),(0,t.jsx)(h,{value:"success_and_failure",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)("span",{children:"Success & Failure"})]})})]})]})]}),((e,s)=>{if(!e.callback_name)return null;let l=Object.entries(p.callback_map).find(([t,s])=>s===e.callback_name)?.[0];if(!l)return null;let i=p.callbackInfo[l]?.dynamic_params||{};return 0===Object.keys(i).length?null:(0,t.jsxs)("div",{className:"mt-6 pt-4 border-t border-gray-100",children:[(0,t.jsxs)("div",{className:"flex items-center space-x-2 mb-4",children:[(0,t.jsx)("div",{className:"w-3 h-3 bg-blue-100 rounded-full flex items-center justify-center",children:(0,t.jsx)("div",{className:"w-1.5 h-1.5 bg-blue-500 rounded-full"})}),(0,t.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Integration Parameters"})]}),(0,t.jsx)("div",{className:"grid grid-cols-1 gap-4",children:Object.entries(i).map(([l,i])=>(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-gray-700 capitalize flex items-center space-x-1",children:[(0,t.jsx)("span",{children:l.replace(/_/g," ")}),(0,t.jsx)(a.Tooltip,{title:`Environment variable reference recommended: os.environ/${l.toUpperCase()}`,children:(0,t.jsx)(r.InfoCircleOutlined,{className:"text-gray-400 cursor-help text-xs"})}),"password"===i&&(0,t.jsx)("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-800",children:"Sensitive"}),"number"===i&&(0,t.jsx)("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-800",children:"Number"})]}),"number"===i&&(0,t.jsx)("span",{className:"text-xs text-gray-500",children:"Value must be between 0 and 1"}),"number"===i?(0,t.jsx)(g.default,{step:.01,width:400,placeholder:`os.environ/${l.toUpperCase()}`,value:e.callback_vars[l]||"",onChange:e=>w(s,l,e.target.value)}):(0,t.jsx)(o.TextInput,{type:"password"===i?"password":"text",placeholder:`os.environ/${l.toUpperCase()}`,value:e.callback_vars[l]||"",onChange:e=>w(s,l,e.target.value)})]},l))})]})})(l,c)]})]},c)})}),0===e.length&&(0,t.jsxs)("div",{className:"text-center py-12 text-gray-500 border-2 border-dashed border-gray-200 rounded-lg bg-gray-50/50",children:[(0,t.jsx)(u.CogIcon,{className:"w-12 h-12 text-gray-300 mb-3 mx-auto"}),(0,t.jsx)("div",{className:"text-base font-medium mb-1",children:"No logging integrations configured"}),(0,t.jsx)("div",{className:"text-sm text-gray-400",children:'Click "Add Integration" to configure logging for this team'})]})]})}])},651904,e=>{"use strict";var t=e.i(843476),s=e.i(599724),a=e.i(266484);e.s(["default",0,function({value:e,onChange:l,premiumUser:r=!1,disabledCallbacks:i=[],onDisabledCallbacksChange:n}){return r?(0,t.jsx)(a.default,{value:e,onChange:l,disabledCallbacks:i,onDisabledCallbacksChange:n}):(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex flex-wrap gap-2 mb-3",children:[(0,t.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,t.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,t.jsx)("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-lg",children:(0,t.jsxs)(s.Text,{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,t.jsx)("a",{href:"https://www.litellm.ai/#pricing",target:"_blank",rel:"noopener noreferrer",className:"underline",children:"here"}),"."]})})]})}])},939510,e=>{"use strict";var t=e.i(843476),s=e.i(808613),a=e.i(199133),l=e.i(592968),r=e.i(827252);let{Option:i}=a.Select;e.s(["default",0,({type:e,name:n,showDetailedDescriptions:o=!0,className:c="",initialValue:d=null,form:u,onChange:m})=>{let p=e.toUpperCase(),g=e.toLowerCase(),h=`Select 'guaranteed_throughput' to prevent overallocating ${p} limit when the key belongs to a Team with specific ${p} limits.`;return(0,t.jsx)(s.Form.Item,{label:(0,t.jsxs)("span",{children:[p," Rate Limit Type"," ",(0,t.jsx)(l.Tooltip,{title:h,children:(0,t.jsx)(r.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:n,initialValue:d,className:c,children:(0,t.jsx)(a.Select,{defaultValue:o?"default":void 0,placeholder:"Select rate limit type",style:{width:"100%"},optionLabelProp:o?"label":void 0,onChange:e=>{u&&u.setFieldValue(n,e),m&&m(e)},children:o?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(i,{value:"best_effort_throughput",label:"Default",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Default"}),(0,t.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["Best effort throughput - no error if we're overallocating ",g," (Team/Key Limits checked at runtime)."]})]})}),(0,t.jsx)(i,{value:"guaranteed_throughput",label:"Guaranteed throughput",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Guaranteed throughput"}),(0,t.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["Guaranteed throughput - raise an error if we're overallocating ",g," (also checks model-specific limits)"]})]})}),(0,t.jsx)(i,{value:"dynamic",label:"Dynamic",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Dynamic"}),(0,t.jsxs)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:["If the key has a set ",p," (e.g. 2 ",p,") and there are no 429 errors, it can dynamically exceed the limit when the model being called is not erroring."]})]})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(i,{value:"best_effort_throughput",children:"Best effort throughput"}),(0,t.jsx)(i,{value:"guaranteed_throughput",children:"Guaranteed throughput"}),(0,t.jsx)(i,{value:"dynamic",children:"Dynamic"})]})})})}])},460285,575260,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(404206),l=e.i(723731),r=e.i(653824),i=e.i(881073),n=e.i(197647),o=e.i(764205),c=e.i(158392),d=e.i(419470),u=e.i(689020);let m=(0,s.forwardRef)(({accessToken:e,value:m,onChange:p,modelData:g},h)=>{let[x,y]=(0,s.useState)({routerSettings:{},selectedStrategy:null,enableTagFiltering:!1}),[f,_]=(0,s.useState)([]),[j,b]=(0,s.useState)([]),[v,w]=(0,s.useState)([]),[N,k]=(0,s.useState)([]),[S,C]=(0,s.useState)({}),[T,I]=(0,s.useState)({}),A=(0,s.useRef)(!1),L=(0,s.useRef)(null);(0,s.useEffect)(()=>{let e=m?.router_settings?JSON.stringify({routing_strategy:m.router_settings.routing_strategy,fallbacks:m.router_settings.fallbacks,enable_tag_filtering:m.router_settings.enable_tag_filtering}):null;if(A.current&&e===L.current){A.current=!1;return}if(A.current&&e!==L.current&&(A.current=!1),e!==L.current)if(L.current=e,m?.router_settings){let e=m.router_settings,{fallbacks:t,...s}=e;y({routerSettings:s,selectedStrategy:e.routing_strategy||null,enableTagFiltering:e.enable_tag_filtering??!1});let a=e.fallbacks||[];_(a),b(a&&0!==a.length?a.map((e,t)=>{let[s,a]=Object.entries(e)[0];return{id:(t+1).toString(),primaryModel:s||null,fallbackModels:a||[]}}):[{id:"1",primaryModel:null,fallbackModels:[]}])}else y({routerSettings:{},selectedStrategy:null,enableTagFiltering:!1}),_([]),b([{id:"1",primaryModel:null,fallbackModels:[]}])},[m]),(0,s.useEffect)(()=>{e&&(0,o.getRouterSettingsCall)(e).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}}),C(t);let s=e.fields.find(e=>"routing_strategy"===e.field_name);s?.options&&k(s.options),e.routing_strategy_descriptions&&I(e.routing_strategy_descriptions)}})},[e]),(0,s.useEffect)(()=>{e&&(async()=>{try{let t=await (0,u.fetchAvailableModels)(e);w(t)}catch(e){console.error("Error fetching model info for fallbacks:",e)}})()},[e]);let F=()=>{let e=new Set(["allowed_fails","cooldown_time","num_retries","timeout","retry_after"]),t=new Set(["model_group_alias","retry_policy"]),s=Object.fromEntries(Object.entries({...x.routerSettings,enable_tag_filtering:x.enableTagFiltering,routing_strategy:x.selectedStrategy,fallbacks:f.length>0?f:null}).map(([s,a])=>{if("routing_strategy_args"!==s&&"routing_strategy"!==s&&"enable_tag_filtering"!==s&&"fallbacks"!==s){let l=document.querySelector(`input[name="${s}"]`);if(l&&void 0!==l.value&&""!==l.value){let r=((s,a,l)=>{if(null==a)return l;let r=String(a).trim();if(""===r||"null"===r.toLowerCase())return null;if(e.has(s)){let e=Number(r);return Number.isNaN(e)?l:e}if(t.has(s)){if(""===r)return null;try{return JSON.parse(r)}catch{return l}}return"true"===r.toLowerCase()||"false"!==r.toLowerCase()&&r})(s,l.value,a);return[s,r]}}else if("routing_strategy"===s)return[s,x.selectedStrategy];else if("enable_tag_filtering"===s)return[s,x.enableTagFiltering];else if("fallbacks"===s)return[s,f.length>0?f:null];else if("routing_strategy_args"===s&&"latency-based-routing"===x.selectedStrategy){let e=document.querySelector('input[name="lowest_latency_buffer"]'),t=document.querySelector('input[name="ttl"]'),s={};return e?.value&&(s.lowest_latency_buffer=Number(e.value)),t?.value&&(s.ttl=Number(t.value)),["routing_strategy_args",Object.keys(s).length>0?s:null]}return[s,a]}).filter(e=>null!=e)),a=(e,t=!1)=>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:f.length>0?f: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:x.enableTagFiltering,routing_strategy_args:a(s.routing_strategy_args)}};(0,s.useEffect)(()=>{if(!p)return;let e=setTimeout(()=>{A.current=!0,p({router_settings:F()})},100);return()=>clearTimeout(e)},[x,f]);let M=Array.from(new Set(v.map(e=>e.model_group))).sort();return((0,s.useImperativeHandle)(h,()=>({getValue:()=>({router_settings:F()})})),e)?(0,t.jsx)("div",{className:"w-full",children:(0,t.jsxs)(r.TabGroup,{className:"w-full",children:[(0,t.jsxs)(i.TabList,{variant:"line",defaultValue:"1",className:"px-8 pt-4",children:[(0,t.jsx)(n.Tab,{value:"1",children:"Loadbalancing"}),(0,t.jsx)(n.Tab,{value:"2",children:"Fallbacks"})]}),(0,t.jsxs)(l.TabPanels,{className:"px-8 py-6",children:[(0,t.jsx)(a.TabPanel,{children:(0,t.jsx)(c.default,{value:x,onChange:y,routerFieldsMetadata:S,availableRoutingStrategies:N,routingStrategyDescriptions:T})}),(0,t.jsx)(a.TabPanel,{children:(0,t.jsx)(d.FallbackSelectionForm,{groups:j,onGroupsChange:e=>{b(e),_(e.filter(e=>e.primaryModel&&e.fallbackModels.length>0).map(e=>({[e.primaryModel]:e.fallbackModels})))},availableModels:M,maxGroups:5})})]})]})}):null});m.displayName="RouterSettingsAccordion",e.s(["default",0,m],460285);var p=e.i(199133),g=e.i(482725),h=e.i(56456);e.s(["default",0,({projects:e,value:s,onChange:a,disabled:l,loading:r,teamId:i})=>{let n=i?e?.filter(e=>e.team_id===i):e;return(0,t.jsx)(p.Select,{showSearch:!0,placeholder:"Search or select a project",value:s,onChange:a,disabled:l,loading:r,allowClear:!0,notFoundContent:r?(0,t.jsx)(g.Spin,{indicator:(0,t.jsx)(h.LoadingOutlined,{spin:!0}),size:"small"}):void 0,filterOption:(e,t)=>{if(!t)return!1;let s=n?.find(e=>e.project_id===t.key);if(!s)return!1;let a=e.toLowerCase().trim(),l=(s.project_alias||"").toLowerCase(),r=(s.project_id||"").toLowerCase();return l.includes(a)||r.includes(a)},optionFilterProp:"children",children:!r&&n?.map(e=>(0,t.jsxs)(p.Select.Option,{value:e.project_id,children:[(0,t.jsx)("span",{className:"font-medium",children:e.project_alias||e.project_id})," ",(0,t.jsxs)("span",{className:"text-gray-500",children:["(",e.project_id,")"]})]},e.project_id))})}],575260)},75921,e=>{"use strict";var t=e.i(843476),s=e.i(266027),a=e.i(243652),l=e.i(764205),r=e.i(135214);let i=(0,a.createQueryKeys)("mcpAccessGroups");var n=e.i(500727),o=e.i(199133);e.s(["default",0,({onChange:e,value:a,className:c,accessToken:d,placeholder:u="Select MCP servers",disabled:m=!1,teamId:p})=>{let{data:g=[],isLoading:h}=(0,n.useMCPServers)(p),{data:x=[],isLoading:y}=(()=>{let{accessToken:e}=(0,r.default)();return(0,s.useQuery)({queryKey:i.list({}),queryFn:async()=>await (0,l.fetchMCPAccessGroups)(e),enabled:!!e})})(),f=[...x.map(e=>({label:e,value:e,isAccessGroup:!0,searchText:`${e} Access Group`})),...g.map(e=>({label:`${e.server_name||e.server_id} (${e.server_id})`,value:e.server_id,isAccessGroup:!1,searchText:`${e.server_name||e.server_id} ${e.server_id} MCP Server`}))],_=[...a?.servers||[],...a?.accessGroups||[]];return(0,t.jsx)("div",{children:(0,t.jsx)(o.Select,{mode:"multiple",placeholder:u,onChange:t=>{e({servers:t.filter(e=>!x.includes(e)),accessGroups:t.filter(e=>x.includes(e))})},value:_,loading:h||y,className:c,allowClear:!0,showSearch:!0,style:{width:"100%"},disabled:m,filterOption:(e,t)=>(f.find(e=>e.value===t?.value)?.searchText||"").toLowerCase().includes(e.toLowerCase()),children:f.map(e=>(0,t.jsx)(o.Select.Option,{value:e.value,label:e.label,children:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[(0,t.jsx)("span",{style:{display:"inline-block",width:8,height:8,borderRadius:"50%",background:e.isAccessGroup?"#52c41a":"#1890ff",flexShrink:0}}),(0,t.jsx)("span",{style:{flex:1},children:e.label}),(0,t.jsx)("span",{style:{color:e.isAccessGroup?"#52c41a":"#1890ff",fontSize:"12px",fontWeight:500,opacity:.8},children:e.isAccessGroup?"Access Group":"MCP Server"})]})},e.value))})})}],75921)},390605,e=>{"use strict";var t=e.i(843476),s=e.i(271645),a=e.i(764205),l=e.i(599724),r=e.i(482725),i=e.i(91739),n=e.i(500727),o=e.i(531516),c=e.i(696609);e.s(["default",0,({accessToken:e,selectedServers:d,toolPermissions:u,onChange:m,disabled:p=!1})=>{let{data:g=[]}=(0,n.useMCPServers)(),[h,x]=(0,s.useState)({}),[y,f]=(0,s.useState)({}),[_,j]=(0,s.useState)({}),[b,v]=(0,s.useState)({}),w=(0,s.useRef)(u);(0,s.useEffect)(()=>{w.current=u},[u]);let N=(0,s.useMemo)(()=>0===d.length?[]:g.filter(e=>d.includes(e.server_id)),[g,d]),k=async(e,t)=>{f(t=>({...t,[e]:!0})),j(t=>({...t,[e]:""}));try{let s=await (0,a.listMCPTools)(t,e);if(s.error)j(t=>({...t,[e]:s.message||"Failed to fetch tools"})),x(t=>({...t,[e]:[]}));else{let t=s.tools||[];x(s=>({...s,[e]:t}));let a=w.current;if(!a[e]&&t.length>0){let s=t.filter(e=>"delete"!==(0,c.classifyToolOp)(e.name,e.description||"")).map(e=>e.name);m({...a,[e]:s})}}}catch(t){console.error(`Error fetching tools for server ${e}:`,t),j(t=>({...t,[e]:"Failed to fetch tools"})),x(t=>({...t,[e]:[]}))}finally{f(t=>({...t,[e]:!1}))}};(0,s.useEffect)(()=>{N.forEach(t=>{h[t.server_id]||y[t.server_id]||k(t.server_id,e)})},[N,e]);let S=(e,t)=>{m({...u,[e]:t})};return 0===d.length?null:(0,t.jsx)("div",{className:"space-y-4",children:N.map(e=>{let s=e.server_name||e.alias||e.server_id,a=h[e.server_id]||[],n=u[e.server_id]||[],c=y[e.server_id],d=_[e.server_id],g=b[e.server_id]??"crud";return(0,t.jsxs)("div",{className:"border rounded-lg bg-gray-50",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between p-4 border-b bg-white rounded-t-lg",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(l.Text,{className:"font-semibold text-gray-900",children:s}),e.description&&(0,t.jsx)(l.Text,{className:"text-sm text-gray-500",children:e.description})]}),(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[!p&&a.length>0&&(0,t.jsx)(i.Radio.Group,{value:g,onChange:t=>v(s=>({...s,[e.server_id]:t.target.value})),size:"small",optionType:"button",buttonStyle:"solid",options:[{label:"Risk Groups",value:"crud"},{label:"Flat List",value:"flat"}]}),!p&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("button",{type:"button",className:"text-sm text-blue-600 hover:text-blue-700 font-medium",onClick:()=>{var t;let s;return s=h[t=e.server_id]||[],void m({...u,[t]:s.map(e=>e.name)})},disabled:c,children:"Select All"}),(0,t.jsx)("button",{type:"button",className:"text-sm text-blue-600 hover:text-blue-700 font-medium",onClick:()=>{var t;return t=e.server_id,void m({...u,[t]:[]})},disabled:c,children:"Deselect All"})]})]})]}),(0,t.jsxs)("div",{className:"p-4",children:[c&&(0,t.jsxs)("div",{className:"flex items-center justify-center py-8",children:[(0,t.jsx)(r.Spin,{size:"large"}),(0,t.jsx)(l.Text,{className:"ml-3 text-gray-500",children:"Loading tools..."})]}),d&&!c&&(0,t.jsxs)("div",{className:"p-4 bg-red-50 border border-red-200 rounded-lg text-center",children:[(0,t.jsx)(l.Text,{className:"text-red-600 font-medium",children:"Unable to load tools"}),(0,t.jsx)(l.Text,{className:"text-sm text-red-500 mt-1",children:d})]}),!c&&!d&&a.length>0&&"crud"===g&&(0,t.jsx)(o.default,{tools:a,value:u[e.server_id]?n:void 0,onChange:t=>S(e.server_id,t),readOnly:p}),!c&&!d&&a.length>0&&"flat"===g&&(0,t.jsx)("div",{className:"space-y-2",children:a.map(s=>{let a=n.includes(s.name);return(0,t.jsxs)("div",{className:"flex items-start gap-2",children:[(0,t.jsx)("input",{type:"checkbox",checked:a,onChange:()=>{if(p)return;let t=a?n.filter(e=>e!==s.name):[...n,s.name];S(e.server_id,t)},disabled:p,className:"mt-0.5"}),(0,t.jsx)("div",{className:"flex-1 min-w-0",children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(l.Text,{className:"font-medium text-gray-900",children:s.name}),(0,t.jsxs)(l.Text,{className:"text-sm text-gray-500",children:["- ",s.description||"No description"]})]})})]},s.name)})}),!c&&!d&&0===a.length&&(0,t.jsx)("div",{className:"text-center py-6",children:(0,t.jsx)(l.Text,{className:"text-gray-500",children:"No tools available"})})]})]},e.server_id)})})}])},702597,364769,e=>{"use strict";var t=e.i(843476),s=e.i(207082),a=e.i(510674),l=e.i(292639),r=e.i(135214),i=e.i(500330),n=e.i(827252),o=e.i(912598),c=e.i(677667),d=e.i(130643),u=e.i(898667),m=e.i(994388),p=e.i(309426),g=e.i(350967),h=e.i(599724),x=e.i(779241),y=e.i(629569),f=e.i(464571),_=e.i(808613),j=e.i(311451),b=e.i(212931),v=e.i(91739),w=e.i(199133),N=e.i(790848),k=e.i(262218),S=e.i(592968),C=e.i(374009),T=e.i(271645),I=e.i(708347),A=e.i(552130),L=e.i(557662),F=e.i(9314),M=e.i(860585),O=e.i(82946),P=e.i(392110),E=e.i(533882),$=e.i(844565),V=e.i(651904),B=e.i(939510),G=e.i(460285),R=e.i(663435),D=e.i(575260),K=e.i(371455),U=e.i(355619),q=e.i(75921),z=e.i(390605),W=e.i(727749),H=e.i(764205),Q=e.i(237016),J=e.i(998573);let Y=({apiKey:e})=>{let[s,a]=(0,T.useState)(!1);return(0,t.jsxs)("div",{children:[(0,t.jsxs)("p",{className:"mb-2",children:["Please save this secret key somewhere safe and accessible. For security reasons,"," ",(0,t.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,t.jsx)("p",{className:"text-sm text-gray-600 mt-3 mb-1",children:"Virtual Key:"}),(0,t.jsx)("div",{style:{background:"#f8f8f8",padding:"10px",borderRadius:"5px",marginBottom:"10px"},children:(0,t.jsx)("pre",{style:{wordWrap:"break-word",whiteSpace:"normal",margin:0},children:e})}),(0,t.jsx)(Q.CopyToClipboard,{text:e,onCopy:()=>{a(!0),J.message.success("Key copied to clipboard"),setTimeout(()=>a(!1),2e3)},children:(0,t.jsx)(f.Button,{type:"primary",style:{marginTop:12},children:s?"Copied!":"Copy Virtual Key"})})]})};e.s(["default",0,Y],364769);var X=e.i(435451),Z=e.i(916940);let{Option:ee}=w.Select,et=async(e,t,s,a)=>{try{if(null===e||null===t)return[];if(null!==s){let l=(await (0,H.modelAvailableCall)(s,e,t,!0,a,!0)).data.map(e=>e.id);return console.log("available_model_names:",l),l}return[]}catch(e){return console.error("Error fetching user models:",e),[]}},es=async(e,t,s,a)=>{try{if(null===e||null===t)return;if(null!==s){let l=(await (0,H.modelAvailableCall)(s,e,t)).data.map(e=>e.id);console.log("available_model_names:",l),a(l)}}catch(e){console.error("Error fetching user models:",e)}};e.s(["default",0,({team:e,teams:Q,data:J,addKey:ea,autoOpenCreate:el,prefillData:er})=>{let{accessToken:ei,userId:en,userRole:eo,premiumUser:ec}=(0,r.default)(),ed=ec||null!=eo&&I.rolesWithWriteAccess.includes(eo),{data:eu,isLoading:em}=(0,a.useProjects)(),{data:ep}=(0,l.useUISettings)(),eg=!!ep?.values?.enable_projects_ui,eh=(0,o.useQueryClient)(),[ex]=_.Form.useForm(),[ey,ef]=(0,T.useState)(!1),[e_,ej]=(0,T.useState)(null),[eb,ev]=(0,T.useState)(null),[ew,eN]=(0,T.useState)([]),[ek,eS]=(0,T.useState)([]),[eC,eT]=(0,T.useState)("you"),[eI,eA]=(0,T.useState)((e=>{let t=[];if(console.log("data:",JSON.stringify(e)),e)for(let s of e)s.metadata&&s.metadata.tags&&t.push(...s.metadata.tags);let s=Array.from(new Set(t)).map(e=>({value:e,label:e}));return console.log("uniqueTags:",s),s})(J)),[eL,eF]=(0,T.useState)(!1),[eM,eO]=(0,T.useState)(null),[eP,eE]=(0,T.useState)([]),[e$,eV]=(0,T.useState)([]),[eB,eG]=(0,T.useState)([]),[eR,eD]=(0,T.useState)([]),[eK,eU]=(0,T.useState)(e),[eq,ez]=(0,T.useState)(null),[eW,eH]=(0,T.useState)(!1),[eQ,eJ]=(0,T.useState)(null),[eY,eX]=(0,T.useState)({}),[eZ,e0]=(0,T.useState)([]),[e1,e2]=(0,T.useState)(!1),[e4,e5]=(0,T.useState)([]),[e3,e6]=(0,T.useState)([]),[e7,e9]=(0,T.useState)("llm_api"),[e8,te]=(0,T.useState)({}),[tt,ts]=(0,T.useState)(!1),[ta,tl]=(0,T.useState)("30d"),[tr,ti]=(0,T.useState)(null),[tn,to]=(0,T.useState)(0),[tc,td]=(0,T.useState)([]),[tu,tm]=(0,T.useState)(null),tp=()=>{ef(!1),ex.resetFields(),eD([]),e6([]),e9("llm_api"),te({}),ts(!1),tl("30d"),ti(null),to(e=>e+1),tm(null),ez(null)},tg=()=>{ef(!1),ej(null),eU(null),ex.resetFields(),eD([]),e6([]),e9("llm_api"),te({}),ts(!1),tl("30d"),ti(null),to(e=>e+1),tm(null),ez(null)};(0,T.useEffect)(()=>{en&&eo&&ei&&es(en,eo,ei,eN)},[ei,en,eo]),(0,T.useEffect)(()=>{ei&&(0,H.getAgentsList)(ei).then(e=>td(e?.agents||[])).catch(()=>td([]))},[ei]),(0,T.useEffect)(()=>{let e=async()=>{try{let e=(await (0,H.getPoliciesList)(ei)).policies.map(e=>e.policy_name);eV(e)}catch(e){console.error("Failed to fetch policies:",e)}},t=async()=>{try{let e=await (0,H.getPromptsList)(ei);eG(e.prompts.map(e=>e.prompt_id))}catch(e){console.error("Failed to fetch prompts:",e)}};(async()=>{try{let e=(await (0,H.getGuardrailsList)(ei)).guardrails.map(e=>e.guardrail_name);eE(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})(),e(),t()},[ei]),(0,T.useEffect)(()=>{(async()=>{try{if(ei){let e=sessionStorage.getItem("possibleUserRoles");if(e)eX(JSON.parse(e));else{let e=await (0,H.getPossibleUserRoles)(ei);sessionStorage.setItem("possibleUserRoles",JSON.stringify(e)),eX(e)}}}catch(e){console.error("Error fetching possible user roles:",e)}})()},[ei]),(0,T.useEffect)(()=>{if(el&&!eL&&Q&&eo&&I.rolesWithWriteAccess.includes(eo)&&(ef(!0),eF(!0),er)){if(er.owned_by&&("another_user"===er.owned_by&&"Admin"!==eo?eT("you"):eT(er.owned_by)),er.team_id){let e=Q?.find(e=>e.team_id===er.team_id)||null;e&&(eU(e),ex.setFieldsValue({team_id:er.team_id}))}er.key_alias&&ex.setFieldsValue({key_alias:er.key_alias}),er.models&&er.models.length>0&&eO(er.models),er.key_type&&(e9(er.key_type),ex.setFieldsValue({key_type:er.key_type}))}},[el,er,Q,eL,ex,eo]);let th=ek.includes("no-default-models")&&!eK,tx=async e=>{try{let t,a=e?.key_alias??"",l=e?.team_id??null;if((J?.filter(e=>e.team_id===l).map(e=>e.key_alias)??[]).includes(a))throw Error(`Key alias ${a} already exists for team with ID ${l}, please provide another key alias`);if(W.default.info("Making API Call"),ef(!0),"you"===eC)e.user_id=en;else if("agent"===eC){if(!tu)return void W.default.fromBackend("Please select an agent");e.agent_id=tu}let r={};try{r=JSON.parse(e.metadata||"{}")}catch(e){console.error("Error parsing metadata:",e)}if("service_account"===eC&&(r.service_account_id=e.key_alias),eR.length>0&&(r={...r,logging:eR.filter(e=>e.callback_name)}),e3.length>0){let e=(0,L.mapDisplayToInternalNames)(e3);r={...r,litellm_disabled_callbacks:e}}if(tt&&(e.auto_rotate=!0,e.rotation_interval=ta),e.duration&&""!==e.duration.trim()||(e.duration=null),e.metadata=JSON.stringify(r),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&&(e.allowed_mcp_servers_and_groups.servers?.length>0||e.allowed_mcp_servers_and_groups.accessGroups?.length>0)){e.object_permission||(e.object_permission={});let{servers:t,accessGroups:s}=e.allowed_mcp_servers_and_groups;t&&t.length>0&&(e.object_permission.mcp_servers=t),s&&s.length>0&&(e.object_permission.mcp_access_groups=s),delete e.allowed_mcp_servers_and_groups}let i=e.mcp_tool_permissions||{};if(Object.keys(i).length>0&&(e.object_permission||(e.object_permission={}),e.object_permission.mcp_tool_permissions=i),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&&(e.allowed_agents_and_groups.agents?.length>0||e.allowed_agents_and_groups.accessGroups?.length>0)){e.object_permission||(e.object_permission={});let{agents:t,accessGroups:s}=e.allowed_agents_and_groups;t&&t.length>0&&(e.object_permission.agents=t),s&&s.length>0&&(e.object_permission.agent_access_groups=s),delete e.allowed_agents_and_groups}Object.keys(e8).length>0&&(e.aliases=JSON.stringify(e8)),tr?.router_settings&&Object.values(tr.router_settings).some(e=>null!=e&&""!==e)&&(e.router_settings=tr.router_settings),t="service_account"===eC?await (0,H.keyCreateServiceAccountCall)(ei,e):await (0,H.keyCreateCall)(ei,en,e),console.log("key create Response:",t),ea(t),eh.invalidateQueries({queryKey:s.keyKeys.lists()}),ej(t.key),ev(t.soft_budget),W.default.success("Virtual Key Created"),ex.resetFields(),localStorage.removeItem("userData"+en)}catch(t){console.log("error in create key:",t);let e=(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: ${e}`;let s=t;try{if(!e||"object"!=typeof e||e instanceof Error){let e=t.match(/\{[\s\S]*\}/);if(e){let t=JSON.parse(e[0]),a=t?.error||t;a?.message&&(s=a.message)}}else{let t=e?.error||e;t?.message&&(s=t.message)}}catch(e){}return t.includes("team_member_permission_error")||s.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: ${e}`})(t);W.default.fromBackend(e)}};(0,T.useEffect)(()=>{if(eq){let e=eu?.find(e=>e.project_id===eq);eS(e?.models??[]),ex.setFieldValue("models",[]);return}en&&eo&&ei&&et(en,eo,ei,eK?.team_id??null).then(e=>{eS(Array.from(new Set([...eK?.models??[],...e])))}),eM||ex.setFieldValue("models",[]),ex.setFieldValue("allowed_mcp_servers_and_groups",{servers:[],accessGroups:[]})},[eK,eq,ei,en,eo,ex]),(0,T.useEffect)(()=>{if(!eM||0===eM.length||!ek||0===ek.length)return;let e=eM.filter(e=>ek.includes(e));e.length>0&&ex.setFieldsValue({models:e}),eO(null)},[eM,ek,ex]),(0,T.useEffect)(()=>{if(!eq||!Q)return;let e=eu?.find(e=>e.project_id===eq);if(!e?.team_id||eK?.team_id===e.team_id)return;let t=Q.find(t=>t.team_id===e.team_id)||null;t&&(eU(t),ex.setFieldValue("team_id",t.team_id))},[Q,eq,eu]);let ty=async e=>{if(!e)return void e0([]);e2(!0);try{let t=new URLSearchParams;if(t.append("user_email",e),null==ei)return;let s=(await (0,H.userFilterUICall)(ei,t)).map(e=>({label:`${e.user_email} (${e.user_id})`,value:e.user_id,user:e}));e0(s)}catch(e){console.error("Error fetching users:",e),W.default.fromBackend("Failed to search for users")}finally{e2(!1)}},tf=(0,T.useCallback)((0,C.default)(e=>ty(e),300),[ei]);return(0,t.jsxs)("div",{children:[eo&&I.rolesWithWriteAccess.includes(eo)&&(0,t.jsx)(m.Button,{className:"mx-auto",onClick:()=>ef(!0),children:"+ Create New Key"}),(0,t.jsx)(b.Modal,{open:ey,width:1e3,footer:null,onOk:tp,onCancel:tg,children:(0,t.jsxs)(_.Form,{form:ex,onFinish:tx,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,t.jsxs)("div",{className:"mb-8",children:[(0,t.jsx)(y.Title,{className:"mb-4",children:"Key Ownership"}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Owned By"," ",(0,t.jsx)(S.Tooltip,{title:"Select who will own this Virtual Key",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),className:"mb-4",children:(0,t.jsxs)(v.Radio.Group,{onChange:e=>eT(e.target.value),value:eC,children:[(0,t.jsx)(v.Radio,{value:"you",children:"You"}),(0,t.jsx)(v.Radio,{value:"service_account",children:"Service Account"}),"Admin"===eo&&(0,t.jsx)(v.Radio,{value:"another_user",children:"Another User"}),(0,t.jsxs)(v.Radio,{value:"agent",children:["Agent ",(0,t.jsx)(k.Tag,{color:"purple",children:"New"})]})]})}),"another_user"===eC&&(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["User ID"," ",(0,t.jsx)(S.Tooltip,{title:"The user who will own this key and be responsible for its usage",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"user_id",className:"mt-4",rules:[{required:"another_user"===eC,message:"Please input the user ID of the user you are assigning the key to"}],children:(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{style:{display:"flex",marginBottom:"8px"},children:[(0,t.jsx)(w.Select,{showSearch:!0,placeholder:"Type email to search for users",filterOption:!1,onSearch:e=>{tf(e)},onSelect:(e,t)=>{let s;return s=t.user,void ex.setFieldsValue({user_id:s.user_id})},options:eZ,loading:e1,allowClear:!0,style:{width:"100%"},notFoundContent:e1?"Searching...":"No users found"}),(0,t.jsx)(f.Button,{onClick:()=>eH(!0),style:{marginLeft:"8px"},children:"Create User"})]}),(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"Search by email to find users"})]})}),"agent"===eC&&(0,t.jsxs)("div",{className:"mt-4 p-4 bg-purple-50 border border-purple-200 rounded-md",children:[(0,t.jsx)("div",{className:"mb-3",children:(0,t.jsxs)("span",{className:"text-sm font-medium text-gray-700",children:["Select Agent ",(0,t.jsx)("span",{className:"text-red-500",children:"*"})]})}),(0,t.jsx)(w.Select,{showSearch:!0,placeholder:"Select an agent",style:{width:"100%"},value:tu,onChange:e=>tm(e),filterOption:(e,t)=>t?.label?.toLowerCase().includes(e.toLowerCase()),options:tc.map(e=>({label:e.agent_name||e.agent_id,value:e.agent_id}))}),(0,t.jsx)("div",{className:"text-xs text-gray-500 mt-2",children:"This key will be used by the selected agent to make requests to LiteLLM"})]}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Team"," ",(0,t.jsx)(S.Tooltip,{title:"The team this key belongs to, which determines available models and budget limits",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"team_id",initialValue:e?e.team_id:null,className:"mt-4",rules:[{required:"service_account"===eC,message:"Please select a team for the service account"}],help:"service_account"===eC?"required":"",children:(0,t.jsx)(R.default,{teams:Q,disabled:null!==eq,loading:!Q,onChange:e=>{eU(Q?.find(t=>t.team_id===e)||null),ez(null),ex.setFieldValue("project_id",void 0)}})}),eg&&(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Project"," ",(0,t.jsx)(S.Tooltip,{title:"Assign this key to a project. Selecting a project will lock the team to the project's team.",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"project_id",className:"mt-4",children:(0,t.jsx)(D.default,{projects:eu,teamId:eK?.team_id,loading:em||!Q,onChange:e=>{if(!e){ez(null),eU(null),ex.setFieldValue("team_id",void 0);return}ez(e)}})})]}),th&&(0,t.jsx)("div",{className:"mb-8 p-4 bg-blue-50 border border-blue-200 rounded-md",children:(0,t.jsx)(h.Text,{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."})}),!th&&(0,t.jsxs)("div",{className:"mb-8",children:[(0,t.jsx)(y.Title,{className:"mb-4",children:"Key Details"}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["you"===eC||"another_user"===eC?"Key Name":"Service Account ID"," ",(0,t.jsx)(S.Tooltip,{title:"you"===eC||"another_user"===eC?"A descriptive name to identify this key":"Unique identifier for this service account",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"key_alias",rules:[{required:!0,message:`Please input a ${"you"===eC?"key name":"service account ID"}`}],help:"required",children:(0,t.jsx)(x.TextInput,{placeholder:""})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Models"," ",(0,t.jsx)(S.Tooltip,{title:"Select which models this key can access. Choose 'All Team Models' to grant access to all models available to the team. Leave empty to allow access to all models.",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"models",rules:[],help:"management"===e7||"read_only"===e7?"Models field is disabled for this key type":"optional - leave empty to allow access to all models",className:"mt-4",children:(0,t.jsxs)(w.Select,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},disabled:"management"===e7||"read_only"===e7,onChange:e=>{e.includes("all-team-models")&&ex.setFieldsValue({models:["all-team-models"]})},children:[!eq&&(0,t.jsx)(ee,{value:"all-team-models",children:"All Team Models"},"all-team-models"),ek.map(e=>(0,t.jsx)(ee,{value:e,children:(0,U.getModelDisplayName)(e)},e))]})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Key Type"," ",(0,t.jsx)(S.Tooltip,{title:"Select the type of key to determine what routes and operations this key can access",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"key_type",initialValue:"llm_api",className:"mt-4",children:(0,t.jsxs)(w.Select,{defaultValue:"llm_api",placeholder:"Select key type",style:{width:"100%"},optionLabelProp:"label",onChange:e=>{e9(e),("management"===e||"read_only"===e)&&ex.setFieldsValue({models:[]})},children:[(0,t.jsx)(ee,{value:"default",label:"Default",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Default"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call AI APIs + Management routes"})]})}),(0,t.jsx)(ee,{value:"llm_api",label:"AI APIs",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"AI APIs"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call only AI API routes (chat/completions, embeddings, etc.)"})]})}),(0,t.jsx)(ee,{value:"management",label:"Management",children:(0,t.jsxs)("div",{style:{padding:"4px 0"},children:[(0,t.jsx)("div",{style:{fontWeight:500},children:"Management"}),(0,t.jsx)("div",{style:{fontSize:"11px",color:"#6b7280",marginTop:"2px"},children:"Can call only management routes (user/team/key management)"})]})})]})})]}),!th&&(0,t.jsx)("div",{className:"mb-8",children:(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)(y.Title,{className:"m-0",children:"Optional Settings"})}),(0,t.jsxs)(d.AccordionBody,{children:[(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Max Budget (USD)"," ",(0,t.jsx)(S.Tooltip,{title:"Maximum amount in USD this key can spend. When reached, the key will be blocked from making further requests",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"max_budget",help:`Budget cannot exceed team max budget: $${e?.max_budget!==null&&e?.max_budget!==void 0?e?.max_budget:"unlimited"}`,rules:[{validator:async(t,s)=>{if(s&&e&&null!==e.max_budget&&s>e.max_budget)throw Error(`Budget cannot exceed team max budget: $${(0,i.formatNumberWithCommas)(e.max_budget,4)}`)}}],children:(0,t.jsx)(X.default,{step:.01,precision:2,width:200})}),(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Reset Budget"," ",(0,t.jsx)(S.Tooltip,{title:"How often the budget should reset. For example, setting 'daily' will reset the budget every 24 hours",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"budget_duration",help:`Team Reset Budget: ${e?.budget_duration!==null&&e?.budget_duration!==void 0?e?.budget_duration:"None"}`,children:(0,t.jsx)(M.default,{onChange:e=>ex.setFieldValue("budget_duration",e)})}),(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Tokens per minute Limit (TPM)"," ",(0,t.jsx)(S.Tooltip,{title:"Maximum number of tokens this key can process per minute. Helps control usage and costs",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"tpm_limit",help:`TPM cannot exceed team TPM limit: ${e?.tpm_limit!==null&&e?.tpm_limit!==void 0?e?.tpm_limit:"unlimited"}`,rules:[{validator:async(t,s)=>{if(s&&e&&null!==e.tpm_limit&&s>e.tpm_limit)throw Error(`TPM limit cannot exceed team TPM limit: ${e.tpm_limit}`)}}],children:(0,t.jsx)(X.default,{step:1,width:400})}),(0,t.jsx)(B.default,{type:"tpm",name:"tpm_limit_type",className:"mt-4",initialValue:null,form:ex,showDetailedDescriptions:!0}),(0,t.jsx)(_.Form.Item,{className:"mt-4",label:(0,t.jsxs)("span",{children:["Requests per minute Limit (RPM)"," ",(0,t.jsx)(S.Tooltip,{title:"Maximum number of API requests this key can make per minute. Helps prevent abuse and manage load",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"rpm_limit",help:`RPM cannot exceed team RPM limit: ${e?.rpm_limit!==null&&e?.rpm_limit!==void 0?e?.rpm_limit:"unlimited"}`,rules:[{validator:async(t,s)=>{if(s&&e&&null!==e.rpm_limit&&s>e.rpm_limit)throw Error(`RPM limit cannot exceed team RPM limit: ${e.rpm_limit}`)}}],children:(0,t.jsx)(X.default,{step:1,width:400})}),(0,t.jsx)(B.default,{type:"rpm",name:"rpm_limit_type",className:"mt-4",initialValue:null,form:ex,showDetailedDescriptions:!0}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Guardrails"," ",(0,t.jsx)(S.Tooltip,{title:"Apply safety guardrails to this key to filter content or enforce policies",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",className:"mt-4",help:ed?"Select existing guardrails or enter new ones":"Premium feature - Upgrade to set guardrails by key",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},disabled:!ed,placeholder:ed?"Select or enter guardrails":"Premium feature - Upgrade to set guardrails by key",options:eP.map(e=>({value:e,label:e}))})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Disable Global Guardrails"," ",(0,t.jsx)(S.Tooltip,{title:"When enabled, this key will bypass any guardrails configured to run on every request (global guardrails)",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"disable_global_guardrails",className:"mt-4",valuePropName:"checked",help:ed?"Bypass global guardrails for this key":"Premium feature - Upgrade to disable global guardrails by key",children:(0,t.jsx)(N.Switch,{disabled:!ed,checkedChildren:"Yes",unCheckedChildren:"No"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Policies"," ",(0,t.jsx)(S.Tooltip,{title:"Apply policies to this key to control guardrails and other settings",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/guardrail_policies",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"policies",className:"mt-4",help:ec?"Select existing policies or enter new ones":"Premium feature - Upgrade to set policies by key",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},disabled:!ec,placeholder:ec?"Select or enter policies":"Premium feature - Upgrade to set policies by key",options:e$.map(e=>({value:e,label:e}))})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Prompts"," ",(0,t.jsx)(S.Tooltip,{title:"Allow this key to use specific prompt templates",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/prompt_management",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"prompts",className:"mt-4",help:ec?"Select existing prompts or enter new ones":"Premium feature - Upgrade to set prompts by key",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},disabled:!ec,placeholder:ec?"Select or enter prompts":"Premium feature - Upgrade to set prompts by key",options:eB.map(e=>({value:e,label:e}))})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Access Groups"," ",(0,t.jsx)(S.Tooltip,{title:"Assign access groups to this key. Access groups control which models, MCP servers, and agents this key can use",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"access_group_ids",className:"mt-4",help:"Select access groups to assign to this key",children:(0,t.jsx)(F.default,{placeholder:"Select access groups (optional)"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Pass Through Routes"," ",(0,t.jsx)(S.Tooltip,{title:"Allow this key to use specific pass through routes",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/pass_through",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"allowed_passthrough_routes",className:"mt-4",help:ec?"Select existing pass through routes or enter new ones":"Premium feature - Upgrade to set pass through routes by key",children:(0,t.jsx)($.default,{onChange:e=>ex.setFieldValue("allowed_passthrough_routes",e),value:ex.getFieldValue("allowed_passthrough_routes"),accessToken:ei,placeholder:ec?"Select or enter pass through routes":"Premium feature - Upgrade to set pass through routes by key",disabled:!ec,teamId:eK?eK.team_id:null})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Vector Stores"," ",(0,t.jsx)(S.Tooltip,{title:"Select which vector stores this key can access. If none selected, the key will have access to all available vector stores",children:(0,t.jsx)(n.InfoCircleOutlined,{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,t.jsx)(Z.default,{onChange:e=>ex.setFieldValue("allowed_vector_store_ids",e),value:ex.getFieldValue("allowed_vector_store_ids"),accessToken:ei,placeholder:"Select vector stores (optional)"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Metadata"," ",(0,t.jsx)(S.Tooltip,{title:"JSON object with additional information about this key. Used for tracking or custom logic",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"metadata",className:"mt-4",children:(0,t.jsx)(j.Input.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Tags"," ",(0,t.jsx)(S.Tooltip,{title:"Tags for tracking spend and/or doing tag-based routing. Used for analytics and filtering",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"tags",className:"mt-4",help:"Tags for tracking spend and/or doing tag-based routing.",children:(0,t.jsx)(w.Select,{mode:"tags",style:{width:"100%"},placeholder:"Enter tags",tokenSeparators:[","],options:eI})}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"MCP Settings"})}),(0,t.jsxs)(d.AccordionBody,{children:[(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed MCP Servers"," ",(0,t.jsx)(S.Tooltip,{title:"Select which MCP servers or access groups this key can access",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_mcp_servers_and_groups",help:"Select MCP servers or access groups this key can access",children:(0,t.jsx)(q.default,{onChange:e=>ex.setFieldValue("allowed_mcp_servers_and_groups",e),value:ex.getFieldValue("allowed_mcp_servers_and_groups"),accessToken:ei,teamId:eK?.team_id??null,placeholder:"Select MCP servers or access groups (optional)"})}),(0,t.jsx)(_.Form.Item,{name:"mcp_tool_permissions",initialValue:{},hidden:!0,children:(0,t.jsx)(j.Input,{type:"hidden"})}),(0,t.jsx)(_.Form.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:()=>(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(z.default,{accessToken:ei,selectedServers:ex.getFieldValue("allowed_mcp_servers_and_groups")?.servers||[],toolPermissions:ex.getFieldValue("mcp_tool_permissions")||{},onChange:e=>ex.setFieldsValue({mcp_tool_permissions:e})})})})]})]}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Agent Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)(_.Form.Item,{label:(0,t.jsxs)("span",{children:["Allowed Agents"," ",(0,t.jsx)(S.Tooltip,{title:"Select which agents or access groups this key can access",children:(0,t.jsx)(n.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_agents_and_groups",help:"Select agents or access groups this key can access",children:(0,t.jsx)(A.default,{onChange:e=>ex.setFieldValue("allowed_agents_and_groups",e),value:ex.getFieldValue("allowed_agents_and_groups"),accessToken:ei,placeholder:"Select agents or access groups (optional)"})})})]}),ec?(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Logging Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(V.default,{value:eR,onChange:eD,premiumUser:!0,disabledCallbacks:e3,onDisabledCallbacksChange:e6})})})]}):(0,t.jsx)(S.Tooltip,{title:(0,t.jsxs)("span",{children:["Key-level logging settings is an enterprise feature, get in touch -",(0,t.jsx)("a",{href:"https://www.litellm.ai/enterprise",target:"_blank",children:"https://www.litellm.ai/enterprise"})]}),placement:"top",children:(0,t.jsxs)("div",{style:{position:"relative"},children:[(0,t.jsx)("div",{style:{opacity:.5},children:(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Logging Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(V.default,{value:eR,onChange:eD,premiumUser:!1,disabledCallbacks:e3,onDisabledCallbacksChange:e6})})})]})}),(0,t.jsx)("div",{style:{position:"absolute",inset:0,cursor:"not-allowed"}})]})}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Router Settings"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4 w-full",children:(0,t.jsx)(G.default,{accessToken:ei||"",value:tr||void 0,onChange:ti,modelData:ew.length>0?{data:ew.map(e=>({model_name:e}))}:void 0},tn)})})]},`router-settings-accordion-${tn}`),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Model Aliases"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsxs)("div",{className:"mt-4",children:[(0,t.jsx)(h.Text,{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,t.jsx)(E.default,{accessToken:ei,initialModelAliases:e8,onAliasUpdate:te,showExampleConfig:!1})]})})]}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsx)("b",{children:"Key Lifecycle"})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(P.default,{form:ex,autoRotationEnabled:tt,onAutoRotationChange:ts,rotationInterval:ta,onRotationIntervalChange:tl,isCreateMode:!0})})}),(0,t.jsx)(_.Form.Item,{name:"duration",hidden:!0,initialValue:null,children:(0,t.jsx)(j.Input,{})})]}),(0,t.jsxs)(c.Accordion,{className:"mt-4 mb-4",children:[(0,t.jsx)(u.AccordionHeader,{children:(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("b",{children:"Advanced Settings"}),(0,t.jsx)(S.Tooltip,{title:(0,t.jsxs)("span",{children:["Learn more about advanced settings in our"," ",(0,t.jsx)("a",{href:H.proxyBaseUrl?`${H.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,t.jsx)(n.InfoCircleOutlined,{className:"text-gray-400 hover:text-gray-300 cursor-help"})})]})}),(0,t.jsx)(d.AccordionBody,{children:(0,t.jsx)(O.default,{schemaComponent:"GenerateKeyRequest",form:ex,excludedFields:["key_alias","team_id","models","duration","metadata","tags","guardrails","max_budget","budget_duration","tpm_limit","rpm_limit"]})})]})]})]})}),(0,t.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,t.jsx)(f.Button,{htmlType:"submit",disabled:th,style:{opacity:th?.5:1},children:"Create Key"})})]})}),eW&&(0,t.jsx)(b.Modal,{title:"Create New User",open:eW,onCancel:()=>eH(!1),footer:null,width:800,children:(0,t.jsx)(K.CreateUserButton,{userID:en,accessToken:ei,teams:Q,possibleUIRoles:eY,onUserCreated:e=>{eJ(e),ex.setFieldsValue({user_id:e}),eH(!1)},isEmbedded:!0})}),e_&&(0,t.jsx)(b.Modal,{open:ey,onOk:tp,onCancel:tg,footer:null,children:(0,t.jsxs)(g.Grid,{numItems:1,className:"gap-2 w-full",children:[(0,t.jsx)(y.Title,{children:"Save your Key"}),(0,t.jsx)(p.Col,{numColSpan:1,children:null!=e_?(0,t.jsx)(Y,{apiKey:e_}):(0,t.jsx)(h.Text,{children:"Key being created, this might take 30s"})})]})})]})},"fetchTeamModels",0,et,"fetchUserModels",0,es],702597)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/59945beef3825b62.js b/litellm/proxy/_experimental/out/_next/static/chunks/59945beef3825b62.js new file mode 100644 index 00000000000..ee28549d2b3 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/59945beef3825b62.js @@ -0,0 +1 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,461451,37329,100070,e=>{"use strict";var t=e.i(843476),s=e.i(271645),l=e.i(304967),i=e.i(629569),r=e.i(599724),n=e.i(350967),a=e.i(994388),o=e.i(366283),c=e.i(779241),d=e.i(114600),u=e.i(808613),p=e.i(764205),m=e.i(237016),g=e.i(596239),h=e.i(438957),_=e.i(166406),x=e.i(270377),f=e.i(475647),y=e.i(190702),j=e.i(727749);e.s(["default",0,({accessToken:e,userID:v,proxySettings:b})=>{let[S]=u.Form.useForm(),[I,k]=(0,s.useState)(!1),[T,C]=(0,s.useState)(null),[w,E]=(0,s.useState)("");(0,s.useEffect)(()=>{let e="";E(e=b&&b.PROXY_BASE_URL&&void 0!==b.PROXY_BASE_URL?b.PROXY_BASE_URL:window.location.origin)},[b]);let O=`${w}/scim/v2`,N=async t=>{if(!e||!v)return void j.default.fromBackend("You need to be logged in to create a SCIM token");try{k(!0);let s={key_alias:t.key_alias||"SCIM Access Token",team_id:null,models:[],allowed_routes:["/scim/*"]},l=await (0,p.keyCreateCall)(e,v,s);C(l),j.default.success("SCIM token created successfully")}catch(e){console.error("Error creating SCIM token:",e),j.default.fromBackend("Failed to create SCIM token: "+(0,y.parseErrorMessage)(e))}finally{k(!1)}};return(0,t.jsx)(n.Grid,{numItems:1,children:(0,t.jsxs)(l.Card,{children:[(0,t.jsx)("div",{className:"flex items-center mb-4",children:(0,t.jsx)(i.Title,{children:"SCIM Configuration"})}),(0,t.jsx)(r.Text,{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)(d.Divider,{}),(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)(i.Title,{className:"text-lg flex items-center",children:[(0,t.jsx)(g.LinkOutlined,{className:"h-5 w-5 mr-2"}),"SCIM Tenant URL"]})]}),(0,t.jsx)(r.Text,{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)(c.TextInput,{value:O,disabled:!0,className:"flex-grow"}),(0,t.jsx)(m.CopyToClipboard,{text:O,onCopy:()=>j.default.success("URL copied to clipboard"),children:(0,t.jsxs)(a.Button,{variant:"primary",className:"ml-2 flex items-center",children:[(0,t.jsx)(_.CopyOutlined,{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)(i.Title,{className:"text-lg flex items-center",children:[(0,t.jsx)(h.KeyOutlined,{className:"h-5 w-5 mr-2"}),"Authentication Token"]})]}),(0,t.jsx)(o.Callout,{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."}),T?(0,t.jsxs)(l.Card,{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)(x.ExclamationCircleOutlined,{className:"h-5 w-5 mr-2"}),(0,t.jsx)(i.Title,{className:"text-lg text-yellow-800",children:"Your SCIM Token"})]}),(0,t.jsx)(r.Text,{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)(c.TextInput,{value:T.key,className:"flex-grow mr-2 bg-white",type:"password",disabled:!0}),(0,t.jsx)(m.CopyToClipboard,{text:T.key,onCopy:()=>j.default.success("Token copied to clipboard"),children:(0,t.jsxs)(a.Button,{variant:"primary",className:"flex items-center",children:[(0,t.jsx)(_.CopyOutlined,{className:"h-4 w-4 mr-1"}),"Copy"]})})]}),(0,t.jsxs)(a.Button,{className:"mt-4 flex items-center",variant:"secondary",onClick:()=>C(null),children:[(0,t.jsx)(f.PlusCircleOutlined,{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)(u.Form,{form:S,onFinish:N,layout:"vertical",children:[(0,t.jsx)(u.Form.Item,{name:"key_alias",label:"Token Name",rules:[{required:!0,message:"Please enter a name for your token"}],children:(0,t.jsx)(c.TextInput,{placeholder:"SCIM Access Token"})}),(0,t.jsx)(u.Form.Item,{children:(0,t.jsxs)(a.Button,{variant:"primary",type:"submit",loading:I,className:"flex items-center",children:[(0,t.jsx)(h.KeyOutlined,{className:"h-4 w-4 mr-1"}),"Create SCIM Token"]})})]})})]})]})]})})}],461451);var v=e.i(135214),b=e.i(266027),S=e.i(243652);let I=(0,S.createQueryKeys)("sso"),k=()=>{let{accessToken:e,userId:t,userRole:s}=(0,v.default)();return(0,b.useQuery)({queryKey:I.detail("settings"),queryFn:async()=>await (0,p.getSSOSettings)(e),enabled:!!(e&&t&&s)})};var T=e.i(464571),C=e.i(175712),w=e.i(869216),E=e.i(770914),O=e.i(262218),N=e.i(898586),A=e.i(688511),P=e.i(98919),F=e.i(727612);let M={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:""},B={google:"Google SSO",microsoft:"Microsoft SSO",okta:"Okta / Auth0 SSO",generic:"Generic SSO"},U={internal_user_viewer:"Internal Viewer",internal_user:"Internal User",proxy_admin_viewer:"Proxy Admin Viewer",proxy_admin:"Proxy Admin"};var L=e.i(212931),R=e.i(536916),z=e.i(311451),D=e.i(199133);let V={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"}]}},G=({form:e,onFormSubmit:s})=>(0,t.jsx)("div",{children:(0,t.jsxs)(u.Form,{form:e,onFinish:s,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,t.jsx)(u.Form.Item,{label:"SSO Provider",name:"sso_provider",rules:[{required:!0,message:"Please select an SSO provider"}],children:(0,t.jsx)(D.Select,{children:Object.entries(M).map(([e,s])=>(0,t.jsx)(D.Select.Option,{value:e,children:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"4px 0"},children:[s&&(0,t.jsx)("img",{src:s,alt:e,style:{height:24,width:24,marginRight:12,objectFit:"contain"}}),(0,t.jsx)("span",{children:B[e]||e.charAt(0).toUpperCase()+e.slice(1)+" SSO"})]})},e))})}),(0,t.jsx)(u.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.sso_provider!==t.sso_provider,children:({getFieldValue:e})=>{let s,l=e("sso_provider");return l&&(s=V[l])?s.fields.map(e=>(0,t.jsx)(u.Form.Item,{label:e.label,name:e.name,rules:[{required:!0,message:`Please enter the ${e.label.toLowerCase()}`}],children:e.name.includes("client")?(0,t.jsx)(z.Input.Password,{}):(0,t.jsx)(c.TextInput,{placeholder:e.placeholder})},e.name)):null}}),(0,t.jsx)(u.Form.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.TextInput,{})}),(0,t.jsx)(u.Form.Item,{label:"Proxy Base URL",name:"proxy_base_url",normalize:e=>e?.trim(),rules:[{required:!0,message:"Please enter the proxy base url"},{pattern:/^https?:\/\/.+/,message:"URL must start with http:// or https://"},{validator:(e,t)=>t&&/^https?:\/\/.+/.test(t)&&t.endsWith("/")?Promise.reject("URL must not end with a trailing slash"):Promise.resolve()}],children:(0,t.jsx)(c.TextInput,{placeholder:"https://example.com"})}),(0,t.jsx)(u.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.sso_provider!==t.sso_provider,children:({getFieldValue:e})=>{let s=e("sso_provider");return"okta"===s||"generic"===s?(0,t.jsx)(u.Form.Item,{label:"Use Role Mappings",name:"use_role_mappings",valuePropName:"checked",children:(0,t.jsx)(R.Checkbox,{})}):null}}),(0,t.jsx)(u.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.use_role_mappings!==t.use_role_mappings||e.sso_provider!==t.sso_provider,children:({getFieldValue:e})=>{let s=e("use_role_mappings"),l=e("sso_provider");return s&&("okta"===l||"generic"===l)?(0,t.jsx)(u.Form.Item,{label:"Group Claim",name:"group_claim",rules:[{required:!0,message:"Please enter the group claim"}],children:(0,t.jsx)(c.TextInput,{})}):null}}),(0,t.jsx)(u.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.use_role_mappings!==t.use_role_mappings||e.sso_provider!==t.sso_provider,children:({getFieldValue:e})=>{let s=e("use_role_mappings"),l=e("sso_provider");return s&&("okta"===l||"generic"===l)?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(u.Form.Item,{label:"Default Role",name:"default_role",initialValue:"Internal User",children:(0,t.jsxs)(D.Select,{children:[(0,t.jsx)(D.Select.Option,{value:"internal_user_viewer",children:"Internal Viewer"}),(0,t.jsx)(D.Select.Option,{value:"internal_user",children:"Internal User"}),(0,t.jsx)(D.Select.Option,{value:"proxy_admin_viewer",children:"Admin Viewer"}),(0,t.jsx)(D.Select.Option,{value:"proxy_admin",children:"Proxy Admin"})]})}),(0,t.jsx)(u.Form.Item,{label:"Proxy Admin Teams",name:"proxy_admin_teams",children:(0,t.jsx)(c.TextInput,{})}),(0,t.jsx)(u.Form.Item,{label:"Admin Viewer Teams",name:"admin_viewer_teams",children:(0,t.jsx)(c.TextInput,{})}),(0,t.jsx)(u.Form.Item,{label:"Internal User Teams",name:"internal_user_teams",children:(0,t.jsx)(c.TextInput,{})}),(0,t.jsx)(u.Form.Item,{label:"Internal Viewer Teams",name:"internal_viewer_teams",children:(0,t.jsx)(c.TextInput,{})})]}):null}}),(0,t.jsx)(u.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.sso_provider!==t.sso_provider,children:({getFieldValue:e})=>{let s=e("sso_provider");return"okta"===s||"generic"===s?(0,t.jsx)(u.Form.Item,{label:"Use Team Mappings",name:"use_team_mappings",valuePropName:"checked",children:(0,t.jsx)(R.Checkbox,{})}):null}}),(0,t.jsx)(u.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.use_team_mappings!==t.use_team_mappings||e.sso_provider!==t.sso_provider,children:({getFieldValue:e})=>{let s=e("use_team_mappings"),l=e("sso_provider");return s&&("okta"===l||"generic"===l)?(0,t.jsx)(u.Form.Item,{label:"Team IDs JWT Field",name:"team_ids_jwt_field",rules:[{required:!0,message:"Please enter the team IDs JWT field"}],children:(0,t.jsx)(c.TextInput,{})}):null}})]})});var q=e.i(954616);let H=()=>{let{accessToken:e}=(0,v.default)();return(0,q.useMutation)({mutationFn:async t=>{if(!e)throw Error("Access token is required");return await (0,p.updateSSOSettings)(e,t)}})},$=e=>{let{proxy_admin_teams:t,admin_viewer_teams:s,internal_user_teams:l,internal_viewer_teams:i,default_role:r,group_claim:n,use_role_mappings:a,use_team_mappings:o,team_ids_jwt_field:c,...d}=e,u={...d},p=d.sso_provider;if(a&&("okta"===p||"generic"===p)){let e=e=>e&&""!==e.trim()?e.split(",").map(e=>e.trim()).filter(e=>e.length>0):[];u.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(t),proxy_admin_viewer:e(s),internal_user:e(l),internal_user_viewer:e(i)}}}return o&&("okta"===p||"generic"===p)&&(u.team_mappings={team_ids_jwt_field:c}),u},K=e=>e.google_client_id?"google":e.microsoft_client_id?"microsoft":e.generic_client_id?e.generic_authorization_endpoint?.includes("okta")||e.generic_authorization_endpoint?.includes("auth0")?"okta":"generic":null,W=({isVisible:e,onCancel:s,onSuccess:l})=>{let[i]=u.Form.useForm(),{mutateAsync:r,isPending:n}=H(),a=async e=>{let t=$(e);await r(t,{onSuccess:()=>{j.default.success("SSO settings added successfully"),l()},onError:e=>{j.default.fromBackend("Failed to save SSO settings: "+(0,y.parseErrorMessage)(e))}})},o=()=>{i.resetFields(),s()};return(0,t.jsx)(L.Modal,{title:"Add SSO",open:e,width:800,footer:(0,t.jsxs)(E.Space,{children:[(0,t.jsx)(T.Button,{onClick:o,disabled:n,children:"Cancel"}),(0,t.jsx)(T.Button,{loading:n,onClick:()=>i.submit(),children:n?"Adding...":"Add SSO"})]}),onCancel:o,children:(0,t.jsx)(G,{form:i,onFormSubmit:a})})};var Q=e.i(127952);let Y=({isVisible:e,onCancel:s,onSuccess:l})=>{let{data:i}=k(),{mutateAsync:r,isPending:n}=H(),a=async()=>{await r({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,team_mappings:null},{onSuccess:()=>{j.default.success("SSO settings cleared successfully"),s(),l()},onError:e=>{j.default.fromBackend("Failed to clear SSO settings: "+(0,y.parseErrorMessage)(e))}})};return(0,t.jsx)(Q.default,{isOpen:e,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:i?.values&&K(i?.values)||"Generic"}],onCancel:s,onOk:a,confirmLoading:n})},J=({isVisible:e,onCancel:l,onSuccess:i})=>{let[r]=u.Form.useForm(),n=k(),{mutateAsync:a,isPending:o}=H();(0,s.useEffect)(()=>{if(e&&n.data&&n.data.values){let e=n.data;console.log("Raw SSO data received:",e),console.log("SSO values:",e.values),console.log("user_email from API:",e.values.user_email);let t=null;e.values.google_client_id?t="google":e.values.microsoft_client_id?t="microsoft":e.values.generic_client_id&&(t=e.values.generic_authorization_endpoint?.includes("okta")||e.values.generic_authorization_endpoint?.includes("auth0")?"okta":"generic");let s={};if(e.values.role_mappings){let t=e.values.role_mappings,l=e=>e&&0!==e.length?e.join(", "):"";s={use_role_mappings:!0,group_claim:t.group_claim,default_role:t.default_role||"internal_user",proxy_admin_teams:l(t.roles?.proxy_admin),admin_viewer_teams:l(t.roles?.proxy_admin_viewer),internal_user_teams:l(t.roles?.internal_user),internal_viewer_teams:l(t.roles?.internal_user_viewer)}}let l={};e.values.team_mappings&&(l={use_team_mappings:!0,team_ids_jwt_field:e.values.team_mappings.team_ids_jwt_field});let i={sso_provider:t,...e.values,...s,...l};console.log("Setting form values:",i),r.resetFields(),setTimeout(()=>{r.setFieldsValue(i),console.log("Form values set, current form values:",r.getFieldsValue())},100)}},[e,n.data,r]);let c=async e=>{try{let t=$(e);await a(t,{onSuccess:()=>{j.default.success("SSO settings updated successfully"),i()},onError:e=>{j.default.fromBackend("Failed to save SSO settings: "+(0,y.parseErrorMessage)(e))}})}catch(e){j.default.fromBackend("Failed to process SSO settings: "+(0,y.parseErrorMessage)(e))}},d=()=>{r.resetFields(),l()};return(0,t.jsx)(L.Modal,{title:"Edit SSO Settings",open:e,width:800,footer:(0,t.jsxs)(E.Space,{children:[(0,t.jsx)(T.Button,{onClick:d,disabled:o,children:"Cancel"}),(0,t.jsx)(T.Button,{loading:o,onClick:()=>r.submit(),children:o?"Saving...":"Save"})]}),onCancel:d,children:(0,t.jsx)(G,{form:r,onFormSubmit:c})})};var Z=e.i(286536),X=e.i(77705);function ee({defaultHidden:e=!0,value:l}){let[i,r]=(0,s.useState)(e);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?i?"•".repeat(l.length):l:(0,t.jsx)("span",{className:"text-gray-400 italic",children:"Not configured"})}),l&&(0,t.jsx)(T.Button,{type:"text",size:"small",icon:i?(0,t.jsx)(Z.Eye,{className:"w-4 h-4"}):(0,t.jsx)(X.EyeOff,{className:"w-4 h-4"}),onClick:()=>r(!i),className:"text-gray-400 hover:text-gray-600"})]})}var et=e.i(312361),es=e.i(291542),el=e.i(761911);let{Title:ei,Text:er}=N.Typography;function en({roleMappings:e}){if(!e)return null;let s=[{title:"Role",dataIndex:"role",key:"role",render:e=>(0,t.jsx)(er,{strong:!0,children:U[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)(O.Tag,{color:"blue",children:e},s)):(0,t.jsx)(er,{className:"text-gray-400 italic",children:"No groups mapped"})})}];return(0,t.jsxs)(C.Card,{children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(el.Users,{className:"w-6 h-6 text-gray-400 mb-2"}),(0,t.jsx)(ei,{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)(ei,{level:5,children:"Group Claim"}),(0,t.jsx)("div",{children:(0,t.jsx)(er,{code:!0,children:e.group_claim})})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(ei,{level:5,children:"Default Role"}),(0,t.jsx)("div",{children:(0,t.jsx)(er,{strong:!0,children:U[e.default_role]})})]})]}),(0,t.jsx)(et.Divider,{}),(0,t.jsx)(es.Table,{columns:s,dataSource:Object.entries(e.roles).map(([e,t])=>({role:e,groups:t})),pagination:!1,bordered:!0,size:"small",className:"w-full"})]})]})}var ea=e.i(21548);let{Title:eo,Paragraph:ec}=N.Typography;function ed({onAdd: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)(ea.Empty,{image:ea.Empty.PRESENTED_IMAGE_SIMPLE,description:(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(eo,{level:4,children:"No SSO Configuration Found"}),(0,t.jsx)(ec,{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)(T.Button,{type:"primary",size:"large",onClick:e,className:"flex items-center gap-2 mx-auto mt-4",children:"Configure SSO"})})})}var eu=e.i(981339);let{Title:ep,Text:em}=N.Typography;function eg(){return(0,t.jsx)(C.Card,{children:(0,t.jsxs)(E.Space,{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)(P.Shield,{className:"w-6 h-6 text-gray-400"}),(0,t.jsxs)("div",{children:[(0,t.jsx)(ep,{level:3,children:"SSO Configuration"}),(0,t.jsx)(em,{type:"secondary",children:"Manage Single Sign-On authentication settings"})]})]}),(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(eu.Skeleton.Button,{active:!0,size:"default",style:{width:170,height:32}}),(0,t.jsx)(eu.Skeleton.Button,{active:!0,size:"default",style:{width:190,height:32}})]})]}),(0,t.jsxs)(w.Descriptions,{bordered:!0,...{column:{xxl:1,xl:1,lg:1,md:1,sm:1,xs:1}},children:[(0,t.jsx)(w.Descriptions.Item,{label:(0,t.jsx)(eu.Skeleton.Node,{active:!0,style:{width:80,height:16}}),children:(0,t.jsx)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:(0,t.jsx)(eu.Skeleton.Node,{active:!0,style:{width:100,height:16}})})}),(0,t.jsx)(w.Descriptions.Item,{label:(0,t.jsx)(eu.Skeleton.Node,{active:!0,style:{width:80,height:16}}),children:(0,t.jsx)(eu.Skeleton.Node,{active:!0,style:{width:200,height:16}})}),(0,t.jsx)(w.Descriptions.Item,{label:(0,t.jsx)(eu.Skeleton.Node,{active:!0,style:{width:80,height:16}}),children:(0,t.jsx)(eu.Skeleton.Node,{active:!0,style:{width:250,height:16}})}),(0,t.jsx)(w.Descriptions.Item,{label:(0,t.jsx)(eu.Skeleton.Node,{active:!0,style:{width:80,height:16}}),children:(0,t.jsx)(eu.Skeleton.Node,{active:!0,style:{width:180,height:16}})}),(0,t.jsx)(w.Descriptions.Item,{label:(0,t.jsx)(eu.Skeleton.Node,{active:!0,style:{width:80,height:16}}),children:(0,t.jsx)(eu.Skeleton.Node,{active:!0,style:{width:220,height:16}})})]})]})})}let{Title:eh,Text:e_}=N.Typography;function ex(){let{data:e,refetch:l,isLoading:i}=k(),[r,n]=(0,s.useState)(!1),[a,o]=(0,s.useState)(!1),[c,d]=(0,s.useState)(!1),u=!!e?.values.google_client_id||!!e?.values.microsoft_client_id||!!e?.values.generic_client_id,p=e?.values?K(e.values):null,m=!!e?.values.role_mappings,g=!!e?.values.team_mappings,h=e=>(0,t.jsx)(e_,{className:"font-mono text-gray-600 text-sm",copyable:!!e,children:e||"-"}),_=e=>e||(0,t.jsx)("span",{className:"text-gray-400 italic",children:"Not configured"}),x=e=>e.team_mappings?.team_ids_jwt_field?(0,t.jsx)(O.Tag,{children:e.team_mappings.team_ids_jwt_field}):(0,t.jsx)("span",{className:"text-gray-400 italic",children:"Not configured"}),f={column:{xxl:1,xl:1,lg:1,md:1,sm:1,xs:1}},y={google:{providerText:B.google,fields:[{label:"Client ID",render:e=>(0,t.jsx)(ee,{value:e.google_client_id})},{label:"Client Secret",render:e=>(0,t.jsx)(ee,{value:e.google_client_secret})},{label:"Proxy Base URL",render:e=>_(e.proxy_base_url)}]},microsoft:{providerText:B.microsoft,fields:[{label:"Client ID",render:e=>(0,t.jsx)(ee,{value:e.microsoft_client_id})},{label:"Client Secret",render:e=>(0,t.jsx)(ee,{value:e.microsoft_client_secret})},{label:"Tenant",render:e=>_(e.microsoft_tenant)},{label:"Proxy Base URL",render:e=>_(e.proxy_base_url)}]},okta:{providerText:B.okta,fields:[{label:"Client ID",render:e=>(0,t.jsx)(ee,{value:e.generic_client_id})},{label:"Client Secret",render:e=>(0,t.jsx)(ee,{value:e.generic_client_secret})},{label:"Authorization Endpoint",render:e=>h(e.generic_authorization_endpoint)},{label:"Token Endpoint",render:e=>h(e.generic_token_endpoint)},{label:"User Info Endpoint",render:e=>h(e.generic_userinfo_endpoint)},{label:"Proxy Base URL",render:e=>_(e.proxy_base_url)},g?{label:"Team IDs JWT Field",render:e=>x(e)}:null]},generic:{providerText:B.generic,fields:[{label:"Client ID",render:e=>(0,t.jsx)(ee,{value:e.generic_client_id})},{label:"Client Secret",render:e=>(0,t.jsx)(ee,{value:e.generic_client_secret})},{label:"Authorization Endpoint",render:e=>h(e.generic_authorization_endpoint)},{label:"Token Endpoint",render:e=>h(e.generic_token_endpoint)},{label:"User Info Endpoint",render:e=>h(e.generic_userinfo_endpoint)},{label:"Proxy Base URL",render:e=>_(e.proxy_base_url)},g?{label:"Team IDs JWT Field",render:e=>x(e)}:null]}};return(0,t.jsxs)(t.Fragment,{children:[i?(0,t.jsx)(eg,{}):(0,t.jsxs)(E.Space,{direction:"vertical",size:"large",className:"w-full",children:[(0,t.jsx)(C.Card,{children:(0,t.jsxs)(E.Space,{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)(P.Shield,{className:"w-6 h-6 text-gray-400"}),(0,t.jsxs)("div",{children:[(0,t.jsx)(eh,{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:u&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(T.Button,{icon:(0,t.jsx)(A.Edit,{className:"w-4 h-4"}),onClick:()=>d(!0),children:"Edit SSO Settings"}),(0,t.jsx)(T.Button,{danger:!0,icon:(0,t.jsx)(F.Trash2,{className:"w-4 h-4"}),onClick:()=>n(!0),children:"Delete SSO Settings"})]})})]}),u?(()=>{if(!e?.values||!p)return null;let{values:s}=e,l=y[p];return l?(0,t.jsxs)(w.Descriptions,{bordered:!0,...f,children:[(0,t.jsx)(w.Descriptions.Item,{label:"Provider",children:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[M[p]&&(0,t.jsx)("img",{src:M[p],alt:p,style:{height:24,width:24,objectFit:"contain"}}),(0,t.jsx)("span",{children:l.providerText})]})}),l.fields.map((e,l)=>e&&(0,t.jsx)(w.Descriptions.Item,{label:e.label,children:e.render(s)},l))]}):null})():(0,t.jsx)(ed,{onAdd:()=>o(!0)})]})}),m&&(0,t.jsx)(en,{roleMappings:e?.values.role_mappings})]}),(0,t.jsx)(Y,{isVisible:r,onCancel:()=>n(!1),onSuccess:()=>l()}),(0,t.jsx)(W,{isVisible:a,onCancel:()=>o(!1),onSuccess:()=>{o(!1),l()}}),(0,t.jsx)(J,{isVisible:c,onCancel:()=>d(!1),onSuccess:()=>{d(!1),l()}})]})}e.s(["default",()=>ex],37329);var ef=e.i(912598);let ey=(0,S.createQueryKeys)("uiSettings");e.s(["useUpdateUISettings",0,e=>{let t=(0,ef.useQueryClient)();return(0,q.useMutation)({mutationFn:async t=>{if(!e)throw Error("Access token is required");return(0,p.updateUiSettings)(e,t)},onSuccess:()=>{t.invalidateQueries({queryKey:ey.all})}})}],100070)},111672,e=>{"use strict";var t=e.i(843476),s=e.i(109799),l=e.i(785242),i=e.i(135214),r=e.i(218129),n=e.i(477189),a=e.i(457202),o=e.i(299251),c=e.i(153702);e.i(247167);var d=e.i(931067),u=e.i(271645);let p={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M766.4 744.3c43.7 0 79.4-36.2 79.4-80.5 0-53.5-79.4-140.8-79.4-140.8S687 610.3 687 663.8c0 44.3 35.7 80.5 79.4 80.5zm-377.1-44.1c7.1 7.1 18.6 7.1 25.6 0l256.1-256c7.1-7.1 7.1-18.6 0-25.6l-256-256c-.6-.6-1.3-1.2-2-1.7l-78.2-78.2a9.11 9.11 0 00-12.8 0l-48 48a9.11 9.11 0 000 12.8l67.2 67.2-207.8 207.9c-7.1 7.1-7.1 18.6 0 25.6l255.9 256zm12.9-448.6l178.9 178.9H223.4l178.8-178.9zM904 816H120c-4.4 0-8 3.6-8 8v80c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-80c0-4.4-3.6-8-8-8z"}}]},name:"bg-colors",theme:"outlined"};var m=e.i(9583),g=u.forwardRef(function(e,t){return u.createElement(m.default,(0,d.default)({},e,{ref:t,icon:p}))}),h=e.i(182399);let _={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M832 64H192c-17.7 0-32 14.3-32 32v832c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V96c0-17.7-14.3-32-32-32zm-260 72h96v209.9L621.5 312 572 347.4V136zm220 752H232V136h280v296.9c0 3.3 1 6.6 3 9.3a15.9 15.9 0 0022.3 3.7l83.8-59.9 81.4 59.4c2.7 2 6 3.1 9.4 3.1 8.8 0 16-7.2 16-16V136h64v752z"}}]},name:"book",theme:"outlined"};var x=u.forwardRef(function(e,t){return u.createElement(m.default,(0,d.default)({},e,{ref:t,icon:_}))});let f={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M928 160H96c-17.7 0-32 14.3-32 32v640c0 17.7 14.3 32 32 32h832c17.7 0 32-14.3 32-32V192c0-17.7-14.3-32-32-32zm-792 72h752v120H136V232zm752 560H136V440h752v352zm-237-64h165c4.4 0 8-3.6 8-8v-72c0-4.4-3.6-8-8-8H651c-4.4 0-8 3.6-8 8v72c0 4.4 3.6 8 8 8z"}}]},name:"credit-card",theme:"outlined"};var y=u.forwardRef(function(e,t){return u.createElement(m.default,(0,d.default)({},e,{ref:t,icon:f}))}),j=e.i(210612),v=e.i(19732),b=e.i(993914),S=e.i(366845),S=S,I=e.i(438957),k=e.i(777579),T=e.i(788191),C=e.i(983561),w=e.i(602073),E=e.i(928685),O=e.i(313603),N=e.i(232164),A=e.i(645526),P=e.i(366308),F=e.i(771674),M=e.i(592143),B=e.i(372943),U=e.i(899268),L=e.i(708347),R=e.i(844444),z=e.i(190983);let{Sider:D}=B.Layout,V=[{groupLabel:"AI GATEWAY",items:[{key:"api-keys",page:"api-keys",label:"Virtual Keys",icon:(0,t.jsx)(I.KeyOutlined,{})},{key:"llm-playground",page:"llm-playground",label:"Playground",icon:(0,t.jsx)(T.PlayCircleOutlined,{}),roles:L.rolesWithWriteAccess},{key:"models",page:"models",label:"Models + Endpoints",icon:(0,t.jsx)(h.BlockOutlined,{}),roles:L.rolesWithWriteAccess},{key:"agents",page:"agents",label:"Agents",icon:(0,t.jsx)(C.RobotOutlined,{}),roles:L.rolesWithWriteAccess},{key:"mcp-servers",page:"mcp-servers",label:"MCP Servers",icon:(0,t.jsx)(P.ToolOutlined,{})},{key:"guardrails",page:"guardrails",label:"Guardrails",icon:(0,t.jsx)(w.SafetyOutlined,{}),roles:L.all_admin_roles},{key:"policies",page:"policies",label:(0,t.jsx)("span",{className:"flex items-center gap-4",children:"Policies"}),icon:(0,t.jsx)(a.AuditOutlined,{}),roles:L.all_admin_roles},{key:"tools",page:"tools",label:"Tools",icon:(0,t.jsx)(P.ToolOutlined,{}),children:[{key:"search-tools",page:"search-tools",label:"Search Tools",icon:(0,t.jsx)(E.SearchOutlined,{})},{key:"vector-stores",page:"vector-stores",label:"Vector Stores",icon:(0,t.jsx)(j.DatabaseOutlined,{})},{key:"tool-policies",page:"tool-policies",label:"Tool Policies",icon:(0,t.jsx)(w.SafetyOutlined,{})}]}]},{groupLabel:"OBSERVABILITY",items:[{key:"new_usage",page:"new_usage",icon:(0,t.jsx)(c.BarChartOutlined,{}),roles:[...L.all_admin_roles,...L.internalUserRoles],label:"Usage"},{key:"logs",page:"logs",label:"Logs",icon:(0,t.jsx)(k.LineChartOutlined,{})},{key:"guardrails-monitor",page:"guardrails-monitor",label:"Guardrails Monitor",icon:(0,t.jsx)(w.SafetyOutlined,{}),roles:[...L.all_admin_roles,...L.internalUserRoles]}]},{groupLabel:"ACCESS CONTROL",items:[{key:"teams",page:"teams",label:"Teams",icon:(0,t.jsx)(A.TeamOutlined,{})},{key:"projects",page:"projects",label:(0,t.jsxs)("span",{className:"flex items-center gap-2",children:["Projects ",(0,t.jsx)(R.default,{})]}),icon:(0,t.jsx)(S.default,{}),roles:L.all_admin_roles},{key:"users",page:"users",label:"Internal Users",icon:(0,t.jsx)(F.UserOutlined,{}),roles:L.all_admin_roles},{key:"organizations",page:"organizations",label:"Organizations",icon:(0,t.jsx)(o.BankOutlined,{}),roles:L.all_admin_roles},{key:"access-groups",page:"access-groups",label:"Access Groups",icon:(0,t.jsx)(h.BlockOutlined,{}),roles:L.all_admin_roles},{key:"budgets",page:"budgets",label:"Budgets",icon:(0,t.jsx)(y,{}),roles:L.all_admin_roles}]},{groupLabel:"DEVELOPER TOOLS",items:[{key:"api_ref",page:"api_ref",label:"API Reference",icon:(0,t.jsx)(r.ApiOutlined,{})},{key:"model-hub-table",page:"model-hub-table",label:"AI Hub",icon:(0,t.jsx)(n.AppstoreOutlined,{})},{key:"learning-resources",page:"learning-resources",label:"Learning Resources",icon:(0,t.jsx)(x,{}),external_url:"https://models.litellm.ai/cookbook"},{key:"experimental",page:"experimental",label:"Experimental",icon:(0,t.jsx)(v.ExperimentOutlined,{}),children:[{key:"caching",page:"caching",label:"Caching",icon:(0,t.jsx)(j.DatabaseOutlined,{}),roles:L.all_admin_roles},{key:"prompts",page:"prompts",label:"Prompts",icon:(0,t.jsx)(b.FileTextOutlined,{}),roles:L.all_admin_roles},{key:"transform-request",page:"transform-request",label:"API Playground",icon:(0,t.jsx)(r.ApiOutlined,{}),roles:[...L.all_admin_roles,...L.internalUserRoles]},{key:"tag-management",page:"tag-management",label:"Tag Management",icon:(0,t.jsx)(N.TagsOutlined,{}),roles:L.all_admin_roles},{key:"claude-code-plugins",page:"claude-code-plugins",label:"Claude Code Plugins",icon:(0,t.jsx)(P.ToolOutlined,{}),roles:L.all_admin_roles},{key:"4",page:"usage",label:"Old Usage",icon:(0,t.jsx)(c.BarChartOutlined,{})}]}]},{groupLabel:"SETTINGS",roles:L.all_admin_roles,items:[{key:"settings",page:"settings",label:(0,t.jsxs)("span",{className:"flex items-center gap-2",children:["Settings ",(0,t.jsx)(R.default,{})]}),icon:(0,t.jsx)(O.SettingOutlined,{}),roles:L.all_admin_roles,children:[{key:"router-settings",page:"router-settings",label:"Router Settings",icon:(0,t.jsx)(O.SettingOutlined,{}),roles:L.all_admin_roles},{key:"logging-and-alerts",page:"logging-and-alerts",label:"Logging & Alerts",icon:(0,t.jsx)(O.SettingOutlined,{}),roles:L.all_admin_roles},{key:"admin-panel",page:"admin-panel",label:(0,t.jsxs)("span",{className:"flex items-center gap-2",children:["Admin Settings ",(0,t.jsx)(R.default,{dot:!0,children:(0,t.jsx)("span",{})})]}),icon:(0,t.jsx)(O.SettingOutlined,{}),roles:L.all_admin_roles},{key:"cost-tracking",page:"cost-tracking",label:"Cost Tracking",icon:(0,t.jsx)(c.BarChartOutlined,{}),roles:L.all_admin_roles},{key:"ui-theme",page:"ui-theme",label:"UI Theme",icon:(0,t.jsx)(g,{}),roles:L.all_admin_roles}]}]}];e.s(["default",0,({setPage:e,defaultSelectedKey:r,collapsed:n=!1,enabledPagesInternalUsers:a,enableProjectsUI:o,disableAgentsForInternalUsers:c,allowAgentsForTeamAdmins:d,disableVectorStoresForInternalUsers:p,allowVectorStoresForTeamAdmins:m})=>{let g,{userId:h,accessToken:_,userRole:x}=(0,i.default)(),{data:f}=(0,s.useOrganizations)(),{data:y}=(0,l.useTeams)(),j=(0,u.useMemo)(()=>!!h&&!!f&&f.some(e=>e.members?.some(e=>e.user_id===h&&"org_admin"===e.user_role)),[h,f]),v=(0,u.useMemo)(()=>(0,L.isUserTeamAdminForAnyTeam)(y??null,h??""),[y,h]),b=t=>{let s=new URLSearchParams(window.location.search);s.set("page",t),window.history.pushState(null,"",`?${s.toString()}`),e(t)},S=(e,s,l)=>{if(l)return(0,t.jsx)("a",{href:l,target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),style:{color:"inherit",textDecoration:"none"},children:e});let i=new URLSearchParams(window.location.search);i.set("page",s);let r=`?${i.toString()}`;return(0,t.jsx)("a",{href:r,onClick:e=>{e.metaKey||e.ctrlKey||e.shiftKey||1===e.button?e.stopPropagation():e.preventDefault()},style:{color:"inherit",textDecoration:"none"},children:e})},I=e=>{let t=(0,L.isAdminRole)(x);return null!=a&&console.log("[LeftNav] Filtering with enabled pages:",{userRole:x,isAdmin:t,enabledPagesInternalUsers:a}),e.map(e=>({...e,children:e.children?I(e.children):void 0})).filter(e=>{if("organizations"===e.key||"users"===e.key){if(!(!e.roles||e.roles.includes(x)||j))return!1;if(!t&&null!=a){let t=a.includes(e.page);return console.log(`[LeftNav] Page "${e.page}" (${e.key}): ${t?"VISIBLE":"HIDDEN"}`),t}return!0}if("projects"===e.key&&!o||!t&&"agents"===e.key&&c&&!(d&&v)||!t&&"vector-stores"===e.key&&p&&!(m&&v)||e.roles&&!e.roles.includes(x))return!1;if(!t&&null!=a){if(e.children&&e.children.length>0&&e.children.some(e=>a.includes(e.page)))return console.log(`[LeftNav] Parent "${e.page}" (${e.key}): VISIBLE (has visible children)`),!0;let t=a.includes(e.page);return console.log(`[LeftNav] Page "${e.page}" (${e.key}): ${t?"VISIBLE":"HIDDEN"}`),t}return!0})},k=(e=>{for(let t of V)for(let s of t.items){if(s.page===e)return s.key;if(s.children){let t=s.children.find(t=>t.page===e);if(t)return t.key}}return"api-keys"})(r);return(0,t.jsx)(B.Layout,{children:(0,t.jsxs)(D,{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)(M.ConfigProvider,{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)(U.Menu,{mode:"inline",selectedKeys:[k],defaultOpenKeys:[],inlineCollapsed:n,className:"custom-sidebar-menu",style:{borderRight:0,backgroundColor:"transparent",fontSize:"13px",paddingTop:"4px"},items:(g=[],V.forEach(e=>{if(e.roles&&!e.roles.includes(x))return;let s=I(e.items);0!==s.length&&g.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:e.groupLabel}),children:s.map(e=>({key:e.key,icon:e.icon,label:S(e.label,e.page,e.external_url),children:e.children?.map(e=>({key:e.key,icon:e.icon,label:S(e.label,e.page,e.external_url),onClick:()=>{e.external_url?window.open(e.external_url,"_blank"):b(e.page)}})),onClick:e.children?void 0:()=>{e.external_url?window.open(e.external_url,"_blank"):b(e.page)}}))})}),g)})}),(0,L.isAdminRole)(x)&&!n&&(0,t.jsx)(z.default,{accessToken:_,width:220})]})})},"menuGroups",()=>V],111672)},105278,e=>{"use strict";var t=e.i(843476),s=e.i(135214),l=e.i(994388),i=e.i(366283),r=e.i(304967),n=e.i(269200),a=e.i(942232),o=e.i(977572),c=e.i(427612),d=e.i(64848),u=e.i(496020),p=e.i(560445),m=e.i(464571),g=e.i(808613),h=e.i(311451),_=e.i(212931),x=e.i(770914),f=e.i(653496),y=e.i(898586),j=e.i(271645),v=e.i(844444),b=e.i(700514),S=e.i(727749),I=e.i(764205),k=e.i(461451),T=e.i(37329),C=e.i(292639),w=e.i(100070),E=e.i(111672);let O={"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","tool-policies":"Configure tool use policies and permissions","vector-stores":"Manage vector databases for embeddings",new_usage:"View usage analytics and metrics",logs:"Access request and response logs","guardrails-monitor":"Monitor guardrail performance and view logs",users:"Manage internal user accounts and permissions",teams:"Create and manage teams for access control",organizations:"Manage organizations and their members",projects:"Manage projects within teams","access-groups":"Manage access groups for role-based permissions",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 N=e.i(708347);let A=e=>!e||0===e.length||e.some(e=>N.internalUserRoles.includes(e));var P=e.i(536916),F=e.i(362024),M=e.i(262218);function B({enabledPagesInternalUsers:e,enabledPagesPropertyDescription:s,isUpdating:l,onUpdate:i}){let r=null!=e,n=(0,j.useMemo)(()=>{let e;return e=[],E.menuGroups.forEach(t=>{t.items.forEach(s=>{if(s.page&&"tools"!==s.page&&"experimental"!==s.page&&"settings"!==s.page&&A(s.roles)){let l="string"==typeof s.label?s.label:s.key;e.push({page:s.page,label:l,group:t.groupLabel,description:O[s.page]||"No description available"})}if(s.children){let l="string"==typeof s.label?s.label:s.key;s.children.forEach(s=>{if(A(s.roles)){let i="string"==typeof s.label?s.label:s.key;e.push({page:s.page,label:i,group:`${t.groupLabel} > ${l}`,description:O[s.page]||"No description available"})}})}})}),e},[]),a=(0,j.useMemo)(()=>{let e={};return n.forEach(t=>{e[t.group]||(e[t.group]=[]),e[t.group].push(t)}),e},[n]),[o,c]=(0,j.useState)(e||[]);return(0,j.useMemo)(()=>{e?c(e):c([])},[e]),(0,t.jsxs)(x.Space,{direction:"vertical",size:"middle",style:{width:"100%"},children:[(0,t.jsxs)(x.Space,{direction:"vertical",size:4,children:[(0,t.jsxs)(x.Space,{align:"center",children:[(0,t.jsx)(y.Typography.Text,{strong:!0,children:"Internal User Page Visibility"}),!r&&(0,t.jsx)(M.Tag,{color:"default",style:{marginLeft:"8px"},children:"Not set (all pages visible)"}),r&&(0,t.jsxs)(M.Tag,{color:"blue",style:{marginLeft:"8px"},children:[o.length," page",1!==o.length?"s":""," selected"]})]}),s&&(0,t.jsx)(y.Typography.Text,{type:"secondary",children:s}),(0,t.jsx)(y.Typography.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)(y.Typography.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)(F.Collapse,{items:[{key:"page-visibility",label:"Configure Page Visibility",children:(0,t.jsxs)(x.Space,{direction:"vertical",size:"middle",style:{width:"100%"},children:[(0,t.jsx)(P.Checkbox.Group,{value:o,onChange:c,style:{width:"100%"},children:(0,t.jsx)(x.Space,{direction:"vertical",size:"middle",style:{width:"100%"},children:Object.entries(a).map(([e,s])=>(0,t.jsxs)("div",{children:[(0,t.jsx)(y.Typography.Text,{strong:!0,style:{fontSize:"11px",color:"#6b7280",letterSpacing:"0.05em",display:"block",marginBottom:"8px"},children:e}),(0,t.jsx)(x.Space,{direction:"vertical",size:"small",style:{marginLeft:"16px",width:"100%"},children:s.map(e=>(0,t.jsx)("div",{style:{marginBottom:"4px"},children:(0,t.jsx)(P.Checkbox,{value:e.page,children:(0,t.jsxs)(x.Space,{direction:"vertical",size:0,children:[(0,t.jsx)(y.Typography.Text,{children:e.label}),(0,t.jsx)(y.Typography.Text,{type:"secondary",style:{fontSize:"12px"},children:e.description})]})})},e.page))})]},e))})}),(0,t.jsxs)(x.Space,{children:[(0,t.jsx)(m.Button,{type:"primary",onClick:()=>{i({enabled_ui_pages_internal_users:o.length>0?o:null})},loading:l,disabled:l,children:"Save Page Visibility Settings"}),r&&(0,t.jsx)(m.Button,{onClick:()=>{c([]),i({enabled_ui_pages_internal_users:null})},loading:l,disabled:l,children:"Reset to Default (All Pages)"})]})]})}]})]})}var U=e.i(175712),L=e.i(312361),R=e.i(981339),z=e.i(790848);function D(){let{accessToken:e}=(0,s.default)(),{data:l,isLoading:i,isError:r,error:n}=(0,C.useUISettings)(),{mutate:a,isPending:o,error:c}=(0,w.useUpdateUISettings)(e),d=l?.field_schema,u=d?.properties?.disable_model_add_for_internal_users,m=d?.properties?.disable_team_admin_delete_team_user,g=d?.properties?.require_auth_for_public_ai_hub,h=d?.properties?.forward_client_headers_to_llm_api,_=d?.properties?.enable_projects_ui,f=d?.properties?.enabled_ui_pages_internal_users,j=d?.properties?.disable_agents_for_internal_users,v=d?.properties?.allow_agents_for_team_admins,b=d?.properties?.disable_vector_stores_for_internal_users,I=d?.properties?.allow_vector_stores_for_team_admins,k=d?.properties?.scope_user_search_to_org,T=l?.values??{},E=!!T.disable_model_add_for_internal_users,O=!!T.disable_team_admin_delete_team_user,N=!!T.disable_agents_for_internal_users,A=!!T.disable_vector_stores_for_internal_users;return(0,t.jsx)(U.Card,{title:"UI Settings",children:i?(0,t.jsx)(R.Skeleton,{active:!0}):r?(0,t.jsx)(p.Alert,{type:"error",message:"Could not load UI settings",description:n instanceof Error?n.message:void 0}):(0,t.jsxs)(x.Space,{direction:"vertical",size:"large",style:{width:"100%"},children:[d?.description&&(0,t.jsx)(y.Typography.Paragraph,{style:{marginBottom:0},children:d.description}),c&&(0,t.jsx)(p.Alert,{type:"error",message:"Could not update UI settings",description:c instanceof Error?c.message:void 0}),(0,t.jsxs)(x.Space,{align:"start",size:"middle",children:[(0,t.jsx)(z.Switch,{checked:E,disabled:o,loading:o,onChange:e=>{a({disable_model_add_for_internal_users:e},{onSuccess:()=>{S.default.success("UI settings updated successfully")},onError:e=>{S.default.fromBackend(e)}})},"aria-label":u?.description??"Disable model add for internal users"}),(0,t.jsxs)(x.Space,{direction:"vertical",size:4,children:[(0,t.jsx)(y.Typography.Text,{strong:!0,children:"Disable model add for internal users"}),u?.description&&(0,t.jsx)(y.Typography.Text,{type:"secondary",children:u.description})]})]}),(0,t.jsxs)(x.Space,{align:"start",size:"middle",children:[(0,t.jsx)(z.Switch,{checked:O,disabled:o,loading:o,onChange:e=>{a({disable_team_admin_delete_team_user:e},{onSuccess:()=>{S.default.success("UI settings updated successfully")},onError:e=>{S.default.fromBackend(e)}})},"aria-label":m?.description??"Disable team admin delete team user"}),(0,t.jsxs)(x.Space,{direction:"vertical",size:4,children:[(0,t.jsx)(y.Typography.Text,{strong:!0,children:"Disable team admin delete team user"}),m?.description&&(0,t.jsx)(y.Typography.Text,{type:"secondary",children:m.description})]})]}),(0,t.jsxs)(x.Space,{align:"start",size:"middle",children:[(0,t.jsx)(z.Switch,{checked:T.require_auth_for_public_ai_hub,disabled:o,loading:o,onChange:e=>{a({require_auth_for_public_ai_hub:e},{onSuccess:()=>{S.default.success("UI settings updated successfully")},onError:e=>{S.default.fromBackend(e)}})},"aria-label":g?.description??"Require authentication for public AI Hub"}),(0,t.jsxs)(x.Space,{direction:"vertical",size:4,children:[(0,t.jsx)(y.Typography.Text,{strong:!0,children:"Require authentication for public AI Hub"}),g?.description&&(0,t.jsx)(y.Typography.Text,{type:"secondary",children:g.description})]})]}),(0,t.jsxs)(x.Space,{align:"start",size:"middle",children:[(0,t.jsx)(z.Switch,{checked:!!T.forward_client_headers_to_llm_api,disabled:o,loading:o,onChange:e=>{a({forward_client_headers_to_llm_api:e},{onSuccess:()=>{S.default.success("UI settings updated successfully")},onError:e=>{S.default.fromBackend(e)}})},"aria-label":h?.description??"Forward client headers to LLM API"}),(0,t.jsxs)(x.Space,{direction:"vertical",size:4,children:[(0,t.jsx)(y.Typography.Text,{strong:!0,children:"Forward client headers to LLM API"}),(0,t.jsx)(y.Typography.Text,{type:"secondary",children:h?.description??"If enabled, forwards client headers (e.g. Authorization) to the LLM API. Required for Claude Code with Max subscription."})]})]}),(0,t.jsxs)(x.Space,{align:"start",size:"middle",children:[(0,t.jsx)(z.Switch,{checked:!!T.enable_projects_ui,disabled:o,loading:o,onChange:e=>{a({enable_projects_ui:e},{onSuccess:()=>{S.default.success("UI settings updated successfully. Refreshing page..."),setTimeout(()=>window.location.reload(),1e3)},onError:e=>{S.default.fromBackend(e)}})},"aria-label":_?.description??"Enable Projects UI"}),(0,t.jsxs)(x.Space,{direction:"vertical",size:4,children:[(0,t.jsx)(y.Typography.Text,{strong:!0,children:"[BETA] Enable Projects (page will refresh)"}),(0,t.jsx)(y.Typography.Text,{type:"secondary",children:_?.description??"If enabled, shows the Projects feature in the UI sidebar and the project field in key management."})]})]}),(0,t.jsx)(L.Divider,{}),(0,t.jsxs)(x.Space,{align:"start",size:"middle",children:[(0,t.jsx)(z.Switch,{checked:N,disabled:o,loading:o,onChange:e=>{a({disable_agents_for_internal_users:e},{onSuccess:()=>{S.default.success("UI settings updated successfully")},onError:e=>{S.default.fromBackend(e)}})},"aria-label":j?.description??"Disable agents for internal users"}),(0,t.jsxs)(x.Space,{direction:"vertical",size:4,children:[(0,t.jsx)(y.Typography.Text,{strong:!0,children:"Disable agents for internal users"}),j?.description&&(0,t.jsx)(y.Typography.Text,{type:"secondary",children:j.description})]})]}),(0,t.jsxs)(x.Space,{align:"start",size:"middle",style:{marginLeft:32},children:[(0,t.jsx)(z.Switch,{checked:!!T.allow_agents_for_team_admins,disabled:o||!N,loading:o,onChange:e=>{a({allow_agents_for_team_admins:e},{onSuccess:()=>{S.default.success("UI settings updated successfully")},onError:e=>{S.default.fromBackend(e)}})},"aria-label":v?.description??"Allow agents for team admins"}),(0,t.jsxs)(x.Space,{direction:"vertical",size:4,children:[(0,t.jsx)(y.Typography.Text,{strong:!0,type:N?void 0:"secondary",children:"Allow agents for team admins"}),v?.description&&(0,t.jsx)(y.Typography.Text,{type:"secondary",children:v.description})]})]}),(0,t.jsx)(L.Divider,{}),(0,t.jsxs)(x.Space,{align:"start",size:"middle",children:[(0,t.jsx)(z.Switch,{checked:A,disabled:o,loading:o,onChange:e=>{a({disable_vector_stores_for_internal_users:e},{onSuccess:()=>{S.default.success("UI settings updated successfully")},onError:e=>{S.default.fromBackend(e)}})},"aria-label":b?.description??"Disable vector stores for internal users"}),(0,t.jsxs)(x.Space,{direction:"vertical",size:4,children:[(0,t.jsx)(y.Typography.Text,{strong:!0,children:"Disable vector stores for internal users"}),b?.description&&(0,t.jsx)(y.Typography.Text,{type:"secondary",children:b.description})]})]}),(0,t.jsxs)(x.Space,{align:"start",size:"middle",style:{marginLeft:32},children:[(0,t.jsx)(z.Switch,{checked:!!T.allow_vector_stores_for_team_admins,disabled:o||!A,loading:o,onChange:e=>{a({allow_vector_stores_for_team_admins:e},{onSuccess:()=>{S.default.success("UI settings updated successfully")},onError:e=>{S.default.fromBackend(e)}})},"aria-label":I?.description??"Allow vector stores for team admins"}),(0,t.jsxs)(x.Space,{direction:"vertical",size:4,children:[(0,t.jsx)(y.Typography.Text,{strong:!0,type:A?void 0:"secondary",children:"Allow vector stores for team admins"}),I?.description&&(0,t.jsx)(y.Typography.Text,{type:"secondary",children:I.description})]})]}),(0,t.jsx)(L.Divider,{}),(0,t.jsxs)(x.Space,{align:"start",size:"middle",children:[(0,t.jsx)(z.Switch,{checked:!!T.scope_user_search_to_org,disabled:o,loading:o,onChange:e=>{a({scope_user_search_to_org:e},{onSuccess:()=>{S.default.success("UI settings updated successfully")},onError:e=>{S.default.fromBackend(e)}})},"aria-label":k?.description??"Scope user search to organization"}),(0,t.jsxs)(x.Space,{direction:"vertical",size:4,children:[(0,t.jsx)(y.Typography.Text,{strong:!0,children:"Scope user search to organization"}),(0,t.jsx)(y.Typography.Text,{type:"secondary",children:k?.description??"If enabled, the user search endpoint restricts results by organization. When off, any authenticated user can search all users."})]})]}),(0,t.jsx)(L.Divider,{}),(0,t.jsx)(B,{enabledPagesInternalUsers:T.enabled_ui_pages_internal_users,enabledPagesPropertyDescription:f?.description,isUpdating:o,onUpdate:e=>{a(e,{onSuccess:()=>{S.default.success("Page visibility settings updated successfully")},onError:e=>{S.default.fromBackend(e)}})}})]})})}let V=async e=>{let t=(0,I.getProxyBaseUrl)(),s=t?`${t}/config_overrides/hashicorp_vault`:"/config_overrides/hashicorp_vault",l=await fetch(s,{method:"GET",headers:{[(0,I.getGlobalLitellmHeaderName)()]:`Bearer ${e}`}});if(!l.ok){let e=await l.json();throw Error((0,I.deriveErrorMessage)(e))}return await l.json()},G=async(e,t)=>{let s=(0,I.getProxyBaseUrl)(),l=s?`${s}/config_overrides/hashicorp_vault`:"/config_overrides/hashicorp_vault",i=await fetch(l,{method:"POST",headers:{[(0,I.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!i.ok){let e=await i.json();throw Error((0,I.deriveErrorMessage)(e))}return await i.json()},q=async e=>{let t=(0,I.getProxyBaseUrl)(),s=t?`${t}/config_overrides/hashicorp_vault`:"/config_overrides/hashicorp_vault",l=await fetch(s,{method:"DELETE",headers:{[(0,I.getGlobalLitellmHeaderName)()]:`Bearer ${e}`}});if(!l.ok){let e=await l.json();throw Error((0,I.deriveErrorMessage)(e))}return await l.json()},H=async e=>{let t=(0,I.getProxyBaseUrl)(),s=t?`${t}/config_overrides/hashicorp_vault/test_connection`:"/config_overrides/hashicorp_vault/test_connection",l=await fetch(s,{method:"POST",headers:{[(0,I.getGlobalLitellmHeaderName)()]:`Bearer ${e}`}});if(!l.ok){let e=await l.json();throw Error((0,I.deriveErrorMessage)(e))}return await l.json()};var $=e.i(266027);let K=(0,e.i(243652).createQueryKeys)("hashicorpVaultConfig"),W=()=>{let{accessToken:e}=(0,s.default)();return(0,$.useQuery)({queryKey:K.list({}),queryFn:async()=>{if(!e)throw Error("Access token is required");return V(e)},enabled:!!e,staleTime:36e5,gcTime:36e5})};var Q=e.i(954616),Y=e.i(912598);let J=e=>{let t=(0,Y.useQueryClient)();return(0,Q.useMutation)({mutationFn:async t=>{if(!e)throw Error("Access token is required");return G(e,t)},onSuccess:()=>{t.invalidateQueries({queryKey:K.all})}})};var Z=e.i(127952),X=e.i(869216),ee=e.i(525720),et=e.i(688511),es=e.i(475254);let el=(0,es.default)("key-round",[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]]),ei=(0,es.default)("plug-zap",[["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m18 3-4 4h6l-4 4",key:"16psg9"}]]);var er=e.i(727612);let en=new Set(["vault_token","approle_secret_id","client_key"]),ea={vault_addr:"Vault Address",vault_namespace:"Namespace",vault_mount_name:"KV Mount Name",vault_path_prefix:"Path Prefix",vault_token:"Token",approle_role_id:"Role ID",approle_secret_id:"Secret ID",approle_mount_path:"Mount Path",client_cert:"Client Certificate",client_key:"Client Key",vault_cert_role:"Certificate Role"},eo=[{title:"Connection",fields:["vault_addr","vault_namespace","vault_mount_name","vault_path_prefix"]},{title:"Token Authentication",subtitle:"Use a Vault token to authenticate. Only one auth method is required.",fields:["vault_token"]},{title:"AppRole Authentication",subtitle:"Use AppRole credentials to authenticate. Only one auth method is required.",fields:["approle_role_id","approle_secret_id","approle_mount_path"]},{title:"TLS",subtitle:"Optional client certificate for mTLS.",fields:["client_cert","client_key","vault_cert_role"]}],ec=({isVisible:e,onCancel:l,onSuccess:i})=>{let[r]=g.Form.useForm(),{accessToken:n}=(0,s.default)(),{data:a}=W(),{mutate:o,isPending:c}=J(n),d=a?.field_schema,u=d?.properties??{},p=a?.values??{};(0,j.useEffect)(()=>{if(e&&a){r.resetFields();let e={};for(let[t,s]of Object.entries(p))en.has(t)||(e[t]=s);r.setFieldsValue(e)}},[e,a,r]);let f=()=>{r.resetFields(),l()},v=e=>{let s=u[e];if(!s)return null;let l="vault_addr"===e?[{pattern:/^https?:\/\/.+/,message:"Must start with http:// or https://"}]:void 0,i=en.has(e),r=p[e],n=i&&null!=r&&""!==r?`Leave blank to keep existing (${r})`:s?.description;return(0,t.jsx)(g.Form.Item,{name:e,label:ea[e]??e,rules:l,children:i?(0,t.jsx)(h.Input.Password,{placeholder:n}):(0,t.jsx)(h.Input,{placeholder:s?.description})},e)};return(0,t.jsx)(_.Modal,{title:"Edit Hashicorp Vault Configuration",open:e,width:700,footer:(0,t.jsxs)(x.Space,{children:[(0,t.jsx)(m.Button,{onClick:f,disabled:c,children:"Cancel"}),(0,t.jsx)(m.Button,{type:"primary",loading:c,onClick:()=>r.submit(),children:c?"Saving...":"Save"})]}),onCancel:f,children:(0,t.jsx)(g.Form,{form:r,layout:"vertical",onFinish:e=>{let t={};for(let[s,l]of Object.entries(e))null!=l&&""!==l?t[s]=l:en.has(s)||(t[s]="");o(t,{onSuccess:()=>{S.default.success("Hashicorp Vault configuration updated successfully"),i()},onError:e=>{S.default.fromBackend(e)}})},children:eo.map((e,s)=>(0,t.jsxs)("div",{children:[s>0&&(0,t.jsx)(L.Divider,{}),(0,t.jsx)(y.Typography.Title,{level:5,style:{marginBottom:4},children:e.title}),e.subtitle&&(0,t.jsx)(y.Typography.Paragraph,{type:"secondary",style:{marginBottom:16},children:e.subtitle}),e.fields.map(v)]},e.title))})})};var ed=e.i(21548);let{Title:eu,Paragraph:ep}=y.Typography;function em({onAdd: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)(ed.Empty,{image:ed.Empty.PRESENTED_IMAGE_SIMPLE,description:(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(eu,{level:4,children:"No Vault Configuration Found"}),(0,t.jsx)(ep,{type:"secondary",className:"max-w-md mx-auto",children:"Configure Hashicorp Vault to securely manage provider API keys and secrets for your LiteLLM deployment."})]}),children:(0,t.jsx)(m.Button,{type:"primary",size:"large",onClick:e,className:"flex items-center gap-2 mx-auto mt-4",children:"Configure Vault"})})})}let{Title:eg,Text:eh}=y.Typography,e_={column:{xxl:1,xl:1,lg:1,md:1,sm:1,xs:1}};function ex(){let e,{accessToken:l}=(0,s.default)(),{data:i,isLoading:r,isError:n,error:a}=W(),{mutate:o,isPending:c}=(e=(0,Y.useQueryClient)(),(0,Q.useMutation)({mutationFn:async()=>{if(!l)throw Error("Access token is required");return q(l)},onSuccess:()=>{e.invalidateQueries({queryKey:K.all})}})),{mutate:d,isPending:u}=J(l),[g,h]=(0,j.useState)(!1),[_,f]=(0,j.useState)(!1),[v,b]=(0,j.useState)(null),[I,k]=(0,j.useState)(!1),T=i?.values??{},C=!!T.vault_addr,w=async()=>{if(l){k(!0);try{let e=await H(l);S.default.success(e.message||"Connection to Vault successful!")}catch(e){S.default.fromBackend(e)}finally{k(!1)}}};return(0,t.jsxs)(t.Fragment,{children:[r?(0,t.jsx)(U.Card,{children:(0,t.jsx)(R.Skeleton,{active:!0})}):n?(0,t.jsx)(U.Card,{children:(0,t.jsx)(p.Alert,{type:"error",message:"Could not load Hashicorp Vault configuration",description:a instanceof Error?a.message:void 0})}):(0,t.jsx)(U.Card,{children:(0,t.jsxs)(x.Space,{direction:"vertical",size:"large",className:"w-full",children:[(0,t.jsxs)(ee.Flex,{justify:"space-between",align:"center",children:[(0,t.jsxs)(ee.Flex,{align:"center",gap:12,children:[(0,t.jsx)(el,{className:"w-6 h-6 text-gray-400"}),(0,t.jsxs)("div",{children:[(0,t.jsx)(eg,{level:3,style:{marginBottom:0},children:"Hashicorp Vault"}),(0,t.jsx)(eh,{type:"secondary",children:"Manage secret manager configuration"})]})]}),(0,t.jsx)(x.Space,{children:C&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(m.Button,{icon:(0,t.jsx)(ei,{className:"w-4 h-4"}),loading:I,onClick:w,children:"Test Connection"}),(0,t.jsx)(m.Button,{icon:(0,t.jsx)(et.Edit,{className:"w-4 h-4"}),onClick:()=>h(!0),children:"Edit Configuration"}),(0,t.jsx)(m.Button,{danger:!0,icon:(0,t.jsx)(er.Trash2,{className:"w-4 h-4"}),onClick:()=>f(!0),children:"Delete Configuration"})]})})]}),C&&(0,t.jsx)(p.Alert,{type:"info",showIcon:!0,message:'Secrets must be stored with the field name "key"',description:(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(eh,{code:!0,children:"vault kv put secret/SECRET_NAME key=secret_value"}),(0,t.jsx)("br",{}),(0,t.jsx)(y.Typography.Link,{href:"https://docs.litellm.ai/docs/secret_managers/hashicorp_vault",target:"_blank",children:"View documentation"})]})}),C?(()=>{let e=Object.entries(T).filter(([e,t])=>null!=t&&""!==t);return 0===e.length?null:(0,t.jsxs)(X.Descriptions,{bordered:!0,...e_,children:[(0,t.jsx)(X.Descriptions.Item,{label:"Auth Method",children:(0,t.jsx)(eh,{children:T.approle_role_id||T.approle_secret_id?"AppRole":T.client_cert&&T.client_key?"TLS Certificate":T.vault_token?"Token":"None"})}),e.map(([e])=>{let s;return(0,t.jsx)(X.Descriptions.Item,{label:ea[e]??e,children:(s=T[e])?en.has(e)?(0,t.jsxs)(ee.Flex,{justify:"space-between",align:"center",children:[(0,t.jsx)(eh,{className:"font-mono text-gray-600",children:s}),(0,t.jsx)(m.Button,{type:"text",size:"small",danger:!0,icon:(0,t.jsx)(er.Trash2,{className:"w-3.5 h-3.5"}),onClick:()=>b(e)})]}):(0,t.jsx)(eh,{className:"font-mono text-gray-600",children:s}):(0,t.jsx)("span",{className:"text-gray-400 italic",children:"Not configured"})},e)})]})})():(0,t.jsx)(em,{onAdd:()=>h(!0)})]})}),(0,t.jsx)(ec,{isVisible:g,onCancel:()=>h(!1),onSuccess:()=>h(!1)}),(0,t.jsx)(Z.default,{isOpen:_,title:"Delete Hashicorp Vault Configuration?",message:"Models using Vault secrets will lose access to their API keys until a new configuration is saved.",resourceInformationTitle:"Vault Configuration",resourceInformation:[{label:"Vault Address",value:T.vault_addr}],onCancel:()=>f(!1),onOk:()=>{o(void 0,{onSuccess:()=>{S.default.success("Hashicorp Vault configuration deleted"),f(!1)},onError:e=>{S.default.fromBackend(e)}})},confirmLoading:c}),(0,t.jsx)(Z.default,{isOpen:null!==v,title:`Clear ${v?ea[v]??v:""}?`,message:"This will remove the stored value.",resourceInformationTitle:"Field",resourceInformation:[{label:"Field",value:v?ea[v]??v:""}],onCancel:()=>b(null),onOk:()=>{v&&d({[v]:""},{onSuccess:()=>{S.default.success(`${ea[v]??v} cleared`),b(null)},onError:e=>{S.default.fromBackend(e)}})},confirmLoading:u})]})}var ef=e.i(199133),ey=e.i(599724),ej=e.i(779241),ev=e.i(190702);let eb={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:""},eS={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"}]}},eI=({isAddSSOModalVisible:e,isInstructionsModalVisible:s,handleAddSSOOk:l,handleAddSSOCancel:i,handleShowInstructions:r,handleInstructionsOk:n,handleInstructionsCancel:a,form:o,accessToken:c,ssoConfigured:d=!1})=>{let[u,p]=(0,j.useState)(!1);(0,j.useEffect)(()=>{(async()=>{if(e&&c)try{let e=await (0,I.getSSOSettings)(c);if(console.log("Raw SSO data received:",e),e&&e.values){console.log("SSO values:",e.values),console.log("user_email from API:",e.values.user_email);let t=null;e.values.google_client_id?t="google":e.values.microsoft_client_id?t="microsoft":e.values.generic_client_id&&(t=e.values.generic_authorization_endpoint?.includes("okta")||e.values.generic_authorization_endpoint?.includes("auth0")?"okta":"generic");let s={};if(e.values.role_mappings){let t=e.values.role_mappings,l=e=>e&&0!==e.length?e.join(", "):"";s={use_role_mappings:!0,group_claim:t.group_claim,default_role:t.default_role||"internal_user",proxy_admin_teams:l(t.roles?.proxy_admin),admin_viewer_teams:l(t.roles?.proxy_admin_viewer),internal_user_teams:l(t.roles?.internal_user),internal_viewer_teams:l(t.roles?.internal_user_viewer)}}let l={sso_provider:t,proxy_base_url:e.values.proxy_base_url,user_email:e.values.user_email,...e.values,...s};console.log("Setting form values:",l),o.resetFields(),setTimeout(()=>{o.setFieldsValue(l),console.log("Form values set, current form values:",o.getFieldsValue())},100)}}catch(e){console.error("Failed to load SSO settings:",e)}})()},[e,c,o]);let x=async e=>{if(!c)return void S.default.fromBackend("No access token available");try{let{proxy_admin_teams:t,admin_viewer_teams:s,internal_user_teams:l,internal_viewer_teams:i,default_role:n,group_claim:a,use_role_mappings:o,...d}=e,u={...d};if(o){let e=e=>e&&""!==e.trim()?e.split(",").map(e=>e.trim()).filter(e=>e.length>0):[];u.role_mappings={provider:"generic",group_claim:a,default_role:({internal_user_viewer:"internal_user_viewer",internal_user:"internal_user",proxy_admin_viewer:"proxy_admin_viewer",proxy_admin:"proxy_admin"})[n]||"internal_user",roles:{proxy_admin:e(t),proxy_admin_viewer:e(s),internal_user:e(l),internal_user_viewer:e(i)}}}await (0,I.updateSSOSettings)(c,u),r(e)}catch(e){S.default.fromBackend("Failed to save SSO settings: "+(0,ev.parseErrorMessage)(e))}},f=async()=>{if(!c)return void S.default.fromBackend("No access token available");try{await (0,I.updateSSOSettings)(c,{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}),o.resetFields(),p(!1),l(),S.default.success("SSO settings cleared successfully")}catch(e){console.error("Failed to clear SSO settings:",e),S.default.fromBackend("Failed to clear SSO settings")}};return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(_.Modal,{title:d?"Edit SSO Settings":"Add SSO",open:e,width:800,footer:null,onOk:l,onCancel:i,children:(0,t.jsxs)(g.Form,{form:o,onFinish:x,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(g.Form.Item,{label:"SSO Provider",name:"sso_provider",rules:[{required:!0,message:"Please select an SSO provider"}],children:(0,t.jsx)(ef.Select,{children:Object.entries(eb).map(([e,s])=>(0,t.jsx)(ef.Select.Option,{value:e,children:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"4px 0"},children:[s&&(0,t.jsx)("img",{src:s,alt:e,style:{height:24,width:24,marginRight:12,objectFit:"contain"}}),(0,t.jsxs)("span",{children:["okta"===e.toLowerCase()?"Okta / Auth0":e.charAt(0).toUpperCase()+e.slice(1)," ","SSO"]})]})},e))})}),(0,t.jsx)(g.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.sso_provider!==t.sso_provider,children:({getFieldValue:e})=>{let s,l=e("sso_provider");return l&&(s=eS[l])?s.fields.map(e=>(0,t.jsx)(g.Form.Item,{label:e.label,name:e.name,rules:[{required:!0,message:`Please enter the ${e.label.toLowerCase()}`}],children:e.name.includes("client")?(0,t.jsx)(h.Input.Password,{}):(0,t.jsx)(ej.TextInput,{placeholder:e.placeholder})},e.name)):null}}),(0,t.jsx)(g.Form.Item,{label:"Proxy Admin Email",name:"user_email",rules:[{required:!0,message:"Please enter the email of the proxy admin"}],children:(0,t.jsx)(ej.TextInput,{})}),(0,t.jsx)(g.Form.Item,{label:"Proxy Base URL",name:"proxy_base_url",normalize:e=>e?.trim(),rules:[{required:!0,message:"Please enter the proxy base url"},{pattern:/^https?:\/\/.+/,message:"URL must start with http:// or https://"},{validator:(e,t)=>t&&/^https?:\/\/.+/.test(t)&&t.endsWith("/")?Promise.reject("URL must not end with a trailing slash"):Promise.resolve()}],children:(0,t.jsx)(ej.TextInput,{placeholder:"https://example.com"})}),(0,t.jsx)(g.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.sso_provider!==t.sso_provider,children:({getFieldValue:e})=>{let s=e("sso_provider");return"okta"===s||"generic"===s?(0,t.jsx)(g.Form.Item,{label:"Use Role Mappings",name:"use_role_mappings",valuePropName:"checked",children:(0,t.jsx)(P.Checkbox,{})}):null}}),(0,t.jsx)(g.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.use_role_mappings!==t.use_role_mappings,children:({getFieldValue:e})=>e("use_role_mappings")?(0,t.jsx)(g.Form.Item,{label:"Group Claim",name:"group_claim",rules:[{required:!0,message:"Please enter the group claim"}],children:(0,t.jsx)(ej.TextInput,{})}):null}),(0,t.jsx)(g.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.use_role_mappings!==t.use_role_mappings,children:({getFieldValue:e})=>e("use_role_mappings")?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(g.Form.Item,{label:"Default Role",name:"default_role",initialValue:"Internal User",children:(0,t.jsxs)(ef.Select,{children:[(0,t.jsx)(ef.Select.Option,{value:"internal_user_viewer",children:"Internal Viewer"}),(0,t.jsx)(ef.Select.Option,{value:"internal_user",children:"Internal User"}),(0,t.jsx)(ef.Select.Option,{value:"proxy_admin_viewer",children:"Admin Viewer"}),(0,t.jsx)(ef.Select.Option,{value:"proxy_admin",children:"Proxy Admin"})]})}),(0,t.jsx)(g.Form.Item,{label:"Proxy Admin Teams",name:"proxy_admin_teams",children:(0,t.jsx)(ej.TextInput,{})}),(0,t.jsx)(g.Form.Item,{label:"Admin Viewer Teams",name:"admin_viewer_teams",children:(0,t.jsx)(ej.TextInput,{})}),(0,t.jsx)(g.Form.Item,{label:"Internal User Teams",name:"internal_user_teams",children:(0,t.jsx)(ej.TextInput,{})}),(0,t.jsx)(g.Form.Item,{label:"Internal Viewer Teams",name:"internal_viewer_teams",children:(0,t.jsx)(ej.TextInput,{})})]}):null})]}),(0,t.jsxs)("div",{style:{textAlign:"right",marginTop:"10px",display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"8px"},children:[d&&(0,t.jsx)(m.Button,{onClick:()=>p(!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)(m.Button,{htmlType:"submit",children:"Save"})]})]})}),(0,t.jsxs)(_.Modal,{title:"Confirm Clear SSO Settings",open:u,onOk:f,onCancel:()=>p(!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)(_.Modal,{title:"SSO Setup Instructions",open:s,width:800,footer:null,onOk:n,onCancel:a,children:[(0,t.jsx)("p",{children:"Follow these steps to complete the SSO setup:"}),(0,t.jsx)(ey.Text,{className:"mt-2",children:"1. DO NOT Exit this TAB"}),(0,t.jsx)(ey.Text,{className:"mt-2",children:"2. Open a new tab, visit your proxy base url"}),(0,t.jsx)(ey.Text,{className:"mt-2",children:"3. Confirm your SSO is configured correctly and you can login on the new Tab"}),(0,t.jsx)(ey.Text,{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)(m.Button,{onClick:n,children:"Done"})})]})]})},ek=({accessToken:e,onSuccess:s})=>{let[l]=g.Form.useForm(),[i,r]=(0,j.useState)(!1);(0,j.useEffect)(()=>{(async()=>{if(e)try{let t=await (0,I.getSSOSettings)(e);if(t&&t.values){let e=t.values.ui_access_mode,s={};e&&"object"==typeof e?s={ui_access_mode_type:e.type,restricted_sso_group:e.restricted_sso_group,sso_group_jwt_field:e.sso_group_jwt_field}:"string"==typeof e&&(s={ui_access_mode_type:e,restricted_sso_group:t.values.restricted_sso_group,sso_group_jwt_field:t.values.team_ids_jwt_field||t.values.sso_group_jwt_field}),l.setFieldsValue(s)}}catch(e){console.error("Failed to load UI access settings:",e)}})()},[e,l]);let n=async t=>{if(!e)return void S.default.fromBackend("No access token available");r(!0);try{let l;l="all_authenticated_users"===t.ui_access_mode_type?{ui_access_mode:"none"}:{ui_access_mode:{type:t.ui_access_mode_type,restricted_sso_group:t.restricted_sso_group,sso_group_jwt_field:t.sso_group_jwt_field}},await (0,I.updateSSOSettings)(e,l),s()}catch(e){console.error("Failed to save UI access settings:",e),S.default.fromBackend("Failed to save UI access settings")}finally{r(!1)}};return(0,t.jsxs)("div",{style:{padding:"16px"},children:[(0,t.jsx)("div",{style:{marginBottom:"16px"},children:(0,t.jsx)(ey.Text,{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)(g.Form,{form:l,onFinish:n,layout:"vertical",children:[(0,t.jsx)(g.Form.Item,{label:"UI Access Mode",name:"ui_access_mode_type",tooltip:"Controls who can access the UI interface",children:(0,t.jsxs)(ef.Select,{placeholder:"Select access mode",children:[(0,t.jsx)(ef.Select.Option,{value:"all_authenticated_users",children:"All Authenticated Users"}),(0,t.jsx)(ef.Select.Option,{value:"restricted_sso_group",children:"Restricted SSO Group"})]})}),(0,t.jsx)(g.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.ui_access_mode_type!==t.ui_access_mode_type,children:({getFieldValue:e})=>"restricted_sso_group"===e("ui_access_mode_type")?(0,t.jsx)(g.Form.Item,{label:"Restricted SSO Group",name:"restricted_sso_group",rules:[{required:!0,message:"Please enter the restricted SSO group"}],children:(0,t.jsx)(ej.TextInput,{placeholder:"ui-access-group"})}):null}),(0,t.jsx)(g.Form.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)(ej.TextInput,{placeholder:"groups"})}),(0,t.jsx)("div",{style:{textAlign:"right",marginTop:"16px"},children:(0,t.jsx)(m.Button,{type:"primary",htmlType:"submit",loading:i,style:{backgroundColor:"#6366f1",borderColor:"#6366f1"},children:"Update UI Access Control"})})]})]})},{Title:eT,Paragraph:eC,Text:ew}=y.Typography;e.s(["default",0,({proxySettings:e})=>{let{premiumUser:y,accessToken:C,userId:w}=(0,s.default)(),[E]=g.Form.useForm(),[O,N]=(0,j.useState)(!1),[A,P]=(0,j.useState)(!1),[F,M]=(0,j.useState)(!1),[B,U]=(0,j.useState)(!1),[L,R]=(0,j.useState)(!1),[z,V]=(0,j.useState)(!1),[G,q]=(0,j.useState)([]),[H,$]=(0,j.useState)(null),[K,W]=(0,j.useState)(!1),Q=(0,b.useBaseUrl)(),Y="All IP Addresses Allowed",J=Q;J+="/fallback/login";let Z=async()=>{if(C)try{let e=await (0,I.getSSOSettings)(C);if(e&&e.values){let t=e.values.google_client_id&&e.values.google_client_secret,s=e.values.microsoft_client_id&&e.values.microsoft_client_secret,l=e.values.generic_client_id&&e.values.generic_client_secret;W(t||s||l)}else W(!1)}catch(e){console.error("Error checking SSO configuration:",e),W(!1)}},X=async()=>{try{if(!0!==y)return void S.default.fromBackend("This feature is only available for premium users. Please upgrade your account.");if(C){let e=await (0,I.getAllowedIPs)(C);q(e&&e.length>0?e:[Y])}else q([Y])}catch(e){console.error("Error fetching allowed IPs:",e),S.default.fromBackend(`Failed to fetch allowed IPs ${e}`),q([Y])}finally{!0===y&&M(!0)}},ee=async e=>{try{if(C){await (0,I.addAllowedIP)(C,e.ip);let t=await (0,I.getAllowedIPs)(C);q(t),S.default.success("IP address added successfully")}}catch(e){console.error("Error adding IP:",e),S.default.fromBackend(`Failed to add IP address ${e}`)}finally{U(!1)}},et=async e=>{$(e),R(!0)},es=async()=>{if(H&&C)try{await (0,I.deleteAllowedIP)(C,H);let e=await (0,I.getAllowedIPs)(C);q(e.length>0?e:[Y]),S.default.success("IP address deleted successfully")}catch(e){console.error("Error deleting IP:",e),S.default.fromBackend(`Failed to delete IP address ${e}`)}finally{R(!1),$(null)}};(0,j.useEffect)(()=>{Z()},[C,y,Z]);let el=()=>{V(!1)},ei=[{key:"sso-settings",label:"SSO Settings",children:(0,t.jsx)(T.default,{})},{key:"security-settings",label:"Security Settings",children:(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(r.Card,{children:[(0,t.jsx)(eT,{level:4,children:" ✨ Security Settings"}),(0,t.jsx)(p.Alert,{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)(l.Button,{style:{width:"150px"},onClick:()=>N(!0),children:K?"Edit SSO Settings":"Add SSO"})}),(0,t.jsx)("div",{children:(0,t.jsx)(l.Button,{style:{width:"150px"},onClick:X,children:"Allowed IPs"})}),(0,t.jsx)("div",{children:(0,t.jsx)(l.Button,{style:{width:"150px"},onClick:()=>!0===y?V(!0):S.default.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)(eI,{isAddSSOModalVisible:O,isInstructionsModalVisible:A,handleAddSSOOk:()=>{N(!1),E.resetFields(),C&&y&&Z()},handleAddSSOCancel:()=>{N(!1),E.resetFields()},handleShowInstructions:e=>{N(!1),P(!0)},handleInstructionsOk:()=>{P(!1),C&&y&&Z()},handleInstructionsCancel:()=>{P(!1),C&&y&&Z()},form:E,accessToken:C,ssoConfigured:K}),(0,t.jsx)(_.Modal,{title:"Manage Allowed IP Addresses",width:800,open:F,onCancel:()=>M(!1),footer:[(0,t.jsx)(l.Button,{className:"mx-1",onClick:()=>U(!0),children:"Add IP Address"},"add"),(0,t.jsx)(l.Button,{onClick:()=>M(!1),children:"Close"},"close")],children:(0,t.jsxs)(n.Table,{children:[(0,t.jsx)(c.TableHead,{children:(0,t.jsxs)(u.TableRow,{children:[(0,t.jsx)(d.TableHeaderCell,{children:"IP Address"}),(0,t.jsx)(d.TableHeaderCell,{className:"text-right",children:"Action"})]})}),(0,t.jsx)(a.TableBody,{children:G.map((e,s)=>(0,t.jsxs)(u.TableRow,{children:[(0,t.jsx)(o.TableCell,{children:e}),(0,t.jsx)(o.TableCell,{className:"text-right",children:e!==Y&&(0,t.jsx)(l.Button,{onClick:()=>et(e),color:"red",size:"xs",children:"Delete"})})]},s))})]})}),(0,t.jsx)(_.Modal,{title:"Add Allowed IP Address",open:B,onCancel:()=>U(!1),footer:null,children:(0,t.jsxs)(g.Form,{onFinish:ee,children:[(0,t.jsx)(g.Form.Item,{name:"ip",rules:[{required:!0,message:"Please enter an IP address"}],children:(0,t.jsx)(h.Input,{placeholder:"Enter IP address"})}),(0,t.jsx)(g.Form.Item,{children:(0,t.jsx)(m.Button,{htmlType:"submit",children:"Add IP Address"})})]})}),(0,t.jsx)(_.Modal,{title:"Confirm Delete",open:L,onCancel:()=>R(!1),onOk:es,footer:[(0,t.jsx)(l.Button,{className:"mx-1",onClick:()=>es(),children:"Yes"},"delete"),(0,t.jsx)(l.Button,{onClick:()=>R(!1),children:"Close"},"close")],children:(0,t.jsxs)(ew,{children:["Are you sure you want to delete the IP address: ",H,"?"]})}),(0,t.jsx)(_.Modal,{title:"UI Access Control Settings",open:z,width:600,footer:null,onOk:el,onCancel:()=>{V(!1)},children:(0,t.jsx)(ek,{accessToken:C,onSuccess:()=>{el(),S.default.success("UI Access Control settings updated successfully")}})})]}),(0,t.jsxs)(i.Callout,{title:"Login without SSO",color:"teal",children:["If you need to login without sso, you can access"," ",(0,t.jsxs)("a",{href:J,target:"_blank",rel:"noopener noreferrer",children:[(0,t.jsx)("b",{children:J})," "]})]})]})},{key:"scim",label:"SCIM",children:(0,t.jsx)(k.default,{accessToken:C,userID:w,proxySettings:e})},{key:"ui-settings",label:(0,t.jsx)(x.Space,{children:(0,t.jsxs)(ew,{children:["UI Settings ",(0,t.jsx)(v.default,{})]})}),children:(0,t.jsx)(D,{})},{key:"hashicorp-vault",label:"Hashicorp Vault",children:(0,t.jsx)(ex,{})}];return(0,t.jsxs)("div",{className:"w-full m-2 mt-2 p-8",children:[(0,t.jsx)(eT,{level:4,children:"Admin Access "}),(0,t.jsx)(eC,{children:"Go to 'Internal Users' page to add other admins."}),(0,t.jsx)(f.Tabs,{items:ei})]})}],105278)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/357cb7abc13b2168.js b/litellm/proxy/_experimental/out/_next/static/chunks/5b44cdfc729a6dc9.js similarity index 92% rename from litellm/proxy/_experimental/out/_next/static/chunks/357cb7abc13b2168.js rename to litellm/proxy/_experimental/out/_next/static/chunks/5b44cdfc729a6dc9.js index 06247a44177..596897ca5d2 100644 --- a/litellm/proxy/_experimental/out/_next/static/chunks/357cb7abc13b2168.js +++ b/litellm/proxy/_experimental/out/_next/static/chunks/5b44cdfc729a6dc9.js @@ -1 +1 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,596115,e=>{"use strict";var s=e.i(843476),l=e.i(271645),a=e.i(764205),t=e.i(584578),r=e.i(808613),i=e.i(56567),o=e.i(468133),n=e.i(708347),d=e.i(304967),c=e.i(994388),m=e.i(309426),h=e.i(599724),u=e.i(350967),x=e.i(404206),p=e.i(747871),g=e.i(500330),_=e.i(752978),j=e.i(197647),f=e.i(653824),b=e.i(881073),y=e.i(723731),v=e.i(278587);let w=({lastRefreshed:e,onRefresh:l,userRole:a,children:t})=>(0,s.jsxs)(f.TabGroup,{className:"gap-2 h-[75vh] w-full",children:[(0,s.jsxs)(b.TabList,{className:"flex justify-between mt-2 w-full items-center",children:[(0,s.jsxs)("div",{className:"flex",children:[(0,s.jsx)(j.Tab,{children:"Your Teams"}),(0,s.jsx)(j.Tab,{children:"Available Teams"}),(0,n.isAdminRole)(a||"")&&(0,s.jsx)(j.Tab,{children:"Default Team Settings"})]}),(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[e&&(0,s.jsxs)(h.Text,{children:["Last Refreshed: ",e]}),(0,s.jsx)(_.Icon,{icon:v.RefreshIcon,variant:"shadow",size:"xs",className:"self-center",onClick:l})]})]}),(0,s.jsx)(y.TabPanels,{children:t})]});var T=e.i(206929),C=e.i(35983);let N=({filters:e,organizations:l,showFilters:a,onToggleFilters:t,onChange:r,onReset:i})=>(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 by Team Name...",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:e.team_alias,onChange:e=>r("team_alias",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 ${a?"bg-gray-100":""}`,onClick:()=>t(!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",(e.team_id||e.team_alias||e.organization_id)&&(0,s.jsx)("span",{"data-testid":"active-filter-indicator",className:"w-2 h-2 rounded-full bg-blue-500"})]}),(0,s.jsxs)("button",{className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2",onClick:i,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.jsxs)("div",{className:"relative w-64",children:[(0,s.jsx)("input",{type:"text",placeholder:"Enter Team ID",className:"w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:e.team_id,onChange:e=>r("team_id",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:"M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0zm6 2a9 9 0 11-18 0 9 9 0 0118 0z"})})]}),(0,s.jsx)("div",{className:"w-64",children:(0,s.jsx)(T.Select,{value:e.organization_id||"",onValueChange:e=>r("organization_id",e),placeholder:"Select Organization",children:l?.map(e=>(0,s.jsx)(C.SelectItem,{value:e.organization_id||"",children:e.organization_alias||e.organization_id},e.organization_id))})})]})]});var S=e.i(135214),k=e.i(269200),I=e.i(942232),F=e.i(977572),A=e.i(427612),z=e.i(64848),M=e.i(496020),O=e.i(592968),P=e.i(591935),L=e.i(68155),D=e.i(389083),B=e.i(871943),E=e.i(502547),R=e.i(355619);let V=({team:e})=>{let[a,t]=(0,l.useState)(!1);return(0,s.jsx)(F.TableCell,{style:{maxWidth:"8-x",whiteSpace:"pre-wrap",overflow:"hidden"},className:e.models.length>3?"px-0":"",children:(0,s.jsx)("div",{className:"flex flex-col",children:Array.isArray(e.models)?(0,s.jsx)("div",{className:"flex flex-col",children:0===e.models.length?(0,s.jsx)(D.Badge,{size:"xs",className:"mb-1",color:"red",children:(0,s.jsx)(h.Text,{children:"All Proxy Models"})}):(0,s.jsx)(s.Fragment,{children:(0,s.jsxs)("div",{className:"flex items-start",children:[e.models.length>3&&(0,s.jsx)("div",{children:(0,s.jsx)(_.Icon,{icon:a?B.ChevronDownIcon:E.ChevronRightIcon,className:"cursor-pointer",size:"xs",onClick:()=>{t(e=>!e)}})}),(0,s.jsxs)("div",{className:"flex flex-wrap gap-1",children:[e.models.slice(0,3).map((e,l)=>"all-proxy-models"===e?(0,s.jsx)(D.Badge,{size:"xs",color:"red",children:(0,s.jsx)(h.Text,{children:"All Proxy Models"})},l):(0,s.jsx)(D.Badge,{size:"xs",color:"blue",children:(0,s.jsx)(h.Text,{children:e.length>30?`${(0,R.getModelDisplayName)(e).slice(0,30)}...`:(0,R.getModelDisplayName)(e)})},l)),e.models.length>3&&!a&&(0,s.jsx)(D.Badge,{size:"xs",color:"gray",className:"cursor-pointer",children:(0,s.jsxs)(h.Text,{children:["+",e.models.length-3," ",e.models.length-3==1?"more model":"more models"]})}),a&&(0,s.jsx)("div",{className:"flex flex-wrap gap-1",children:e.models.slice(3).map((e,l)=>"all-proxy-models"===e?(0,s.jsx)(D.Badge,{size:"xs",color:"red",children:(0,s.jsx)(h.Text,{children:"All Proxy Models"})},l+3):(0,s.jsx)(D.Badge,{size:"xs",color:"blue",children:(0,s.jsx)(h.Text,{children:e.length>30?`${(0,R.getModelDisplayName)(e).slice(0,30)}...`:(0,R.getModelDisplayName)(e)})},l+3))})]})]})})}):null})})};var H=e.i(918549),H=H,W=e.i(846753),W=W;let U=({team:e,userId:l})=>{var a;let t,r=(a=((e,s)=>{if(!s)return null;let l=e.members_with_roles?.find(e=>e.user_id===s);return l?.role??null})(e,l),t="inline-flex items-center px-2.5 py-0.5 rounded-md text-xs font-medium border","admin"===a?(0,s.jsxs)("span",{className:t,style:{backgroundColor:"#EEF2FF",color:"#3730A3",borderColor:"#C7D2FE"},children:[(0,s.jsx)(H.default,{className:"h-3 w-3 mr-1"}),"Admin"]}):(0,s.jsxs)("span",{className:t,style:{backgroundColor:"#F3F4F6",color:"#4B5563",borderColor:"#E5E7EB"},children:[(0,s.jsx)(W.default,{className:"h-3 w-3 mr-1"}),"Member"]}));return(0,s.jsx)(F.TableCell,{children:r})},$=({teams:e,currentOrg:l,setSelectedTeamId:a,perTeamInfo:t,userRole:r,userId:i,setEditTeam:o,onDeleteTeam:n})=>(0,s.jsxs)(k.Table,{children:[(0,s.jsx)(A.TableHead,{children:(0,s.jsxs)(M.TableRow,{children:[(0,s.jsx)(z.TableHeaderCell,{children:"Team Name"}),(0,s.jsx)(z.TableHeaderCell,{children:"Team ID"}),(0,s.jsx)(z.TableHeaderCell,{children:"Created"}),(0,s.jsx)(z.TableHeaderCell,{children:"Spend (USD)"}),(0,s.jsx)(z.TableHeaderCell,{children:"Budget (USD)"}),(0,s.jsx)(z.TableHeaderCell,{children:"Models"}),(0,s.jsx)(z.TableHeaderCell,{children:"Organization"}),(0,s.jsx)(z.TableHeaderCell,{children:"Your Role"}),(0,s.jsx)(z.TableHeaderCell,{children:"Info"})]})}),(0,s.jsx)(I.TableBody,{children:e&&e.length>0?e.filter(e=>!l||e.organization_id===l.organization_id).sort((e,s)=>new Date(s.created_at).getTime()-new Date(e.created_at).getTime()).map(e=>(0,s.jsxs)(M.TableRow,{children:[(0,s.jsx)(F.TableCell,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:e.team_alias}),(0,s.jsx)(F.TableCell,{children:(0,s.jsx)("div",{className:"overflow-hidden",children:(0,s.jsx)(O.Tooltip,{title:e.team_id,children:(0,s.jsxs)(c.Button,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>{a(e.team_id)},children:[e.team_id.slice(0,7),"..."]})})})}),(0,s.jsx)(F.TableCell,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:e.created_at?new Date(e.created_at).toLocaleDateString():"N/A"}),(0,s.jsx)(F.TableCell,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:(0,g.formatNumberWithCommas)(e.spend,4)}),(0,s.jsx)(F.TableCell,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:null!==e.max_budget&&void 0!==e.max_budget?e.max_budget:"No limit"}),(0,s.jsx)(V,{team:e}),(0,s.jsx)(F.TableCell,{children:e.organization_id}),(0,s.jsx)(U,{team:e,userId:i}),(0,s.jsxs)(F.TableCell,{children:[(0,s.jsxs)(h.Text,{children:[t&&e.team_id&&t[e.team_id]&&t[e.team_id].keys&&t[e.team_id].keys.length," ","Keys"]}),(0,s.jsxs)(h.Text,{children:[t&&e.team_id&&t[e.team_id]&&t[e.team_id].team_info&&t[e.team_id].team_info.members_with_roles&&t[e.team_id].team_info.members_with_roles.length," ","Members"]})]}),(0,s.jsx)(F.TableCell,{children:"Admin"==r?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(_.Icon,{icon:P.PencilAltIcon,size:"sm",onClick:()=>{a(e.team_id),o(!0)}}),(0,s.jsx)(_.Icon,{onClick:()=>n(e.team_id),icon:L.TrashIcon,size:"sm"})]}):null})]},e.team_id)):null})]});var G=e.i(582458),G=G,J=e.i(995926);let K=({teams:e,teamToDelete:a,onCancel:t,onConfirm:r})=>{let[i,o]=(0,l.useState)(""),n=e?.find(e=>e.team_id===a),d=n?.team_alias||"",c=n?.keys?.length||0,m=i===d;return(0,s.jsx)("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:(0,s.jsxs)("div",{className:"bg-white rounded-lg shadow-xl w-full max-w-2xl min-h-[380px] py-6 overflow-hidden transform transition-all flex flex-col justify-between",children:[(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center justify-between px-6 py-4 border-b border-gray-200",children:[(0,s.jsx)("h3",{className:"text-lg font-semibold text-gray-900",children:"Delete Team"}),(0,s.jsx)("button",{"aria-label":"Close",onClick:()=>{t(),o("")},className:"text-gray-400 hover:text-gray-500 focus:outline-none",children:(0,s.jsx)(J.XIcon,{size:20})})]}),(0,s.jsxs)("div",{className:"px-6 py-4",children:[c>0&&(0,s.jsxs)("div",{className:"flex items-start gap-3 p-4 bg-red-50 border border-red-100 rounded-md mb-5",children:[(0,s.jsx)("div",{className:"text-red-500 mt-0.5",children:(0,s.jsx)(G.default,{size:20})}),(0,s.jsxs)("div",{children:[(0,s.jsxs)("p",{className:"text-base font-medium text-red-600",children:["Warning: This team has ",c," associated key",c>1?"s":"","."]}),(0,s.jsx)("p",{className:"text-base text-red-600 mt-2",children:"Deleting the team will also delete all associated keys. This action is irreversible."})]})]}),(0,s.jsx)("p",{className:"text-base text-gray-600 mb-5",children:"Are you sure you want to force delete this team and all its keys?"}),(0,s.jsxs)("div",{className:"mb-5",children:[(0,s.jsxs)("label",{className:"block text-base font-medium text-gray-700 mb-2",children:["Type ",(0,s.jsx)("span",{className:"underline",children:d})," to confirm deletion:"]}),(0,s.jsx)("input",{type:"text",value:i,onChange:e=>o(e.target.value),placeholder:"Enter team name exactly",className:"w-full px-4 py-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-base",autoFocus:!0})]})]})]}),(0,s.jsxs)("div",{className:"px-6 py-4 bg-gray-50 flex justify-end gap-4",children:[(0,s.jsx)("button",{onClick:()=>{t(),o("")},className:"px-5 py-3 bg-white border border-gray-300 rounded-md text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500",children:"Cancel"}),(0,s.jsx)("button",{onClick:r,disabled:!m,className:`px-5 py-3 rounded-md text-base font-medium text-white focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 ${m?"bg-red-600 hover:bg-red-700":"bg-red-300 cursor-not-allowed"}`,children:"Force Delete"})]})]})})};var q=e.i(464571),Y=e.i(311451),X=e.i(212931),Q=e.i(199133),Z=e.i(790848),ee=e.i(677667),es=e.i(130643),el=e.i(898667),ea=e.i(779241),et=e.i(827252),er=e.i(435451),ei=e.i(916940),eo=e.i(75921),en=e.i(552130),ed=e.i(651904),ec=e.i(533882),em=e.i(727749),eh=e.i(390605);let eu=({isTeamModalVisible:e,handleOk:t,handleCancel:i,currentOrg:o,organizations:n,teams:d,setTeams:c,modelAliases:m,setModelAliases:u,loggingSettings:x,setLoggingSettings:p,setIsTeamModalVisible:g})=>{let{userId:_,userRole:j,accessToken:f,premiumUser:b}=(0,S.default)(),[y]=r.Form.useForm(),[v,w]=(0,l.useState)([]),[T,C]=(0,l.useState)(null),[N,k]=(0,l.useState)([]),[I,F]=(0,l.useState)([]),[A,z]=(0,l.useState)([]),[M,P]=(0,l.useState)([]),[L,D]=(0,l.useState)(!1);(0,l.useEffect)(()=>{(async()=>{try{if(null===_||null===j||null===f)return;let e=await (0,R.fetchAvailableModelsForTeamOrKey)(_,j,f);e&&w(e)}catch(e){console.error("Error fetching user models:",e)}})()},[f,_,j,d]),(0,l.useEffect)(()=>{let e;console.log(`currentOrgForCreateTeam: ${T}`);let s=(e=[],T&&T.models.length>0?(console.log(`organization.models: ${T.models}`),e=T.models):e=v,(0,R.unfurlWildcardModelsInList)(e,v));console.log(`models: ${s}`),k(s),y.setFieldValue("models",[])},[T,v,y]);let B=async()=>{try{if(null==f)return;let e=await (0,a.fetchMCPAccessGroups)(f);P(e)}catch(e){console.error("Failed to fetch MCP access groups:",e)}};(0,l.useEffect)(()=>{B()},[f,B]),(0,l.useEffect)(()=>{let e=async()=>{try{if(null==f)return;let e=(await (0,a.getPoliciesList)(f)).policies.map(e=>e.policy_name);z(e)}catch(e){console.error("Failed to fetch policies:",e)}};(async()=>{try{if(null==f)return;let e=(await (0,a.getGuardrailsList)(f)).guardrails.map(e=>e.guardrail_name);F(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})(),e()},[f]);let E=async e=>{try{if(console.log(`formValues: ${JSON.stringify(e)}`),null!=f){let s=e?.team_alias,l=d?.map(e=>e.team_alias)??[],t=e?.organization_id||o?.organization_id;if(""===t||"string"!=typeof t?e.organization_id=null:e.organization_id=t.trim(),l.includes(s))throw Error(`Team alias ${s} already exists, please pick another alias`);if(em.default.info("Creating Team"),x.length>0){let s={};if(e.metadata)try{s=JSON.parse(e.metadata)}catch(e){console.warn("Invalid JSON in metadata field, starting with empty object")}s={...s,logging:x.filter(e=>e.callback_name)},e.metadata=JSON.stringify(s)}if(e.secret_manager_settings&&"string"==typeof e.secret_manager_settings)if(""===e.secret_manager_settings.trim())delete e.secret_manager_settings;else try{e.secret_manager_settings=JSON.parse(e.secret_manager_settings)}catch(e){throw Error("Failed to parse secret manager settings: "+e)}if(e.allowed_vector_store_ids&&e.allowed_vector_store_ids.length>0||e.allowed_mcp_servers_and_groups&&(e.allowed_mcp_servers_and_groups.servers?.length>0||e.allowed_mcp_servers_and_groups.accessGroups?.length>0||e.allowed_mcp_servers_and_groups.toolPermissions)){if(e.object_permission={},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){let{servers:s,accessGroups:l}=e.allowed_mcp_servers_and_groups;s&&s.length>0&&(e.object_permission.mcp_servers=s),l&&l.length>0&&(e.object_permission.mcp_access_groups=l),delete e.allowed_mcp_servers_and_groups}if(e.mcp_tool_permissions&&Object.keys(e.mcp_tool_permissions).length>0&&(e.object_permission||(e.object_permission={}),e.object_permission.mcp_tool_permissions=e.mcp_tool_permissions,delete e.mcp_tool_permissions),e.allowed_agents_and_groups){let{agents:s,accessGroups:l}=e.allowed_agents_and_groups;e.object_permission||(e.object_permission={}),s&&s.length>0&&(e.object_permission.agents=s),l&&l.length>0&&(e.object_permission.agent_access_groups=l),delete e.allowed_agents_and_groups}}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),Object.keys(m).length>0&&(e.model_aliases=m);let r=await (0,a.teamCreateCall)(f,e);null!==d?c([...d,r]):c([r]),console.log(`response for team create call: ${r}`),em.default.success("Team created"),y.resetFields(),p([]),u({}),g(!1)}}catch(e){console.error("Error creating the team:",e),em.default.fromBackend("Error creating the team: "+e)}};return(0,s.jsx)(X.Modal,{title:"Create Team",open:e,width:1e3,footer:null,onOk:t,onCancel:i,children:(0,s.jsxs)(r.Form,{form:y,onFinish:E,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(r.Form.Item,{label:"Team Name",name:"team_alias",rules:[{required:!0,message:"Please input a team name"}],children:(0,s.jsx)(ea.TextInput,{placeholder:""})}),(0,s.jsx)(r.Form.Item,{label:(0,s.jsxs)("span",{children:["Organization"," ",(0,s.jsx)(O.Tooltip,{title:(0,s.jsxs)("span",{children:["Organizations can have multiple teams. Learn more about"," ",(0,s.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/user_management_heirarchy",target:"_blank",rel:"noopener noreferrer",style:{color:"#1890ff",textDecoration:"underline"},onClick:e=>e.stopPropagation(),children:"user management hierarchy"})]}),children:(0,s.jsx)(et.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"organization_id",initialValue:o?o.organization_id:null,className:"mt-8",children:(0,s.jsx)(Q.Select,{showSearch:!0,allowClear:!0,placeholder:"Search or select an Organization",onChange:e=>{y.setFieldValue("organization_id",e),C(n?.find(s=>s.organization_id===e)||null)},filterOption:(e,s)=>!!s&&(s.children?.toString()||"").toLowerCase().includes(e.toLowerCase()),optionFilterProp:"children",children:n?.map(e=>(0,s.jsxs)(Q.Select.Option,{value:e.organization_id,children:[(0,s.jsx)("span",{className:"font-medium",children:e.organization_alias})," ",(0,s.jsxs)("span",{className:"text-gray-500",children:["(",e.organization_id,")"]})]},e.organization_id))})}),(0,s.jsx)(r.Form.Item,{label:(0,s.jsxs)("span",{children:["Models"," ",(0,s.jsx)(O.Tooltip,{title:"These are the models that your selected team has access to",children:(0,s.jsx)(et.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"models",children:(0,s.jsxs)(Q.Select,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[(0,s.jsx)(Q.Select.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),N.map(e=>(0,s.jsx)(Q.Select.Option,{value:e,children:(0,R.getModelDisplayName)(e)},e))]})}),(0,s.jsx)(r.Form.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,s.jsx)(er.default,{step:.01,precision:2,width:200})}),(0,s.jsx)(r.Form.Item,{className:"mt-8",label:"Reset Budget",name:"budget_duration",children:(0,s.jsxs)(Q.Select,{defaultValue:null,placeholder:"n/a",children:[(0,s.jsx)(Q.Select.Option,{value:"24h",children:"daily"}),(0,s.jsx)(Q.Select.Option,{value:"7d",children:"weekly"}),(0,s.jsx)(Q.Select.Option,{value:"30d",children:"monthly"})]})}),(0,s.jsx)(r.Form.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,s.jsx)(er.default,{step:1,width:400})}),(0,s.jsx)(r.Form.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,s.jsx)(er.default,{step:1,width:400})}),(0,s.jsxs)(ee.Accordion,{className:"mt-20 mb-8",onClick:()=>{L||(B(),D(!0))},children:[(0,s.jsx)(el.AccordionHeader,{children:(0,s.jsx)("b",{children:"Additional Settings"})}),(0,s.jsxs)(es.AccordionBody,{children:[(0,s.jsx)(r.Form.Item,{label:"Team ID",name:"team_id",help:"ID of the team you want to create. If not provided, it will be generated automatically.",children:(0,s.jsx)(ea.TextInput,{onChange:e=>{e.target.value=e.target.value.trim()}})}),(0,s.jsx)(r.Form.Item,{label:"Team Member Budget (USD)",name:"team_member_budget",normalize:e=>e?Number(e):void 0,tooltip:"This is the individual budget for a user in the team.",children:(0,s.jsx)(er.default,{step:.01,precision:2,width:200})}),(0,s.jsx)(r.Form.Item,{label:"Team Member Key Duration (eg: 1d, 1mo)",name:"team_member_key_duration",tooltip:"Set a limit to the duration of a team member's key. Format: 30s (seconds), 30m (minutes), 30h (hours), 30d (days), 1mo (month)",children:(0,s.jsx)(ea.TextInput,{placeholder:"e.g., 30d"})}),(0,s.jsx)(r.Form.Item,{label:"Team Member RPM Limit",name:"team_member_rpm_limit",tooltip:"The RPM (Requests Per Minute) limit for individual team members",children:(0,s.jsx)(er.default,{step:1,width:400})}),(0,s.jsx)(r.Form.Item,{label:"Team Member TPM Limit",name:"team_member_tpm_limit",tooltip:"The TPM (Tokens Per Minute) limit for individual team members",children:(0,s.jsx)(er.default,{step:1,width:400})}),(0,s.jsx)(r.Form.Item,{label:"Metadata",name:"metadata",help:"Additional team metadata. Enter metadata as JSON object.",children:(0,s.jsx)(Y.Input.TextArea,{rows:4})}),(0,s.jsx)(r.Form.Item,{label:"Secret Manager Settings",name:"secret_manager_settings",help:b?"Enter secret manager configuration as a JSON object.":"Premium feature - Upgrade to manage secret manager settings.",rules:[{validator:async(e,s)=>{if(!s)return Promise.resolve();try{return JSON.parse(s),Promise.resolve()}catch(e){return Promise.reject(Error("Please enter valid JSON"))}}}],children:(0,s.jsx)(Y.Input.TextArea,{rows:4,placeholder:'{"namespace": "admin", "mount": "secret", "path_prefix": "litellm"}',disabled:!b})}),(0,s.jsx)(r.Form.Item,{label:(0,s.jsxs)("span",{children:["Guardrails"," ",(0,s.jsx)(O.Tooltip,{title:"Setup your first guardrail",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)(et.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",className:"mt-8",help:"Select existing guardrails or enter new ones",children:(0,s.jsx)(Q.Select,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter guardrails",options:I.map(e=>({value:e,label:e}))})}),(0,s.jsx)(r.Form.Item,{label:(0,s.jsxs)("span",{children:["Disable Global Guardrails"," ",(0,s.jsx)(O.Tooltip,{title:"When enabled, this team will bypass any guardrails configured to run on every request (global guardrails)",children:(0,s.jsx)(et.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"disable_global_guardrails",className:"mt-4",valuePropName:"checked",help:"Bypass global guardrails for this team",children:(0,s.jsx)(Z.Switch,{checkedChildren:"Yes",unCheckedChildren:"No"})}),(0,s.jsx)(r.Form.Item,{label:(0,s.jsxs)("span",{children:["Policies"," ",(0,s.jsx)(O.Tooltip,{title:"Apply policies to this team 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)(et.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"policies",className:"mt-8",help:"Select existing policies or enter new ones",children:(0,s.jsx)(Q.Select,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter policies",options:A.map(e=>({value:e,label:e}))})}),(0,s.jsx)(r.Form.Item,{label:(0,s.jsxs)("span",{children:["Allowed Vector Stores"," ",(0,s.jsx)(O.Tooltip,{title:"Select which vector stores this team can access by default. Leave empty for access to all vector stores",children:(0,s.jsx)(et.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_vector_store_ids",className:"mt-8",help:"Select vector stores this team can access. Leave empty for access to all vector stores",children:(0,s.jsx)(ei.default,{onChange:e=>y.setFieldValue("allowed_vector_store_ids",e),value:y.getFieldValue("allowed_vector_store_ids"),accessToken:f||"",placeholder:"Select vector stores (optional)"})})]})]}),(0,s.jsxs)(ee.Accordion,{className:"mt-8 mb-8",children:[(0,s.jsx)(el.AccordionHeader,{children:(0,s.jsx)("b",{children:"MCP Settings"})}),(0,s.jsxs)(es.AccordionBody,{children:[(0,s.jsx)(r.Form.Item,{label:(0,s.jsxs)("span",{children:["Allowed MCP Servers"," ",(0,s.jsx)(O.Tooltip,{title:"Select which MCP servers or access groups this team can access",children:(0,s.jsx)(et.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_mcp_servers_and_groups",className:"mt-4",help:"Select MCP servers or access groups this team can access",children:(0,s.jsx)(eo.default,{onChange:e=>y.setFieldValue("allowed_mcp_servers_and_groups",e),value:y.getFieldValue("allowed_mcp_servers_and_groups"),accessToken:f||"",placeholder:"Select MCP servers or access groups (optional)"})}),(0,s.jsx)(r.Form.Item,{name:"mcp_tool_permissions",initialValue:{},hidden:!0,children:(0,s.jsx)(Y.Input,{type:"hidden"})}),(0,s.jsx)(r.Form.Item,{noStyle:!0,shouldUpdate:(e,s)=>e.allowed_mcp_servers_and_groups!==s.allowed_mcp_servers_and_groups||e.mcp_tool_permissions!==s.mcp_tool_permissions,children:()=>(0,s.jsx)("div",{className:"mt-6",children:(0,s.jsx)(eh.default,{accessToken:f||"",selectedServers:y.getFieldValue("allowed_mcp_servers_and_groups")?.servers||[],toolPermissions:y.getFieldValue("mcp_tool_permissions")||{},onChange:e=>y.setFieldsValue({mcp_tool_permissions:e})})})})]})]}),(0,s.jsxs)(ee.Accordion,{className:"mt-8 mb-8",children:[(0,s.jsx)(el.AccordionHeader,{children:(0,s.jsx)("b",{children:"Agent Settings"})}),(0,s.jsx)(es.AccordionBody,{children:(0,s.jsx)(r.Form.Item,{label:(0,s.jsxs)("span",{children:["Allowed Agents"," ",(0,s.jsx)(O.Tooltip,{title:"Select which agents or access groups this team can access",children:(0,s.jsx)(et.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_agents_and_groups",className:"mt-4",help:"Select agents or access groups this team can access",children:(0,s.jsx)(en.default,{onChange:e=>y.setFieldValue("allowed_agents_and_groups",e),value:y.getFieldValue("allowed_agents_and_groups"),accessToken:f||"",placeholder:"Select agents or access groups (optional)"})})})]}),(0,s.jsxs)(ee.Accordion,{className:"mt-8 mb-8",children:[(0,s.jsx)(el.AccordionHeader,{children:(0,s.jsx)("b",{children:"Logging Settings"})}),(0,s.jsx)(es.AccordionBody,{children:(0,s.jsx)("div",{className:"mt-4",children:(0,s.jsx)(ed.default,{value:x,onChange:p,premiumUser:b})})})]}),(0,s.jsxs)(ee.Accordion,{className:"mt-8 mb-8",children:[(0,s.jsx)(el.AccordionHeader,{children:(0,s.jsx)("b",{children:"Model Aliases"})}),(0,s.jsx)(es.AccordionBody,{children:(0,s.jsxs)("div",{className:"mt-4",children:[(0,s.jsx)(h.Text,{className:"text-sm text-gray-600 mb-4",children:"Create custom aliases for models that can be used by team members in API calls. This allows you to create shortcuts for specific models."}),(0,s.jsx)(ec.default,{accessToken:f||"",initialModelAliases:m,onAliasUpdate:u,showExampleConfig:!1})]})})]})]}),(0,s.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,s.jsx)(q.Button,{htmlType:"submit",children:"Create Team"})})]})})},ex=({teams:e,accessToken:_,setTeams:j,userID:f,userRole:b,organizations:y,premiumUser:v=!1})=>{let[T,C]=(0,l.useState)(null),[k,I]=(0,l.useState)(!1),[F,A]=(0,l.useState)({team_id:"",team_alias:"",organization_id:"",sort_by:"created_at",sort_order:"desc"}),[z]=r.Form.useForm(),[M]=r.Form.useForm(),[O,P]=(0,l.useState)(null),[L,D]=(0,l.useState)(!1),[B,E]=(0,l.useState)(!1),[R,V]=(0,l.useState)(!1),[H,W]=(0,l.useState)(!1),[U,G]=(0,l.useState)([]),[J,q]=(0,l.useState)(!1),[Y,X]=(0,l.useState)(null),[Q,Z]=(0,l.useState)({}),[ee,es]=(0,l.useState)([]),[el,ea]=(0,l.useState)({}),{lastRefreshed:et,onRefreshClick:er}=(({currentOrg:e,setTeams:s})=>{let[a,r]=(0,l.useState)(""),{accessToken:i,userId:o,userRole:n}=(0,S.default)(),d=(0,l.useCallback)(()=>{r(new Date().toLocaleString())},[]);return(0,l.useEffect)(()=>{i&&(0,t.fetchTeams)(i,o,n,e,s).then(),d()},[i,e,a,d,s,o,n]),{lastRefreshed:a,setLastRefreshed:r,onRefreshClick:d}})({currentOrg:T,setTeams:j});(0,l.useEffect)(()=>{e&&Z(e.reduce((e,s)=>(e[s.team_id]={keys:s.keys||[],team_info:{members_with_roles:s.members_with_roles||[]}},e),{}))},[e]);let ei=async e=>{X(e),q(!0)},eo=async()=>{if(null!=Y&&null!=e&&null!=_){try{await (0,a.teamDeleteCall)(_,Y),(0,t.fetchTeams)(_,f,b,T,j)}catch(e){console.error("Error deleting the team:",e)}q(!1),X(null)}};return(0,s.jsx)("div",{className:"w-full mx-4 h-[75vh]",children:(0,s.jsx)(u.Grid,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:(0,s.jsxs)(m.Col,{numColSpan:1,className:"flex flex-col gap-2",children:[("Admin"==b||"Org Admin"==b)&&(0,s.jsx)(c.Button,{className:"w-fit",onClick:()=>E(!0),children:"+ Create New Team"}),O?(0,s.jsx)(i.default,{teamId:O,onUpdate:e=>{j(s=>{if(null==s)return s;let l=s.map(s=>e.team_id===s.team_id?(0,g.updateExistingKeys)(s,e):s);return _&&(0,t.fetchTeams)(_,f,b,T,j),l})},onClose:()=>{P(null),D(!1)},accessToken:_,is_team_admin:(e=>{if(null==e||null==e.members_with_roles)return!1;for(let s=0;se.team_id===O)),is_proxy_admin:"Admin"==b,userModels:U,editTeam:L,premiumUser:v}):(0,s.jsxs)(w,{lastRefreshed:et,onRefresh:er,userRole:b,children:[(0,s.jsxs)(x.TabPanel,{children:[(0,s.jsxs)(h.Text,{children:["Click on “Team ID” to view team details ",(0,s.jsx)("b",{children:"and"})," manage team members."]}),(0,s.jsx)(u.Grid,{numItems:1,className:"gap-2 pt-2 pb-2 h-[75vh] w-full mt-2",children:(0,s.jsx)(m.Col,{numColSpan:1,children:(0,s.jsxs)(d.Card,{className:"w-full mx-auto flex-auto overflow-hidden overflow-y-auto max-h-[50vh]",children:[(0,s.jsx)("div",{className:"border-b px-6 py-4",children:(0,s.jsx)("div",{className:"flex flex-col space-y-4",children:(0,s.jsx)(N,{filters:F,organizations:y,showFilters:k,onToggleFilters:I,onChange:(e,s)=>{let l={...F,[e]:s};A(l),_&&(0,a.v2TeamListCall)(_,l.organization_id||null,null,l.team_id||null,l.team_alias||null).then(e=>{e&&e.teams&&j(e.teams)}).catch(e=>{console.error("Error fetching teams:",e)})},onReset:()=>{A({team_id:"",team_alias:"",organization_id:"",sort_by:"created_at",sort_order:"desc"}),_&&(0,a.v2TeamListCall)(_,null,f||null,null,null).then(e=>{e&&e.teams&&j(e.teams)}).catch(e=>{console.error("Error fetching teams:",e)})}})})}),(0,s.jsx)($,{teams:e,currentOrg:T,perTeamInfo:Q,userRole:b,userId:f,setSelectedTeamId:P,setEditTeam:D,onDeleteTeam:ei}),J&&(0,s.jsx)(K,{teams:e,teamToDelete:Y,onCancel:()=>{q(!1),X(null)},onConfirm:eo})]})})})]}),(0,s.jsx)(x.TabPanel,{children:(0,s.jsx)(p.default,{accessToken:_,userID:f})}),(0,n.isAdminRole)(b||"")&&(0,s.jsx)(x.TabPanel,{children:(0,s.jsx)(o.default,{accessToken:_,userID:f||"",userRole:b||""})})]}),("Admin"==b||"Org Admin"==b)&&(0,s.jsx)(eu,{isTeamModalVisible:B,handleOk:()=>{E(!1),z.resetFields(),es([]),ea({})},handleCancel:()=>{E(!1),z.resetFields(),es([]),ea({})},currentOrg:T,organizations:y,teams:e,setTeams:j,modelAliases:el,setModelAliases:ea,loggingSettings:ee,setLoggingSettings:es,setIsTeamModalVisible:E})]})})})};var ep=e.i(214541),eg=e.i(846835);e.s(["default",0,()=>{let{accessToken:e,userId:a,userRole:t}=(0,S.default)(),{teams:r,setTeams:i}=(0,ep.default)(),[o,n]=(0,l.useState)([]);return(0,l.useEffect)(()=>{(0,eg.fetchOrganizations)(e,n).then(()=>{})},[e]),(0,s.jsx)(ex,{teams:r,accessToken:e,setTeams:i,userID:a,userRole:t,organizations:o})}],596115)}]); \ No newline at end of file +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,596115,e=>{"use strict";var s=e.i(843476),l=e.i(271645),a=e.i(764205),t=e.i(584578),r=e.i(808613),i=e.i(56567),o=e.i(468133),n=e.i(708347),d=e.i(304967),c=e.i(994388),m=e.i(309426),h=e.i(599724),u=e.i(350967),x=e.i(404206),p=e.i(747871),g=e.i(500330),_=e.i(752978),j=e.i(197647),f=e.i(653824),b=e.i(881073),y=e.i(723731),v=e.i(278587);let w=({lastRefreshed:e,onRefresh:l,userRole:a,children:t})=>(0,s.jsxs)(f.TabGroup,{className:"gap-2 h-[75vh] w-full",children:[(0,s.jsxs)(b.TabList,{className:"flex justify-between mt-2 w-full items-center",children:[(0,s.jsxs)("div",{className:"flex",children:[(0,s.jsx)(j.Tab,{children:"Your Teams"}),(0,s.jsx)(j.Tab,{children:"Available Teams"}),(0,n.isAdminRole)(a||"")&&(0,s.jsx)(j.Tab,{children:"Default Team Settings"})]}),(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[e&&(0,s.jsxs)(h.Text,{children:["Last Refreshed: ",e]}),(0,s.jsx)(_.Icon,{icon:v.RefreshIcon,variant:"shadow",size:"xs",className:"self-center",onClick:l})]})]}),(0,s.jsx)(y.TabPanels,{children:t})]});var T=e.i(206929),C=e.i(35983);let N=({filters:e,organizations:l,showFilters:a,onToggleFilters:t,onChange:r,onReset:i})=>(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 by Team Name...",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:e.team_alias,onChange:e=>r("team_alias",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 ${a?"bg-gray-100":""}`,onClick:()=>t(!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",(e.team_id||e.team_alias||e.organization_id)&&(0,s.jsx)("span",{"data-testid":"active-filter-indicator",className:"w-2 h-2 rounded-full bg-blue-500"})]}),(0,s.jsxs)("button",{className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2",onClick:i,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.jsxs)("div",{className:"relative w-64",children:[(0,s.jsx)("input",{type:"text",placeholder:"Enter Team ID",className:"w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:e.team_id,onChange:e=>r("team_id",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:"M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0zm6 2a9 9 0 11-18 0 9 9 0 0118 0z"})})]}),(0,s.jsx)("div",{className:"w-64",children:(0,s.jsx)(T.Select,{value:e.organization_id||"",onValueChange:e=>r("organization_id",e),placeholder:"Select Organization",children:l?.map(e=>(0,s.jsx)(C.SelectItem,{value:e.organization_id||"",children:e.organization_alias||e.organization_id},e.organization_id))})})]})]});var S=e.i(135214),k=e.i(269200),I=e.i(942232),F=e.i(977572),A=e.i(427612),z=e.i(64848),M=e.i(496020),O=e.i(592968),P=e.i(591935),L=e.i(68155),D=e.i(389083),B=e.i(871943),E=e.i(502547),R=e.i(355619);let V=({team:e})=>{let[a,t]=(0,l.useState)(!1);return(0,s.jsx)(F.TableCell,{style:{maxWidth:"8-x",whiteSpace:"pre-wrap",overflow:"hidden"},className:e.models.length>3?"px-0":"",children:(0,s.jsx)("div",{className:"flex flex-col",children:Array.isArray(e.models)?(0,s.jsx)("div",{className:"flex flex-col",children:0===e.models.length?(0,s.jsx)(D.Badge,{size:"xs",className:"mb-1",color:"red",children:(0,s.jsx)(h.Text,{children:"All Proxy Models"})}):(0,s.jsx)(s.Fragment,{children:(0,s.jsxs)("div",{className:"flex items-start",children:[e.models.length>3&&(0,s.jsx)("div",{children:(0,s.jsx)(_.Icon,{icon:a?B.ChevronDownIcon:E.ChevronRightIcon,className:"cursor-pointer",size:"xs",onClick:()=>{t(e=>!e)}})}),(0,s.jsxs)("div",{className:"flex flex-wrap gap-1",children:[e.models.slice(0,3).map((e,l)=>"all-proxy-models"===e?(0,s.jsx)(D.Badge,{size:"xs",color:"red",children:(0,s.jsx)(h.Text,{children:"All Proxy Models"})},l):(0,s.jsx)(D.Badge,{size:"xs",color:"blue",children:(0,s.jsx)(h.Text,{children:e.length>30?`${(0,R.getModelDisplayName)(e).slice(0,30)}...`:(0,R.getModelDisplayName)(e)})},l)),e.models.length>3&&!a&&(0,s.jsx)(D.Badge,{size:"xs",color:"gray",className:"cursor-pointer",children:(0,s.jsxs)(h.Text,{children:["+",e.models.length-3," ",e.models.length-3==1?"more model":"more models"]})}),a&&(0,s.jsx)("div",{className:"flex flex-wrap gap-1",children:e.models.slice(3).map((e,l)=>"all-proxy-models"===e?(0,s.jsx)(D.Badge,{size:"xs",color:"red",children:(0,s.jsx)(h.Text,{children:"All Proxy Models"})},l+3):(0,s.jsx)(D.Badge,{size:"xs",color:"blue",children:(0,s.jsx)(h.Text,{children:e.length>30?`${(0,R.getModelDisplayName)(e).slice(0,30)}...`:(0,R.getModelDisplayName)(e)})},l+3))})]})]})})}):null})})};var H=e.i(918549),H=H,W=e.i(846753),W=W;let U=({team:e,userId:l})=>{var a;let t,r=(a=((e,s)=>{if(!s)return null;let l=e.members_with_roles?.find(e=>e.user_id===s);return l?.role??null})(e,l),t="inline-flex items-center px-2.5 py-0.5 rounded-md text-xs font-medium border","admin"===a?(0,s.jsxs)("span",{className:t,style:{backgroundColor:"#EEF2FF",color:"#3730A3",borderColor:"#C7D2FE"},children:[(0,s.jsx)(H.default,{className:"h-3 w-3 mr-1"}),"Admin"]}):(0,s.jsxs)("span",{className:t,style:{backgroundColor:"#F3F4F6",color:"#4B5563",borderColor:"#E5E7EB"},children:[(0,s.jsx)(W.default,{className:"h-3 w-3 mr-1"}),"Member"]}));return(0,s.jsx)(F.TableCell,{children:r})},$=({teams:e,currentOrg:l,setSelectedTeamId:a,perTeamInfo:t,userRole:r,userId:i,setEditTeam:o,onDeleteTeam:n})=>(0,s.jsxs)(k.Table,{children:[(0,s.jsx)(A.TableHead,{children:(0,s.jsxs)(M.TableRow,{children:[(0,s.jsx)(z.TableHeaderCell,{children:"Team Name"}),(0,s.jsx)(z.TableHeaderCell,{children:"Team ID"}),(0,s.jsx)(z.TableHeaderCell,{children:"Created"}),(0,s.jsx)(z.TableHeaderCell,{children:"Spend (USD)"}),(0,s.jsx)(z.TableHeaderCell,{children:"Budget (USD)"}),(0,s.jsx)(z.TableHeaderCell,{children:"Models"}),(0,s.jsx)(z.TableHeaderCell,{children:"Organization"}),(0,s.jsx)(z.TableHeaderCell,{children:"Your Role"}),(0,s.jsx)(z.TableHeaderCell,{children:"Info"})]})}),(0,s.jsx)(I.TableBody,{children:e&&e.length>0?e.filter(e=>!l||e.organization_id===l.organization_id).sort((e,s)=>new Date(s.created_at).getTime()-new Date(e.created_at).getTime()).map(e=>(0,s.jsxs)(M.TableRow,{children:[(0,s.jsx)(F.TableCell,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:e.team_alias}),(0,s.jsx)(F.TableCell,{children:(0,s.jsx)("div",{className:"overflow-hidden",children:(0,s.jsx)(O.Tooltip,{title:e.team_id,children:(0,s.jsxs)(c.Button,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>{a(e.team_id)},children:[e.team_id.slice(0,7),"..."]})})})}),(0,s.jsx)(F.TableCell,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:e.created_at?new Date(e.created_at).toLocaleDateString():"N/A"}),(0,s.jsx)(F.TableCell,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:(0,g.formatNumberWithCommas)(e.spend,4)}),(0,s.jsx)(F.TableCell,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:null!==e.max_budget&&void 0!==e.max_budget?e.max_budget:"No limit"}),(0,s.jsx)(V,{team:e}),(0,s.jsx)(F.TableCell,{children:e.organization_id}),(0,s.jsx)(U,{team:e,userId:i}),(0,s.jsxs)(F.TableCell,{children:[(0,s.jsxs)(h.Text,{children:[t&&e.team_id&&t[e.team_id]&&t[e.team_id].keys&&t[e.team_id].keys.length," ","Keys"]}),(0,s.jsxs)(h.Text,{children:[t&&e.team_id&&t[e.team_id]&&t[e.team_id].team_info&&t[e.team_id].team_info.members_with_roles&&t[e.team_id].team_info.members_with_roles.length," ","Members"]})]}),(0,s.jsx)(F.TableCell,{children:"Admin"==r?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(_.Icon,{icon:P.PencilAltIcon,size:"sm",onClick:()=>{a(e.team_id),o(!0)}}),(0,s.jsx)(_.Icon,{onClick:()=>n(e.team_id),icon:L.TrashIcon,size:"sm"})]}):null})]},e.team_id)):null})]});var G=e.i(582458),G=G,J=e.i(995926);let K=({teams:e,teamToDelete:a,onCancel:t,onConfirm:r})=>{let[i,o]=(0,l.useState)(""),n=e?.find(e=>e.team_id===a),d=n?.team_alias||"",c=n?.keys?.length||0,m=i===d;return(0,s.jsx)("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:(0,s.jsxs)("div",{className:"bg-white rounded-lg shadow-xl w-full max-w-2xl min-h-[380px] py-6 overflow-hidden transform transition-all flex flex-col justify-between",children:[(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center justify-between px-6 py-4 border-b border-gray-200",children:[(0,s.jsx)("h3",{className:"text-lg font-semibold text-gray-900",children:"Delete Team"}),(0,s.jsx)("button",{"aria-label":"Close",onClick:()=>{t(),o("")},className:"text-gray-400 hover:text-gray-500 focus:outline-none",children:(0,s.jsx)(J.XIcon,{size:20})})]}),(0,s.jsxs)("div",{className:"px-6 py-4",children:[c>0&&(0,s.jsxs)("div",{className:"flex items-start gap-3 p-4 bg-red-50 border border-red-100 rounded-md mb-5",children:[(0,s.jsx)("div",{className:"text-red-500 mt-0.5",children:(0,s.jsx)(G.default,{size:20})}),(0,s.jsxs)("div",{children:[(0,s.jsxs)("p",{className:"text-base font-medium text-red-600",children:["Warning: This team has ",c," associated key",c>1?"s":"","."]}),(0,s.jsx)("p",{className:"text-base text-red-600 mt-2",children:"Deleting the team will also delete all associated keys. This action is irreversible."})]})]}),(0,s.jsx)("p",{className:"text-base text-gray-600 mb-5",children:"Are you sure you want to force delete this team and all its keys?"}),(0,s.jsxs)("div",{className:"mb-5",children:[(0,s.jsxs)("label",{className:"block text-base font-medium text-gray-700 mb-2",children:["Type ",(0,s.jsx)("span",{className:"underline",children:d})," to confirm deletion:"]}),(0,s.jsx)("input",{type:"text",value:i,onChange:e=>o(e.target.value),placeholder:"Enter team name exactly",className:"w-full px-4 py-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-base",autoFocus:!0})]})]})]}),(0,s.jsxs)("div",{className:"px-6 py-4 bg-gray-50 flex justify-end gap-4",children:[(0,s.jsx)("button",{onClick:()=>{t(),o("")},className:"px-5 py-3 bg-white border border-gray-300 rounded-md text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500",children:"Cancel"}),(0,s.jsx)("button",{onClick:r,disabled:!m,className:`px-5 py-3 rounded-md text-base font-medium text-white focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 ${m?"bg-red-600 hover:bg-red-700":"bg-red-300 cursor-not-allowed"}`,children:"Force Delete"})]})]})})};var q=e.i(464571),Y=e.i(311451),X=e.i(212931),Q=e.i(199133),Z=e.i(790848),ee=e.i(677667),es=e.i(130643),el=e.i(898667),ea=e.i(779241),et=e.i(827252),er=e.i(435451),ei=e.i(916940),eo=e.i(75921),en=e.i(552130),ed=e.i(651904),ec=e.i(533882),em=e.i(727749),eh=e.i(390605);let eu=({isTeamModalVisible:e,handleOk:t,handleCancel:i,currentOrg:o,organizations:n,teams:d,setTeams:c,modelAliases:m,setModelAliases:u,loggingSettings:x,setLoggingSettings:p,setIsTeamModalVisible:g})=>{let{userId:_,userRole:j,accessToken:f,premiumUser:b}=(0,S.default)(),[y]=r.Form.useForm(),[v,w]=(0,l.useState)([]),[T,C]=(0,l.useState)(null),[N,k]=(0,l.useState)([]),[I,F]=(0,l.useState)([]),[A,z]=(0,l.useState)([]),[M,P]=(0,l.useState)([]),[L,D]=(0,l.useState)(!1);(0,l.useEffect)(()=>{(async()=>{try{if(null===_||null===j||null===f)return;let e=await (0,R.fetchAvailableModelsForTeamOrKey)(_,j,f);e&&w(e)}catch(e){console.error("Error fetching user models:",e)}})()},[f,_,j,d]),(0,l.useEffect)(()=>{let e;console.log(`currentOrgForCreateTeam: ${T}`);let s=(e=[],T&&T.models.length>0?(console.log(`organization.models: ${T.models}`),e=T.models):e=v,(0,R.unfurlWildcardModelsInList)(e,v));console.log(`models: ${s}`),k(s),y.setFieldValue("models",[])},[T,v,y]);let B=async()=>{try{if(null==f)return;let e=await (0,a.fetchMCPAccessGroups)(f);P(e)}catch(e){console.error("Failed to fetch MCP access groups:",e)}};(0,l.useEffect)(()=>{B()},[f,B]),(0,l.useEffect)(()=>{let e=async()=>{try{if(null==f)return;let e=(await (0,a.getPoliciesList)(f)).policies.map(e=>e.policy_name);z(e)}catch(e){console.error("Failed to fetch policies:",e)}};(async()=>{try{if(null==f)return;let e=(await (0,a.getGuardrailsList)(f)).guardrails.map(e=>e.guardrail_name);F(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})(),e()},[f]);let E=async e=>{try{if(console.log(`formValues: ${JSON.stringify(e)}`),null!=f){let s=e?.team_alias,l=d?.map(e=>e.team_alias)??[],t=e?.organization_id||o?.organization_id;if(""===t||"string"!=typeof t?e.organization_id=null:e.organization_id=t.trim(),l.includes(s))throw Error(`Team alias ${s} already exists, please pick another alias`);if(em.default.info("Creating Team"),x.length>0){let s={};if(e.metadata)try{s=JSON.parse(e.metadata)}catch(e){console.warn("Invalid JSON in metadata field, starting with empty object")}s={...s,logging:x.filter(e=>e.callback_name)},e.metadata=JSON.stringify(s)}if(e.secret_manager_settings&&"string"==typeof e.secret_manager_settings)if(""===e.secret_manager_settings.trim())delete e.secret_manager_settings;else try{e.secret_manager_settings=JSON.parse(e.secret_manager_settings)}catch(e){throw Error("Failed to parse secret manager settings: "+e)}if(e.allowed_vector_store_ids&&e.allowed_vector_store_ids.length>0||e.allowed_mcp_servers_and_groups&&(e.allowed_mcp_servers_and_groups.servers?.length>0||e.allowed_mcp_servers_and_groups.accessGroups?.length>0||e.allowed_mcp_servers_and_groups.toolPermissions)){if(e.object_permission={},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){let{servers:s,accessGroups:l}=e.allowed_mcp_servers_and_groups;s&&s.length>0&&(e.object_permission.mcp_servers=s),l&&l.length>0&&(e.object_permission.mcp_access_groups=l),delete e.allowed_mcp_servers_and_groups}if(e.mcp_tool_permissions&&Object.keys(e.mcp_tool_permissions).length>0&&(e.object_permission||(e.object_permission={}),e.object_permission.mcp_tool_permissions=e.mcp_tool_permissions,delete e.mcp_tool_permissions),e.allowed_agents_and_groups){let{agents:s,accessGroups:l}=e.allowed_agents_and_groups;e.object_permission||(e.object_permission={}),s&&s.length>0&&(e.object_permission.agents=s),l&&l.length>0&&(e.object_permission.agent_access_groups=l),delete e.allowed_agents_and_groups}}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),Object.keys(m).length>0&&(e.model_aliases=m);let r=await (0,a.teamCreateCall)(f,e);null!==d?c([...d,r]):c([r]),console.log(`response for team create call: ${r}`),em.default.success("Team created"),y.resetFields(),p([]),u({}),g(!1)}}catch(e){console.error("Error creating the team:",e),em.default.fromBackend("Error creating the team: "+e)}};return(0,s.jsx)(X.Modal,{title:"Create Team",open:e,width:1e3,footer:null,onOk:t,onCancel:i,children:(0,s.jsxs)(r.Form,{form:y,onFinish:E,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(r.Form.Item,{label:"Team Name",name:"team_alias",rules:[{required:!0,message:"Please input a team name"}],children:(0,s.jsx)(ea.TextInput,{placeholder:""})}),(0,s.jsx)(r.Form.Item,{label:(0,s.jsxs)("span",{children:["Organization"," ",(0,s.jsx)(O.Tooltip,{title:(0,s.jsxs)("span",{children:["Organizations can have multiple teams. Learn more about"," ",(0,s.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/user_management_heirarchy",target:"_blank",rel:"noopener noreferrer",style:{color:"#1890ff",textDecoration:"underline"},onClick:e=>e.stopPropagation(),children:"user management hierarchy"})]}),children:(0,s.jsx)(et.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"organization_id",initialValue:o?o.organization_id:null,className:"mt-8",children:(0,s.jsx)(Q.Select,{showSearch:!0,allowClear:!0,placeholder:"Search or select an Organization",onChange:e=>{y.setFieldValue("organization_id",e),C(n?.find(s=>s.organization_id===e)||null)},filterOption:(e,s)=>!!s&&(s.children?.toString()||"").toLowerCase().includes(e.toLowerCase()),optionFilterProp:"children",children:n?.map(e=>(0,s.jsxs)(Q.Select.Option,{value:e.organization_id,children:[(0,s.jsx)("span",{className:"font-medium",children:e.organization_alias})," ",(0,s.jsxs)("span",{className:"text-gray-500",children:["(",e.organization_id,")"]})]},e.organization_id))})}),(0,s.jsx)(r.Form.Item,{label:(0,s.jsxs)("span",{children:["Models"," ",(0,s.jsx)(O.Tooltip,{title:"These are the models that your selected team has access to",children:(0,s.jsx)(et.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"models",children:(0,s.jsxs)(Q.Select,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[(0,s.jsx)(Q.Select.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),N.map(e=>(0,s.jsx)(Q.Select.Option,{value:e,children:(0,R.getModelDisplayName)(e)},e))]})}),(0,s.jsx)(r.Form.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,s.jsx)(er.default,{step:.01,precision:2,width:200})}),(0,s.jsx)(r.Form.Item,{className:"mt-8",label:"Reset Budget",name:"budget_duration",children:(0,s.jsxs)(Q.Select,{defaultValue:null,placeholder:"n/a",children:[(0,s.jsx)(Q.Select.Option,{value:"24h",children:"daily"}),(0,s.jsx)(Q.Select.Option,{value:"7d",children:"weekly"}),(0,s.jsx)(Q.Select.Option,{value:"30d",children:"monthly"})]})}),(0,s.jsx)(r.Form.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,s.jsx)(er.default,{step:1,width:400})}),(0,s.jsx)(r.Form.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,s.jsx)(er.default,{step:1,width:400})}),(0,s.jsxs)(ee.Accordion,{className:"mt-20 mb-8",onClick:()=>{L||(B(),D(!0))},children:[(0,s.jsx)(el.AccordionHeader,{children:(0,s.jsx)("b",{children:"Additional Settings"})}),(0,s.jsxs)(es.AccordionBody,{children:[(0,s.jsx)(r.Form.Item,{label:"Team ID",name:"team_id",help:"ID of the team you want to create. If not provided, it will be generated automatically.",children:(0,s.jsx)(ea.TextInput,{onChange:e=>{e.target.value=e.target.value.trim()}})}),(0,s.jsx)(r.Form.Item,{label:"Team Member Budget (USD)",name:"team_member_budget",normalize:e=>e?Number(e):void 0,tooltip:"This is the individual budget for a user in the team.",children:(0,s.jsx)(er.default,{step:.01,precision:2,width:200})}),(0,s.jsx)(r.Form.Item,{label:"Team Member Key Duration (eg: 1d, 1mo)",name:"team_member_key_duration",tooltip:"Set a limit to the duration of a team member's key. Format: 30s (seconds), 30m (minutes), 30h (hours), 30d (days), 1mo (month)",children:(0,s.jsx)(ea.TextInput,{placeholder:"e.g., 30d"})}),(0,s.jsx)(r.Form.Item,{label:"Team Member RPM Limit",name:"team_member_rpm_limit",tooltip:"The RPM (Requests Per Minute) limit for individual team members",children:(0,s.jsx)(er.default,{step:1,width:400})}),(0,s.jsx)(r.Form.Item,{label:"Team Member TPM Limit",name:"team_member_tpm_limit",tooltip:"The TPM (Tokens Per Minute) limit for individual team members",children:(0,s.jsx)(er.default,{step:1,width:400})}),(0,s.jsx)(r.Form.Item,{label:"Metadata",name:"metadata",help:"Additional team metadata. Enter metadata as JSON object.",children:(0,s.jsx)(Y.Input.TextArea,{rows:4})}),(0,s.jsx)(r.Form.Item,{label:"Secret Manager Settings",name:"secret_manager_settings",help:b?"Enter secret manager configuration as a JSON object.":"Premium feature - Upgrade to manage secret manager settings.",rules:[{validator:async(e,s)=>{if(!s)return Promise.resolve();try{return JSON.parse(s),Promise.resolve()}catch(e){return Promise.reject(Error("Please enter valid JSON"))}}}],children:(0,s.jsx)(Y.Input.TextArea,{rows:4,placeholder:'{"namespace": "admin", "mount": "secret", "path_prefix": "litellm"}',disabled:!b})}),(0,s.jsx)(r.Form.Item,{label:(0,s.jsxs)("span",{children:["Guardrails"," ",(0,s.jsx)(O.Tooltip,{title:"Setup your first guardrail",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)(et.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",className:"mt-8",help:"Select existing guardrails or enter new ones",children:(0,s.jsx)(Q.Select,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter guardrails",options:I.map(e=>({value:e,label:e}))})}),(0,s.jsx)(r.Form.Item,{label:(0,s.jsxs)("span",{children:["Disable Global Guardrails"," ",(0,s.jsx)(O.Tooltip,{title:"When enabled, this team will bypass any guardrails configured to run on every request (global guardrails)",children:(0,s.jsx)(et.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"disable_global_guardrails",className:"mt-4",valuePropName:"checked",help:"Bypass global guardrails for this team",children:(0,s.jsx)(Z.Switch,{checkedChildren:"Yes",unCheckedChildren:"No"})}),(0,s.jsx)(r.Form.Item,{label:(0,s.jsxs)("span",{children:["Policies"," ",(0,s.jsx)(O.Tooltip,{title:"Apply policies to this team 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)(et.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"policies",className:"mt-8",help:"Select existing policies or enter new ones",children:(0,s.jsx)(Q.Select,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter policies",options:A.map(e=>({value:e,label:e}))})}),(0,s.jsx)(r.Form.Item,{label:(0,s.jsxs)("span",{children:["Allowed Vector Stores"," ",(0,s.jsx)(O.Tooltip,{title:"Select which vector stores this team can access by default. Leave empty for access to all vector stores",children:(0,s.jsx)(et.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_vector_store_ids",className:"mt-8",help:"Select vector stores this team can access. Leave empty for access to all vector stores",children:(0,s.jsx)(ei.default,{onChange:e=>y.setFieldValue("allowed_vector_store_ids",e),value:y.getFieldValue("allowed_vector_store_ids"),accessToken:f||"",placeholder:"Select vector stores (optional)"})})]})]}),(0,s.jsxs)(ee.Accordion,{className:"mt-8 mb-8",children:[(0,s.jsx)(el.AccordionHeader,{children:(0,s.jsx)("b",{children:"MCP Settings"})}),(0,s.jsxs)(es.AccordionBody,{children:[(0,s.jsx)(r.Form.Item,{label:(0,s.jsxs)("span",{children:["Allowed MCP Servers"," ",(0,s.jsx)(O.Tooltip,{title:"Select which MCP servers or access groups this team can access",children:(0,s.jsx)(et.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_mcp_servers_and_groups",className:"mt-4",help:"Select MCP servers or access groups this team can access",children:(0,s.jsx)(eo.default,{onChange:e=>y.setFieldValue("allowed_mcp_servers_and_groups",e),value:y.getFieldValue("allowed_mcp_servers_and_groups"),accessToken:f||"",placeholder:"Select MCP servers or access groups (optional)"})}),(0,s.jsx)(r.Form.Item,{name:"mcp_tool_permissions",initialValue:{},hidden:!0,children:(0,s.jsx)(Y.Input,{type:"hidden"})}),(0,s.jsx)(r.Form.Item,{noStyle:!0,shouldUpdate:(e,s)=>e.allowed_mcp_servers_and_groups!==s.allowed_mcp_servers_and_groups||e.mcp_tool_permissions!==s.mcp_tool_permissions,children:()=>(0,s.jsx)("div",{className:"mt-6",children:(0,s.jsx)(eh.default,{accessToken:f||"",selectedServers:y.getFieldValue("allowed_mcp_servers_and_groups")?.servers||[],toolPermissions:y.getFieldValue("mcp_tool_permissions")||{},onChange:e=>y.setFieldsValue({mcp_tool_permissions:e})})})})]})]}),(0,s.jsxs)(ee.Accordion,{className:"mt-8 mb-8",children:[(0,s.jsx)(el.AccordionHeader,{children:(0,s.jsx)("b",{children:"Agent Settings"})}),(0,s.jsx)(es.AccordionBody,{children:(0,s.jsx)(r.Form.Item,{label:(0,s.jsxs)("span",{children:["Allowed Agents"," ",(0,s.jsx)(O.Tooltip,{title:"Select which agents or access groups this team can access",children:(0,s.jsx)(et.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"allowed_agents_and_groups",className:"mt-4",help:"Select agents or access groups this team can access",children:(0,s.jsx)(en.default,{onChange:e=>y.setFieldValue("allowed_agents_and_groups",e),value:y.getFieldValue("allowed_agents_and_groups"),accessToken:f||"",placeholder:"Select agents or access groups (optional)"})})})]}),(0,s.jsxs)(ee.Accordion,{className:"mt-8 mb-8",children:[(0,s.jsx)(el.AccordionHeader,{children:(0,s.jsx)("b",{children:"Logging Settings"})}),(0,s.jsx)(es.AccordionBody,{children:(0,s.jsx)("div",{className:"mt-4",children:(0,s.jsx)(ed.default,{value:x,onChange:p,premiumUser:b})})})]}),(0,s.jsxs)(ee.Accordion,{className:"mt-8 mb-8",children:[(0,s.jsx)(el.AccordionHeader,{children:(0,s.jsx)("b",{children:"Model Aliases"})}),(0,s.jsx)(es.AccordionBody,{children:(0,s.jsxs)("div",{className:"mt-4",children:[(0,s.jsx)(h.Text,{className:"text-sm text-gray-600 mb-4",children:"Create custom aliases for models that can be used by team members in API calls. This allows you to create shortcuts for specific models."}),(0,s.jsx)(ec.default,{accessToken:f||"",initialModelAliases:m,onAliasUpdate:u,showExampleConfig:!1})]})})]})]}),(0,s.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,s.jsx)(q.Button,{htmlType:"submit",children:"Create Team"})})]})})},ex=({teams:e,accessToken:_,setTeams:j,userID:f,userRole:b,organizations:y,premiumUser:v=!1})=>{let[T,C]=(0,l.useState)(null),[k,I]=(0,l.useState)(!1),[F,A]=(0,l.useState)({team_id:"",team_alias:"",organization_id:"",sort_by:"created_at",sort_order:"desc"}),[z]=r.Form.useForm(),[M]=r.Form.useForm(),[O,P]=(0,l.useState)(null),[L,D]=(0,l.useState)(!1),[B,E]=(0,l.useState)(!1),[R,V]=(0,l.useState)(!1),[H,W]=(0,l.useState)(!1),[U,G]=(0,l.useState)([]),[J,q]=(0,l.useState)(!1),[Y,X]=(0,l.useState)(null),[Q,Z]=(0,l.useState)({}),[ee,es]=(0,l.useState)([]),[el,ea]=(0,l.useState)({}),{lastRefreshed:et,onRefreshClick:er}=(({currentOrg:e,setTeams:s})=>{let[a,r]=(0,l.useState)(""),{accessToken:i,userId:o,userRole:n}=(0,S.default)(),d=(0,l.useCallback)(()=>{r(new Date().toLocaleString())},[]);return(0,l.useEffect)(()=>{i&&(0,t.fetchTeams)(i,o,n,e,s).then(),d()},[i,e,a,d,s,o,n]),{lastRefreshed:a,setLastRefreshed:r,onRefreshClick:d}})({currentOrg:T,setTeams:j});(0,l.useEffect)(()=>{e&&Z(e.reduce((e,s)=>(e[s.team_id]={keys:s.keys||[],team_info:{members_with_roles:s.members_with_roles||[]}},e),{}))},[e]);let ei=async e=>{X(e),q(!0)},eo=async()=>{if(null!=Y&&null!=e&&null!=_){try{await (0,a.teamDeleteCall)(_,Y),(0,t.fetchTeams)(_,f,b,T,j)}catch(e){console.error("Error deleting the team:",e)}q(!1),X(null)}};return(0,s.jsx)("div",{className:"w-full mx-4 h-[75vh]",children:(0,s.jsx)(u.Grid,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:(0,s.jsxs)(m.Col,{numColSpan:1,className:"flex flex-col gap-2",children:[("Admin"==b||"Org Admin"==b)&&(0,s.jsx)(c.Button,{className:"w-fit",onClick:()=>E(!0),children:"+ Create New Team"}),O?(0,s.jsx)(i.default,{teamId:O,onUpdate:e=>{j(s=>{if(null==s)return s;let l=s.map(s=>e.team_id===s.team_id?(0,g.updateExistingKeys)(s,e):s);return _&&(0,t.fetchTeams)(_,f,b,T,j),l})},onClose:()=>{P(null),D(!1)},accessToken:_,is_team_admin:(e=>{if(null==e||null==e.members_with_roles)return!1;for(let s=0;se.team_id===O)),is_proxy_admin:"Admin"==b,is_org_admin:(()=>{let s=e?.find(e=>e.team_id===O);if(!s?.organization_id||!y||!f)return!1;let l=y.find(e=>e.organization_id===s.organization_id);return l?.members?.some(e=>e.user_id===f&&"org_admin"===e.user_role)??!1})(),userModels:U,editTeam:L,premiumUser:v}):(0,s.jsxs)(w,{lastRefreshed:et,onRefresh:er,userRole:b,children:[(0,s.jsxs)(x.TabPanel,{children:[(0,s.jsxs)(h.Text,{children:["Click on “Team ID” to view team details ",(0,s.jsx)("b",{children:"and"})," manage team members."]}),(0,s.jsx)(u.Grid,{numItems:1,className:"gap-2 pt-2 pb-2 h-[75vh] w-full mt-2",children:(0,s.jsx)(m.Col,{numColSpan:1,children:(0,s.jsxs)(d.Card,{className:"w-full mx-auto flex-auto overflow-hidden overflow-y-auto max-h-[50vh]",children:[(0,s.jsx)("div",{className:"border-b px-6 py-4",children:(0,s.jsx)("div",{className:"flex flex-col space-y-4",children:(0,s.jsx)(N,{filters:F,organizations:y,showFilters:k,onToggleFilters:I,onChange:(e,s)=>{let l={...F,[e]:s};A(l),_&&(0,a.v2TeamListCall)(_,l.organization_id||null,null,l.team_id||null,l.team_alias||null).then(e=>{e&&e.teams&&j(e.teams)}).catch(e=>{console.error("Error fetching teams:",e)})},onReset:()=>{A({team_id:"",team_alias:"",organization_id:"",sort_by:"created_at",sort_order:"desc"}),_&&(0,a.v2TeamListCall)(_,null,f||null,null,null).then(e=>{e&&e.teams&&j(e.teams)}).catch(e=>{console.error("Error fetching teams:",e)})}})})}),(0,s.jsx)($,{teams:e,currentOrg:T,perTeamInfo:Q,userRole:b,userId:f,setSelectedTeamId:P,setEditTeam:D,onDeleteTeam:ei}),J&&(0,s.jsx)(K,{teams:e,teamToDelete:Y,onCancel:()=>{q(!1),X(null)},onConfirm:eo})]})})})]}),(0,s.jsx)(x.TabPanel,{children:(0,s.jsx)(p.default,{accessToken:_,userID:f})}),(0,n.isAdminRole)(b||"")&&(0,s.jsx)(x.TabPanel,{children:(0,s.jsx)(o.default,{accessToken:_,userID:f||"",userRole:b||""})})]}),("Admin"==b||"Org Admin"==b)&&(0,s.jsx)(eu,{isTeamModalVisible:B,handleOk:()=>{E(!1),z.resetFields(),es([]),ea({})},handleCancel:()=>{E(!1),z.resetFields(),es([]),ea({})},currentOrg:T,organizations:y,teams:e,setTeams:j,modelAliases:el,setModelAliases:ea,loggingSettings:ee,setLoggingSettings:es,setIsTeamModalVisible:E})]})})})};var ep=e.i(214541),eg=e.i(846835);e.s(["default",0,()=>{let{accessToken:e,userId:a,userRole:t}=(0,S.default)(),{teams:r,setTeams:i}=(0,ep.default)(),[o,n]=(0,l.useState)([]);return(0,l.useEffect)(()=>{(0,eg.fetchOrganizations)(e,n).then(()=>{})},[e]),(0,s.jsx)(ex,{teams:r,accessToken:e,setTeams:i,userID:a,userRole:t,organizations:o})}],596115)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/5c6d02376dbf0f55.js b/litellm/proxy/_experimental/out/_next/static/chunks/5c6d02376dbf0f55.js deleted file mode 100644 index ade2353b315..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/5c6d02376dbf0f55.js +++ /dev/null @@ -1 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,94629,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4"}))});e.s(["SwitchVerticalIcon",0,r],94629)},991124,e=>{"use strict";let t=(0,e.i(475254).default)("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"}]]);e.s(["default",()=>t])},902555,e=>{"use strict";var t=e.i(843476),r=e.i(591935),a=e.i(122577),i=e.i(278587),s=e.i(68155),l=e.i(360820),o=e.i(871943),n=e.i(434626),d=e.i(592968),m=e.i(115504),c=e.i(752978);function u({icon:e,onClick:r,className:a,disabled:i,dataTestId:s}){return i?(0,t.jsx)(c.Icon,{icon:e,size:"sm",className:"opacity-50 cursor-not-allowed","data-testid":s}):(0,t.jsx)(c.Icon,{icon:e,size:"sm",onClick:r,className:(0,m.cx)("cursor-pointer",a),"data-testid":s})}let g={Edit:{icon:r.PencilAltIcon,className:"hover:text-blue-600"},Delete:{icon:s.TrashIcon,className:"hover:text-red-600"},Test:{icon:a.PlayIcon,className:"hover:text-blue-600"},Regenerate:{icon:i.RefreshIcon,className:"hover:text-green-600"},Up:{icon:l.ChevronUpIcon,className:"hover:text-blue-600"},Down:{icon:o.ChevronDownIcon,className:"hover:text-blue-600"},Open:{icon:n.ExternalLinkIcon,className:"hover:text-green-600"}};function h({onClick:e,tooltipText:r,disabled:a=!1,disabledTooltipText:i,dataTestId:s,variant:l}){let{icon:o,className:n}=g[l];return(0,t.jsx)(d.Tooltip,{title:a?i:r,children:(0,t.jsx)("span",{children:(0,t.jsx)(u,{icon:o,onClick:e,className:n,disabled:a,dataTestId:s})})})}e.s(["default",()=>h],902555)},728889,e=>{"use strict";var t=e.i(290571),r=e.i(271645),a=e.i(829087),i=e.i(480731),s=e.i(444755),l=e.i(673706),o=e.i(95779);let n={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"}},d={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:""}},c=(0,l.makeClassName)("Icon"),u=r.default.forwardRef((e,u)=>{let{icon:g,variant:h="simple",tooltip:p,size:x=i.Sizes.SM,color:b,className:_}=e,f=(0,t.__rest)(e,["icon","variant","tooltip","size","color","className"]),y=((e,t)=>{switch(e){case"simple":return{textColor:t?(0,l.getColorClassNames)(t,o.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",bgColor:"",borderColor:"",ringColor:""};case"light":return{textColor:t?(0,l.getColorClassNames)(t,o.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",bgColor:t?(0,s.tremorTwMerge)((0,l.getColorClassNames)(t,o.colorPalette.background).bgColor,"bg-opacity-20"):"bg-tremor-brand-muted dark:bg-dark-tremor-brand-muted",borderColor:"",ringColor:""};case"shadow":return{textColor:t?(0,l.getColorClassNames)(t,o.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",bgColor:t?(0,s.tremorTwMerge)((0,l.getColorClassNames)(t,o.colorPalette.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:t?(0,l.getColorClassNames)(t,o.colorPalette.text).textColor:"text-tremor-brand-inverted dark:text-dark-tremor-brand-inverted",bgColor:t?(0,s.tremorTwMerge)((0,l.getColorClassNames)(t,o.colorPalette.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:t?(0,l.getColorClassNames)(t,o.colorPalette.text).textColor:"text-tremor-brand dark:text-dark-tremor-brand",bgColor:t?(0,s.tremorTwMerge)((0,l.getColorClassNames)(t,o.colorPalette.background).bgColor,"bg-opacity-20"):"bg-tremor-background dark:bg-dark-tremor-background",borderColor:t?(0,l.getColorClassNames)(t,o.colorPalette.ring).borderColor:"border-tremor-brand-subtle dark:border-dark-tremor-brand-subtle",ringColor:t?(0,s.tremorTwMerge)((0,l.getColorClassNames)(t,o.colorPalette.ring).ringColor,"ring-opacity-40"):"ring-tremor-brand-muted dark:ring-dark-tremor-brand-muted"}}})(h,b),{tooltipProps:j,getReferenceProps:v}=(0,a.useTooltip)();return r.default.createElement("span",Object.assign({ref:(0,l.mergeRefs)([u,j.refs.setReference]),className:(0,s.tremorTwMerge)(c("root"),"inline-flex shrink-0 items-center justify-center",y.bgColor,y.textColor,y.borderColor,y.ringColor,m[h].rounded,m[h].border,m[h].shadow,m[h].ring,n[x].paddingX,n[x].paddingY,_)},v,f),r.default.createElement(a.default,Object.assign({text:p},j)),r.default.createElement(g,{className:(0,s.tremorTwMerge)(c("icon"),"shrink-0",d[x].height,d[x].width)}))});u.displayName="Icon",e.s(["default",()=>u],728889)},752978,e=>{"use strict";var t=e.i(728889);e.s(["Icon",()=>t.default])},591935,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.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.s(["PencilAltIcon",0,r],591935)},434626,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("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"}))});e.s(["ExternalLinkIcon",0,r],434626)},122577,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"}),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 12a9 9 0 11-18 0 9 9 0 0118 0z"}))});e.s(["PlayIcon",0,r],122577)},100486,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M899.6 276.5L705 396.4 518.4 147.5a8.06 8.06 0 00-12.9 0L319 396.4 124.3 276.5c-5.7-3.5-13.1 1.2-12.2 7.9L188.5 865c1.1 7.9 7.9 14 16 14h615.1c8 0 14.9-6 15.9-14l76.4-580.6c.8-6.7-6.5-11.4-12.3-7.9zm-126 534.1H250.3l-53.8-409.4 139.8 86.1L512 252.9l175.7 234.4 139.8-86.1-53.9 409.4zM512 509c-62.1 0-112.6 50.5-112.6 112.6S449.9 734.2 512 734.2s112.6-50.5 112.6-112.6S574.1 509 512 509zm0 160.9c-26.6 0-48.2-21.6-48.2-48.3 0-26.6 21.6-48.3 48.2-48.3s48.2 21.6 48.2 48.3c0 26.6-21.6 48.3-48.2 48.3z"}}]},name:"crown",theme:"outlined"};var i=e.i(9583),s=r.forwardRef(function(e,s){return r.createElement(i.default,(0,t.default)({},e,{ref:s,icon:a}))});e.s(["CrownOutlined",0,s],100486)},829672,836938,310730,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),a=e.i(914949),i=e.i(404948);let s=e=>e?"function"==typeof e?e():e:null;e.s(["getRenderPropValue",0,s],836938);var l=e.i(613541),o=e.i(763731),n=e.i(242064),d=e.i(491816);e.i(793154);var m=e.i(880476),c=e.i(183293),u=e.i(717356),g=e.i(320560),h=e.i(307358),p=e.i(246422),x=e.i(838378),b=e.i(617933);let _=(0,p.genStyleHooks)("Popover",e=>{let{colorBgElevated:t,colorText:r}=e,a=(0,x.mergeToken)(e,{popoverBg:t,popoverColor:r});return[(e=>{let{componentCls:t,popoverColor:r,titleMinWidth:a,fontWeightStrong:i,innerPadding:s,boxShadowSecondary:l,colorTextHeading:o,borderRadiusLG:n,zIndexPopup:d,titleMarginBottom:m,colorBgElevated:u,popoverBg:h,titleBorderBottom:p,innerContentPadding:x,titlePadding:b}=e;return[{[t]:Object.assign(Object.assign({},(0,c.resetComponent)(e)),{position:"absolute",top:0,left:{_skip_check_:!0,value:0},zIndex:d,fontWeight:"normal",whiteSpace:"normal",textAlign:"start",cursor:"auto",userSelect:"text","--valid-offset-x":"var(--arrow-offset-horizontal, var(--arrow-x))",transformOrigin:"var(--valid-offset-x, 50%) var(--arrow-y, 50%)","--antd-arrow-background-color":u,width:"max-content",maxWidth:"100vw","&-rtl":{direction:"rtl"},"&-hidden":{display:"none"},[`${t}-content`]:{position:"relative"},[`${t}-inner`]:{backgroundColor:h,backgroundClip:"padding-box",borderRadius:n,boxShadow:l,padding:s},[`${t}-title`]:{minWidth:a,marginBottom:m,color:o,fontWeight:i,borderBottom:p,padding:b},[`${t}-inner-content`]:{color:r,padding:x}})},(0,g.default)(e,"var(--antd-arrow-background-color)"),{[`${t}-pure`]:{position:"relative",maxWidth:"none",margin:e.sizePopupArrow,display:"inline-block",[`${t}-content`]:{display:"inline-block"}}}]})(a),(e=>{let{componentCls:t}=e;return{[t]:b.PresetColors.map(r=>{let a=e[`${r}6`];return{[`&${t}-${r}`]:{"--antd-arrow-background-color":a,[`${t}-inner`]:{backgroundColor:a},[`${t}-arrow`]:{background:"transparent"}}}})}})(a),(0,u.initZoomMotion)(a,"zoom-big")]},e=>{let{lineWidth:t,controlHeight:r,fontHeight:a,padding:i,wireframe:s,zIndexPopupBase:l,borderRadiusLG:o,marginXS:n,lineType:d,colorSplit:m,paddingSM:c}=e,u=r-a;return Object.assign(Object.assign(Object.assign({titleMinWidth:177,zIndexPopup:l+30},(0,h.getArrowToken)(e)),(0,g.getArrowOffsetToken)({contentRadius:o,limitVerticalRadius:!0})),{innerPadding:12*!s,titleMarginBottom:s?0:n,titlePadding:s?`${u/2}px ${i}px ${u/2-t}px`:0,titleBorderBottom:s?`${t}px ${d} ${m}`:"none",innerContentPadding:s?`${c}px ${i}px`:0})},{resetStyle:!1,deprecatedTokens:[["width","titleMinWidth"],["minWidth","titleMinWidth"]]});var f=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,a=Object.getOwnPropertySymbols(e);it.indexOf(a[i])&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(r[a[i]]=e[a[i]]);return r};let y=({title:e,content:r,prefixCls:a})=>e||r?t.createElement(t.Fragment,null,e&&t.createElement("div",{className:`${a}-title`},e),r&&t.createElement("div",{className:`${a}-inner-content`},r)):null,j=e=>{let{hashId:a,prefixCls:i,className:l,style:o,placement:n="top",title:d,content:c,children:u}=e,g=s(d),h=s(c),p=(0,r.default)(a,i,`${i}-pure`,`${i}-placement-${n}`,l);return t.createElement("div",{className:p,style:o},t.createElement("div",{className:`${i}-arrow`}),t.createElement(m.Popup,Object.assign({},e,{className:a,prefixCls:i}),u||t.createElement(y,{prefixCls:i,title:g,content:h})))},v=e=>{let{prefixCls:a,className:i}=e,s=f(e,["prefixCls","className"]),{getPrefixCls:l}=t.useContext(n.ConfigContext),o=l("popover",a),[d,m,c]=_(o);return d(t.createElement(j,Object.assign({},s,{prefixCls:o,hashId:m,className:(0,r.default)(i,c)})))};e.s(["Overlay",0,y,"default",0,v],310730);var w=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,a=Object.getOwnPropertySymbols(e);it.indexOf(a[i])&&Object.prototype.propertyIsEnumerable.call(e,a[i])&&(r[a[i]]=e[a[i]]);return r};let C=t.forwardRef((e,m)=>{var c,u;let{prefixCls:g,title:h,content:p,overlayClassName:x,placement:b="top",trigger:f="hover",children:j,mouseEnterDelay:v=.1,mouseLeaveDelay:C=.1,onOpenChange:k,overlayStyle:N={},styles:S,classNames:T}=e,I=w(e,["prefixCls","title","content","overlayClassName","placement","trigger","children","mouseEnterDelay","mouseLeaveDelay","onOpenChange","overlayStyle","styles","classNames"]),{getPrefixCls:M,className:z,style:O,classNames:P,styles:D}=(0,n.useComponentConfig)("popover"),L=M("popover",g),[B,E,F]=_(L),A=M(),R=(0,r.default)(x,E,F,z,P.root,null==T?void 0:T.root),V=(0,r.default)(P.body,null==T?void 0:T.body),[$,U]=(0,a.default)(!1,{value:null!=(c=e.open)?c:e.visible,defaultValue:null!=(u=e.defaultOpen)?u:e.defaultVisible}),K=(e,t)=>{U(e,!0),null==k||k(e,t)},W=s(h),G=s(p);return B(t.createElement(d.default,Object.assign({placement:b,trigger:f,mouseEnterDelay:v,mouseLeaveDelay:C},I,{prefixCls:L,classNames:{root:R,body:V},styles:{root:Object.assign(Object.assign(Object.assign(Object.assign({},D.root),O),N),null==S?void 0:S.root),body:Object.assign(Object.assign({},D.body),null==S?void 0:S.body)},ref:m,open:$,onOpenChange:e=>{K(e)},overlay:W||G?t.createElement(y,{prefixCls:L,title:W,content:G}):null,transitionName:(0,l.getTransitionName)(A,"zoom-big",I.transitionName),"data-popover-inject":!0}),(0,o.cloneElement)(j,{onKeyDown:e=>{var r,a;(0,t.isValidElement)(j)&&(null==(a=null==j?void 0:(r=j.props).onKeyDown)||a.call(r,e)),e.keyCode===i.default.ESC&&K(!1,e)}})))});C._InternalPanelDoNotUseOrYouWillBeFired=v,e.s(["default",0,C],829672)},282786,e=>{"use strict";var t=e.i(829672);e.s(["Popover",()=>t.default])},751904,e=>{"use strict";var t=e.i(401361);e.s(["EditOutlined",()=>t.default])},56567,e=>{"use strict";var t=e.i(843476),r=e.i(135214),a=e.i(907308),i=e.i(764205),s=e.i(500330),l=e.i(11751),o=e.i(708347),n=e.i(751904),d=e.i(827252),m=e.i(987432),c=e.i(530212),u=e.i(389083),g=e.i(304967),h=e.i(350967),p=e.i(599724),x=e.i(779241),b=e.i(629569),_=e.i(464571),f=e.i(808613),y=e.i(311451),j=e.i(998573),v=e.i(199133),w=e.i(790848),C=e.i(653496),k=e.i(592968),N=e.i(678784),S=e.i(118366),T=e.i(271645),I=e.i(9314),M=e.i(552130),z=e.i(127952);function O({className:e,value:r,onChange:a}){return(0,t.jsxs)(v.Select,{className:e,value:r,onChange:a,children:[(0,t.jsx)(v.Select.Option,{value:"24h",children:"Daily"}),(0,t.jsx)(v.Select.Option,{value:"7d",children:"Weekly"}),(0,t.jsx)(v.Select.Option,{value:"30d",children:"Monthly"})]})}var P=e.i(844565),D=e.i(355619),L=e.i(643449),B=e.i(75921),E=e.i(390605),F=e.i(162386),A=e.i(727749),R=e.i(384767),V=e.i(435451),$=e.i(916940),U=e.i(183588),K=e.i(276173),W=e.i(91979),G=e.i(269200),q=e.i(942232),H=e.i(977572),J=e.i(427612),Y=e.i(64848),X=e.i(496020),Q=e.i(536916),Z=e.i(21548);let ee={"/key/generate":"Member can generate a virtual key for this team","/key/service-account/generate":"Member can generate a service account key (not belonging to any user) for this team","/key/update":"Member can update a virtual key belonging to this team","/key/delete":"Member can delete a virtual key belonging to this team","/key/info":"Member can get info about a virtual key belonging to this team","/key/regenerate":"Member can regenerate a virtual key belonging to this team","/key/{key_id}/regenerate":"Member can regenerate a virtual key belonging to this team","/key/list":"Member can list virtual keys belonging to this team","/key/block":"Member can block a virtual key belonging to this team","/key/unblock":"Member can unblock a virtual key belonging to this team","/team/daily/activity":"Member can view all team usage data (not just their own)"},et=({teamId:e,accessToken:r,canEditTeam:a})=>{let[s,l]=(0,T.useState)([]),[o,n]=(0,T.useState)([]),[d,c]=(0,T.useState)(!0),[u,h]=(0,T.useState)(!1),[x,f]=(0,T.useState)(!1),y=async()=>{try{if(c(!0),!r)return;let t=await (0,i.getTeamPermissionsCall)(r,e),a=t.all_available_permissions||[];l(a);let s=t.team_member_permissions||[];n(s),f(!1)}catch(e){A.default.fromBackend("Failed to load permissions"),console.error("Error fetching permissions:",e)}finally{c(!1)}};(0,T.useEffect)(()=>{y()},[e,r]);let j=async()=>{try{if(!r)return;h(!0),await (0,i.teamPermissionsUpdateCall)(r,e,o),A.default.success("Permissions updated successfully"),f(!1)}catch(e){A.default.fromBackend("Failed to update permissions"),console.error("Error updating permissions:",e)}finally{h(!1)}};if(d)return(0,t.jsx)("div",{className:"p-6 text-center",children:"Loading permissions..."});let v=s.length>0;return(0,t.jsxs)(g.Card,{className:"bg-white shadow-md rounded-md p-6",children:[(0,t.jsxs)("div",{className:"flex flex-col sm:flex-row justify-between items-start sm:items-center border-b pb-4 mb-6",children:[(0,t.jsx)(b.Title,{className:"mb-2 sm:mb-0",children:"Member Permissions"}),a&&x&&(0,t.jsxs)("div",{className:"flex gap-3",children:[(0,t.jsx)(_.Button,{icon:(0,t.jsx)(W.ReloadOutlined,{}),onClick:()=>{y()},children:"Reset"}),(0,t.jsxs)(_.Button,{onClick:j,loading:u,type:"primary",children:[(0,t.jsx)(m.SaveOutlined,{})," Save Changes"]})]})]}),(0,t.jsx)(p.Text,{className:"mb-6 text-gray-600",children:"Control what team members can do when they are not team admins."}),v?(0,t.jsx)("div",{className:"overflow-x-auto",children:(0,t.jsxs)(G.Table,{className:" min-w-full",children:[(0,t.jsx)(J.TableHead,{children:(0,t.jsxs)(X.TableRow,{children:[(0,t.jsx)(Y.TableHeaderCell,{children:"Method"}),(0,t.jsx)(Y.TableHeaderCell,{children:"Endpoint"}),(0,t.jsx)(Y.TableHeaderCell,{children:"Description"}),(0,t.jsx)(Y.TableHeaderCell,{className:"sticky right-0 bg-white shadow-[-4px_0_4px_-4px_rgba(0,0,0,0.1)] text-center",children:"Allow Access"})]})}),(0,t.jsx)(q.TableBody,{children:s.map(e=>{let r=(e=>{let t=e.includes("/info")||e.includes("/list")||e.includes("/activity")?"GET":"POST",r=ee[e];if(!r){for(let[t,a]of Object.entries(ee))if(e.includes(t)){r=a;break}}return r||(r=`Access ${e}`),{method:t,endpoint:e,description:r,route:e}})(e);return(0,t.jsxs)(X.TableRow,{className:"hover:bg-gray-50 transition-colors",children:[(0,t.jsx)(H.TableCell,{children:(0,t.jsx)("span",{className:`px-2 py-1 rounded text-xs font-medium ${"GET"===r.method?"bg-blue-100 text-blue-800":"bg-green-100 text-green-800"}`,children:r.method})}),(0,t.jsx)(H.TableCell,{children:(0,t.jsx)("span",{className:"font-mono text-sm text-gray-800",children:r.endpoint})}),(0,t.jsx)(H.TableCell,{className:"text-gray-700",children:r.description}),(0,t.jsx)(H.TableCell,{className:"sticky right-0 bg-white shadow-[-4px_0_4px_-4px_rgba(0,0,0,0.1)] text-center",children:(0,t.jsx)(Q.Checkbox,{checked:o.includes(e),onChange:t=>{n(t.target.checked?[...o,e]:o.filter(t=>t!==e)),f(!0)},disabled:!a})})]},e)})})]})}):(0,t.jsx)("div",{className:"py-12",children:(0,t.jsx)(Z.Empty,{description:"No permissions available"})})]})},er="overview",ea="virtual-keys",ei="members",es="member-permissions",el="settings",eo={[er]:"Overview",[ea]:"Virtual Keys",[ei]:"Members",[es]:"Member Permissions",[el]:"Settings"};var en=e.i(292639),ed=e.i(770914),em=e.i(898586),ec=e.i(294612);function eu({teamData:e,canEditTeam:a,handleMemberDelete:i,setSelectedEditMember:l,setIsEditMemberModalVisible:n,setIsAddMemberModalVisible:m}){let c=e=>{if(null==e)return"0";if("number"==typeof e){let t=Number(e);return t===Math.floor(t)?t.toString():(0,s.formatNumberWithCommas)(t,8).replace(/\.?0+$/,"")}return"0"},{data:u}=(0,en.useUISettings)(),{userId:g,userRole:h}=(0,r.default)(),p=!!u?.values?.disable_team_admin_delete_team_user,x=(0,o.isUserTeamAdminForSingleTeam)(e.team_info.members_with_roles,g||""),b=(0,o.isProxyAdminRole)(h||""),_=[{title:(0,t.jsxs)(ed.Space,{direction:"horizontal",children:["Team Member Spend (USD)",(0,t.jsx)(k.Tooltip,{title:"This is the amount spent by a user in the team.",children:(0,t.jsx)(d.InfoCircleOutlined,{})})]}),key:"spend",render:(r,a)=>(0,t.jsxs)(em.Typography.Text,{children:["$",(0,s.formatNumberWithCommas)((t=>{if(!t)return 0;let r=e.team_memberships.find(e=>e.user_id===t);return r?.spend||0})(a.user_id),4)]})},{title:"Team Member Budget (USD)",key:"budget",render:(r,a)=>{let i=(t=>{if(!t)return null;let r=e.team_memberships.find(e=>e.user_id===t),a=r?.litellm_budget_table?.max_budget;return null==a?null:c(a)})(a.user_id);return(0,t.jsx)(em.Typography.Text,{children:i?`$${(0,s.formatNumberWithCommas)(Number(i),4)}`:"No Limit"})}},{title:(0,t.jsxs)(ed.Space,{direction:"horizontal",children:["Team Member Rate Limits",(0,t.jsx)(k.Tooltip,{title:"Rate limits for this member's usage within this team.",children:(0,t.jsx)(d.InfoCircleOutlined,{})})]}),key:"rate_limits",render:(r,a)=>(0,t.jsx)(em.Typography.Text,{children:(t=>{if(!t)return"No Limits";let r=e.team_memberships.find(e=>e.user_id===t),a=r?.litellm_budget_table?.rpm_limit,i=r?.litellm_budget_table?.tpm_limit,s=[a?`${c(a)} RPM`:null,i?`${c(i)} TPM`:null].filter(Boolean);return s.length>0?s.join(" / "):"No Limits"})(a.user_id)})}];return(0,t.jsx)(ec.default,{members:e.team_info.members_with_roles,canEdit:a,onEdit:t=>{let r=e.team_memberships.find(e=>e.user_id===t.user_id);l({...t,max_budget_in_team:r?.litellm_budget_table?.max_budget||null,tpm_limit:r?.litellm_budget_table?.tpm_limit||null,rpm_limit:r?.litellm_budget_table?.rpm_limit||null}),n(!0)},onDelete:i,onAddMember:()=>m(!0),roleColumnTitle:"Team Role",roleTooltip:"This role applies only to this team and is independent from the user's proxy-level role.",extraColumns:_,showDeleteForMember:()=>b||x&&!p})}var eg=e.i(207082),eh=e.i(871943),ep=e.i(502547),ex=e.i(360820),eb=e.i(94629),e_=e.i(152990),ef=e.i(682830),ey=e.i(994388),ej=e.i(752978),ev=e.i(282786),ew=e.i(981339),eC=e.i(969550),ek=e.i(20147),eN=e.i(266027),eS=e.i(633627);function eT({teamId:e,teamAlias:a,organization:i}){let{accessToken:l}=(0,r.default)(),[o,n]=(0,T.useState)(null),[m,c]=(0,T.useState)([{id:"created_at",desc:!0}]),[g,h]=(0,T.useState)({pageIndex:0,pageSize:50}),[x,b]=(0,T.useState)({"Organization ID":"","Key Alias":"","User ID":"","Sort By":"created_at","Sort Order":"desc"}),_=m.length>0?m[0].id:"created_at",f=m.length>0?m[0].desc?"desc":"asc":"desc",y=g.pageIndex,j=g.pageSize,{data:v,isPending:w,isFetching:C,refetch:N}=(0,eg.useKeys)(y+1,j,{teamID:e,organizationID:x["Organization ID"]?.trim()||void 0,selectedKeyAlias:x["Key Alias"]?.trim()||void 0,userID:x["User ID"]?.trim()||void 0,sortBy:_||void 0,sortOrder:f||void 0,expand:"user"}),S=(0,T.useMemo)(()=>{let e=v?.keys||[],t=i?.organization_id;return t?e.map(e=>({...e,organization_id:(e.organization_id??e.org_id)||t})):e},[v?.keys,i?.organization_id]),I=v?.total_count??0,M=v?.total_pages??0,[z,O]=(0,T.useState)({}),P=(0,T.useMemo)(()=>({team_id:e,team_alias:a||e,models:[],max_budget:null,budget_duration:null,tpm_limit:null,rpm_limit:null,organization_id:i?.organization_id||"",created_at:"",keys:[],members_with_roles:[],spend:0}),[e,a,i]),L=(0,eN.useQuery)({queryKey:["teamFilterOptions",e,l],queryFn:async()=>(0,eS.fetchTeamFilterOptions)(l,e),enabled:!!l&&!!e,staleTime:3e4}).data||{keyAliases:[],organizationIds:[],userIds:[]},B=(0,T.useCallback)(()=>{N?.()},[N]);(0,T.useEffect)(()=>(window.addEventListener("storage",B),()=>window.removeEventListener("storage",B)),[B]);let E=(0,T.useCallback)((e,t=!1)=>{b(t=>({...t,"Organization ID":e["Organization ID"]??t["Organization ID"],"Key Alias":e["Key Alias"]??t["Key Alias"],"User ID":e["User ID"]??t["User ID"],"Sort By":e["Sort By"]??t["Sort By"]??"created_at","Sort Order":e["Sort Order"]??t["Sort Order"]??"desc"})),t||h(e=>({...e,pageIndex:0}))},[]),F=(0,T.useCallback)(()=>{b({"Organization ID":"","Key Alias":"","User ID":"","Sort By":"created_at","Sort Order":"desc"}),h(e=>({...e,pageIndex:0}))},[]),A=(0,T.useMemo)(()=>[{name:"Organization ID",label:"Organization ID",isSearchable:!0,searchFn:async e=>{let{organizationIds:t}=L;if(!t.length)return[];let r=e.toLowerCase();return(r?t.filter(e=>e.toLowerCase().includes(r)):t).map(e=>({label:e,value:e}))}},{name:"Key Alias",label:"Key Alias",isSearchable:!0,searchFn:async e=>{let{keyAliases:t}=L,r=e.toLowerCase();return(r?t.filter(e=>e.toLowerCase().includes(r)):t).map(e=>({label:e,value:e}))}},{name:"User ID",label:"User ID",isSearchable:!0,searchFn:async e=>{let{userIds:t}=L,r=e.toLowerCase();return(r?t.filter(e=>e.id.toLowerCase().includes(r)||e.email.toLowerCase().includes(r)):t).map(e=>({label:e.email?`${e.id} (${e.email})`:e.id,value:e.id}))}}],[L]),R=(0,T.useMemo)(()=>[{id:"token",accessorKey:"token",header:"Key ID",size:100,enableSorting:!0,cell:e=>{let r=e.getValue(),a=e.cell.column.getSize();return(0,t.jsx)(k.Tooltip,{title:r,children:(0,t.jsx)(ey.Button,{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 block",style:{maxWidth:a,overflow:"hidden"},onClick:()=>n(e.row.original),children:r??"-"})})}},{id:"key_alias",accessorKey:"key_alias",header:"Key Alias",size:150,enableSorting:!0,cell:e=>{let r=e.getValue(),a=e.cell.column.getSize();return(0,t.jsx)(k.Tooltip,{title:r,children:(0,t.jsx)("span",{className:"font-mono text-xs truncate block",style:{maxWidth:a,overflow:"hidden"},children:r??"-"})})}},{id:"key_name",accessorKey:"key_name",header:"Secret Key",size:120,enableSorting:!1,cell:e=>(0,t.jsx)("span",{className:"font-mono text-xs",children:e.getValue()})},{id:"organization_id",accessorKey:"organization_id",header:"Organization ID",size:140,enableSorting:!1,cell:e=>e.getValue()?e.renderValue():"-"},{id:"user_email",accessorKey:"user",header:"User Email",size:160,enableSorting:!1,cell:e=>{let r=e.getValue(),a=r?.user_email,i=e.cell.column.getSize();return(0,t.jsx)(k.Tooltip,{title:a,children:(0,t.jsx)("span",{className:"font-mono text-xs truncate block",style:{maxWidth:i,overflow:"hidden"},children:a??"-"})})}},{id:"user_id",accessorKey:"user_id",header:"User ID",size:70,enableSorting:!1,cell:e=>{let r=e.getValue(),a="default_user_id"===r?"Default Proxy Admin":r,i=e.cell.column.getSize();return(0,t.jsx)(k.Tooltip,{title:a,children:(0,t.jsx)("span",{className:"font-mono text-xs truncate block",style:{maxWidth:i,overflow:"hidden"},children:a??"-"})})}},{id:"created_at",accessorKey:"created_at",header:"Created At",size:120,enableSorting:!0,cell:e=>{let t=e.getValue();return t?new Date(t).toLocaleDateString():"-"}},{id:"created_by",accessorKey:"created_by",header:"Created By",size:70,enableSorting:!1,cell:e=>{let r=e.getValue(),a="default_user_id"===r?"Default Proxy Admin":r,i=e.cell.column.getSize();return(0,t.jsx)(k.Tooltip,{title:a,children:(0,t.jsx)("span",{className:"font-mono text-xs truncate block",style:{maxWidth:i,overflow:"hidden"},children:a??"-"})})}},{id:"updated_at",accessorKey:"updated_at",header:"Updated At",size:120,enableSorting:!0,cell:e=>{let t=e.getValue();return t?new Date(t).toLocaleDateString():"Never"}},{id:"last_active",accessorKey:"last_active",header:()=>(0,t.jsxs)("span",{className:"flex items-center gap-1",children:["Last Active",(0,t.jsx)(ev.Popover,{content:"This is a new field and is not backfilled. Only new key usage will update this value.",trigger:"hover",children:(0,t.jsx)(d.InfoCircleOutlined,{className:"text-gray-400 text-xs cursor-help"})})]}),size:130,enableSorting:!1,cell:e=>{let r=e.getValue();if(!r)return"Unknown";let a=new Date(r);return(0,t.jsx)(k.Tooltip,{title:a.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"long"}),children:(0,t.jsx)("span",{children:a.toLocaleDateString()})})}},{id:"expires",accessorKey:"expires",header:"Expires",size:120,enableSorting:!1,cell:e=>{let t=e.getValue();return t?new Date(t).toLocaleDateString():"Never"}},{id:"spend",accessorKey:"spend",header:"Spend (USD)",size:100,enableSorting:!0,cell:e=>(0,s.formatNumberWithCommas)(e.getValue(),4)},{id:"max_budget",accessorKey:"max_budget",header:"Budget (USD)",size:110,enableSorting:!0,cell:e=>{let t=e.getValue();return null===t?"Unlimited":`$${(0,s.formatNumberWithCommas)(t)}`}},{id:"budget_reset_at",accessorKey:"budget_reset_at",header:"Budget Reset",size:130,enableSorting:!1,cell:e=>{let t=e.getValue();return t?new Date(t).toLocaleString():"Never"}},{id:"models",accessorKey:"models",header:"Models",size:200,enableSorting:!1,cell:e=>{let r=e.getValue();return(0,t.jsx)("div",{className:"flex flex-col py-2",children:Array.isArray(r)?(0,t.jsx)("div",{className:"flex flex-col",children:0===r.length?(0,t.jsx)(u.Badge,{size:"xs",className:"mb-1",color:"red",children:(0,t.jsx)(p.Text,{children:"All Proxy Models"})}):(0,t.jsx)(t.Fragment,{children:(0,t.jsxs)("div",{className:"flex items-start",children:[r.length>3&&(0,t.jsx)("div",{children:(0,t.jsx)(ej.Icon,{icon:z[e.row.id]?eh.ChevronDownIcon:ep.ChevronRightIcon,className:"cursor-pointer",size:"xs",onClick:()=>O(t=>({...t,[e.row.id]:!t[e.row.id]}))})}),(0,t.jsxs)("div",{className:"flex flex-wrap gap-1",children:[r.slice(0,3).map((e,r)=>"all-proxy-models"===e?(0,t.jsx)(u.Badge,{size:"xs",color:"red",children:(0,t.jsx)(p.Text,{children:"All Proxy Models"})},r):(0,t.jsx)(u.Badge,{size:"xs",color:"blue",children:(0,t.jsx)(p.Text,{children:e.length>30?`${(0,D.getModelDisplayName)(e).slice(0,30)}...`:(0,D.getModelDisplayName)(e)})},r)),r.length>3&&!z[e.row.id]&&(0,t.jsx)(u.Badge,{size:"xs",color:"gray",className:"cursor-pointer",children:(0,t.jsxs)(p.Text,{children:["+",r.length-3," ",r.length-3==1?"more model":"more models"]})}),z[e.row.id]&&(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:r.slice(3).map((e,r)=>"all-proxy-models"===e?(0,t.jsx)(u.Badge,{size:"xs",color:"red",children:(0,t.jsx)(p.Text,{children:"All Proxy Models"})},r+3):(0,t.jsx)(u.Badge,{size:"xs",color:"blue",children:(0,t.jsx)(p.Text,{children:e.length>30?`${(0,D.getModelDisplayName)(e).slice(0,30)}...`:(0,D.getModelDisplayName)(e)})},r+3))})]})]})})}):null})}},{id:"rate_limits",header:"Rate Limits",size:140,enableSorting:!1,cell:({row:e})=>{let r=e.original;return(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{children:["TPM: ",null!==r.tpm_limit?r.tpm_limit:"Unlimited"]}),(0,t.jsxs)("div",{children:["RPM: ",null!==r.rpm_limit?r.rpm_limit:"Unlimited"]})]})}}],[z]),V=(0,T.useCallback)(e=>{let t="function"==typeof e?e(m):e;if(c(t),t?.length>0){let e=t[0];E({"Sort By":e.id,"Sort Order":e.desc?"desc":"asc"},!0)}},[m,E]),$=(0,e_.useReactTable)({data:S,columns:R,columnResizeMode:"onChange",columnResizeDirection:"ltr",state:{sorting:m,pagination:g},onSortingChange:V,onPaginationChange:h,getCoreRowModel:(0,ef.getCoreRowModel)(),enableSorting:!0,manualSorting:!0,manualPagination:!0,pageCount:M});return(0,t.jsx)("div",{className:"w-full h-full overflow-hidden",children:o?(0,t.jsx)(ek.default,{keyId:o.token,onClose:()=>n(null),keyData:o,teams:[P],onDelete:N}):(0,t.jsxs)("div",{className:"border-b py-4 flex-1 overflow-hidden",children:[(0,t.jsx)("div",{className:"w-full mb-6",children:(0,t.jsx)(eC.default,{options:A,onApplyFilters:E,initialValues:x,onResetFilters:F})}),(0,t.jsxs)("div",{className:"flex items-center justify-between w-full mb-4",children:[w||C?(0,t.jsx)(ew.Skeleton.Node,{active:!0,style:{width:200,height:20}}):(0,t.jsxs)("span",{className:"inline-flex text-sm text-gray-700",children:[I," Member",1!==I?"s":""]}),(0,t.jsxs)("div",{className:"inline-flex items-center gap-2",children:[w||C?(0,t.jsx)(ew.Skeleton.Node,{active:!0,style:{width:74,height:20}}):(0,t.jsxs)("span",{className:"text-sm text-gray-700",children:["Page ",y+1," of ",$.getPageCount()]}),w||C?(0,t.jsx)(ew.Skeleton.Button,{active:!0,size:"small",style:{width:84,height:30}}):(0,t.jsx)("button",{onClick:()=>$.previousPage(),disabled:w||C||!$.getCanPreviousPage(),className:"px-3 py-1 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Previous"}),w||C?(0,t.jsx)(ew.Skeleton.Button,{active:!0,size:"small",style:{width:58,height:30}}):(0,t.jsx)("button",{onClick:()=>$.nextPage(),disabled:w||C||!$.getCanNextPage(),className:"px-3 py-1 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Next"})]})]}),(0,t.jsx)("div",{className:"h-[75vh] 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)(G.Table,{className:"[&_td]:py-0.5 [&_th]:py-1",style:{width:$.getCenterTotalSize()},children:[(0,t.jsx)(J.TableHead,{children:$.getHeaderGroups().map(e=>(0,t.jsx)(X.TableRow,{children:e.headers.map(e=>(0,t.jsx)(Y.TableHeaderCell,{"data-header-id":e.id,className:`py-1 h-8 relative hover:bg-gray-50 ${"actions"===e.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]":""}`,style:{width:e.getSize(),position:"relative",cursor:e.column.getCanSort()?"pointer":"default"},onMouseEnter:()=>{let t=document.querySelector(`[data-header-id="${e.id}"] .resizer`);t&&(t.style.opacity="0.5")},onMouseLeave:()=>{let t=document.querySelector(`[data-header-id="${e.id}"] .resizer`);t&&!e.column.getIsResizing()&&(t.style.opacity="0")},onClick:e.column.getCanSort()?e.column.getToggleSortingHandler():void 0,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,e_.flexRender)(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)(ex.ChevronUpIcon,{className:"h-4 w-4 text-blue-500"}),desc:(0,t.jsx)(eh.ChevronDownIcon,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,t.jsx)(eb.SwitchVerticalIcon,{className:"h-4 w-4 text-gray-400"})}),(0,t.jsx)("div",{onDoubleClick:()=>e.column.resetSize(),onMouseDown:e.getResizeHandler(),onTouchStart:e.getResizeHandler(),className:`resizer ${$.options.columnResizeDirection} ${e.column.getIsResizing()?"isResizing":""}`,style:{position:"absolute",right:0,top:0,height:"100%",width:"5px",background:e.column.getIsResizing()?"#3b82f6":"transparent",cursor:"col-resize",userSelect:"none",touchAction:"none",opacity:+!!e.column.getIsResizing()}})]})},e.id))},e.id))}),(0,t.jsx)(q.TableBody,{children:w||C?(0,t.jsx)(X.TableRow,{children:(0,t.jsx)(H.TableCell,{colSpan:R.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:"Loading keys..."})})})}):S.length>0?$.getRowModel().rows.map(e=>(0,t.jsx)(X.TableRow,{className:"h-8",children:e.getVisibleCells().map(e=>(0,t.jsx)(H.TableCell,{style:{width:e.column.getSize(),maxWidth:"8-x",whiteSpace:"pre-wrap",overflow:"hidden"},className:`py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap ${"models"===e.column.id&&Array.isArray(e.getValue())&&e.getValue().length>3?"px-0":""}`,children:(0,e_.flexRender)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,t.jsx)(X.TableRow,{children:(0,t.jsx)(H.TableCell,{colSpan:R.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:"No keys found"})})})})})]})})})})]})})}e.s(["default",0,({teamId:e,onClose:W,accessToken:G,is_team_admin:q,is_proxy_admin:H,userModels:J,editTeam:Y,premiumUser:X=!1,onUpdate:Q})=>{let[Z,ee]=(0,T.useState)(null),[en,ed]=(0,T.useState)(!0),[em,ec]=(0,T.useState)(!1),[eg]=f.Form.useForm(),[eh,ep]=(0,T.useState)(!1),[ex,eb]=(0,T.useState)(null),[e_,ef]=(0,T.useState)(!1),[ey,ej]=(0,T.useState)([]),[ev,ew]=(0,T.useState)(!1),[eC,ek]=(0,T.useState)({}),[eN,eS]=(0,T.useState)([]),[eI,eM]=(0,T.useState)([]),[ez,eO]=(0,T.useState)({}),[eP,eD]=(0,T.useState)(!1),[eL,eB]=(0,T.useState)(null),[eE,eF]=(0,T.useState)(!1),[eA,eR]=(0,T.useState)(!1),[eV,e$]=(0,T.useState)(!1),[eU,eK]=(0,T.useState)(null),{userRole:eW}=(0,r.default)(),eG=q||H,eq=(0,T.useMemo)(()=>{let e;return e=[er,ea],eG?[...e,ei,es,el]:e},[eG]),eH=(0,T.useMemo)(()=>Y&&eG?el:er,[Y,eG]),eJ=async()=>{try{if(ed(!0),!G)return;let t=await (0,i.teamInfoCall)(G,e);ee(t)}catch(e){A.default.fromBackend("Failed to load team information"),console.error("Error fetching team info:",e)}finally{ed(!1)}};(0,T.useEffect)(()=>{eJ()},[e,G]),(0,T.useEffect)(()=>{(async()=>{if(!G||!Z?.team_info?.organization_id)return eK(null);try{let e=await (0,i.organizationInfoCall)(G,Z.team_info.organization_id);eK(e)}catch(e){console.error("Error fetching organization info:",e),eK(null)}})()},[G,Z?.team_info?.organization_id]),(0,T.useMemo)(()=>{let e;return e=[],e=eU?eU.models.includes("all-proxy-models")?J:eU.models.length>0?eU.models:J:J,(0,D.unfurlWildcardModelsInList)(e,J)},[eU,J]),(0,T.useEffect)(()=>{let e=async()=>{try{if(!G)return;let e=(await (0,i.getPoliciesList)(G)).policies.map(e=>e.policy_name);eM(e)}catch(e){console.error("Failed to fetch policies:",e)}};(async()=>{try{if(!G)return;let e=(await (0,i.getGuardrailsList)(G)).guardrails.map(e=>e.guardrail_name);eS(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})(),e()},[G]),(0,T.useEffect)(()=>{(async()=>{if(!G||!Z?.team_info?.policies||0===Z.team_info.policies.length)return;eD(!0);let e={};try{await Promise.all(Z.team_info.policies.map(async t=>{try{let r=await (0,i.getPolicyInfoWithGuardrails)(G,t);e[t]=r.resolved_guardrails||[]}catch(r){console.error(`Failed to fetch guardrails for policy ${t}:`,r),e[t]=[]}})),eO(e)}catch(e){console.error("Failed to fetch policy guardrails:",e)}finally{eD(!1)}})()},[G,Z?.team_info?.policies]);let eY=async t=>{try{if(null==G)return;let r={user_email:t.user_email,user_id:t.user_id,role:t.role};await (0,i.teamMemberAddCall)(G,e,r),A.default.success("Team member added successfully"),ec(!1),eg.resetFields();let a=await (0,i.teamInfoCall)(G,e);ee(a),Q(a)}catch(t){let e="Failed to add team member";t?.raw?.detail?.error?.includes("Assigning team admins is a premium feature")?e="Assigning admins is an enterprise-only feature. Please upgrade your LiteLLM plan to enable this.":t?.message&&(e=t.message),A.default.fromBackend(e),console.error("Error adding team member:",t)}},eX=async t=>{try{if(null==G)return;let r={user_email:t.user_email,user_id:t.user_id,role:t.role,max_budget_in_team:t.max_budget_in_team,tpm_limit:t.tpm_limit,rpm_limit:t.rpm_limit};j.message.destroy(),await (0,i.teamMemberUpdateCall)(G,e,r),A.default.success("Team member updated successfully"),ep(!1);let a=await (0,i.teamInfoCall)(G,e);ee(a),Q(a)}catch(t){let e="Failed to update team member";t?.raw?.detail?.includes("Assigning team admins is a premium feature")?e="Assigning admins is an enterprise-only feature. Please upgrade your LiteLLM plan to enable this.":t?.message&&(e=t.message),ep(!1),j.message.destroy(),A.default.fromBackend(e),console.error("Error updating team member:",t)}},eQ=async()=>{if(eL&&G){eR(!0);try{await (0,i.teamMemberDeleteCall)(G,e,eL),A.default.success("Team member removed successfully");let t=await (0,i.teamInfoCall)(G,e);ee(t),Q(t)}catch(e){A.default.fromBackend("Failed to remove team member"),console.error("Error removing team member:",e)}finally{eR(!1),eF(!1),eB(null)}}},eZ=async t=>{try{let r;if(!G)return;e$(!0);let a={};try{let{soft_budget_alerting_emails:e,...r}=t.metadata?JSON.parse(t.metadata):{};a=r}catch(e){A.default.fromBackend("Invalid JSON in metadata field");return}if("string"==typeof t.secret_manager_settings&&t.secret_manager_settings.trim().length>0)try{r=JSON.parse(t.secret_manager_settings)}catch(e){A.default.fromBackend("Invalid JSON in secret manager settings");return}let s=e=>null==e||"string"==typeof e&&""===e.trim()||"number"==typeof e&&Number.isNaN(e)?null:e,o={team_id:e,team_alias:t.team_alias,models:t.models,tpm_limit:s(t.tpm_limit),rpm_limit:s(t.rpm_limit),max_budget:t.max_budget,soft_budget:s(t.soft_budget),budget_duration:t.budget_duration,metadata:{...a,...t.guardrails?.length>0?{guardrails:t.guardrails}:{},...t.logging_settings?.length>0?{logging:t.logging_settings}:{},disable_global_guardrails:t.disable_global_guardrails||!1,soft_budget_alerting_emails:"string"==typeof t.soft_budget_alerting_emails?t.soft_budget_alerting_emails.split(",").map(e=>e.trim()).filter(e=>e.length>0):t.soft_budget_alerting_emails||[],...void 0!==r?{secret_manager_settings:r}:{}},...t.policies?.length>0?{policies:t.policies}:{},organization_id:t.organization_id};o.max_budget=(0,l.mapEmptyStringToNull)(o.max_budget),o.team_member_budget_duration=t.team_member_budget_duration,void 0!==t.team_member_budget&&(o.team_member_budget=Number(t.team_member_budget)),void 0!==t.team_member_key_duration&&(o.team_member_key_duration=t.team_member_key_duration),(void 0!==t.team_member_tpm_limit||void 0!==t.team_member_rpm_limit)&&(o.team_member_tpm_limit=s(t.team_member_tpm_limit),o.team_member_rpm_limit=s(t.team_member_rpm_limit));let{servers:n,accessGroups:d}=t.mcp_servers_and_groups||{servers:[],accessGroups:[]},m=new Set(n||[]),c=Object.fromEntries(Object.entries(t.mcp_tool_permissions||{}).filter(([e])=>m.has(e)));o.object_permission={},n&&(o.object_permission.mcp_servers=n),d&&(o.object_permission.mcp_access_groups=d),c&&(o.object_permission.mcp_tool_permissions=c),delete t.mcp_servers_and_groups,delete t.mcp_tool_permissions;let{agents:u,accessGroups:g}=t.agents_and_groups||{agents:[],accessGroups:[]};u&&u.length>0&&(o.object_permission.agents=u),g&&g.length>0&&(o.object_permission.agent_access_groups=g),delete t.agents_and_groups,t.vector_stores&&t.vector_stores.length>0&&(o.object_permission.vector_stores=t.vector_stores),void 0!==t.access_group_ids&&(o.access_group_ids=t.access_group_ids),await (0,i.teamUpdateCall)(G,o),A.default.success("Team settings updated successfully"),ef(!1),eJ()}catch(e){console.error("Error updating team:",e)}finally{e$(!1)}};if(en)return(0,t.jsx)("div",{className:"p-4",children:"Loading..."});if(!Z?.team_info)return(0,t.jsx)("div",{className:"p-4",children:"Team not found"});let{team_info:e0}=Z,e1=async(e,t)=>{await (0,s.copyToClipboard)(e)&&(ek(e=>({...e,[t]:!0})),setTimeout(()=>{ek(e=>({...e,[t]:!1}))},2e3))};return(0,t.jsxs)("div",{className:"p-4",children:[(0,t.jsx)("div",{className:"flex justify-between items-center mb-6",children:(0,t.jsxs)("div",{children:[(0,t.jsx)(_.Button,{type:"text",icon:(0,t.jsx)(c.ArrowLeftIcon,{className:"h-4 w-4"}),onClick:W,className:"mb-4",children:"Back to Teams"}),(0,t.jsx)(b.Title,{children:e0.team_alias}),(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(p.Text,{className:"text-gray-500 font-mono",children:e0.team_id}),(0,t.jsx)(_.Button,{type:"text",size:"small",icon:eC["team-id"]?(0,t.jsx)(N.CheckIcon,{size:12}):(0,t.jsx)(S.CopyIcon,{size:12}),onClick:()=>e1(e0.team_id,"team-id"),className:`left-2 z-10 transition-all duration-200 ${eC["team-id"]?"text-green-600 bg-green-50 border-green-200":"text-gray-500 hover:text-gray-700 hover:bg-gray-100"}`})]})]})}),(0,t.jsx)(C.Tabs,{defaultActiveKey:eH,className:"mb-4",items:[{key:er,label:eo[er],children:(0,t.jsxs)(h.Grid,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,t.jsxs)(g.Card,{children:[(0,t.jsx)(p.Text,{children:"Budget Status"}),(0,t.jsxs)("div",{className:"mt-2",children:[(0,t.jsxs)(b.Title,{children:["$",(0,s.formatNumberWithCommas)(e0.spend,4)]}),(0,t.jsxs)(p.Text,{children:["of ",null===e0.max_budget?"Unlimited":`$${(0,s.formatNumberWithCommas)(e0.max_budget,4)}`]}),e0.budget_duration&&(0,t.jsxs)(p.Text,{className:"text-gray-500",children:["Reset: ",e0.budget_duration]}),(0,t.jsx)("br",{}),e0.team_member_budget_table&&(0,t.jsxs)(p.Text,{className:"text-gray-500",children:["Team Member Budget: $",(0,s.formatNumberWithCommas)(e0.team_member_budget_table.max_budget,4)]})]})]}),(0,t.jsxs)(g.Card,{children:[(0,t.jsx)(p.Text,{children:"Rate Limits"}),(0,t.jsxs)("div",{className:"mt-2",children:[(0,t.jsxs)(p.Text,{children:["TPM: ",e0.tpm_limit||"Unlimited"]}),(0,t.jsxs)(p.Text,{children:["RPM: ",e0.rpm_limit||"Unlimited"]}),e0.max_parallel_requests&&(0,t.jsxs)(p.Text,{children:["Max Parallel Requests: ",e0.max_parallel_requests]})]})]}),(0,t.jsxs)(g.Card,{children:[(0,t.jsx)(p.Text,{children:"Models"}),(0,t.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:0===e0.models.length?(0,t.jsx)(u.Badge,{color:"red",children:"All proxy models"}):e0.models.map((e,r)=>(0,t.jsx)(u.Badge,{color:"red",children:e},r))})]}),(0,t.jsxs)(g.Card,{children:[(0,t.jsx)(p.Text,{className:"font-semibold text-gray-900",children:"Virtual Keys"}),(0,t.jsxs)("div",{className:"mt-2",children:[(0,t.jsxs)(p.Text,{children:["User Keys: ",Z.keys.filter(e=>e.user_id).length]}),(0,t.jsxs)(p.Text,{children:["Service Account Keys: ",Z.keys.filter(e=>!e.user_id).length]}),(0,t.jsxs)(p.Text,{className:"text-gray-500",children:["Total: ",Z.keys.length]})]})]}),(0,t.jsx)(R.default,{objectPermission:e0.object_permission,variant:"card",accessToken:G}),(0,t.jsxs)(g.Card,{children:[(0,t.jsx)(p.Text,{className:"font-semibold text-gray-900 mb-3",children:"Guardrails"}),e0.guardrails&&e0.guardrails.length>0?(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:e0.guardrails.map((e,r)=>(0,t.jsx)(u.Badge,{color:"blue",children:e},r))}):(0,t.jsx)(p.Text,{className:"text-gray-500",children:"No guardrails configured"}),e0.metadata?.disable_global_guardrails&&(0,t.jsx)("div",{className:"mt-3 pt-3 border-t border-gray-200",children:(0,t.jsx)(u.Badge,{color:"yellow",children:"Global Guardrails Disabled"})})]}),(0,t.jsxs)(g.Card,{children:[(0,t.jsx)(p.Text,{className:"font-semibold text-gray-900 mb-3",children:"Policies"}),e0.policies&&e0.policies.length>0?(0,t.jsx)("div",{className:"space-y-4",children:e0.policies.map((e,r)=>(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(u.Badge,{color:"purple",children:e}),eP&&(0,t.jsx)(p.Text,{className:"text-xs text-gray-400",children:"Loading guardrails..."})]}),!eP&&ez[e]&&ez[e].length>0&&(0,t.jsxs)("div",{className:"ml-4 pl-3 border-l-2 border-gray-200",children:[(0,t.jsx)(p.Text,{className:"text-xs text-gray-500 mb-1",children:"Resolved Guardrails:"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-1",children:ez[e].map((e,r)=>(0,t.jsx)(u.Badge,{color:"blue",size:"xs",children:e},r))})]})]},r))}):(0,t.jsx)(p.Text,{className:"text-gray-500",children:"No policies configured"})]}),(0,t.jsx)(L.default,{loggingConfigs:e0.metadata?.logging||[],disabledCallbacks:[],variant:"card"})]})},{key:ea,label:eo[ea],children:(0,t.jsx)(eT,{teamId:e,teamAlias:e0.team_alias,organization:eU})},{key:ei,label:eo[ei],children:(0,t.jsx)(eu,{teamData:Z,canEditTeam:eG,handleMemberDelete:e=>{eB(e),eF(!0)},setSelectedEditMember:eb,setIsEditMemberModalVisible:ep,setIsAddMemberModalVisible:ec})},{key:es,label:eo[es],children:(0,t.jsx)(et,{teamId:e,accessToken:G,canEditTeam:eG})},{key:el,label:eo[el],children:(0,t.jsxs)(g.Card,{className:"overflow-y-auto max-h-[65vh]",children:[(0,t.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,t.jsx)(b.Title,{children:"Team Settings"}),eG&&!e_&&(0,t.jsx)(_.Button,{icon:(0,t.jsx)(n.EditOutlined,{className:"h-4 w-4"}),onClick:()=>ef(!0),children:"Edit Settings"})]}),e_?(0,t.jsxs)(f.Form,{form:eg,onFinish:eZ,initialValues:{...e0,team_alias:e0.team_alias,models:e0.models,tpm_limit:e0.tpm_limit,rpm_limit:e0.rpm_limit,max_budget:e0.max_budget,soft_budget:e0.soft_budget,budget_duration:e0.budget_duration,team_member_tpm_limit:e0.team_member_budget_table?.tpm_limit,team_member_rpm_limit:e0.team_member_budget_table?.rpm_limit,team_member_budget:e0.team_member_budget_table?.max_budget,team_member_budget_duration:e0.team_member_budget_table?.budget_duration,guardrails:e0.metadata?.guardrails||[],policies:e0.policies||[],disable_global_guardrails:e0.metadata?.disable_global_guardrails||!1,soft_budget_alerting_emails:Array.isArray(e0.metadata?.soft_budget_alerting_emails)?e0.metadata.soft_budget_alerting_emails.join(", "):"",metadata:e0.metadata?JSON.stringify((({logging:e,secret_manager_settings:t,soft_budget_alerting_emails:r,...a})=>a)(e0.metadata),null,2):"",logging_settings:e0.metadata?.logging||[],secret_manager_settings:e0.metadata?.secret_manager_settings?JSON.stringify(e0.metadata.secret_manager_settings,null,2):"",organization_id:e0.organization_id,vector_stores:e0.object_permission?.vector_stores||[],mcp_servers:e0.object_permission?.mcp_servers||[],mcp_access_groups:e0.object_permission?.mcp_access_groups||[],mcp_servers_and_groups:{servers:e0.object_permission?.mcp_servers||[],accessGroups:e0.object_permission?.mcp_access_groups||[]},mcp_tool_permissions:e0.object_permission?.mcp_tool_permissions||{},agents_and_groups:{agents:e0.object_permission?.agents||[],accessGroups:e0.object_permission?.agent_access_groups||[]},access_group_ids:e0.access_group_ids||[]},layout:"vertical",children:[(0,t.jsx)(f.Form.Item,{label:"Team Name",name:"team_alias",rules:[{required:!0,message:"Please input a team name"}],children:(0,t.jsx)(y.Input,{type:""})}),(0,t.jsx)(f.Form.Item,{label:"Models",name:"models",rules:[{required:!0,message:"Please select at least one model"}],children:(0,t.jsx)(F.ModelSelect,{value:eg.getFieldValue("models")||[],onChange:e=>eg.setFieldValue("models",e),teamID:e,organizationID:Z?.team_info?.organization_id||void 0,options:{includeSpecialOptions:!0,includeUserModels:!Z?.team_info?.organization_id,showAllProxyModelsOverride:(0,o.isProxyAdminRole)(eW)&&!Z?.team_info?.organization_id},context:"team",dataTestId:"models-select"})}),(0,t.jsx)(f.Form.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,t.jsx)(V.default,{step:.01,precision:2,style:{width:"100%"}})}),(0,t.jsx)(f.Form.Item,{label:"Soft Budget (USD)",name:"soft_budget",children:(0,t.jsx)(V.default,{step:.01,precision:2,style:{width:"100%"}})}),(0,t.jsx)(f.Form.Item,{label:"Soft Budget Alerting Emails",name:"soft_budget_alerting_emails",tooltip:"Comma-separated email addresses to receive alerts when the soft budget is reached",children:(0,t.jsx)(y.Input,{placeholder:"example1@test.com, example2@test.com"})}),(0,t.jsx)(f.Form.Item,{label:"Team Member Budget (USD)",name:"team_member_budget",tooltip:"This is the individual budget for a user in the team.",children:(0,t.jsx)(V.default,{step:.01,precision:2,style:{width:"100%"}})}),(0,t.jsx)(f.Form.Item,{label:"Team Member Budget Duration",name:"team_member_budget_duration",children:(0,t.jsx)(O,{onChange:e=>eg.setFieldValue("team_member_budget_duration",e),value:eg.getFieldValue("team_member_budget_duration")})}),(0,t.jsx)(f.Form.Item,{label:"Team Member Key Duration (eg: 1d, 1mo)",name:"team_member_key_duration",tooltip:"Set a limit to the duration of a team member's key. Format: 30s (seconds), 30m (minutes), 30h (hours), 30d (days), 1mo (month)",children:(0,t.jsx)(x.TextInput,{placeholder:"e.g., 30d"})}),(0,t.jsx)(f.Form.Item,{label:"Team Member TPM Limit",name:"team_member_tpm_limit",tooltip:"Default tokens per minute limit for an individual team member. This limit applies to all requests the user makes within this team. Can be overridden per member.",children:(0,t.jsx)(V.default,{step:1,style:{width:"100%"},placeholder:"e.g., 1000"})}),(0,t.jsx)(f.Form.Item,{label:"Team Member RPM Limit",name:"team_member_rpm_limit",tooltip:"Default requests per minute limit for an individual team member. This limit applies to all requests the user makes within this team. Can be overridden per member.",children:(0,t.jsx)(V.default,{step:1,style:{width:"100%"},placeholder:"e.g., 100"})}),(0,t.jsx)(f.Form.Item,{label:"Reset Budget",name:"budget_duration",children:(0,t.jsxs)(v.Select,{placeholder:"n/a",children:[(0,t.jsx)(v.Select.Option,{value:"24h",children:"daily"}),(0,t.jsx)(v.Select.Option,{value:"7d",children:"weekly"}),(0,t.jsx)(v.Select.Option,{value:"30d",children:"monthly"})]})}),(0,t.jsx)(f.Form.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,t.jsx)(V.default,{step:1,style:{width:"100%"}})}),(0,t.jsx)(f.Form.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,t.jsx)(V.default,{step:1,style:{width:"100%"}})}),(0,t.jsx)(f.Form.Item,{label:(0,t.jsxs)("span",{children:["Guardrails"," ",(0,t.jsx)(k.Tooltip,{title:"Setup your first guardrail",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(d.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",help:"Select existing guardrails or enter new ones",children:(0,t.jsx)(v.Select,{mode:"tags",placeholder:"Select or enter guardrails",options:eN.map(e=>({value:e,label:e}))})}),(0,t.jsx)(f.Form.Item,{label:(0,t.jsxs)("span",{children:["Disable Global Guardrails",(0,t.jsx)(k.Tooltip,{title:"When enabled, this team will bypass any guardrails configured to run on every request (global guardrails)",children:(0,t.jsx)(d.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"disable_global_guardrails",valuePropName:"checked",help:"Bypass global guardrails for this team",children:(0,t.jsx)(w.Switch,{checkedChildren:"Yes",unCheckedChildren:"No"})}),(0,t.jsx)(f.Form.Item,{label:(0,t.jsxs)("span",{children:["Policies"," ",(0,t.jsx)(k.Tooltip,{title:"Apply policies to this team to control guardrails and other settings",children:(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/guardrail_policies",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,t.jsx)(d.InfoCircleOutlined,{style:{marginLeft:"4px"}})})})]}),name:"policies",help:"Select existing policies or enter new ones",children:(0,t.jsx)(v.Select,{mode:"tags",placeholder:"Select or enter policies",options:eI.map(e=>({value:e,label:e}))})}),(0,t.jsx)(f.Form.Item,{label:(0,t.jsxs)("span",{children:["Access Groups"," ",(0,t.jsx)(k.Tooltip,{title:"Assign access groups to this team. Access groups control which models, MCP servers, and agents this team can use",children:(0,t.jsx)(d.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"access_group_ids",children:(0,t.jsx)(I.default,{placeholder:"Select access groups (optional)"})}),(0,t.jsx)(f.Form.Item,{label:"Vector Stores",name:"vector_stores","aria-label":"Vector Stores",children:(0,t.jsx)($.default,{onChange:e=>eg.setFieldValue("vector_stores",e),value:eg.getFieldValue("vector_stores"),accessToken:G||"",placeholder:"Select vector stores"})}),(0,t.jsx)(f.Form.Item,{label:"Allowed Pass Through Routes",name:"allowed_passthrough_routes",children:(0,t.jsx)(P.default,{onChange:e=>eg.setFieldValue("allowed_passthrough_routes",e),value:eg.getFieldValue("allowed_passthrough_routes"),accessToken:G||"",placeholder:"Select pass through routes"})}),(0,t.jsx)(f.Form.Item,{label:"MCP Servers / Access Groups",name:"mcp_servers_and_groups",children:(0,t.jsx)(B.default,{onChange:e=>eg.setFieldValue("mcp_servers_and_groups",e),value:eg.getFieldValue("mcp_servers_and_groups"),accessToken:G||"",placeholder:"Select MCP servers or access groups (optional)"})}),(0,t.jsx)(f.Form.Item,{name:"mcp_tool_permissions",initialValue:{},hidden:!0,children:(0,t.jsx)(y.Input,{type:"hidden"})}),(0,t.jsx)(f.Form.Item,{noStyle:!0,shouldUpdate:(e,t)=>e.mcp_servers_and_groups!==t.mcp_servers_and_groups||e.mcp_tool_permissions!==t.mcp_tool_permissions,children:()=>(0,t.jsx)("div",{className:"mb-6",children:(0,t.jsx)(E.default,{accessToken:G||"",selectedServers:eg.getFieldValue("mcp_servers_and_groups")?.servers||[],toolPermissions:eg.getFieldValue("mcp_tool_permissions")||{},onChange:e=>eg.setFieldsValue({mcp_tool_permissions:e})})})}),(0,t.jsx)(f.Form.Item,{label:"Agents / Access Groups",name:"agents_and_groups",children:(0,t.jsx)(M.default,{onChange:e=>eg.setFieldValue("agents_and_groups",e),value:eg.getFieldValue("agents_and_groups"),accessToken:G||"",placeholder:"Select agents or access groups (optional)"})}),(0,t.jsx)(f.Form.Item,{label:"Organization ID",name:"organization_id",children:(0,t.jsx)(y.Input,{type:"",disabled:!0})}),(0,t.jsx)(f.Form.Item,{label:"Logging Settings",name:"logging_settings",children:(0,t.jsx)(U.default,{value:eg.getFieldValue("logging_settings"),onChange:e=>eg.setFieldValue("logging_settings",e)})}),(0,t.jsx)(f.Form.Item,{label:"Secret Manager Settings",name:"secret_manager_settings",help:X?"Enter secret manager configuration as a JSON object.":"Premium feature - Upgrade to manage secret manager settings.",rules:[{validator:async(e,t)=>{if(!t)return Promise.resolve();try{return JSON.parse(t),Promise.resolve()}catch(e){return Promise.reject(Error("Please enter valid JSON"))}}}],children:(0,t.jsx)(y.Input.TextArea,{rows:6,placeholder:'{"namespace": "admin", "mount": "secret", "path_prefix": "litellm"}',disabled:!X})}),(0,t.jsx)(f.Form.Item,{label:"Metadata",name:"metadata",children:(0,t.jsx)(y.Input.TextArea,{rows:10})}),(0,t.jsx)("div",{className:"sticky z-10 bg-white p-4 pr-0 border-t border-gray-200 bottom-[-1.5rem] inset-x-[-1.5rem]",children:(0,t.jsxs)("div",{className:"flex justify-end items-center gap-2",children:[(0,t.jsx)(_.Button,{onClick:()=>ef(!1),disabled:eV,children:"Cancel"}),(0,t.jsx)(_.Button,{icon:(0,t.jsx)(m.SaveOutlined,{className:"h-4 w-4"}),type:"primary",htmlType:"submit",loading:eV,children:"Save Changes"})]})})]}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(p.Text,{className:"font-medium",children:"Team Name"}),(0,t.jsx)("div",{children:e0.team_alias})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(p.Text,{className:"font-medium",children:"Team ID"}),(0,t.jsx)("div",{className:"font-mono",children:e0.team_id})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(p.Text,{className:"font-medium",children:"Created At"}),(0,t.jsx)("div",{children:new Date(e0.created_at).toLocaleString()})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(p.Text,{className:"font-medium",children:"Models"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:e0.models.map((e,r)=>(0,t.jsx)(u.Badge,{color:"red",children:e},r))})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(p.Text,{className:"font-medium",children:"Rate Limits"}),(0,t.jsxs)("div",{children:["TPM: ",e0.tpm_limit||"Unlimited"]}),(0,t.jsxs)("div",{children:["RPM: ",e0.rpm_limit||"Unlimited"]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(p.Text,{className:"font-medium",children:"Team Budget"}),(0,t.jsxs)("div",{children:["Max Budget:"," ",null!==e0.max_budget?`$${(0,s.formatNumberWithCommas)(e0.max_budget,4)}`:"No Limit"]}),(0,t.jsxs)("div",{children:["Soft Budget:"," ",null!==e0.soft_budget&&void 0!==e0.soft_budget?`$${(0,s.formatNumberWithCommas)(e0.soft_budget,4)}`:"No Limit"]}),(0,t.jsxs)("div",{children:["Budget Reset: ",e0.budget_duration||"Never"]}),e0.metadata?.soft_budget_alerting_emails&&Array.isArray(e0.metadata.soft_budget_alerting_emails)&&e0.metadata.soft_budget_alerting_emails.length>0&&(0,t.jsxs)("div",{children:["Soft Budget Alerting Emails: ",e0.metadata.soft_budget_alerting_emails.join(", ")]})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)(p.Text,{className:"font-medium",children:["Team Member Settings"," ",(0,t.jsx)(k.Tooltip,{title:"These are limits on individual team members",children:(0,t.jsx)(d.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),(0,t.jsxs)("div",{children:["Max Budget: ",e0.team_member_budget_table?.max_budget||"No Limit"]}),(0,t.jsxs)("div",{children:["Budget Duration: ",e0.team_member_budget_table?.budget_duration||"No Limit"]}),(0,t.jsxs)("div",{children:["Key Duration: ",e0.metadata?.team_member_key_duration||"No Limit"]}),(0,t.jsxs)("div",{children:["TPM Limit: ",e0.team_member_budget_table?.tpm_limit||"No Limit"]}),(0,t.jsxs)("div",{children:["RPM Limit: ",e0.team_member_budget_table?.rpm_limit||"No Limit"]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(p.Text,{className:"font-medium",children:"Organization ID"}),(0,t.jsx)("div",{children:e0.organization_id})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(p.Text,{className:"font-medium",children:"Status"}),(0,t.jsx)(u.Badge,{color:e0.blocked?"red":"green",children:e0.blocked?"Blocked":"Active"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(p.Text,{className:"font-medium",children:"Disable Global Guardrails"}),(0,t.jsx)("div",{children:e0.metadata?.disable_global_guardrails===!0?(0,t.jsx)(u.Badge,{color:"yellow",children:"Enabled - Global guardrails bypassed"}):(0,t.jsx)(u.Badge,{color:"green",children:"Disabled - Global guardrails active"})})]}),(0,t.jsx)(R.default,{objectPermission:e0.object_permission,variant:"inline",className:"pt-4 border-t border-gray-200",accessToken:G}),(0,t.jsx)(L.default,{loggingConfigs:e0.metadata?.logging||[],disabledCallbacks:[],variant:"inline",className:"pt-4 border-t border-gray-200"}),e0.metadata?.secret_manager_settings&&(0,t.jsxs)("div",{className:"pt-4 border-t border-gray-200",children:[(0,t.jsx)(p.Text,{className:"font-medium",children:"Secret Manager Settings"}),(0,t.jsx)("pre",{className:"mt-2 bg-gray-50 p-3 rounded text-xs overflow-x-auto",children:JSON.stringify(e0.metadata.secret_manager_settings,null,2)})]})]})]})}].filter(e=>eq.includes(e.key))}),(0,t.jsx)(K.default,{visible:eh,onCancel:()=>ep(!1),onSubmit:eX,initialData:ex,mode:"edit",config:{title:"Edit Member",showEmail:!0,showUserId:!0,roleOptions:[{label:"Admin",value:"admin"},{label:"User",value:"user"}],additionalFields:[{name:"max_budget_in_team",label:(0,t.jsxs)("span",{children:["Team Member Budget (USD)"," ",(0,t.jsx)(k.Tooltip,{title:"Maximum amount in USD this member can spend within this team. This is separate from any global user budget limits",children:(0,t.jsx)(d.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),type:"numerical",step:.01,min:0,placeholder:"Budget limit for this member within this team"},{name:"tpm_limit",label:(0,t.jsxs)("span",{children:["Team Member TPM Limit"," ",(0,t.jsx)(k.Tooltip,{title:"Maximum tokens per minute this member can use within this team. This is separate from any global user TPM limit",children:(0,t.jsx)(d.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),type:"numerical",step:1,min:0,placeholder:"Tokens per minute limit for this member in this team"},{name:"rpm_limit",label:(0,t.jsxs)("span",{children:["Team Member RPM Limit"," ",(0,t.jsx)(k.Tooltip,{title:"Maximum requests per minute this member can make within this team. This is separate from any global user RPM limit",children:(0,t.jsx)(d.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),type:"numerical",step:1,min:0,placeholder:"Requests per minute limit for this member in this team"}]}}),(0,t.jsx)(a.default,{isVisible:em,onCancel:()=>ec(!1),onSubmit:eY,accessToken:G}),(0,t.jsx)(z.default,{isOpen:eE,title:"Delete Team Member",alertMessage:"Removing team members will also delete any keys created by or created for this member.",message:"Are you sure you want to remove this member from the team? This action cannot be undone.",resourceInformationTitle:"Team Member Information",resourceInformation:[{label:"User ID",value:eL?.user_id,code:!0},{label:"Email",value:eL?.user_email},{label:"Role",value:eL?.role}],onCancel:()=>{eF(!1),eB(null)},onOk:eQ,confirmLoading:eA})]})}],56567)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/5c823f037243a06f.js b/litellm/proxy/_experimental/out/_next/static/chunks/5c823f037243a06f.js new file mode 100644 index 00000000000..645a51ff92c --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/5c823f037243a06f.js @@ -0,0 +1 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,355619,e=>{"use strict";var s=e.i(764205);let t=async(e,t,l)=>{try{if(null===e||null===t)return;if(null!==l){let a=(await (0,s.modelAvailableCall)(l,e,t,!0,null,!0)).data.map(e=>e.id),r=[],i=[];return a.forEach(e=>{e.endsWith("/*")?r.push(e):i.push(e)}),[...r,...i]}}catch(e){console.error("Error fetching user models:",e)}};e.s(["fetchAvailableModelsForTeamOrKey",0,t,"getModelDisplayName",0,e=>{if("all-proxy-models"===e)return"All Proxy Models";if(e.endsWith("/*")){let s=e.replace("/*","");return`All ${s} models`}return e},"unfurlWildcardModelsInList",0,(e,s)=>{let t=[],l=[];return console.log("teamModels",e),console.log("allModels",s),e.forEach(e=>{if(e.endsWith("/*")){let a=e.replace("/*",""),r=s.filter(e=>e.startsWith(a+"/"));l.push(...r),t.push(e)}else l.push(e)}),[...t,...l].filter((e,s,t)=>t.indexOf(e)===s)}])},213205,e=>{"use strict";e.i(247167);var s=e.i(931067),t=e.i(271645);let l={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M678.3 642.4c24.2-13 51.9-20.4 81.4-20.4h.1c3 0 4.4-3.6 2.2-5.6a371.67 371.67 0 00-103.7-65.8c-.4-.2-.8-.3-1.2-.5C719.2 505 759.6 431.7 759.6 349c0-137-110.8-248-247.5-248S264.7 212 264.7 349c0 82.7 40.4 156 102.6 201.1-.4.2-.8.3-1.2.5-44.7 18.9-84.8 46-119.3 80.6a373.42 373.42 0 00-80.4 119.5A373.6 373.6 0 00137 888.8a8 8 0 008 8.2h59.9c4.3 0 7.9-3.5 8-7.8 2-77.2 32.9-149.5 87.6-204.3C357 628.2 432.2 597 512.2 597c56.7 0 111.1 15.7 158 45.1a8.1 8.1 0 008.1.3zM512.2 521c-45.8 0-88.9-17.9-121.4-50.4A171.2 171.2 0 01340.5 349c0-45.9 17.9-89.1 50.3-121.6S466.3 177 512.2 177s88.9 17.9 121.4 50.4A171.2 171.2 0 01683.9 349c0 45.9-17.9 89.1-50.3 121.6C601.1 503.1 558 521 512.2 521zM880 759h-84v-84c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v84h-84c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h84v84c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8v-84h84c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8z"}}]},name:"user-add",theme:"outlined"};var a=e.i(9583),r=t.forwardRef(function(e,r){return t.createElement(a.default,(0,s.default)({},e,{ref:r,icon:l}))});e.s(["UserAddOutlined",0,r],213205)},860585,e=>{"use strict";var s=e.i(843476),t=e.i(199133);let{Option:l}=t.Select;e.s(["default",0,({value:e,onChange:a,className:r="",style:i={}})=>(0,s.jsxs)(t.Select,{style:{width:"100%",...i},value:e||void 0,onChange:a,className:r,placeholder:"n/a",allowClear:!0,children:[(0,s.jsx)(l,{value:"24h",children:"daily"}),(0,s.jsx)(l,{value:"7d",children:"weekly"}),(0,s.jsx)(l,{value:"30d",children:"monthly"})]}),"getBudgetDurationLabel",0,e=>e?({"24h":"daily","7d":"weekly","30d":"monthly"})[e]||e:"Not set"])},663435,e=>{"use strict";var s=e.i(843476),t=e.i(199133);e.s(["default",0,({teams:e,value:l,onChange:a,disabled:r,loading:i})=>(0,s.jsx)(t.Select,{showSearch:!0,placeholder:"Search or select a team",value:l,onChange:a,disabled:r,loading:i,allowClear:!0,filterOption:(s,t)=>{if(!t)return!1;let l=e?.find(e=>e.team_id===t.key);if(!l)return!1;let a=s.toLowerCase().trim(),r=(l.team_alias||"").toLowerCase(),i=(l.team_id||"").toLowerCase();return r.includes(a)||i.includes(a)},optionFilterProp:"children",children:e?.map(e=>(0,s.jsxs)(t.Select.Option,{value:e.team_id,children:[(0,s.jsx)("span",{className:"font-medium",children:e.team_alias})," ",(0,s.jsxs)("span",{className:"text-gray-500",children:["(",e.team_id,")"]})]},e.team_id))})])},285027,e=>{"use strict";e.i(247167);var s=e.i(931067),t=e.i(271645);let l={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"};var a=e.i(9583),r=t.forwardRef(function(e,r){return t.createElement(a.default,(0,s.default)({},e,{ref:r,icon:l}))});e.s(["WarningOutlined",0,r],285027)},447082,e=>{"use strict";var s=e.i(843476),t=e.i(271645),l=e.i(599724),a=e.i(464571),r=e.i(212931),i=e.i(291542),n=e.i(515831),d=e.i(898586),o=e.i(519756),c=e.i(737434),m=e.i(285027),u=e.i(993914),x=e.i(955135);e.i(247167);var h=e.i(931067);let p={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"};var f=e.i(9583),g=t.forwardRef(function(e,s){return t.createElement(f.default,(0,h.default)({},e,{ref:s,icon:p}))}),j=e.i(764205),y=e.i(59935),v=e.i(220508),b=e.i(964306);let w=t.forwardRef(function(e,s){return t.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:s},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"}))});var N=e.i(237016),_=e.i(727749);e.s(["default",0,({accessToken:e,teams:h,possibleUIRoles:p,onUsersCreated:f})=>{let[C,S]=(0,t.useState)(!1),[k,I]=(0,t.useState)([]),[T,U]=(0,t.useState)(!1),[V,O]=(0,t.useState)(null),[B,L]=(0,t.useState)(null),[M,F]=(0,t.useState)(null),[z,E]=(0,t.useState)(null),[P,A]=(0,t.useState)(null),[R,D]=(0,t.useState)("http://localhost:4000");(0,t.useEffect)(()=>{(async()=>{try{let s=await (0,j.getProxyUISettings)(e);A(s)}catch(e){console.error("Error fetching UI settings:",e)}})(),D(new URL("/",window.location.href).toString())},[e]);let $=async()=>{U(!0);let s=k.map(e=>({...e,status:"pending"}));I(s);let t=!1;for(let l=0;le.trim()).filter(Boolean),0===s.teams.length&&delete s.teams),a.models&&"string"==typeof a.models&&""!==a.models.trim()&&(s.models=a.models.split(",").map(e=>e.trim()).filter(Boolean),0===s.models.length&&delete s.models),a.max_budget&&""!==a.max_budget.toString().trim()){let e=parseFloat(a.max_budget.toString());!isNaN(e)&&e>0&&(s.max_budget=e)}a.budget_duration&&""!==a.budget_duration.trim()&&(s.budget_duration=a.budget_duration.trim()),a.metadata&&"string"==typeof a.metadata&&""!==a.metadata.trim()&&(s.metadata=a.metadata.trim()),console.log("Sending user data:",s);let r=await (0,j.userCreateCall)(e,null,s);if(console.log("Full response:",r),r&&(r.key||r.user_id)){t=!0,console.log("Success case triggered");let s=r.data?.user_id||r.user_id;try{if(P?.SSO_ENABLED){let e=new URL("/ui",R).toString();I(s=>s.map((s,t)=>t===l?{...s,status:"success",key:r.key||r.user_id,invitation_link:e}:s))}else{let t=await (0,j.invitationCreateCall)(e,s),a=new URL(`/ui?invitation_id=${t.id}`,R).toString();I(e=>e.map((e,s)=>s===l?{...e,status:"success",key:r.key||r.user_id,invitation_link:a}:e))}}catch(e){console.error("Error creating invitation:",e),I(e=>e.map((e,s)=>s===l?{...e,status:"success",key:r.key||r.user_id,error:"User created but failed to generate invitation link"}:e))}}else{console.log("Error case triggered");let e=r?.error||"Failed to create user";console.log("Error message:",e),I(s=>s.map((s,t)=>t===l?{...s,status:"failed",error:e}:s))}}catch(s){console.error("Caught error:",s);let e=s?.response?.data?.error||s?.message||String(s);I(s=>s.map((s,t)=>t===l?{...s,status:"failed",error:e}:s))}}U(!1),t&&f&&f()},W=[{title:"Row",dataIndex:"rowNumber",key:"rowNumber",width:80},{title:"Email",dataIndex:"user_email",key:"user_email"},{title:"Role",dataIndex:"user_role",key:"user_role"},{title:"Teams",dataIndex:"teams",key:"teams"},{title:"Budget",dataIndex:"max_budget",key:"max_budget"},{title:"Status",key:"status",render:(e,t)=>t.isValid?t.status&&"pending"!==t.status?"success"===t.status?(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(v.CheckCircleIcon,{className:"h-5 w-5 text-green-500 mr-2"}),(0,s.jsx)("span",{className:"text-green-500",children:"Success"})]}),t.invitation_link&&(0,s.jsx)("div",{className:"mt-1",children:(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)("span",{className:"text-xs text-gray-500 truncate max-w-[150px]",children:t.invitation_link}),(0,s.jsx)(N.CopyToClipboard,{text:t.invitation_link,onCopy:()=>_.default.success("Invitation link copied!"),children:(0,s.jsx)("button",{className:"ml-1 text-blue-500 text-xs hover:text-blue-700",children:"Copy"})})]})})]}):(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(b.XCircleIcon,{className:"h-5 w-5 text-red-500 mr-2"}),(0,s.jsx)("span",{className:"text-red-500",children:"Failed"})]}),t.error&&(0,s.jsx)("span",{className:"text-sm text-red-500 ml-7",children:JSON.stringify(t.error)})]}):(0,s.jsx)("span",{className:"text-gray-500",children:"Pending"}):(0,s.jsxs)("div",{children:[(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(b.XCircleIcon,{className:"h-5 w-5 text-red-500 mr-2"}),(0,s.jsx)("span",{className:"text-red-500",children:"Invalid"})]}),t.error&&(0,s.jsx)("span",{className:"text-sm text-red-500 ml-7",children:t.error})]})}];return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(a.Button,{type:"primary",className:"mb-0",onClick:()=>S(!0),children:"+ Bulk Invite Users"}),(0,s.jsx)(r.Modal,{title:"Bulk Invite Users",open:C,width:800,onCancel:()=>S(!1),bodyStyle:{maxHeight:"70vh",overflow:"auto"},footer:null,children:(0,s.jsx)("div",{className:"flex flex-col",children:0===k.length?(0,s.jsxs)("div",{className:"mb-6",children:[(0,s.jsxs)("div",{className:"flex items-center mb-4",children:[(0,s.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"1"}),(0,s.jsx)("h3",{className:"text-lg font-medium",children:"Download and fill the template"})]}),(0,s.jsxs)("div",{className:"ml-11 mb-6",children:[(0,s.jsx)("p",{className:"mb-4",children:"Add multiple users at once by following these steps:"}),(0,s.jsxs)("ol",{className:"list-decimal list-inside space-y-2 ml-2 mb-4",children:[(0,s.jsx)("li",{children:"Download our CSV template"}),(0,s.jsx)("li",{children:"Add your users' information to the spreadsheet"}),(0,s.jsx)("li",{children:"Save the file and upload it here"}),(0,s.jsx)("li",{children:"After creation, download the results file containing the Virtual Keys for each user"})]}),(0,s.jsxs)("div",{className:"bg-gray-50 p-4 rounded-md border border-gray-200 mb-4",children:[(0,s.jsx)("h4",{className:"font-medium mb-2",children:"Template Column Names"}),(0,s.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-red-500 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"user_email"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:"User's email address (required)"})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-red-500 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"user_role"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'User\'s role (one of: "proxy_admin", "proxy_admin_viewer", "internal_user", "internal_user_viewer")'})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"teams"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'Comma-separated team IDs (e.g., "team-1,team-2")'})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"max_budget"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'Maximum budget as a number (e.g., "100")'})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"budget_duration"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'Budget reset period (e.g., "30d", "1mo")'})]})]}),(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,s.jsxs)("div",{children:[(0,s.jsx)("p",{className:"font-medium",children:"models"}),(0,s.jsx)("p",{className:"text-sm text-gray-600",children:'Comma-separated allowed models (e.g., "gpt-3.5-turbo,gpt-4")'})]})]})]})]}),(0,s.jsx)(a.Button,{type:"primary",size:"large",className:"w-full md:w-auto",icon:(0,s.jsx)(c.DownloadOutlined,{}),children:"Download CSV Template"})]}),(0,s.jsxs)("div",{className:"flex items-center mb-4",children:[(0,s.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"2"}),(0,s.jsx)("h3",{className:"text-lg font-medium",children:"Upload your completed CSV"})]}),(0,s.jsxs)("div",{className:"ml-11",children:[z?(0,s.jsxs)("div",{className:`mb-4 p-4 rounded-md border ${M?"bg-red-50 border-red-200":"bg-blue-50 border-blue-200"}`,children:[(0,s.jsxs)("div",{className:"flex items-center justify-between",children:[(0,s.jsxs)("div",{className:"flex items-center",children:[M?(0,s.jsx)(g,{className:"text-red-500 text-xl mr-3"}):(0,s.jsx)(u.FileTextOutlined,{className:"text-blue-500 text-xl mr-3"}),(0,s.jsxs)("div",{children:[(0,s.jsx)(d.Typography.Text,{strong:!0,className:M?"text-red-800":"text-blue-800",children:z.name}),(0,s.jsxs)(d.Typography.Text,{className:`block text-xs ${M?"text-red-600":"text-blue-600"}`,children:[(z.size/1024).toFixed(1)," KB • ",new Date().toLocaleDateString()]})]})]}),(0,s.jsx)(a.Button,{size:"small",onClick:()=>{E(null),I([]),O(null),L(null),F(null)},className:"flex items-center",icon:(0,s.jsx)(x.DeleteOutlined,{}),children:"Remove"})]}),M?(0,s.jsxs)("div",{className:"mt-3 text-red-600 text-sm flex items-start",children:[(0,s.jsx)(m.WarningOutlined,{className:"mr-2 mt-0.5"}),(0,s.jsx)("span",{children:M})]}):!B&&(0,s.jsxs)("div",{className:"mt-3 flex items-center",children:[(0,s.jsx)("div",{className:"w-full bg-gray-200 rounded-full h-1.5",children:(0,s.jsx)("div",{className:"bg-blue-500 h-1.5 rounded-full w-full animate-pulse"})}),(0,s.jsx)("span",{className:"ml-2 text-xs text-blue-600",children:"Processing..."})]})]}):(0,s.jsx)(n.Upload,{beforeUpload:e=>((O(null),L(null),F(null),E(e),"text/csv"===e.type||e.name.endsWith(".csv"))?e.size>5242880?F(`File is too large (${(e.size/1048576).toFixed(1)} MB). Please upload a CSV file smaller than 5MB.`):y.default.parse(e,{complete:e=>{if(!e.data||0===e.data.length){L("The CSV file appears to be empty. Please upload a file with data."),I([]);return}if(1===e.data.length){L("The CSV file only contains headers but no user data. Please add user data to your CSV."),I([]);return}let s=e.data[0];if(0===s.length||1===s.length&&""===s[0]){L("The CSV file doesn't contain any column headers. Please make sure your CSV has headers."),I([]);return}let t=["user_email","user_role"].filter(e=>!s.includes(e));if(t.length>0){L(`Your CSV is missing these required columns: ${t.join(", ")}. Please add these columns to your CSV file.`),I([]);return}try{let t=e.data.slice(1).map((e,t)=>{if(0===e.length||1===e.length&&""===e[0])return null;if(e.length=parseFloat(l.max_budget.toString())&&a.push("Max budget must be greater than 0")),l.budget_duration&&!l.budget_duration.match(/^\d+[dhmwy]$|^\d+mo$/)&&a.push(`Invalid budget duration format "${l.budget_duration}". Use format like "30d", "1mo", "2w", "6h"`),l.teams&&"string"==typeof l.teams&&h&&h.length>0){let e=h.map(e=>e.team_id),s=l.teams.split(",").map(e=>e.trim()).filter(s=>!e.includes(s));s.length>0&&a.push(`Unknown team(s): ${s.join(", ")}`)}return a.length>0&&(l.isValid=!1,l.error=a.join(", ")),l}).filter(Boolean),l=t.filter(e=>e.isValid);I(t),0===t.length?L("No valid data rows found in the CSV file. Please check your file format."):0===l.length?O("No valid users found in the CSV. Please check the errors below and fix your CSV file."):l.length{O(`Failed to parse CSV file: ${e.message}`),I([])},header:!1}):(F(`Invalid file type: ${e.name}. Please upload a CSV file (.csv extension).`),_.default.fromBackend("Invalid file type. Please upload a CSV file.")),!1),accept:".csv",maxCount:1,showUploadList:!1,children:(0,s.jsxs)("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-blue-500 transition-colors cursor-pointer",children:[(0,s.jsx)(o.UploadOutlined,{className:"text-3xl text-gray-400 mb-2"}),(0,s.jsx)("p",{className:"mb-1",children:"Drag and drop your CSV file here"}),(0,s.jsx)("p",{className:"text-sm text-gray-500 mb-3",children:"or"}),(0,s.jsx)(a.Button,{size:"small",children:"Browse files"}),(0,s.jsx)("p",{className:"text-xs text-gray-500 mt-4",children:"Only CSV files (.csv) are supported"})]})}),B&&(0,s.jsx)("div",{className:"mb-4 p-4 bg-yellow-50 border border-yellow-200 rounded-md",children:(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)(w,{className:"h-5 w-5 text-yellow-500 mr-2 mt-0.5"}),(0,s.jsxs)("div",{children:[(0,s.jsx)(d.Typography.Text,{strong:!0,className:"text-yellow-800",children:"CSV Structure Error"}),(0,s.jsx)(d.Typography.Paragraph,{className:"text-yellow-700 mt-1 mb-0",children:B}),(0,s.jsx)(d.Typography.Paragraph,{className:"text-yellow-700 mt-2 mb-0",children:"Please download our template and ensure your CSV follows the required format."})]})]})})]})]}):(0,s.jsxs)("div",{className:"mb-6",children:[(0,s.jsxs)("div",{className:"flex items-center mb-4",children:[(0,s.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"3"}),(0,s.jsx)("h3",{className:"text-lg font-medium",children:k.some(e=>"success"===e.status||"failed"===e.status)?"User Creation Results":"Review and create users"})]}),V&&(0,s.jsx)("div",{className:"ml-11 mb-4 p-4 bg-red-50 border border-red-200 rounded-md",children:(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)(m.WarningOutlined,{className:"text-red-500 mr-2 mt-1"}),(0,s.jsxs)("div",{children:[(0,s.jsx)(l.Text,{className:"text-red-600 font-medium",children:V}),k.some(e=>!e.isValid)&&(0,s.jsxs)("ul",{className:"mt-2 list-disc list-inside text-red-600 text-sm",children:[(0,s.jsx)("li",{children:"Check the table below for specific errors in each row"}),(0,s.jsx)("li",{children:"Common issues include invalid email formats, missing required fields, or incorrect role values"}),(0,s.jsx)("li",{children:"Fix these issues in your CSV file and upload again"})]})]})]})}),(0,s.jsxs)("div",{className:"ml-11",children:[(0,s.jsxs)("div",{className:"flex justify-between items-center mb-3",children:[(0,s.jsx)("div",{className:"flex items-center",children:k.some(e=>"success"===e.status||"failed"===e.status)?(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(l.Text,{className:"text-lg font-medium mr-3",children:"Creation Summary"}),(0,s.jsxs)(l.Text,{className:"text-sm bg-green-100 text-green-800 px-2 py-1 rounded mr-2",children:[k.filter(e=>"success"===e.status).length," Successful"]}),k.some(e=>"failed"===e.status)&&(0,s.jsxs)(l.Text,{className:"text-sm bg-red-100 text-red-800 px-2 py-1 rounded",children:[k.filter(e=>"failed"===e.status).length," Failed"]})]}):(0,s.jsxs)("div",{className:"flex items-center",children:[(0,s.jsx)(l.Text,{className:"text-lg font-medium mr-3",children:"User Preview"}),(0,s.jsxs)(l.Text,{className:"text-sm bg-blue-100 text-blue-800 px-2 py-1 rounded",children:[k.filter(e=>e.isValid).length," of ",k.length," users valid"]})]})}),!k.some(e=>"success"===e.status||"failed"===e.status)&&(0,s.jsxs)("div",{className:"flex space-x-3",children:[(0,s.jsx)(a.Button,{onClick:()=>{I([]),O(null)},children:"Back"}),(0,s.jsx)(a.Button,{type:"primary",onClick:$,disabled:0===k.filter(e=>e.isValid).length||T,children:T?"Creating...":`Create ${k.filter(e=>e.isValid).length} Users`})]})]}),k.some(e=>"success"===e.status)&&(0,s.jsx)("div",{className:"mb-4 p-4 bg-blue-50 border border-blue-200 rounded-md",children:(0,s.jsxs)("div",{className:"flex items-start",children:[(0,s.jsx)("div",{className:"mr-3 mt-1",children:(0,s.jsx)(v.CheckCircleIcon,{className:"h-5 w-5 text-blue-500"})}),(0,s.jsxs)("div",{children:[(0,s.jsx)(l.Text,{className:"font-medium text-blue-800",children:"User creation complete"}),(0,s.jsxs)(l.Text,{className:"block text-sm text-blue-700 mt-1",children:[(0,s.jsx)("span",{className:"font-medium",children:"Next step:"})," Download the credentials file containing Virtual Keys and invitation links. Users will need these Virtual Keys to make LLM requests through LiteLLM."]})]})]})}),(0,s.jsx)(i.Table,{dataSource:k,columns:W,size:"small",pagination:{pageSize:5},scroll:{y:300},rowClassName:e=>e.isValid?"":"bg-red-50"}),!k.some(e=>"success"===e.status||"failed"===e.status)&&(0,s.jsxs)("div",{className:"flex justify-end mt-4",children:[(0,s.jsx)(a.Button,{onClick:()=>{I([]),O(null)},className:"mr-3",children:"Back"}),(0,s.jsx)(a.Button,{type:"primary",onClick:$,disabled:0===k.filter(e=>e.isValid).length||T,children:T?"Creating...":`Create ${k.filter(e=>e.isValid).length} Users`})]}),k.some(e=>"success"===e.status||"failed"===e.status)&&(0,s.jsxs)("div",{className:"flex justify-end mt-4",children:[(0,s.jsx)(a.Button,{onClick:()=>{I([]),O(null)},className:"mr-3",children:"Start New Bulk Import"}),(0,s.jsx)(a.Button,{type:"primary",onClick:()=>{let e=k.map(e=>({user_email:e.user_email,user_role:e.user_role,status:e.status,key:e.key||"",invitation_link:e.invitation_link||"",error:e.error||""})),s=new Blob([y.default.unparse(e)],{type:"text/csv"}),t=window.URL.createObjectURL(s),l=document.createElement("a");l.href=t,l.download="bulk_users_results.csv",document.body.appendChild(l),l.click(),document.body.removeChild(l),window.URL.revokeObjectURL(t)},icon:(0,s.jsx)(c.DownloadOutlined,{}),children:"Download User Credentials"})]})]})]})})})]})}],447082)},371455,172372,e=>{"use strict";var s=e.i(843476),t=e.i(827252),l=e.i(213205),a=e.i(912598),r=e.i(109799),i=e.i(677667),n=e.i(130643),d=e.i(898667),o=e.i(35983),c=e.i(779241),m=e.i(560445),u=e.i(464571),x=e.i(808613),h=e.i(311451),p=e.i(212931),f=e.i(199133),g=e.i(770914),j=e.i(592968),y=e.i(898586),v=e.i(271645),b=e.i(447082),w=e.i(663435),N=e.i(355619),_=e.i(727749),C=e.i(764205),S=e.i(237016),k=e.i(599724);function I({isInvitationLinkModalVisible:e,setIsInvitationLinkModalVisible:t,baseUrl:l,invitationLinkData:a,modalType:r="invitation"}){let{Title:i,Paragraph:n}=y.Typography,d=()=>{if(!l)return"";let e=new URL(l).pathname,s=e&&"/"!==e?`${e}/ui`:"ui";if(a?.has_user_setup_sso)return new URL(s,l).toString();let t=`${s}?invitation_id=${a?.id}`;return"resetPassword"===r&&(t+="&action=reset_password"),new URL(t,l).toString()};return(0,s.jsxs)(p.Modal,{title:"invitation"===r?"Invitation Link":"Reset Password Link",open:e,width:800,footer:null,onOk:()=>{t(!1)},onCancel:()=>{t(!1)},children:[(0,s.jsx)(n,{children:"invitation"===r?"Copy and send the generated link to onboard this user to the proxy.":"Copy and send the generated link to the user to reset their password."}),(0,s.jsxs)("div",{className:"flex justify-between pt-5 pb-2",children:[(0,s.jsx)(k.Text,{className:"text-base",children:"User ID"}),(0,s.jsx)(k.Text,{children:a?.user_id})]}),(0,s.jsxs)("div",{className:"flex justify-between pt-5 pb-2",children:[(0,s.jsx)(k.Text,{children:"invitation"===r?"Invitation Link":"Reset Password Link"}),(0,s.jsx)(k.Text,{children:(0,s.jsx)(k.Text,{children:d()})})]}),(0,s.jsx)("div",{className:"flex justify-end mt-5",children:(0,s.jsx)(S.CopyToClipboard,{text:d(),onCopy:()=>_.default.success("Copied!"),children:(0,s.jsx)(u.Button,{type:"primary",children:"invitation"===r?"Copy invitation link":"Copy password reset link"})})})]})}e.s(["default",()=>I],172372);let{Option:T}=f.Select,{Text:U,Link:V,Title:O}=y.Typography;e.s(["CreateUserButton",0,({userID:e,accessToken:y,teams:S,possibleUIRoles:k,onUserCreated:O,isEmbedded:B=!1})=>{let L=(0,a.useQueryClient)(),[M,F]=(0,v.useState)(null),[z]=x.Form.useForm(),[E,P]=(0,v.useState)(!1),[A,R]=(0,v.useState)(!1),[D,$]=(0,v.useState)([]),[W,K]=(0,v.useState)(!1),[q,H]=(0,v.useState)(null),[G,J]=(0,v.useState)(null),{data:Q=[]}=(0,r.useOrganizations)(),X=(0,v.useMemo)(()=>{let e=Q.flatMap(e=>e.teams||[]);return e.length>0?e:S||[]},[Q,S]);(0,v.useEffect)(()=>{let s=async()=>{try{let s=await (0,C.modelAvailableCall)(y,e,"any"),t=[];for(let e=0;e{try{_.default.info("Making API Call"),B||P(!0),s.models&&0!==s.models.length||"proxy_admin"===s.user_role||(s.models=["no-default-models"]),s.organization_ids&&(s.organizations=s.organization_ids,delete s.organization_ids);let t=await (0,C.userCreateCall)(y,null,s);await L.invalidateQueries({queryKey:["userList"]}),R(!0);let l=t.data?.user_id||t.user_id;if(O&&B){O(l),z.resetFields();return}if(M?.SSO_ENABLED){let s={id:"u">typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){let s=16*Math.random()|0;return("x"==e?s:3&s|8).toString(16)}),user_id:l,is_accepted:!1,accepted_at:null,expires_at:new Date(Date.now()+6048e5),created_at:new Date,created_by:e,updated_at:new Date,updated_by:e,has_user_setup_sso:!0};H(s),K(!0)}else(0,C.invitationCreateCall)(y,l).then(e=>{e.has_user_setup_sso=!1,H(e),K(!0)});_.default.success("API user Created"),z.resetFields(),localStorage.removeItem("userData"+e)}catch(s){let e=s.response?.data?.detail||s?.message||"Error creating the user";_.default.fromBackend(e),console.error("Error creating the user:",s)}};return B?(0,s.jsxs)(x.Form,{form:z,onFinish:Y,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,s.jsx)(m.Alert,{message:"Email invitations",description:(0,s.jsxs)(s.Fragment,{children:["New users receive an email invite only when an email integration (SMTP, Resend, or SendGrid) is configured."," ",(0,s.jsx)(V,{href:"https://docs.litellm.ai/docs/proxy/email",target:"_blank",children:"Learn how to set up email notifications"})]}),type:"info",showIcon:!0,className:"mb-4"}),(0,s.jsx)(x.Form.Item,{label:"User Email",name:"user_email",children:(0,s.jsx)(c.TextInput,{placeholder:""})}),(0,s.jsx)(x.Form.Item,{label:"User Role",name:"user_role",children:(0,s.jsx)(f.Select,{children:k&&Object.entries(k).map(([e,{ui_label:t,description:l}])=>(0,s.jsx)(o.SelectItem,{value:e,title:t,children:(0,s.jsxs)("div",{className:"flex",children:[t," ",(0,s.jsx)(U,{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:l})]})},e))})}),(0,s.jsx)(x.Form.Item,{label:"Team",name:"team_id",children:(0,s.jsx)(f.Select,{placeholder:"Select Team",style:{width:"100%"},children:(0,s.jsx)(w.default,{teams:X})})}),(0,s.jsx)(x.Form.Item,{label:"Metadata",name:"metadata",children:(0,s.jsx)(h.Input.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,s.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,s.jsx)(u.Button,{htmlType:"submit",children:"Create User"})})]}):(0,s.jsxs)("div",{className:"flex gap-2",children:[(0,s.jsx)(u.Button,{type:"primary",className:"mb-0",onClick:()=>P(!0),children:"+ Invite User"}),(0,s.jsx)(b.default,{accessToken:y,teams:S,possibleUIRoles:k}),(0,s.jsxs)(p.Modal,{title:"Invite User",open:E,width:800,footer:null,onOk:()=>{P(!1),z.resetFields()},onCancel:()=>{P(!1),R(!1),z.resetFields()},children:[(0,s.jsxs)(g.Space,{direction:"vertical",size:"middle",children:[(0,s.jsx)(U,{className:"mb-1",children:"Create a User who can own keys"}),(0,s.jsx)(m.Alert,{message:"Email invitations",description:(0,s.jsxs)(s.Fragment,{children:["New users receive an email invite only when an email integration (SMTP, Resend, or SendGrid) is configured."," ",(0,s.jsx)(V,{href:"https://docs.litellm.ai/docs/proxy/email",target:"_blank",children:"Learn how to set up email notifications"})]}),type:"info",showIcon:!0,className:"mb-4"})]}),(0,s.jsxs)(x.Form,{form:z,onFinish:Y,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,s.jsx)(x.Form.Item,{label:"User Email",name:"user_email",children:(0,s.jsx)(h.Input,{})}),(0,s.jsx)(x.Form.Item,{label:(0,s.jsxs)("span",{children:["Global Proxy Role"," ",(0,s.jsx)(j.Tooltip,{title:"This role is independent of any team/org specific roles. Configure Team / Organization Admins in the Settings",children:(0,s.jsx)(t.InfoCircleOutlined,{})})]}),name:"user_role",children:(0,s.jsx)(f.Select,{children:k&&Object.entries(k).map(([e,{ui_label:t,description:l}])=>(0,s.jsxs)(o.SelectItem,{value:e,title:t,children:[(0,s.jsx)(U,{children:t}),(0,s.jsxs)(U,{type:"secondary",children:[" - ",l]})]},e))})}),(0,s.jsx)(x.Form.Item,{label:"Team",className:"gap-2",name:"team_id",help:"If selected, user will be added as a 'user' role to the team.",children:(0,s.jsx)(w.default,{teams:X})}),(0,s.jsx)(x.Form.Item,{label:"Organization",name:"organization_ids",help:"The user will be added to the selected organization(s).",children:(0,s.jsx)(f.Select,{mode:"multiple",placeholder:"Select Organization",style:{width:"100%"},children:Q.map(e=>(0,s.jsxs)(T,{value:e.organization_id,children:[e.organization_alias," (",e.organization_id,")"]},e.organization_id))})}),(0,s.jsx)(x.Form.Item,{label:"Metadata",name:"metadata",children:(0,s.jsx)(h.Input.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,s.jsxs)(i.Accordion,{children:[(0,s.jsx)(d.AccordionHeader,{children:(0,s.jsx)(U,{strong:!0,children:"Personal Key Creation"})}),(0,s.jsx)(n.AccordionBody,{children:(0,s.jsx)(x.Form.Item,{className:"gap-2",label:(0,s.jsxs)("span",{children:["Models"," ",(0,s.jsx)(j.Tooltip,{title:"Models user has access to, outside of team scope.",children:(0,s.jsx)(t.InfoCircleOutlined,{style:{marginLeft:"4px"}})})]}),name:"models",help:"Models user has access to, outside of team scope.",children:(0,s.jsxs)(f.Select,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[(0,s.jsx)(f.Select.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),(0,s.jsx)(f.Select.Option,{value:"no-default-models",children:"No Default Models"},"no-default-models"),D.map(e=>(0,s.jsx)(f.Select.Option,{value:e,children:(0,N.getModelDisplayName)(e)},e))]})})})]}),(0,s.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,s.jsx)(u.Button,{type:"primary",icon:(0,s.jsx)(l.UserAddOutlined,{}),htmlType:"submit",children:"Invite User"})})]})]}),A&&(0,s.jsx)(I,{isInvitationLinkModalVisible:W,setIsInvitationLinkModalVisible:K,baseUrl:G||"",invitationLinkData:q})]})}],371455)}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/5cf73abe29f8a3ae.js b/litellm/proxy/_experimental/out/_next/static/chunks/5cf73abe29f8a3ae.js deleted file mode 100644 index 517acb1eb51..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/5cf73abe29f8a3ae.js +++ /dev/null @@ -1,427 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,879664,e=>{"use strict";let t=(0,e.i(475254).default)("info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]);e.s(["default",()=>t])},115571,371401,e=>{"use strict";let t="local-storage-change";function a(e){window.dispatchEvent(new CustomEvent(t,{detail:{key:e}}))}function i(e){try{return window.localStorage.getItem(e)}catch(t){return console.warn(`Error reading localStorage key "${e}":`,t),null}}function n(e,t){try{window.localStorage.setItem(e,t)}catch(t){console.warn(`Error setting localStorage key "${e}":`,t)}}function r(e){try{window.localStorage.removeItem(e)}catch(t){console.warn(`Error removing localStorage key "${e}":`,t)}}e.s(["LOCAL_STORAGE_EVENT",0,t,"emitLocalStorageChange",()=>a,"getLocalStorageItem",()=>i,"removeLocalStorageItem",()=>r,"setLocalStorageItem",()=>n],115571);var l=e.i(271645);function o(e){let a=t=>{"disableUsageIndicator"===t.key&&e()},i=t=>{let{key:a}=t.detail;"disableUsageIndicator"===a&&e()};return window.addEventListener("storage",a),window.addEventListener(t,i),()=>{window.removeEventListener("storage",a),window.removeEventListener(t,i)}}function s(){return"true"===i("disableUsageIndicator")}function c(){return(0,l.useSyncExternalStore)(o,s)}e.s(["useDisableUsageIndicator",()=>c],371401)},275144,e=>{"use strict";var t=e.i(843476),a=e.i(271645),i=e.i(764205);let n=(0,a.createContext)(void 0);e.s(["ThemeProvider",0,({children:e,accessToken:r})=>{let[l,o]=(0,a.useState)(null),[s,c]=(0,a.useState)(null);return(0,a.useEffect)(()=>{(async()=>{try{let e=(0,i.getProxyBaseUrl)(),t=e?`${e}/get/ui_theme_settings`:"/get/ui_theme_settings",a=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}});if(a.ok){let e=await a.json();e.values?.logo_url&&o(e.values.logo_url),e.values?.favicon_url&&c(e.values.favicon_url)}}catch(e){console.warn("Failed to load theme settings from backend:",e)}})()},[]),(0,a.useEffect)(()=>{if(s){let e=document.querySelectorAll("link[rel*='icon']");if(e.length>0)e.forEach(e=>{e.href=s});else{let e=document.createElement("link");e.rel="icon",e.href=s,document.head.appendChild(e)}}},[s]),(0,t.jsx)(n.Provider,{value:{logoUrl:l,setLogoUrl:o,faviconUrl:s,setFaviconUrl:c},children:e})},"useTheme",0,()=>{let e=(0,a.useContext)(n);if(!e)throw Error("useTheme must be used within a ThemeProvider");return e}])},755151,e=>{"use strict";var t=e.i(247153);e.s(["DownOutlined",()=>t.default])},326373,e=>{"use strict";var t=e.i(21539);e.s(["Dropdown",()=>t.default])},264843,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let i={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M464 512a48 48 0 1096 0 48 48 0 10-96 0zm200 0a48 48 0 1096 0 48 48 0 10-96 0zm-400 0a48 48 0 1096 0 48 48 0 10-96 0zm661.2-173.6c-22.6-53.7-55-101.9-96.3-143.3a444.35 444.35 0 00-143.3-96.3C630.6 75.7 572.2 64 512 64h-2c-60.6.3-119.3 12.3-174.5 35.9a445.35 445.35 0 00-142 96.5c-40.9 41.3-73 89.3-95.2 142.8-23 55.4-34.6 114.3-34.3 174.9A449.4 449.4 0 00112 714v152a46 46 0 0046 46h152.1A449.4 449.4 0 00510 960h2.1c59.9 0 118-11.6 172.7-34.3a444.48 444.48 0 00142.8-95.2c41.3-40.9 73.8-88.7 96.5-142 23.6-55.2 35.6-113.9 35.9-174.5.3-60.9-11.5-120-34.8-175.6zm-151.1 438C704 845.8 611 884 512 884h-1.7c-60.3-.3-120.2-15.3-173.1-43.5l-8.4-4.5H188V695.2l-4.5-8.4C155.3 633.9 140.3 574 140 513.7c-.4-99.7 37.7-193.3 107.6-263.8 69.8-70.5 163.1-109.5 262.8-109.9h1.7c50 0 98.5 9.7 144.2 28.9 44.6 18.7 84.6 45.6 119 80 34.3 34.3 61.3 74.4 80 119 19.4 46.2 29.1 95.2 28.9 145.8-.6 99.6-39.7 192.9-110.1 262.7z"}}]},name:"message",theme:"outlined"};var n=e.i(9583),r=a.forwardRef(function(e,r){return a.createElement(n.default,(0,t.default)({},e,{ref:r,icon:i}))});e.s(["MessageOutlined",0,r],264843)},44121,186515,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let i={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M408 442h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8zm-8 204c0 4.4 3.6 8 8 8h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56zm504-486H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm0 632H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zM115.4 518.9L271.7 642c5.8 4.6 14.4.5 14.4-6.9V388.9c0-7.4-8.5-11.5-14.4-6.9L115.4 505.1a8.74 8.74 0 000 13.8z"}}]},name:"menu-fold",theme:"outlined"};var n=e.i(9583),r=a.forwardRef(function(e,r){return a.createElement(n.default,(0,t.default)({},e,{ref:r,icon:i}))});e.s(["MenuFoldOutlined",0,r],44121);let l={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M408 442h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8zm-8 204c0 4.4 3.6 8 8 8h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56zm504-486H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm0 632H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zM142.4 642.1L298.7 519a8.84 8.84 0 000-13.9L142.4 381.9c-5.8-4.6-14.4-.5-14.4 6.9v246.3a8.9 8.9 0 0014.4 7z"}}]},name:"menu-unfold",theme:"outlined"};var o=a.forwardRef(function(e,i){return a.createElement(n.default,(0,t.default)({},e,{ref:i,icon:l}))});e.s(["MenuUnfoldOutlined",0,o],186515)},602073,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let i={icon:{tag:"svg",attrs:{viewBox:"0 0 1024 1024",focusable:"false"},children:[{tag:"path",attrs:{d:"M512 64L128 192v384c0 212.1 171.9 384 384 384s384-171.9 384-384V192L512 64zm312 512c0 172.3-139.7 312-312 312S200 748.3 200 576V246l312-110 312 110v330z"}},{tag:"path",attrs:{d:"M378.4 475.1a35.91 35.91 0 00-50.9 0 35.91 35.91 0 000 50.9l129.4 129.4 2.1 2.1a33.98 33.98 0 0048.1 0L730.6 434a33.98 33.98 0 000-48.1l-2.8-2.8a33.98 33.98 0 00-48.1 0L483 579.7 378.4 475.1z"}}]},name:"safety",theme:"outlined"};var n=e.i(9583),r=a.forwardRef(function(e,r){return a.createElement(n.default,(0,t.default)({},e,{ref:r,icon:i}))});e.s(["SafetyOutlined",0,r],602073)},62478,e=>{"use strict";var t=e.i(764205);let a=async e=>{if(!e)return null;try{return await (0,t.getProxyUISettings)(e)}catch(e){return console.error("Error fetching proxy settings:",e),null}};e.s(["fetchProxySettings",0,a])},818581,(e,t,a)=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0}),Object.defineProperty(a,"useMergedRef",{enumerable:!0,get:function(){return n}});let i=e.r(271645);function n(e,t){let a=(0,i.useRef)(null),n=(0,i.useRef)(null);return(0,i.useCallback)(i=>{if(null===i){let e=a.current;e&&(a.current=null,e());let t=n.current;t&&(n.current=null,t())}else e&&(a.current=r(e,i)),t&&(n.current=r(t,i))},[e,t])}function r(e,t){if("function"!=typeof e)return e.current=t,()=>{e.current=null};{let a=e(t);return"function"==typeof a?a:()=>e(null)}}("function"==typeof a.default||"object"==typeof a.default&&null!==a.default)&&void 0===a.default.__esModule&&(Object.defineProperty(a.default,"__esModule",{value:!0}),Object.assign(a.default,a),t.exports=a.default)},190272,785913,e=>{"use strict";var t,a,i=((t={}).AUDIO_SPEECH="audio_speech",t.AUDIO_TRANSCRIPTION="audio_transcription",t.IMAGE_GENERATION="image_generation",t.VIDEO_GENERATION="video_generation",t.CHAT="chat",t.RESPONSES="responses",t.IMAGE_EDITS="image_edits",t.ANTHROPIC_MESSAGES="anthropic_messages",t.EMBEDDING="embedding",t),n=((a={}).IMAGE="image",a.VIDEO="video",a.CHAT="chat",a.RESPONSES="responses",a.IMAGE_EDITS="image_edits",a.ANTHROPIC_MESSAGES="anthropic_messages",a.EMBEDDINGS="embeddings",a.SPEECH="speech",a.TRANSCRIPTION="transcription",a.A2A_AGENTS="a2a_agents",a.MCP="mcp",a.REALTIME="realtime",a);let r={image_generation:"image",video_generation:"video",chat:"chat",responses:"responses",image_edits:"image_edits",anthropic_messages:"anthropic_messages",audio_speech:"speech",audio_transcription:"transcription",embedding:"embeddings"};e.s(["EndpointType",()=>n,"getEndpointType",0,e=>{if(console.log("getEndpointType:",e),Object.values(i).includes(e)){let t=r[e];return console.log("endpointType:",t),t}return"chat"}],785913),e.s(["generateCodeSnippet",0,e=>{let t,{apiKeySource:a,accessToken:i,apiKey:r,inputMessage:l,chatHistory:o,selectedTags:s,selectedVectorStores:c,selectedGuardrails:d,selectedPolicies:u,selectedMCPServers:m,mcpServers:g,mcpServerToolRestrictions:p,selectedVoice:f,endpointType:h,selectedModel:b,selectedSdk:_,proxySettings:v}=e,w="session"===a?i:r,x=window.location.origin,y=v?.LITELLM_UI_API_DOC_BASE_URL;y&&y.trim()?x=y:v?.PROXY_BASE_URL&&(x=v.PROXY_BASE_URL);let E=l||"Your prompt here",j=E.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n"),$=o.filter(e=>!e.isImage).map(({role:e,content:t})=>({role:e,content:t})),C={};s.length>0&&(C.tags=s),c.length>0&&(C.vector_stores=c),d.length>0&&(C.guardrails=d),u.length>0&&(C.policies=u);let k=b||"your-model-name",O="azure"===_?`import openai - -client = openai.AzureOpenAI( - api_key="${w||"YOUR_LITELLM_API_KEY"}", - azure_endpoint="${x}", - api_version="2024-02-01" -)`:`import openai - -client = openai.OpenAI( - api_key="${w||"YOUR_LITELLM_API_KEY"}", - base_url="${x}" -)`;switch(h){case n.CHAT:{let e=Object.keys(C).length>0,a="";if(e){let e=JSON.stringify({metadata:C},null,2).split("\n").map(e=>" ".repeat(4)+e).join("\n").trim();a=`, - extra_body=${e}`}let i=$.length>0?$:[{role:"user",content:E}];t=` -import base64 - -# Helper function to encode images to base64 -def encode_image(image_path): - with open(image_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode('utf-8') - -# Example with text only -response = client.chat.completions.create( - model="${k}", - messages=${JSON.stringify(i,null,4)}${a} -) - -print(response) - -# Example with image or PDF (uncomment and provide file path to use) -# base64_file = encode_image("path/to/your/file.jpg") # or .pdf -# response_with_file = client.chat.completions.create( -# model="${k}", -# messages=[ -# { -# "role": "user", -# "content": [ -# { -# "type": "text", -# "text": "${j}" -# }, -# { -# "type": "image_url", -# "image_url": { -# "url": f"data:image/jpeg;base64,{base64_file}" # or data:application/pdf;base64,{base64_file} -# } -# } -# ] -# } -# ]${a} -# ) -# print(response_with_file) -`;break}case n.RESPONSES:{let e=Object.keys(C).length>0,a="";if(e){let e=JSON.stringify({metadata:C},null,2).split("\n").map(e=>" ".repeat(4)+e).join("\n").trim();a=`, - extra_body=${e}`}let i=$.length>0?$:[{role:"user",content:E}];t=` -import base64 - -# Helper function to encode images to base64 -def encode_image(image_path): - with open(image_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode('utf-8') - -# Example with text only -response = client.responses.create( - model="${k}", - input=${JSON.stringify(i,null,4)}${a} -) - -print(response.output_text) - -# Example with image or PDF (uncomment and provide file path to use) -# base64_file = encode_image("path/to/your/file.jpg") # or .pdf -# response_with_file = client.responses.create( -# model="${k}", -# input=[ -# { -# "role": "user", -# "content": [ -# {"type": "input_text", "text": "${j}"}, -# { -# "type": "input_image", -# "image_url": f"data:image/jpeg;base64,{base64_file}", # or data:application/pdf;base64,{base64_file} -# }, -# ], -# } -# ]${a} -# ) -# print(response_with_file.output_text) -`;break}case n.IMAGE:t="azure"===_?` -# NOTE: The Azure SDK does not have a direct equivalent to the multi-modal 'responses.create' method shown for OpenAI. -# This snippet uses 'client.images.generate' and will create a new image based on your prompt. -# It does not use the uploaded image, as 'client.images.generate' does not support image inputs in this context. -import os -import requests -import json -import time -from PIL import Image - -result = client.images.generate( - model="${k}", - prompt="${l}", - n=1 -) - -json_response = json.loads(result.model_dump_json()) - -# Set the directory for the stored image -image_dir = os.path.join(os.curdir, 'images') - -# If the directory doesn't exist, create it -if not os.path.isdir(image_dir): - os.mkdir(image_dir) - -# Initialize the image path -image_filename = f"generated_image_{int(time.time())}.png" -image_path = os.path.join(image_dir, image_filename) - -try: - # Retrieve the generated image - if json_response.get("data") && len(json_response["data"]) > 0 && json_response["data"][0].get("url"): - image_url = json_response["data"][0]["url"] - generated_image = requests.get(image_url).content - with open(image_path, "wb") as image_file: - image_file.write(generated_image) - - print(f"Image saved to {image_path}") - # Display the image - image = Image.open(image_path) - image.show() - else: - print("Could not find image URL in response.") - print("Full response:", json_response) -except Exception as e: - print(f"An error occurred: {e}") - print("Full response:", json_response) -`:` -import base64 -import os -import time -import json -from PIL import Image -import requests - -# Helper function to encode images to base64 -def encode_image(image_path): - with open(image_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode('utf-8') - -# Helper function to create a file (simplified for this example) -def create_file(image_path): - # In a real implementation, this would upload the file to OpenAI - # For this example, we'll just return a placeholder ID - return f"file_{os.path.basename(image_path).replace('.', '_')}" - -# The prompt entered by the user -prompt = "${j}" - -# Encode images to base64 -base64_image1 = encode_image("body-lotion.png") -base64_image2 = encode_image("soap.png") - -# Create file IDs -file_id1 = create_file("body-lotion.png") -file_id2 = create_file("incense-kit.png") - -response = client.responses.create( - model="${k}", - input=[ - { - "role": "user", - "content": [ - {"type": "input_text", "text": prompt}, - { - "type": "input_image", - "image_url": f"data:image/jpeg;base64,{base64_image1}", - }, - { - "type": "input_image", - "image_url": f"data:image/jpeg;base64,{base64_image2}", - }, - { - "type": "input_image", - "file_id": file_id1, - }, - { - "type": "input_image", - "file_id": file_id2, - } - ], - } - ], - tools=[{"type": "image_generation"}], -) - -# Process the response -image_generation_calls = [ - output - for output in response.output - if output.type == "image_generation_call" -] - -image_data = [output.result for output in image_generation_calls] - -if image_data: - image_base64 = image_data[0] - image_filename = f"edited_image_{int(time.time())}.png" - with open(image_filename, "wb") as f: - f.write(base64.b64decode(image_base64)) - print(f"Image saved to {image_filename}") -else: - # If no image is generated, there might be a text response with an explanation - text_response = [output.text for output in response.output if hasattr(output, 'text')] - if text_response: - print("No image generated. Model response:") - print("\\n".join(text_response)) - else: - print("No image data found in response.") - print("Full response for debugging:") - print(response) -`;break;case n.IMAGE_EDITS:t="azure"===_?` -import base64 -import os -import time -import json -from PIL import Image -import requests - -# Helper function to encode images to base64 -def encode_image(image_path): - with open(image_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode('utf-8') - -# The prompt entered by the user -prompt = "${j}" - -# Encode images to base64 -base64_image1 = encode_image("body-lotion.png") -base64_image2 = encode_image("soap.png") - -# Create file IDs -file_id1 = create_file("body-lotion.png") -file_id2 = create_file("incense-kit.png") - -response = client.responses.create( - model="${k}", - input=[ - { - "role": "user", - "content": [ - {"type": "input_text", "text": prompt}, - { - "type": "input_image", - "image_url": f"data:image/jpeg;base64,{base64_image1}", - }, - { - "type": "input_image", - "image_url": f"data:image/jpeg;base64,{base64_image2}", - }, - { - "type": "input_image", - "file_id": file_id1, - }, - { - "type": "input_image", - "file_id": file_id2, - } - ], - } - ], - tools=[{"type": "image_generation"}], -) - -# Process the response -image_generation_calls = [ - output - for output in response.output - if output.type == "image_generation_call" -] - -image_data = [output.result for output in image_generation_calls] - -if image_data: - image_base64 = image_data[0] - image_filename = f"edited_image_{int(time.time())}.png" - with open(image_filename, "wb") as f: - f.write(base64.b64decode(image_base64)) - print(f"Image saved to {image_filename}") -else: - # If no image is generated, there might be a text response with an explanation - text_response = [output.text for output in response.output if hasattr(output, 'text')] - if text_response: - print("No image generated. Model response:") - print("\\n".join(text_response)) - else: - print("No image data found in response.") - print("Full response for debugging:") - print(response) -`:` -import base64 -import os -import time - -# Helper function to encode images to base64 -def encode_image(image_path): - with open(image_path, "rb") as image_file: - return base64.b64encode(image_file.read()).decode('utf-8') - -# Helper function to create a file (simplified for this example) -def create_file(image_path): - # In a real implementation, this would upload the file to OpenAI - # For this example, we'll just return a placeholder ID - return f"file_{os.path.basename(image_path).replace('.', '_')}" - -# The prompt entered by the user -prompt = "${j}" - -# Encode images to base64 -base64_image1 = encode_image("body-lotion.png") -base64_image2 = encode_image("soap.png") - -# Create file IDs -file_id1 = create_file("body-lotion.png") -file_id2 = create_file("incense-kit.png") - -response = client.responses.create( - model="${k}", - input=[ - { - "role": "user", - "content": [ - {"type": "input_text", "text": prompt}, - { - "type": "input_image", - "image_url": f"data:image/jpeg;base64,{base64_image1}", - }, - { - "type": "input_image", - "image_url": f"data:image/jpeg;base64,{base64_image2}", - }, - { - "type": "input_image", - "file_id": file_id1, - }, - { - "type": "input_image", - "file_id": file_id2, - } - ], - } - ], - tools=[{"type": "image_generation"}], -) - -# Process the response -image_generation_calls = [ - output - for output in response.output - if output.type == "image_generation_call" -] - -image_data = [output.result for output in image_generation_calls] - -if image_data: - image_base64 = image_data[0] - image_filename = f"edited_image_{int(time.time())}.png" - with open(image_filename, "wb") as f: - f.write(base64.b64decode(image_base64)) - print(f"Image saved to {image_filename}") -else: - # If no image is generated, there might be a text response with an explanation - text_response = [output.text for output in response.output if hasattr(output, 'text')] - if text_response: - print("No image generated. Model response:") - print("\\n".join(text_response)) - else: - print("No image data found in response.") - print("Full response for debugging:") - print(response) -`;break;case n.EMBEDDINGS:t=` -response = client.embeddings.create( - input="${l||"Your string here"}", - model="${k}", - encoding_format="base64" # or "float" -) - -print(response.data[0].embedding) -`;break;case n.TRANSCRIPTION:t=` -# Open the audio file -audio_file = open("path/to/your/audio/file.mp3", "rb") - -# Make the transcription request -response = client.audio.transcriptions.create( - model="${k}", - file=audio_file${l?`, - prompt="${l.replace(/"/g,'\\"')}"`:""} -) - -print(response.text) -`;break;case n.SPEECH:t=` -# Make the text-to-speech request -response = client.audio.speech.create( - model="${k}", - input="${l||"Your text to convert to speech here"}", - voice="${f}" # Options: alloy, ash, ballad, coral, echo, fable, nova, onyx, sage, shimmer -) - -# Save the audio to a file -output_filename = "output_speech.mp3" -response.stream_to_file(output_filename) -print(f"Audio saved to {output_filename}") - -# Optional: Customize response format and speed -# response = client.audio.speech.create( -# model="${k}", -# input="${l||"Your text to convert to speech here"}", -# voice="alloy", -# response_format="mp3", # Options: mp3, opus, aac, flac, wav, pcm -# speed=1.0 # Range: 0.25 to 4.0 -# ) -# response.stream_to_file("output_speech.mp3") -`;break;default:t="\n# Code generation for this endpoint is not implemented yet."}return`${O} -${t}`}],190272)},563113,887719,e=>{"use strict";var t=e.i(271645),a=e.i(864517),i=e.i(244009),n=e.i(408850),r=e.i(87414);let l=function(...e){let t={};return e.forEach(e=>{e&&Object.keys(e).forEach(a=>{void 0!==e[a]&&(t[a]=e[a])})}),t};function o(e){if(!e)return;let{closable:t,closeIcon:a}=e;return{closable:t,closeIcon:a}}function s(e){let{closable:a,closeIcon:i}=e||{};return t.default.useMemo(()=>{if(!a&&(!1===a||!1===i||null===i))return!1;if(void 0===a&&void 0===i)return null;let e={closeIcon:"boolean"!=typeof i&&null!==i?i:void 0};return a&&"object"==typeof a&&(e=Object.assign(Object.assign({},e),a)),e},[a,i])}e.s(["default",0,l],887719);let c={};e.s(["pickClosable",()=>o,"useClosable",0,(e,o,d=c)=>{let u=s(e),m=s(o),[g]=(0,n.useLocale)("global",r.default.global),p="boolean"!=typeof u&&!!(null==u?void 0:u.disabled),f=t.default.useMemo(()=>Object.assign({closeIcon:t.default.createElement(a.default,null)},d),[d]),h=t.default.useMemo(()=>!1!==u&&(u?l(f,m,u):!1!==m&&(m?l(f,m):!!f.closable&&f)),[u,m,f]);return t.default.useMemo(()=>{var e,a;if(!1===h)return[!1,null,p,{}];let{closeIconRender:n}=f,{closeIcon:r}=h,l=r,o=(0,i.default)(h,!0);return null!=l&&(n&&(l=n(r)),l=t.default.isValidElement(l)?t.default.cloneElement(l,Object.assign(Object.assign(Object.assign({},l.props),{"aria-label":null!=(a=null==(e=l.props)?void 0:e["aria-label"])?a:g.close}),o)):t.default.createElement("span",Object.assign({"aria-label":g.close},o),l)),[!0,l,p,o]},[p,g.close,h,f])}],563113)},735049,e=>{"use strict";var t=e.i(654310),a=function(e){if((0,t.default)()&&window.document.documentElement){var a=Array.isArray(e)?e:[e],i=window.document.documentElement;return a.some(function(e){return e in i.style})}return!1},i=function(e,t){if(!a(e))return!1;var i=document.createElement("div"),n=i.style[e];return i.style[e]=t,i.style[e]!==n};function n(e,t){return Array.isArray(e)||void 0===t?a(e):i(e,t)}e.s(["isStyleSupport",()=>n])},190144,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let i={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M832 64H296c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h496v688c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8V96c0-17.7-14.3-32-32-32zM704 192H192c-17.7 0-32 14.3-32 32v530.7c0 8.5 3.4 16.6 9.4 22.6l173.3 173.3c2.2 2.2 4.7 4 7.4 5.5v1.9h4.2c3.5 1.3 7.2 2 11 2H704c17.7 0 32-14.3 32-32V224c0-17.7-14.3-32-32-32zM350 856.2L263.9 770H350v86.2zM664 888H414V746c0-22.1-17.9-40-40-40H232V264h432v624z"}}]},name:"copy",theme:"outlined"};var n=e.i(9583),r=a.forwardRef(function(e,r){return a.createElement(n.default,(0,t.default)({},e,{ref:r,icon:i}))});e.s(["default",0,r],190144)},464571,e=>{"use strict";var t=e.i(920228);e.s(["Button",()=>t.default])},185793,e=>{"use strict";e.i(247167);var t=e.i(271645),a=e.i(343794),i=e.i(242064),n=e.i(529681);let r=e=>{let{prefixCls:i,className:n,style:r,size:l,shape:o}=e,s=(0,a.default)({[`${i}-lg`]:"large"===l,[`${i}-sm`]:"small"===l}),c=(0,a.default)({[`${i}-circle`]:"circle"===o,[`${i}-square`]:"square"===o,[`${i}-round`]:"round"===o}),d=t.useMemo(()=>"number"==typeof l?{width:l,height:l,lineHeight:`${l}px`}:{},[l]);return t.createElement("span",{className:(0,a.default)(i,s,c,n),style:Object.assign(Object.assign({},d),r)})};e.i(296059);var l=e.i(694758),o=e.i(915654),s=e.i(246422),c=e.i(838378);let d=new l.Keyframes("ant-skeleton-loading",{"0%":{backgroundPosition:"100% 50%"},"100%":{backgroundPosition:"0 50%"}}),u=e=>({height:e,lineHeight:(0,o.unit)(e)}),m=e=>Object.assign({width:e},u(e)),g=(e,t)=>Object.assign({width:t(e).mul(5).equal(),minWidth:t(e).mul(5).equal()},u(e)),p=e=>Object.assign({width:e},u(e)),f=(e,t,a)=>{let{skeletonButtonCls:i}=e;return{[`${a}${i}-circle`]:{width:t,minWidth:t,borderRadius:"50%"},[`${a}${i}-round`]:{borderRadius:t}}},h=(e,t)=>Object.assign({width:t(e).mul(2).equal(),minWidth:t(e).mul(2).equal()},u(e)),b=(0,s.genStyleHooks)("Skeleton",e=>{let{componentCls:t,calc:a}=e;return(e=>{let{componentCls:t,skeletonAvatarCls:a,skeletonTitleCls:i,skeletonParagraphCls:n,skeletonButtonCls:r,skeletonInputCls:l,skeletonImageCls:o,controlHeight:s,controlHeightLG:c,controlHeightSM:u,gradientFromColor:b,padding:_,marginSM:v,borderRadius:w,titleHeight:x,blockRadius:y,paragraphLiHeight:E,controlHeightXS:j,paragraphMarginTop:$}=e;return{[t]:{display:"table",width:"100%",[`${t}-header`]:{display:"table-cell",paddingInlineEnd:_,verticalAlign:"top",[a]:Object.assign({display:"inline-block",verticalAlign:"top",background:b},m(s)),[`${a}-circle`]:{borderRadius:"50%"},[`${a}-lg`]:Object.assign({},m(c)),[`${a}-sm`]:Object.assign({},m(u))},[`${t}-content`]:{display:"table-cell",width:"100%",verticalAlign:"top",[i]:{width:"100%",height:x,background:b,borderRadius:y,[`+ ${n}`]:{marginBlockStart:u}},[n]:{padding:0,"> li":{width:"100%",height:E,listStyle:"none",background:b,borderRadius:y,"+ li":{marginBlockStart:j}}},[`${n}> li:last-child:not(:first-child):not(:nth-child(2))`]:{width:"61%"}},[`&-round ${t}-content`]:{[`${i}, ${n} > li`]:{borderRadius:w}}},[`${t}-with-avatar ${t}-content`]:{[i]:{marginBlockStart:v,[`+ ${n}`]:{marginBlockStart:$}}},[`${t}${t}-element`]:Object.assign(Object.assign(Object.assign(Object.assign({display:"inline-block",width:"auto"},(e=>{let{borderRadiusSM:t,skeletonButtonCls:a,controlHeight:i,controlHeightLG:n,controlHeightSM:r,gradientFromColor:l,calc:o}=e;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({[a]:Object.assign({display:"inline-block",verticalAlign:"top",background:l,borderRadius:t,width:o(i).mul(2).equal(),minWidth:o(i).mul(2).equal()},h(i,o))},f(e,i,a)),{[`${a}-lg`]:Object.assign({},h(n,o))}),f(e,n,`${a}-lg`)),{[`${a}-sm`]:Object.assign({},h(r,o))}),f(e,r,`${a}-sm`))})(e)),(e=>{let{skeletonAvatarCls:t,gradientFromColor:a,controlHeight:i,controlHeightLG:n,controlHeightSM:r}=e;return{[t]:Object.assign({display:"inline-block",verticalAlign:"top",background:a},m(i)),[`${t}${t}-circle`]:{borderRadius:"50%"},[`${t}${t}-lg`]:Object.assign({},m(n)),[`${t}${t}-sm`]:Object.assign({},m(r))}})(e)),(e=>{let{controlHeight:t,borderRadiusSM:a,skeletonInputCls:i,controlHeightLG:n,controlHeightSM:r,gradientFromColor:l,calc:o}=e;return{[i]:Object.assign({display:"inline-block",verticalAlign:"top",background:l,borderRadius:a},g(t,o)),[`${i}-lg`]:Object.assign({},g(n,o)),[`${i}-sm`]:Object.assign({},g(r,o))}})(e)),(e=>{let{skeletonImageCls:t,imageSizeBase:a,gradientFromColor:i,borderRadiusSM:n,calc:r}=e;return{[t]:Object.assign(Object.assign({display:"inline-flex",alignItems:"center",justifyContent:"center",verticalAlign:"middle",background:i,borderRadius:n},p(r(a).mul(2).equal())),{[`${t}-path`]:{fill:"#bfbfbf"},[`${t}-svg`]:Object.assign(Object.assign({},p(a)),{maxWidth:r(a).mul(4).equal(),maxHeight:r(a).mul(4).equal()}),[`${t}-svg${t}-svg-circle`]:{borderRadius:"50%"}}),[`${t}${t}-circle`]:{borderRadius:"50%"}}})(e)),[`${t}${t}-block`]:{width:"100%",[r]:{width:"100%"},[l]:{width:"100%"}},[`${t}${t}-active`]:{[` - ${i}, - ${n} > li, - ${a}, - ${r}, - ${l}, - ${o} - `]:Object.assign({},{background:e.skeletonLoadingBackground,backgroundSize:"400% 100%",animationName:d,animationDuration:e.skeletonLoadingMotionDuration,animationTimingFunction:"ease",animationIterationCount:"infinite"})}}})((0,c.mergeToken)(e,{skeletonAvatarCls:`${t}-avatar`,skeletonTitleCls:`${t}-title`,skeletonParagraphCls:`${t}-paragraph`,skeletonButtonCls:`${t}-button`,skeletonInputCls:`${t}-input`,skeletonImageCls:`${t}-image`,imageSizeBase:a(e.controlHeight).mul(1.5).equal(),borderRadius:100,skeletonLoadingBackground:`linear-gradient(90deg, ${e.gradientFromColor} 25%, ${e.gradientToColor} 37%, ${e.gradientFromColor} 63%)`,skeletonLoadingMotionDuration:"1.4s"}))},e=>{let{colorFillContent:t,colorFill:a}=e;return{color:t,colorGradientEnd:a,gradientFromColor:t,gradientToColor:a,titleHeight:e.controlHeight/2,blockRadius:e.borderRadiusSM,paragraphMarginTop:e.marginLG+e.marginXXS,paragraphLiHeight:e.controlHeight/2}},{deprecatedTokens:[["color","gradientFromColor"],["colorGradientEnd","gradientToColor"]]}),_=e=>{let{prefixCls:i,className:n,style:r,rows:l=0}=e,o=Array.from({length:l}).map((a,i)=>t.createElement("li",{key:i,style:{width:((e,t)=>{let{width:a,rows:i=2}=t;return Array.isArray(a)?a[e]:i-1===e?a:void 0})(i,e)}}));return t.createElement("ul",{className:(0,a.default)(i,n),style:r},o)},v=({prefixCls:e,className:i,width:n,style:r})=>t.createElement("h3",{className:(0,a.default)(e,i),style:Object.assign({width:n},r)});function w(e){return e&&"object"==typeof e?e:{}}let x=e=>{let{prefixCls:n,loading:l,className:o,rootClassName:s,style:c,children:d,avatar:u=!1,title:m=!0,paragraph:g=!0,active:p,round:f}=e,{getPrefixCls:h,direction:x,className:y,style:E}=(0,i.useComponentConfig)("skeleton"),j=h("skeleton",n),[$,C,k]=b(j);if(l||!("loading"in e)){let e,i,n=!!u,l=!!m,d=!!g;if(n){let a=Object.assign(Object.assign({prefixCls:`${j}-avatar`},l&&!d?{size:"large",shape:"square"}:{size:"large",shape:"circle"}),w(u));e=t.createElement("div",{className:`${j}-header`},t.createElement(r,Object.assign({},a)))}if(l||d){let e,a;if(l){let a=Object.assign(Object.assign({prefixCls:`${j}-title`},!n&&d?{width:"38%"}:n&&d?{width:"50%"}:{}),w(m));e=t.createElement(v,Object.assign({},a))}if(d){let e,i=Object.assign(Object.assign({prefixCls:`${j}-paragraph`},(e={},n&&l||(e.width="61%"),!n&&l?e.rows=3:e.rows=2,e)),w(g));a=t.createElement(_,Object.assign({},i))}i=t.createElement("div",{className:`${j}-content`},e,a)}let h=(0,a.default)(j,{[`${j}-with-avatar`]:n,[`${j}-active`]:p,[`${j}-rtl`]:"rtl"===x,[`${j}-round`]:f},y,o,s,C,k);return $(t.createElement("div",{className:h,style:Object.assign(Object.assign({},E),c)},e,i))}return null!=d?d:null};x.Button=e=>{let{prefixCls:l,className:o,rootClassName:s,active:c,block:d=!1,size:u="default"}=e,{getPrefixCls:m}=t.useContext(i.ConfigContext),g=m("skeleton",l),[p,f,h]=b(g),_=(0,n.default)(e,["prefixCls"]),v=(0,a.default)(g,`${g}-element`,{[`${g}-active`]:c,[`${g}-block`]:d},o,s,f,h);return p(t.createElement("div",{className:v},t.createElement(r,Object.assign({prefixCls:`${g}-button`,size:u},_))))},x.Avatar=e=>{let{prefixCls:l,className:o,rootClassName:s,active:c,shape:d="circle",size:u="default"}=e,{getPrefixCls:m}=t.useContext(i.ConfigContext),g=m("skeleton",l),[p,f,h]=b(g),_=(0,n.default)(e,["prefixCls","className"]),v=(0,a.default)(g,`${g}-element`,{[`${g}-active`]:c},o,s,f,h);return p(t.createElement("div",{className:v},t.createElement(r,Object.assign({prefixCls:`${g}-avatar`,shape:d,size:u},_))))},x.Input=e=>{let{prefixCls:l,className:o,rootClassName:s,active:c,block:d,size:u="default"}=e,{getPrefixCls:m}=t.useContext(i.ConfigContext),g=m("skeleton",l),[p,f,h]=b(g),_=(0,n.default)(e,["prefixCls"]),v=(0,a.default)(g,`${g}-element`,{[`${g}-active`]:c,[`${g}-block`]:d},o,s,f,h);return p(t.createElement("div",{className:v},t.createElement(r,Object.assign({prefixCls:`${g}-input`,size:u},_))))},x.Image=e=>{let{prefixCls:n,className:r,rootClassName:l,style:o,active:s}=e,{getPrefixCls:c}=t.useContext(i.ConfigContext),d=c("skeleton",n),[u,m,g]=b(d),p=(0,a.default)(d,`${d}-element`,{[`${d}-active`]:s},r,l,m,g);return u(t.createElement("div",{className:p},t.createElement("div",{className:(0,a.default)(`${d}-image`,r),style:o},t.createElement("svg",{viewBox:"0 0 1098 1024",xmlns:"http://www.w3.org/2000/svg",className:`${d}-image-svg`},t.createElement("title",null,"Image placeholder"),t.createElement("path",{d:"M365.714286 329.142857q0 45.714286-32.036571 77.677714t-77.677714 32.036571-77.677714-32.036571-32.036571-77.677714 32.036571-77.677714 77.677714-32.036571 77.677714 32.036571 32.036571 77.677714zM950.857143 548.571429l0 256-804.571429 0 0-109.714286 182.857143-182.857143 91.428571 91.428571 292.571429-292.571429zM1005.714286 146.285714l-914.285714 0q-7.460571 0-12.873143 5.412571t-5.412571 12.873143l0 694.857143q0 7.460571 5.412571 12.873143t12.873143 5.412571l914.285714 0q7.460571 0 12.873143-5.412571t5.412571-12.873143l0-694.857143q0-7.460571-5.412571-12.873143t-12.873143-5.412571zM1097.142857 164.571429l0 694.857143q0 37.741714-26.843429 64.585143t-64.585143 26.843429l-914.285714 0q-37.741714 0-64.585143-26.843429t-26.843429-64.585143l0-694.857143q0-37.741714 26.843429-64.585143t64.585143-26.843429l914.285714 0q37.741714 0 64.585143 26.843429t26.843429 64.585143z",className:`${d}-image-path`})))))},x.Node=e=>{let{prefixCls:n,className:r,rootClassName:l,style:o,active:s,children:c}=e,{getPrefixCls:d}=t.useContext(i.ConfigContext),u=d("skeleton",n),[m,g,p]=b(u),f=(0,a.default)(u,`${u}-element`,{[`${u}-active`]:s},g,r,l,p);return m(t.createElement("div",{className:f},t.createElement("div",{className:(0,a.default)(`${u}-image`,r),style:o},c)))},e.s(["default",0,x],185793)},959013,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let i={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8z"}},{tag:"path",attrs:{d:"M192 474h672q8 0 8 8v60q0 8-8 8H160q-8 0-8-8v-60q0-8 8-8z"}}]},name:"plus",theme:"outlined"};var n=e.i(9583),r=a.forwardRef(function(e,r){return a.createElement(n.default,(0,t.default)({},e,{ref:r,icon:i}))});e.s(["default",0,r],959013)},269200,e=>{"use strict";var t=e.i(290571),a=e.i(271645),i=e.i(444755);let n=(0,e.i(673706).makeClassName)("Table"),r=a.default.forwardRef((e,r)=>{let{children:l,className:o}=e,s=(0,t.__rest)(e,["children","className"]);return a.default.createElement("div",{className:(0,i.tremorTwMerge)(n("root"),"overflow-auto",o)},a.default.createElement("table",Object.assign({ref:r,className:(0,i.tremorTwMerge)(n("table"),"w-full text-tremor-default","text-tremor-content","dark:text-dark-tremor-content")},s),l))});r.displayName="Table",e.s(["Table",()=>r],269200)},427612,e=>{"use strict";var t=e.i(290571),a=e.i(271645),i=e.i(444755);let n=(0,e.i(673706).makeClassName)("TableHead"),r=a.default.forwardRef((e,r)=>{let{children:l,className:o}=e,s=(0,t.__rest)(e,["children","className"]);return a.default.createElement(a.default.Fragment,null,a.default.createElement("thead",Object.assign({ref:r,className:(0,i.tremorTwMerge)(n("root"),"text-left","text-tremor-content","dark:text-dark-tremor-content",o)},s),l))});r.displayName="TableHead",e.s(["TableHead",()=>r],427612)},64848,e=>{"use strict";var t=e.i(290571),a=e.i(271645),i=e.i(444755);let n=(0,e.i(673706).makeClassName)("TableHeaderCell"),r=a.default.forwardRef((e,r)=>{let{children:l,className:o}=e,s=(0,t.__rest)(e,["children","className"]);return a.default.createElement(a.default.Fragment,null,a.default.createElement("th",Object.assign({ref:r,className:(0,i.tremorTwMerge)(n("root"),"whitespace-nowrap text-left font-semibold top-0 px-4 py-3.5","text-tremor-content-strong","dark:text-dark-tremor-content-strong",o)},s),l))});r.displayName="TableHeaderCell",e.s(["TableHeaderCell",()=>r],64848)},942232,e=>{"use strict";var t=e.i(290571),a=e.i(271645),i=e.i(444755);let n=(0,e.i(673706).makeClassName)("TableBody"),r=a.default.forwardRef((e,r)=>{let{children:l,className:o}=e,s=(0,t.__rest)(e,["children","className"]);return a.default.createElement(a.default.Fragment,null,a.default.createElement("tbody",Object.assign({ref:r,className:(0,i.tremorTwMerge)(n("root"),"align-top divide-y","divide-tremor-border","dark:divide-dark-tremor-border",o)},s),l))});r.displayName="TableBody",e.s(["TableBody",()=>r],942232)},496020,e=>{"use strict";var t=e.i(290571),a=e.i(271645),i=e.i(444755);let n=(0,e.i(673706).makeClassName)("TableRow"),r=a.default.forwardRef((e,r)=>{let{children:l,className:o}=e,s=(0,t.__rest)(e,["children","className"]);return a.default.createElement(a.default.Fragment,null,a.default.createElement("tr",Object.assign({ref:r,className:(0,i.tremorTwMerge)(n("row"),o)},s),l))});r.displayName="TableRow",e.s(["TableRow",()=>r],496020)},977572,e=>{"use strict";var t=e.i(290571),a=e.i(271645),i=e.i(444755);let n=(0,e.i(673706).makeClassName)("TableCell"),r=a.default.forwardRef((e,r)=>{let{children:l,className:o}=e,s=(0,t.__rest)(e,["children","className"]);return a.default.createElement(a.default.Fragment,null,a.default.createElement("td",Object.assign({ref:r,className:(0,i.tremorTwMerge)(n("root"),"align-middle whitespace-nowrap text-left p-4",o)},s),l))});r.displayName="TableCell",e.s(["TableCell",()=>r],977572)},360820,e=>{"use strict";var t=e.i(271645);let a=t.forwardRef(function(e,a){return t.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:a},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 15l7-7 7 7"}))});e.s(["ChevronUpIcon",0,a],360820)},871943,e=>{"use strict";var t=e.i(271645);let a=t.forwardRef(function(e,a){return t.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:a},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"}))});e.s(["ChevronDownIcon",0,a],871943)},94629,e=>{"use strict";var t=e.i(271645);let a=t.forwardRef(function(e,a){return t.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:a},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4"}))});e.s(["SwitchVerticalIcon",0,a],94629)},991124,e=>{"use strict";let t=(0,e.i(475254).default)("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"}]]);e.s(["default",()=>t])},434626,e=>{"use strict";var t=e.i(271645);let a=t.forwardRef(function(e,a){return t.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:a},e),t.createElement("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"}))});e.s(["ExternalLinkIcon",0,a],434626)},100486,e=>{"use strict";e.i(247167);var t=e.i(931067),a=e.i(271645);let i={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M899.6 276.5L705 396.4 518.4 147.5a8.06 8.06 0 00-12.9 0L319 396.4 124.3 276.5c-5.7-3.5-13.1 1.2-12.2 7.9L188.5 865c1.1 7.9 7.9 14 16 14h615.1c8 0 14.9-6 15.9-14l76.4-580.6c.8-6.7-6.5-11.4-12.3-7.9zm-126 534.1H250.3l-53.8-409.4 139.8 86.1L512 252.9l175.7 234.4 139.8-86.1-53.9 409.4zM512 509c-62.1 0-112.6 50.5-112.6 112.6S449.9 734.2 512 734.2s112.6-50.5 112.6-112.6S574.1 509 512 509zm0 160.9c-26.6 0-48.2-21.6-48.2-48.3 0-26.6 21.6-48.3 48.2-48.3s48.2 21.6 48.2 48.3c0 26.6-21.6 48.3-48.2 48.3z"}}]},name:"crown",theme:"outlined"};var n=e.i(9583),r=a.forwardRef(function(e,r){return a.createElement(n.default,(0,t.default)({},e,{ref:r,icon:i}))});e.s(["CrownOutlined",0,r],100486)},798496,e=>{"use strict";var t=e.i(843476),a=e.i(152990),i=e.i(682830),n=e.i(271645),r=e.i(269200),l=e.i(427612),o=e.i(64848),s=e.i(942232),c=e.i(496020),d=e.i(977572),u=e.i(94629),m=e.i(360820),g=e.i(871943);function p({data:e=[],columns:p,isLoading:f=!1,defaultSorting:h=[],pagination:b,onPaginationChange:_,enablePagination:v=!1}){let[w,x]=n.default.useState(h),[y]=n.default.useState("onChange"),[E,j]=n.default.useState({}),[$,C]=n.default.useState({}),k=(0,a.useReactTable)({data:e,columns:p,state:{sorting:w,columnSizing:E,columnVisibility:$,...v&&b?{pagination:b}:{}},columnResizeMode:y,onSortingChange:x,onColumnSizingChange:j,onColumnVisibilityChange:C,...v&&_?{onPaginationChange:_}:{},getCoreRowModel:(0,i.getCoreRowModel)(),getSortedRowModel:(0,i.getSortedRowModel)(),...v?{getPaginationRowModel:(0,i.getPaginationRowModel)()}:{},enableSorting:!0,enableColumnResizing:!0,defaultColumn:{minSize:40,maxSize:500}});return(0,t.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,t.jsx)("div",{className:"overflow-x-auto",children:(0,t.jsx)("div",{className:"relative min-w-full",children:(0,t.jsxs)(r.Table,{className:"[&_td]:py-2 [&_th]:py-2",style:{width:k.getTotalSize(),minWidth:"100%",tableLayout:"fixed"},children:[(0,t.jsx)(l.TableHead,{children:k.getHeaderGroups().map(e=>(0,t.jsx)(c.TableRow,{children:e.headers.map(e=>(0,t.jsxs)(o.TableHeaderCell,{className:`py-1 h-8 relative ${"actions"===e.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)] w-[120px] ml-8":""} ${e.column.columnDef.meta?.className||""}`,style:{width:"actions"===e.id?120:e.getSize(),position:"actions"===e.id?"sticky":"relative",right:"actions"===e.id?0:"auto"},onClick:e.column.getCanSort()?e.column.getToggleSortingHandler():void 0,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,a.flexRender)(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)(m.ChevronUpIcon,{className:"h-4 w-4 text-blue-500"}),desc:(0,t.jsx)(g.ChevronDownIcon,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,t.jsx)(u.SwitchVerticalIcon,{className:"h-4 w-4 text-gray-400"})})]}),e.column.getCanResize()&&(0,t.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 ${e.column.getIsResizing()?"bg-blue-500":"hover:bg-blue-200"}`})]},e.id))},e.id))}),(0,t.jsx)(s.TableBody,{children:f?(0,t.jsx)(c.TableRow,{children:(0,t.jsx)(d.TableCell,{colSpan:p.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:"🚅 Loading models..."})})})}):k.getRowModel().rows.length>0?k.getRowModel().rows.map(e=>(0,t.jsx)(c.TableRow,{children:e.getVisibleCells().map(e=>(0,t.jsx)(d.TableCell,{className:`py-0.5 overflow-hidden ${"actions"===e.column.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)] w-[120px] ml-8":""} ${e.column.columnDef.meta?.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,a.flexRender)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,t.jsx)(c.TableRow,{children:(0,t.jsx)(d.TableCell,{colSpan:p.length,className:"h-8 text-center",children:(0,t.jsx)("div",{className:"text-center text-gray-500",children:(0,t.jsx)("p",{children:"No models found"})})})})})]})})})})}e.s(["ModelDataTable",()=>p])}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/5e885408342574d1.js b/litellm/proxy/_experimental/out/_next/static/chunks/5e885408342574d1.js deleted file mode 100644 index bcf83f8360e..00000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/5e885408342574d1.js +++ /dev/null @@ -1 +0,0 @@ -(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,757440,e=>{"use strict";var t=e.i(290571),r=e.i(271645);let a=e=>{var a=(0,t.__rest)(e,[]);return r.default.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"},a),r.default.createElement("path",{d:"M11.9999 13.1714L16.9497 8.22168L18.3639 9.63589L11.9999 15.9999L5.63599 9.63589L7.0502 8.22168L11.9999 13.1714Z"}))};e.s(["default",()=>a])},446428,854056,e=>{"use strict";let t;var r=e.i(290571),a=e.i(271645);let l=e=>{var t=(0,r.__rest)(e,[]);return a.default.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"},t),a.default.createElement("path",{d:"M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 10.5858L9.17157 7.75736L7.75736 9.17157L10.5858 12L7.75736 14.8284L9.17157 16.2426L12 13.4142L14.8284 16.2426L16.2426 14.8284L13.4142 12L16.2426 9.17157L14.8284 7.75736L12 10.5858Z"}))};e.s(["default",()=>l],446428);var n=e.i(746725),s=e.i(914189),i=e.i(553521),o=e.i(835696),d=e.i(941444),c=e.i(178677),u=e.i(294316),m=e.i(83733),f=e.i(233137),h=e.i(732607),p=e.i(397701),g=e.i(700020);function v(e){var t;return!!(e.enter||e.enterFrom||e.enterTo||e.leave||e.leaveFrom||e.leaveTo)||(null!=(t=e.as)?t:C)!==a.Fragment||1===a.default.Children.count(e.children)}let b=(0,a.createContext)(null);b.displayName="TransitionContext";var x=((t=x||{}).Visible="visible",t.Hidden="hidden",t);let y=(0,a.createContext)(null);function w(e){return"children"in e?w(e.children):e.current.filter(({el:e})=>null!==e.current).filter(({state:e})=>"visible"===e).length>0}function j(e,t){let r=(0,d.useLatestValue)(e),l=(0,a.useRef)([]),o=(0,i.useIsMounted)(),c=(0,n.useDisposables)(),u=(0,s.useEvent)((e,t=g.RenderStrategy.Hidden)=>{let a=l.current.findIndex(({el:t})=>t===e);-1!==a&&((0,p.match)(t,{[g.RenderStrategy.Unmount](){l.current.splice(a,1)},[g.RenderStrategy.Hidden](){l.current[a].state="hidden"}}),c.microTask(()=>{var e;!w(l)&&o.current&&(null==(e=r.current)||e.call(r))}))}),m=(0,s.useEvent)(e=>{let t=l.current.find(({el:t})=>t===e);return t?"visible"!==t.state&&(t.state="visible"):l.current.push({el:e,state:"visible"}),()=>u(e,g.RenderStrategy.Unmount)}),f=(0,a.useRef)([]),h=(0,a.useRef)(Promise.resolve()),v=(0,a.useRef)({enter:[],leave:[]}),b=(0,s.useEvent)((e,r,a)=>{f.current.splice(0),t&&(t.chains.current[r]=t.chains.current[r].filter(([t])=>t!==e)),null==t||t.chains.current[r].push([e,new Promise(e=>{f.current.push(e)})]),null==t||t.chains.current[r].push([e,new Promise(e=>{Promise.all(v.current[r].map(([e,t])=>t)).then(()=>e())})]),"enter"===r?h.current=h.current.then(()=>null==t?void 0:t.wait.current).then(()=>a(r)):a(r)}),x=(0,s.useEvent)((e,t,r)=>{Promise.all(v.current[t].splice(0).map(([e,t])=>t)).then(()=>{var e;null==(e=f.current.shift())||e()}).then(()=>r(t))});return(0,a.useMemo)(()=>({children:l,register:m,unregister:u,onStart:b,onStop:x,wait:h,chains:v}),[m,u,l,b,x,v,h])}y.displayName="NestingContext";let C=a.Fragment,E=g.RenderFeatures.RenderStrategy,N=(0,g.forwardRefWithAs)(function(e,t){let{show:r,appear:l=!1,unmount:n=!0,...i}=e,d=(0,a.useRef)(null),m=v(e),h=(0,u.useSyncRefs)(...m?[d,t]:null===t?[]:[t]);(0,c.useServerHandoffComplete)();let p=(0,f.useOpenClosed)();if(void 0===r&&null!==p&&(r=(p&f.State.Open)===f.State.Open),void 0===r)throw Error("A is used but it is missing a `show={true | false}` prop.");let[x,C]=(0,a.useState)(r?"visible":"hidden"),N=j(()=>{r||C("hidden")}),[k,T]=(0,a.useState)(!0),O=(0,a.useRef)([r]);(0,o.useIsoMorphicEffect)(()=>{!1!==k&&O.current[O.current.length-1]!==r&&(O.current.push(r),T(!1))},[O,r]);let M=(0,a.useMemo)(()=>({show:r,appear:l,initial:k}),[r,l,k]);(0,o.useIsoMorphicEffect)(()=>{r?C("visible"):w(N)||null===d.current||C("hidden")},[r,N]);let R={unmount:n},L=(0,s.useEvent)(()=>{var t;k&&T(!1),null==(t=e.beforeEnter)||t.call(e)}),A=(0,s.useEvent)(()=>{var t;k&&T(!1),null==(t=e.beforeLeave)||t.call(e)}),_=(0,g.useRender)();return a.default.createElement(y.Provider,{value:N},a.default.createElement(b.Provider,{value:M},_({ourProps:{...R,as:a.Fragment,children:a.default.createElement(S,{ref:h,...R,...i,beforeEnter:L,beforeLeave:A})},theirProps:{},defaultTag:a.Fragment,features:E,visible:"visible"===x,name:"Transition"})))}),S=(0,g.forwardRefWithAs)(function(e,t){var r,l;let{transition:n=!0,beforeEnter:i,afterEnter:d,beforeLeave:x,afterLeave:N,enter:S,enterFrom:k,enterTo:T,entered:O,leave:M,leaveFrom:R,leaveTo:L,...A}=e,[_,P]=(0,a.useState)(null),z=(0,a.useRef)(null),$=v(e),B=(0,u.useSyncRefs)(...$?[z,t,P]:null===t?[]:[t]),I=null==(r=A.unmount)||r?g.RenderStrategy.Unmount:g.RenderStrategy.Hidden,{show:D,appear:F,initial:V}=function(){let e=(0,a.useContext)(b);if(null===e)throw Error("A is used but it is missing a parent or .");return e}(),[H,W]=(0,a.useState)(D?"visible":"hidden"),U=function(){let e=(0,a.useContext)(y);if(null===e)throw Error("A is used but it is missing a parent or .");return e}(),{register:K,unregister:Z}=U;(0,o.useIsoMorphicEffect)(()=>K(z),[K,z]),(0,o.useIsoMorphicEffect)(()=>{if(I===g.RenderStrategy.Hidden&&z.current)return D&&"visible"!==H?void W("visible"):(0,p.match)(H,{hidden:()=>Z(z),visible:()=>K(z)})},[H,z,K,Z,D,I]);let q=(0,c.useServerHandoffComplete)();(0,o.useIsoMorphicEffect)(()=>{if($&&q&&"visible"===H&&null===z.current)throw Error("Did you forget to passthrough the `ref` to the actual DOM node?")},[z,H,q,$]);let J=V&&!F,Y=F&&D&&V,G=(0,a.useRef)(!1),Q=j(()=>{G.current||(W("hidden"),Z(z))},U),X=(0,s.useEvent)(e=>{G.current=!0,Q.onStart(z,e?"enter":"leave",e=>{"enter"===e?null==i||i():"leave"===e&&(null==x||x())})}),ee=(0,s.useEvent)(e=>{let t=e?"enter":"leave";G.current=!1,Q.onStop(z,t,e=>{"enter"===e?null==d||d():"leave"===e&&(null==N||N())}),"leave"!==t||w(Q)||(W("hidden"),Z(z))});(0,a.useEffect)(()=>{$&&n||(X(D),ee(D))},[D,$,n]);let et=!(!n||!$||!q||J),[,er]=(0,m.useTransition)(et,_,D,{start:X,end:ee}),ea=(0,g.compact)({ref:B,className:(null==(l=(0,h.classNames)(A.className,Y&&S,Y&&k,er.enter&&S,er.enter&&er.closed&&k,er.enter&&!er.closed&&T,er.leave&&M,er.leave&&!er.closed&&R,er.leave&&er.closed&&L,!er.transition&&D&&O))?void 0:l.trim())||void 0,...(0,m.transitionDataAttributes)(er)}),el=0;"visible"===H&&(el|=f.State.Open),"hidden"===H&&(el|=f.State.Closed),er.enter&&(el|=f.State.Opening),er.leave&&(el|=f.State.Closing);let en=(0,g.useRender)();return a.default.createElement(y.Provider,{value:Q},a.default.createElement(f.OpenClosedProvider,{value:el},en({ourProps:ea,theirProps:A,defaultTag:C,features:E,visible:"visible"===H,name:"Transition.Child"})))}),k=(0,g.forwardRefWithAs)(function(e,t){let r=null!==(0,a.useContext)(b),l=null!==(0,f.useOpenClosed)();return a.default.createElement(a.default.Fragment,null,!r&&l?a.default.createElement(N,{ref:t,...e}):a.default.createElement(S,{ref:t,...e}))}),T=Object.assign(N,{Child:k,Root:N});e.s(["Transition",()=>T],854056)},206929,e=>{"use strict";var t=e.i(290571),r=e.i(757440),a=e.i(271645),l=e.i(446428),n=e.i(444755),s=e.i(673706),i=e.i(103471),o=e.i(495470),d=e.i(854056),c=e.i(888288);let u=(0,s.makeClassName)("Select"),m=a.default.forwardRef((e,s)=>{let{defaultValue:m="",value:f,onValueChange:h,placeholder:p="Select...",disabled:g=!1,icon:v,enableClear:b=!1,required:x,children:y,name:w,error:j=!1,errorMessage:C,className:E,id:N}=e,S=(0,t.__rest)(e,["defaultValue","value","onValueChange","placeholder","disabled","icon","enableClear","required","children","name","error","errorMessage","className","id"]),k=(0,a.useRef)(null),T=a.Children.toArray(y),[O,M]=(0,c.default)(m,f),R=(0,a.useMemo)(()=>{let e=a.default.Children.toArray(y).filter(a.isValidElement);return(0,i.constructValueToNameMapping)(e)},[y]);return a.default.createElement("div",{className:(0,n.tremorTwMerge)("w-full min-w-[10rem] text-tremor-default",E)},a.default.createElement("div",{className:"relative"},a.default.createElement("select",{title:"select-hidden",required:x,className:(0,n.tremorTwMerge)("h-full w-full absolute left-0 top-0 -z-10 opacity-0"),value:O,onChange:e=>{e.preventDefault()},name:w,disabled:g,id:N,onFocus:()=>{let e=k.current;e&&e.focus()}},a.default.createElement("option",{className:"hidden",value:"",disabled:!0,hidden:!0},p),T.map(e=>{let t=e.props.value,r=e.props.children;return a.default.createElement("option",{className:"hidden",key:t,value:t},r)})),a.default.createElement(o.Listbox,Object.assign({as:"div",ref:s,defaultValue:O,value:O,onChange:e=>{null==h||h(e),M(e)},disabled:g,id:N},S),({value:e})=>{var t;return a.default.createElement(a.default.Fragment,null,a.default.createElement(o.ListboxButton,{ref:k,className:(0,n.tremorTwMerge)("w-full outline-none text-left whitespace-nowrap truncate rounded-tremor-default focus:ring-2 transition duration-100 border pr-8 py-2","border-tremor-border shadow-tremor-input focus:border-tremor-brand-subtle focus:ring-tremor-brand-muted","dark:border-dark-tremor-border dark:shadow-dark-tremor-input dark:focus:border-dark-tremor-brand-subtle dark:focus:ring-dark-tremor-brand-muted",v?"pl-10":"pl-3",(0,i.getSelectButtonColors)((0,i.hasValue)(e),g,j))},v&&a.default.createElement("span",{className:(0,n.tremorTwMerge)("absolute inset-y-0 left-0 flex items-center ml-px pl-2.5")},a.default.createElement(v,{className:(0,n.tremorTwMerge)(u("Icon"),"flex-none h-5 w-5","text-tremor-content-subtle","dark:text-dark-tremor-content-subtle")})),a.default.createElement("span",{className:"w-[90%] block truncate"},e&&null!=(t=R.get(e))?t:p),a.default.createElement("span",{className:(0,n.tremorTwMerge)("absolute inset-y-0 right-0 flex items-center mr-3")},a.default.createElement(r.default,{className:(0,n.tremorTwMerge)(u("arrowDownIcon"),"flex-none h-5 w-5","text-tremor-content-subtle","dark:text-dark-tremor-content-subtle")}))),b&&O?a.default.createElement("button",{type:"button",className:(0,n.tremorTwMerge)("absolute inset-y-0 right-0 flex items-center mr-8"),onClick:e=>{e.preventDefault(),M(""),null==h||h("")}},a.default.createElement(l.default,{className:(0,n.tremorTwMerge)(u("clearIcon"),"flex-none h-4 w-4","text-tremor-content-subtle","dark:text-dark-tremor-content-subtle")})):null,a.default.createElement(d.Transition,{enter:"transition ease duration-100 transform",enterFrom:"opacity-0 -translate-y-4",enterTo:"opacity-100 translate-y-0",leave:"transition ease duration-100 transform",leaveFrom:"opacity-100 translate-y-0",leaveTo:"opacity-0 -translate-y-4"},a.default.createElement(o.ListboxOptions,{anchor:"bottom start",className:(0,n.tremorTwMerge)("z-10 w-[var(--button-width)] divide-y overflow-y-auto outline-none rounded-tremor-default max-h-[228px] border [--anchor-gap:4px]","bg-tremor-background border-tremor-border divide-tremor-border shadow-tremor-dropdown","dark:bg-dark-tremor-background dark:border-dark-tremor-border dark:divide-dark-tremor-border dark:shadow-dark-tremor-dropdown")},y)))})),j&&C?a.default.createElement("p",{className:(0,n.tremorTwMerge)("errorMessage","text-sm text-rose-500 mt-1")},C):null)});m.displayName="Select",e.s(["Select",()=>m],206929)},987432,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let a={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M893.3 293.3L730.7 130.7c-7.5-7.5-16.7-13-26.7-16V112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V338.5c0-17-6.7-33.2-18.7-45.2zM384 184h256v104H384V184zm456 656H184V184h136v136c0 17.7 14.3 32 32 32h320c17.7 0 32-14.3 32-32V205.8l136 136V840zM512 442c-79.5 0-144 64.5-144 144s64.5 144 144 144 144-64.5 144-144-64.5-144-144-144zm0 224c-44.2 0-80-35.8-80-80s35.8-80 80-80 80 35.8 80 80-35.8 80-80 80z"}}]},name:"save",theme:"outlined"};var l=e.i(9583),n=r.forwardRef(function(e,n){return r.createElement(l.default,(0,t.default)({},e,{ref:n,icon:a}))});e.s(["SaveOutlined",0,n],987432)},91979,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let 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"};var l=e.i(9583),n=r.forwardRef(function(e,n){return r.createElement(l.default,(0,t.default)({},e,{ref:n,icon:a}))});e.s(["ReloadOutlined",0,n],91979)},969550,e=>{"use strict";var t=e.i(843476),r=e.i(271645);let a=r.forwardRef(function(e,t){return r.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:t},e),r.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",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"}))});var l=e.i(464571),n=e.i(311451),s=e.i(199133),i=e.i(374009);e.s(["default",0,({options:e,onApplyFilters:o,onResetFilters:d,initialValues:c={},buttonLabel:u="Filters"})=>{let[m,f]=(0,r.useState)(!1),[h,p]=(0,r.useState)(c),[g,v]=(0,r.useState)({}),[b,x]=(0,r.useState)({}),[y,w]=(0,r.useState)({}),[j,C]=(0,r.useState)({}),E=(0,r.useCallback)((0,i.default)(async(e,t)=>{if(t.isSearchable&&t.searchFn){x(e=>({...e,[t.name]:!0}));try{let r=await t.searchFn(e);v(e=>({...e,[t.name]:r}))}catch(e){console.error("Error searching:",e),v(e=>({...e,[t.name]:[]}))}finally{x(e=>({...e,[t.name]:!1}))}}},300),[]),N=(0,r.useCallback)(async e=>{if(e.isSearchable&&e.searchFn&&!j[e.name]){x(t=>({...t,[e.name]:!0})),C(t=>({...t,[e.name]:!0}));try{let t=await e.searchFn("");v(r=>({...r,[e.name]:t}))}catch(t){console.error("Error loading initial options:",t),v(t=>({...t,[e.name]:[]}))}finally{x(t=>({...t,[e.name]:!1}))}}},[j]);(0,r.useEffect)(()=>{m&&e.forEach(e=>{e.isSearchable&&!j[e.name]&&N(e)})},[m,e,N,j]);let S=(e,t)=>{let r={...h,[e]:t};p(r),o(r)};return(0,t.jsxs)("div",{className:"w-full",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 mb-6",children:[(0,t.jsx)(l.Button,{icon:(0,t.jsx)(a,{className:"h-4 w-4"}),onClick:()=>f(!m),className:"flex items-center gap-2",children:u}),(0,t.jsx)(l.Button,{onClick:()=>{let t={};e.forEach(e=>{t[e.name]=""}),p(t),d()},children:"Reset Filters"})]}),m&&(0,t.jsx)("div",{className:"grid grid-cols-3 gap-x-6 gap-y-4 mb-6",children:["Team ID","Status","Organization ID","Key Alias","User ID","End User","Error Code","Error Message","Key Hash","Model"].map(r=>{let a,l=e.find(e=>e.label===r||e.name===r);return l?(0,t.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,t.jsx)("label",{className:"text-sm text-gray-600",children:l.label||l.name}),l.isSearchable?(0,t.jsx)(s.Select,{showSearch:!0,className:"w-full",placeholder:`Search ${l.label||l.name}...`,value:h[l.name]||void 0,onChange:e=>S(l.name,e),onOpenChange:e=>{e&&l.isSearchable&&!j[l.name]&&N(l)},onSearch:e=>{w(t=>({...t,[l.name]:e})),l.searchFn&&E(e,l)},filterOption:!1,loading:b[l.name],options:g[l.name]||[],allowClear:!0,notFoundContent:b[l.name]?"Loading...":"No results found"}):l.options?(0,t.jsx)(s.Select,{className:"w-full",placeholder:`Select ${l.label||l.name}...`,value:h[l.name]||void 0,onChange:e=>S(l.name,e),allowClear:!0,children:l.options.map(e=>(0,t.jsx)(s.Select.Option,{value:e.value,children:e.label},e.value))}):l.customComponent?(a=l.customComponent,(0,t.jsx)(a,{value:h[l.name]||void 0,onChange:e=>S(l.name,e??""),placeholder:`Select ${l.label||l.name}...`})):(0,t.jsx)(n.Input,{className:"w-full",placeholder:`Enter ${l.label||l.name}...`,value:h[l.name]||"",onChange:e=>S(l.name,e.target.value),allowClear:!0})]},l.name):null})})]})}],969550)},633627,e=>{"use strict";var t=e.i(764205);let r=(e,t,r,a)=>{for(let l of e){let e=l?.key_alias;e&&"string"==typeof e&&t.add(e.trim());let n=l?.organization_id??l?.org_id;n&&"string"==typeof n&&r.add(n.trim());let s=l?.user_id;if(s&&"string"==typeof s){let e=l?.user?.user_email||s;a.set(s,e)}}},a=async(e,a)=>{if(!e||!a)return{keyAliases:[],organizationIds:[],userIds:[]};try{let l=new Set,n=new Set,s=new Map,i=await (0,t.keyListCall)(e,null,a,null,null,null,1,100,null,null,"user",null),o=i?.keys||[],d=i?.total_pages??1;r(o,l,n,s);let c=Math.min(d,10)-1;if(c>0){let i=Array.from({length:c},(r,l)=>(0,t.keyListCall)(e,null,a,null,null,null,l+2,100,null,null,"user",null));for(let e of(await Promise.allSettled(i)))"fulfilled"===e.status&&r(e.value?.keys||[],l,n,s)}return{keyAliases:Array.from(l).sort(),organizationIds:Array.from(n).sort(),userIds:Array.from(s.entries()).map(([e,t])=>({id:e,email:t}))}}catch(e){return console.error("Error fetching team filter options:",e),{keyAliases:[],organizationIds:[],userIds:[]}}},l=async(e,r)=>{if(!e)return[];try{let a=[],l=1,n=!0;for(;n;){let s=await (0,t.teamListCall)(e,r||null,null);a=[...a,...s],l{if(!e)return[];try{let r=[],a=1,l=!0;for(;l;){let n=await (0,t.organizationListCall)(e);r=[...r,...n],a{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4"}))});e.s(["SwitchVerticalIcon",0,r],94629)},991124,e=>{"use strict";let t=(0,e.i(475254).default)("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"}]]);e.s(["default",()=>t])},678784,678745,e=>{"use strict";let t=(0,e.i(475254).default)("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);e.s(["default",()=>t],678745),e.s(["CheckIcon",()=>t],678784)},118366,e=>{"use strict";var t=e.i(991124);e.s(["CopyIcon",()=>t.default])},829672,836938,310730,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(343794),a=e.i(914949),l=e.i(404948);let n=e=>e?"function"==typeof e?e():e:null;e.s(["getRenderPropValue",0,n],836938);var s=e.i(613541),i=e.i(763731),o=e.i(242064),d=e.i(491816);e.i(793154);var c=e.i(880476),u=e.i(183293),m=e.i(717356),f=e.i(320560),h=e.i(307358),p=e.i(246422),g=e.i(838378),v=e.i(617933);let b=(0,p.genStyleHooks)("Popover",e=>{let{colorBgElevated:t,colorText:r}=e,a=(0,g.mergeToken)(e,{popoverBg:t,popoverColor:r});return[(e=>{let{componentCls:t,popoverColor:r,titleMinWidth:a,fontWeightStrong:l,innerPadding:n,boxShadowSecondary:s,colorTextHeading:i,borderRadiusLG:o,zIndexPopup:d,titleMarginBottom:c,colorBgElevated:m,popoverBg:h,titleBorderBottom:p,innerContentPadding:g,titlePadding:v}=e;return[{[t]:Object.assign(Object.assign({},(0,u.resetComponent)(e)),{position:"absolute",top:0,left:{_skip_check_:!0,value:0},zIndex:d,fontWeight:"normal",whiteSpace:"normal",textAlign:"start",cursor:"auto",userSelect:"text","--valid-offset-x":"var(--arrow-offset-horizontal, var(--arrow-x))",transformOrigin:"var(--valid-offset-x, 50%) var(--arrow-y, 50%)","--antd-arrow-background-color":m,width:"max-content",maxWidth:"100vw","&-rtl":{direction:"rtl"},"&-hidden":{display:"none"},[`${t}-content`]:{position:"relative"},[`${t}-inner`]:{backgroundColor:h,backgroundClip:"padding-box",borderRadius:o,boxShadow:s,padding:n},[`${t}-title`]:{minWidth:a,marginBottom:c,color:i,fontWeight:l,borderBottom:p,padding:v},[`${t}-inner-content`]:{color:r,padding:g}})},(0,f.default)(e,"var(--antd-arrow-background-color)"),{[`${t}-pure`]:{position:"relative",maxWidth:"none",margin:e.sizePopupArrow,display:"inline-block",[`${t}-content`]:{display:"inline-block"}}}]})(a),(e=>{let{componentCls:t}=e;return{[t]:v.PresetColors.map(r=>{let a=e[`${r}6`];return{[`&${t}-${r}`]:{"--antd-arrow-background-color":a,[`${t}-inner`]:{backgroundColor:a},[`${t}-arrow`]:{background:"transparent"}}}})}})(a),(0,m.initZoomMotion)(a,"zoom-big")]},e=>{let{lineWidth:t,controlHeight:r,fontHeight:a,padding:l,wireframe:n,zIndexPopupBase:s,borderRadiusLG:i,marginXS:o,lineType:d,colorSplit:c,paddingSM:u}=e,m=r-a;return Object.assign(Object.assign(Object.assign({titleMinWidth:177,zIndexPopup:s+30},(0,h.getArrowToken)(e)),(0,f.getArrowOffsetToken)({contentRadius:i,limitVerticalRadius:!0})),{innerPadding:12*!n,titleMarginBottom:n?0:o,titlePadding:n?`${m/2}px ${l}px ${m/2-t}px`:0,titleBorderBottom:n?`${t}px ${d} ${c}`:"none",innerContentPadding:n?`${u}px ${l}px`:0})},{resetStyle:!1,deprecatedTokens:[["width","titleMinWidth"],["minWidth","titleMinWidth"]]});var x=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var l=0,a=Object.getOwnPropertySymbols(e);lt.indexOf(a[l])&&Object.prototype.propertyIsEnumerable.call(e,a[l])&&(r[a[l]]=e[a[l]]);return r};let y=({title:e,content:r,prefixCls:a})=>e||r?t.createElement(t.Fragment,null,e&&t.createElement("div",{className:`${a}-title`},e),r&&t.createElement("div",{className:`${a}-inner-content`},r)):null,w=e=>{let{hashId:a,prefixCls:l,className:s,style:i,placement:o="top",title:d,content:u,children:m}=e,f=n(d),h=n(u),p=(0,r.default)(a,l,`${l}-pure`,`${l}-placement-${o}`,s);return t.createElement("div",{className:p,style:i},t.createElement("div",{className:`${l}-arrow`}),t.createElement(c.Popup,Object.assign({},e,{className:a,prefixCls:l}),m||t.createElement(y,{prefixCls:l,title:f,content:h})))},j=e=>{let{prefixCls:a,className:l}=e,n=x(e,["prefixCls","className"]),{getPrefixCls:s}=t.useContext(o.ConfigContext),i=s("popover",a),[d,c,u]=b(i);return d(t.createElement(w,Object.assign({},n,{prefixCls:i,hashId:c,className:(0,r.default)(l,u)})))};e.s(["Overlay",0,y,"default",0,j],310730);var C=function(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(r[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var l=0,a=Object.getOwnPropertySymbols(e);lt.indexOf(a[l])&&Object.prototype.propertyIsEnumerable.call(e,a[l])&&(r[a[l]]=e[a[l]]);return r};let E=t.forwardRef((e,c)=>{var u,m;let{prefixCls:f,title:h,content:p,overlayClassName:g,placement:v="top",trigger:x="hover",children:w,mouseEnterDelay:j=.1,mouseLeaveDelay:E=.1,onOpenChange:N,overlayStyle:S={},styles:k,classNames:T}=e,O=C(e,["prefixCls","title","content","overlayClassName","placement","trigger","children","mouseEnterDelay","mouseLeaveDelay","onOpenChange","overlayStyle","styles","classNames"]),{getPrefixCls:M,className:R,style:L,classNames:A,styles:_}=(0,o.useComponentConfig)("popover"),P=M("popover",f),[z,$,B]=b(P),I=M(),D=(0,r.default)(g,$,B,R,A.root,null==T?void 0:T.root),F=(0,r.default)(A.body,null==T?void 0:T.body),[V,H]=(0,a.default)(!1,{value:null!=(u=e.open)?u:e.visible,defaultValue:null!=(m=e.defaultOpen)?m:e.defaultVisible}),W=(e,t)=>{H(e,!0),null==N||N(e,t)},U=n(h),K=n(p);return z(t.createElement(d.default,Object.assign({placement:v,trigger:x,mouseEnterDelay:j,mouseLeaveDelay:E},O,{prefixCls:P,classNames:{root:D,body:F},styles:{root:Object.assign(Object.assign(Object.assign(Object.assign({},_.root),L),S),null==k?void 0:k.root),body:Object.assign(Object.assign({},_.body),null==k?void 0:k.body)},ref:c,open:V,onOpenChange:e=>{W(e)},overlay:U||K?t.createElement(y,{prefixCls:P,title:U,content:K}):null,transitionName:(0,s.getTransitionName)(I,"zoom-big",O.transitionName),"data-popover-inject":!0}),(0,i.cloneElement)(w,{onKeyDown:e=>{var r,a;(0,t.isValidElement)(w)&&(null==(a=null==w?void 0:(r=w.props).onKeyDown)||a.call(r,e)),e.keyCode===l.default.ESC&&W(!1,e)}})))});E._InternalPanelDoNotUseOrYouWillBeFired=j,e.s(["default",0,E],829672)},282786,e=>{"use strict";var t=e.i(829672);e.s(["Popover",()=>t.default])},751904,e=>{"use strict";var t=e.i(401361);e.s(["EditOutlined",()=>t.default])},918549,e=>{"use strict";let t=(0,e.i(475254).default)("shield",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]]);e.s(["default",()=>t])},114600,e=>{"use strict";var t=e.i(290571),r=e.i(444755),a=e.i(673706),l=e.i(271645);let n=(0,a.makeClassName)("Divider"),s=l.default.forwardRef((e,a)=>{let{className:s,children:i}=e,o=(0,t.__rest)(e,["className","children"]);return l.default.createElement("div",Object.assign({ref:a,className:(0,r.tremorTwMerge)(n("root"),"w-full mx-auto my-6 flex justify-between gap-3 items-center text-tremor-default","text-tremor-content","dark:text-dark-tremor-content",s)},o),i?l.default.createElement(l.default.Fragment,null,l.default.createElement("div",{className:(0,r.tremorTwMerge)("w-full h-[1px] bg-tremor-border dark:bg-dark-tremor-border")}),l.default.createElement("div",{className:(0,r.tremorTwMerge)("text-inherit whitespace-nowrap")},i),l.default.createElement("div",{className:(0,r.tremorTwMerge)("w-full h-[1px] bg-tremor-border dark:bg-dark-tremor-border")})):l.default.createElement("div",{className:(0,r.tremorTwMerge)("w-full h-[1px] bg-tremor-border dark:bg-dark-tremor-border")}))});s.displayName="Divider",e.s(["Divider",()=>s],114600)},584578,e=>{"use strict";var t=e.i(764205);let r=async(e,r,a,l,n)=>{let s;s="Admin"!=a&&"Admin Viewer"!=a?await (0,t.teamListCall)(e,l?.organization_id||null,r):await (0,t.teamListCall)(e,l?.organization_id||null),console.log(`givenTeams: ${s}`),n(s)};e.s(["fetchTeams",0,r])},468133,e=>{"use strict";var t=e.i(843476),r=e.i(271645),a=e.i(304967),l=e.i(629569),n=e.i(599724),s=e.i(114600),i=e.i(994388),o=e.i(779241),d=e.i(898586),c=e.i(482725),u=e.i(790848),m=e.i(199133),f=e.i(764205),h=e.i(860585),p=e.i(355619),g=e.i(727749),v=e.i(162386);e.s(["default",0,({accessToken:e,userID:b,userRole:x})=>{let[y,w]=(0,r.useState)(!0),[j,C]=(0,r.useState)(null),[E,N]=(0,r.useState)(!1),[S,k]=(0,r.useState)({}),[T,O]=(0,r.useState)(!1),[M,R]=(0,r.useState)([]),{Paragraph:L}=d.Typography,{Option:A}=m.Select;(0,r.useEffect)(()=>{(async()=>{if(!e)return w(!1);try{let t=await (0,f.getDefaultTeamSettings)(e);if(C(t),k(t.values||{}),e)try{let t=await (0,f.modelAvailableCall)(e,b,x);if(t&&t.data){let e=t.data.map(e=>e.id);R(e)}}catch(e){console.error("Error fetching available models:",e)}}catch(e){console.error("Error fetching team SSO settings:",e),g.default.fromBackend("Failed to fetch team settings")}finally{w(!1)}})()},[e]);let _=async()=>{if(e){O(!0);try{let t=await (0,f.updateDefaultTeamSettings)(e,S);C({...j,values:t.settings}),N(!1),g.default.success("Default team settings updated successfully")}catch(e){console.error("Error updating team settings:",e),g.default.fromBackend("Failed to update team settings")}finally{O(!1)}}},P=(e,t)=>{k(r=>({...r,[e]:t}))};return y?(0,t.jsx)("div",{className:"flex justify-center items-center h-64",children:(0,t.jsx)(c.Spin,{size:"large"})}):j?(0,t.jsxs)(a.Card,{children:[(0,t.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,t.jsx)(l.Title,{className:"text-xl",children:"Default Team Settings"}),!y&&j&&(E?(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(i.Button,{variant:"secondary",onClick:()=>{N(!1),k(j.values||{})},disabled:T,children:"Cancel"}),(0,t.jsx)(i.Button,{onClick:_,loading:T,children:"Save Changes"})]}):(0,t.jsx)(i.Button,{onClick:()=>N(!0),children:"Edit Settings"}))]}),(0,t.jsx)(n.Text,{children:"These settings will be applied by default when creating new teams."}),j?.field_schema?.description&&(0,t.jsx)(L,{className:"mb-4 mt-2",children:j.field_schema.description}),(0,t.jsx)(s.Divider,{}),(0,t.jsx)("div",{className:"mt-4 space-y-4",children:(()=>{let{values:e,field_schema:r}=j;return r&&r.properties?Object.entries(r.properties).map(([r,a])=>{let l=e[r],s=r.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)(n.Text,{className:"font-medium text-lg",children:s}),(0,t.jsx)(L,{className:"text-sm text-gray-500 mt-1",children:a.description||"No description available"}),E?(0,t.jsx)("div",{className:"mt-2",children:((e,r,a)=>{let l=r.type;if("budget_duration"===e)return(0,t.jsx)(h.default,{value:S[e]||null,onChange:t=>P(e,t),className:"mt-2"});if("boolean"===l)return(0,t.jsx)("div",{className:"mt-2",children:(0,t.jsx)(u.Switch,{checked:!!S[e],onChange:t=>P(e,t)})});if("array"===l&&r.items?.enum)return(0,t.jsx)(m.Select,{mode:"multiple",style:{width:"100%"},value:S[e]||[],onChange:t=>P(e,t),className:"mt-2",children:r.items.enum.map(e=>(0,t.jsx)(A,{value:e,children:e},e))});if("models"===e)return(0,t.jsx)(v.ModelSelect,{value:S[e]||[],onChange:t=>P(e,t),context:"global",style:{width:"100%"},options:{includeSpecialOptions:!0}});if("string"===l&&r.enum)return(0,t.jsx)(m.Select,{style:{width:"100%"},value:S[e]||"",onChange:t=>P(e,t),className:"mt-2",children:r.enum.map(e=>(0,t.jsx)(A,{value:e,children:e},e))});else return(0,t.jsx)(o.TextInput,{value:void 0!==S[e]?String(S[e]):"",onChange:t=>P(e,t.target.value),placeholder:r.description||"",className:"mt-2"})})(r,a,0)}):(0,t.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:((e,r)=>{if(null==r)return(0,t.jsx)("span",{className:"text-gray-400",children:"Not set"});if("budget_duration"===e)return(0,t.jsx)("span",{children:(0,h.getBudgetDurationLabel)(r)});if("boolean"==typeof r)return(0,t.jsx)("span",{children:r?"Enabled":"Disabled"});if("models"===e&&Array.isArray(r))return 0===r.length?(0,t.jsx)("span",{className:"text-gray-400",children:"None"}):(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:r.map((e,r)=>(0,t.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:(0,p.getModelDisplayName)(e)},r))});if("object"==typeof r)return Array.isArray(r)?0===r.length?(0,t.jsx)("span",{className:"text-gray-400",children:"None"}):(0,t.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:r.map((e,r)=>(0,t.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:"object"==typeof e?JSON.stringify(e):String(e)},r))}):(0,t.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify(r,null,2)});return(0,t.jsx)("span",{children:String(r)})})(r,l)})]},r)}):(0,t.jsx)(n.Text,{children:"No schema information available"})})()})]}):(0,t.jsx)(a.Card,{children:(0,t.jsx)(n.Text,{children:"No team settings available or you do not have permission to view them."})})}])},747871,e=>{"use strict";var t=e.i(843476),r=e.i(271645),a=e.i(269200),l=e.i(942232),n=e.i(977572),s=e.i(427612),i=e.i(64848),o=e.i(496020),d=e.i(304967),c=e.i(994388),u=e.i(599724),m=e.i(389083),f=e.i(764205),h=e.i(727749);e.s(["default",0,({accessToken:e,userID:p})=>{let[g,v]=(0,r.useState)([]);(0,r.useEffect)(()=>{(async()=>{if(e&&p)try{let t=await (0,f.availableTeamListCall)(e);v(t)}catch(e){console.error("Error fetching available teams:",e)}})()},[e,p]);let b=async t=>{if(e&&p)try{await (0,f.teamMemberAddCall)(e,t,{user_id:p,role:"user"}),h.default.success("Successfully joined team"),v(e=>e.filter(e=>e.team_id!==t))}catch(e){console.error("Error joining team:",e),h.default.fromBackend("Failed to join team")}};return(0,t.jsx)(d.Card,{className:"w-full mx-auto flex-auto overflow-y-auto max-h-[50vh]",children:(0,t.jsxs)(a.Table,{children:[(0,t.jsx)(s.TableHead,{children:(0,t.jsxs)(o.TableRow,{children:[(0,t.jsx)(i.TableHeaderCell,{children:"Team Name"}),(0,t.jsx)(i.TableHeaderCell,{children:"Description"}),(0,t.jsx)(i.TableHeaderCell,{children:"Members"}),(0,t.jsx)(i.TableHeaderCell,{children:"Models"}),(0,t.jsx)(i.TableHeaderCell,{children:"Actions"})]})}),(0,t.jsxs)(l.TableBody,{children:[g.map(e=>(0,t.jsxs)(o.TableRow,{children:[(0,t.jsx)(n.TableCell,{children:(0,t.jsx)(u.Text,{children:e.team_alias})}),(0,t.jsx)(n.TableCell,{children:(0,t.jsx)(u.Text,{children:e.description||"No description available"})}),(0,t.jsx)(n.TableCell,{children:(0,t.jsxs)(u.Text,{children:[e.members_with_roles.length," members"]})}),(0,t.jsx)(n.TableCell,{children:(0,t.jsx)("div",{className:"flex flex-col",children:e.models&&0!==e.models.length?e.models.map((e,r)=>(0,t.jsx)(m.Badge,{size:"xs",className:"mb-1",color:"blue",children:(0,t.jsx)(u.Text,{children:e.length>30?`${e.slice(0,30)}...`:e})},r)):(0,t.jsx)(m.Badge,{size:"xs",color:"red",children:(0,t.jsx)(u.Text,{children:"All Proxy Models"})})})}),(0,t.jsx)(n.TableCell,{children:(0,t.jsx)(c.Button,{size:"xs",variant:"secondary",onClick:()=>b(e.team_id),children:"Join Team"})})]},e.team_id)),0===g.length&&(0,t.jsx)(o.TableRow,{children:(0,t.jsx)(n.TableCell,{colSpan:5,className:"text-center",children:(0,t.jsxs)(u.Text,{children:["No available teams to join. See how to set available teams"," ",(0,t.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/self_serve#all-settings-for-self-serve--sso-flow",target:"_blank",rel:"noopener noreferrer",className:"text-blue-500 hover:text-blue-700 underline",children:"here"}),"."]})})})]})]})})}])}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/5ec157703332dbc8.js b/litellm/proxy/_experimental/out/_next/static/chunks/5ec157703332dbc8.js new file mode 100644 index 00000000000..345ee2ef9bd --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/5ec157703332dbc8.js @@ -0,0 +1,8 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,955135,e=>{"use strict";var t=e.i(597440);e.s(["DeleteOutlined",()=>t.default])},309821,e=>{"use strict";e.i(247167);var t=e.i(271645);e.i(262370);var r=e.i(135551),n=e.i(201072),o=e.i(121229),i=e.i(726289),a=e.i(864517),l=e.i(343794),s=e.i(529681),c=e.i(242064),d=e.i(931067),u=e.i(209428),f=e.i(703923),m={percent:0,prefixCls:"rc-progress",strokeColor:"#2db7f5",strokeLinecap:"round",strokeWidth:1,trailColor:"#D9D9D9",trailWidth:1,gapPosition:"bottom"},p=function(){var e=(0,t.useRef)([]),r=(0,t.useRef)(null);return(0,t.useEffect)(function(){var t=Date.now(),n=!1;e.current.forEach(function(e){if(e){n=!0;var o=e.style;o.transitionDuration=".3s, .3s, .3s, .06s",r.current&&t-r.current<100&&(o.transitionDuration="0s, 0s")}}),n&&(r.current=Date.now())}),e.current},g=e.i(410160),h=e.i(392221),b=e.i(654310),v=0,y=(0,b.default)();let x=function(e){var r=t.useState(),n=(0,h.default)(r,2),o=n[0],i=n[1];return t.useEffect(function(){var e;i("rc_progress_".concat((y?(e=v,v+=1):e="TEST_OR_SSR",e)))},[]),e||o};var k=function(e){var r=e.bg,n=e.children;return t.createElement("div",{style:{width:"100%",height:"100%",background:r}},n)};function C(e,t){return Object.keys(e).map(function(r){var n=parseFloat(r),o="".concat(Math.floor(n*t),"%");return"".concat(e[r]," ").concat(o)})}var w=t.forwardRef(function(e,r){var n=e.prefixCls,o=e.color,i=e.gradientId,a=e.radius,l=e.style,s=e.ptg,c=e.strokeLinecap,d=e.strokeWidth,u=e.size,f=e.gapDegree,m=o&&"object"===(0,g.default)(o),p=u/2,h=t.createElement("circle",{className:"".concat(n,"-circle-path"),r:a,cx:p,cy:p,stroke:m?"#FFF":void 0,strokeLinecap:c,strokeWidth:d,opacity:+(0!==s),style:l,ref:r});if(!m)return h;var b="".concat(i,"-conic"),v=C(o,(360-f)/360),y=C(o,1),x="conic-gradient(from ".concat(f?"".concat(180+f/2,"deg"):"0deg",", ").concat(v.join(", "),")"),w="linear-gradient(to ".concat(f?"bottom":"top",", ").concat(y.join(", "),")");return t.createElement(t.Fragment,null,t.createElement("mask",{id:b},h),t.createElement("foreignObject",{x:0,y:0,width:u,height:u,mask:"url(#".concat(b,")")},t.createElement(k,{bg:w},t.createElement(k,{bg:x}))))}),S=function(e,t,r,n,o,i,a,l,s,c){var d=arguments.length>10&&void 0!==arguments[10]?arguments[10]:0,u=(100-n)/100*t;return"round"===s&&100!==n&&(u+=c/2)>=t&&(u=t-.01),{stroke:"string"==typeof l?l:void 0,strokeDasharray:"".concat(t,"px ").concat(e),strokeDashoffset:u+d,transform:"rotate(".concat(o+r/100*360*((360-i)/360)+(0===i?0:({bottom:0,top:180,left:90,right:-90})[a]),"deg)"),transformOrigin:"".concat(50,"px ").concat(50,"px"),transition:"stroke-dashoffset .3s ease 0s, stroke-dasharray .3s ease 0s, stroke .3s, stroke-width .06s ease .3s, opacity .3s ease 0s",fillOpacity:0}},E=["id","prefixCls","steps","strokeWidth","trailWidth","gapDegree","gapPosition","trailColor","strokeLinecap","style","className","strokeColor","percent"];function j(e){var t=null!=e?e:[];return Array.isArray(t)?t:[t]}let _=function(e){var r,n,o,i,a=(0,u.default)((0,u.default)({},m),e),s=a.id,c=a.prefixCls,h=a.steps,b=a.strokeWidth,v=a.trailWidth,y=a.gapDegree,k=void 0===y?0:y,C=a.gapPosition,_=a.trailColor,N=a.strokeLinecap,O=a.style,$=a.className,T=a.strokeColor,M=a.percent,R=(0,f.default)(a,E),P=x(s),I="".concat(P,"-gradient"),D=50-b/2,L=2*Math.PI*D,F=k>0?90+k/2:-90,z=(360-k)/360*L,A="object"===(0,g.default)(h)?h:{count:h,gap:2},B=A.count,H=A.gap,q=j(M),W=j(T),K=W.find(function(e){return e&&"object"===(0,g.default)(e)}),U=K&&"object"===(0,g.default)(K)?"butt":N,X=S(L,z,0,100,F,k,C,_,U,b),G=p();return t.createElement("svg",(0,d.default)({className:(0,l.default)("".concat(c,"-circle"),$),viewBox:"0 0 ".concat(100," ").concat(100),style:O,id:s,role:"presentation"},R),!B&&t.createElement("circle",{className:"".concat(c,"-circle-trail"),r:D,cx:50,cy:50,stroke:_,strokeLinecap:U,strokeWidth:v||b,style:X}),B?(r=Math.round(B*(q[0]/100)),n=100/B,o=0,Array(B).fill(null).map(function(e,i){var a=i<=r-1?W[0]:_,l=a&&"object"===(0,g.default)(a)?"url(#".concat(I,")"):void 0,s=S(L,z,o,n,F,k,C,a,"butt",b,H);return o+=(z-s.strokeDashoffset+H)*100/z,t.createElement("circle",{key:i,className:"".concat(c,"-circle-path"),r:D,cx:50,cy:50,stroke:l,strokeWidth:b,opacity:1,style:s,ref:function(e){G[i]=e}})})):(i=0,q.map(function(e,r){var n=W[r]||W[W.length-1],o=S(L,z,i,e,F,k,C,n,U,b);return i+=e,t.createElement(w,{key:r,color:n,ptg:e,radius:D,prefixCls:c,gradientId:I,style:o,strokeLinecap:U,strokeWidth:b,gapDegree:k,ref:function(e){G[r]=e},size:100})}).reverse()))};var N=e.i(491816);e.i(765846);var O=e.i(896091);function $(e){return!e||e<0?0:e>100?100:e}function T({success:e,successPercent:t}){let r=t;return e&&"progress"in e&&(r=e.progress),e&&"percent"in e&&(r=e.percent),r}let M=(e,t,r)=>{var n,o,i,a;let l=-1,s=-1;if("step"===t){let t=r.steps,n=r.strokeWidth;"string"==typeof e||void 0===e?(l="small"===e?2:14,s=null!=n?n:8):"number"==typeof e?[l,s]=[e,e]:[l=14,s=8]=Array.isArray(e)?e:[e.width,e.height],l*=t}else if("line"===t){let t=null==r?void 0:r.strokeWidth;"string"==typeof e||void 0===e?s=t||("small"===e?6:8):"number"==typeof e?[l,s]=[e,e]:[l=-1,s=8]=Array.isArray(e)?e:[e.width,e.height]}else("circle"===t||"dashboard"===t)&&("string"==typeof e||void 0===e?[l,s]="small"===e?[60,60]:[120,120]:"number"==typeof e?[l,s]=[e,e]:Array.isArray(e)&&(l=null!=(o=null!=(n=e[0])?n:e[1])?o:120,s=null!=(a=null!=(i=e[0])?i:e[1])?a:120));return[l,s]},R=e=>{let{prefixCls:r,trailColor:n=null,strokeLinecap:o="round",gapPosition:i,gapDegree:a,width:s=120,type:c,children:d,success:u,size:f=s,steps:m}=e,[p,g]=M(f,"circle"),{strokeWidth:h}=e;void 0===h&&(h=Math.max(3/p*100,6));let b=t.useMemo(()=>a||0===a?a:"dashboard"===c?75:void 0,[a,c]),v=(({percent:e,success:t,successPercent:r})=>{let n=$(T({success:t,successPercent:r}));return[n,$($(e)-n)]})(e),y="[object Object]"===Object.prototype.toString.call(e.strokeColor),x=(({success:e={},strokeColor:t})=>{let{strokeColor:r}=e;return[r||O.presetPrimaryColors.green,t||null]})({success:u,strokeColor:e.strokeColor}),k=(0,l.default)(`${r}-inner`,{[`${r}-circle-gradient`]:y}),C=t.createElement(_,{steps:m,percent:m?v[1]:v,strokeWidth:h,trailWidth:h,strokeColor:m?x[1]:x,strokeLinecap:o,trailColor:n,prefixCls:r,gapDegree:b,gapPosition:i||"dashboard"===c&&"bottom"||void 0}),w=p<=20,S=t.createElement("div",{className:k,style:{width:p,height:g,fontSize:.15*p+6}},C,!w&&d);return w?t.createElement(N.default,{title:d},S):S};e.i(296059);var P=e.i(694758),I=e.i(915654),D=e.i(183293),L=e.i(246422),F=e.i(838378);let z="--progress-line-stroke-color",A="--progress-percent",B=e=>{let t=e?"100%":"-100%";return new P.Keyframes(`antProgress${e?"RTL":"LTR"}Active`,{"0%":{transform:`translateX(${t}) scaleX(0)`,opacity:.1},"20%":{transform:`translateX(${t}) scaleX(0)`,opacity:.5},to:{transform:"translateX(0) scaleX(1)",opacity:0}})},H=(0,L.genStyleHooks)("Progress",e=>{let t=e.calc(e.marginXXS).div(2).equal(),r=(0,F.mergeToken)(e,{progressStepMarginInlineEnd:t,progressStepMinWidth:t,progressActiveMotionDuration:"2.4s"});return[(e=>{let{componentCls:t,iconCls:r}=e;return{[t]:Object.assign(Object.assign({},(0,D.resetComponent)(e)),{display:"inline-block","&-rtl":{direction:"rtl"},"&-line":{position:"relative",width:"100%",fontSize:e.fontSize},[`${t}-outer`]:{display:"inline-flex",alignItems:"center",width:"100%"},[`${t}-inner`]:{position:"relative",display:"inline-block",width:"100%",flex:1,overflow:"hidden",verticalAlign:"middle",backgroundColor:e.remainingColor,borderRadius:e.lineBorderRadius},[`${t}-inner:not(${t}-circle-gradient)`]:{[`${t}-circle-path`]:{stroke:e.defaultColor}},[`${t}-success-bg, ${t}-bg`]:{position:"relative",background:e.defaultColor,borderRadius:e.lineBorderRadius,transition:`all ${e.motionDurationSlow} ${e.motionEaseInOutCirc}`},[`${t}-layout-bottom`]:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",[`${t}-text`]:{width:"max-content",marginInlineStart:0,marginTop:e.marginXXS}},[`${t}-bg`]:{overflow:"hidden","&::after":{content:'""',background:{_multi_value_:!0,value:["inherit",`var(${z})`]},height:"100%",width:`calc(1 / var(${A}) * 100%)`,display:"block"},[`&${t}-bg-inner`]:{minWidth:"max-content","&::after":{content:"none"},[`${t}-text-inner`]:{color:e.colorWhite,[`&${t}-text-bright`]:{color:"rgba(0, 0, 0, 0.45)"}}}},[`${t}-success-bg`]:{position:"absolute",insetBlockStart:0,insetInlineStart:0,backgroundColor:e.colorSuccess},[`${t}-text`]:{display:"inline-block",marginInlineStart:e.marginXS,color:e.colorText,lineHeight:1,width:"2em",whiteSpace:"nowrap",textAlign:"start",verticalAlign:"middle",wordBreak:"normal",[r]:{fontSize:e.fontSize},[`&${t}-text-outer`]:{width:"max-content"},[`&${t}-text-outer${t}-text-start`]:{width:"max-content",marginInlineStart:0,marginInlineEnd:e.marginXS}},[`${t}-text-inner`]:{display:"flex",justifyContent:"center",alignItems:"center",width:"100%",height:"100%",marginInlineStart:0,padding:`0 ${(0,I.unit)(e.paddingXXS)}`,[`&${t}-text-start`]:{justifyContent:"start"},[`&${t}-text-end`]:{justifyContent:"end"}},[`&${t}-status-active`]:{[`${t}-bg::before`]:{position:"absolute",inset:0,backgroundColor:e.colorBgContainer,borderRadius:e.lineBorderRadius,opacity:0,animationName:B(),animationDuration:e.progressActiveMotionDuration,animationTimingFunction:e.motionEaseOutQuint,animationIterationCount:"infinite",content:'""'}},[`&${t}-rtl${t}-status-active`]:{[`${t}-bg::before`]:{animationName:B(!0)}},[`&${t}-status-exception`]:{[`${t}-bg`]:{backgroundColor:e.colorError},[`${t}-text`]:{color:e.colorError}},[`&${t}-status-exception ${t}-inner:not(${t}-circle-gradient)`]:{[`${t}-circle-path`]:{stroke:e.colorError}},[`&${t}-status-success`]:{[`${t}-bg`]:{backgroundColor:e.colorSuccess},[`${t}-text`]:{color:e.colorSuccess}},[`&${t}-status-success ${t}-inner:not(${t}-circle-gradient)`]:{[`${t}-circle-path`]:{stroke:e.colorSuccess}}})}})(r),(e=>{let{componentCls:t,iconCls:r}=e;return{[t]:{[`${t}-circle-trail`]:{stroke:e.remainingColor},[`&${t}-circle ${t}-inner`]:{position:"relative",lineHeight:1,backgroundColor:"transparent"},[`&${t}-circle ${t}-text`]:{position:"absolute",insetBlockStart:"50%",insetInlineStart:0,width:"100%",margin:0,padding:0,color:e.circleTextColor,fontSize:e.circleTextFontSize,lineHeight:1,whiteSpace:"normal",textAlign:"center",transform:"translateY(-50%)",[r]:{fontSize:e.circleIconFontSize}},[`${t}-circle&-status-exception`]:{[`${t}-text`]:{color:e.colorError}},[`${t}-circle&-status-success`]:{[`${t}-text`]:{color:e.colorSuccess}}},[`${t}-inline-circle`]:{lineHeight:1,[`${t}-inner`]:{verticalAlign:"bottom"}}}})(r),(e=>{let{componentCls:t}=e;return{[t]:{[`${t}-steps`]:{display:"inline-block","&-outer":{display:"flex",flexDirection:"row",alignItems:"center"},"&-item":{flexShrink:0,minWidth:e.progressStepMinWidth,marginInlineEnd:e.progressStepMarginInlineEnd,backgroundColor:e.remainingColor,transition:`all ${e.motionDurationSlow}`,"&-active":{backgroundColor:e.defaultColor}}}}}})(r),(e=>{let{componentCls:t,iconCls:r}=e;return{[t]:{[`${t}-small&-line, ${t}-small&-line ${t}-text ${r}`]:{fontSize:e.fontSizeSM}}}})(r)]},e=>({circleTextColor:e.colorText,defaultColor:e.colorInfo,remainingColor:e.colorFillSecondary,lineBorderRadius:100,circleTextFontSize:"1em",circleIconFontSize:`${e.fontSize/e.fontSizeSM}em`}));var q=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&0>t.indexOf(n)&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,n=Object.getOwnPropertySymbols(e);ot.indexOf(n[o])&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(r[n[o]]=e[n[o]]);return r};let W=e=>{let{prefixCls:r,direction:n,percent:o,size:i,strokeWidth:a,strokeColor:s,strokeLinecap:c="round",children:d,trailColor:u=null,percentPosition:f,success:m}=e,{align:p,type:g}=f,h=s&&"string"!=typeof s?((e,t)=>{let{from:r=O.presetPrimaryColors.blue,to:n=O.presetPrimaryColors.blue,direction:o="rtl"===t?"to left":"to right"}=e,i=q(e,["from","to","direction"]);if(0!==Object.keys(i).length){let e,t=(e=[],Object.keys(i).forEach(t=>{let r=Number.parseFloat(t.replace(/%/g,""));Number.isNaN(r)||e.push({key:r,value:i[t]})}),(e=e.sort((e,t)=>e.key-t.key)).map(({key:e,value:t})=>`${t} ${e}%`).join(", ")),r=`linear-gradient(${o}, ${t})`;return{background:r,[z]:r}}let a=`linear-gradient(${o}, ${r}, ${n})`;return{background:a,[z]:a}})(s,n):{[z]:s,background:s},b="square"===c||"butt"===c?0:void 0,[v,y]=M(null!=i?i:[-1,a||("small"===i?6:8)],"line",{strokeWidth:a}),x=Object.assign(Object.assign({width:`${$(o)}%`,height:y,borderRadius:b},h),{[A]:$(o)/100}),k=T(e),C={width:`${$(k)}%`,height:y,borderRadius:b,backgroundColor:null==m?void 0:m.strokeColor},w=t.createElement("div",{className:`${r}-inner`,style:{backgroundColor:u||void 0,borderRadius:b}},t.createElement("div",{className:(0,l.default)(`${r}-bg`,`${r}-bg-${g}`),style:x},"inner"===g&&d),void 0!==k&&t.createElement("div",{className:`${r}-success-bg`,style:C})),S="outer"===g&&"start"===p,E="outer"===g&&"end"===p;return"outer"===g&&"center"===p?t.createElement("div",{className:`${r}-layout-bottom`},w,d):t.createElement("div",{className:`${r}-outer`,style:{width:v<0?"100%":v}},S&&d,w,E&&d)},K=e=>{let{size:r,steps:n,rounding:o=Math.round,percent:i=0,strokeWidth:a=8,strokeColor:s,trailColor:c=null,prefixCls:d,children:u}=e,f=o(i/100*n),[m,p]=M(null!=r?r:["small"===r?2:14,a],"step",{steps:n,strokeWidth:a}),g=m/n,h=Array.from({length:n});for(let e=0;et.indexOf(n)&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,n=Object.getOwnPropertySymbols(e);ot.indexOf(n[o])&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(r[n[o]]=e[n[o]]);return r};let X=["normal","exception","active","success"],G=t.forwardRef((e,d)=>{let u,{prefixCls:f,className:m,rootClassName:p,steps:g,strokeColor:h,percent:b=0,size:v="default",showInfo:y=!0,type:x="line",status:k,format:C,style:w,percentPosition:S={}}=e,E=U(e,["prefixCls","className","rootClassName","steps","strokeColor","percent","size","showInfo","type","status","format","style","percentPosition"]),{align:j="end",type:_="outer"}=S,N=Array.isArray(h)?h[0]:h,O="string"==typeof h||Array.isArray(h)?h:void 0,P=t.useMemo(()=>{if(N){let e="string"==typeof N?N:Object.values(N)[0];return new r.FastColor(e).isLight()}return!1},[h]),I=t.useMemo(()=>{var t,r;let n=T(e);return Number.parseInt(void 0!==n?null==(t=null!=n?n:0)?void 0:t.toString():null==(r=null!=b?b:0)?void 0:r.toString(),10)},[b,e.success,e.successPercent]),D=t.useMemo(()=>!X.includes(k)&&I>=100?"success":k||"normal",[k,I]),{getPrefixCls:L,direction:F,progress:z}=t.useContext(c.ConfigContext),A=L("progress",f),[B,q,G]=H(A),V="line"===x,Q=V&&!g,Y=t.useMemo(()=>{let r;if(!y)return null;let s=T(e),c=C||(e=>`${e}%`),d=V&&P&&"inner"===_;return"inner"===_||C||"exception"!==D&&"success"!==D?r=c($(b),$(s)):"exception"===D?r=V?t.createElement(i.default,null):t.createElement(a.default,null):"success"===D&&(r=V?t.createElement(n.default,null):t.createElement(o.default,null)),t.createElement("span",{className:(0,l.default)(`${A}-text`,{[`${A}-text-bright`]:d,[`${A}-text-${j}`]:Q,[`${A}-text-${_}`]:Q}),title:"string"==typeof r?r:void 0},r)},[y,b,I,D,x,A,C]);"line"===x?u=g?t.createElement(K,Object.assign({},e,{strokeColor:O,prefixCls:A,steps:"object"==typeof g?g.count:g}),Y):t.createElement(W,Object.assign({},e,{strokeColor:N,prefixCls:A,direction:F,percentPosition:{align:j,type:_}}),Y):("circle"===x||"dashboard"===x)&&(u=t.createElement(R,Object.assign({},e,{strokeColor:N,prefixCls:A,progressStatus:D}),Y));let J=(0,l.default)(A,`${A}-status-${D}`,{[`${A}-${"dashboard"===x&&"circle"||x}`]:"line"!==x,[`${A}-inline-circle`]:"circle"===x&&M(v,"circle")[0]<=20,[`${A}-line`]:Q,[`${A}-line-align-${j}`]:Q,[`${A}-line-position-${_}`]:Q,[`${A}-steps`]:g,[`${A}-show-info`]:y,[`${A}-${v}`]:"string"==typeof v,[`${A}-rtl`]:"rtl"===F},null==z?void 0:z.className,m,p,q,G);return B(t.createElement("div",Object.assign({ref:d,style:Object.assign(Object.assign({},null==z?void 0:z.style),w),className:J,role:"progressbar","aria-valuenow":I,"aria-valuemin":0,"aria-valuemax":100},(0,s.default)(E,["trailColor","strokeWidth","width","gapDegree","gapPosition","strokeLinecap","success","successPercent"])),u))});e.s(["default",0,G],309821)},597440,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let n={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M360 184h-8c4.4 0 8-3.6 8-8v8h304v-8c0 4.4 3.6 8 8 8h-8v72h72v-80c0-35.3-28.7-64-64-64H352c-35.3 0-64 28.7-64 64v80h72v-72zm504 72H160c-17.7 0-32 14.3-32 32v32c0 4.4 3.6 8 8 8h60.4l24.7 523c1.6 34.1 29.8 61 63.9 61h454c34.2 0 62.3-26.8 63.9-61l24.7-523H888c4.4 0 8-3.6 8-8v-32c0-17.7-14.3-32-32-32zM731.3 840H292.7l-24.2-512h487l-24.2 512z"}}]},name:"delete",theme:"outlined"};var o=e.i(9583),i=r.forwardRef(function(e,i){return r.createElement(o.default,(0,t.default)({},e,{ref:i,icon:n}))});e.s(["default",0,i],597440)},737434,e=>{"use strict";var t=e.i(184163);e.s(["DownloadOutlined",()=>t.default])},916940,e=>{"use strict";var t=e.i(843476),r=e.i(271645),n=e.i(199133),o=e.i(764205);e.s(["default",0,({onChange:e,value:i,className:a,accessToken:l,placeholder:s="Select vector stores",disabled:c=!1})=>{let[d,u]=(0,r.useState)([]),[f,m]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{(async()=>{if(l){m(!0);try{let e=await (0,o.vectorStoreListCall)(l);e.data&&u(e.data)}catch(e){console.error("Error fetching vector stores:",e)}finally{m(!1)}}})()},[l]),(0,t.jsx)("div",{children:(0,t.jsx)(n.Select,{mode:"multiple",placeholder:s,onChange:e,value:i,loading:f,className:a,allowClear:!0,options:d.map(e=>({label:`${e.vector_store_name||e.vector_store_id} (${e.vector_store_id})`,value:e.vector_store_id,title:e.vector_store_description||e.vector_store_id})),optionFilterProp:"label",showSearch:!0,style:{width:"100%"},disabled:c})})}])},107233,37727,e=>{"use strict";var t=e.i(603908);e.s(["Plus",()=>t.default],107233);var r=e.i(841947);e.s(["X",()=>r.default],37727)},246349,e=>{"use strict";let t=(0,e.i(475254).default)("chevron-right",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);e.s(["default",()=>t])},309426,e=>{"use strict";var t=e.i(290571),r=e.i(444755),n=e.i(673706),o=e.i(271645),i=e.i(46757);let a=(0,n.makeClassName)("Col"),l=o.default.forwardRef((e,n)=>{let l,s,c,d,{numColSpan:u=1,numColSpanSm:f,numColSpanMd:m,numColSpanLg:p,children:g,className:h}=e,b=(0,t.__rest)(e,["numColSpan","numColSpanSm","numColSpanMd","numColSpanLg","children","className"]),v=(e,t)=>e&&Object.keys(t).includes(String(e))?t[e]:"";return o.default.createElement("div",Object.assign({ref:n,className:(0,r.tremorTwMerge)(a("root"),(l=v(u,i.colSpan),s=v(f,i.colSpanSm),c=v(m,i.colSpanMd),d=v(p,i.colSpanLg),(0,r.tremorTwMerge)(l,s,c,d)),h)},b),g)});l.displayName="Col",e.s(["Col",()=>l],309426)},950724,(e,t,r)=>{t.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},100236,(e,t,r)=>{t.exports=e.g&&e.g.Object===Object&&e.g},139088,(e,t,r)=>{var n=e.r(100236),o="object"==typeof self&&self&&self.Object===Object&&self;t.exports=n||o||Function("return this")()},631926,(e,t,r)=>{var n=e.r(139088);t.exports=function(){return n.Date.now()}},748891,(e,t,r)=>{var n=/\s/;t.exports=function(e){for(var t=e.length;t--&&n.test(e.charAt(t)););return t}},830364,(e,t,r)=>{var n=e.r(748891),o=/^\s+/;t.exports=function(e){return e?e.slice(0,n(e)+1).replace(o,""):e}},630353,(e,t,r)=>{t.exports=e.r(139088).Symbol},243436,(e,t,r)=>{var n=e.r(630353),o=Object.prototype,i=o.hasOwnProperty,a=o.toString,l=n?n.toStringTag:void 0;t.exports=function(e){var t=i.call(e,l),r=e[l];try{e[l]=void 0;var n=!0}catch(e){}var o=a.call(e);return n&&(t?e[l]=r:delete e[l]),o}},223243,(e,t,r)=>{var n=Object.prototype.toString;t.exports=function(e){return n.call(e)}},377684,(e,t,r)=>{var n=e.r(630353),o=e.r(243436),i=e.r(223243),a=n?n.toStringTag:void 0;t.exports=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":a&&a in Object(e)?o(e):i(e)}},877289,(e,t,r)=>{t.exports=function(e){return null!=e&&"object"==typeof e}},361884,(e,t,r)=>{var n=e.r(377684),o=e.r(877289);t.exports=function(e){return"symbol"==typeof e||o(e)&&"[object Symbol]"==n(e)}},773759,(e,t,r)=>{var n=e.r(830364),o=e.r(950724),i=e.r(361884),a=0/0,l=/^[-+]0x[0-9a-f]+$/i,s=/^0b[01]+$/i,c=/^0o[0-7]+$/i,d=parseInt;t.exports=function(e){if("number"==typeof e)return e;if(i(e))return a;if(o(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=o(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=n(e);var r=s.test(e);return r||c.test(e)?d(e.slice(2),r?2:8):l.test(e)?a:+e}},374009,(e,t,r)=>{var n=e.r(950724),o=e.r(631926),i=e.r(773759),a=Math.max,l=Math.min;t.exports=function(e,t,r){var s,c,d,u,f,m,p=0,g=!1,h=!1,b=!0;if("function"!=typeof e)throw TypeError("Expected a function");function v(t){var r=s,n=c;return s=c=void 0,p=t,u=e.apply(n,r)}function y(e){var r=e-m,n=e-p;return void 0===m||r>=t||r<0||h&&n>=d}function x(){var e,r,n,i=o();if(y(i))return k(i);f=setTimeout(x,(e=i-m,r=i-p,n=t-e,h?l(n,d-r):n))}function k(e){return(f=void 0,b&&s)?v(e):(s=c=void 0,u)}function C(){var e,r=o(),n=y(r);if(s=arguments,c=this,m=r,n){if(void 0===f)return p=e=m,f=setTimeout(x,t),g?v(e):u;if(h)return clearTimeout(f),f=setTimeout(x,t),v(m)}return void 0===f&&(f=setTimeout(x,t)),u}return t=i(t)||0,n(r)&&(g=!!r.leading,d=(h="maxWait"in r)?a(i(r.maxWait)||0,t):d,b="trailing"in r?!!r.trailing:b),C.cancel=function(){void 0!==f&&clearTimeout(f),p=0,s=m=c=f=void 0},C.flush=function(){return void 0===f?u:k(o())},C}},964306,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"}))});e.s(["XCircleIcon",0,r],964306)},677667,674175,886148,543086,e=>{"use strict";let t,r;var n,o=e.i(290571),i=e.i(429427),a=e.i(371330),l=e.i(271645),s=e.i(394487),c=e.i(914189),d=e.i(144279),u=e.i(294316),f=e.i(83733);let m=(0,l.createContext)(()=>{});function p({value:e,children:t}){return l.default.createElement(m.Provider,{value:e},t)}e.s(["CloseProvider",()=>p],674175);var g=e.i(233137),h=e.i(233538),b=e.i(397701),v=e.i(402155),y=e.i(700020);let x=null!=(n=l.default.startTransition)?n:function(e){e()};var k=e.i(998348),C=((t=C||{})[t.Open=0]="Open",t[t.Closed=1]="Closed",t),w=((r=w||{})[r.ToggleDisclosure=0]="ToggleDisclosure",r[r.CloseDisclosure=1]="CloseDisclosure",r[r.SetButtonId=2]="SetButtonId",r[r.SetPanelId=3]="SetPanelId",r[r.SetButtonElement=4]="SetButtonElement",r[r.SetPanelElement=5]="SetPanelElement",r);let S={0:e=>({...e,disclosureState:(0,b.match)(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}},E=(0,l.createContext)(null);function j(e){let t=(0,l.useContext)(E);if(null===t){let t=Error(`<${e} /> is missing a parent component.`);throw Error.captureStackTrace&&Error.captureStackTrace(t,j),t}return t}E.displayName="DisclosureContext";let _=(0,l.createContext)(null);_.displayName="DisclosureAPIContext";let N=(0,l.createContext)(null);function O(e,t){return(0,b.match)(t.type,S,e,t)}N.displayName="DisclosurePanelContext";let $=l.Fragment,T=y.RenderFeatures.RenderStrategy|y.RenderFeatures.Static,M=Object.assign((0,y.forwardRefWithAs)(function(e,t){let{defaultOpen:r=!1,...n}=e,o=(0,l.useRef)(null),i=(0,u.useSyncRefs)(t,(0,u.optionalRef)(e=>{o.current=e},void 0===e.as||e.as===l.Fragment)),a=(0,l.useReducer)(O,{disclosureState:+!r,buttonElement:null,panelElement:null,buttonId:null,panelId:null}),[{disclosureState:s,buttonId:d},f]=a,m=(0,c.useEvent)(e=>{f({type:1});let t=(0,v.getOwnerDocument)(o);if(!t||!d)return;let r=e?e instanceof HTMLElement?e:e.current instanceof HTMLElement?e.current:t.getElementById(d):t.getElementById(d);null==r||r.focus()}),h=(0,l.useMemo)(()=>({close:m}),[m]),x=(0,l.useMemo)(()=>({open:0===s,close:m}),[s,m]),k=(0,y.useRender)();return l.default.createElement(E.Provider,{value:a},l.default.createElement(_.Provider,{value:h},l.default.createElement(p,{value:m},l.default.createElement(g.OpenClosedProvider,{value:(0,b.match)(s,{0:g.State.Open,1:g.State.Closed})},k({ourProps:{ref:i},theirProps:n,slot:x,defaultTag:$,name:"Disclosure"})))))}),{Button:(0,y.forwardRefWithAs)(function(e,t){let r=(0,l.useId)(),{id:n=`headlessui-disclosure-button-${r}`,disabled:o=!1,autoFocus:f=!1,...m}=e,[p,g]=j("Disclosure.Button"),b=(0,l.useContext)(N),v=null!==b&&b===p.panelId,x=(0,l.useRef)(null),C=(0,u.useSyncRefs)(x,t,(0,c.useEvent)(e=>{if(!v)return g({type:4,element:e})}));(0,l.useEffect)(()=>{if(!v)return g({type:2,buttonId:n}),()=>{g({type:2,buttonId:null})}},[n,g,v]);let w=(0,c.useEvent)(e=>{var t;if(v){if(1===p.disclosureState)return;switch(e.key){case k.Keys.Space:case k.Keys.Enter:e.preventDefault(),e.stopPropagation(),g({type:0}),null==(t=p.buttonElement)||t.focus()}}else switch(e.key){case k.Keys.Space:case k.Keys.Enter:e.preventDefault(),e.stopPropagation(),g({type:0})}}),S=(0,c.useEvent)(e=>{e.key===k.Keys.Space&&e.preventDefault()}),E=(0,c.useEvent)(e=>{var t;(0,h.isDisabledReactIssue7711)(e.currentTarget)||o||(v?(g({type:0}),null==(t=p.buttonElement)||t.focus()):g({type:0}))}),{isFocusVisible:_,focusProps:O}=(0,i.useFocusRing)({autoFocus:f}),{isHovered:$,hoverProps:T}=(0,a.useHover)({isDisabled:o}),{pressed:M,pressProps:R}=(0,s.useActivePress)({disabled:o}),P=(0,l.useMemo)(()=>({open:0===p.disclosureState,hover:$,active:M,disabled:o,focus:_,autofocus:f}),[p,$,M,_,o,f]),I=(0,d.useResolveButtonType)(e,p.buttonElement),D=v?(0,y.mergeProps)({ref:C,type:I,disabled:o||void 0,autoFocus:f,onKeyDown:w,onClick:E},O,T,R):(0,y.mergeProps)({ref:C,id:n,type:I,"aria-expanded":0===p.disclosureState,"aria-controls":p.panelElement?p.panelId:void 0,disabled:o||void 0,autoFocus:f,onKeyDown:w,onKeyUp:S,onClick:E},O,T,R);return(0,y.useRender)()({ourProps:D,theirProps:m,slot:P,defaultTag:"button",name:"Disclosure.Button"})}),Panel:(0,y.forwardRefWithAs)(function(e,t){let r=(0,l.useId)(),{id:n=`headlessui-disclosure-panel-${r}`,transition:o=!1,...i}=e,[a,s]=j("Disclosure.Panel"),{close:d}=function e(t){let r=(0,l.useContext)(_);if(null===r){let r=Error(`<${t} /> is missing a parent component.`);throw Error.captureStackTrace&&Error.captureStackTrace(r,e),r}return r}("Disclosure.Panel"),[m,p]=(0,l.useState)(null),h=(0,u.useSyncRefs)(t,(0,c.useEvent)(e=>{x(()=>s({type:5,element:e}))}),p);(0,l.useEffect)(()=>(s({type:3,panelId:n}),()=>{s({type:3,panelId:null})}),[n,s]);let b=(0,g.useOpenClosed)(),[v,k]=(0,f.useTransition)(o,m,null!==b?(b&g.State.Open)===g.State.Open:0===a.disclosureState),C=(0,l.useMemo)(()=>({open:0===a.disclosureState,close:d}),[a.disclosureState,d]),w={ref:h,id:n,...(0,f.transitionDataAttributes)(k)},S=(0,y.useRender)();return l.default.createElement(g.ResetOpenClosedProvider,null,l.default.createElement(N.Provider,{value:a.panelId},S({ourProps:w,theirProps:i,slot:C,defaultTag:"div",features:T,visible:v,name:"Disclosure.Panel"})))})});e.s(["Disclosure",()=>M],886148);let R=(0,l.createContext)(void 0);var P=e.i(444755);let I=(0,e.i(673706).makeClassName)("Accordion"),D=(0,l.createContext)({isOpen:!1}),L=l.default.forwardRef((e,t)=>{var r;let{defaultOpen:n=!1,children:i,className:a}=e,s=(0,o.__rest)(e,["defaultOpen","children","className"]),c=null!=(r=(0,l.useContext)(R))?r:(0,P.tremorTwMerge)("rounded-tremor-default border");return l.default.createElement(M,Object.assign({as:"div",ref:t,className:(0,P.tremorTwMerge)(I("root"),"overflow-hidden","bg-tremor-background border-tremor-border","dark:bg-dark-tremor-background dark:border-dark-tremor-border",c,a),defaultOpen:n},s),({open:e})=>l.default.createElement(D.Provider,{value:{isOpen:e}},i))});L.displayName="Accordion",e.s(["OpenContext",()=>D,"default",()=>L],543086),e.s(["Accordion",()=>L],677667)},898667,e=>{"use strict";var t=e.i(290571),r=e.i(271645),n=e.i(886148);let o=e=>{var n=(0,t.__rest)(e,[]);return r.default.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"},n),r.default.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 i=e.i(543086),a=e.i(444755);let l=(0,e.i(673706).makeClassName)("AccordionHeader"),s=r.default.forwardRef((e,s)=>{let{children:c,className:d}=e,u=(0,t.__rest)(e,["children","className"]),{isOpen:f}=(0,r.useContext)(i.OpenContext);return r.default.createElement(n.Disclosure.Button,Object.assign({ref:s,className:(0,a.tremorTwMerge)(l("root"),"w-full flex items-center justify-between px-4 py-3","text-tremor-content-emphasis","dark:text-dark-tremor-content-emphasis",d)},u),r.default.createElement("div",{className:(0,a.tremorTwMerge)(l("children"),"flex flex-1 text-inherit mr-4")},c),r.default.createElement("div",null,r.default.createElement(o,{className:(0,a.tremorTwMerge)(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")})))});s.displayName="AccordionHeader",e.s(["AccordionHeader",()=>s],898667)},130643,e=>{"use strict";var t=e.i(290571),r=e.i(271645),n=e.i(886148),o=e.i(444755);let i=(0,e.i(673706).makeClassName)("AccordionBody"),a=r.default.forwardRef((e,a)=>{let{children:l,className:s}=e,c=(0,t.__rest)(e,["children","className"]);return r.default.createElement(n.Disclosure.Panel,Object.assign({ref:a,className:(0,o.tremorTwMerge)(i("root"),"w-full text-tremor-default px-4 pb-3","text-tremor-content","dark:text-dark-tremor-content",s)},c),l)});a.displayName="AccordionBody",e.s(["AccordionBody",()=>a],130643)},83733,233137,e=>{"use strict";let t,r;var n,o,i=e.i(247167),a=e.i(271645),l=e.i(544508),s=e.i(746725),c=e.i(835696);void 0!==i.default&&"u">typeof globalThis&&"u">typeof Element&&(null==(n=null==i.default?void 0:i.default.env)?void 0:n.NODE_ENV)==="test"&&void 0===(null==(o=null==Element?void 0:Element.prototype)?void 0:o.getAnimations)&&(Element.prototype.getAnimations=function(){return console.warn(["Headless UI has polyfilled `Element.prototype.getAnimations` for your tests.","Please install a proper polyfill e.g. `jsdom-testing-mocks`, to silence these warnings.","","Example usage:","```js","import { mockAnimationsApi } from 'jsdom-testing-mocks'","mockAnimationsApi()","```"].join(` +`)),[]});var d=((t=d||{})[t.None=0]="None",t[t.Closed=1]="Closed",t[t.Enter=2]="Enter",t[t.Leave=4]="Leave",t);function u(e){let t={};for(let r in e)!0===e[r]&&(t[`data-${r}`]="");return t}function f(e,t,r,n){let[o,i]=(0,a.useState)(r),{hasFlag:d,addFlag:u,removeFlag:f}=function(e=0){let[t,r]=(0,a.useState)(e),n=(0,a.useCallback)(e=>r(e),[t]),o=(0,a.useCallback)(e=>r(t=>t|e),[t]),i=(0,a.useCallback)(e=>(t&e)===e,[t]);return{flags:t,setFlag:n,addFlag:o,hasFlag:i,removeFlag:(0,a.useCallback)(e=>r(t=>t&~e),[r]),toggleFlag:(0,a.useCallback)(e=>r(t=>t^e),[r])}}(e&&o?3:0),m=(0,a.useRef)(!1),p=(0,a.useRef)(!1),g=(0,s.useDisposables)();return(0,c.useIsoMorphicEffect)(()=>{var o;if(e){if(r&&i(!0),!t){r&&u(3);return}return null==(o=null==n?void 0:n.start)||o.call(n,r),function(e,{prepare:t,run:r,done:n,inFlight:o}){let i=(0,l.disposables)();return function(e,{inFlight:t,prepare:r}){if(null!=t&&t.current)return r();let n=e.style.transition;e.style.transition="none",r(),e.offsetHeight,e.style.transition=n}(e,{prepare:t,inFlight:o}),i.nextFrame(()=>{r(),i.requestAnimationFrame(()=>{i.add(function(e,t){var r,n;let o=(0,l.disposables)();if(!e)return o.dispose;let i=!1;o.add(()=>{i=!0});let a=null!=(n=null==(r=e.getAnimations)?void 0:r.call(e).filter(e=>e instanceof CSSTransition))?n:[];return 0===a.length?t():Promise.allSettled(a.map(e=>e.finished)).then(()=>{i||t()}),o.dispose}(e,n))})}),i.dispose}(t,{inFlight:m,prepare(){p.current?p.current=!1:p.current=m.current,m.current=!0,p.current||(r?(u(3),f(4)):(u(4),f(2)))},run(){p.current?r?(f(3),u(4)):(f(4),u(3)):r?f(1):u(1)},done(){var e;p.current&&"function"==typeof t.getAnimations&&t.getAnimations().length>0||(m.current=!1,f(7),r||i(!1),null==(e=null==n?void 0:n.end)||e.call(n,r))}})}},[e,r,t,g]),e?[o,{closed:d(1),enter:d(2),leave:d(4),transition:d(2)||d(4)}]:[r,{closed:void 0,enter:void 0,leave:void 0,transition:void 0}]}e.s(["transitionDataAttributes",()=>u,"useTransition",()=>f],83733);let m=(0,a.createContext)(null);m.displayName="OpenClosedContext";var p=((r=p||{})[r.Open=1]="Open",r[r.Closed=2]="Closed",r[r.Closing=4]="Closing",r[r.Opening=8]="Opening",r);function g(){return(0,a.useContext)(m)}function h({value:e,children:t}){return a.default.createElement(m.Provider,{value:e},t)}function b({children:e}){return a.default.createElement(m.Provider,{value:null},e)}e.s(["OpenClosedProvider",()=>h,"ResetOpenClosedProvider",()=>b,"State",()=>p,"useOpenClosed",()=>g],233137)},233538,e=>{"use strict";function t(e){let t=e.parentElement,r=null;for(;t&&!(t instanceof HTMLFieldSetElement);)t instanceof HTMLLegendElement&&(r=t),t=t.parentElement;let n=(null==t?void 0:t.getAttribute("disabled"))==="";return!(n&&function(e){if(!e)return!1;let t=e.previousElementSibling;for(;null!==t;){if(t instanceof HTMLLegendElement)return!1;t=t.previousElementSibling}return!0}(r))&&n}e.s(["isDisabledReactIssue7711",()=>t])},888288,220508,e=>{"use strict";var t=e.i(271645);let r=(e,r)=>{let n=void 0!==r,[o,i]=(0,t.useState)(e);return[n?r:o,e=>{n||i(e)}]};e.s(["default",()=>r],888288);let n=t.forwardRef(function(e,r){return t.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:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"}))});e.s(["CheckCircleIcon",0,n],220508)},503269,214520,601893,694421,140721,942803,35889,722678,e=>{"use strict";var t=e.i(271645),r=e.i(914189);function n(e,n,o){let[i,a]=(0,t.useState)(o),l=void 0!==e,s=(0,t.useRef)(l),c=(0,t.useRef)(!1),d=(0,t.useRef)(!1);return!l||s.current||c.current?l||!s.current||d.current||(d.current=!0,s.current=l,console.error("A component is changing from controlled to uncontrolled. This may be caused by the value changing from a defined value to undefined, which should not happen.")):(c.current=!0,s.current=l,console.error("A component is changing from uncontrolled to controlled. This may be caused by the value changing from undefined to a defined value, which should not happen.")),[l?e:i,(0,r.useEvent)(e=>(l||a(e),null==n?void 0:n(e)))]}function o(e){let[r]=(0,t.useState)(e);return r}e.s(["useControllable",()=>n],503269),e.s(["useDefaultValue",()=>o],214520);let i=(0,t.createContext)(void 0);function a(){return(0,t.useContext)(i)}e.s(["useDisabled",()=>a],601893);var l=e.i(174080),s=e.i(746725);function c(e={},t=null,r=[]){for(let[n,o]of Object.entries(e))!function e(t,r,n){if(Array.isArray(n))for(let[o,i]of n.entries())e(t,d(r,o.toString()),i);else n instanceof Date?t.push([r,n.toISOString()]):"boolean"==typeof n?t.push([r,n?"1":"0"]):"string"==typeof n?t.push([r,n]):"number"==typeof n?t.push([r,`${n}`]):null==n?t.push([r,""]):c(n,r,t)}(r,d(t,n),o);return r}function d(e,t){return e?e+"["+t+"]":t}function u(e){var t,r;let n=null!=(t=null==e?void 0:e.form)?t:e.closest("form");if(n){for(let t of n.elements)if(t!==e&&("INPUT"===t.tagName&&"submit"===t.type||"BUTTON"===t.tagName&&"submit"===t.type||"INPUT"===t.nodeName&&"image"===t.type))return void t.click();null==(r=n.requestSubmit)||r.call(n)}}e.s(["attemptSubmit",()=>u,"objectToFormEntries",()=>c],694421);var f=e.i(700020),m=e.i(2788);let p=(0,t.createContext)(null);function g({children:e}){let r=(0,t.useContext)(p);if(!r)return t.default.createElement(t.default.Fragment,null,e);let{target:n}=r;return n?(0,l.createPortal)(t.default.createElement(t.default.Fragment,null,e),n):null}function h({data:e,form:r,disabled:n,onReset:o,overrides:i}){let[a,l]=(0,t.useState)(null),d=(0,s.useDisposables)();return(0,t.useEffect)(()=>{if(o&&a)return d.addEventListener(a,"reset",o)},[a,r,o]),t.default.createElement(g,null,t.default.createElement(b,{setForm:l,formId:r}),c(e).map(([e,o])=>t.default.createElement(m.Hidden,{features:m.HiddenFeatures.Hidden,...(0,f.compact)({key:e,as:"input",type:"hidden",hidden:!0,readOnly:!0,form:r,disabled:n,name:e,value:o,...i})})))}function b({setForm:e,formId:r}){return(0,t.useEffect)(()=>{if(r){let t=document.getElementById(r);t&&e(t)}},[e,r]),r?null:t.default.createElement(m.Hidden,{features:m.HiddenFeatures.Hidden,as:"input",type:"hidden",hidden:!0,readOnly:!0,ref:t=>{if(!t)return;let r=t.closest("form");r&&e(r)}})}e.s(["FormFields",()=>h],140721);let v=(0,t.createContext)(void 0);function y(){return(0,t.useContext)(v)}e.s(["useProvidedId",()=>y],942803);var x=e.i(835696),k=e.i(294316);let C=(0,t.createContext)(null);function w(){var e,r;return null!=(r=null==(e=(0,t.useContext)(C))?void 0:e.value)?r:void 0}function S(){let[e,n]=(0,t.useState)([]);return[e.length>0?e.join(" "):void 0,(0,t.useMemo)(()=>function(e){let o=(0,r.useEvent)(e=>(n(t=>[...t,e]),()=>n(t=>{let r=t.slice(),n=r.indexOf(e);return -1!==n&&r.splice(n,1),r}))),i=(0,t.useMemo)(()=>({register:o,slot:e.slot,name:e.name,props:e.props,value:e.value}),[o,e.slot,e.name,e.props,e.value]);return t.default.createElement(C.Provider,{value:i},e.children)},[n])]}C.displayName="DescriptionContext";let E=Object.assign((0,f.forwardRefWithAs)(function(e,r){let n=(0,t.useId)(),o=a(),{id:i=`headlessui-description-${n}`,...l}=e,s=function e(){let r=(0,t.useContext)(C);if(null===r){let t=Error("You used a component, but it is not inside a relevant parent.");throw Error.captureStackTrace&&Error.captureStackTrace(t,e),t}return r}(),c=(0,k.useSyncRefs)(r);(0,x.useIsoMorphicEffect)(()=>s.register(i),[i,s.register]);let d=o||!1,u=(0,t.useMemo)(()=>({...s.slot,disabled:d}),[s.slot,d]),m={ref:c,...s.props,id:i};return(0,f.useRender)()({ourProps:m,theirProps:l,slot:u,defaultTag:"p",name:s.name||"Description"})}),{});e.s(["Description",()=>E,"useDescribedBy",()=>w,"useDescriptions",()=>S],35889);let j=(0,t.createContext)(null);function _(e){var r,n,o;let i=null!=(n=null==(r=(0,t.useContext)(j))?void 0:r.value)?n:void 0;return(null!=(o=null==e?void 0:e.length)?o:0)>0?[i,...e].filter(Boolean).join(" "):i}function N({inherit:e=!1}={}){let n=_(),[o,i]=(0,t.useState)([]),a=e?[n,...o].filter(Boolean):o;return[a.length>0?a.join(" "):void 0,(0,t.useMemo)(()=>function(e){let n=(0,r.useEvent)(e=>(i(t=>[...t,e]),()=>i(t=>{let r=t.slice(),n=r.indexOf(e);return -1!==n&&r.splice(n,1),r}))),o=(0,t.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 t.default.createElement(j.Provider,{value:o},e.children)},[i])]}j.displayName="LabelContext";let O=Object.assign((0,f.forwardRefWithAs)(function(e,n){var o;let i=(0,t.useId)(),l=function e(){let r=(0,t.useContext)(j);if(null===r){let t=Error("You used a