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): render request metrics on the /ui/chat surface (#36845)
Yassin Kortame0f388cb5c92
diff --git a/ui/litellm-dashboard/src/app/chat/page.integration.test.tsx b/ui/litellm-dashboard/src/app/chat/page.integration.test.tsxnew file mode 100644index 00000000000..718c692a7a6--- /dev/null+++ b/ui/litellm-dashboard/src/app/chat/page.integration.test.tsx@@ -0,0 +1,132 @@+import React from "react";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { useChatHistory } from "@/components/chat/useChatHistory";+import ChatConversationPage from "./page";++const { mockMakeOpenAIResponsesRequest } = vi.hoisted(() => ({+ mockMakeOpenAIResponsesRequest: vi.fn(),+}));++vi.mock("next/navigation", () => ({+ useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),+}));++vi.mock("@/components/llm_calls/fetch_models", () => ({+ fetchAvailableModels: vi.fn(async () => [{ model_group: "gpt-5.4-mini" }]),+}));++vi.mock("@/components/llm_calls/responses_api", () => ({+ makeOpenAIResponsesRequest: mockMakeOpenAIResponsesRequest,+}));++vi.mock("@/components/chat/MCPConnectPicker", () => ({+ default: () => <div data-testid="mcp-connect-picker" />,+}));++vi.mock("react-markdown", () => ({+ default: ({ children }: { children: string }) => <div>{children}</div>,+}));++vi.mock("remark-gfm", () => ({ default: () => undefined }));++vi.mock("react-syntax-highlighter", () => ({+ Prism: ({ children }: { children: string }) => <pre>{children}</pre>,+}));++vi.mock("react-syntax-highlighter/dist/esm/styles/prism", () => ({ coy: {} }));++vi.mock("@/contexts/ChatShellContext", () => ({+ useChatShell: () => {+ const history = useChatHistory(null, "metrics-test-user");+ return {+ accessToken: "sk-test",+ userId: "metrics-test-user",+ userEmail: "[email protected]",+ userRole: "Admin",+ premiumUser: false,+ selectedMCPServers: [],+ setSelectedMCPServers: vi.fn(),+ conversations: history.conversations,+ activeConversation: history.activeConversation,+ activeConversationId: history.currentActiveId,+ storageUnavailable: false,+ staleId: false,+ createConversation: history.createConversation,+ appendMessage: history.appendMessage,+ updateLastAssistantMessage: history.updateLastAssistantMessage,+ truncateFromMessage: history.truncateFromMessage,+ deleteConversation: vi.fn(),+ renameConversation: vi.fn(),+ };+ },+}));++const ONE_TURN_ARG_COUNT = 25;+const ON_TIMING_DATA_INDEX = 7;+const ON_USAGE_DATA_INDEX = 8;+const ON_TOTAL_LATENCY_INDEX = 24;++async function sendOneMessage(): Promise<void> {+ render(<ChatConversationPage />);+ await waitFor(() => expect(screen.getByRole("button", { name: /gpt-5\.4-mini/ })).toBeInTheDocument());+ fireEvent.change(screen.getByPlaceholderText("How can I help you today?"), {+ target: { value: "How much did this cost?" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Send" }));+ await waitFor(() => expect(mockMakeOpenAIResponsesRequest).toHaveBeenCalledTimes(1));+}++describe("/ui/chat request metrics", () => {+ beforeEach(() => {+ localStorage.clear();+ mockMakeOpenAIResponsesRequest.mockReset();+ });++ it("renders latency, TTFT, token counts and cost reported for the assistant turn", async () => {+ mockMakeOpenAIResponsesRequest.mockImplementation(async (...args: unknown[]) => {+ const updateTextUI = args[1] as (role: string, delta: string) => void;+ const onTimingData = args[ON_TIMING_DATA_INDEX] as ((ttft: number) => void) | undefined;+ const onUsageData = args[ON_USAGE_DATA_INDEX] as ((usage: Record<string, number>) => void) | undefined;+ const onTotalLatency = args[ON_TOTAL_LATENCY_INDEX] as ((latency: number) => void) | undefined;++ updateTextUI("assistant", "Sixty three microdollars.");+ onTimingData?.(250);+ onUsageData?.({ promptTokens: 12, completionTokens: 8, totalTokens: 20, cost: 0.000063 });+ onTotalLatency?.(1200);+ });++ await sendOneMessage();++ await waitFor(() => expect(screen.getByLabelText("Total: 20")).toBeInTheDocument());+ expect(screen.getByLabelText("TTFT: 0.25s")).toBeInTheDocument();+ expect(screen.getByLabelText("Total Latency: 1.20s")).toBeInTheDocument();+ expect(screen.getByLabelText("In: 12")).toBeInTheDocument();+ expect(screen.getByLabelText("Out: 8")).toBeInTheDocument();+ expect(screen.getByLabelText("Cost: $0.000063")).toBeInTheDocument();+ });++ it("supplies the timing, usage and latency callbacks at the positional slots the Responses helper reads", async () => {+ mockMakeOpenAIResponsesRequest.mockResolvedValue(undefined);++ await sendOneMessage();++ const call = mockMakeOpenAIResponsesRequest.mock.calls[0];+ expect(call).toHaveLength(ONE_TURN_ARG_COUNT);+ expect(typeof call[ON_TIMING_DATA_INDEX]).toBe("function");+ expect(typeof call[ON_USAGE_DATA_INDEX]).toBe("function");+ expect(typeof call[ON_TOTAL_LATENCY_INDEX]).toBe("function");+ });++ it("shows no metrics bar for a turn the provider reported no usage for", async () => {+ mockMakeOpenAIResponsesRequest.mockImplementation(async (...args: unknown[]) => {+ const updateTextUI = args[1] as (role: string, delta: string) => void;+ updateTextUI("assistant", "No usage here.");+ });++ await sendOneMessage();++ await waitFor(() => expect(screen.getByText("No usage here.")).toBeInTheDocument());+ expect(document.querySelector(".response-metrics")).toBeNull();+ });+});diff --git a/ui/litellm-dashboard/src/app/chat/page.tsx b/ui/litellm-dashboard/src/app/chat/page.tsxindex 7b6b26c6436..0391bafcfd9 100644--- a/ui/litellm-dashboard/src/app/chat/page.tsx+++ b/ui/litellm-dashboard/src/app/chat/page.tsx@@ -15,6 +15,7 @@ import ChatMessages from "@/components/chat/ChatMessages";import MCPConnectPicker from "@/components/chat/MCPConnectPicker";import { fetchAvailableModels } from "@/components/llm_calls/fetch_models";import { makeOpenAIResponsesRequest } from "@/components/llm_calls/responses_api";+import type { TokenUsage } from "@/components/chat_ui/ResponseMetrics";import type { MCPEvent } from "@/components/chat/types";import { getProviderLogoAndName } from "@/components/provider_info_helpers";@@ -202,8 +203,8 @@ export default function ChatConversationPage() {accumulatedReasoning += rc;updateLastAssistantMessage(convId!, { reasoningContent: accumulatedReasoning });},- undefined,- undefined,+ (timeToFirstToken: number) => updateLastAssistantMessage(convId!, { timeToFirstToken }),+ (usage: TokenUsage) => updateLastAssistantMessage(convId!, { usage }),undefined,undefined,undefined,@@ -216,6 +217,14 @@ export default function ChatConversationPage() {// one full localStorage write per MCP event during streaming.accumulatedMCPEvents.push(event);},+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ true,+ (totalLatency: number) => updateLastAssistantMessage(convId!, { totalLatency }),);streamCompletedCleanly = true;} catch (err: unknown) {diff --git a/ui/litellm-dashboard/src/components/chat/ChatMessages.tsx b/ui/litellm-dashboard/src/components/chat/ChatMessages.tsxindex dc58973d4ca..502260ccef4 100644--- a/ui/litellm-dashboard/src/components/chat/ChatMessages.tsx+++ b/ui/litellm-dashboard/src/components/chat/ChatMessages.tsx@@ -11,6 +11,7 @@ import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";import { coy } from "react-syntax-highlighter/dist/esm/styles/prism";import ReasoningContent from "@/components/chat_ui/ReasoningContent";import MCPEventsDisplay from "@/components/chat_ui/MCPEventsDisplay";+import ResponseMetrics from "@/components/chat_ui/ResponseMetrics";import { ChatMessage } from "./types";const REDACTED_KEY_PATTERNS = /token|key|secret|password|auth/i;@@ -248,6 +249,12 @@ function AssistantBubble({ message, isLastMessage, isStreaming, isTypingIndicato<MCPEventsDisplay events={mcpEvents} /></div>)}++ <ResponseMetrics+ timeToFirstToken={message.timeToFirstToken}+ totalLatency={message.totalLatency}+ usage={message.usage}+ /></div>);}diff --git a/ui/litellm-dashboard/src/components/chat/types.ts b/ui/litellm-dashboard/src/components/chat/types.tsindex 9b657306db6..89276ff54db 100644--- a/ui/litellm-dashboard/src/components/chat/types.ts+++ b/ui/litellm-dashboard/src/components/chat/types.ts@@ -1,4 +1,5 @@import type { MCPEvent } from "../mcp_tools/types";+import type { TokenUsage } from "../chat_ui/ResponseMetrics";export type { MCPEvent };export interface ChatMessage {@@ -11,9 +12,16 @@ export interface ChatMessage {toolName?: string;toolArgs?: Record<string, unknown>;toolResult?: string;+ timeToFirstToken?: number;+ totalLatency?: number;+ usage?: TokenUsage;timestamp: number;}+export type AssistantMessageUpdate = Partial<+ Pick<ChatMessage, "content" | "reasoningContent" | "mcpEvents" | "timeToFirstToken" | "totalLatency" | "usage">+>;+export interface Conversation {id: string;title: string;diff --git a/ui/litellm-dashboard/src/components/chat/useChatHistory.ts b/ui/litellm-dashboard/src/components/chat/useChatHistory.tsindex 8e6c3ce5877..b99ef52d18f 100644--- a/ui/litellm-dashboard/src/components/chat/useChatHistory.ts+++ b/ui/litellm-dashboard/src/components/chat/useChatHistory.ts@@ -1,5 +1,5 @@import { useCallback, useEffect, useState } from "react";-import { ChatMessage, Conversation } from "./types";+import { AssistantMessageUpdate, ChatMessage, Conversation } from "./types";const STORAGE_KEY_PREFIX = "litellm_chat_history_v1";const MAX_CONVERSATIONS = 100;@@ -57,10 +57,7 @@ export function useChatHistory(staleId: boolean;createConversation: (model: string) => string;appendMessage: (conversationId: string, message: Omit<ChatMessage, "id" | "timestamp">) => void;- updateLastAssistantMessage: (- conversationId: string,- updates: Partial<Pick<ChatMessage, "content" | "reasoningContent" | "mcpEvents">>,- ) => void;+ updateLastAssistantMessage: (conversationId: string, updates: AssistantMessageUpdate) => void;/** Remove the message with `messageId` and all subsequent messages from the conversation. */truncateFromMessage: (conversationId: string, messageId: string) => void;deleteConversation: (id: string) => void;@@ -150,25 +147,22 @@ export function useChatHistory(});}, []);- const updateLastAssistantMessage = useCallback(- (conversationId: string, updates: Partial<Pick<ChatMessage, "content" | "reasoningContent" | "mcpEvents">>) => {- setConversations((prev) => {- const updated = prev.map((conv) => {- if (conv.id !== conversationId) return conv;- const messages = [...conv.messages];- const lastAssistantIndex = messages.reduceRight((found, msg, idx) => {- if (found !== -1) return found;- return msg.role === "assistant" ? idx : -1;- }, -1);- if (lastAssistantIndex === -1) return conv;- messages[lastAssistantIndex] = { ...messages[lastAssistantIndex], ...updates };- return { ...conv, messages, updatedAt: Date.now() };- });- return trimConversations(updated);+ const updateLastAssistantMessage = useCallback((conversationId: string, updates: AssistantMessageUpdate) => {+ setConversations((prev) => {+ const updated = prev.map((conv) => {+ if (conv.id !== conversationId) return conv;+ const messages = [...conv.messages];+ const lastAssistantIndex = messages.reduceRight((found, msg, idx) => {+ if (found !== -1) return found;+ return msg.role === "assistant" ? idx : -1;+ }, -1);+ if (lastAssistantIndex === -1) return conv;+ messages[lastAssistantIndex] = { ...messages[lastAssistantIndex], ...updates };+ return { ...conv, messages, updatedAt: Date.now() };});- },- [],- );+ return trimConversations(updated);+ });+ }, []);const truncateFromMessage = useCallback((conversationId: string, messageId: string) => {setConversations((prev) => {diff --git a/ui/litellm-dashboard/src/components/llm_calls/responses_api.test.tsx b/ui/litellm-dashboard/src/components/llm_calls/responses_api.test.tsxindex ae70af4d779..065eaaf3632 100644--- a/ui/litellm-dashboard/src/components/llm_calls/responses_api.test.tsx+++ b/ui/litellm-dashboard/src/components/llm_calls/responses_api.test.tsx@@ -172,6 +172,57 @@ describe("responses_api", () => {expect(onTotalLatency).toHaveBeenLastCalledWith(expect.any(Number));});+ it("should forward the cost the proxy reports on the streamed usage object", async () => {+ async function* streamWithCost() {+ yield { type: "response.output_text.delta", delta: "Hi" };+ yield {+ type: "response.completed",+ response: {+ id: "resp_cost",+ usage: { output_tokens: 12, input_tokens: 12, total_tokens: 24, cost: 0.000063 },+ },+ };+ }+ mockResponsesCreate.mockResolvedValueOnce(streamWithCost());++ const onUsageData = vi.fn();++ await makeOpenAIResponsesRequest(+ messages,+ mockUpdateTextUI,+ "gpt-4",+ "test-token",+ undefined,+ undefined,+ undefined,+ undefined,+ onUsageData,+ );++ expect(onUsageData).toHaveBeenCalledWith(+ { completionTokens: 12, promptTokens: 12, totalTokens: 24, cost: 0.000063 },+ "",+ );+ });++ it("should omit cost when the proxy reports none", async () => {+ const onUsageData = vi.fn();++ await makeOpenAIResponsesRequest(+ messages,+ mockUpdateTextUI,+ "gpt-4",+ "test-token",+ undefined,+ undefined,+ undefined,+ undefined,+ onUsageData,+ );++ expect(onUsageData).toHaveBeenCalledWith(expect.not.objectContaining({ cost: expect.anything() }), "");+ });+it("should replay MCP output items as events for a non-streaming response", async () => {mockResponsesCreate.mockResolvedValueOnce({id: "resp_789",diff --git a/ui/litellm-dashboard/src/components/llm_calls/responses_api.tsx b/ui/litellm-dashboard/src/components/llm_calls/responses_api.tsxindex ec98c559c6b..775ccee9bee 100644--- a/ui/litellm-dashboard/src/components/llm_calls/responses_api.tsx+++ b/ui/litellm-dashboard/src/components/llm_calls/responses_api.tsx@@ -299,6 +299,10 @@ export async function makeOpenAIResponsesRequest(usageData.reasoningTokens = usage.completion_tokens_details.reasoning_tokens;}+ if (usage.cost !== undefined && usage.cost !== null) {+ usageData.cost = Number(usage.cost);+ }+onUsageData(usageData, mcpToolUsed);}}diff --git a/ui/litellm-dashboard/src/contexts/ChatShellContext.tsx b/ui/litellm-dashboard/src/contexts/ChatShellContext.tsxindex b0f590d2394..bb1b9d1e670 100644--- a/ui/litellm-dashboard/src/contexts/ChatShellContext.tsx+++ b/ui/litellm-dashboard/src/contexts/ChatShellContext.tsx@@ -3,7 +3,7 @@import React, { createContext, useContext, useState } from "react";import { useSearchParams } from "next/navigation";import { useChatHistory } from "@/components/chat/useChatHistory";-import type { ChatMessage, Conversation } from "@/components/chat/types";+import type { AssistantMessageUpdate, ChatMessage, Conversation } from "@/components/chat/types";interface ChatShellContextValue {accessToken: string;@@ -20,10 +20,7 @@ interface ChatShellContextValue {staleId: boolean;createConversation: (model: string) => string;appendMessage: (conversationId: string, message: Omit<ChatMessage, "id" | "timestamp">) => void;- updateLastAssistantMessage: (- conversationId: string,- updates: Partial<Pick<ChatMessage, "content" | "reasoningContent" | "mcpEvents">>,- ) => void;+ updateLastAssistantMessage: (conversationId: string, updates: AssistantMessageUpdate) => void;truncateFromMessage: (conversationId: string, messageId: string) => void;deleteConversation: (id: string) => void;renameConversation: (id: string, newTitle: string) => void;