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
Implement health check frontend UI components and dashboard integration (#11679)
Cole McIntoshae74eb833b60
diff --git a/ui/litellm-dashboard/package-lock.json b/ui/litellm-dashboard/package-lock.jsonindex 00ba2f7588a..f0656e8eb0a 100644--- a/ui/litellm-dashboard/package-lock.json+++ b/ui/litellm-dashboard/package-lock.json@@ -4357,6 +4357,7 @@"version": "0.513.0","resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.513.0.tgz","integrity": "sha512-CJZKq2g8Y8yN4Aq002GahSXbG2JpFv9kXwyiOAMvUBv7pxeOFHUWKB0mO7MiY4ZVFCV4aNjv2BJFq/z3DgKPQg==",+ "license": "ISC","peerDependencies": {"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"}diff --git a/ui/litellm-dashboard/src/components/model_dashboard.tsx b/ui/litellm-dashboard/src/components/model_dashboard.tsxindex f27081cc130..9e2c0c3f45f 100644--- a/ui/litellm-dashboard/src/components/model_dashboard.tsx+++ b/ui/litellm-dashboard/src/components/model_dashboard.tsx@@ -78,6 +78,7 @@ import {Space,Row,Col,+ Checkbox,} from "antd";import { Badge, BadgeDelta, Button } from "@tremor/react";import RequestAccess from "./request_model_access";@@ -112,6 +113,7 @@ import ModelInfoView from "./model_info_view";import AddModelTab from "./add_model/add_model_tab";import { ModelDataTable } from "./model_dashboard/table";import { columns } from "./model_dashboard/columns";+import HealthCheckComponent from "./model_dashboard/HealthCheckComponent";import { all_admin_roles } from "@/utils/roles";import { Table as TableInstance } from '@tanstack/react-table';@@ -195,7 +197,8 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({[]);const [selectedProvider, setSelectedProvider] = useState<Providers>(Providers.OpenAI);- const [healthCheckResponse, setHealthCheckResponse] = useState<string>("");+ const [healthCheckResponse, setHealthCheckResponse] = useState<any>(null);+ const [isHealthCheckLoading, setIsHealthCheckLoading] = useState<boolean>(false);const [editModalVisible, setEditModalVisible] = useState<boolean>(false);const [selectedModel, setSelectedModel] = useState<any>(null);@@ -263,6 +266,8 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({const dropdownRef = useRef<HTMLDivElement>(null);const tableRef = useRef<TableInstance<any>>(null);++const setProviderModelsFn = (provider: Providers) => {const _providerModels = getProviderModels(provider, modelMap);setProviderModels(_providerModels);@@ -524,7 +529,7 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({setProviderSettings(_providerSettings);}-+// loop through modelDataResponse and get all`model_name` valueslet all_model_groups: Set<string> = new Set();@@ -814,15 +819,20 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({const runHealthCheck = async () => {try {message.info("Running health check...");- setHealthCheckResponse("");+ setIsHealthCheckLoading(true);+ setHealthCheckResponse(null);const response = await healthCheckCall(accessToken);setHealthCheckResponse(response);} catch (error) {console.error("Error running health check:", error);setHealthCheckResponse("Error running health check");+ } finally {+ setIsHealthCheckLoading(false);}};++const FilterByContent = (<div ><Text className="mb-1">Select API Key Name</Text>@@ -1085,7 +1095,7 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({<Tab>Add Model</Tab>{all_admin_roles.includes(userRole) && <Tab>LLM Credentials</Tab>}{all_admin_roles.includes(userRole) && <Tab>- <pre>/health Models</pre>+ Health Status</Tab>}{all_admin_roles.includes(userRole) && <Tab>Model Analytics</Tab>}{all_admin_roles.includes(userRole) && <Tab>Model Retry Settings</Tab>}@@ -1254,17 +1264,12 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({<CredentialsPanel accessToken={accessToken} uploadProps={uploadProps} credentialList={credentialsList} fetchCredentials={fetchCredentials} /></TabPanel><TabPanel>- <Card>- <Text>- `/health` will run a very small request through your models- configured on litellm- </Text>-- <Button onClick={runHealthCheck}>Run `/health`</Button>- {healthCheckResponse && (- <pre>{JSON.stringify(healthCheckResponse, null, 2)}</pre>- )}- </Card>+ <HealthCheckComponent+ accessToken={accessToken}+ modelData={modelData}+ all_models_on_proxy={all_models_on_proxy}+ getDisplayModelName={getDisplayModelName}+ /></TabPanel><TabPanel><Grid numItems={4} className="mt-2 mb-2">@@ -1612,6 +1617,7 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({</TabPanels></TabGroup>)}+</div>);};diff --git a/ui/litellm-dashboard/src/components/model_dashboard/HealthCheckComponent.tsx b/ui/litellm-dashboard/src/components/model_dashboard/HealthCheckComponent.tsxnew file mode 100644index 00000000000..6444031bc12--- /dev/null+++ b/ui/litellm-dashboard/src/components/model_dashboard/HealthCheckComponent.tsx@@ -0,0 +1,575 @@+import React, { useState, useEffect, useRef } from "react";+import { Title, Text, Button, Badge } from "@tremor/react";+import { Modal, message } from "antd";+import { Button as AntdButton } from "antd";+import { ModelDataTable } from "./table";+import { healthCheckColumns } from "./health_check_columns";+import { errorPatterns } from "@/utils/errorPatterns";+import {+ individualModelHealthCheckCall,+ latestHealthChecksCall,+} from "../networking";+import { Table as TableInstance } from '@tanstack/react-table';++interface HealthStatus {+ status: string;+ lastCheck: string;+ loading: boolean;+ error?: string;+ fullError?: string;+}++interface HealthCheckComponentProps {+ accessToken: string | null;+ modelData: any;+ all_models_on_proxy: string[];+ getDisplayModelName: (model: any) => string;+}++const HealthCheckComponent: React.FC<HealthCheckComponentProps> = ({+ accessToken,+ modelData,+ all_models_on_proxy,+ getDisplayModelName,+}) => {+ const [modelHealthStatuses, setModelHealthStatuses] = useState<{[key: string]: HealthStatus}>({});+ const [selectedModelsForHealth, setSelectedModelsForHealth] = useState<string[]>([]);+ const [allModelsSelected, setAllModelsSelected] = useState<boolean>(false);+ const [errorModalVisible, setErrorModalVisible] = useState(false);+ const [selectedErrorDetails, setSelectedErrorDetails] = useState<{+ modelName: string;+ cleanedError: string;+ fullError: string;+ } | null>(null);++ const healthTableRef = useRef<TableInstance<any>>(null);++ // Initialize health statuses on component mount+ useEffect(() => {+ if (!accessToken || !modelData?.data) return;++ const initializeHealthStatuses = async () => {+ const healthStatusMap: {[key: string]: HealthStatus} = {};++ // Initialize all models with default state using model names+ modelData.data.forEach((model: any) => {+ const modelName = model.model_name;+ healthStatusMap[modelName] = {+ status: 'none',+ lastCheck: 'None',+ loading: false,+ error: undefined,+ fullError: undefined,+ };+ });++ try {+ const latestHealthChecks = await latestHealthChecksCall(accessToken);++ // Override with actual database data if it exists+ if (latestHealthChecks && latestHealthChecks.latest_health_checks && typeof latestHealthChecks.latest_health_checks === 'object') {+ Object.entries(latestHealthChecks.latest_health_checks).forEach(([key, checkData]: [string, any]) => {+ if (!checkData) return;++ let targetModelName: string | null = null;++ // The key could be either model_id or model_name, try both approaches+ const directModelMatch = modelData.data.find((m: any) => m.model_name === key);+ if (directModelMatch) {+ targetModelName = directModelMatch.model_name;+ } else {+ // If not a direct match, treat as model_id and find the corresponding model+ const modelByIdMatch = modelData.data.find((m: any) => m.model_info && m.model_info.id === key);+ if (modelByIdMatch) {+ targetModelName = modelByIdMatch.model_name;+ } else {+ // Check if checkData contains model_name and use that+ if (checkData.model_name) {+ const modelByNameInData = modelData.data.find((m: any) => m.model_name === checkData.model_name);+ if (modelByNameInData) {+ targetModelName = modelByNameInData.model_name;+ }+ }+ }+ }++ if (targetModelName) {+ const fullError = checkData.error_message || undefined;++ healthStatusMap[targetModelName] = {+ status: checkData.status || 'unknown',+ lastCheck: checkData.checked_at ? new Date(checkData.checked_at).toLocaleString() : 'None',+ loading: false,+ error: fullError ? extractMeaningfulError(fullError) : undefined,+ fullError: fullError,+ };+ }+ });+ }+ } catch (healthError) {+ console.warn("Failed to load health check history (using default states):", healthError);+ }++ setModelHealthStatuses(healthStatusMap);+ };++ initializeHealthStatuses();+ }, [accessToken, modelData]);++ // Helper function to extract meaningful error information+ const extractMeaningfulError = (error: any): string => {+ if (!error) return 'Health check failed';++ let errorStr = typeof error === 'string' ? error : JSON.stringify(error);++ // First, look for explicit "ErrorType: StatusCode" patterns+ const directPatternMatch = errorStr.match(/(\w+Error):\s*(\d{3})/i);+ if (directPatternMatch) {+ return `${directPatternMatch[1]}: ${directPatternMatch[2]}`;+ }++ // Look for error types and status codes separately, then combine them+ const errorTypeMatch = errorStr.match(/(AuthenticationError|RateLimitError|BadRequestError|InternalServerError|TimeoutError|NotFoundError|ForbiddenError|ServiceUnavailableError|BadGatewayError|ContentPolicyViolationError|\w+Error)/i);+ const statusCodeMatch = errorStr.match(/\b(400|401|403|404|408|429|500|502|503|504)\b/);++ if (errorTypeMatch && statusCodeMatch) {+ return `${errorTypeMatch[1]}: ${statusCodeMatch[1]}`;+ }++ // If we have a status code but no clear error type, map it+ if (statusCodeMatch) {+ const statusCode = statusCodeMatch[1];+ const statusToError: {[key: string]: string} = {+ '400': 'BadRequestError',+ '401': 'AuthenticationError',+ '403': 'ForbiddenError',+ '404': 'NotFoundError',+ '408': 'TimeoutError',+ '429': 'RateLimitError',+ '500': 'InternalServerError',+ '502': 'BadGatewayError',+ '503': 'ServiceUnavailableError',+ '504': 'GatewayTimeoutError',+ };+ return `${statusToError[statusCode]}: ${statusCode}`;+ }++ // If we have an error type but no status code, map error type to expected status code+ if (errorTypeMatch) {+ const errorType = errorTypeMatch[1];+ const errorToStatus: {[key: string]: string} = {+ 'AuthenticationError': '401',+ 'RateLimitError': '429',+ 'BadRequestError': '400',+ 'InternalServerError': '500',+ 'TimeoutError': '408',+ 'NotFoundError': '404',+ 'ForbiddenError': '403',+ 'ServiceUnavailableError': '503',+ 'BadGatewayError': '502',+ 'GatewayTimeoutError': '504',+ 'ContentPolicyViolationError': '400',+ };++ const mappedStatus = errorToStatus[errorType];+ if (mappedStatus) {+ return `${errorType}: ${mappedStatus}`;+ }+ return errorType;+ }++ // Check for specific error patterns from errorPatterns+ for (const { pattern, replacement } of errorPatterns) {+ if (pattern.test(errorStr)) {+ return replacement;+ }+ }++ // Look for common error keywords and provide meaningful names with status codes+ if (/missing.*api.*key|invalid.*key|unauthorized/i.test(errorStr)) {+ return 'AuthenticationError: 401';+ }+ if (/rate.*limit|too.*many.*requests/i.test(errorStr)) {+ return 'RateLimitError: 429';+ }+ if (/timeout|timed.*out/i.test(errorStr)) {+ return 'TimeoutError: 408';+ }+ if (/not.*found/i.test(errorStr)) {+ return 'NotFoundError: 404';+ }+ if (/forbidden|access.*denied/i.test(errorStr)) {+ return 'ForbiddenError: 403';+ }+ if (/internal.*server.*error/i.test(errorStr)) {+ return 'InternalServerError: 500';+ }++ // Fallback: clean up the error string and return first meaningful part+ const cleaned = errorStr+ .replace(/[\n\r]+/g, ' ')+ .replace(/\s+/g, ' ')+ .trim();++ // Try to get first meaningful sentence or phrase+ const sentences = cleaned.split(/[.!?]/);+ const firstSentence = sentences[0]?.trim();++ if (firstSentence && firstSentence.length > 0) {+ return firstSentence.length > 100 ? firstSentence.substring(0, 97) + '...' : firstSentence;+ }++ return cleaned.length > 100 ? cleaned.substring(0, 97) + '...' : cleaned;+ };++ const runIndividualHealthCheck = async (modelName: string) => {+ if (!accessToken) return;++ setModelHealthStatuses(prev => ({+ ...prev,+ [modelName]: {+ ...prev[modelName],+ loading: true,+ status: 'checking'+ }+ }));++ try {+ // Run the health check and process the response directly+ const response = await individualModelHealthCheckCall(accessToken, modelName);+ const currentTime = new Date().toLocaleString();++ // Check if there are any unhealthy endpoints (which means this specific model failed)+ if (response.unhealthy_count > 0 && response.unhealthy_endpoints && response.unhealthy_endpoints.length > 0) {+ const rawError = response.unhealthy_endpoints[0]?.error || 'Health check failed';+ const errorMessage = extractMeaningfulError(rawError);+ setModelHealthStatuses(prev => ({+ ...prev,+ [modelName]: {+ status: 'unhealthy',+ lastCheck: currentTime,+ loading: false,+ error: errorMessage,+ fullError: rawError+ }+ }));+ } else {+ setModelHealthStatuses(prev => ({+ ...prev,+ [modelName]: {+ status: 'healthy',+ lastCheck: currentTime,+ loading: false+ }+ }));+ }++ // Refresh health status from database to get the saved check data including timestamp+ try {+ const latestHealthChecks = await latestHealthChecksCall(accessToken);++ // Find the model ID for this model name to look up database data+ const model = modelData.data.find((m: any) => m.model_name === modelName);+ if (model) {+ const modelId = model.model_info.id;+ const checkData = latestHealthChecks.latest_health_checks?.[modelId];++ if (checkData) {+ const fullError = checkData.error_message || undefined;+ setModelHealthStatuses(prev => ({+ ...prev,+ [modelName]: {+ status: checkData.status || prev[modelName]?.status || 'unknown',+ lastCheck: checkData.checked_at ? new Date(checkData.checked_at).toLocaleString() : prev[modelName]?.lastCheck || 'None',+ loading: false,+ error: fullError ? extractMeaningfulError(fullError) : prev[modelName]?.error,+ fullError: fullError || prev[modelName]?.fullError,+ }+ }));+ }+ }+ } catch (dbError) {+ // Ignore database errors - we already have the health check result from the API call+ console.debug("Could not fetch updated status from database (non-critical):", dbError);+ }++ } catch (error) {+ const currentTime = new Date().toLocaleString();+ const rawError = error instanceof Error ? error.message : String(error);+ const errorMessage = extractMeaningfulError(rawError);+ setModelHealthStatuses(prev => ({+ ...prev,+ [modelName]: {+ status: 'unhealthy',+ lastCheck: currentTime,+ loading: false,+ error: errorMessage,+ fullError: rawError+ }+ }));+ }+ };++ const runAllHealthChecks = async () => {+ const modelsToCheck = selectedModelsForHealth.length > 0 ? selectedModelsForHealth : all_models_on_proxy;++ // Set all models to loading state+ const loadingStatuses = modelsToCheck.reduce((acc, modelName) => {+ acc[modelName] = {+ ...modelHealthStatuses[modelName],+ loading: true,+ status: 'checking'+ };+ return acc;+ }, {} as typeof modelHealthStatuses);++ setModelHealthStatuses(prev => ({ ...prev, ...loadingStatuses }));++ // Store results from individual health checks+ const healthCheckResults: {[key: string]: any} = {};++ // Run all health checks in parallel and collect results+ const healthCheckPromises = modelsToCheck.map(async (modelName) => {+ if (!accessToken) return;++ try {+ // Run the health check and store the result+ const response = await individualModelHealthCheckCall(accessToken, modelName);+ healthCheckResults[modelName] = response;++ // Update status immediately based on response+ const currentTime = new Date().toLocaleString();+ // Check if there are any unhealthy endpoints (which means this specific model failed)+ if (response.unhealthy_count > 0 && response.unhealthy_endpoints && response.unhealthy_endpoints.length > 0) {+ const rawError = response.unhealthy_endpoints[0]?.error || 'Health check failed';+ const errorMessage = extractMeaningfulError(rawError);+ setModelHealthStatuses(prev => ({+ ...prev,+ [modelName]: {+ status: 'unhealthy',+ lastCheck: currentTime,+ loading: false,+ error: errorMessage,+ fullError: rawError+ }+ }));+ } else {+ setModelHealthStatuses(prev => ({+ ...prev,+ [modelName]: {+ status: 'healthy',+ lastCheck: currentTime,+ loading: false+ }+ }));+ }+ } catch (error) {+ console.error(`Health check failed for ${modelName}:`, error);+ // Set error status for failed health checks+ const currentTime = new Date().toLocaleString();+ const rawError = error instanceof Error ? error.message : String(error);+ const errorMessage = extractMeaningfulError(rawError);+ setModelHealthStatuses(prev => ({+ ...prev,+ [modelName]: {+ status: 'unhealthy',+ lastCheck: currentTime,+ loading: false,+ error: errorMessage,+ fullError: rawError+ }+ }));+ }+ });++ // Wait for all health checks to complete+ await Promise.allSettled(healthCheckPromises);++ // Refresh health statuses from database to get the saved check data including timestamps+ try {+ if (!accessToken) return;+ const latestHealthChecks = await latestHealthChecksCall(accessToken);++ if (latestHealthChecks.latest_health_checks) {+ // Update health statuses from database, which should have the most accurate saved data+ Object.entries(latestHealthChecks.latest_health_checks).forEach(([modelId, checkData]: [string, any]) => {+ // Find the model name for this model ID+ const model = modelData.data.find((m: any) => m.model_info.id === modelId);+ if (model && modelsToCheck.includes(model.model_name) && checkData) {+ const modelName = model.model_name;+ const fullError = checkData.error_message || undefined;+ setModelHealthStatuses(prev => {+ const currentStatus = prev[modelName];+ return {+ ...prev,+ [modelName]: {+ status: checkData.status || currentStatus?.status || 'unknown',+ lastCheck: checkData.checked_at ? new Date(checkData.checked_at).toLocaleString() : currentStatus?.lastCheck || 'None',+ loading: false,+ error: fullError ? extractMeaningfulError(fullError) : currentStatus?.error,+ fullError: fullError || currentStatus?.fullError,+ }+ };+ });+ }+ });+ }+ } catch (dbError) {+ console.warn("Failed to fetch updated health statuses from database (non-critical):", dbError);+ // This is non-critical - we already have the health check results from the API calls+ }+ };++ const handleModelSelection = (modelName: string, checked: boolean) => {+ if (checked) {+ setSelectedModelsForHealth(prev => [...prev, modelName]);+ } else {+ setSelectedModelsForHealth(prev => prev.filter(name => name !== modelName));+ setAllModelsSelected(false);+ }+ };++ const handleSelectAll = (checked: boolean) => {+ setAllModelsSelected(checked);+ if (checked) {+ setSelectedModelsForHealth(all_models_on_proxy);+ } else {+ setSelectedModelsForHealth([]);+ }+ };++ const getStatusBadge = (status: string) => {+ switch (status) {+ case 'healthy':+ return <Badge color="emerald">healthy</Badge>;+ case 'unhealthy':+ return <Badge color="red">unhealthy</Badge>;+ case 'checking':+ return <Badge color="blue">checking</Badge>;+ case 'none':+ return <Badge color="gray">none</Badge>;+ default:+ return <Badge color="gray">unknown</Badge>;+ }+ };++ const showErrorModal = (modelName: string, cleanedError: string, fullError: string) => {+ setSelectedErrorDetails({+ modelName,+ cleanedError,+ fullError+ });+ setErrorModalVisible(true);+ };++ const closeErrorModal = () => {+ setErrorModalVisible(false);+ setSelectedErrorDetails(null);+ };++ return (+ <div className="bg-white rounded-lg shadow">+ <div className="border-b px-6 py-4">+ <div className="flex justify-between items-center">+ <div>+ <Title>Model Health Status</Title>+ <Text className="text-gray-600 mt-1">+ Run health checks on individual models to verify they are working correctly+ </Text>+ </div>+ <div className="flex items-center gap-3">+ {selectedModelsForHealth.length > 0 && (+ <Button+ size="sm"+ variant="light"+ onClick={() => handleSelectAll(false)}+ className="px-3 py-1 text-sm"+ >+ Clear Selection+ </Button>+ )}+ <Button+ size="sm"+ variant="secondary"+ onClick={runAllHealthChecks}+ disabled={Object.values(modelHealthStatuses).some(status => status.loading)}+ className="px-3 py-1 text-sm"+ >+ {selectedModelsForHealth.length > 0 && selectedModelsForHealth.length < all_models_on_proxy.length+ ? 'Run Selected Checks'+ : 'Run All Checks'}+ </Button>+ </div>+ </div>+ </div>++ <div className="p-6">+ <ModelDataTable+ columns={healthCheckColumns(+ modelHealthStatuses,+ selectedModelsForHealth,+ allModelsSelected,+ handleModelSelection,+ handleSelectAll,+ runIndividualHealthCheck,+ getStatusBadge,+ getDisplayModelName,+ showErrorModal,+ )}+ data={modelData.data.map((model: any) => {+ const modelName = model.model_name;+ const healthStatus = modelHealthStatuses[modelName] || { status: 'none', lastCheck: 'None', loading: false };+ return {+ model_name: model.model_name,+ model_info: model.model_info,+ provider: model.provider,+ litellm_model_name: model.litellm_model_name,+ health_status: healthStatus.status,+ last_check: healthStatus.lastCheck,+ health_loading: healthStatus.loading,+ health_error: healthStatus.error,+ health_full_error: healthStatus.fullError,+ };+ })}+ isLoading={false}+ table={healthTableRef}+ />+ </div>++ {/* Error Modal */}+ <Modal+ title={selectedErrorDetails ? `Health Check Error - ${selectedErrorDetails.modelName}` : 'Error Details'}+ open={errorModalVisible}+ onCancel={closeErrorModal}+ footer={[+ <AntdButton key="close" onClick={closeErrorModal}>+ Close+ </AntdButton>+ ]}+ width={800}+ >+ {selectedErrorDetails && (+ <div className="space-y-4">+ <div>+ <Text className="font-medium">Error:</Text>+ <div className="mt-2 p-3 bg-red-50 border border-red-200 rounded-md">+ <Text className="text-red-800">{selectedErrorDetails.cleanedError}</Text>+ </div>+ </div>++ <div>+ <Text className="font-medium">Full Error Details:</Text>+ <div className="mt-2 p-3 bg-gray-50 border border-gray-200 rounded-md max-h-96 overflow-y-auto">+ <pre className="text-sm text-gray-800 whitespace-pre-wrap">+ {selectedErrorDetails.fullError}+ </pre>+ </div>+ </div>+ </div>+ )}+ </Modal>+ </div>+ );+};++export default HealthCheckComponent;\ No newline at end of filediff --git a/ui/litellm-dashboard/src/components/model_dashboard/health_check_columns.tsx b/ui/litellm-dashboard/src/components/model_dashboard/health_check_columns.tsxnew file mode 100644index 00000000000..eaee6181f5c--- /dev/null+++ b/ui/litellm-dashboard/src/components/model_dashboard/health_check_columns.tsx@@ -0,0 +1,244 @@+import { ColumnDef } from "@tanstack/react-table";+import { Button, Badge } from "@tremor/react";+import { Tooltip, Checkbox } from "antd";+import { Text } from "@tremor/react";+import { InformationCircleIcon } from "@heroicons/react/outline";++interface HealthCheckData {+ model_name: string;+ model_info: {+ id: string;+ created_at?: string;+ team_id?: string;+ };+ provider?: string;+ litellm_model_name?: string;+ health_status: string;+ last_check: string;+ health_loading: boolean;+ health_error?: string;+ health_full_error?: string;+}++interface HealthStatus {+ status: string;+ lastCheck: string;+ loading: boolean;+ error?: string;+ fullError?: string;+}++export const healthCheckColumns = (+ modelHealthStatuses: {[key: string]: HealthStatus},+ selectedModelsForHealth: string[],+ allModelsSelected: boolean,+ handleModelSelection: (modelName: string, checked: boolean) => void,+ handleSelectAll: (checked: boolean) => void,+ runIndividualHealthCheck: (modelName: string) => void,+ getStatusBadge: (status: string) => JSX.Element,+ getDisplayModelName: (model: any) => string,+ showErrorModal?: (modelName: string, cleanedError: string, fullError: string) => void,+): ColumnDef<HealthCheckData>[] => [+ {+ header: () => (+ <div className="flex items-center gap-2">+ <Checkbox+ checked={allModelsSelected}+ indeterminate={selectedModelsForHealth.length > 0 && !allModelsSelected}+ onChange={(e) => handleSelectAll(e.target.checked)}+ />+ <span>Model ID</span>+ </div>+ ),+ accessorKey: "model_info.id",+ enableSorting: true,+ sortingFn: "alphanumeric",+ cell: ({ row }) => {+ const model = row.original;+ const modelName = model.model_name;+ const isSelected = selectedModelsForHealth.includes(modelName);++ return (+ <div className="flex items-center gap-2">+ <Checkbox+ checked={isSelected}+ onChange={(e) => handleModelSelection(modelName, e.target.checked)}+ />+ <Tooltip title={model.model_info.id}>+ <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]"+ >+ {model.model_info.id}+ </div>+ </Tooltip>+ </div>+ );+ },+ },+ {+ header: "Model Name",+ accessorKey: "model_name",+ enableSorting: true,+ sortingFn: "alphanumeric",+ cell: ({ row }) => {+ const model = row.original;+ const displayName = getDisplayModelName(model) || model.model_name;++ return (+ <div className="font-medium text-sm">+ <Tooltip title={displayName}>+ <div className="truncate max-w-[200px]">+ {displayName}+ </div>+ </Tooltip>+ </div>+ );+ },+ },+ {+ header: "Health Status",+ accessorKey: "health_status",+ enableSorting: true,+ sortingFn: (rowA, rowB, columnId) => {+ const statusA = rowA.getValue("health_status") as string || 'unknown';+ const statusB = rowB.getValue("health_status") as string || 'unknown';++ // Define sorting order: healthy > checking > unknown > unhealthy+ const statusOrder = { 'healthy': 0, 'checking': 1, 'unknown': 2, 'unhealthy': 3 };+ const orderA = statusOrder[statusA as keyof typeof statusOrder] ?? 4;+ const orderB = statusOrder[statusB as keyof typeof statusOrder] ?? 4;++ return orderA - orderB;+ },+ cell: ({ row }) => {+ const model = row.original;+ const healthStatus = {+ status: model.health_status,+ loading: model.health_loading,+ error: model.health_error+ };++ if (healthStatus.loading) {+ return (+ <div className="flex items-center space-x-2">+ <div className="flex space-x-1">+ <div className="w-2 h-2 bg-indigo-500 rounded-full animate-pulse"></div>+ <div className="w-2 h-2 bg-indigo-500 rounded-full animate-pulse" style={{animationDelay: '0.2s'}}></div>+ <div className="w-2 h-2 bg-indigo-500 rounded-full animate-pulse" style={{animationDelay: '0.4s'}}></div>+ </div>+ <Text className="text-gray-600 text-sm">Checking...</Text>+ </div>+ );+ }++ return (+ <div className="flex items-center space-x-2">+ {getStatusBadge(healthStatus.status)}+ </div>+ );+ },+ },+ {+ header: "Error Details",+ accessorKey: "health_error",+ enableSorting: false,+ cell: ({ row }) => {+ const model = row.original;+ const modelName = model.model_name;+ const healthStatus = modelHealthStatuses[modelName];++ if (!healthStatus?.error) {+ return <Text className="text-gray-400 text-sm">No errors</Text>;+ }++ const cleanedError = healthStatus.error;+ const fullError = healthStatus.fullError || healthStatus.error;++ return (+ <div className="flex items-center space-x-2">+ <div className="max-w-[200px]">+ <Tooltip title={cleanedError} placement="top">+ <Text className="text-red-600 text-sm truncate">+ {cleanedError}+ </Text>+ </Tooltip>+ </div>+ {showErrorModal && fullError !== cleanedError && (+ <Tooltip title="View full error details" placement="top">+ <button+ onClick={() => showErrorModal(modelName, cleanedError, fullError)}+ className="p-1 text-red-600 hover:text-red-800 hover:bg-red-50 rounded cursor-pointer transition-colors"+ >+ <InformationCircleIcon className="h-4 w-4" />+ </button>+ </Tooltip>+ )}+ </div>+ );+ },+ },+ {+ header: "Last Check",+ accessorKey: "last_check",+ enableSorting: true,+ sortingFn: (rowA, rowB, columnId) => {+ const lastCheckA = rowA.getValue("last_check") as string || 'Never checked';+ const lastCheckB = rowB.getValue("last_check") as string || 'Never checked';++ // Handle special cases+ if (lastCheckA === 'Never checked' && lastCheckB === 'Never checked') return 0;+ if (lastCheckA === 'Never checked') return 1; // Never checked goes to bottom+ if (lastCheckB === 'Never checked') return -1;+ if (lastCheckA === 'Check in progress...' && lastCheckB === 'Check in progress...') return 0;+ if (lastCheckA === 'Check in progress...') return -1; // In progress goes to top+ if (lastCheckB === 'Check in progress...') return 1;++ // Parse dates for comparison+ const dateA = new Date(lastCheckA);+ const dateB = new Date(lastCheckB);++ // If dates are invalid, treat as never checked+ if (isNaN(dateA.getTime()) && isNaN(dateB.getTime())) return 0;+ if (isNaN(dateA.getTime())) return 1;+ if (isNaN(dateB.getTime())) return -1;++ // Sort by date (most recent first)+ return dateB.getTime() - dateA.getTime();+ },+ cell: ({ row }) => {+ const model = row.original;++ return (+ <Text className="text-gray-600 text-sm">+ {model.health_loading ? 'Check in progress...' : model.last_check}+ </Text>+ );+ },+ },+ {+ header: "Actions",+ id: "actions",+ cell: ({ row }) => {+ const model = row.original;+ const modelName = model.model_name;++ return (+ <div+ className={`text-sm cursor-pointer ${+ model.health_loading+ ? 'text-gray-400 cursor-not-allowed'+ : 'text-indigo-600 hover:text-indigo-700 hover:underline'+ }`}+ onClick={() => {+ if (!model.health_loading) {+ runIndividualHealthCheck(modelName);+ }+ }}+ >+ {model.health_loading ? 'Checking...' : 'Run Check'}+ </div>+ );+ },+ enableSorting: false,+ },+];\ No newline at end of filediff --git a/ui/litellm-dashboard/src/components/model_dashboard/table.tsx b/ui/litellm-dashboard/src/components/model_dashboard/table.tsxindex 9818ace3db0..c3e0c03c5fd 100644--- a/ui/litellm-dashboard/src/components/model_dashboard/table.tsx+++ b/ui/litellm-dashboard/src/components/model_dashboard/table.tsx@@ -92,7 +92,7 @@ export function ModelDataTable<TData, TValue>({<div className="rounded-lg custom-border relative"><div className="overflow-x-auto"><div className="relative min-w-full">- <Table className="[&_td]:py-0.5 [&_th]:py-1 w-full">+ <Table className="[&_td]:py-2 [&_th]:py-2 w-full"><TableHead>{tableInstance.getHeaderGroups().map((headerGroup) => (<TableRow key={headerGroup.id}>diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsxindex 767c375ce68..3e4af1d6d24 100644--- a/ui/litellm-dashboard/src/components/networking.tsx+++ b/ui/litellm-dashboard/src/components/networking.tsx@@ -4284,6 +4284,34 @@ export const healthCheckCall = async (accessToken: String) => {}};+export const individualModelHealthCheckCall = async (accessToken: String, modelName: string) => {+ /**+ * Run health check for a specific model using model name+ */+ try {+ let url = proxyBaseUrl ? `${proxyBaseUrl}/health?model=${encodeURIComponent(modelName)}` : `/health?model=${encodeURIComponent(modelName)}`;++ const response = await fetch(url, {+ method: "GET",+ headers: {+ [globalLitellmHeaderName]: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ });++ if (!response.ok) {+ const errorData = await response.text();+ throw new Error(errorData || "Network response was not ok");+ }++ const data = await response.json();+ return data;+ } catch (error) {+ console.error(`Failed to call /health for model ${modelName}:`, error);+ throw error;+ }+};+export const cachingHealthCheckCall = async (accessToken: String) => {/*** Get all the models user has access to@@ -4316,6 +4344,80 @@ export const cachingHealthCheckCall = async (accessToken: String) => {}};+export const healthCheckHistoryCall = async (+ accessToken: String,+ model?: string,+ statusFilter?: string,+ limit: number = 100,+ offset: number = 0+) => {+ /**+ * Get health check history for models+ */+ try {+ let url = proxyBaseUrl ? `${proxyBaseUrl}/health/history` : `/health/history`;++ const params = new URLSearchParams();+ if (model) params.append('model', model);+ if (statusFilter) params.append('status_filter', statusFilter);+ params.append('limit', limit.toString());+ params.append('offset', offset.toString());++ if (params.toString()) {+ url += `?${params.toString()}`;+ }++ const response = await fetch(url, {+ method: "GET",+ headers: {+ [globalLitellmHeaderName]: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ });++ if (!response.ok) {+ const errorData = await response.text();+ handleError(errorData);+ throw new Error(errorData);+ }++ const data = await response.json();+ return data;+ } catch (error) {+ console.error("Failed to call /health/history:", error);+ throw error;+ }+};++export const latestHealthChecksCall = async (accessToken: String) => {+ /**+ * Get the latest health check status for all models+ */+ try {+ let url = proxyBaseUrl ? `${proxyBaseUrl}/health/latest` : `/health/latest`;++ const response = await fetch(url, {+ method: "GET",+ headers: {+ [globalLitellmHeaderName]: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ });++ if (!response.ok) {+ const errorData = await response.text();+ handleError(errorData);+ throw new Error(errorData);+ }++ const data = await response.json();+ return data;+ } catch (error) {+ console.error("Failed to call /health/latest:", error);+ throw error;+ }+};+export const getProxyUISettings = async (accessToken: String,) => {diff --git a/ui/litellm-dashboard/src/utils/errorPatterns.ts b/ui/litellm-dashboard/src/utils/errorPatterns.tsnew file mode 100644index 00000000000..3b46a6604d0--- /dev/null+++ b/ui/litellm-dashboard/src/utils/errorPatterns.ts@@ -0,0 +1,53 @@+export interface ErrorPattern {+ pattern: RegExp;+ replacement: string;+}++// Centralised list of common error patterns.+// Add new patterns here without touching component files.+export const errorPatterns: ErrorPattern[] = [+ // Generic missing API key (covers OpenAI, Anthropic, etc.)+ {+ pattern: /Missing .* API Key/i,+ replacement: 'Missing API Key',+ },+ // Network / connectivity issues+ {+ pattern: /Connection timeout/i,+ replacement: 'Connection timeout',+ },+ {+ pattern: /Network.*not.*ok/i,+ replacement: 'Network connection failed',+ },+ // HTTP status based errors+ {+ 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',+ },+ // LiteLLM specific wrapped errors+ {+ pattern: /litellm\.AuthenticationError/i,+ replacement: 'Authentication failed',+ },+ {+ pattern: /litellm\.RateLimitError/i,+ replacement: 'Rate limit exceeded',+ },+ {+ pattern: /litellm\.APIError/i,+ replacement: 'API error',+ },+];\ No newline at end of file