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
fix(agents): show an agent's attached virtual key in the UI (#29619)
ryan-crabbe-berriac56320f260a
diff --git a/litellm/proxy/agent_endpoints/endpoints.py b/litellm/proxy/agent_endpoints/endpoints.pyindex ebbc26e6a9a..450c6414270 100644--- a/litellm/proxy/agent_endpoints/endpoints.py+++ b/litellm/proxy/agent_endpoints/endpoints.py@@ -26,6 +26,7 @@ from litellm.proxy.common_utils.rbac_utils import check_feature_access_for_userfrom litellm.proxy.management_endpoints.common_daily_activity import get_daily_activityfrom litellm.types.agents import (AgentConfig,+ AgentKeySummary,AgentMakePublicResponse,AgentResponse,MakeAgentsPublicRequest,@@ -68,18 +69,43 @@ def _build_merged_agent_card(router = APIRouter()+async def _attach_keys_to_agents(agents: list[AgentResponse], prisma_client) -> None:+ """Attach each agent's virtual keys, derived from the key table's agent_id+ foreign key. Mirrors how spend is joined into the agent response so the UI+ never has to cross-reference a full key dump client-side. Only non-secret+ fields are exposed (alias, masked key_name, hashed token)."""+ agent_ids = [agent.agent_id for agent in agents]+ if not agent_ids:+ return+ key_rows = await prisma_client.db.litellm_verificationtoken.find_many(+ where={"agent_id": {"in": agent_ids}},+ )+ keys_by_agent: dict[str, list[AgentKeySummary]] = {}+ for row in key_rows:+ keys_by_agent.setdefault(row.agent_id, []).append(+ AgentKeySummary(+ token=row.token,+ key_alias=row.key_alias,+ key_name=row.key_name,+ )+ )+ for agent in agents:+ agent.keys = keys_by_agent.get(agent.agent_id)++def _redact_sensitive_agent_fields(- agents: List[AgentResponse],-) -> List[AgentResponse]:+ agents: list[AgentResponse],+) -> list[AgentResponse]:"""Return copies of the given agents with sensitive configuration fieldsredacted. The original objects are not modified."""- redacted: List[AgentResponse] = []+ redacted: list[AgentResponse] = []for agent in agents:copy = agent.model_copy(deep=True)copy.static_headers = Nonecopy.extra_headers = None+ copy.keys = Noneif copy.litellm_params:copy.litellm_params = _get_masked_values(copy.litellm_params,@@ -218,6 +244,7 @@ async def get_agents(for agent in returned_agents:if agent.agent_id in spend_map:agent.spend = spend_map[agent.agent_id]+ await _attach_keys_to_agents(returned_agents, prisma_client)# add is_public field to each agent - we do it this way, to allow setting config agents as publicfor agent in returned_agents:@@ -462,6 +489,8 @@ async def get_agent_by_id(if agent is None:raise HTTPException(status_code=404, detail=f"Agent with ID {agent_id} not found")+ await _attach_keys_to_agents([agent], prisma_client)+# Redact sensitive fields for non-admin usersis_admin = (user_api_key_dict.user_role == LitellmUserRoles.PROXY_ADMINdiff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.pyindex eed7d869a5d..961087ef445 100644--- a/litellm/proxy/management_endpoints/key_management_endpoints.py+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py@@ -4897,6 +4897,7 @@ async def list_keys(status: Optional[str] = Query(None, description="Filter by status (e.g. 'deleted')"),project_id: Optional[str] = Query(None, description="Filter keys by project ID"),access_group_id: Optional[str] = Query(None, description="Filter keys by access group ID"),+ agent_id: Optional[str] = Query(None, description="Filter keys by agent ID"),substring_matching: bool = Query(False,description="If true (proxy admins only), match user_id/key_alias as case-insensitive substrings instead of exact values. Defaults to false: /key/list matched these exactly before substring search was added, and an exact user_id/key_alias filter must never return another user's keys.",@@ -5014,6 +5015,7 @@ async def list_keys(status=status,project_id=project_id,access_group_id=access_group_id,+ agent_id=agent_id,use_substring_matching=use_substring_matching,)@@ -5234,6 +5236,7 @@ def _build_key_filter_conditions(include_created_by_keys: bool = False,project_id: Optional[str] = None,access_group_id: Optional[str] = None,+ agent_id: Optional[str] = None,use_substring_matching: bool = False,) -> Dict[str, Union[str, Dict[str, Any], List[Dict[str, Any]]]]:"""Build filter conditions for key listing.@@ -5340,6 +5343,8 @@ def _build_key_filter_conditions(where = {"AND": [where, {"project_id": project_id}]}if access_group_id:where = {"AND": [where, {"access_group_ids": {"hasSome": [access_group_id]}}]}+ if agent_id and isinstance(agent_id, str):+ where = {"AND": [where, {"agent_id": agent_id}]}verbose_proxy_logger.debug(f"Filter conditions: {where}")return where@@ -5367,6 +5372,7 @@ async def _list_key_helper(status: Optional[str] = None,project_id: Optional[str] = None,access_group_id: Optional[str] = None,+ agent_id: Optional[str] = None,use_substring_matching: bool = False,) -> KeyListResponseObject:"""@@ -5403,6 +5409,7 @@ async def _list_key_helper(include_created_by_keys=include_created_by_keys,project_id=project_id,access_group_id=access_group_id,+ agent_id=agent_id,use_substring_matching=use_substring_matching,)diff --git a/litellm/types/agents.py b/litellm/types/agents.pyindex c6347c17fd2..254ed5c6c7b 100644--- a/litellm/types/agents.py+++ b/litellm/types/agents.py@@ -205,6 +205,12 @@ class PatchAgentRequest(TypedDict, total=False):# Request/Response models for CRUD endpoints+class AgentKeySummary(BaseModel):+ token: str+ key_alias: Optional[str] = None+ key_name: Optional[str] = None++class AgentResponse(BaseModel):agent_id: stragent_name: str@@ -218,6 +224,7 @@ class AgentResponse(BaseModel):session_rpm_limit: Optional[int] = Nonestatic_headers: Optional[Dict[str, str]] = Noneextra_headers: Optional[List[str]] = None+ keys: Optional[List[AgentKeySummary]] = Nonecreated_at: Optional[datetime] = Noneupdated_at: Optional[datetime] = Nonecreated_by: Optional[str] = Nonediff --git a/tests/test_litellm/proxy/agent_endpoints/test_endpoints.py b/tests/test_litellm/proxy/agent_endpoints/test_endpoints.pyindex 68df365ff37..0cb03023e0f 100644--- a/tests/test_litellm/proxy/agent_endpoints/test_endpoints.py+++ b/tests/test_litellm/proxy/agent_endpoints/test_endpoints.py@@ -7,6 +7,7 @@ from fastapi.testclient import TestClientfrom litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuthfrom litellm.proxy.agent_endpoints import endpoints as agent_endpointsfrom litellm.proxy.agent_endpoints.endpoints import (+ _attach_keys_to_agents,_check_agent_management_permission,get_agent_daily_activity,router,@@ -275,6 +276,99 @@ async def test_get_agent_daily_activity_with_agent_names(monkeypatch):}+async def test_attach_keys_to_agents_groups_by_agent_and_omits_secret():+ """+ The agents response must carry each agent's attached virtual keys (derived+ from the key table's agent_id FK), grouped per agent, exposing only+ non-secret summary fields. Agents with no key get None so the UI renders+ "Needs Setup" rather than a stale badge.+ """++ class _Row:+ def __init__(self, token, agent_id, key_alias, key_name):+ self.token = token+ self.agent_id = agent_id+ self.key_alias = key_alias+ self.key_name = key_name+ self.user_id = "secret-owner" # extra field that must NOT leak++ agent_with_keys = _sample_agent_response(agent_id="agent-1")+ agent_without_keys = _sample_agent_response(agent_id="agent-2")++ mock_prisma = MagicMock()+ mock_prisma.db.litellm_verificationtoken.find_many = AsyncMock(+ return_value=[+ _Row("hash-aaa", "agent-1", "primary", "sk-...aaa"),+ _Row("hash-bbb", "agent-1", "backup", "sk-...bbb"),+ ]+ )++ await _attach_keys_to_agents([agent_with_keys, agent_without_keys], mock_prisma)++ # Query is scoped to the agents being returned, not the whole key table.+ where = mock_prisma.db.litellm_verificationtoken.find_many.call_args.kwargs["where"]+ assert where == {"agent_id": {"in": ["agent-1", "agent-2"]}}++ # agent-1 gets both of its keys; agent-2 gets None.+ assert agent_without_keys.keys is None+ assert agent_with_keys.keys is not None+ assert {k.token for k in agent_with_keys.keys} == {"hash-aaa", "hash-bbb"}+ assert {k.key_alias for k in agent_with_keys.keys} == {"primary", "backup"}++ # Only summary fields are exposed; the row's user_id must not be carried.+ summary = agent_with_keys.keys[0]+ assert set(summary.model_dump().keys()) == {"token", "key_alias", "key_name"}+++class TestAgentByIdKeyRedaction:+ """GET /v1/agents/{id} surfaces attached keys to admins but never to+ non-admins, even when the agent has keys attached."""++ @pytest.fixture(autouse=True)+ def _setup(self, monkeypatch):+ self.mock_registry = MagicMock()+ self.mock_registry.get_agent_by_id = MagicMock(+ return_value=_sample_agent_response()+ )+ monkeypatch.setattr(agent_endpoints, "AGENT_REGISTRY", self.mock_registry)++ def _get_as(self, role: LitellmUserRoles):+ key_row = MagicMock()+ key_row.token = "hash-aaa"+ key_row.agent_id = "agent-123"+ key_row.key_alias = "primary"+ key_row.key_name = "sk-...aaa"++ test_client = _make_app_with_role(role)+ with patch("litellm.proxy.proxy_server.prisma_client") as mock_prisma:+ mock_prisma.db.litellm_agentstable.find_unique = AsyncMock(+ return_value=None+ )+ mock_prisma.db.litellm_verificationtoken.find_many = AsyncMock(+ return_value=[key_row]+ )+ return test_client.get(+ "/v1/agents/agent-123", headers={"Authorization": "Bearer k"}+ )++ def test_admin_sees_attached_keys(self):+ resp = self._get_as(LitellmUserRoles.PROXY_ADMIN)+ assert resp.status_code == 200+ keys = resp.json()["keys"]+ assert keys is not None+ assert keys[0] == {+ "token": "hash-aaa",+ "key_alias": "primary",+ "key_name": "sk-...aaa",+ }++ def test_non_admin_never_sees_keys(self):+ resp = self._get_as(LitellmUserRoles.INTERNAL_USER)+ assert resp.status_code == 200+ assert resp.json()["keys"] is None++# ---------- RBAC enforcement tests ----------@@ -302,6 +396,9 @@ class TestAgentRBACInternalUser:mock_prisma.db.litellm_agentstable.find_unique = AsyncMock(return_value=None)+ mock_prisma.db.litellm_verificationtoken.find_many = AsyncMock(+ return_value=[]+ )resp = self.internal_client.get("/v1/agents/agent-123", headers={"Authorization": "Bearer k"})diff --git a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.pyindex a92eaa3a5f6..02c9a249ae8 100644--- a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py+++ b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py@@ -5756,6 +5756,51 @@ def test_build_key_filter_conditions_member_only_team_restricts_to_service_accou), f"member-only team must be restricted to user_id=NULL keys, got: {serialized}"+def test_build_key_filter_conditions_agent_id_narrows_visibility():+ """+ Filtering /key/list by agent_id must AND the agent_id on top of the+ caller's visibility conditions (it can only narrow results, never widen+ them). Without this the UI cannot list an agent's keys server-side and+ falls back to fetching every key and filtering client-side.+ """+ from litellm.proxy.management_endpoints.key_management_endpoints import (+ _build_key_filter_conditions,+ )++ agent_id = "agent-123"+ where = _build_key_filter_conditions(+ user_id="some-user",+ team_id=None,+ organization_id=None,+ key_alias=None,+ key_hash=None,+ exclude_team_id=None,+ admin_team_ids=["team-a"],+ member_team_ids=None,+ include_created_by_keys=False,+ agent_id=agent_id,+ )++ # agent_id must be applied as a top-level AND so it intersects (narrows) the+ # visibility OR-conditions rather than being added as another OR branch.+ assert where.get("AND"), f"expected top-level AND, got: {where}"+ assert {"agent_id": agent_id} in where["AND"], f"agent_id not ANDed: {where}"++ # Omitting agent_id must not introduce any agent_id constraint.+ where_without = _build_key_filter_conditions(+ user_id="some-user",+ team_id=None,+ organization_id=None,+ key_alias=None,+ key_hash=None,+ exclude_team_id=None,+ admin_team_ids=["team-a"],+ member_team_ids=None,+ include_created_by_keys=False,+ )+ assert "agent_id" not in json.dumps(where_without)++@pytest.mark.asyncioasync def test_generate_key_negative_max_budget():"""diff --git a/ui/litellm-dashboard/src/app/(dashboard)/hooks/keys/useKeys.test.ts b/ui/litellm-dashboard/src/app/(dashboard)/hooks/keys/useKeys.test.tsindex 4f534b4117e..164e393eb9b 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/hooks/keys/useKeys.test.ts+++ b/ui/litellm-dashboard/src/app/(dashboard)/hooks/keys/useKeys.test.ts@@ -459,6 +459,38 @@ describe("useKeys", () => {const callUrl = mockFetch.mock.calls[0][0];expect(callUrl).not.toContain("project_id");});++ it("should pass agentID filter to the API", async () => {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ json: async () => mockKeysResponse,+ });++ const { result } = renderHook(() => useKeys(1, 10, { agentID: "agent-123" }), { wrapper });++ await waitFor(() => {+ expect(result.current.isLoading).toBe(false);+ });++ const callUrl = mockFetch.mock.calls[0][0];+ expect(callUrl).toContain("agent_id=agent-123");+ });++ it("should not include agent_id param when agentID is null", async () => {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ json: async () => mockKeysResponse,+ });++ const { result } = renderHook(() => useKeys(1, 10, { agentID: null }), { wrapper });++ await waitFor(() => {+ expect(result.current.isLoading).toBe(false);+ });++ const callUrl = mockFetch.mock.calls[0][0];+ expect(callUrl).not.toContain("agent_id");+ });});describe("useDeletedKeys", () => {diff --git a/ui/litellm-dashboard/src/app/(dashboard)/hooks/keys/useKeys.ts b/ui/litellm-dashboard/src/app/(dashboard)/hooks/keys/useKeys.tsindex 8c4b999d012..701a9d30001 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/hooks/keys/useKeys.ts+++ b/ui/litellm-dashboard/src/app/(dashboard)/hooks/keys/useKeys.ts@@ -29,6 +29,7 @@ export interface KeyListCallOptions {organizationID?: string | null;teamID?: string | null;projectID?: string | null;+ agentID?: string | null;selectedKeyAlias?: string | null;userID?: string | null;keyHash?: string | null;@@ -49,6 +50,7 @@ const keyListCall = async (accessToken: string, page: number, pageSize: number,Object.entries({team_id: options.teamID,project_id: options.projectID,+ agent_id: options.agentID,organization_id: options.organizationID,key_alias: options.selectedKeyAlias,key_hash: options.keyHash,diff --git a/ui/litellm-dashboard/src/components/agents.test.tsx b/ui/litellm-dashboard/src/components/agents.test.tsxindex 21dc2cbf9fe..848b8d5e891 100644--- a/ui/litellm-dashboard/src/components/agents.test.tsx+++ b/ui/litellm-dashboard/src/components/agents.test.tsx@@ -1,5 +1,5 @@import React from "react";-import { render, screen, waitFor, act, fireEvent } from "@testing-library/react";+import { render, screen, waitFor, act, fireEvent, within } from "@testing-library/react";import { describe, it, expect, vi, beforeEach } from "vitest";import AgentsPanel from "./agents";import * as networking from "./networking";@@ -7,7 +7,6 @@ import * as networking from "./networking";vi.mock("./networking", () => ({getAgentsList: vi.fn().mockResolvedValue({ agents: [] }),deleteAgentCall: vi.fn(),- keyListCall: vi.fn().mockResolvedValue({ keys: [] }),}));vi.mock("./agents/add_agent_form", () => ({@@ -81,6 +80,34 @@ describe("AgentsPanel", () => {});});+ it("should show Active when an agent has keys and Needs Setup when it has none", async () => {+ vi.mocked(networking.getAgentsList).mockResolvedValue({+ agents: [+ {+ agent_id: "agent-with-key",+ agent_name: "Keyed Agent",+ litellm_params: { model: "gpt-4" },+ spend: 0,+ keys: [{ token: "hash-aaa", key_alias: "primary", key_name: "sk-...aaa" }],+ },+ {+ agent_id: "agent-no-key",+ agent_name: "Keyless Agent",+ litellm_params: { model: "gpt-4" },+ spend: 0,+ keys: [],+ },+ ],+ });++ render(<AgentsPanel accessToken="test-token" userRole="Admin" />);++ const keyedRow = (await screen.findByText("Keyed Agent")).closest("tr")!;+ const keylessRow = screen.getByText("Keyless Agent").closest("tr")!;+ expect(within(keyedRow).getByText("Active")).toBeInTheDocument();+ expect(within(keylessRow).getByText("Needs Setup")).toBeInTheDocument();+ });+it("should call getAgentsList with health_check=true when toggle is enabled", async () => {render(<AgentsPanel accessToken="test-token" userRole="Admin" />);await waitFor(() => {diff --git a/ui/litellm-dashboard/src/components/agents.tsx b/ui/litellm-dashboard/src/components/agents.tsxindex bcba328c461..0d8916942da 100644--- a/ui/litellm-dashboard/src/components/agents.tsx+++ b/ui/litellm-dashboard/src/components/agents.tsx@@ -13,12 +13,12 @@ import {} from "@tremor/react";import { Modal, Alert, Tooltip, Skeleton, Switch } from "antd";import { CheckCircleOutlined } from "@ant-design/icons";-import { getAgentsList, deleteAgentCall, keyListCall } from "./networking";+import { getAgentsList, deleteAgentCall } from "./networking";import AddAgentForm from "./agents/add_agent_form";import { isAdminRole } from "@/utils/roles";import AgentInfoView from "./agents/agent_info";import NotificationsManager from "./molecules/notifications_manager";-import { Agent, AgentKeyInfo } from "./agents/types";+import { Agent } from "./agents/types";import { Team } from "./key_team_helpers/key_list";import { formatNumberWithCommas } from "@/utils/dataUtils";import TableIconActionButton from "./common_components/IconActionButton/TableIconActionButtons/TableIconActionButton";@@ -35,7 +35,6 @@ interface AgentsResponse {const AgentsPanel: React.FC<AgentsPanelProps> = ({ accessToken, userRole, teams }) => {const [agentsList, setAgentsList] = useState<Agent[]>([]);- const [keyInfoMap, setKeyInfoMap] = useState<Record<string, AgentKeyInfo>>({});const [isAddModalVisible, setIsAddModalVisible] = useState(false);const [isLoading, setIsLoading] = useState(false);const [isDeleting, setIsDeleting] = useState(false);@@ -61,41 +60,10 @@ const AgentsPanel: React.FC<AgentsPanelProps> = ({ accessToken, userRole, teams}};- const fetchKeysForAgents = async () => {- if (!accessToken) return;- try {- const { keys = [] } = await keyListCall(accessToken, null, null, null, null, null, 1, 500);- const map: Record<string, AgentKeyInfo> = {};- for (const key of keys) {- const agentId = (key as { agent_id?: string }).agent_id;- if (agentId && !map[agentId]) {- map[agentId] = {- has_key: true,- key_alias: (key as { key_alias?: string }).key_alias,- token_prefix: (key as { token?: string }).token- ? `${(key as { token: string }).token.slice(0, 8)}…`- : undefined,- };- }- }- setKeyInfoMap(map);- } catch (error) {- console.error("Error fetching keys for agents:", error);- }- };-useEffect(() => {fetchAgents();}, [accessToken]);- useEffect(() => {- if (accessToken && agentsList.length > 0) {- fetchKeysForAgents();- } else if (agentsList.length === 0) {- setKeyInfoMap({});- }- }, [accessToken, agentsList.length]);-const handleHealthCheckToggle = (checked: boolean) => {setHealthCheckEnabled(checked);fetchAgents(checked);@@ -248,7 +216,7 @@ const AgentsPanel: React.FC<AgentsPanelProps> = ({ accessToken, userRole, teams<Text>{agent.created_at ? new Date(agent.created_at).toLocaleDateString() : "N/A"}</Text></TableCell><TableCell>- {keyInfoMap[agent.agent_id]?.has_key ? (+ {(agent.keys?.length ?? 0) > 0 ? (<Badge color="green">Active</Badge>) : (<Badge color="yellow">Needs Setup</Badge>diff --git a/ui/litellm-dashboard/src/components/agents/agent_info.tsx b/ui/litellm-dashboard/src/components/agents/agent_info.tsxindex d4420931a20..46ffa9b5ccf 100644--- a/ui/litellm-dashboard/src/components/agents/agent_info.tsx+++ b/ui/litellm-dashboard/src/components/agents/agent_info.tsx@@ -5,6 +5,10 @@ import MessageManager from "@/components/molecules/message_manager";import { ArrowLeftIcon } from "@heroicons/react/outline";import { getAgentInfo, patchAgentCall, getAgentCreateMetadata, AgentCreateInfo } from "../networking";import { Agent } from "./types";+import { KeyResponse } from "../key_team_helpers/key_list";+import { useKeys } from "@/app/(dashboard)/hooks/keys/useKeys";+import KeyInfoView from "../templates/key_info_view";+import AgentVirtualKeys from "./agent_virtual_keys";import AgentFormFields from "./agent_form_fields";import DynamicAgentFormFields, { buildDynamicAgentData } from "./dynamic_agent_form_fields";import { buildAgentDataFromForm, parseAgentForForm } from "./agent_config";@@ -22,6 +26,9 @@ interface AgentInfoViewProps {const AgentInfoView: React.FC<AgentInfoViewProps> = ({ agentId, onClose, accessToken, isAdmin }) => {const [agent, setAgent] = useState<Agent | null>(null);+ const [selectedKey, setSelectedKey] = useState<KeyResponse | null>(null);+ const { data: keysData, isLoading: keysLoading, refetch: refetchAgentKeys } = useKeys(1, 100, { agentID: agentId });+ const agentKeys = keysData?.keys ?? [];const [isLoading, setIsLoading] = useState(true);const [isEditing, setIsEditing] = useState(false);const [isSaving, setIsSaving] = useState(false);@@ -192,6 +199,22 @@ const AgentInfoView: React.FC<AgentInfoViewProps> = ({ agentId, onClose, accessTreturn date.toLocaleString();};+ if (selectedKey) {+ return (+ <KeyInfoView+ keyId={selectedKey.token}+ keyData={selectedKey}+ onClose={() => setSelectedKey(null)}+ onDelete={() => {+ setSelectedKey(null);+ refetchAgentKeys();+ }}+ teams={null}+ backButtonText="Back to Agent"+ />+ );+ }+return (<div className="p-4"><div>@@ -257,6 +280,8 @@ const AgentInfoView: React.FC<AgentInfoViewProps> = ({ agentId, onClose, accessT<Descriptions.Item label="Updated At">{formatDate(agent.updated_at)}</Descriptions.Item></Descriptions>+ <AgentVirtualKeys keys={agentKeys} isLoading={keysLoading} onKeyClick={setSelectedKey} />+{agent.object_permission &&(agent.object_permission.mcp_servers?.length ||agent.object_permission.mcp_access_groups?.length ||diff --git a/ui/litellm-dashboard/src/components/agents/agent_virtual_keys.test.tsx b/ui/litellm-dashboard/src/components/agents/agent_virtual_keys.test.tsxnew file mode 100644index 00000000000..9a58ad557a2--- /dev/null+++ b/ui/litellm-dashboard/src/components/agents/agent_virtual_keys.test.tsx@@ -0,0 +1,51 @@+import React from "react";+import { describe, it, expect, vi } from "vitest";+import { screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { renderWithProviders } from "../../../tests/test-utils";+import AgentVirtualKeys from "./agent_virtual_keys";+import type { KeyResponse } from "../key_team_helpers/key_list";++const makeKey = (overrides: Partial<KeyResponse>): KeyResponse =>+ ({+ token: "hash-abc123def456",+ key_alias: "agent-primary",+ key_name: "sk-...abcd",+ ...overrides,+ }) as unknown as KeyResponse;++describe("AgentVirtualKeys", () => {+ it("shows the empty state when the agent has no keys", () => {+ renderWithProviders(<AgentVirtualKeys keys={[]} isLoading={false} onKeyClick={vi.fn()} />);+ expect(screen.getByText("No virtual key assigned to this agent.")).toBeInTheDocument();+ });++ it("shows a loading state while keys are fetching", () => {+ renderWithProviders(<AgentVirtualKeys keys={[]} isLoading={true} onKeyClick={vi.fn()} />);+ expect(screen.getByText("Loading keys...")).toBeInTheDocument();+ });++ it("renders each attached key's alias and masked name", () => {+ const keys = [+ makeKey({ token: "hash-aaa", key_alias: "primary", key_name: "sk-...aaa" }),+ makeKey({ token: "hash-bbb", key_alias: "backup", key_name: "sk-...bbb" }),+ ];+ renderWithProviders(<AgentVirtualKeys keys={keys} isLoading={false} onKeyClick={vi.fn()} />);++ expect(screen.getByText("primary")).toBeInTheDocument();+ expect(screen.getByText("backup")).toBeInTheDocument();+ expect(screen.getByText("sk-...aaa")).toBeInTheDocument();+ expect(screen.getByText("sk-...bbb")).toBeInTheDocument();+ });++ it("fires onKeyClick with the full key when its Key ID is clicked", async () => {+ const onKeyClick = vi.fn();+ const key = makeKey({ token: "hash-clickme", key_alias: "clickable" });+ renderWithProviders(<AgentVirtualKeys keys={[key]} isLoading={false} onKeyClick={onKeyClick} />);++ await userEvent.click(screen.getByRole("button"));++ expect(onKeyClick).toHaveBeenCalledTimes(1);+ expect(onKeyClick).toHaveBeenCalledWith(key);+ });+});diff --git a/ui/litellm-dashboard/src/components/agents/agent_virtual_keys.tsx b/ui/litellm-dashboard/src/components/agents/agent_virtual_keys.tsxnew file mode 100644index 00000000000..afc6344c2ef--- /dev/null+++ b/ui/litellm-dashboard/src/components/agents/agent_virtual_keys.tsx@@ -0,0 +1,47 @@+import React from "react";+import { Button, Tooltip, Typography } from "antd";+import { KeyOutlined } from "@ant-design/icons";+import { KeyResponse } from "../key_team_helpers/key_list";++const { Title, Text } = Typography;++interface AgentVirtualKeysProps {+ keys: KeyResponse[];+ isLoading: boolean;+ onKeyClick: (key: KeyResponse) => void;+}++const AgentVirtualKeys: React.FC<AgentVirtualKeysProps> = ({ keys, isLoading, onKeyClick }) => {+ return (+ <div style={{ marginTop: 24 }}>+ <Title level={4}>Virtual Keys</Title>+ {isLoading ? (+ <Text className="mt-2 block">Loading keys...</Text>+ ) : keys.length === 0 ? (+ <Text className="mt-2 block text-gray-500">No virtual key assigned to this agent.</Text>+ ) : (+ <div className="mt-3 flex flex-col gap-2">+ {keys.map((key) => (+ <div key={key.token} className="flex items-center gap-3 border border-gray-100 rounded px-3 py-2">+ <KeyOutlined className="text-gray-400" />+ <span className="font-medium">{key.key_alias || "Unnamed key"}</span>+ {key.key_name && <span className="font-mono text-xs text-gray-500">{key.key_name}</span>}+ <Tooltip title={key.token}>+ <Button+ size="small"+ type="link"+ className="font-mono text-blue-500 ml-auto"+ onClick={() => onKeyClick(key)}+ >+ {key.token?.slice(0, 12)}...+ </Button>+ </Tooltip>+ </div>+ ))}+ </div>+ )}+ </div>+ );+};++export default AgentVirtualKeys;diff --git a/ui/litellm-dashboard/src/components/agents/types.ts b/ui/litellm-dashboard/src/components/agents/types.tsindex 3e27177c815..c29c566a5fe 100644--- a/ui/litellm-dashboard/src/components/agents/types.ts+++ b/ui/litellm-dashboard/src/components/agents/types.ts@@ -1,7 +1,7 @@-export interface AgentKeyInfo {- key_alias?: string;- token_prefix?: string;- has_key: boolean;+export interface AgentAttachedKey {+ token: string;+ key_alias?: string | null;+ key_name?: string | null;}export interface AgentObjectPermission {@@ -23,6 +23,7 @@ export interface Agent {[key: string]: any;};object_permission?: AgentObjectPermission;+ keys?: AgentAttachedKey[] | null;spend?: number;tpm_limit?: number | null;rpm_limit?: number | null;diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.tsindex 43be9ad6e39..b0a3e0e3fe1 100644--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@ -41787,6 +41787,8 @@ export interface operations {project_id?: string | null;/** @description Filter keys by access group ID */access_group_id?: string | null;+ /** @description Filter keys by agent ID */+ agent_id?: string | null;/** @description If true (proxy admins only), match user_id/key_alias as case-insensitive substrings instead of exact values. Defaults to false: /key/list matched these exactly before substring search was added, and an exact user_id/key_alias filter must never return another user's keys. */substring_matching?: boolean;};@@ -43768,13 +43770,13 @@ export interface operations {/*** @description Unified rate-limit error.*- * Every rate-limit condition surfaced by litellm — whether it originated from- * an upstream LLM provider, a vendor batch endpoint, or one of litellm's own- * proxy-side limiters (parallel-requests, dynamic-rate, batch-rate, budget,- * max-iterations, etc.) — is raised as an instance of this class.+ * Every rate-limit condition surfaced by litellm — whether it originated from+ * an upstream LLM provider, a vendor batch endpoint, or one of litellm's own+ * proxy-side limiters (parallel-requests, dynamic-rate, batch-rate, budget,+ * max-iterations, etc.) — is raised as an instance of this class.*- * The :attr:`category` attribute lets callers distinguish the source. See- * :class:`RateLimitErrorCategory` for the available values.+ * The :attr:`category` attribute lets callers distinguish the source. See+ * :class:`RateLimitErrorCategory` for the available values.*/429: {headers: {