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
feat(ui): migrate playground chat controls toward shadcn
mubashir1osmanif5d98c0b8ce1
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/A2AMetrics.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/A2AMetrics.tsxindex 004a513f061..6ddfe1442f5 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/A2AMetrics.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/A2AMetrics.tsx@@ -1,17 +1,19 @@import React, { useState } from "react";-import { Tooltip, Button } from "antd";import {- CheckCircleOutlined,- ClockCircleOutlined,- LoadingOutlined,- ExclamationCircleOutlined,- CopyOutlined,- DownOutlined,- RightOutlined,- LinkOutlined,- FileTextOutlined,- RobotOutlined,-} from "@ant-design/icons";+ Bot,+ CheckCircle,+ ChevronDown,+ ChevronRight,+ CircleAlert,+ Clock,+ Copy,+ FileText,+ Link,+ LoaderCircle,+} from "lucide-react";+import { Button } from "@/components/ui/button";+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";export interface A2ATaskMetadata {taskId?: string;@@ -21,7 +23,7 @@ export interface A2ATaskMetadata {timestamp?: string;message?: string;};- metadata?: Record<string, any>;+ metadata?: Record<string, unknown>;}interface A2AMetricsProps {@@ -33,15 +35,15 @@ interface A2AMetricsProps {const getStatusIcon = (state?: string) => {switch (state) {case "completed":- return <CheckCircleOutlined className="text-green-500" />;+ return <CheckCircle className="size-3 text-green-500" />;case "working":case "submitted":- return <LoadingOutlined className="text-blue-500" />;+ return <LoaderCircle className="size-3 animate-spin text-blue-500" />;case "failed":case "canceled":- return <ExclamationCircleOutlined className="text-red-500" />;+ return <CircleAlert className="size-3 text-red-500" />;default:- return <ClockCircleOutlined className="text-gray-500" />;+ return <Clock className="size-3 text-gray-500" />;}};@@ -91,7 +93,7 @@ const A2AMetrics: React.FC<A2AMetricsProps> = ({ a2aMetadata, timeToFirstToken,<div className="a2a-metrics mt-3 pt-2 border-t border-gray-200 text-xs">{/* A2A Metadata Header */}<div className="flex items-center mb-2 text-gray-600">- <RobotOutlined className="mr-1.5 text-blue-500" />+ <Bot className="mr-1.5 size-4 text-blue-500" /><span className="font-medium text-gray-700">A2A Metadata</span></div>@@ -109,28 +111,33 @@ const A2AMetrics: React.FC<A2AMetricsProps> = ({ a2aMetadata, timeToFirstToken,{/* Timestamp */}{formattedTime && (- <Tooltip title={status?.timestamp}>- <span className="flex items-center">- <ClockCircleOutlined className="mr-1" />+ <Tooltip>+ <TooltipTrigger render={<span className="flex items-center" />}>+ <Clock className="mr-1 size-3" />{formattedTime}- </span>+ </TooltipTrigger>+ <TooltipContent>{status?.timestamp}</TooltipContent></Tooltip>)}{/* Latency */}{totalLatency !== undefined && (- <Tooltip title="Total latency">- <span className="flex items-center text-blue-600">- <ClockCircleOutlined className="mr-1" />+ <Tooltip>+ <TooltipTrigger render={<span className="flex items-center text-blue-600" />}>+ <Clock className="mr-1 size-3" />{(totalLatency / 1000).toFixed(2)}s- </span>+ </TooltipTrigger>+ <TooltipContent>Total latency</TooltipContent></Tooltip>)}{/* Time to first token */}{timeToFirstToken !== undefined && (- <Tooltip title="Time to first token">- <span className="flex items-center text-green-600">TTFT: {(timeToFirstToken / 1000).toFixed(2)}s</span>+ <Tooltip>+ <TooltipTrigger render={<span className="flex items-center text-green-600" />}>+ TTFT: {(timeToFirstToken / 1000).toFixed(2)}s+ </TooltipTrigger>+ <TooltipContent>Time to first token</TooltipContent></Tooltip>)}</div>@@ -139,95 +146,133 @@ const A2AMetrics: React.FC<A2AMetricsProps> = ({ a2aMetadata, timeToFirstToken,<div className="flex flex-wrap items-center gap-3 text-gray-500 ml-4 mt-1.5">{/* Task ID */}{taskId && (- <Tooltip title={`Click to copy: ${taskId}`}>- <span- className="flex items-center cursor-pointer hover:text-gray-700"- onClick={() => copyToClipboard(taskId)}+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ type="button"+ variant="ghost"+ size="xs"+ className="h-auto p-0 font-normal text-gray-500 hover:bg-transparent hover:text-gray-700"+ onClick={() => copyToClipboard(taskId)}+ aria-label={`Copy task ID ${taskId}`}+ />+ }>- <FileTextOutlined className="mr-1" />+ <FileText className="size-3" />Task: {truncateId(taskId)}- <CopyOutlined className="ml-1 text-gray-400 hover:text-gray-600" />- </span>+ <Copy className="size-3 text-gray-400" />+ </TooltipTrigger>+ <TooltipContent>Click to copy: {taskId}</TooltipContent></Tooltip>)}{/* Context/Session ID */}{contextId && (- <Tooltip title={`Click to copy: ${contextId}`}>- <span- className="flex items-center cursor-pointer hover:text-gray-700"- onClick={() => copyToClipboard(contextId)}+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ type="button"+ variant="ghost"+ size="xs"+ className="h-auto p-0 font-normal text-gray-500 hover:bg-transparent hover:text-gray-700"+ onClick={() => copyToClipboard(contextId)}+ aria-label={`Copy session ID ${contextId}`}+ />+ }>- <LinkOutlined className="mr-1" />+ <Link className="size-3" />Session: {truncateId(contextId)}- <CopyOutlined className="ml-1 text-gray-400 hover:text-gray-600" />- </span>+ <Copy className="size-3 text-gray-400" />+ </TooltipTrigger>+ <TooltipContent>Click to copy: {contextId}</TooltipContent></Tooltip>)}{/* Details toggle */}{(metadata || status?.message) && (- <Button- type="text"- size="small"- className="text-xs text-blue-500 hover:text-blue-700 p-0 h-auto"- onClick={() => setShowDetails(!showDetails)}- >- {showDetails ? <DownOutlined /> : <RightOutlined />}- <span className="ml-1">Details</span>- </Button>+ <Collapsible open={showDetails} onOpenChange={setShowDetails}>+ <CollapsibleTrigger+ render={+ <Button+ type="button"+ variant="ghost"+ size="xs"+ className="h-auto p-0 text-xs text-blue-500 hover:bg-transparent hover:text-blue-700"+ />+ }+ >+ {showDetails ? <ChevronDown className="size-3" /> : <ChevronRight className="size-3" />}+ Details+ </CollapsibleTrigger>+ </Collapsible>)}</div>{/* Expandable details panel */}- {showDetails && (- <div className="mt-2 ml-4 p-3 bg-gray-50 rounded-md text-gray-600 border border-gray-200">- {/* Status message */}- {status?.message && (- <div className="mb-2">- <span className="font-medium text-gray-700">Status Message:</span>- <span className="ml-2">{status.message}</span>- </div>- )}-- {/* Full IDs */}- {taskId && (- <div className="mb-1.5 flex items-center">- <span className="font-medium text-gray-700 w-24">Task ID:</span>- <code className="ml-2 px-2 py-1 bg-white border border-gray-200 rounded-sm text-xs font-mono">- {taskId}- </code>- <CopyOutlined- className="ml-2 cursor-pointer text-gray-400 hover:text-blue-500"- onClick={() => copyToClipboard(taskId)}- />- </div>- )}-- {contextId && (- <div className="mb-1.5 flex items-center">- <span className="font-medium text-gray-700 w-24">Session ID:</span>- <code className="ml-2 px-2 py-1 bg-white border border-gray-200 rounded-sm text-xs font-mono">- {contextId}- </code>- <CopyOutlined- className="ml-2 cursor-pointer text-gray-400 hover:text-blue-500"- onClick={() => copyToClipboard(contextId)}- />- </div>- )}-- {/* Metadata fields */}- {metadata && Object.keys(metadata).length > 0 && (- <div className="mt-3">- <span className="font-medium text-gray-700">Custom Metadata:</span>- <pre className="mt-1.5 p-2 bg-white border border-gray-200 rounded-sm text-xs font-mono overflow-x-auto whitespace-pre-wrap">- {JSON.stringify(metadata, null, 2)}- </pre>- </div>- )}- </div>- )}+ <Collapsible open={showDetails} onOpenChange={setShowDetails}>+ <CollapsibleContent>+ <div className="mt-2 ml-4 p-3 bg-gray-50 rounded-md text-gray-600 border border-gray-200">+ {/* Status message */}+ {status?.message && (+ <div className="mb-2">+ <span className="font-medium text-gray-700">Status Message:</span>+ <span className="ml-2">{status.message}</span>+ </div>+ )}++ {/* Full IDs */}+ {taskId && (+ <div className="mb-1.5 flex items-center">+ <span className="font-medium text-gray-700 w-24">Task ID:</span>+ <code className="ml-2 px-2 py-1 bg-white border border-gray-200 rounded-sm text-xs font-mono">+ {taskId}+ </code>+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ className="ml-2 text-gray-400 hover:text-blue-500"+ onClick={() => copyToClipboard(taskId)}+ aria-label={`Copy task ID ${taskId}`}+ >+ <Copy className="size-3" />+ </Button>+ </div>+ )}++ {contextId && (+ <div className="mb-1.5 flex items-center">+ <span className="font-medium text-gray-700 w-24">Session ID:</span>+ <code className="ml-2 px-2 py-1 bg-white border border-gray-200 rounded-sm text-xs font-mono">+ {contextId}+ </code>+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ className="ml-2 text-gray-400 hover:text-blue-500"+ onClick={() => copyToClipboard(contextId)}+ aria-label={`Copy session ID ${contextId}`}+ >+ <Copy className="size-3" />+ </Button>+ </div>+ )}++ {/* Metadata fields */}+ {metadata && Object.keys(metadata).length > 0 && (+ <div className="mt-3">+ <span className="font-medium text-gray-700">Custom Metadata:</span>+ <pre className="mt-1.5 p-2 bg-white border border-gray-200 rounded-sm text-xs font-mono overflow-x-auto whitespace-pre-wrap">+ {JSON.stringify(metadata, null, 2)}+ </pre>+ </div>+ )}+ </div>+ </CollapsibleContent>+ </Collapsible></div>);};diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/AdditionalModelSettings.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/AdditionalModelSettings.tsxindex d4320110c4c..4deb7051954 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/AdditionalModelSettings.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/AdditionalModelSettings.tsx@@ -1,7 +1,10 @@-import { InfoCircleOutlined } from "@ant-design/icons";-import { Text } from "@tremor/react";-import { Checkbox, InputNumber, Popover, Slider, Tooltip, Typography } from "antd";-import React, { useEffect, useState } from "react";+import { Info } from "lucide-react";+import React, { useEffect, useId, useState } from "react";+import { Checkbox } from "@/components/ui/checkbox";+import { Input } from "@/components/ui/input";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { cn } from "@/lib/cva.config";interface AdditionalModelSettingsProps {temperature?: number;@@ -17,6 +20,10 @@ interface AdditionalModelSettingsProps {showAdvancedParams?: boolean;}+function clamp(value: number, min: number, max: number): number {+ return Math.min(max, Math.max(min, value));+}+const AdditionalModelSettings: React.FC<AdditionalModelSettingsProps> = ({temperature = 1.0,maxTokens = 2048,@@ -36,7 +43,12 @@ const AdditionalModelSettings: React.FC<AdditionalModelSettingsProps> = ({const [localTemperature, setLocalTemperature] = useState(temperature);const [localMaxTokens, setLocalMaxTokens] = useState(maxTokens);- // Sync local state with props when they change+ const streamingId = useId();+ const advancedId = useId();+ const fallbacksId = useId();+ const temperatureId = useId();+ const maxTokensId = useId();+useEffect(() => {setLocalTemperature(temperature);}, [temperature]);@@ -45,21 +57,18 @@ const AdditionalModelSettings: React.FC<AdditionalModelSettingsProps> = ({setLocalMaxTokens(maxTokens);}, [maxTokens]);- const handleTemperatureChange = (value: number | null) => {- const newValue = value ?? 1.0;+ const handleTemperatureChange = (value: number) => {+ const newValue = clamp(Number.isFinite(value) ? value : 1.0, 0, 2);setLocalTemperature(newValue);onTemperatureChange?.(newValue);};- const handleMaxTokensChange = (value: number | null) => {- const newValue = value ?? 1000;+ const handleMaxTokensChange = (value: number) => {+ const newValue = clamp(Number.isFinite(value) ? Math.round(value) : 1000, 1, 32768);setLocalMaxTokens(newValue);onMaxTokensChange?.(newValue);};- const disabledOpacity = useAdvancedParams ? 1 : 0.4;- const disabledTextColor = useAdvancedParams ? "text-gray-700" : "text-gray-400";-const handleUseAdvancedParamsChange = (checked: boolean) => {if (onUseAdvancedParamsChange) {onUseAdvancedParamsChange(checked);@@ -68,129 +77,176 @@ const AdditionalModelSettings: React.FC<AdditionalModelSettingsProps> = ({}};+ const disabledTextColor = useAdvancedParams ? "text-gray-700" : "text-gray-400";+return (- <div className="space-y-4 p-4 w-80">+ <div className="w-80 space-y-4 p-4">{onStreamingChange && (- <div className="flex items-center gap-1">- <Checkbox checked={streamingEnabled} onChange={(e) => onStreamingChange(e.target.checked)}>- <span className="font-medium">Stream responses</span>- </Checkbox>- <Tooltip title="Streams the answer token by token. Uncheck to send a non-streaming request and render the full response at once.">- <InfoCircleOutlined- className="text-xs text-gray-400 cursor-pointer shrink-0 hover:text-gray-600"- aria-label="Help: Stream responses"- />+ <div className="flex items-center gap-2">+ <Checkbox+ id={streamingId}+ checked={streamingEnabled}+ onCheckedChange={(checked) => onStreamingChange(checked === true)}+ aria-label="Stream responses"+ />+ <label htmlFor={streamingId} className="cursor-pointer text-sm font-medium">+ Stream responses+ </label>+ <Tooltip>+ <TooltipTrigger aria-label="Help: Stream responses">+ <Info className="size-3 shrink-0 cursor-pointer text-gray-400 hover:text-gray-600" />+ </TooltipTrigger>+ <TooltipContent className="max-w-xs">+ Streams the answer token by token. Uncheck to send a non-streaming request and render the full response at+ once.+ </TooltipContent></Tooltip></div>)}{showAdvancedParams && (- <Checkbox checked={useAdvancedParams} onChange={(e) => handleUseAdvancedParamsChange(e.target.checked)}>- <span className="font-medium">Use Advanced Parameters</span>- </Checkbox>+ <div className="flex items-center gap-2">+ <Checkbox+ id={advancedId}+ checked={useAdvancedParams}+ onCheckedChange={(checked) => handleUseAdvancedParamsChange(checked === true)}+ aria-label="Use Advanced Parameters"+ />+ <label htmlFor={advancedId} className="cursor-pointer text-sm font-medium">+ Use Advanced Parameters+ </label>+ </div>)}{onMockTestFallbacksChange && (- <div className="flex items-center gap-1">- <Checkbox checked={mockTestFallbacks ?? false} onChange={(e) => onMockTestFallbacksChange(e.target.checked)}>- <span className="font-medium">Simulate failure to test fallbacks</span>- </Checkbox>- <Popover- trigger="hover"- placement="right"- content={- <div style={{ maxWidth: 340 }}>- <Typography.Paragraph className="text-sm" style={{ marginBottom: 8 }}>- Causes the first request to fail so the router tries fallbacks (if configured). Use this to verify- your fallback setup.- </Typography.Paragraph>- <Typography.Paragraph className="text-sm" style={{ marginBottom: 0 }}>- Behavior can differ when keys, teams, or router settings are configured.{" "}- <a- href="https://docs.litellm.ai/docs/proxy/keys_teams_router_settings"- target="_blank"- rel="noopener noreferrer"- className="text-blue-600 hover:text-blue-800"- >- Learn more- </a>- </Typography.Paragraph>- </div>- }- >- <InfoCircleOutlined- className="text-xs text-gray-400 cursor-pointer shrink-0 hover:text-gray-600"- aria-label="Help: Simulate failure to test fallbacks"- />+ <div className="flex items-center gap-2">+ <Checkbox+ id={fallbacksId}+ checked={mockTestFallbacks ?? false}+ onCheckedChange={(checked) => onMockTestFallbacksChange(checked === true)}+ aria-label="Simulate failure to test fallbacks"+ />+ <label htmlFor={fallbacksId} className="cursor-pointer text-sm font-medium">+ Simulate failure to test fallbacks+ </label>+ <Popover>+ <PopoverTrigger aria-label="Help: Simulate failure to test fallbacks">+ <Info className="size-3 shrink-0 cursor-pointer text-gray-400 hover:text-gray-600" />+ </PopoverTrigger>+ <PopoverContent side="right" className="max-w-[340px] gap-2 p-3 text-sm">+ <p>+ Causes the first request to fail so the router tries fallbacks (if configured). Use this to verify your+ fallback setup.+ </p>+ <p>+ Behavior can differ when keys, teams, or router settings are configured.{" "}+ <a+ href="https://docs.litellm.ai/docs/proxy/keys_teams_router_settings"+ target="_blank"+ rel="noopener noreferrer"+ className="text-blue-600 hover:text-blue-800"+ >+ Learn more+ </a>+ </p>+ </PopoverContent></Popover></div>)}{showAdvancedParams && (- <div className="space-y-4 transition-opacity duration-200" style={{ opacity: disabledOpacity }}>+ <div+ className={cn("space-y-4 transition-opacity duration-200", useAdvancedParams ? "opacity-100" : "opacity-40")}+ ><div>- <div className="flex items-center justify-between mb-2">+ <div className="mb-2 flex items-center justify-between"><div className="flex items-center gap-1">- <Text className={`text-sm ${disabledTextColor}`}>Temperature</Text>- <Tooltip title="Controls randomness. Lower values make output more deterministic, higher values more creative.">- <InfoCircleOutlined className={`text-xs ${disabledTextColor} cursor-help`} />+ <label htmlFor={temperatureId} className={cn("text-sm", disabledTextColor)}>+ Temperature+ </label>+ <Tooltip>+ <TooltipTrigger aria-label="Help: Temperature">+ <Info className={cn("size-3 cursor-help", disabledTextColor)} />+ </TooltipTrigger>+ <TooltipContent className="max-w-xs">+ Controls randomness. Lower values make output more deterministic, higher values more creative.+ </TooltipContent></Tooltip></div>- <InputNumber+ <Input+ id={`${temperatureId}-number`}+ type="number"min={0}max={2}step={0.1}value={localTemperature}- onChange={handleTemperatureChange}disabled={!useAdvancedParams}- precision={1}- className="w-20"+ className="h-8 w-20"+ onChange={(event) => handleTemperatureChange(Number(event.target.value))}/></div>- <Slider+ <input+ id={temperatureId}+ type="range"min={0}max={2}step={0.1}value={localTemperature}- onChange={handleTemperatureChange}disabled={!useAdvancedParams}- marks={{- 0: "0",- 1: "1.0",- 2: "2.0",- }}+ aria-label="Temperature"+ className="w-full accent-primary disabled:cursor-not-allowed"+ onChange={(event) => handleTemperatureChange(Number(event.target.value))}/>+ <div className="mt-1 flex justify-between text-xs text-gray-400">+ <span>0</span>+ <span>1.0</span>+ <span>2.0</span>+ </div></div><div>- <div className="flex items-center justify-between mb-2">+ <div className="mb-2 flex items-center justify-between"><div className="flex items-center gap-1">- <Text className={`text-sm ${disabledTextColor}`}>Max Tokens</Text>- <Tooltip title="Maximum number of tokens to generate in the response.">- <InfoCircleOutlined className={`text-xs ${disabledTextColor} cursor-help`} />+ <label htmlFor={maxTokensId} className={cn("text-sm", disabledTextColor)}>+ Max Tokens+ </label>+ <Tooltip>+ <TooltipTrigger aria-label="Help: Max Tokens">+ <Info className={cn("size-3 cursor-help", disabledTextColor)} />+ </TooltipTrigger>+ <TooltipContent className="max-w-xs">+ Maximum number of tokens to generate in the response.+ </TooltipContent></Tooltip></div>- <InputNumber+ <Input+ id={`${maxTokensId}-number`}+ type="number"min={1}max={32768}step={1}value={localMaxTokens}- onChange={handleMaxTokensChange}disabled={!useAdvancedParams}+ className="h-8 w-24"+ onChange={(event) => handleMaxTokensChange(Number(event.target.value))}/></div>- <Slider+ <input+ id={maxTokensId}+ type="range"min={1}max={32768}step={1}value={localMaxTokens}- onChange={handleMaxTokensChange}disabled={!useAdvancedParams}- marks={{- 1: "1",- 32768: "32768",- }}+ aria-label="Max Tokens"+ className="w-full accent-primary disabled:cursor-not-allowed"+ onChange={(event) => handleMaxTokensChange(Number(event.target.value))}/>+ <div className="mt-1 flex justify-between text-xs text-gray-400">+ <span>1</span>+ <span>32768</span>+ </div></div></div>)}diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/ChatImageUpload.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/ChatImageUpload.tsxindex 55527d997ac..6f210118281 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/ChatImageUpload.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/ChatImageUpload.tsx@@ -1,43 +1,70 @@-import React from "react";-import { Upload, Tooltip } from "antd";-import { PaperClipOutlined } from "@ant-design/icons";--const { Dragger } = Upload;+import React, { useId, useRef } from "react";+import { Paperclip } from "lucide-react";+import NotificationsManager from "@/components/molecules/notifications_manager";+import { Button } from "@/components/ui/button";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { CHAT_ATTACHMENT_ACCEPT, validateChatAttachment } from "./uploadValidation";interface ChatImageUploadProps {chatUploadedImage: File | null;chatImagePreviewUrl: string | null;- onImageUpload: (file: File) => false;+ onImageUpload: (file: File) => void;onRemoveImage: () => void;+ disabled?: boolean;}-const ChatImageUpload: React.FC<ChatImageUploadProps> = ({- chatUploadedImage,- chatImagePreviewUrl,- onImageUpload,- onRemoveImage,-}) => {+const ChatImageUpload: React.FC<ChatImageUploadProps> = ({ chatUploadedImage, onImageUpload, disabled = false }) => {+ const inputRef = useRef<HTMLInputElement>(null);+ const inputId = useId();++ if (chatUploadedImage) {+ return null;+ }++ const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {+ const file = event.target.files?.[0];+ event.target.value = "";+ if (!file) {+ return;+ }+ const result = validateChatAttachment(file);+ if (!result.ok) {+ NotificationsManager.error(result.error);+ return;+ }+ onImageUpload(file);+ };+return (<>- {/* Subtle upload button - only show when no image */}- {!chatUploadedImage && (- <Dragger- beforeUpload={onImageUpload}- accept="image/*,.pdf"- showUploadList={false}- className="inline-block"- style={{ padding: 0, border: "none", background: "none" }}- >- <Tooltip title="Attach image or PDF">- <button+ <input+ id={inputId}+ ref={inputRef}+ type="file"+ accept={CHAT_ATTACHMENT_ACCEPT}+ className="sr-only"+ tabIndex={-1}+ disabled={disabled}+ onChange={handleFileChange}+ />+ <Tooltip>+ <TooltipTrigger+ render={+ <Buttontype="button"- className="flex items-center justify-center w-8 h-8 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-md transition-colors"- >- <PaperClipOutlined style={{ fontSize: "16px" }} />- </button>- </Tooltip>- </Dragger>- )}+ variant="ghost"+ size="icon-sm"+ disabled={disabled}+ aria-label="Attach image or PDF"+ className="text-gray-400 hover:text-gray-600"+ onClick={() => inputRef.current?.click()}+ />+ }+ >+ <Paperclip className="size-4" />+ </TooltipTrigger>+ <TooltipContent>Attach image or PDF</TooltipContent>+ </Tooltip></>);};diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/ChatMessageBubble.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/ChatMessageBubble.tsxindex 8e71017a7b5..c438b4982bf 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/ChatMessageBubble.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/ChatMessageBubble.tsx@@ -41,9 +41,9 @@ function ChatMessageBubble({const isUser = message.role === "user";return (- <div className={`mb-4 ${isUser ? "text-right" : "text-left"}`}>+ <div className={`mb-4 min-w-0 ${isUser ? "text-right" : "text-left"}`}><div- className="inline-block max-w-[80%] rounded-lg shadow-xs p-3.5 px-4"+ className="inline-block min-w-0 max-w-[92%] overflow-hidden rounded-lg p-3 shadow-xs sm:max-w-[85%] sm:px-4"style={{backgroundColor: isUser ? "#f0f8ff" : "#ffffff",border: isUser ? "1px solid #e6f0fa" : "1px solid #f0f0f0",@@ -51,7 +51,7 @@ function ChatMessageBubble({}}>{/* Header: role icon + name + model badge */}- <div className="flex items-center gap-2 mb-1.5">+ <div className="mb-1.5 flex min-w-0 items-center gap-2"><divclassName="flex items-center justify-center w-6 h-6 rounded-full mr-1"style={{@@ -66,7 +66,7 @@ function ChatMessageBubble({</div><strong className="text-sm capitalize">{message.role}</strong>{message.role === "assistant" && message.model && (- <span className="text-xs px-2 py-0.5 rounded-sm bg-gray-100 text-gray-600 font-normal">+ <span className="max-w-48 truncate rounded-sm bg-gray-100 px-2 py-0.5 text-xs font-normal text-gray-600 sm:max-w-80">{message.model}</span>)}diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/ChatUI.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/ChatUI.tsxindex 57ff7906eda..5edcbe84aa8 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/ChatUI.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/ChatUI.tsx@@ -66,7 +66,16 @@ import { MessageType } from "@/components/chat_ui/types";import { useCodeInterpreter } from "../../hooks/useCodeInterpreter";import { useChatHistory } from "../../hooks/useChatHistory";import { getSecureItem, setSecureItem } from "@/utils/secureStorage";+import { SearchSelect } from "@/components/shared/SearchSelect";+import { Select as ShadcnSelect, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { useDebouncedCallback } from "@tanstack/react-pacer/debouncer";+import {+ AUDIO_ACCEPT,+ IMAGE_EDIT_ACCEPT,+ validateAudioFile,+ validateChatAttachment,+ validateImageEditFile,+} from "./uploadValidation";const { TextArea } = Input;const { Dragger } = Upload;@@ -177,6 +186,8 @@ const ChatUI: React.FC<ChatUIProps> = ({const [selectedModel, setSelectedModel] = useState<string | undefined>(simplified ? fixedModel : undefined);const [showCustomModelInput, setShowCustomModelInput] = useState<boolean>(false);const [modelInfo, setModelInfo] = useState<ModelGroup[]>([]);+ const [isLoadingModels, setIsLoadingModels] = useState(false);+ const [modelLoadError, setModelLoadError] = useState(false);const [agentInfo, setAgentInfo] = useState<Agent[]>([]);const [selectedAgent, setSelectedAgent] = useState<string | undefined>(undefined);const debouncedSetSelectedModel = useDebouncedCallback((value: string) => setSelectedModel(value), {@@ -388,17 +399,17 @@ const ChatUI: React.FC<ChatUIProps> = ({]);useEffect(() => {- let userApiKey = apiKeySource === "session" ? accessToken : apiKey;- if (!userApiKey || !token || !userRole || !userID) {+ const userApiKey = apiKeySource === "session" ? accessToken : apiKey.trim();+ if (!userApiKey) {+ setModelInfo([]);+ setModelLoadError(false);return;}- // Fetch model info and set the default selected model (skip in simplified mode; we use fixedModel)const loadModels = async () => {+ setIsLoadingModels(true);+ setModelLoadError(false);try {- if (!userApiKey) {- return;- }const uniqueModels = await fetchAvailableModels(userApiKey);setModelInfo(uniqueModels);@@ -412,6 +423,10 @@ const ChatUI: React.FC<ChatUIProps> = ({}} catch (error) {console.error("Error fetching model info:", error);+ setModelInfo([]);+ setModelLoadError(true);+ } finally {+ setIsLoadingModels(false);}};@@ -419,7 +434,7 @@ const ChatUI: React.FC<ChatUIProps> = ({loadModels();}loadMCPServers();- }, [accessToken, userID, userRole, apiKeySource, apiKey, token, simplified]);+ }, [accessToken, apiKeySource, apiKey, simplified]);// Load tools when MCP direct mode has a server (or toolset) selecteduseEffect(() => {@@ -494,13 +509,35 @@ const ChatUI: React.FC<ChatUIProps> = ({}};- const handleImageUpload = (file: File) => {- setUploadedImages((prev) => [...prev, file]);+ const createBlobPreviewUrl = (file: File): string => {const rawPreviewUrl = URL.createObjectURL(file);- // Sanitize: only allow blob: URLs to prevent XSS via img src injection.- const previewUrl = rawPreviewUrl.startsWith("blob:") ? rawPreviewUrl : "";- setImagePreviewUrls((prev) => [...prev, previewUrl]);- return false; // Prevent default upload behavior+ return rawPreviewUrl.startsWith("blob:") ? rawPreviewUrl : "";+ };++ const handleImageFiles = (files: File[]) => {+ let nextCount = uploadedImages.length;+ const accepted: File[] = [];+ const previews: string[] = [];+ for (const file of files) {+ const result = validateImageEditFile(file, nextCount);+ if (!result.ok) {+ NotificationsManager.error(result.error);+ continue;+ }+ accepted.push(file);+ previews.push(createBlobPreviewUrl(file));+ nextCount += 1;+ }+ if (accepted.length === 0) {+ return;+ }+ setUploadedImages((prev) => [...prev, ...accepted]);+ setImagePreviewUrls((prev) => [...prev, ...previews]);+ };++ const handleImageUpload = (file: File): false => {+ handleImageFiles([file]);+ return false;};const handleRemoveImage = (index: number) => {@@ -519,11 +556,14 @@ const ChatUI: React.FC<ChatUIProps> = ({setImagePreviewUrls([]);};- const handleResponsesImageUpload = (file: File): false => {+ const handleResponsesImageUpload = (file: File): void => {+ const result = validateChatAttachment(file);+ if (!result.ok) {+ NotificationsManager.error(result.error);+ return;+ }setResponsesUploadedImage(file);- const previewUrl = URL.createObjectURL(file);- setResponsesImagePreviewUrl(previewUrl);- return false; // Prevent default upload behavior+ setResponsesImagePreviewUrl(createBlobPreviewUrl(file));};const handleRemoveResponsesImage = () => {@@ -534,11 +574,14 @@ const ChatUI: React.FC<ChatUIProps> = ({setResponsesImagePreviewUrl(null);};- const handleChatImageUpload = (file: File): false => {+ const handleChatImageUpload = (file: File): void => {+ const result = validateChatAttachment(file);+ if (!result.ok) {+ NotificationsManager.error(result.error);+ return;+ }setChatUploadedImage(file);- const previewUrl = URL.createObjectURL(file);- setChatImagePreviewUrl(previewUrl);- return false; // Prevent default upload behavior+ setChatImagePreviewUrl(createBlobPreviewUrl(file));};const handleRemoveChatImage = () => {@@ -550,8 +593,13 @@ const ChatUI: React.FC<ChatUIProps> = ({};const handleAudioUpload = (file: File): false => {+ const result = validateAudioFile(file);+ if (!result.ok) {+ NotificationsManager.error(result.error);+ return false;+ }setUploadedAudio(file);- return false; // Prevent default upload behavior+ return false;};const handleRemoveAudio = () => {@@ -1002,8 +1050,12 @@ const ChatUI: React.FC<ChatUIProps> = ({const onModelChange = (value: string) => {setSelectedModel(value);-setShowCustomModelInput(value === "custom");++ const model = modelInfo.find((option) => option.model_group === value);+ if (model?.mode) {+ setEndpointType(getEndpointType(model.mode));+ }};// Check if the selected model is a chat model@@ -1020,35 +1072,43 @@ const ChatUI: React.FC<ChatUIProps> = ({};const supportsStreamingToggle = endpointType === EndpointType.CHAT || endpointType === EndpointType.RESPONSES;+ let modelEmptyText = "No models available for this key";+ if (modelLoadError) {+ modelEmptyText = "Unable to load models for this key";+ } else if (apiKeySource === "custom" && !apiKey.trim()) {+ modelEmptyText = "Enter a Virtual Key to load models";+ }const antIcon = <LoadingOutlined style={{ fontSize: 24 }} spin />;return (- <div className={`w-full bg-white ${simplified ? "h-full flex flex-col" : "p-4 pb-0"}`}>- <Card className={`w-full rounded-xl shadow-md overflow-hidden ${simplified ? "h-full flex flex-col" : ""}`}>- <div className={`flex w-full gap-4 ${simplified ? "h-full" : "h-[80vh]"}`}>+ <div className={`min-h-0 min-w-0 bg-white ${simplified ? "flex h-full w-full flex-col" : "h-full w-full p-3"}`}>+ <Card className="flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden rounded-xl shadow-md">+ <div className="flex h-full min-h-0 min-w-0 w-full flex-col lg:flex-row">{/* Left Sidebar with Controls - hidden in simplified mode */}{!simplified && (- <div className="w-1/4 p-4 bg-gray-50 overflow-y-auto">+ <div className="max-h-[42%] w-full shrink-0 overflow-y-auto border-b border-gray-200 bg-gray-50 p-4 lg:max-h-none lg:w-72 lg:border-r lg:border-b-0 xl:w-80"><Title className="text-xl font-semibold mb-6 mt-2">Configurations</Title><div className="space-y-4"><div><Text className="font-medium block mb-2 text-gray-700 flex items-center"><KeyOutlined className="mr-2" /> Virtual Key Source</Text>- <Select+ <ShadcnSelectdisabled={disabledPersonalKeyCreation}value={apiKeySource}- style={{ width: "100%" }}- onChange={(value) => {+ onValueChange={(value) => {setApiKeySource(value as "session" | "custom");}}- options={[- { value: "session", label: "Current UI Session" },- { value: "custom", label: "Virtual Key" },- ]}- className="rounded-md"- />+ >+ <SelectTrigger className="w-full" size="sm" aria-label="Virtual Key Source">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="session">Current UI Session</SelectItem>+ <SelectItem value="custom">Virtual Key</SelectItem>+ </SelectContent>+ </ShadcnSelect>{apiKeySource === "custom" && (<TextInputclassName="mt-2"@@ -1141,16 +1201,24 @@ const ChatUI: React.FC<ChatUIProps> = ({<SoundOutlined className="mr-2" />Voice</Text>- <Select+ <ShadcnSelectvalue={selectedVoice}- onChange={(value) => {+ onValueChange={(value) => {setSelectedVoice(value);sessionStorage.setItem("selectedVoice", value);}}- style={{ width: "100%" }}- className="rounded-md"- options={OPEN_AI_VOICE_SELECT_OPTIONS}- />+ >+ <SelectTrigger className="w-full" size="sm" aria-label="Voice">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {OPEN_AI_VOICE_SELECT_OPTIONS.map((voice) => (+ <SelectItem key={voice.value} value={voice.value}>+ {voice.label}+ </SelectItem>+ ))}+ </SelectContent>+ </ShadcnSelect></div>)}@@ -1212,46 +1280,20 @@ const ChatUI: React.FC<ChatUIProps> = ({</Tooltip>)}</Text>- <Select+ <SearchSelectvalue={selectedModel}- placeholder="Select a Model"- onChange={onModelChange}+ placeholder={isLoadingModels ? "Loading models..." : "Select a Model"}+ emptyText={modelEmptyText}+ disabled={isLoadingModels}+ onValueChange={onModelChange}options={[- { value: "custom", label: "Enter custom model", key: "custom" },- ...Array.from(- new Set(- modelInfo- .filter((option) => {- if (!option.mode) {- //If no mode, show all models- return true;- }- const optionEndpoint = getEndpointType(option.mode);- // Show chat models for responses/anthropic_messages/interactions endpoints as they are compatible- if (- endpointType === EndpointType.RESPONSES ||- endpointType === EndpointType.ANTHROPIC_MESSAGES ||- endpointType === EndpointType.INTERACTIONS- ) {- return optionEndpoint === endpointType || optionEndpoint === EndpointType.CHAT;- }- // Show image models for image_edits endpoint as they are compatible- if (endpointType === EndpointType.IMAGE_EDITS) {- return optionEndpoint === endpointType || optionEndpoint === EndpointType.IMAGE;- }- return optionEndpoint === endpointType;- })- .map((option) => option.model_group),- ),- ).map((model_group, index) => ({- value: model_group,- label: model_group,- key: index,+ { value: "custom", label: "Enter custom model" },+ ...modelInfo.map((model) => ({+ value: model.model_group,+ label: model.model_group,+ sublabel: model.mode ? `Mode: ${model.mode}` : undefined,})),]}- style={{ width: "100%" }}- showSearch={true}- className="rounded-md"/>{showCustomModelInput && (<TextInput@@ -1269,35 +1311,16 @@ const ChatUI: React.FC<ChatUIProps> = ({<Text className="font-medium block mb-2 text-gray-700 flex items-center"><RobotOutlined className="mr-2" /> Select Agent</Text>- <Select+ <SearchSelectvalue={selectedAgent}placeholder="Select an Agent"- onChange={(value) => setSelectedAgent(value)}+ onValueChange={(value) => setSelectedAgent(value)}options={agentInfo.map((agent) => ({value: agent.agent_name,label: agent.agent_name || agent.agent_id,- key: agent.agent_id,+ sublabel: agent.agent_card_params?.description,}))}- style={{ width: "100%" }}- showSearch={true}- className="rounded-md"- optionLabelProp="label"- >- {agentInfo.map((agent) => (- <Select.Option- key={agent.agent_id}- value={agent.agent_name}- label={agent.agent_name || agent.agent_id}- >- <div className="flex flex-col py-1">- <span className="font-medium">{agent.agent_name || agent.agent_id}</span>- {agent.agent_card_params?.description && (- <span className="text-xs text-gray-500 mt-1">{agent.agent_card_params.description}</span>- )}- </div>- </Select.Option>- ))}- </Select>+ />{agentInfo.length === 0 && (<Text className="text-xs text-gray-500 mt-2 block">No agents found. Create agents via /v1/agents endpoint.@@ -1697,7 +1720,7 @@ const ChatUI: React.FC<ChatUIProps> = ({)}{/* Main Chat Area */}- <div className={`flex flex-col bg-white ${simplified ? "flex-1 w-full" : "w-3/4"}`}>+ <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-white">{endpointType === EndpointType.REALTIME ? (<RealtimePlaygroundaccessToken={apiKeySource === "session" ? accessToken || "" : apiKey}@@ -1707,9 +1730,9 @@ const ChatUI: React.FC<ChatUIProps> = ({/>) : (<>- <div className="p-4 border-b border-gray-200 flex justify-between items-center">+ <div className="flex shrink-0 flex-wrap items-center justify-between gap-2 border-b border-gray-200 p-3 sm:p-4"><Title className="text-xl font-semibold mb-0">{simplified ? "Chat" : "Test Key"}</Title>- <div className="flex gap-2">+ <div className="flex flex-wrap justify-end gap-2"><TremorButtononClick={clearChatHistory}className="bg-gray-100 hover:bg-gray-200 text-gray-700 border-gray-300"@@ -1728,7 +1751,7 @@ const ChatUI: React.FC<ChatUIProps> = ({)}</div></div>- <div className="flex-1 overflow-auto p-4 pb-0">+ <div className="min-h-0 min-w-0 flex-1 overflow-auto p-3 pb-0 sm:p-4 sm:pb-0">{chatHistory.length === 0 && (<div className="h-full flex flex-col items-center justify-center text-gray-400"><RobotOutlined style={{ fontSize: "48px", marginBottom: "16px" }} />@@ -1788,18 +1811,18 @@ const ChatUI: React.FC<ChatUIProps> = ({<div ref={chatEndRef} style={{ height: "1px" }} /></div>- <div className="p-4 border-t border-gray-200 bg-white">+ <div className="max-h-[50%] shrink-0 overflow-y-auto border-t border-gray-200 bg-white p-3 sm:p-4">{/* Image Upload Section for Image Edits */}{endpointType === EndpointType.IMAGE_EDITS && (<div className="mb-4">{uploadedImages.length === 0 ? (- <Dragger beforeUpload={handleImageUpload} accept="image/*" showUploadList={false}>+ <Dragger beforeUpload={handleImageUpload} accept={IMAGE_EDIT_ACCEPT} showUploadList={false}><p className="ant-upload-drag-icon"><PictureOutlined style={{ fontSize: "24px", color: "#666" }} /></p><p className="ant-upload-text text-sm">Click or drag images to upload</p><p className="ant-upload-hint text-xs text-gray-500">- Support for PNG, JPG, JPEG formats. Multiple images supported.+ Support for PNG, JPG, JPEG, GIF, WebP. Multiple images supported.</p></Dragger>) : (@@ -1840,12 +1863,12 @@ const ChatUI: React.FC<ChatUIProps> = ({<inputid="additional-image-upload"type="file"- accept="image/*"+ accept={IMAGE_EDIT_ACCEPT}multiplestyle={{ display: "none" }}onChange={(e) => {- const files = Array.from(e.target.files || []);- files.forEach((file) => handleImageUpload(file));+ handleImageFiles(Array.from(e.target.files || []));+ e.target.value = "";}}/></div>@@ -1858,11 +1881,7 @@ const ChatUI: React.FC<ChatUIProps> = ({{endpointType === EndpointType.TRANSCRIPTION && (<div className="mb-4">{!uploadedAudio ? (- <Dragger- beforeUpload={handleAudioUpload}- accept="audio/*,.mp3,.mp4,.mpeg,.mpga,.m4a,.wav,.webm"- showUploadList={false}- >+ <Dragger beforeUpload={handleAudioUpload} accept={AUDIO_ACCEPT} showUploadList={false}><p className="ant-upload-drag-icon"><SoundOutlined style={{ fontSize: "24px", color: "#666" }} /></p>diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/CodeInterpreterOutput.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/CodeInterpreterOutput.tsxindex c27273a116d..8dc503f369c 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/CodeInterpreterOutput.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/CodeInterpreterOutput.tsx@@ -1,15 +1,10 @@-import React, { useState, useEffect } from "react";-import { Collapse, Spin } from "antd";-import {- CodeOutlined,- DownloadOutlined,- FileImageOutlined,- FileTextOutlined,- LoadingOutlined,-} from "@ant-design/icons";+import React, { useEffect, useState } from "react";+import { Code, Download, FileImage, FileText, Loader2 } from "lucide-react";import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";import { coy } from "react-syntax-highlighter/dist/esm/styles/prism";import { getProxyBaseUrl, getGlobalLitellmHeaderName } from "@/components/networking";+import { Button } from "@/components/ui/button";+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";interface ContainerFileCitation {type: "container_file_citation";@@ -27,48 +22,60 @@ interface CodeInterpreterOutputProps {accessToken: string;}-const CodeInterpreterOutput: React.FC<CodeInterpreterOutputProps> = ({- code,- containerId,- annotations = [],- accessToken,-}) => {+const IMAGE_EXTENSIONS = [".png", ".jpg", ".jpeg", ".gif"] as const;++function isImageFilename(filename: string | undefined): boolean {+ if (!filename) {+ return false;+ }+ const lower = filename.toLowerCase();+ return IMAGE_EXTENSIONS.some((ext) => lower.endsWith(ext));+}++const CodeInterpreterOutput: React.FC<CodeInterpreterOutputProps> = ({ code, annotations = [], accessToken }) => {const [imageUrls, setImageUrls] = useState<Record<string, string>>({});const [loadingImages, setLoadingImages] = useState<Record<string, boolean>>({});+ const [codeOpen, setCodeOpen] = useState(false);const proxyBaseUrl = getProxyBaseUrl();- // Fetch images from container files APIuseEffect(() => {+ const createdUrls: string[] = [];+ let cancelled = false;+const fetchImages = async () => {for (const annotation of annotations) {- const isImage =- annotation.filename?.toLowerCase().endsWith(".png") ||- annotation.filename?.toLowerCase().endsWith(".jpg") ||- annotation.filename?.toLowerCase().endsWith(".jpeg") ||- annotation.filename?.toLowerCase().endsWith(".gif");+ if (!isImageFilename(annotation.filename) || !annotation.container_id || !annotation.file_id) {+ continue;+ }- if (isImage && annotation.container_id && annotation.file_id) {+ if (!cancelled) {setLoadingImages((prev) => ({ ...prev, [annotation.file_id]: true }));+ }- try {- // Fetch image content from container files API- const response = await fetch(- `${proxyBaseUrl}/v1/containers/${annotation.container_id}/files/${annotation.file_id}/content`,- {- headers: {- [getGlobalLitellmHeaderName()]: `Bearer ${accessToken}`,- },+ try {+ const response = await fetch(+ `${proxyBaseUrl}/v1/containers/${annotation.container_id}/files/${annotation.file_id}/content`,+ {+ headers: {+ [getGlobalLitellmHeaderName()]: `Bearer ${accessToken}`,},- );+ },+ );- if (response.ok) {- const blob = await response.blob();- const url = URL.createObjectURL(blob);+ if (response.ok) {+ const blob = await response.blob();+ const url = URL.createObjectURL(blob);+ createdUrls.push(url);+ if (!cancelled) {setImageUrls((prev) => ({ ...prev, [annotation.file_id]: url }));+ } else {+ URL.revokeObjectURL(url);}- } catch (error) {- console.error("Error fetching image:", error);- } finally {+ }+ } catch (error) {+ console.error("Error fetching image:", error);+ } finally {+ if (!cancelled) {setLoadingImages((prev) => ({ ...prev, [annotation.file_id]: false }));}}@@ -76,12 +83,12 @@ const CodeInterpreterOutput: React.FC<CodeInterpreterOutputProps> = ({};if (annotations.length > 0 && accessToken) {- fetchImages();+ void fetchImages();}- // Cleanup URLs on unmountreturn () => {- Object.values(imageUrls).forEach((url) => URL.revokeObjectURL(url));+ cancelled = true;+ createdUrls.forEach((url) => URL.revokeObjectURL(url));};}, [annotations, accessToken, proxyBaseUrl]);@@ -112,22 +119,8 @@ const CodeInterpreterOutput: React.FC<CodeInterpreterOutputProps> = ({}};- // Separate images and other files- const imageAnnotations = annotations.filter(- (a) =>- a.filename?.toLowerCase().endsWith(".png") ||- a.filename?.toLowerCase().endsWith(".jpg") ||- a.filename?.toLowerCase().endsWith(".jpeg") ||- a.filename?.toLowerCase().endsWith(".gif"),- );-- const fileAnnotations = annotations.filter(- (a) =>- !a.filename?.toLowerCase().endsWith(".png") &&- !a.filename?.toLowerCase().endsWith(".jpg") &&- !a.filename?.toLowerCase().endsWith(".jpeg") &&- !a.filename?.toLowerCase().endsWith(".gif"),- );+ const imageAnnotations = annotations.filter((a) => isImageFilename(a.filename));+ const fileAnnotations = annotations.filter((a) => !isImageFilename(a.filename));if (!code && annotations.length === 0) {return null;@@ -135,44 +128,46 @@ const CodeInterpreterOutput: React.FC<CodeInterpreterOutputProps> = ({return (<div className="mt-3 space-y-3">- {/* Executed Code - Collapsible */}{code && (- <Collapse- size="small"- items={[- {- key: "code",- label: (- <span className="flex items-center gap-2 text-sm text-gray-600">- <CodeOutlined /> Python Code Executed- </span>- ),- children: (- <SyntaxHighlighter- language="python"- style={coy}- customStyle={{- margin: 0,- borderRadius: "6px",- fontSize: "12px",- maxHeight: "300px",- overflow: "auto",- }}- >- {code}- </SyntaxHighlighter>- ),- },- ]}- />+ <Collapsible open={codeOpen} onOpenChange={setCodeOpen} className="rounded-md border border-gray-200">+ <CollapsibleTrigger+ render={+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="w-full justify-start gap-2 text-sm text-gray-600"+ />+ }+ >+ <Code className="size-4" />+ Python Code Executed+ </CollapsibleTrigger>+ <CollapsibleContent>+ <div className="border-t border-gray-200 p-2">+ <SyntaxHighlighter+ language="python"+ style={coy}+ customStyle={{+ margin: 0,+ borderRadius: "6px",+ fontSize: "12px",+ maxHeight: "300px",+ overflow: "auto",+ }}+ >+ {code}+ </SyntaxHighlighter>+ </div>+ </CollapsibleContent>+ </Collapsible>)}- {/* Generated Images */}{imageAnnotations.map((annotation) => (- <div key={annotation.file_id} className="rounded-lg border border-gray-200 overflow-hidden">+ <div key={annotation.file_id} className="overflow-hidden rounded-lg border border-gray-200">{loadingImages[annotation.file_id] ? (- <div className="flex items-center justify-center p-8 bg-gray-50">- <Spin indicator={<LoadingOutlined spin />} />+ <div className="flex items-center justify-center bg-gray-50 p-8">+ <Loader2 className="size-4 animate-spin text-gray-500" aria-hidden="true" /><span className="ml-2 text-sm text-gray-500">Loading image...</span></div>) : imageUrls[annotation.file_id] ? (@@ -180,42 +175,48 @@ const CodeInterpreterOutput: React.FC<CodeInterpreterOutputProps> = ({<imgsrc={imageUrls[annotation.file_id]}alt={annotation.filename || "Generated chart"}- className="max-w-full"- style={{ maxHeight: "400px" }}+ className="max-h-[400px] max-w-full"/>- <div className="flex items-center justify-between px-3 py-2 bg-gray-50 border-t border-gray-200">- <span className="text-xs text-gray-500 flex items-center gap-1">- <FileImageOutlined /> {annotation.filename}+ <div className="flex items-center justify-between border-t border-gray-200 bg-gray-50 px-3 py-2">+ <span className="flex items-center gap-1 text-xs text-gray-500">+ <FileImage className="size-3" aria-hidden="true" />+ {annotation.filename}</span>- <button- onClick={() => handleDownload(annotation)}- className="text-xs text-blue-500 hover:text-blue-700 flex items-center gap-1"+ <Button+ type="button"+ variant="ghost"+ size="xs"+ className="h-auto gap-1 px-1 py-0 text-xs text-blue-500 hover:text-blue-700"+ onClick={() => void handleDownload(annotation)}>- <DownloadOutlined /> Download- </button>+ <Download className="size-3" />+ Download+ </Button></div></div>) : (- <div className="flex items-center justify-center p-4 bg-gray-50">+ <div className="flex items-center justify-center bg-gray-50 p-4"><span className="text-sm text-gray-400">Image not available</span></div>)}</div>))}- {/* Download Links for Other Files */}{fileAnnotations.length > 0 && (<div className="flex flex-wrap gap-2">{fileAnnotations.map((annotation) => (- <button+ <Buttonkey={annotation.file_id}- onClick={() => handleDownload(annotation)}- className="flex items-center gap-2 px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg hover:bg-gray-100 transition-colors"+ type="button"+ variant="outline"+ size="sm"+ className="h-auto gap-2 border-gray-200 bg-gray-50 px-3 py-2 hover:bg-gray-100"+ onClick={() => void handleDownload(annotation)}>- <FileTextOutlined className="text-blue-500" />+ <FileText className="size-4 text-blue-500" aria-hidden="true" /><span className="text-sm">{annotation.filename}</span>- <DownloadOutlined className="text-gray-400" />- </button>+ <Download className="size-3 text-gray-400" aria-hidden="true" />+ </Button>))}</div>)}diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/CodeInterpreterTool.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/CodeInterpreterTool.tsxindex d2682e3a7a8..e5744ac8e38 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/CodeInterpreterTool.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/CodeInterpreterTool.tsx@@ -1,8 +1,8 @@import React from "react";-import { Switch, Tooltip } from "antd";import MessageManager from "@/components/molecules/message_manager";-import { CodeOutlined, InfoCircleOutlined, ExclamationCircleOutlined } from "@ant-design/icons";-import { Text } from "@tremor/react";+import { Code, Info, TriangleAlert } from "lucide-react";+import { Switch } from "@/components/ui/switch";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";interface CodeInterpreterToolProps {accessToken: string;@@ -49,25 +49,30 @@ const CodeInterpreterTool: React.FC<CodeInterpreterToolProps> = ({<div className="border border-gray-200 rounded-lg p-3 bg-linear-to-r from-blue-50 to-purple-50"><div className="flex items-center justify-between"><div className="flex items-center gap-2">- <CodeOutlined className="text-blue-500" />- <Text className="font-medium text-gray-700">Code Interpreter</Text>- <Tooltip title="Run Python code to generate files, charts, and analyze data. Container is created automatically.">- <InfoCircleOutlined className="text-gray-400 text-xs" />+ <Code className="size-4 text-blue-500" />+ <span className="font-medium text-gray-700">Code Interpreter</span>+ <Tooltip>+ <TooltipTrigger aria-label="About Code Interpreter">+ <Info className="size-3 text-gray-400" />+ </TooltipTrigger>+ <TooltipContent>+ Run Python code to generate files, charts, and analyze data. Container is created automatically.+ </TooltipContent></Tooltip></div><Switchchecked={enabled && isOpenAI}- onChange={handleToggle}+ onCheckedChange={handleToggle}disabled={isDisabled}- size="small"- className={enabled && isOpenAI ? "bg-blue-500" : ""}+ size="sm"+ aria-label="Enable Code Interpreter"/></div>{!isOpenAI && (<div className="mt-2 pt-2 border-t border-gray-200"><div className="flex items-start gap-2">- <ExclamationCircleOutlined className="text-amber-500 mt-0.5" />+ <TriangleAlert className="mt-0.5 size-4 shrink-0 text-amber-500" /><div className="text-xs text-gray-600"><span>Code Interpreter is currently only supported for OpenAI models. </span><adiff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/EndpointSelector.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/EndpointSelector.tsxindex c6c15d3714b..644bab5b5a4 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/EndpointSelector.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/EndpointSelector.tsx@@ -1,4 +1,4 @@-import { Select } from "antd";+import { SearchSelect } from "@/components/shared/SearchSelect";import React from "react";import { ENDPOINT_OPTIONS } from "./chatConstants";@@ -11,17 +11,11 @@ interface EndpointSelectorProps {const EndpointSelector: React.FC<EndpointSelectorProps> = ({ endpointType, onEndpointChange, className }) => {return (<div className={className}>- <Select- showSearch+ <SearchSelectvalue={endpointType}- style={{ width: "100%" }}- onChange={onEndpointChange}+ onValueChange={onEndpointChange}options={ENDPOINT_OPTIONS}- className="rounded-md"- filterOption={(input, option) =>- (option?.label ?? "").toLowerCase().includes(input.toLowerCase()) ||- (option?.value ?? "").toLowerCase().includes(input.toLowerCase())- }+ placeholder="Select an endpoint"/></div>);diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/FilePreviewCard.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/FilePreviewCard.tsxindex a046657357e..f5d56b248da 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/FilePreviewCard.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/FilePreviewCard.tsx@@ -1,4 +1,5 @@-import { DeleteOutlined, FilePdfOutlined } from "@ant-design/icons";+import { FileText, X } from "lucide-react";+import { Button } from "@/components/ui/button";interface FilePreviewCardProps {file: File;@@ -15,7 +16,7 @@ function FilePreviewCard({ file, previewUrl, onRemove }: FilePreviewCardProps) {<div className="relative inline-block">{isPdf ? (<div className="w-10 h-10 rounded-md bg-red-500 flex items-center justify-center">- <FilePdfOutlined style={{ fontSize: "16px", color: "white" }} />+ <FileText className="size-4 text-white" aria-hidden="true" /></div>) : (<img@@ -29,12 +30,16 @@ function FilePreviewCard({ file, previewUrl, onRemove }: FilePreviewCardProps) {<div className="text-sm font-medium text-gray-900 truncate">{file.name}</div><div className="text-xs text-gray-500">{isPdf ? "PDF" : "Image"}</div></div>- <button- className="flex items-center justify-center w-6 h-6 text-gray-400 hover:text-gray-600 hover:bg-gray-200 rounded-full transition-colors"+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ aria-label={`Remove ${file.name}`}+ className="text-gray-400 hover:text-gray-600 hover:bg-gray-200"onClick={onRemove}>- <DeleteOutlined style={{ fontSize: "12px" }} />- </button>+ <X className="size-3" />+ </Button></div></div>);diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/ResponsesImageUpload.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/ResponsesImageUpload.tsxindex d5abf13a7d3..97346c34a12 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/ResponsesImageUpload.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/ResponsesImageUpload.tsx@@ -1,43 +1,74 @@-import React from "react";-import { Upload, Tooltip } from "antd";-import { PaperClipOutlined } from "@ant-design/icons";--const { Dragger } = Upload;+import React, { useId, useRef } from "react";+import { Paperclip } from "lucide-react";+import NotificationsManager from "@/components/molecules/notifications_manager";+import { Button } from "@/components/ui/button";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { CHAT_ATTACHMENT_ACCEPT, validateChatAttachment } from "./uploadValidation";interface ResponsesImageUploadProps {responsesUploadedImage: File | null;responsesImagePreviewUrl: string | null;- onImageUpload: (file: File) => false;+ onImageUpload: (file: File) => void;onRemoveImage: () => void;+ disabled?: boolean;}const ResponsesImageUpload: React.FC<ResponsesImageUploadProps> = ({responsesUploadedImage,- responsesImagePreviewUrl,onImageUpload,- onRemoveImage,+ disabled = false,}) => {+ const inputRef = useRef<HTMLInputElement>(null);+ const inputId = useId();++ if (responsesUploadedImage) {+ return null;+ }++ const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {+ const file = event.target.files?.[0];+ event.target.value = "";+ if (!file) {+ return;+ }+ const result = validateChatAttachment(file);+ if (!result.ok) {+ NotificationsManager.error(result.error);+ return;+ }+ onImageUpload(file);+ };+return (<>- {/* Subtle upload button - only show when no image */}- {!responsesUploadedImage && (- <Dragger- beforeUpload={onImageUpload}- accept="image/*,.pdf"- showUploadList={false}- className="inline-block"- style={{ padding: 0, border: "none", background: "none" }}- >- <Tooltip title="Attach image or PDF">- <button+ <input+ id={inputId}+ ref={inputRef}+ type="file"+ accept={CHAT_ATTACHMENT_ACCEPT}+ className="sr-only"+ tabIndex={-1}+ disabled={disabled}+ onChange={handleFileChange}+ />+ <Tooltip>+ <TooltipTrigger+ render={+ <Buttontype="button"- className="flex items-center justify-center w-8 h-8 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-md transition-colors"- >- <PaperClipOutlined style={{ fontSize: "16px" }} />- </button>- </Tooltip>- </Dragger>- )}+ variant="ghost"+ size="icon-sm"+ disabled={disabled}+ aria-label="Attach image or PDF"+ className="text-gray-400 hover:text-gray-600"+ onClick={() => inputRef.current?.click()}+ />+ }+ >+ <Paperclip className="size-4" />+ </TooltipTrigger>+ <TooltipContent>Attach image or PDF</TooltipContent>+ </Tooltip></>);};diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/SearchResultsDisplay.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/SearchResultsDisplay.tsxindex 9b32d196ea6..5a529c48aeb 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/SearchResultsDisplay.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/SearchResultsDisplay.tsx@@ -1,7 +1,8 @@import React, { useState } from "react";-import { Button } from "antd";import { VectorStoreSearchResponse } from "@/components/chat_ui/types";-import { DatabaseOutlined, FileTextOutlined, DownOutlined, RightOutlined } from "@ant-design/icons";+import { ChevronDown, ChevronRight, Database, FileText } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";interface SearchResultsDisplayProps {searchResults: VectorStoreSearchResponse[];@@ -27,95 +28,94 @@ export function SearchResultsDisplay({ searchResults }: SearchResultsDisplayPropreturn (<div className="search-results-content mt-1 mb-2">- <Button- type="text"- className="flex items-center text-xs text-gray-500 hover:text-gray-700"- onClick={() => setIsExpanded(!isExpanded)}- icon={<DatabaseOutlined />}- >- {isExpanded ? "Hide sources" : `Show sources (${totalResults})`}- {isExpanded ? <DownOutlined className="ml-1" /> : <RightOutlined className="ml-1" />}- </Button>+ <Collapsible open={isExpanded} onOpenChange={setIsExpanded}>+ <CollapsibleTrigger+ render={+ <Button type="button" variant="ghost" size="sm" className="text-xs text-gray-500 hover:text-gray-700" />+ }+ >+ <Database className="size-4" />+ {isExpanded ? "Hide sources" : `Show sources (${totalResults})`}+ {isExpanded ? <ChevronDown className="size-3" /> : <ChevronRight className="size-3" />}+ </CollapsibleTrigger>- {isExpanded && (- <div className="mt-2 p-3 bg-gray-50 border border-gray-200 rounded-md text-sm">- <div className="space-y-3">- {searchResults.map((resultPage, pageIndex) => (- <div key={pageIndex}>- <div className="text-xs text-gray-600 mb-2 flex items-center gap-2">- <span className="font-medium">Query:</span>- <span className="italic">"{resultPage.search_query}"</span>- <span className="text-gray-400">•</span>- <span className="text-gray-500">- {resultPage.data.length} result{resultPage.data.length !== 1 ? "s" : ""}- </span>- </div>+ <CollapsibleContent>+ <div className="mt-2 p-3 bg-gray-50 border border-gray-200 rounded-md text-sm">+ <div className="space-y-3">+ {searchResults.map((resultPage, pageIndex) => (+ <div key={pageIndex}>+ <div className="text-xs text-gray-600 mb-2 flex items-center gap-2">+ <span className="font-medium">Query:</span>+ <span className="italic">"{resultPage.search_query}"</span>+ <span className="text-gray-400">•</span>+ <span className="text-gray-500">+ {resultPage.data.length} result{resultPage.data.length !== 1 ? "s" : ""}+ </span>+ </div>- <div className="space-y-2">- {resultPage.data.map((result, resultIndex) => {- const isResultExpanded = expandedResults[`${pageIndex}-${resultIndex}`] || false;+ <div className="space-y-2">+ {resultPage.data.map((result, resultIndex) => {+ const isResultExpanded = expandedResults[`${pageIndex}-${resultIndex}`] || false;- return (- <div key={resultIndex} className="border border-gray-200 rounded-md overflow-hidden bg-white">- <div- className="flex items-center justify-between p-2 cursor-pointer hover:bg-gray-50 transition-colors"- onClick={() => toggleResult(pageIndex, resultIndex)}+ return (+ <Collapsible+ key={resultIndex}+ open={isResultExpanded}+ onOpenChange={() => toggleResult(pageIndex, resultIndex)}+ className="overflow-hidden rounded-md border border-gray-200 bg-white">- <div className="flex items-center gap-2 flex-1 min-w-0">- <svg- className={`w-4 h-4 text-gray-400 transition-transform shrink-0 ${isResultExpanded ? "transform rotate-90" : ""}`}- fill="none"- stroke="currentColor"- viewBox="0 0 24 24"- >- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />- </svg>- <FileTextOutlined className="text-gray-400 shrink-0" style={{ fontSize: "12px" }} />- <span className="text-xs font-medium text-gray-700 truncate">- {result.filename || result.file_id || `Result ${resultIndex + 1}`}- </span>- <span className="text-xs px-2 py-0.5 rounded-sm bg-blue-100 text-blue-700 font-mono shrink-0">- {result.score.toFixed(3)}- </span>- </div>- </div>+ <CollapsibleTrigger className="flex w-full items-center justify-between p-2 text-left transition-colors hover:bg-gray-50">+ <div className="flex items-center gap-2 flex-1 min-w-0">+ <ChevronRight+ className={`size-4 shrink-0 text-gray-400 transition-transform ${isResultExpanded ? "rotate-90" : ""}`}+ />+ <FileText className="size-3 shrink-0 text-gray-400" />+ <span className="text-xs font-medium text-gray-700 truncate">+ {result.filename || result.file_id || `Result ${resultIndex + 1}`}+ </span>+ <span className="text-xs px-2 py-0.5 rounded-sm bg-blue-100 text-blue-700 font-mono shrink-0">+ {result.score.toFixed(3)}+ </span>+ </div>+ </CollapsibleTrigger>- {isResultExpanded && (- <div className="border-t border-gray-200 bg-white">- <div className="p-3 space-y-2">- {result.content.map((content, contentIndex) => (- <div key={contentIndex}>- <div className="text-xs font-mono bg-gray-50 p-2 rounded-sm text-gray-800 whitespace-pre-wrap wrap-break-word">- {content.text}+ <CollapsibleContent>+ <div className="border-t border-gray-200 bg-white">+ <div className="p-3 space-y-2">+ {result.content.map((content, contentIndex) => (+ <div key={contentIndex}>+ <div className="text-xs font-mono bg-gray-50 p-2 rounded-sm text-gray-800 whitespace-pre-wrap wrap-break-word">+ {content.text}+ </div></div>- </div>- ))}+ ))}- {result.attributes && Object.keys(result.attributes).length > 0 && (- <div className="mt-2 pt-2 border-t border-gray-100">- <div className="text-xs text-gray-500 mb-1 font-medium">Metadata:</div>- <div className="space-y-1">- {Object.entries(result.attributes).map(([key, value]) => (- <div key={key} className="text-xs flex gap-2">- <span className="text-gray-500 font-medium">{key}:</span>- <span className="text-gray-700 font-mono break-all">{String(value)}</span>- </div>- ))}+ {result.attributes && Object.keys(result.attributes).length > 0 && (+ <div className="mt-2 pt-2 border-t border-gray-100">+ <div className="text-xs text-gray-500 mb-1 font-medium">Metadata:</div>+ <div className="space-y-1">+ {Object.entries(result.attributes).map(([key, value]) => (+ <div key={key} className="text-xs flex gap-2">+ <span className="text-gray-500 font-medium">{key}:</span>+ <span className="text-gray-700 font-mono break-all">{String(value)}</span>+ </div>+ ))}+ </div></div>- </div>- )}+ )}+ </div></div>- </div>- )}- </div>- );- })}+ </CollapsibleContent>+ </Collapsible>+ );+ })}+ </div></div>- </div>- ))}+ ))}+ </div></div>- </div>- )}+ </CollapsibleContent>+ </Collapsible></div>);}diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/SessionManagement.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/SessionManagement.tsxindex 34f7d7b8407..193ccce9174 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/SessionManagement.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/SessionManagement.tsx@@ -1,8 +1,10 @@import React from "react";-import { Switch, Tooltip } from "antd";-import { InfoCircleOutlined, CopyOutlined } from "@ant-design/icons";+import { Copy, Info } from "lucide-react";import { EndpointType } from "@/components/chat_ui/mode_endpoint_mapping";import NotificationsManager from "@/components/molecules/notifications_manager";+import { Button } from "@/components/ui/button";+import { Switch } from "@/components/ui/switch";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";interface SessionManagementProps {endpointType: string;@@ -21,10 +23,14 @@ const SessionManagement: React.FC<SessionManagementProps> = ({return null;}- const handleCopySessionId = () => {+ const handleCopySessionId = async () => {if (responsesSessionId) {- navigator.clipboard.writeText(responsesSessionId);- NotificationsManager.success("Response ID copied to clipboard!");+ try {+ await navigator.clipboard.writeText(responsesSessionId);+ NotificationsManager.success("Response ID copied to clipboard!");+ } catch {+ NotificationsManager.error("Unable to copy response ID");+ }}};@@ -56,17 +62,26 @@ const SessionManagement: React.FC<SessionManagementProps> = ({<div className="flex items-center justify-between mb-2"><div className="flex items-center gap-2"><span className="text-sm font-medium text-gray-700">Session Management</span>- <Tooltip title="Choose between LiteLLM API session management (using previous_response_id) or UI-based session management (using chat history)">- <InfoCircleOutlined className="text-gray-400" style={{ fontSize: "12px" }} />+ <Tooltip>+ <TooltipTrigger aria-label="About session management">+ <Info className="size-3 text-gray-400" />+ </TooltipTrigger>+ <TooltipContent>+ Choose between LiteLLM API session management (using previous_response_id) or UI-based session management+ (using chat history)+ </TooltipContent></Tooltip></div>- <Switch- checked={useApiSessionManagement}- onChange={onToggleSessionManagement}- checkedChildren="API"- unCheckedChildren="UI"- size="small"- />+ <div className="flex items-center gap-2 text-xs text-gray-600">+ <span aria-hidden="true">UI</span>+ <Switch+ checked={useApiSessionManagement}+ onCheckedChange={onToggleSessionManagement}+ aria-label="Use API session management"+ size="sm"+ />+ <span aria-hidden="true">API</span>+ </div></div>{/* Session Status Indicator */}@@ -79,12 +94,26 @@ const SessionManagement: React.FC<SessionManagementProps> = ({><div className="flex items-center justify-between"><div className="flex items-center gap-1">- <InfoCircleOutlined style={{ fontSize: "12px" }} />+ <Info className="size-3" />{getSessionDisplay()}</div>{responsesSessionId && (- <Tooltip- title={+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ onClick={handleCopySessionId}+ aria-label="Copy response ID"+ className="ml-2 hover:bg-green-100"+ />+ }+ >+ <Copy className="size-3" />+ </TooltipTrigger>+ <TooltipContent className="max-w-lg"><div className="text-xs"><div className="mb-1">Copy response ID to continue session:</div><div className="bg-gray-800 text-gray-100 p-2 rounded-sm font-mono text-xs whitespace-pre-wrap">@@ -99,15 +128,7 @@ const SessionManagement: React.FC<SessionManagementProps> = ({}'`}</div></div>- }- overlayStyle={{ maxWidth: "500px" }}- >- <button- onClick={handleCopySessionId}- className="ml-2 p-1 hover:bg-green-100 rounded-sm transition-colors"- >- <CopyOutlined style={{ fontSize: "12px" }} />- </button>+ </TooltipContent></Tooltip>)}</div>diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/uploadValidation.test.ts b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/uploadValidation.test.tsnew file mode 100644index 00000000000..7718cceb7f1--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/uploadValidation.test.ts@@ -0,0 +1,78 @@+import { describe, expect, it } from "vitest";+import {+ MAX_AUDIO_BYTES,+ MAX_CHAT_ATTACHMENT_BYTES,+ MAX_IMAGE_EDIT_COUNT,+ validateAudioFile,+ validateChatAttachment,+ validateImageEditFile,+} from "./uploadValidation";++function makeFile(name: string, type: string, sizeBytes = 1024): File {+ const content = new Uint8Array(sizeBytes);+ return new File([content], name, { type });+}++describe("validateChatAttachment", () => {+ it("accepts supported image types", () => {+ expect(validateChatAttachment(makeFile("a.png", "image/png"))).toEqual({ ok: true });+ expect(validateChatAttachment(makeFile("a.jpg", "image/jpeg"))).toEqual({ ok: true });+ expect(validateChatAttachment(makeFile("a.webp", "image/webp"))).toEqual({ ok: true });+ });++ it("accepts PDF by mime type or extension", () => {+ expect(validateChatAttachment(makeFile("doc.pdf", "application/pdf"))).toEqual({ ok: true });+ expect(validateChatAttachment(makeFile("doc.PDF", ""))).toEqual({ ok: true });+ });++ it("rejects unsupported types", () => {+ const result = validateChatAttachment(makeFile("notes.txt", "text/plain"));+ expect(result.ok).toBe(false);+ if (!result.ok) {+ expect(result.error).toContain("not a supported attachment");+ }+ });++ it("rejects files over the size limit", () => {+ const result = validateChatAttachment(makeFile("huge.png", "image/png", MAX_CHAT_ATTACHMENT_BYTES + 1));+ expect(result.ok).toBe(false);+ if (!result.ok) {+ expect(result.error).toContain("too large");+ }+ });+});++describe("validateImageEditFile", () => {+ it("accepts images under the count limit", () => {+ expect(validateImageEditFile(makeFile("a.png", "image/png"), 0)).toEqual({ ok: true });+ });++ it("rejects when the count limit is reached", () => {+ const result = validateImageEditFile(makeFile("a.png", "image/png"), MAX_IMAGE_EDIT_COUNT);+ expect(result.ok).toBe(false);+ if (!result.ok) {+ expect(result.error).toContain(`at most ${MAX_IMAGE_EDIT_COUNT}`);+ }+ });++ it("rejects PDFs for image edits", () => {+ const result = validateImageEditFile(makeFile("doc.pdf", "application/pdf"), 0);+ expect(result.ok).toBe(false);+ if (!result.ok) {+ expect(result.error).toContain("not a supported image");+ }+ });+});++describe("validateAudioFile", () => {+ it("accepts common audio types", () => {+ expect(validateAudioFile(makeFile("a.mp3", "audio/mpeg"))).toEqual({ ok: true });+ expect(validateAudioFile(makeFile("a.wav", "audio/wav"))).toEqual({ ok: true });+ expect(validateAudioFile(makeFile("a.webm", ""))).toEqual({ ok: true });+ });++ it("rejects non-audio files and oversized files", () => {+ expect(validateAudioFile(makeFile("a.png", "image/png")).ok).toBe(false);+ expect(validateAudioFile(makeFile("a.mp3", "audio/mpeg", MAX_AUDIO_BYTES + 1)).ok).toBe(false);+ });+});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/uploadValidation.ts b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/uploadValidation.tsnew file mode 100644index 00000000000..a7bcafe2233--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/chat_ui/uploadValidation.ts@@ -0,0 +1,97 @@+export type UploadValidationResult = { ok: true } | { ok: false; error: string };++export const CHAT_ATTACHMENT_ACCEPT = "image/png,image/jpeg,image/jpg,image/gif,image/webp,application/pdf,.pdf";+export const IMAGE_EDIT_ACCEPT = "image/png,image/jpeg,image/jpg,image/gif,image/webp";+export const AUDIO_ACCEPT = "audio/*,.mp3,.mp4,.mpeg,.mpga,.m4a,.wav,.webm";++export const MAX_CHAT_ATTACHMENT_BYTES = 20 * 1024 * 1024;+export const MAX_IMAGE_EDIT_BYTES = 20 * 1024 * 1024;+export const MAX_AUDIO_BYTES = 25 * 1024 * 1024;+export const MAX_IMAGE_EDIT_COUNT = 10;+export const MAX_CHAT_ATTACHMENT_COUNT = 1;++const IMAGE_MIME_TYPES = new Set(["image/png", "image/jpeg", "image/jpg", "image/gif", "image/webp"]);+const IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp"]);+const PDF_MIME_TYPES = new Set(["application/pdf"]);+const PDF_EXTENSIONS = new Set([".pdf"]);+const AUDIO_MIME_PREFIX = "audio/";+const AUDIO_EXTENSIONS = new Set([".mp3", ".mp4", ".mpeg", ".mpga", ".m4a", ".wav", ".webm"]);++function getExtension(fileName: string): string {+ const dot = fileName.lastIndexOf(".");+ if (dot < 0) {+ return "";+ }+ return fileName.slice(dot).toLowerCase();+}++function formatMb(bytes: number): string {+ return `${Math.round(bytes / (1024 * 1024))} MB`;+}++function isImageFile(file: File): boolean {+ if (IMAGE_MIME_TYPES.has(file.type)) {+ return true;+ }+ return IMAGE_EXTENSIONS.has(getExtension(file.name));+}++function isPdfFile(file: File): boolean {+ if (PDF_MIME_TYPES.has(file.type)) {+ return true;+ }+ return PDF_EXTENSIONS.has(getExtension(file.name));+}++function isAudioFile(file: File): boolean {+ if (file.type.startsWith(AUDIO_MIME_PREFIX)) {+ return true;+ }+ return AUDIO_EXTENSIONS.has(getExtension(file.name));+}++function validateSize(file: File, maxBytes: number): UploadValidationResult {+ if (file.size <= maxBytes) {+ return { ok: true };+ }+ return {+ ok: false,+ error: `"${file.name}" is too large. Maximum size is ${formatMb(maxBytes)}.`,+ };+}++export function validateChatAttachment(file: File): UploadValidationResult {+ if (!isImageFile(file) && !isPdfFile(file)) {+ return {+ ok: false,+ error: `"${file.name}" is not a supported attachment. Use PNG, JPEG, GIF, WebP, or PDF.`,+ };+ }+ return validateSize(file, MAX_CHAT_ATTACHMENT_BYTES);+}++export function validateImageEditFile(file: File, currentCount: number): UploadValidationResult {+ if (currentCount >= MAX_IMAGE_EDIT_COUNT) {+ return {+ ok: false,+ error: `You can upload at most ${MAX_IMAGE_EDIT_COUNT} images.`,+ };+ }+ if (!isImageFile(file)) {+ return {+ ok: false,+ error: `"${file.name}" is not a supported image. Use PNG, JPEG, GIF, or WebP.`,+ };+ }+ return validateSize(file, MAX_IMAGE_EDIT_BYTES);+}++export function validateAudioFile(file: File): UploadValidationResult {+ if (!isAudioFile(file)) {+ return {+ ok: false,+ error: `"${file.name}" is not a supported audio file. Use MP3, MP4, MPEG, MPGA, M4A, WAV, or WEBM.`,+ };+ }+ return validateSize(file, MAX_AUDIO_BYTES);+}diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/page.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/page.tsxindex a4ea85311c4..286a4efdcd8 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/page.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/page.tsx@@ -47,16 +47,16 @@ export default function PlaygroundPage() {}return (- <div className="h-full w-full flex flex-col">- <TabGroup className="w-full" style={{ flex: 1, minHeight: 0, display: "flex", flexDirection: "column" }}>- <TabList className="mb-0">+ <div className="flex h-full min-h-0 w-full min-w-0 flex-col overflow-hidden">+ <TabGroup className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">+ <TabList className="mb-0 shrink-0 overflow-x-auto"><Tab>Chat</Tab><Tab>Compare</Tab><Tab>Compliance</Tab><Tab>Agent Builder (Experimental)</Tab></TabList>- <TabPanels className="h-full">- <TabPanel className="h-full">+ <TabPanels className="min-h-0 min-w-0 flex-1 overflow-hidden">+ <TabPanel className="h-full min-h-0 min-w-0 overflow-hidden"><ChatUIaccessToken={accessToken}token={token}diff --git a/ui/litellm-dashboard/src/components/chat_ui/MCPEventsDisplay.tsx b/ui/litellm-dashboard/src/components/chat_ui/MCPEventsDisplay.tsxindex b7ee480458a..fb1a37fb53e 100644--- a/ui/litellm-dashboard/src/components/chat_ui/MCPEventsDisplay.tsx+++ b/ui/litellm-dashboard/src/components/chat_ui/MCPEventsDisplay.tsx@@ -1,224 +1,175 @@-import React from "react";-import { Collapse } from "antd";+import React, { useState } from "react";+import { ChevronRight } from "lucide-react";import type { MCPEvent } from "@/components/mcp_tools/types";--const { Panel } = Collapse;+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";+import { cn } from "@/lib/cva.config";interface MCPEventsDisplayProps {events: MCPEvent[];className?: string;}+function formatArguments(raw: string | undefined): string {+ if (!raw) {+ return "";+ }+ try {+ return JSON.stringify(JSON.parse(raw), null, 2);+ } catch {+ return raw;+ }+}+const MCPEventsDisplay: React.FC<MCPEventsDisplayProps> = ({ events, className }) => {if (!events || events.length === 0) {return null;}- // Find the list tools event- const toolsEvent = events.find(- (event) =>- event.type === "response.output_item.done" &&- event.item?.type === "mcp_list_tools" &&- event.item.tools &&- event.item.tools.length > 0,- );+ const isListToolsEvent = (event: MCPEvent): boolean => {+ if (event.type !== "response.output_item.done") {+ return false;+ }+ if (event.item?.type !== "mcp_list_tools") {+ return false;+ }+ return Boolean(event.item.tools && event.item.tools.length > 0);+ };- // Find MCP call events- const mcpCallEvents = events.filter(- (event) => event.type === "response.output_item.done" && event.item?.type === "mcp_call",- );+ const isMcpCallEvent = (event: MCPEvent): boolean =>+ event.type === "response.output_item.done" && event.item?.type === "mcp_call";++ const toolsEvent = events.find(isListToolsEvent);+ const mcpCallEvents = events.filter(isMcpCallEvent);if (!toolsEvent && mcpCallEvents.length === 0) {return null;}+ const defaultOpenKeys = new Set<string>(+ toolsEvent ? ["list-tools"] : mcpCallEvents.map((_, index) => `mcp-call-${index}`),+ );+return (- <div className={`mcp-events-display ${className || ""}`}>- <style jsx>{`- .openai-mcp-tools {- position: relative;- margin: 0;- padding: 0;- }- .openai-mcp-tools .ant-collapse {- background: transparent !important;- border: none !important;- }- .openai-mcp-tools .ant-collapse-item {- border: none !important;- background: transparent !important;- }- .openai-mcp-tools .ant-collapse-header {- padding: 0 0 0 20px !important;- background: transparent !important;- border: none !important;- font-size: 14px !important;- color: #9ca3af !important;- font-weight: 400 !important;- line-height: 20px !important;- min-height: 20px !important;- }- .openai-mcp-tools .ant-collapse-header:hover {- background: transparent !important;- color: #6b7280 !important;- }- .openai-mcp-tools .ant-collapse-content {- border: none !important;- background: transparent !important;- }- .openai-mcp-tools .ant-collapse-content-box {- padding: 4px 0 0 20px !important;- }- .openai-mcp-tools .ant-collapse-expand-icon {- position: absolute !important;- left: 2px !important;- top: 2px !important;- color: #9ca3af !important;- font-size: 10px !important;- width: 16px !important;- height: 16px !important;- display: flex !important;- align-items: center !important;- justify-content: center !important;- }- .openai-mcp-tools .ant-collapse-expand-icon:hover {- color: #6b7280 !important;- }- .openai-vertical-line {- position: absolute;- left: 9px;- top: 18px;- bottom: 0;- width: 0.5px;- background-color: #f3f4f6;- opacity: 0.8;- }- .tool-item {- font-family: ui-monospace, SFMono-Regular, "SF Mono", Monaco, Consolas, "Liberation Mono", "Courier New",- monospace;- font-size: 13px;- color: #4b5563;- line-height: 18px;- padding: 0;- margin: 0;- background: white;- position: relative;- z-index: 1;- }- .mcp-section {- margin-bottom: 12px;- background: white;- position: relative;- z-index: 1;- }- .mcp-section:last-child {- margin-bottom: 0;- }- .mcp-section-header {- font-size: 13px;- color: #6b7280;- font-weight: 500;- margin-bottom: 4px;- }- .mcp-code-block {- background: #f9fafb;- border: 1px solid #f3f4f6;- border-radius: 6px;- padding: 8px;- font-size: 12px;- }- .mcp-json {- font-family: ui-monospace, SFMono-Regular, "SF Mono", Monaco, Consolas, "Liberation Mono", "Courier New",- monospace;- color: #374151;- margin: 0;- white-space: pre-wrap;- word-wrap: break-word;- }- .mcp-approved {- display: flex;- align-items: center;- font-size: 13px;- color: #6b7280;- }- .mcp-checkmark {- color: #10b981;- margin-right: 6px;- font-weight: bold;- }- .mcp-response-content {- font-size: 13px;- color: #374151;- line-height: 1.5;- white-space: pre-wrap;- font-family: ui-monospace, SFMono-Regular, "SF Mono", Monaco, Consolas, "Liberation Mono", "Courier New",- monospace;- }- `}</style>- <div className="openai-mcp-tools">- <div className="openai-vertical-line"></div>- <Collapse- ghost- size="small"- expandIconPosition="start"- defaultActiveKey={toolsEvent ? ["list-tools"] : mcpCallEvents.map((_, index) => `mcp-call-${index}`)}- >- {/* List Tools Panel */}- {toolsEvent && (- <Panel header="List tools" key="list-tools">- <div>- {toolsEvent.item?.tools?.map((tool, index) => (- <div key={index} className="tool-item">- {tool.name}- </div>- ))}- </div>- </Panel>- )}+ <div className={cn("mcp-events-display", className)}>+ <MCPEventsPanels toolsEvent={toolsEvent} mcpCallEvents={mcpCallEvents} defaultOpenKeys={defaultOpenKeys} />+ </div>+ );+};- {/* MCP Call Panels */}- {mcpCallEvents.map((callEvent, index) => (- <Panel header={callEvent.item?.name || "Tool call"} key={`mcp-call-${index}`}>+interface MCPEventsPanelsProps {+ toolsEvent: MCPEvent | undefined;+ mcpCallEvents: MCPEvent[];+ defaultOpenKeys: Set<string>;+}++function MCPEventsPanels({ toolsEvent, mcpCallEvents, defaultOpenKeys }: MCPEventsPanelsProps) {+ const [openKeys, setOpenKeys] = useState<Set<string>>(defaultOpenKeys);++ const toggleKey = (key: string, open: boolean) => {+ setOpenKeys((prev) => {+ const next = new Set(prev);+ if (open) {+ next.add(key);+ } else {+ next.delete(key);+ }+ return next;+ });+ };++ return (+ <div className="relative m-0 p-0">+ <div className="absolute bottom-0 left-[9px] top-[18px] w-px bg-gray-100 opacity-80" aria-hidden="true" />++ <div className="space-y-1">+ {toolsEvent && (+ <MCPEventPanel+ panelKey="list-tools"+ title="List tools"+ open={openKeys.has("list-tools")}+ onOpenChange={(open) => toggleKey("list-tools", open)}+ >+ <div>+ {toolsEvent.item?.tools?.map((tool, index) => (+ <div key={index} className="relative z-[1] bg-white font-mono text-[13px] leading-[18px] text-gray-600">+ {tool.name}+ </div>+ ))}+ </div>+ </MCPEventPanel>+ )}++ {mcpCallEvents.map((callEvent, index) => {+ const key = `mcp-call-${index}`;+ return (+ <MCPEventPanel+ key={key}+ panelKey={key}+ title={callEvent.item?.name || "Tool call"}+ open={openKeys.has(key)}+ onOpenChange={(open) => toggleKey(key, open)}+ ><div>- {/* Request section */}- <div className="mcp-section">- <div className="mcp-section-header">Request</div>- <div className="mcp-code-block">+ <div className="relative z-[1] mb-3 bg-white last:mb-0">+ <div className="mb-1 text-[13px] font-medium text-gray-500">Request</div>+ <div className="rounded-md border border-gray-100 bg-gray-50 p-2 text-xs">{callEvent.item?.arguments && (- <pre className="mcp-json">- {(() => {- try {- return JSON.stringify(JSON.parse(callEvent.item.arguments), null, 2);- } catch (e) {- return callEvent.item.arguments;- }- })()}+ <pre className="m-0 whitespace-pre-wrap break-words font-mono text-gray-700">+ {formatArguments(callEvent.item.arguments)}</pre>)}</div></div>- {/* Approved section */}- <div className="mcp-section">- <div className="mcp-approved">- <span className="mcp-checkmark">✓</span> Approved+ <div className="relative z-[1] mb-3 bg-white last:mb-0">+ <div className="flex items-center text-[13px] text-gray-500">+ <span className="mr-1.5 font-bold text-emerald-500" aria-hidden="true">+ ✓+ </span>+ Approved</div></div>- {/* Response section */}{callEvent.item?.output && (- <div className="mcp-section">- <div className="mcp-section-header">Response</div>- <div className="mcp-response-content">{callEvent.item.output}</div>+ <div className="relative z-[1] mb-3 bg-white last:mb-0">+ <div className="mb-1 text-[13px] font-medium text-gray-500">Response</div>+ <div className="whitespace-pre-wrap font-mono text-[13px] leading-normal text-gray-700">+ {callEvent.item.output}+ </div></div>)}</div>- </Panel>- ))}- </Collapse>+ </MCPEventPanel>+ );+ })}</div></div>);-};+}++interface MCPEventPanelProps {+ panelKey: string;+ title: string;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ children: React.ReactNode;+}++function MCPEventPanel({ title, open, onOpenChange, children }: MCPEventPanelProps) {+ return (+ <Collapsible open={open} onOpenChange={onOpenChange}>+ <CollapsibleTrigger className="relative flex min-h-5 w-full items-center gap-1 pl-5 text-left text-sm font-normal leading-5 text-gray-400 hover:text-gray-500">+ <ChevronRight+ className={cn("absolute left-0.5 top-0.5 size-4 text-gray-400 transition-transform", open && "rotate-90")}+ aria-hidden="true"+ />+ {title}+ </CollapsibleTrigger>+ <CollapsibleContent>+ <div className="pt-1 pl-5">{children}</div>+ </CollapsibleContent>+ </Collapsible>+ );+}export default MCPEventsDisplay;diff --git a/ui/litellm-dashboard/src/components/chat_ui/ReasoningContent.tsx b/ui/litellm-dashboard/src/components/chat_ui/ReasoningContent.tsxindex 30ba2d3fd95..770fc7d62b7 100644--- a/ui/litellm-dashboard/src/components/chat_ui/ReasoningContent.tsx+++ b/ui/litellm-dashboard/src/components/chat_ui/ReasoningContent.tsx@@ -1,9 +1,10 @@import React, { useState } from "react";-import { Button } from "antd";import ReactMarkdown from "react-markdown";import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";import { coy } from "react-syntax-highlighter/dist/esm/styles/prism";-import { DownOutlined, RightOutlined, BulbOutlined } from "@ant-design/icons";+import { ChevronDown, ChevronRight, Lightbulb } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";interface ReasoningContentProps {reasoningContent: string;@@ -16,63 +17,65 @@ const ReasoningContent: React.FC<ReasoningContentProps> = ({ reasoningContent })return (<div className="reasoning-content mt-1 mb-2">- <Button- type="text"- className="flex items-center text-xs text-gray-500 hover:text-gray-700"- onClick={() => setIsExpanded(!isExpanded)}- icon={<BulbOutlined />}- >- {isExpanded ? "Hide reasoning" : "Show reasoning"}- {isExpanded ? <DownOutlined className="ml-1" /> : <RightOutlined className="ml-1" />}- </Button>-- {isExpanded && (- <div- className="mt-2 p-3 bg-gray-50 border border-gray-200 rounded-md text-sm text-gray-700 max-w-full overflow-x-auto whitespace-pre-wrap break-words"- style={{ wordBreak: "break-word", overflowWrap: "break-word" }}+ <Collapsible open={isExpanded} onOpenChange={setIsExpanded}>+ <CollapsibleTrigger+ render={+ <Button type="button" variant="ghost" size="sm" className="text-xs text-gray-500 hover:text-gray-700" />+ }>- <ReactMarkdown- components={{- code({- node,- inline,- className,- children,- ...props- }: React.ComponentPropsWithoutRef<"code"> & {- inline?: boolean;- node?: any;- }) {- const match = /language-(\w+)/.exec(className || "");- return !inline && match ? (- <SyntaxHighlighter- style={coy as any}- language={match[1]}- PreTag="div"- className="rounded-md my-2"- wrapLines={true}- wrapLongLines={true}- {...props}- >- {String(children).replace(/\n$/, "")}- </SyntaxHighlighter>- ) : (- <code- className={`${className} px-1.5 py-0.5 rounded-sm bg-gray-100 text-sm font-mono`}- style={{ wordBreak: "break-word" }}- {...props}- >- {children}- </code>- );- },- pre: ({ node, ...props }) => <pre style={{ overflowX: "auto", maxWidth: "100%" }} {...props} />,- }}+ <Lightbulb className="size-3.5" />+ {isExpanded ? "Hide reasoning" : "Show reasoning"}+ {isExpanded ? <ChevronDown className="size-3" /> : <ChevronRight className="size-3" />}+ </CollapsibleTrigger>++ <CollapsibleContent>+ <div+ className="mt-2 max-w-full overflow-x-auto whitespace-pre-wrap break-words rounded-md border border-gray-200 bg-gray-50 p-3 text-sm text-gray-700"+ style={{ wordBreak: "break-word", overflowWrap: "break-word" }}>- {reasoningContent}- </ReactMarkdown>- </div>- )}+ <ReactMarkdown+ components={{+ code({+ node,+ inline,+ className,+ children,+ ...props+ }: React.ComponentPropsWithoutRef<"code"> & {+ inline?: boolean;+ node?: unknown;+ }) {+ const match = /language-(\w+)/.exec(className || "");+ return !inline && match ? (+ <SyntaxHighlighter+ style={coy as Record<string, React.CSSProperties>}+ language={match[1]}+ PreTag="div"+ className="my-2 rounded-md"+ wrapLines={true}+ wrapLongLines={true}+ {...props}+ >+ {String(children).replace(/\n$/, "")}+ </SyntaxHighlighter>+ ) : (+ <code+ className={`${className ?? ""} rounded-sm bg-gray-100 px-1.5 py-0.5 font-mono text-sm`}+ style={{ wordBreak: "break-word" }}+ {...props}+ >+ {children}+ </code>+ );+ },+ pre: ({ node, ...props }) => <pre style={{ overflowX: "auto", maxWidth: "100%" }} {...props} />,+ }}+ >+ {reasoningContent}+ </ReactMarkdown>+ </div>+ </CollapsibleContent>+ </Collapsible></div>);};diff --git a/ui/litellm-dashboard/src/components/chat_ui/ResponseMetrics.tsx b/ui/litellm-dashboard/src/components/chat_ui/ResponseMetrics.tsxindex 01eafa4d534..58069d43ade 100644--- a/ui/litellm-dashboard/src/components/chat_ui/ResponseMetrics.tsx+++ b/ui/litellm-dashboard/src/components/chat_ui/ResponseMetrics.tsx@@ -1,14 +1,6 @@import React from "react";-import { Tooltip } from "antd";-import {- ClockCircleOutlined,- NumberOutlined,- ImportOutlined,- ExportOutlined,- BulbOutlined,- ToolOutlined,- DollarOutlined,-} from "@ant-design/icons";+import { ArrowDownToLine, ArrowUpFromLine, Clock, DollarSign, Hash, Lightbulb, Wrench } from "lucide-react";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";export interface TokenUsage {completionTokens?: number;@@ -25,81 +17,102 @@ interface ResponseMetricsProps {toolName?: string;}+interface MetricItemProps {+ label: string;+ tooltip: string;+ icon: React.ReactNode;+ value: string;+}++function MetricItem({ label, tooltip, icon, value }: MetricItemProps) {+ return (+ <Tooltip>+ <TooltipTrigger render={<div className="flex items-center gap-1" aria-label={`${label}: ${value}`} />}>+ {icon}+ <span>+ {label}: {value}+ </span>+ </TooltipTrigger>+ <TooltipContent>{tooltip}</TooltipContent>+ </Tooltip>+ );+}+const ResponseMetrics: React.FC<ResponseMetricsProps> = ({ timeToFirstToken, totalLatency, usage, toolName }) => {if (!timeToFirstToken && !totalLatency && !usage) return null;return (- <div className="response-metrics mt-2 pt-2 border-t border-gray-100 text-xs text-gray-500 flex flex-wrap gap-3">+ <div className="response-metrics mt-2 flex flex-wrap gap-3 border-t border-gray-100 pt-2 text-xs text-gray-500">{timeToFirstToken !== undefined && (- <Tooltip title="Time to first token">- <div className="flex items-center">- <ClockCircleOutlined className="mr-1" />- <span>TTFT: {(timeToFirstToken / 1000).toFixed(2)}s</span>- </div>- </Tooltip>+ <MetricItem+ label="TTFT"+ tooltip="Time to first token"+ icon={<Clock className="size-3" aria-hidden="true" />}+ value={`${(timeToFirstToken / 1000).toFixed(2)}s`}+ />)}{totalLatency !== undefined && (- <Tooltip title="Total latency">- <div className="flex items-center">- <ClockCircleOutlined className="mr-1" />- <span>Total Latency: {(totalLatency / 1000).toFixed(2)}s</span>- </div>- </Tooltip>+ <MetricItem+ label="Total Latency"+ tooltip="Total latency"+ icon={<Clock className="size-3" aria-hidden="true" />}+ value={`${(totalLatency / 1000).toFixed(2)}s`}+ />)}{usage?.promptTokens !== undefined && (- <Tooltip title="Prompt tokens">- <div className="flex items-center">- <ImportOutlined className="mr-1" />- <span>In: {usage.promptTokens}</span>- </div>- </Tooltip>+ <MetricItem+ label="In"+ tooltip="Prompt tokens"+ icon={<ArrowDownToLine className="size-3" aria-hidden="true" />}+ value={String(usage.promptTokens)}+ />)}{usage?.completionTokens !== undefined && (- <Tooltip title="Completion tokens">- <div className="flex items-center">- <ExportOutlined className="mr-1" />- <span>Out: {usage.completionTokens}</span>- </div>- </Tooltip>+ <MetricItem+ label="Out"+ tooltip="Completion tokens"+ icon={<ArrowUpFromLine className="size-3" aria-hidden="true" />}+ value={String(usage.completionTokens)}+ />)}{usage?.reasoningTokens !== undefined && (- <Tooltip title="Reasoning tokens">- <div className="flex items-center">- <BulbOutlined className="mr-1" />- <span>Reasoning: {usage.reasoningTokens}</span>- </div>- </Tooltip>+ <MetricItem+ label="Reasoning"+ tooltip="Reasoning tokens"+ icon={<Lightbulb className="size-3" aria-hidden="true" />}+ value={String(usage.reasoningTokens)}+ />)}{usage?.totalTokens !== undefined && (- <Tooltip title="Total tokens">- <div className="flex items-center">- <NumberOutlined className="mr-1" />- <span>Total: {usage.totalTokens}</span>- </div>- </Tooltip>+ <MetricItem+ label="Total"+ tooltip="Total tokens"+ icon={<Hash className="size-3" aria-hidden="true" />}+ value={String(usage.totalTokens)}+ />)}{usage?.cost !== undefined && (- <Tooltip title="Cost">- <div className="flex items-center">- <DollarOutlined className="mr-1" />- <span>${usage.cost.toFixed(6)}</span>- </div>- </Tooltip>+ <MetricItem+ label="Cost"+ tooltip="Cost"+ icon={<DollarSign className="size-3" aria-hidden="true" />}+ value={`$${usage.cost.toFixed(6)}`}+ />)}{toolName && (- <Tooltip title="Tool used">- <div className="flex items-center">- <ToolOutlined className="mr-1" />- <span>Tool: {toolName}</span>- </div>- </Tooltip>+ <MetricItem+ label="Tool"+ tooltip="Tool used"+ icon={<Wrench className="size-3" aria-hidden="true" />}+ value={toolName}+ />)}</div>);diff --git a/ui/litellm-dashboard/src/components/guardrails/GuardrailSelector.tsx b/ui/litellm-dashboard/src/components/guardrails/GuardrailSelector.tsxindex 09a62a07200..b8abc484588 100644--- a/ui/litellm-dashboard/src/components/guardrails/GuardrailSelector.tsx+++ b/ui/litellm-dashboard/src/components/guardrails/GuardrailSelector.tsx@@ -1,7 +1,7 @@import React, { useEffect, useState } from "react";-import { Select } from "antd";import { Guardrail } from "./types";import { getGuardrailsList } from "../networking";+import { MultiSelect } from "@/components/shared/MultiSelect";interface GuardrailSelectorProps {onChange: (selectedGuardrails: string[]) => void;@@ -40,25 +40,20 @@ const GuardrailSelector: React.FC<GuardrailSelectorProps> = ({ onChange, value,};return (- <div>- <Select- mode="multiple"+ <div className="min-w-0">+ <MultiSelectdisabled={disabled}placeholder={disabled ? "Setting guardrails is a premium feature." : "Select guardrails"}- onChange={handleGuardrailChange}+ onValueChange={handleGuardrailChange}value={value}loading={loading}className={className}- allowClearoptions={guardrails.map((guardrail) => {return {label: `${guardrail.guardrail_name}`,value: guardrail.guardrail_name,};})}- optionFilterProp="label"- showSearch- style={{ width: "100%" }}/></div>);diff --git a/ui/litellm-dashboard/src/components/llm_calls/fetch_models.tsx b/ui/litellm-dashboard/src/components/llm_calls/fetch_models.tsxindex 0de98330c2e..24f1e038f85 100644--- a/ui/litellm-dashboard/src/components/llm_calls/fetch_models.tsx+++ b/ui/litellm-dashboard/src/components/llm_calls/fetch_models.tsx@@ -7,6 +7,13 @@ export interface ModelGroup {mode?: string;}+interface AvailableModel {+ model_group?: string | null;+ model_name?: string | null;+ id?: string | null;+ mode?: string | null;+}+/*** Fetches available models using modelHubCall and formats them for the selection dropdown.*/@@ -15,14 +22,15 @@ export const fetchAvailableModels = async (accessToken: string): Promise<ModelGrconst fetchedModels = await modelHubCall(accessToken);if (fetchedModels?.data.length > 0) {- const models: ModelGroup[] = fetchedModels.data.map((item: any) => ({- model_group: item.model_group, // Display the model_group to the user- mode: item?.mode, // Save the mode for auto-selection of endpoint type- }));+ const models: ModelGroup[] = fetchedModels.data+ .map((item: AvailableModel) => ({+ model_group: item.model_group || item.id || item.model_name || "",+ mode: item.mode || undefined,+ }))+ .filter((model: ModelGroup) => model.model_group !== "");- // Sort models alphabetically by labelmodels.sort((a, b) => a.model_group.localeCompare(b.model_group));- return models;+ return Array.from(new Map(models.map((model) => [model.model_group, model])).values());}return [];} catch (error) {diff --git a/ui/litellm-dashboard/src/components/policies/PolicySelector.tsx b/ui/litellm-dashboard/src/components/policies/PolicySelector.tsxindex 132538d439f..1e565d938d7 100644--- a/ui/litellm-dashboard/src/components/policies/PolicySelector.tsx+++ b/ui/litellm-dashboard/src/components/policies/PolicySelector.tsx@@ -1,7 +1,7 @@import React, { useEffect, useState } from "react";-import { Select } from "antd";import { Policy } from "./types";import { getPoliciesList } from "../networking";+import { MultiSelect } from "@/components/shared/MultiSelect";/** Prefix for policy version IDs in request body; must match backend POLICY_VERSION_ID_PREFIX. */export const POLICY_VERSION_ID_PREFIX = "policy_";@@ -80,22 +80,17 @@ const PolicySelector: React.FC<PolicySelectorProps> = ({};return (- <div>- <Select- mode="multiple"+ <div className="min-w-0">+ <MultiSelectdisabled={disabled}placeholder={disabled ? "Setting policies is a premium feature." : "Select policies (production or published versions)"}- onChange={handlePolicyChange}+ onValueChange={handlePolicyChange}value={value}loading={loading}className={className}- allowClearoptions={getPolicyOptionEntries(policies)}- optionFilterProp="label"- showSearch- style={{ width: "100%" }}/></div>);diff --git a/ui/litellm-dashboard/src/components/shared/MultiSelect.tsx b/ui/litellm-dashboard/src/components/shared/MultiSelect.tsxnew file mode 100644index 00000000000..429e12ed646--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/MultiSelect.tsx@@ -0,0 +1,119 @@+"use client";++import { useState } from "react";+import {+ Combobox,+ ComboboxChip,+ ComboboxChips,+ ComboboxChipsInput,+ ComboboxContent,+ ComboboxEmpty,+ ComboboxItem,+ ComboboxList,+ ComboboxValue,+} from "@/components/ui/combobox";++export interface MultiSelectOption {+ label: string;+ value: string;+ description?: string;+}++interface MultiSelectProps {+ options: MultiSelectOption[];+ value?: string[];+ onValueChange: (value: string[]) => void;+ placeholder?: string;+ emptyText?: string;+ disabled?: boolean;+ loading?: boolean;+ allowCustomValues?: boolean;+ className?: string;+}++const matchesQuery = (option: MultiSelectOption, query: string): boolean => {+ const normalizedQuery = query.trim().toLowerCase();+ return (+ !normalizedQuery ||+ option.label.toLowerCase().includes(normalizedQuery) ||+ option.value.toLowerCase().includes(normalizedQuery) ||+ (option.description?.toLowerCase().includes(normalizedQuery) ?? false)+ );+};++export function MultiSelect({+ options,+ value = [],+ onValueChange,+ placeholder = "Select options",+ emptyText = "No options found",+ disabled = false,+ loading = false,+ allowCustomValues = false,+ className,+}: MultiSelectProps) {+ const [query, setQuery] = useState("");+ const selectedOptions = value.map(+ (selectedValue) =>+ options.find((option) => option.value === selectedValue) ?? {+ label: selectedValue,+ value: selectedValue,+ },+ );+ const customOption = query.trim();+ const customOptionExists = options.some((option) => option.value.toLowerCase() === customOption.toLowerCase());+ const items =+ allowCustomValues && customOption && !customOptionExists+ ? [...options, { label: `Create "${customOption}"`, value: customOption }]+ : options;++ return (+ <Combobox+ multiple+ items={items}+ value={selectedOptions}+ onValueChange={(selected: MultiSelectOption[]) => {+ onValueChange(selected.map((option) => option.value));+ setQuery("");+ }}+ inputValue={query}+ onInputValueChange={setQuery}+ isItemEqualToValue={(option: MultiSelectOption, selected: MultiSelectOption) => option.value === selected.value}+ itemToStringLabel={(option: MultiSelectOption) => option.label}+ filter={matchesQuery}+ disabled={disabled || loading}+ >+ <ComboboxChips className={`min-h-8 py-1 text-sm ${className ?? ""}`}>+ <ComboboxValue>+ {(selected: MultiSelectOption[]) =>+ selected.map((option) => (+ <ComboboxChip key={option.value} aria-label={option.label}>+ {option.label}+ </ComboboxChip>+ ))+ }+ </ComboboxValue>+ <ComboboxChipsInput+ placeholder={loading ? "Loading..." : placeholder}+ className="h-5 min-w-24 flex-1 border-0 bg-transparent py-0 text-sm"+ aria-label={placeholder}+ />+ </ComboboxChips>+ <ComboboxContent>+ <ComboboxEmpty>{emptyText}</ComboboxEmpty>+ <ComboboxList>+ {(option: MultiSelectOption) => (+ <ComboboxItem key={option.value} value={option}>+ <span className="min-w-0">+ <span className="block truncate">{option.label}</span>+ {option.description && (+ <span className="block truncate text-xs text-muted-foreground">{option.description}</span>+ )}+ </span>+ </ComboboxItem>+ )}+ </ComboboxList>+ </ComboboxContent>+ </Combobox>+ );+}diff --git a/ui/litellm-dashboard/src/components/shared/SearchSelect.tsx b/ui/litellm-dashboard/src/components/shared/SearchSelect.tsxindex eff5cfc804d..f67a1cffa1d 100644--- a/ui/litellm-dashboard/src/components/shared/SearchSelect.tsx+++ b/ui/litellm-dashboard/src/components/shared/SearchSelect.tsx@@ -56,9 +56,9 @@ export function SearchSelect({<ComboboxInputplaceholder={placeholder}showClear={value != null && value !== ""}- className={`w-full ${className ?? ""}`}+ className={`h-8 w-full text-sm ${className ?? ""}`}/>- <ComboboxContent>+ <ComboboxContent side="bottom" collisionAvoidance={{ side: "shift", align: "shift", fallbackAxisSide: "none" }}><ComboboxEmpty>{emptyText}</ComboboxEmpty><ComboboxList>{(item: SearchSelectOption) => (diff --git a/ui/litellm-dashboard/src/components/tag_management/TagSelector.tsx b/ui/litellm-dashboard/src/components/tag_management/TagSelector.tsxindex 9d2a3ff97a2..7ca809a0610 100644--- a/ui/litellm-dashboard/src/components/tag_management/TagSelector.tsx+++ b/ui/litellm-dashboard/src/components/tag_management/TagSelector.tsx@@ -1,7 +1,7 @@import React, { useEffect, useState } from "react";-import { Select } from "antd";import { Tag } from "./types";import { tagListCall } from "../networking";+import { MultiSelect } from "@/components/shared/MultiSelect";interface TagSelectorProps {onChange: (selectedTags: string[]) => void;@@ -17,6 +17,7 @@ const TagSelector: React.FC<TagSelectorProps> = ({ onChange, value, className, auseEffect(() => {const fetchTags = async () => {if (!accessToken) return;+ setLoading(true);try {const response = await tagListCall(accessToken);setTags(Object.values(response));@@ -31,24 +32,18 @@ const TagSelector: React.FC<TagSelectorProps> = ({ onChange, value, className, a}, [accessToken]);return (- <Select- mode="tags"- showSearch+ <MultiSelectplaceholder="Select or create tags"- onChange={onChange}+ onValueChange={onChange}value={value}loading={loading}className={className}+ allowCustomValuesoptions={tags.map((tag) => ({label: tag.name,value: tag.name,- title: tag.description || tag.name,+ description: tag.description || undefined,}))}- optionFilterProp="label"- tokenSeparators={[","]}- maxTagCount="responsive"- allowClear- style={{ width: "100%" }}/>);};diff --git a/ui/litellm-dashboard/src/components/ui/combobox.tsx b/ui/litellm-dashboard/src/components/ui/combobox.tsxindex 2854928140e..541ad8bb25c 100644--- a/ui/litellm-dashboard/src/components/ui/combobox.tsx+++ b/ui/litellm-dashboard/src/components/ui/combobox.tsx@@ -83,10 +83,14 @@ function ComboboxContent({sideOffset = 6,align = "start",alignOffset = 0,+ collisionAvoidance,anchor,...props}: ComboboxPrimitive.Popup.Props &- Pick<ComboboxPrimitive.Positioner.Props, "side" | "align" | "sideOffset" | "alignOffset" | "anchor">) {+ Pick<+ ComboboxPrimitive.Positioner.Props,+ "side" | "align" | "sideOffset" | "alignOffset" | "collisionAvoidance" | "anchor"+ >) {return (<ComboboxPrimitive.Portal><ComboboxPrimitive.Positioner@@ -94,6 +98,7 @@ function ComboboxContent({sideOffset={sideOffset}align={align}alignOffset={alignOffset}+ collisionAvoidance={collisionAvoidance}anchor={anchor}className="isolate z-50">diff --git a/ui/litellm-dashboard/src/components/vector_store_management/VectorStoreSelector.tsx b/ui/litellm-dashboard/src/components/vector_store_management/VectorStoreSelector.tsxindex 2642b74e492..d80996f6a28 100644--- a/ui/litellm-dashboard/src/components/vector_store_management/VectorStoreSelector.tsx+++ b/ui/litellm-dashboard/src/components/vector_store_management/VectorStoreSelector.tsx@@ -1,7 +1,7 @@import React, { useEffect, useState } from "react";-import { Select } from "antd";import { VectorStore } from "./types";import { vectorStoreListCall } from "../networking";+import { MultiSelect } from "@/components/shared/MultiSelect";interface VectorStoreSelectorProps {onChange: (selectedVectorStores: string[]) => void;value?: string[];@@ -43,24 +43,19 @@ const VectorStoreSelector: React.FC<VectorStoreSelectorProps> = ({}, [accessToken]);return (- <div>- <Select- mode="multiple"+ <div className="min-w-0">+ <MultiSelectplaceholder={placeholder}- onChange={onChange}+ onValueChange={onChange}value={value}loading={loading}className={className}- allowClear+ disabled={disabled}options={vectorStores.map((store) => ({label: `${store.vector_store_name || store.vector_store_id} (${store.vector_store_id})`,value: store.vector_store_id,- title: store.vector_store_description || store.vector_store_id,+ description: store.vector_store_description || undefined,}))}- optionFilterProp="label"- showSearch- style={{ width: "100%" }}- disabled={disabled}/></div>);