The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
[Feature] UI - Cache Settings Redis Add Semantic Cache Settings (#16398)
yuneng-jiang8412950b9439
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex e57820e1248..3ab7eface51 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -4209,7 +4209,7 @@ class ProxyStartupEvent:# Key fixes:# 1. Remove/minimize jitter to avoid normalize() memory explosion# 2. Use larger misfire_grace_time to prevent backlog calculations- # 3. Set replace_existing=True to avoid duplicate jobs (must be passed per-job, not as default)+ # 3. Set replace_existing=True to avoid duplicate jobsfrom apscheduler.executors.asyncio import AsyncIOExecutorfrom apscheduler.jobstores.memory import MemoryJobStorediff --git a/litellm/types/management_endpoints/cache_settings_endpoints.py b/litellm/types/management_endpoints/cache_settings_endpoints.pyindex 4afef21b194..d2a8a39e4f8 100644--- a/litellm/types/management_endpoints/cache_settings_endpoints.py+++ b/litellm/types/management_endpoints/cache_settings_endpoints.py@@ -150,6 +150,25 @@ CACHE_SETTINGS_FIELDS: List[CacheSettingsField] = [ui_field_name="Sentinel Password",redis_type="sentinel",),+ # Semantic-specific fields+ CacheSettingsField(+ field_name="similarity_threshold",+ field_type="Float",+ field_value=None,+ field_description="Similarity threshold for semantic cache",+ field_default=0.8,+ ui_field_name="Similarity Threshold",+ redis_type="semantic",+ ),+ CacheSettingsField(+ field_name="redis_semantic_cache_embedding_model",+ field_type="Models_Select",+ field_value=None,+ field_description="Embedding model for semantic cache",+ field_default=None,+ ui_field_name="Embedding Model",+ redis_type="semantic",+ ),# GCP IAM authentication fieldsCacheSettingsField(field_name="gcp_service_account",diff --git a/ui/litellm-dashboard/src/components/cache_settings/CacheFieldGroup.test.tsx b/ui/litellm-dashboard/src/components/cache_settings/CacheFieldGroup.test.tsxindex 9809bec743e..6eba0718948 100644--- a/ui/litellm-dashboard/src/components/cache_settings/CacheFieldGroup.test.tsx+++ b/ui/litellm-dashboard/src/components/cache_settings/CacheFieldGroup.test.tsx@@ -1,8 +1,21 @@-import { describe, it, expect, beforeEach } from "vitest";+import { describe, it, expect, beforeEach, vi } from "vitest";import { render, screen, cleanup } from "@testing-library/react";import CacheFieldGroup from "./CacheFieldGroup";describe("CacheFieldGroup", () => {+ vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({+ default: () => ({+ token: "mock-token",+ accessToken: "mock-access-token",+ userId: "mock-user-id",+ userEmail: "[email protected]",+ userRole: "Admin",+ premiumUser: false,+ disabledPersonalKeyCreation: false,+ showSSOBanner: false,+ }),+ }));+beforeEach(() => {cleanup();});@@ -40,12 +53,7 @@ describe("CacheFieldGroup", () => {// Test with cluster type - should show host and redis_startup_nodesconst { rerender } = render(- <CacheFieldGroup- title="Cluster Settings"- fields={fields}- cacheSettings={cacheSettings}- redisType="cluster"- />+ <CacheFieldGroup title="Cluster Settings" fields={fields} cacheSettings={cacheSettings} redisType="cluster" />,);expect(screen.getByText("Cluster Settings")).toBeInTheDocument();@@ -55,12 +63,7 @@ describe("CacheFieldGroup", () => {// Test with sentinel type - should show host and sentinel_nodesrerender(- <CacheFieldGroup- title="Sentinel Settings"- fields={fields}- cacheSettings={cacheSettings}- redisType="sentinel"- />+ <CacheFieldGroup title="Sentinel Settings" fields={fields} cacheSettings={cacheSettings} redisType="sentinel" />,);expect(screen.getByText("Sentinel Settings")).toBeInTheDocument();@@ -69,14 +72,7 @@ describe("CacheFieldGroup", () => {expect(screen.queryByText("Startup Nodes")).not.toBeInTheDocument();// Test with node type - should only show host- rerender(- <CacheFieldGroup- title="Node Settings"- fields={fields}- cacheSettings={cacheSettings}- redisType="node"- />- );+ rerender(<CacheFieldGroup title="Node Settings" fields={fields} cacheSettings={cacheSettings} redisType="node" />);expect(screen.getByText("Node Settings")).toBeInTheDocument();expect(screen.getAllByText("Host")).toHaveLength(1);@@ -106,7 +102,7 @@ describe("CacheFieldGroup", () => {fields={fields}cacheSettings={cacheSettings}redisType="node" // No fields match this type- />+ />,);// Component should return null, so container should be empty@@ -131,12 +127,7 @@ describe("CacheFieldGroup", () => {const cacheSettings = {}; // No port value setrender(- <CacheFieldGroup- title="Connection Settings"- fields={fields}- cacheSettings={cacheSettings}- redisType="node"- />+ <CacheFieldGroup title="Connection Settings" fields={fields} cacheSettings={cacheSettings} redisType="node" />,);const input = screen.getByRole("spinbutton", { name: "" });@@ -145,4 +136,3 @@ describe("CacheFieldGroup", () => {expect(input).toHaveValue(6379);});});-diff --git a/ui/litellm-dashboard/src/components/cache_settings/CacheFieldRenderer.test.tsx b/ui/litellm-dashboard/src/components/cache_settings/CacheFieldRenderer.test.tsxindex 67b4cadfd5f..3cfacac7fda 100644--- a/ui/litellm-dashboard/src/components/cache_settings/CacheFieldRenderer.test.tsx+++ b/ui/litellm-dashboard/src/components/cache_settings/CacheFieldRenderer.test.tsx@@ -1,7 +1,21 @@-import { describe, it, expect } from "vitest";+import { describe, it, expect, vi } from "vitest";import { render, screen } from "@testing-library/react";import CacheFieldRenderer from "./CacheFieldRenderer";+// Mock the useAuthorized hook to avoid Next.js router dependency+vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({+ default: () => ({+ token: "mock-token",+ accessToken: "mock-access-token",+ userId: "mock-user-id",+ userEmail: "[email protected]",+ userRole: "Admin",+ premiumUser: false,+ disabledPersonalKeyCreation: false,+ showSSOBanner: false,+ }),+}));+describe("CacheFieldRenderer", () => {it("should render a checkbox for Boolean field type", () => {/**@@ -110,4 +124,3 @@ describe("CacheFieldRenderer", () => {expect(input).toHaveValue("localhost");});});-diff --git a/ui/litellm-dashboard/src/components/cache_settings/CacheFieldRenderer.tsx b/ui/litellm-dashboard/src/components/cache_settings/CacheFieldRenderer.tsxindex e711376138d..f2f316fb146 100644--- a/ui/litellm-dashboard/src/components/cache_settings/CacheFieldRenderer.tsx+++ b/ui/litellm-dashboard/src/components/cache_settings/CacheFieldRenderer.tsx@@ -1,21 +1,45 @@-import React from "react";-import { TextInput, NumberInput } from "@tremor/react";+"use client";++import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";+import { NumberInput, TextInput } from "@tremor/react";+import { Select } from "antd";+import React, { useEffect, useState } from "react";+import { fetchAvailableModels, ModelGroup } from "../chat_ui/llm_calls/fetch_models";+import NumericalInput from "../shared/numerical_input";interface CacheFieldRendererProps {field: any;currentValue: any;}-const CacheFieldRenderer: React.FC<CacheFieldRendererProps> = ({- field,- currentValue,-}) => {+const CacheFieldRenderer: React.FC<CacheFieldRendererProps> = ({ field, currentValue }) => {+ const [modelInfo, setModelInfo] = useState<ModelGroup[]>([]);+ const [selectedModel, setSelectedModel] = useState<string>(currentValue || "");+ const { accessToken } = useAuthorized();++ useEffect(() => {+ if (!accessToken) return;++ const loadModels = async () => {+ try {+ const uniqueModels = await fetchAvailableModels(accessToken);+ console.log("Fetched models for selector:", uniqueModels);++ if (uniqueModels.length > 0) {+ setModelInfo(uniqueModels);+ }+ } catch (error) {+ console.error("Error fetching model info:", error);+ }+ };++ loadModels();+ }, [accessToken]);+if (field.field_type === "Boolean") {return (<div className="space-y-2">- <label className="text-sm font-medium text-gray-700">- {field.ui_field_name}- </label>+ <label className="text-sm font-medium text-gray-700">{field.ui_field_name}</label><div className="flex items-center"><inputtype="checkbox"@@ -29,12 +53,25 @@ const CacheFieldRenderer: React.FC<CacheFieldRendererProps> = ({);}+ if (field.field_type === "Integer" || field.field_type === "Float") {+ return (+ <div className="space-y-2">+ <label className="text-sm font-medium text-gray-700">{field.ui_field_name}</label>+ <NumericalInput+ name={field.field_name}+ type="number"+ defaultValue={currentValue}+ placeholder={field.field_description}+ />+ <p className="text-xs text-gray-500">{field.field_description}</p>+ </div>+ );+ }+if (field.field_type === "List") {return (<div className="space-y-2">- <label className="text-sm font-medium text-gray-700">- {field.ui_field_name}- </label>+ <label className="text-sm font-medium text-gray-700">{field.ui_field_name}</label><textareaname={field.field_name}defaultValue={typeof currentValue === "object" ? JSON.stringify(currentValue, null, 2) : currentValue}@@ -47,49 +84,66 @@ const CacheFieldRenderer: React.FC<CacheFieldRendererProps> = ({);}+ if (field.field_type === "Models_Select") {+ const embeddingModels = modelInfo+ .filter((option: ModelGroup) => option.mode === "embedding")+ .map((option: ModelGroup) => ({+ value: option.model_group,+ label: option.model_group,+ }));++ return (+ <div className="space-y-2">+ <label className="text-sm font-medium text-gray-700">{field.ui_field_name}</label>+ <Select+ value={selectedModel}+ onChange={setSelectedModel}+ showSearch={true}+ placeholder="Search and select a model..."+ options={embeddingModels}+ style={{ width: "100%" }}+ className="rounded-md"+ filterOption={(input, option) => (option?.label ?? "").toLowerCase().includes(input.toLowerCase())}+ />+ {/* Hidden input to capture the value for form submission */}+ <input type="hidden" name={field.field_name} value={selectedModel} />+ {field.field_description && <p className="text-xs text-gray-500">{field.field_description}</p>}+ </div>+ );+ }+// Render number input for numeric fieldsif (field.field_type === "Integer" || field.field_type === "Float") {return (<div className="space-y-2">- <label className="text-sm font-medium text-gray-700">- {field.ui_field_name}- </label>+ <label className="text-sm font-medium text-gray-700">{field.ui_field_name}</label><NumberInputname={field.field_name}defaultValue={currentValue}placeholder={field.field_description}step={field.field_type === "Float" ? 0.01 : 1}/>- {field.field_description && (- <p className="text-xs text-gray-500">{field.field_description}</p>- )}+ {field.field_description && <p className="text-xs text-gray-500">{field.field_description}</p>}</div>);}// Determine input type for text-based fields- const inputType: "text" | "password" | "email" | "url" | undefined =- (field.field_name === "password" || field.field_name.includes("password"))- ? "password"- : "text";+ const inputType: "text" | "password" | "email" | "url" | undefined =+ field.field_name === "password" || field.field_name.includes("password") ? "password" : "text";return (<div className="space-y-2">- <label className="text-sm font-medium text-gray-700">- {field.ui_field_name}- </label>+ <label className="text-sm font-medium text-gray-700">{field.ui_field_name}</label><TextInputname={field.field_name}type={inputType}defaultValue={currentValue}placeholder={field.field_description}/>- {field.field_description && (- <p className="text-xs text-gray-500">{field.field_description}</p>- )}+ {field.field_description && <p className="text-xs text-gray-500">{field.field_description}</p>}</div>);};export default CacheFieldRenderer;-diff --git a/ui/litellm-dashboard/src/components/cache_settings/RedisTypeSelector.test.tsx b/ui/litellm-dashboard/src/components/cache_settings/RedisTypeSelector.test.tsxnew file mode 100644index 00000000000..9d4d5a6d425--- /dev/null+++ b/ui/litellm-dashboard/src/components/cache_settings/RedisTypeSelector.test.tsx@@ -0,0 +1,12 @@+import { describe, expect, it } from "vitest";+import RedisTypeSelector from "./RedisTypeSelector";+import { render } from "@testing-library/react";++describe("RedisTypeSelector", () => {+ it("should render the component", () => {+ const { getAllByText } = render(+ <RedisTypeSelector redisType="redis" redisTypeDescriptions={{}} onTypeChange={() => {}} />,+ );+ expect(getAllByText(/Redis/i).length).toBeGreaterThan(0);+ });+});diff --git a/ui/litellm-dashboard/src/components/cache_settings/RedisTypeSelector.tsx b/ui/litellm-dashboard/src/components/cache_settings/RedisTypeSelector.tsxindex 08a054b7440..a94d44dd4e0 100644--- a/ui/litellm-dashboard/src/components/cache_settings/RedisTypeSelector.tsx+++ b/ui/litellm-dashboard/src/components/cache_settings/RedisTypeSelector.tsx@@ -7,11 +7,7 @@ interface RedisTypeSelectorProps {onTypeChange: (type: string) => void;}-const RedisTypeSelector: React.FC<RedisTypeSelectorProps> = ({- redisType,- redisTypeDescriptions,- onTypeChange,-}) => {+const RedisTypeSelector: React.FC<RedisTypeSelectorProps> = ({ redisType, redisTypeDescriptions, onTypeChange }) => {return (<div className="space-y-2"><label className="text-sm font-medium text-gray-700">Redis Type</label>@@ -19,14 +15,13 @@ const RedisTypeSelector: React.FC<RedisTypeSelectorProps> = ({<SelectItem value="node">Node (Single Instance)</SelectItem><SelectItem value="cluster">Cluster</SelectItem><SelectItem value="sentinel">Sentinel</SelectItem>+ <SelectItem value="semantic">Semantic</SelectItem></Select><p className="text-xs text-gray-500">- {redisTypeDescriptions[redisType] ||- "Select the type of Redis deployment you're using"}+ {redisTypeDescriptions[redisType] || "Select the type of Redis deployment you're using"}</p></div>);};export default RedisTypeSelector;-diff --git a/ui/litellm-dashboard/src/components/cache_settings/cacheSettingsUtils.ts b/ui/litellm-dashboard/src/components/cache_settings/cacheSettingsUtils.tsindex 748c1debb1e..b7554136ad4 100644--- a/ui/litellm-dashboard/src/components/cache_settings/cacheSettingsUtils.ts+++ b/ui/litellm-dashboard/src/components/cache_settings/cacheSettingsUtils.ts@@ -7,37 +7,36 @@ export const shouldShowField = (field: any, redisType: string): boolean => {if (field.redis_type === null || field.redis_type === undefined) {return true;}-+return field.redis_type === redisType;};export const getFieldByName = (fields: any[], fieldName: string) => {- return fields.find(f => f.field_name === fieldName);+ return fields.find((f) => f.field_name === fieldName);};export const groupFieldsByCategory = (fields: any[], redisType: string) => {// Basic fields that are always shownconst basicFieldNames = ["host", "port", "password", "username"];- const basicFields = basicFieldNames- .map(name => getFieldByName(fields, name))- .filter(Boolean);+ const basicFields = basicFieldNames.map((name) => getFieldByName(fields, name)).filter(Boolean);// Advanced field groupsconst sslFields = ["ssl", "ssl_cert_reqs", "ssl_check_hostname"]- .map(name => getFieldByName(fields, name))+ .map((name) => getFieldByName(fields, name)).filter(Boolean);-+const cacheManagementFields = ["namespace", "ttl", "max_connections"]- .map(name => getFieldByName(fields, name))+ .map((name) => getFieldByName(fields, name)).filter(Boolean);-+const gcpFields = ["gcp_service_account", "gcp_ssl_ca_certs"]- .map(name => getFieldByName(fields, name))+ .map((name) => getFieldByName(fields, name)).filter(Boolean);// Redis type-specific fields- const clusterFields = fields.filter(f => f.redis_type === "cluster");- const sentinelFields = fields.filter(f => f.redis_type === "sentinel");+ const clusterFields = fields.filter((f) => f.redis_type === "cluster");+ const sentinelFields = fields.filter((f) => f.redis_type === "sentinel");+ const semanticFields = fields.filter((f) => f.redis_type === "semantic");return {basicFields,@@ -46,6 +45,7 @@ export const groupFieldsByCategory = (fields: any[], redisType: string) => {gcpFields,clusterFields,sentinelFields,+ semanticFields,};};@@ -108,4 +108,3 @@ export const gatherFormValues = (fields: any[], redisType: string): { [key: strireturn values;};-diff --git a/ui/litellm-dashboard/src/components/cache_settings/index.tsx b/ui/litellm-dashboard/src/components/cache_settings/index.tsxindex 126298b7725..c7d8c579af3 100644--- a/ui/litellm-dashboard/src/components/cache_settings/index.tsx+++ b/ui/litellm-dashboard/src/components/cache_settings/index.tsx@@ -1,10 +1,6 @@import React, { useState, useEffect, useCallback } from "react";import { Button, Accordion, AccordionHeader, AccordionBody } from "@tremor/react";-import {- getCacheSettingsCall,- testCacheConnectionCall,- updateCacheSettingsCall,-} from "../networking";+import { getCacheSettingsCall, testCacheConnectionCall, updateCacheSettingsCall } from "../networking";import NotificationsManager from "../molecules/notifications_manager";import RedisTypeSelector from "./RedisTypeSelector";import CacheFieldRenderer from "./CacheFieldRenderer";@@ -28,7 +24,7 @@ const CacheSettings: React.FC<CacheSettingsProps> = ({ accessToken, userRole, ustry {const data = await getCacheSettingsCall(accessToken!);console.log("cache settings from API", data);-+if (data.fields) {setFields(data.fields);}@@ -67,7 +63,7 @@ const CacheSettings: React.FC<CacheSettingsProps> = ({ accessToken, userRole, ustry {const testSettings = gatherFormValues(fields, redisType);const result = await testCacheConnectionCall(accessToken, testSettings);-+if (result.status === "success") {NotificationsManager.success("Cache connection test successful!");} else {@@ -89,6 +85,9 @@ const CacheSettings: React.FC<CacheSettingsProps> = ({ accessToken, userRole, ussetIsSaving(true);try {const settingsToSave = gatherFormValues(fields, redisType);+ if (redisType === "semantic") {+ settingsToSave.type = "redis-semantic";+ }await updateCacheSettingsCall(accessToken, settingsToSave);NotificationsManager.success("Cache settings updated successfully");// Reload settings to reflect saved values@@ -105,14 +104,8 @@ const CacheSettings: React.FC<CacheSettingsProps> = ({ accessToken, userRole, usreturn null;}- const {- basicFields,- sslFields,- cacheManagementFields,- gcpFields,- clusterFields,- sentinelFields,- } = groupFieldsByCategory(fields, redisType);+ const { basicFields, sslFields, cacheManagementFields, gcpFields, clusterFields, sentinelFields, semanticFields } =+ groupFieldsByCategory(fields, redisType);return (<div className="w-full space-y-8 py-2">@@ -136,13 +129,7 @@ const CacheSettings: React.FC<CacheSettingsProps> = ({ accessToken, userRole, us{basicFields.map((field: any) => {if (!field) return null;const currentValue = cacheSettings[field.field_name] ?? field.field_default ?? "";- return (- <CacheFieldRenderer- key={field.field_name}- field={field}- currentValue={currentValue}- />- );+ return <CacheFieldRenderer key={field.field_name} field={field} currentValue={currentValue} />;})}</div></div>@@ -154,13 +141,7 @@ const CacheSettings: React.FC<CacheSettingsProps> = ({ accessToken, userRole, us<div className="grid grid-cols-1 gap-6">{clusterFields.map((field: any) => {const currentValue = cacheSettings[field.field_name] ?? field.field_default ?? "";- return (- <CacheFieldRenderer- key={field.field_name}- field={field}- currentValue={currentValue}- />- );+ return <CacheFieldRenderer key={field.field_name} field={field} currentValue={currentValue} />;})}</div></div>@@ -172,13 +153,19 @@ const CacheSettings: React.FC<CacheSettingsProps> = ({ accessToken, userRole, us<div className="grid grid-cols-1 gap-6 sm:grid-cols-2">{sentinelFields.map((field: any) => {const currentValue = cacheSettings[field.field_name] ?? field.field_default ?? "";- return (- <CacheFieldRenderer- key={field.field_name}- field={field}- currentValue={currentValue}- />- );+ return <CacheFieldRenderer key={field.field_name} field={field} currentValue={currentValue} />;+ })}+ </div>+ </div>+ )}++ {redisType === "semantic" && semanticFields.length > 0 && (+ <div className="space-y-6 pt-4 border-t border-gray-200">+ <h4 className="text-sm font-medium text-gray-900">Semantic Configuration</h4>+ <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">+ {semanticFields.map((field: any) => {+ const currentValue = cacheSettings[field.field_name] ?? field.field_default ?? "";+ return <CacheFieldRenderer key={field.field_name} field={field} currentValue={currentValue} />;})}</div></div>@@ -199,13 +186,7 @@ const CacheSettings: React.FC<CacheSettingsProps> = ({ accessToken, userRole, us{sslFields.map((field: any) => {if (!field) return null;const currentValue = cacheSettings[field.field_name] ?? field.field_default ?? "";- return (- <CacheFieldRenderer- key={field.field_name}- field={field}- currentValue={currentValue}- />- );+ return <CacheFieldRenderer key={field.field_name} field={field} currentValue={currentValue} />;})}</div></div>@@ -219,13 +200,7 @@ const CacheSettings: React.FC<CacheSettingsProps> = ({ accessToken, userRole, us{cacheManagementFields.map((field: any) => {if (!field) return null;const currentValue = cacheSettings[field.field_name] ?? field.field_default ?? "";- return (- <CacheFieldRenderer- key={field.field_name}- field={field}- currentValue={currentValue}- />- );+ return <CacheFieldRenderer key={field.field_name} field={field} currentValue={currentValue} />;})}</div></div>@@ -239,13 +214,7 @@ const CacheSettings: React.FC<CacheSettingsProps> = ({ accessToken, userRole, us{gcpFields.map((field: any) => {if (!field) return null;const currentValue = cacheSettings[field.field_name] ?? field.field_default ?? "";- return (- <CacheFieldRenderer- key={field.field_name}- field={field}- currentValue={currentValue}- />- );+ return <CacheFieldRenderer key={field.field_name} field={field} currentValue={currentValue} />;})}</div></div>@@ -257,29 +226,10 @@ const CacheSettings: React.FC<CacheSettingsProps> = ({ accessToken, userRole, us{/* Actions */}<div className="border-t border-gray-200 pt-6 flex justify-end gap-3">- <Button- variant="secondary"- size="sm"- onClick={handleTestConnection}- disabled={isTesting}- className="text-sm"- >+ <Button variant="secondary" size="sm" onClick={handleTestConnection} disabled={isTesting} className="text-sm">{isTesting ? "Testing..." : "Test Connection"}</Button>- <Button- variant="secondary"- size="sm"- onClick={() => window.location.reload()}- className="text-sm"- >- Reset- </Button>- <Button- size="sm"- onClick={handleSaveChanges}- disabled={isSaving}- className="text-sm font-medium"- >+ <Button size="sm" onClick={handleSaveChanges} disabled={isSaving} className="text-sm font-medium">{isSaving ? "Saving..." : "Save Changes"}</Button></div>diff --git a/ui/litellm-dashboard/src/components/router_settings/index.tsx b/ui/litellm-dashboard/src/components/router_settings/index.tsxindex 45d6ad39c83..a94860eacd1 100644--- a/ui/litellm-dashboard/src/components/router_settings/index.tsx+++ b/ui/litellm-dashboard/src/components/router_settings/index.tsx@@ -1,17 +1,11 @@-import React, { useState, useEffect } from "react";-import {- Button,-} from "@tremor/react";-import {- getCallbacksCall,- setCallbacksCall,- getRouterSettingsCall,-} from "../networking";+import { Button } from "@tremor/react";+import React, { useEffect, useState } from "react";import NotificationsManager from "../molecules/notifications_manager";-import RoutingStrategySelector from "./RoutingStrategySelector";-import TagFilteringToggle from "./TagFilteringToggle";+import { getCallbacksCall, getRouterSettingsCall, setCallbacksCall } from "../networking";import LatencyBasedConfiguration from "./LatencyBasedConfiguration";import ReliabilityRetriesSection from "./ReliabilityRetriesSection";+import RoutingStrategySelector from "./RoutingStrategySelector";+import TagFilteringToggle from "./TagFilteringToggle";interface RouterSettingsProps {accessToken: string | null;@@ -49,44 +43,40 @@ const RouterSettings: React.FC<RouterSettingsProps> = ({ accessToken, userRole,setSelectedStrategy(router_settings.routing_strategy);}});- getRouterSettingsCall(accessToken).then((data) => {- console.log("router settings from API", data);- if (data.fields) {- // Build metadata map for easy lookup- const fieldsMap: { [key: string]: any } = {};- data.fields.forEach((field: any) => {- fieldsMap[field.field_name] = {- ui_field_name: field.ui_field_name,- field_description: field.field_description,- options: field.options,- link: field.link,- };- });- setRouterFieldsMetadata(fieldsMap);-- // Extract routing strategies from the routing_strategy field's options- const routingStrategyField = data.fields.find(- (field: any) => field.field_name === "routing_strategy"- );- if (routingStrategyField?.options) {- setAvailableRoutingStrategies(routingStrategyField.options);- }+ getRouterSettingsCall(accessToken).then((data) => {+ console.log("router settings from API", data);+ if (data.fields) {+ // Build metadata map for easy lookup+ const fieldsMap: { [key: string]: any } = {};+ data.fields.forEach((field: any) => {+ fieldsMap[field.field_name] = {+ ui_field_name: field.ui_field_name,+ field_description: field.field_description,+ options: field.options,+ link: field.link,+ };+ });+ setRouterFieldsMetadata(fieldsMap);++ // Extract routing strategies from the routing_strategy field's options+ const routingStrategyField = data.fields.find((field: any) => field.field_name === "routing_strategy");+ if (routingStrategyField?.options) {+ setAvailableRoutingStrategies(routingStrategyField.options);+ }- // Store routing strategy descriptions- if (data.routing_strategy_descriptions) {- setRoutingStrategyDescriptions(data.routing_strategy_descriptions);- }+ // Store routing strategy descriptions+ if (data.routing_strategy_descriptions) {+ setRoutingStrategyDescriptions(data.routing_strategy_descriptions);+ }- // Set enable_tag_filtering value- const tagFilteringField = data.fields.find(- (field: any) => field.field_name === "enable_tag_filtering"- );- if (tagFilteringField?.field_value !== null && tagFilteringField?.field_value !== undefined) {- setEnableTagFiltering(tagFilteringField.field_value);- }+ // Set enable_tag_filtering value+ const tagFilteringField = data.fields.find((field: any) => field.field_name === "enable_tag_filtering");+ if (tagFilteringField?.field_value !== null && tagFilteringField?.field_value !== undefined) {+ setEnableTagFiltering(tagFilteringField.field_value);}- });- }, [accessToken, userRole, userID]);+ }+ });+ }, [accessToken, userRole, userID]);const handleSaveChanges = (router_settings: any) => {if (!accessToken) {@@ -125,24 +115,24 @@ const RouterSettings: React.FC<RouterSettingsProps> = ({ accessToken, userRole,return v;};- // Add enable_tag_filtering to router_settings before processing- const settingsToUpdate = {- ...router_settings,- enable_tag_filtering: enableTagFiltering,- };-- const updatedVariables = Object.fromEntries(- Object.entries(settingsToUpdate)- .map(([key, value]) => {- if (key !== "routing_strategy_args" && key !== "routing_strategy" && key !== "enable_tag_filtering") {- const inputEl = document.querySelector(`input[name="${key}"]`) as HTMLInputElement | null;- const parsed = parseInputValue(key, inputEl?.value, value);- return [key, parsed];- } else if (key === "routing_strategy") {- return [key, selectedStrategy];- } else if (key === "enable_tag_filtering") {- return [key, enableTagFiltering];- } else if (key === "routing_strategy_args" && selectedStrategy === "latency-based-routing") {+ // Add enable_tag_filtering to router_settings before processing+ const settingsToUpdate = {+ ...router_settings,+ enable_tag_filtering: enableTagFiltering,+ };++ const updatedVariables = Object.fromEntries(+ Object.entries(settingsToUpdate)+ .map(([key, value]) => {+ if (key !== "routing_strategy_args" && key !== "routing_strategy" && key !== "enable_tag_filtering") {+ const inputEl = document.querySelector(`input[name="${key}"]`) as HTMLInputElement | null;+ const parsed = parseInputValue(key, inputEl?.value, value);+ return [key, parsed];+ } else if (key === "routing_strategy") {+ return [key, selectedStrategy];+ } else if (key === "enable_tag_filtering") {+ return [key, enableTagFiltering];+ } else if (key === "routing_strategy_args" && selectedStrategy === "latency-based-routing") {let setRoutingStrategyArgs: routingStrategyArgs = {};const lowestLatencyBufferElement = document.querySelector(@@ -184,65 +174,51 @@ const RouterSettings: React.FC<RouterSettingsProps> = ({ accessToken, userRole,return null;}- return (- <div className="w-full space-y-8 py-2">- {/* Routing Settings Section */}- <div className="space-y-6">- <div className="max-w-3xl">- <h3 className="text-sm font-medium text-gray-900">Routing Settings</h3>- <p className="text-xs text-gray-500 mt-1">Configure how requests are routed to deployments</p>- </div>-- {/* Routing Strategy */}- {routerSettings.routing_strategy && (- <RoutingStrategySelector- selectedStrategy={selectedStrategy || routerSettings.routing_strategy}- availableStrategies={availableRoutingStrategies}- routingStrategyDescriptions={routingStrategyDescriptions}- routerFieldsMetadata={routerFieldsMetadata}- onStrategyChange={setSelectedStrategy}- />- )}-- {/* Tag Filtering */}- <TagFilteringToggle- enabled={enableTagFiltering}- routerFieldsMetadata={routerFieldsMetadata}- onToggle={setEnableTagFiltering}- />+ return (+ <div className="w-full space-y-8 py-2">+ {/* Routing Settings Section */}+ <div className="space-y-6">+ <div className="max-w-3xl">+ <h3 className="text-sm font-medium text-gray-900">Routing Settings</h3>+ <p className="text-xs text-gray-500 mt-1">Configure how requests are routed to deployments</p></div>- {/* Divider */}- <div className="border-t border-gray-200" />-- {/* Strategy-Specific Args - Show immediately after strategy if latency-based */}- {selectedStrategy === "latency-based-routing" && (- <LatencyBasedConfiguration- routingStrategyArgs={routerSettings["routing_strategy_args"]}+ {/* Routing Strategy */}+ {routerSettings.routing_strategy && (+ <RoutingStrategySelector+ selectedStrategy={selectedStrategy || routerSettings.routing_strategy}+ availableStrategies={availableRoutingStrategies}+ routingStrategyDescriptions={routingStrategyDescriptions}+ routerFieldsMetadata={routerFieldsMetadata}+ onStrategyChange={setSelectedStrategy}/>)}- {/* Other Settings */}- <ReliabilityRetriesSection- routerSettings={routerSettings}+ {/* Tag Filtering */}+ <TagFilteringToggle+ enabled={enableTagFiltering}routerFieldsMetadata={routerFieldsMetadata}+ onToggle={setEnableTagFiltering}/>+ </div>++ {/* Divider */}+ <div className="border-t border-gray-200" />++ {/* Strategy-Specific Args - Show immediately after strategy if latency-based */}+ {selectedStrategy === "latency-based-routing" && (+ <LatencyBasedConfiguration routingStrategyArgs={routerSettings["routing_strategy_args"]} />+ )}++ {/* Other Settings */}+ <ReliabilityRetriesSection routerSettings={routerSettings} routerFieldsMetadata={routerFieldsMetadata} />{/* Actions - Sticky at bottom */}<div className="border-t border-gray-200 pt-6 flex justify-end gap-3">- <Button- variant="secondary"- size="sm"- onClick={() => window.location.reload()}- className="text-sm"- >+ <Button variant="secondary" size="sm" onClick={() => window.location.reload()} className="text-sm">Reset</Button>- <Button- size="sm"- onClick={() => handleSaveChanges(routerSettings)}- className="text-sm font-medium"- >+ <Button size="sm" onClick={() => handleSaveChanges(routerSettings)} className="text-sm font-medium">Save Changes</Button></div>@@ -251,4 +227,3 @@ const RouterSettings: React.FC<RouterSettingsProps> = ({ accessToken, userRole,};export default RouterSettings;-