Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { fireEvent, render, renderHook, screen, waitFor } from "@testing-library/react";
import { Form } from "antd";
import React from "react";
import { beforeAll, describe, expect, it, vi } from "vitest";
import { Providers } from "../provider_info_helpers";
import ProviderSpecificFields from "./provider_specific_fields";
import ProviderSpecificFields, { useProviderAuthFieldKeys } from "./provider_specific_fields";

vi.mock("../networking", async () => {
const actual = await vi.importActual("../networking");
Expand Down Expand Up @@ -183,6 +184,50 @@ describe("ProviderSpecificFields", () => {
});
});

it("excludeKeys removes parent-owned fields from the rendered set", async () => {
const queryClient = createQueryClient();
render(
<QueryClientProvider client={queryClient}>
<Form>
<ProviderSpecificFields selectedProvider={Providers.OpenAI} excludeKeys={["api_base", "organization"]} />
</Form>
</QueryClientProvider>,
);

await waitFor(() => {
// api_key still rendered, the parent-owned fields are gone
expect(screen.getByLabelText("OpenAI API Key")).toBeInTheDocument();
});
expect(screen.queryByPlaceholderText("https://api.openai.com/v1")).not.toBeInTheDocument();
expect(screen.queryByPlaceholderText("[OPTIONAL] my-unique-org")).not.toBeInTheDocument();
});

it("useProviderAuthFieldKeys returns the full key set when nothing is excluded", async () => {
const queryClient = createQueryClient();
const wrapper = ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
const { result } = renderHook(() => useProviderAuthFieldKeys(Providers.OpenAI), { wrapper });

await waitFor(() => {
expect(result.current).toEqual(["api_base", "organization", "api_key"]);
});
});

it("useProviderAuthFieldKeys excludes parent-owned keys", async () => {
const queryClient = createQueryClient();
const wrapper = ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
const { result } = renderHook(() => useProviderAuthFieldKeys(Providers.OpenAI, ["api_base", "organization"]), {
wrapper,
});

await waitFor(() => {
expect(result.current).toEqual(["api_key"]);
});
});

it("should render the provider specific fields for Azure", async () => {
const queryClient = createQueryClient();
render(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,22 @@
import { Text, TextInput } from "@tremor/react";
import { Button as Button2, Col, Form, Input, Row, Select, Typography, Upload, UploadProps } from "antd";
import React from "react";
import { CredentialItem, ProviderCredentialFieldMetadata } from "../networking";
import { CredentialItem, ProviderCreateInfo, ProviderCredentialFieldMetadata } from "../networking";
import { provider_map, Providers } from "../provider_info_helpers";
const { Link } = Typography;

interface ProviderSpecificFieldsProps {
selectedProvider: Providers;
uploadProps?: UploadProps;
// Field keys to NOT render — used when a parent form already owns these
// inputs (e.g. the model edit form has a dedicated "API Base" field) so we
// don't create a duplicate Form.Item bound to the same name.
excludeKeys?: string[];
// Drop the "required" validation rule from every rendered field. Used in the
// model edit context, where auth fields render blank ("leave blank to keep")
// — a required rule would block onFinish and prevent saving any unrelated
// edit unless the user re-enters the secret.
disableRequired?: boolean;
}

interface ProviderCredentialField {
Expand Down Expand Up @@ -64,12 +73,44 @@
};
};

// Resolve the credential UI fields for a provider from fetched metadata.
// Matches the component's resolution order (display-name enum or raw slug).
const resolveProviderFields = (
providerMetadata: ProviderCreateInfo[] | undefined,
selectedProvider: Providers,
): ProviderCredentialField[] => {
if (!providerMetadata) return [];
const selectedProviderEnum = Providers[selectedProvider as keyof typeof Providers] as Providers;
const providerInfo = providerMetadata.find(
(p) =>
p.provider_display_name === selectedProviderEnum ||
p.provider === selectedProvider ||
p.litellm_provider === selectedProvider,
);
return providerInfo ? providerInfo.credential_fields.map(mapFieldMetadataToUiField) : [];
};

// The auth-field keys a parent form should harvest for this provider, minus
// any keys the parent already owns (excludeKeys). Lets the parent collect the
// right form values on submit without the child reporting them back upward.
export const useProviderAuthFieldKeys = (selectedProvider: Providers, excludeKeys?: string[]): string[] => {
const { data: providerMetadata } = useProviderFields();
const excludeDep = (excludeKeys ?? []).join("\0");
return React.useMemo(() => {
const excludeSet = new Set(excludeKeys ?? []);
return resolveProviderFields(providerMetadata, selectedProvider)
.map((f) => f.key)
.filter((k) => !excludeSet.has(k));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [providerMetadata, selectedProvider, excludeDep]);
};

// In-memory cache of provider credential fields keyed by provider display name.
// This lets us reuse the data across multiple mounts and also supports
// non-React helpers like createCredentialFromModel.
const providerFieldsByDisplayName: Record<string, ProviderCredentialField[]> = {};

export const createCredentialFromModel = (provider: string, modelData: any): CredentialItem => {

Check warning on line 113 in ui/litellm-dashboard/src/components/add_model/provider_specific_fields.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
console.log("provider", provider);
console.log("modelData", modelData);
const enumKey = Object.keys(provider_map).find((key) => provider_map[key].toLowerCase() === provider.toLowerCase());
Expand Down Expand Up @@ -104,7 +145,12 @@
return credential;
};

const ProviderSpecificFields: React.FC<ProviderSpecificFieldsProps> = ({ selectedProvider, uploadProps }) => {
const ProviderSpecificFields: React.FC<ProviderSpecificFieldsProps> = ({
selectedProvider,
uploadProps,
excludeKeys,
disableRequired,
}) => {
const selectedProviderEnum = Providers[selectedProvider as keyof typeof Providers] as Providers;
const form = Form.useFormInstance(); // Get form instance from context

Expand Down Expand Up @@ -179,6 +225,14 @@
return mapped;
}, [selectedProviderEnum, selectedProvider, providerMetadata]);

// eslint-disable-next-line react-hooks/exhaustive-deps
const excludeKeySet = React.useMemo(() => new Set(excludeKeys ?? []), [(excludeKeys ?? []).join("\0")]);

const visibleFields = React.useMemo(
() => (excludeKeySet.size > 0 ? allFields.filter((f) => !excludeKeySet.has(f.key)) : allFields),
[allFields, excludeKeySet],
);

const hasApiVersionField = React.useMemo(() => allFields.some((field) => field.key === "api_version"), [allFields]);
const lastInferredApiVersionRef = React.useRef<string | null>(null);

Expand Down Expand Up @@ -250,12 +304,12 @@
</Col>
</Row>
)}
{allFields.map((field) => (
{visibleFields.map((field) => (
<React.Fragment key={field.key}>
<Form.Item
label={field.label}
name={field.key}
rules={field.required ? [{ required: true, message: "Required" }] : undefined}
rules={field.required && !disableRequired ? [{ required: true, message: "Required" }] : undefined}
tooltip={field.tooltip}
className={field.key === "vertex_credentials" ? "mb-0" : undefined}
>
Expand Down
73 changes: 71 additions & 2 deletions ui/litellm-dashboard/src/components/model_info_view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@
tagListCall,
testConnectionRequest,
} from "./networking";
import { getProviderLogoAndName } from "./provider_info_helpers";
import { getProviderLogoAndName, Providers } from "./provider_info_helpers";
import ProviderSpecificFields, { useProviderAuthFieldKeys } from "./add_model/provider_specific_fields";
import NumericalInput from "./shared/numerical_input";
import { Tag } from "./tag_management/types";
import { getDisplayModelName } from "./view_model/model_name_display";
Expand All @@ -50,11 +51,16 @@
accessToken: string | null;
userID: string | null;
userRole: string | null;
onModelUpdate?: (updatedModel: any) => void;

Check warning on line 54 in ui/litellm-dashboard/src/components/model_info_view.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
modelAccessGroups: string[] | null;
}

// Auth fields the model edit form already renders as dedicated inputs — kept
// out of the inline provider auth section so we don't bind two Form.Items to
// the same name or submit a duplicate value.
const AUTH_FIELD_EXCLUDE_KEYS = ["api_base", "organization", "custom_llm_provider"];

export default function ModelInfoView({

Check warning on line 63 in ui/litellm-dashboard/src/components/model_info_view.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Function 'ModelInfoView' has a complexity of 195. Maximum allowed is 20
modelId,
onClose,
accessToken,
Expand All @@ -64,7 +70,7 @@
modelAccessGroups,
}: ModelInfoViewProps) {
const [form] = Form.useForm();
const [localModelData, setLocalModelData] = useState<any>(null);

Check warning on line 73 in ui/litellm-dashboard/src/components/model_info_view.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
const [deleteLoading, setDeleteLoading] = useState(false);
const [isCredentialModalOpen, setIsCredentialModalOpen] = useState(false);
Expand Down Expand Up @@ -100,7 +106,7 @@
}
const transformed = transformModelData(rawModelDataResponse, getProviderFromModel);
return transformed.data[0] || null;
}, [rawModelDataResponse, modelCostMapData]);

Check warning on line 109 in ui/litellm-dashboard/src/components/model_info_view.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

React Hook useMemo has a missing dependency: 'getProviderFromModel'. Either include it or remove the dependency array

// Keep modelData variable name for backwards compatibility
const modelData = transformedModelData;
Expand All @@ -114,6 +120,20 @@
modelData?.litellm_params?.litellm_credential_name != null &&
modelData?.litellm_params?.litellm_credential_name != undefined;

// Track the live credential dropdown so the Authentication section reacts to
// edits in this session (not just the server snapshot). When a named
// credential is selected the inline provider fields are hidden and never
// submitted, so we can't save a credential name and raw inline auth together.
const liveCredentialName = Form.useWatch("litellm_credential_name", form);
const isUsingCredentialInForm = isEditing ? !!liveCredentialName : usingExistingCredential;

// Provider auth-field keys, resolved from the same metadata
// ProviderSpecificFields renders, minus the fields the edit form already
// owns. The save handler harvests exactly these from the form values.
const authProvider = (localModelData?.litellm_params?.custom_llm_provider ||
modelData?.provider) as Providers;
const authFieldKeys = useProviderAuthFieldKeys(authProvider, AUTH_FIELD_EXCLUDE_KEYS);

// Initialize localModelData from modelData when available
useEffect(() => {
if (modelData && !localModelData) {
Expand Down Expand Up @@ -209,9 +229,9 @@
fetchGuardrails();
fetchTags();
fetchCredentials();
}, [accessToken, modelId]);

Check warning on line 232 in ui/litellm-dashboard/src/components/model_info_view.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

React Hook useEffect has missing dependencies: 'modelData' and 'usingExistingCredential'. Either include them or remove the dependency array

const handleReuseCredential = async (values: any) => {

Check warning on line 234 in ui/litellm-dashboard/src/components/model_info_view.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
if (!accessToken) return;
let credentialItem = {
credential_name: values.credential_name,
Expand All @@ -225,7 +245,7 @@
NotificationsManager.success("Credential stored successfully");
};

const handleModelUpdate = async (values: any) => {

Check warning on line 248 in ui/litellm-dashboard/src/components/model_info_view.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
try {
if (!accessToken) return;
setIsSaving(true);
Expand All @@ -241,9 +261,26 @@
return;
}

// Provider auth fields the user actually entered. Blank/null/undefined
// are omitted (never sent as "") so an untouched secret is preserved by
// the backend's merge instead of being overwritten. Mirrors the submit
// filter used by EditCredentialModal. Skipped entirely when a named
// credential is selected — that path owns auth, and sending both would
// leave conflicting config on the backend.
const authFieldUpdates = values.litellm_credential_name
? {}
: authFieldKeys.reduce<Record<string, any>>((acc, key) => {
const v = values[key];
if (v !== "" && v !== undefined && v !== null) {
acc[key] = v;
}
return acc;
}, {});

let updatedLitellmParams = {
...values.litellm_params,
...parsedExtraParams,
...authFieldUpdates,
Comment thread
veria-ai[bot] marked this conversation as resolved.
Resolved
model: values.litellm_model_name,
api_base: values.api_base,
custom_llm_provider: values.custom_llm_provider,
Expand Down Expand Up @@ -359,11 +396,19 @@

await modelPatchUpdateCall(accessToken, updateData, modelId);

// The secrets the user just typed were sent in the request and are now
// stored encrypted by the backend. Don't echo their plaintext into local
// display state — the read-only LiteLLM Params JSON would render it.
const displayLitellmParams = { ...updatedLitellmParams };
for (const key of Object.keys(authFieldUpdates)) {
delete displayLitellmParams[key];
}

const updatedModelData = {
...localModelData,
model_name: values.model_name,
litellm_model_name: values.litellm_model_name,
litellm_params: updatedLitellmParams,
litellm_params: displayLitellmParams,
model_info: updatedModelInfo,
};

Expand Down Expand Up @@ -1168,6 +1213,30 @@
)}
</div>

{isEditing && (
<div>
<Text className="font-medium">Authentication</Text>
{isUsingCredentialInForm ? (
<div className="mt-1 p-2 bg-gray-50 rounded text-sm text-gray-600">
This model uses the shared credential{" "}
<span className="font-mono">{liveCredentialName}</span>. Update its keys from the LLM
Credentials tab.
</div>
) : (
<div className="mt-2">
<Text className="text-xs text-gray-500 mb-2">
Leave a field blank to keep its current value. Enter a new value to rotate it.
</Text>
<ProviderSpecificFields
selectedProvider={authProvider}
excludeKeys={AUTH_FIELD_EXCLUDE_KEYS}
disableRequired
/>
</div>
)}
</div>
)}

{isWildcardModel && (
<div>
<Text className="font-medium">Health Check Model</Text>
Expand Down
4 changes: 2 additions & 2 deletions ui/litellm-dashboard/src/components/networking.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2781,8 +2781,8 @@ export const modelPatchUpdateCall = async (
modelId: string,
) => {
try {
console.log("Form Values in modelUpateCall:", formValues); // Log the form values before making the API call

// Intentionally not logging the payload: it can contain freshly-entered
// provider secrets (api_key, vertex_credentials, AWS creds).
const url = proxyBaseUrl ? `${proxyBaseUrl}/model/${modelId}/update` : `/model/${modelId}/update`;
const response = await fetch(url, {
method: "PATCH",
Expand Down
Loading