Skip to content

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]

chore: merge main into litellm_lit6314_guardrail_metadata_transfer

yuchengb4e3d7c533e4
diff --cc litellm/llms/openai/chat/guardrail_translation/handler.py
index 76a7f33454a,58ff03e6a0d..0f5096d0108
--- a/litellm/llms/openai/chat/guardrail_translation/handler.py
+++ b/litellm/llms/openai/chat/guardrail_translation/handler.py
@@@ -191,15 -210,6 +210,13 @@@ class OpenAIChatCompletionsHandler(Base
task_mappings=tool_call_task_mappings,
)
+ elif not guardrail_to_apply.records_own_guardrail_information:
- # Every guardrail in applied_guardrails needs a persisted evaluation record,
- # or request logs report it as silently missing (LIT-6314).
+ guardrail_to_apply.add_standard_logging_guardrail_information_to_request_data(
+ guardrail_json_response="no scannable content after message scoping",
+ request_data=data,
+ guardrail_status="not_run",
+ )
+
verbose_proxy_logger.debug(
"OpenAI Chat Completions: Processed input messages: %s",
data.get("messages"),
diff --cc litellm/proxy/compliance_checks.py
index 053c88d10ed,ff311911742..d9cc1d0f4fc
--- a/litellm/proxy/compliance_checks.py
+++ b/litellm/proxy/compliance_checks.py
@@@ -26,8 -26,7 +26,7 @@@ class ComplianceChecker
def __init__(self, data: ComplianceCheckRequest):
self.data = data
- # a not_run entry records a guardrail that never evaluated the request, so it cannot evidence compliance
- self.guardrails = data.guardrail_information or []
+ self.guardrails = [g for g in (data.guardrail_information or []) if g.get("guardrail_status") != "not_run"]
def _get_guardrails_by_mode(self, mode: str) -> list[dict]:
"""
diff --cc litellm/proxy/guardrails/usage_endpoints.py
index 75ffc1545dc,6259efb6654..556b6a4e919
--- a/litellm/proxy/guardrails/usage_endpoints.py
+++ b/litellm/proxy/guardrails/usage_endpoints.py
@@@ -41,6 -42,9 +42,9 @@@ if TYPE_CHECKING
router: Final = APIRouter()
_EMPTY_UNITS: Final[Mapping[str, int]] = MappingProxyType({})
-_ACTION_SEVERITY: Final[Mapping[str, int]] = MappingProxyType({"passed": 0, "flagged": 1, "blocked": 2})
++_ACTION_SEVERITY: Final[Mapping[str, int]] = MappingProxyType({"not_run": 0, "passed": 1, "flagged": 2, "blocked": 3})
+
+ _T = TypeVar("_T")
_USAGE_MAX_RANGE_DAYS: Final = 366
diff --cc litellm/proxy/guardrails/usage_tracking.py
index ec059acb146,797323794d2..6d72d94718f
--- a/litellm/proxy/guardrails/usage_tracking.py
+++ b/litellm/proxy/guardrails/usage_tracking.py
@@@ -160,14 -192,14 +192,16 @@@ async def _upsert_rows_with_retry
return await _upsert_rows_with_retry(retryable, upsert_row, label, sleep, retries_left - 1)
- def _guardrail_status_to_action(status: str | None) -> str:
- """Map StandardLogging guardrail_status to blocked/passed/flagged."""
+ def guardrail_status_to_action(status: str | None) -> str:
- """Map StandardLogging guardrail_status to blocked/passed/flagged."""
++ """Map StandardLogging guardrail_status to blocked/passed/flagged/not_run."""
if not status:
return "passed"
s: Final = (status or "").lower()
++ if s == "not_run":
++ return "not_run"
if "intervened" in s or "block" in s:
return "blocked"
- if "fail" in s or "error" in s:
+ if "flagged" in s or "fail" in s or "error" in s:
return "flagged"
return "passed"
@@@ -316,18 -367,15 +369,16 @@@ async def process_spend_logs_guardrail_
guardrail_id = entry.get("guardrail_id") or entry.get("guardrail_name") or ""
if not guardrail_id:
continue
- status = entry.get("guardrail_status")
- # not_run means the guardrail never evaluated the request: index it for drill-down, keep it out of counts
- if status != "not_run":
- key = _MetricsKey(guardrail_id, date_key)
- daily_guardrail[key]["requests_evaluated"] += 1
+ action = guardrail_status_to_action(entry.get("guardrail_status"))
- if action == "passed":
- daily_guardrail[key]["passed_count"] += 1
- elif action == "blocked":
- daily_guardrail[key]["blocked_count"] += 1
- else:
- daily_guardrail[key]["flagged_count"] += 1
++ if action != "not_run":
+ key = _MetricsKey(guardrail_id, date_key)
+ daily_guardrail[key]["requests_evaluated"] += 1
- action = _guardrail_status_to_action(status)
+ if action == "passed":
+ daily_guardrail[key]["passed_count"] += 1
+ elif action == "blocked":
+ daily_guardrail[key]["blocked_count"] += 1
+ else:
+ daily_guardrail[key]["flagged_count"] += 1
policy_id = entry.get("policy_id")
index_rows.append(
{
diff --cc tests/test_litellm/llms/openai/chat/guardrail_translation/test_openai_guardrail_handler.py
index 24060e94e54,5a29a96829f..4f1163ed806
--- a/tests/test_litellm/llms/openai/chat/guardrail_translation/test_openai_guardrail_handler.py
+++ b/tests/test_litellm/llms/openai/chat/guardrail_translation/test_openai_guardrail_handler.py
@@@ -1561,51 -1893,156 +1893,206 @@@ class TestScanOnlyToolResults
assert data["messages"][4]["content"] == "and then?"
+class TestNoScannableContentRecordsNotRun:
+ """LIT-6314: a guardrail whose scoping leaves nothing to scan must still persist an evaluation record"""
+
+ def _system_only_data(self) -> dict:
+ return {"messages": [{"role": "system", "content": "SYSTEM-PROMPT"}]}
+
+ def _recorded_entries(self, data: dict) -> list:
+ metadata = data.get("metadata") or data.get("litellm_metadata") or {}
+ return metadata.get("standard_logging_guardrail_information") or []
+
+ @pytest.mark.asyncio
+ async def test_skipped_scan_records_not_run_entry(self):
+ handler = OpenAIChatCompletionsHandler()
+ guardrail = MockGuardrail(guardrail_name="skip-system-guardrail")
+ guardrail.skip_system_message_in_guardrail = True
+ data = self._system_only_data()
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert guardrail.last_inputs is None, "nothing survived scoping, apply_guardrail must not run"
+ entries = self._recorded_entries(data)
+ assert len(entries) == 1
+ assert entries[0]["guardrail_name"] == "skip-system-guardrail"
+ assert entries[0]["guardrail_status"] == "not_run"
+
+ @pytest.mark.asyncio
+ async def test_self_recording_guardrail_is_left_alone(self):
+ handler = OpenAIChatCompletionsHandler()
+ guardrail = MockGuardrail(guardrail_name="self-recording-guardrail")
+ guardrail.skip_system_message_in_guardrail = True
+ guardrail.records_own_guardrail_information = True
+ data = self._system_only_data()
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert guardrail.last_inputs is None
+ assert self._recorded_entries(data) == []
+
+ @pytest.mark.asyncio
+ async def test_scannable_content_records_no_extra_entry(self):
+ handler = OpenAIChatCompletionsHandler()
+ guardrail = MockGuardrail(guardrail_name="normal-guardrail")
+ data = {"messages": [{"role": "user", "content": "hello"}]}
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert guardrail.last_inputs is not None
+ assert all(e.get("guardrail_status") != "not_run" for e in self._recorded_entries(data))
++
++
+ class TestBuildBlockSseChunks:
+ """build_block_sse_chunks turns a streaming ModifyResponseException into 200 SSE chunks"""
+
+ def _exc(self, original_response=None):
+ from litellm.exceptions import ModifyResponseException
+
+ return ModifyResponseException(
+ message="Blocked by policy.",
+ model="gpt-5.4-mini",
+ request_data={},
+ guardrail_name="test",
+ original_response=original_response,
+ )
+
+ def _payloads(self, chunks):
+ return [json.loads(chunk.decode().removeprefix("data: ").strip()) for chunk in chunks]
+
+ def test_standalone_block_uses_fresh_identity_and_zero_usage(self):
+ handler = OpenAIChatCompletionsHandler()
+ first, final = self._payloads(handler.build_block_sse_chunks(self._exc(), stream_started=False))
+ assert first["id"].startswith("chatcmpl-")
+ assert first["model"] == "gpt-5.4-mini"
+ assert first["choices"][0]["delta"] == {"role": "assistant", "content": "Blocked by policy."}
+ assert first["choices"][0]["finish_reason"] is None
+ assert final["choices"][0]["delta"] == {}
+ assert final["choices"][0]["finish_reason"] == "content_filter"
+ assert final["usage"] == {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
+
+ def test_continuation_reuses_stream_identity_and_real_usage(self):
+ handler = OpenAIChatCompletionsHandler()
+ yielded = [
+ {"id": "chatcmpl-live", "created": 1724900000, "model": "gpt-5.4-mini-2026-01-01"},
+ ]
+ original = yielded + [
+ {"id": "chatcmpl-live", "usage": {"prompt_tokens": 11, "completion_tokens": 5}},
+ ]
+ first, final = self._payloads(
+ handler.build_block_sse_chunks(
+ self._exc(original_response=original), stream_started=True, responses_so_far=yielded
+ )
+ )
+ assert (first["id"], first["created"], first["model"]) == (
+ "chatcmpl-live",
+ 1724900000,
+ "gpt-5.4-mini-2026-01-01",
+ )
+ assert first["choices"][0]["delta"] == {"content": "Blocked by policy."}
+ assert final["id"] == "chatcmpl-live"
+ assert final["usage"] == {"prompt_tokens": 11, "completion_tokens": 5, "total_tokens": 16}
+
+
+ class TestCheckStreamingHasEnded:
+ """_check_streaming_has_ended lets end_of_stream_only withhold the finish chunk until moderation"""
+
+ def test_empty_and_content_only_chunks_are_not_ended(self):
+ handler = OpenAIChatCompletionsHandler()
+ assert handler._check_streaming_has_ended([]) is False
+ content_only = [
+ {"id": "chatcmpl-live", "choices": [{"index": 0, "delta": {"content": "hi"}, "finish_reason": None}]},
+ {"id": "chatcmpl-live", "choices": []},
+ {"id": "chatcmpl-live", "usage": {"prompt_tokens": 1, "completion_tokens": 1}},
+ ]
+ assert handler._check_streaming_has_ended(content_only) is False
+
+ def test_dict_finish_chunk_marks_stream_ended(self):
+ handler = OpenAIChatCompletionsHandler()
+ chunks = [
+ {"id": "chatcmpl-live", "choices": [{"index": 0, "delta": {"content": "hi"}, "finish_reason": None}]},
+ {"id": "chatcmpl-live", "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]},
+ ]
+ assert handler._check_streaming_has_ended(chunks) is True
+
+ def test_object_finish_chunk_marks_stream_ended(self):
+ from litellm.types.utils import Delta, ModelResponseStream, StreamingChoices
+
+ handler = OpenAIChatCompletionsHandler()
+ chunks = [
+ ModelResponseStream(
+ choices=[StreamingChoices(index=0, delta=Delta(content=None), finish_reason="stop")]
+ )
+ ]
+ assert handler._check_streaming_has_ended(chunks) is True
+
+
+ class TestStreamingScanKey:
+ """get_streaming_scan_key identifies what a sampled round would scan so the
+ unified hook can skip rounds that would re-scan already-cleared text"""
+
+ @staticmethod
+ def _chunk(content, finish_reason=None, index=0):
+ from litellm.types.utils import Delta, ModelResponseStream, StreamingChoices
+
+ return ModelResponseStream(
+ choices=[StreamingChoices(index=index, delta=Delta(content=content), finish_reason=finish_reason)]
+ )
+
+ def test_key_carries_accumulated_text_and_open_stream(self):
+ handler = OpenAIChatCompletionsHandler()
+ key = handler.get_streaming_scan_key([self._chunk("hel"), self._chunk("lo")])
+ assert key == StreamingScanKey(texts=("hello",))
+
+ def test_chunks_without_text_leave_the_key_unchanged(self):
+ handler = OpenAIChatCompletionsHandler()
+ before = handler.get_streaming_scan_key([self._chunk("hel"), self._chunk("lo")])
+ after = handler.get_streaming_scan_key([self._chunk("hel"), self._chunk("lo"), self._chunk(None)])
+ assert after == before
+
+ def test_finish_chunk_without_tool_calls_scans_the_same_payload(self):
+ handler = OpenAIChatCompletionsHandler()
+ open_key = handler.get_streaming_scan_key([self._chunk("hi")])
+ ended_key = handler.get_streaming_scan_key([self._chunk("hi"), self._chunk(None, finish_reason="stop")])
+ assert open_key.stream_ended is False
+ assert ended_key.stream_ended is True
+ assert ended_key == open_key
+
+ def test_tool_calls_only_enter_the_key_once_the_stream_has_ended(self):
+ from litellm.types.utils import (
+ ChatCompletionDeltaToolCall,
+ Delta,
+ Function,
+ ModelResponseStream,
+ StreamingChoices,
+ )
+
+ handler = OpenAIChatCompletionsHandler()
+ tool_call = ChatCompletionDeltaToolCall(
+ id="call_1", index=0, type="function", function=Function(name="get_weather", arguments='{"city": "Paris"}')
+ )
+ tool_chunk = ModelResponseStream(
+ choices=[StreamingChoices(index=0, delta=Delta(content=None, tool_calls=[tool_call]), finish_reason=None)]
+ )
+ open_key = handler.get_streaming_scan_key([self._chunk("hi"), tool_chunk])
+ ended_key = handler.get_streaming_scan_key(
+ [self._chunk("hi"), tool_chunk, self._chunk(None, finish_reason="stop")]
+ )
+ assert open_key == StreamingScanKey(texts=("hi",))
+ assert ended_key.texts == ("hi",)
+ assert len(ended_key.tool_calls) == 1 and "get_weather" in ended_key.tool_calls[0]
+ assert ended_key != open_key
+
+ def test_text_after_the_first_choice_finishes_still_changes_the_key(self):
+ handler = OpenAIChatCompletionsHandler()
+ first_done = [self._chunk("a", index=0), self._chunk("b", finish_reason="stop", index=0)]
+ key_at_first_finish = handler.get_streaming_scan_key(first_done)
+ key_after_more_text = handler.get_streaming_scan_key(first_done + [self._chunk("y", index=1)])
+ assert key_at_first_finish.stream_ended is True
+ assert key_after_more_text.stream_ended is True
+ assert key_after_more_text != key_at_first_finish
+
+ def test_non_stream_items_are_ignored(self):
+ handler = OpenAIChatCompletionsHandler()
+ key = handler.get_streaming_scan_key([self._chunk("hi"), b"data: [DONE]"])
+ assert key.texts == ("hi",)
diff --cc ui/litellm-dashboard/eslint-suppressions.json
index 93966c8d0ee,e2a08a40bcb..773854d29e6
--- a/ui/litellm-dashboard/eslint-suppressions.json
+++ b/ui/litellm-dashboard/eslint-suppressions.json
@@@ -2352,14 -2322,9 +2322,9 @@@
},
"src/components/view_logs/GuardrailViewer/GuardrailViewer.tsx": {
"no-nested-ternary": {
- "count": 4
+ "count": 3
}
},
- "src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx": {
- "no-nested-ternary": {
- "count": 3
- }
- },
"src/components/view_logs/LogDetailsDrawer/LogDetailsDrawer.tsx": {
"no-nested-ternary": {
"count": 2
diff --cc ui/litellm-dashboard/src/app/(dashboard)/guardrails-monitor/_components/GuardrailDetail.tsx
index 253477ffeac,81c39258f67..86b596d4bcd
--- a/ui/litellm-dashboard/src/app/(dashboard)/guardrails-monitor/_components/GuardrailDetail.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/guardrails-monitor/_components/GuardrailDetail.tsx
@@@ -59,7 -57,7 +57,7 @@@ export function GuardrailDetail({ guard
return list.map((l: Record<string, unknown>) => ({
id: l.id as string,
timestamp: l.timestamp as string,
-- action: l.action as "blocked" | "passed" | "flagged",
++ action: l.action as LogEntry["action"],
score: l.score as number | undefined,
model: l.model as string | undefined,
input_snippet: l.input_snippet as string | undefined,
diff --cc ui/litellm-dashboard/src/components/GuardrailsMonitor/LogViewer.test.tsx
index 00000000000,ab91e10c2fd..083b1e5f3e2
mode 000000,100644..100644
--- a/ui/litellm-dashboard/src/components/GuardrailsMonitor/LogViewer.test.tsx
+++ b/ui/litellm-dashboard/src/components/GuardrailsMonitor/LogViewer.test.tsx
@@@ -1,0 -1,97 +1,110 @@@
+ import userEvent from "@testing-library/user-event";
+ import React from "react";
+ import { beforeEach, describe, expect, it, vi } from "vitest";
+
-import { renderWithProviders, screen, testQueryClient, waitFor } from "../../../tests/test-utils";
++import { renderWithProviders, screen, testQueryClient, waitFor, within } from "../../../tests/test-utils";
+ import type { LogEntry as SpendLogEntry } from "@/components/view_logs/columns";
+ import { LogViewer } from "./LogViewer";
+
+ vi.mock("@/components/networking", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/components/networking")>();
+ return { ...actual, uiSpendLogsCall: vi.fn() };
+ });
+
+ vi.mock("@/components/view_logs/LogDetailsDrawer", () => ({
+ LogDetailsDrawer: function LogDetailsDrawerMock({
+ open,
+ logEntry,
+ }: {
+ open: boolean;
+ logEntry?: { request_id: string } | null;
+ }) {
+ return (
+ <div data-testid="log-details-drawer" data-log-id={logEntry?.request_id ?? ""}>
+ {open ? "open" : "closed"}
+ </div>
+ );
+ },
+ }));
+
+ import { uiSpendLogsCall } from "@/components/networking";
+
+ const spendLog = (overrides: Partial<SpendLogEntry>): SpendLogEntry => ({
+ request_id: "req-1",
+ api_key: "key-1",
+ team_id: "team-1",
+ model: "gpt-4o",
+ model_id: "model-1",
+ call_type: "acompletion",
+ spend: 0.01,
+ total_tokens: 10,
+ prompt_tokens: 5,
+ completion_tokens: 5,
+ startTime: "2026-09-02T09:50:13Z",
+ endTime: "2026-09-02T09:50:14Z",
+ cache_hit: "false",
+ messages: [],
+ response: {},
+ ...overrides,
+ });
+
+ const guardrailLog = {
+ id: "provider-victim",
+ timestamp: "2026-09-02 09:50:13",
+ action: "passed" as const,
+ input_snippet: "victim prompt",
+ };
+
+ describe("GuardrailsMonitor LogViewer drawer", () => {
+ beforeEach(() => {
+ vi.mocked(uiSpendLogsCall).mockReset();
+ testQueryClient.clear();
+ });
+
+ it("opens the row whose request_id is the clicked log id even when a newer row carries that id as its call id", async () => {
+ vi.mocked(uiSpendLogsCall).mockResolvedValue({
+ data: [
+ spendLog({ request_id: "provider-attacker", litellm_call_id: "provider-victim" }),
+ spendLog({ request_id: "provider-victim", litellm_call_id: "call-victim" }),
+ ],
+ total: 2,
+ });
+
+ renderWithProviders(<LogViewer logs={[guardrailLog]} accessToken="sk-test" />);
+ await userEvent.click(screen.getByText("victim prompt"));
+
+ await waitFor(() => {
+ expect(screen.getByTestId("log-details-drawer")).toHaveAttribute("data-log-id", "provider-victim");
+ });
+ expect(vi.mocked(uiSpendLogsCall)).toHaveBeenCalledWith(
+ expect.objectContaining({ params: { request_id: "provider-victim" } }),
+ );
+ });
+
+ it("falls back to the first returned row when none carries the clicked id as its request_id", async () => {
+ vi.mocked(uiSpendLogsCall).mockResolvedValue({
+ data: [spendLog({ request_id: "provider-other", litellm_call_id: "provider-victim" })],
+ total: 1,
+ });
+
+ renderWithProviders(<LogViewer logs={[guardrailLog]} accessToken="sk-test" />);
+ await userEvent.click(screen.getByText("victim prompt"));
+
+ await waitFor(() => {
+ expect(screen.getByTestId("log-details-drawer")).toHaveAttribute("data-log-id", "provider-other");
+ });
+ });
+ });
++
++describe("GuardrailsMonitor LogViewer not_run rows", () => {
++ it("renders a not_run log as a neutral Not run badge instead of a pass or failure", () => {
++ renderWithProviders(
++ <LogViewer logs={[{ ...guardrailLog, action: "not_run", input_snippet: "system prompt only" }]} />,
++ );
++
++ const row = screen.getByRole("button", { name: /system prompt only/ });
++ expect(within(row).getByText("Not run")).toHaveClass("text-muted-foreground");
++ expect(within(row).queryByText("Passed")).not.toBeInTheDocument();
++ expect(within(row).queryByText("Blocked")).not.toBeInTheDocument();
++ });
++});
diff --cc ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.test.tsx
index 0fb5504d231,aabac50a661..8cc0d186631
--- a/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.test.tsx
+++ b/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.test.tsx
@@@ -33,16 -33,22 +33,35 @@@ describe("GuardrailViewer", () =>
expect(screen.getByText("1235ms")).toBeInTheDocument();
});
- it("renders not_run entries as not run instead of failed", () => {
+ it("renders guardrail_flagged as FLAGGED (warning), not FAILED", () => {
+ const data = makeGuardrailInformation({
+ guardrail_name: "cc-flag",
+ guardrail_status: "guardrail_flagged",
+ guardrail_provider: "custom_code",
+ });
+ renderWithProviders(<GuardrailViewer data={data} />);
+
+ expect(screen.getByText(/0 Passed/)).toBeInTheDocument();
+ expect(screen.getByText(/1 Flagged/)).toBeInTheDocument();
+ const badges = screen.getAllByText("FLAGGED");
+ expect(badges.length).toBeGreaterThan(0);
+ expect(badges[0]).toHaveClass("text-warning");
+ expect(screen.queryByText("FAILED")).not.toBeInTheDocument();
+ });
+
++ it("renders not_run as NOT RUN (muted) and keeps it out of the evaluated and passed counts", () => {
+ const data = makeGuardrailInformation({ guardrail_status: "not_run", guardrail_mode: "pre_call" });
+ renderWithProviders(<GuardrailViewer data={data} />);
+
++ expect(screen.getByText(/0 guardrails evaluated/)).toBeInTheDocument();
++ expect(screen.getByText(/0 Passed/)).toHaveClass("text-muted-foreground");
+ expect(screen.getByText(/1 Not run/)).toBeInTheDocument();
- // one NOT RUN badge in the timeline, one in the evaluation card
- expect(screen.getAllByText("NOT RUN")).toHaveLength(2);
++ const badges = screen.getAllByText("NOT RUN");
++ expect(badges).toHaveLength(2);
++ expect(badges[0]).toHaveClass("text-muted-foreground");
+ expect(screen.queryByText("FAILED")).not.toBeInTheDocument();
+ });
+
it("calculates and displays masked entity totals", async () => {
const user = userEvent.setup();
const data = makeGuardrailInformation({
diff --cc ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.tsx
index 08f9002b050,271b8f6ce05..7fb4124262b
--- a/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.tsx
+++ b/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.tsx
@@@ -133,38 -133,27 +133,37 @@@ const getTotalMasked = (entry: Guardrai
);
};
- const isEntrySuccess = (entry: GuardrailInformation): boolean => {
- return (entry.guardrail_status ?? "").toLowerCase() === "success";
-type EntryOutcome = "passed" | "flagged" | "failed";
++type EntryOutcome = "passed" | "flagged" | "failed" | "not_run";
+
+ const getEntryOutcome = (entry: GuardrailInformation): EntryOutcome => {
+ const status = (entry.guardrail_status ?? "").toLowerCase();
+ if (status === "success") return "passed";
+ if (status === "guardrail_flagged") return "flagged";
++ if (status === "not_run") return "not_run";
+ return "failed";
};
- const isEntryNotRun = (entry: GuardrailInformation): boolean => {
- return (entry.guardrail_status ?? "").toLowerCase() === "not_run";
- };
-
- type EntryStatusLabel = "PASSED" | "NOT RUN" | "FAILED";
-
- const entryStatusLabel = (entry: GuardrailInformation): EntryStatusLabel => {
- if (isEntrySuccess(entry)) return "PASSED";
- if (isEntryNotRun(entry)) return "NOT RUN";
- return "FAILED";
- };
+ const isEntrySuccess = (entry: GuardrailInformation): boolean => getEntryOutcome(entry) === "passed";
- const StatusIcon = ({ status }: { status: EntryStatusLabel }) => {
- if (status === "PASSED") return <CheckCircleIcon />;
- if (status === "NOT RUN") return <GrayDotIcon />;
- return <FailCircleIcon />;
+ const OUTCOME_LABEL: Record<EntryOutcome, string> = {
+ passed: "PASSED",
+ flagged: "FLAGGED",
+ failed: "FAILED",
++ not_run: "NOT RUN",
};
- const timelineStatusClass = (status: EntryStatusLabel): string => {
- if (status === "PASSED") return "bg-success/15 text-success";
- if (status === "NOT RUN") return "bg-muted text-muted-foreground";
- return "bg-destructive/15 text-destructive";
+ const OUTCOME_BADGE_CLASS: Record<EntryOutcome, string> = {
+ passed: "bg-success/15 text-success border border-success/20",
+ flagged: "bg-warning/15 text-warning border border-warning/20",
+ failed: "bg-destructive/15 text-destructive border border-destructive/20",
++ not_run: "bg-muted text-muted-foreground border border-border",
+};
+
- const cardStatusClass = (status: EntryStatusLabel): string => {
- if (status === "PASSED") return "bg-success/15 text-success border border-success/20";
- if (status === "NOT RUN") return "bg-muted text-muted-foreground border border-border";
- return "bg-destructive/15 text-destructive border border-destructive/20";
++const getHeaderOutcome = (counts: { evaluated: number; passed: number; flagged: number }): EntryOutcome => {
++ if (counts.evaluated === 0) return "not_run";
++ if (counts.passed === counts.evaluated) return "passed";
++ if (counts.passed + counts.flagged === counts.evaluated) return "flagged";
++ return "failed";
};
const getRiskColor = (score: number): string => {
@@@ -232,6 -221,19 +231,20 @@@ const FailCircleIcon = ({ className }:
</svg>
);
+ const FlagCircleIcon = ({ className }: { className?: string }) => (
+ <svg width="22" height="22" viewBox="0 0 22 22" fill="none" className={className}>
+ <circle cx="11" cy="11" r="10" stroke="#D97706" strokeWidth="1.5" fill="#FFFBEB" />
+ <path d="M11 6.5v5M11 14.5v.5" stroke="#D97706" strokeWidth="1.5" strokeLinecap="round" />
+ </svg>
+ );
+
+ const OutcomeIcon = ({ outcome }: { outcome: EntryOutcome }) => {
+ if (outcome === "passed") return <CheckCircleIcon />;
+ if (outcome === "flagged") return <FlagCircleIcon />;
++ if (outcome === "not_run") return <GrayDotIcon />;
+ return <FailCircleIcon />;
+ };
+
const PlayCircleIcon = () => (
<svg width="22" height="22" viewBox="0 0 22 22" fill="none">
<circle cx="11" cy="11" r="10" stroke="#3B82F6" strokeWidth="1.5" fill="#EFF6FF" />
@@@ -694,8 -695,13 +706,11 @@@ const GuardrailViewer = ({ data, access
}, [data]);
const passedCount = guardrailEntries.filter(isEntrySuccess).length;
- const notRunCount = guardrailEntries.filter(isEntryNotRun).length;
- const allPassed = passedCount === guardrailEntries.length - notRunCount;
+ const flaggedCount = guardrailEntries.filter((e) => getEntryOutcome(e) === "flagged").length;
- const allPassed = passedCount === guardrailEntries.length;
- const headerOutcome: EntryOutcome = allPassed
- ? "passed"
- : passedCount + flaggedCount === guardrailEntries.length
- ? "flagged"
- : "failed";
++ const notRunCount = guardrailEntries.filter((e) => getEntryOutcome(e) === "not_run").length;
++ const evaluatedCount = guardrailEntries.length - notRunCount;
++ const allPassed = evaluatedCount > 0 && passedCount === evaluatedCount;
++ const headerOutcome = getHeaderOutcome({ evaluated: evaluatedCount, passed: passedCount, flagged: flaggedCount });
const totalOverheadMs = useMemo(() => {
return Math.round(guardrailEntries.reduce((sum, e) => sum + (e.duration ?? 0), 0) * 1000);
@@@ -727,7 -733,7 +742,7 @@@
<h3 className="text-lg font-semibold text-foreground">Guardrails &amp; Policy Compliance</h3>
<div className="flex items-center gap-2 mt-0.5">
<span className="text-sm text-muted-foreground">
-- {guardrailEntries.length} guardrail{guardrailEntries.length !== 1 ? "s" : ""} evaluated
++ {evaluatedCount} guardrail{evaluatedCount !== 1 ? "s" : ""} evaluated
</span>
<span className="text-muted-foreground">|</span>
<span
@@@ -750,11 -752,13 +761,20 @@@
) : null}
{passedCount} Passed
</span>
+ {flaggedCount > 0 && (
+ <span
+ className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold ${OUTCOME_BADGE_CLASS.flagged}`}
+ >
+ {flaggedCount} Flagged
+ </span>
+ )}
+ {notRunCount > 0 && (
- <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold bg-muted text-muted-foreground border border-border">
++ <span
++ className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold ${OUTCOME_BADGE_CLASS.not_run}`}
++ >
+ {notRunCount} Not run
+ </span>
+ )}
</div>
</div>
</div>
diff --cc ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.integration.test.tsx
index 961aad7dc9e,721525268b3..3637b6c55a3
--- a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.integration.test.tsx
+++ b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.integration.test.tsx
@@@ -491,28 -624,15 +624,34 @@@ describe("LogDetailContent", () =>
});
describe("GuardrailJumpLink", () => {
- it("does not render a not_run entry as a failure", () => {
- render(
- <GuardrailJumpLink
- guardrailEntries={[
- { guardrail_name: "pii-rail", guardrail_status: "success" },
- { guardrail_name: "system-only", guardrail_status: "not_run" },
- ]}
- />,
- );
- expect(screen.getByText(/2 guardrails/)).toHaveTextContent("✓");
- expect(screen.getByText(/2 guardrails/)).not.toHaveTextContent("✗");
+ it.each([
+ [["success", "success"], "text-success", "\u2713"],
+ [["success", "guardrail_flagged"], "text-warning", "\u26A0"],
+ [["guardrail_flagged", "guardrail_intervened"], "text-destructive", "\u2717"],
+ ])("styles %j as %s", (statuses, expectedClass, glyph) => {
+ render(<GuardrailJumpLink guardrailEntries={statuses.map((s) => ({ guardrail_status: s }))} />);
+
+ const pill = screen.getByText(/2 guardrails evaluated/);
+ expect(pill).toHaveClass(expectedClass);
+ expect(pill).toHaveTextContent(glyph);
});
+
- it("still renders a real failure as failed", () => {
- render(
- <GuardrailJumpLink
- guardrailEntries={[
- { guardrail_name: "pii-rail", guardrail_status: "guardrail_intervened" },
- { guardrail_name: "system-only", guardrail_status: "not_run" },
- ]}
- />,
- );
- expect(screen.getByText(/2 guardrails/)).toHaveTextContent("✗");
++ it.each([
++ [["success", "not_run"], "text-success", "\u2713"],
++ [["guardrail_intervened", "not_run"], "text-destructive", "\u2717"],
++ ])("ignores not_run when styling %j as %s", (statuses, expectedClass, glyph) => {
++ render(<GuardrailJumpLink guardrailEntries={statuses.map((s) => ({ guardrail_status: s }))} />);
++
++ const pill = screen.getByText(/1 guardrail evaluated, 1 not run/);
++ expect(pill).toHaveClass(expectedClass);
++ expect(pill).toHaveTextContent(glyph);
++ });
++
++ it("renders an all not_run request as neutral rather than passed", () => {
++ render(<GuardrailJumpLink guardrailEntries={[{ guardrail_status: "not_run" }]} />);
++
++ const pill = screen.getByText(/0 guardrails evaluated, 1 not run/);
++ expect(pill).toHaveClass("text-muted-foreground");
++ expect(pill).not.toHaveTextContent("\u2713");
+ });
});
diff --cc ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx
index 105ae4add45,b5a3412a96f..30cd96935f7
--- a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx
+++ b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx
@@@ -635,13 -696,24 +696,29 @@@ function RequestResponseSection(
);
}
+ const GUARDRAIL_JUMP_LINK_STYLE = {
+ passed: { className: "border border-success/20 bg-success/10 text-success", glyph: "\u2713" },
+ flagged: { className: "border border-warning/20 bg-warning/10 text-warning", glyph: "\u26A0" },
+ failed: { className: "border border-destructive/20 bg-destructive/10 text-destructive", glyph: "\u2717" },
++ not_run: { className: "border border-border bg-muted text-muted-foreground", glyph: "\u2013" },
+ } as const;
+
+ const isPassedStatus = (status: unknown) => status === "pass" || status === "passed" || status === "success";
+ const isFlaggedStatus = (status: unknown) => status === "flagged" || status === "guardrail_flagged";
++const isNotRunStatus = (status: unknown) => status === "not_run";
+
-const guardrailJumpLinkOutcome = (statuses: unknown[]): keyof typeof GUARDRAIL_JUMP_LINK_STYLE => {
- if (statuses.every(isPassedStatus)) return "passed";
- if (statuses.every((s) => isPassedStatus(s) || isFlaggedStatus(s))) return "flagged";
++const guardrailJumpLinkOutcome = (evaluated: unknown[]): keyof typeof GUARDRAIL_JUMP_LINK_STYLE => {
++ if (evaluated.length === 0) return "not_run";
++ if (evaluated.every(isPassedStatus)) return "passed";
++ if (evaluated.every((s) => isPassedStatus(s) || isFlaggedStatus(s))) return "flagged";
+ return "failed";
+ };
+
export function GuardrailJumpLink({ guardrailEntries }: { guardrailEntries: any[] }) {
- // a not_run entry never evaluated the request, so it neither passes nor fails the banner
- const evaluated = guardrailEntries.filter((e) => (e?.guardrail_status || e?.status) !== "not_run");
- const allPassed = evaluated.every((e) => {
- const status = e?.guardrail_status || e?.status;
- return status === "pass" || status === "passed" || status === "success";
- });
- const outcome = guardrailJumpLinkOutcome(guardrailEntries.map((e) => e?.guardrail_status || e?.status));
- const { className, glyph } = GUARDRAIL_JUMP_LINK_STYLE[outcome];
++ const statuses = guardrailEntries.map((e) => e?.guardrail_status || e?.status);
++ const evaluated = statuses.filter((s) => !isNotRunStatus(s));
++ const notRunCount = statuses.length - evaluated.length;
++ const { className, glyph } = GUARDRAIL_JUMP_LINK_STYLE[guardrailJumpLinkOutcome(evaluated)];
const handleClick = () => {
const el = document.getElementById("guardrail-section");
@@@ -668,8 -736,8 +741,9 @@@
fontWeight: 500,
}}
>
- {allPassed ? "\u2713" : "\u2717"} {guardrailEntries.length} guardrail{guardrailEntries.length !== 1 ? "s" : ""}{" "}
- evaluated
- {glyph} {guardrailEntries.length} guardrail
- {guardrailEntries.length !== 1 ? "s" : ""} evaluated
++ {glyph} {evaluated.length} guardrail
++ {evaluated.length !== 1 ? "s" : ""} evaluated
++ {notRunCount > 0 ? `, ${notRunCount} not run` : ""}
<span style={{ fontSize: 11, opacity: 0.7 }}>{"\u2193"}</span>
</div>
</div>