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]

[Feature] UI - Allow setting base_url in API reference docs (#16674)

yuneng-jiangf9ec353b80b5
diff --git a/docs/my-website/docs/proxy/config_settings.md b/docs/my-website/docs/proxy/config_settings.md
index 4d02d5729bf..67b5ad26fb9 100644
--- a/docs/my-website/docs/proxy/config_settings.md
+++ b/docs/my-website/docs/proxy/config_settings.md
@@ -655,6 +655,7 @@ router_settings:
| LITELLM_GLOBAL_MAX_PARALLEL_REQUEST_RETRY_TIMEOUT | Timeout for retries of parallel requests in LiteLLM
| LITELLM_MIGRATION_DIR | Custom migrations directory for prisma migrations, used for baselining db in read-only file systems.
| LITELLM_HOSTED_UI | URL of the hosted UI for LiteLLM
+| LITELLM_UI_API_DOC_BASE_URL | Optional override for the API Reference base URL (used in sample code/docs) when the admin UI runs on a different host than the proxy. Defaults to `PROXY_BASE_URL` when unset.
| LITELM_ENVIRONMENT | Environment of LiteLLM Instance, used by logging services. Currently only used by DeepEval.
| LITELLM_KEY_ROTATION_ENABLED | Enable auto-key rotation for LiteLLM (boolean). Default is false.
| LITELLM_KEY_ROTATION_CHECK_INTERVAL_SECONDS | Interval in seconds for how often to run job that auto-rotates keys. Default is 86400 (24 hours).
diff --git a/docs/my-website/docs/proxy/control_plane_and_data_plane.md b/docs/my-website/docs/proxy/control_plane_and_data_plane.md
index db0b7884c92..b0fe2b71ee2 100644
--- a/docs/my-website/docs/proxy/control_plane_and_data_plane.md
+++ b/docs/my-website/docs/proxy/control_plane_and_data_plane.md
@@ -163,6 +163,10 @@ DISABLE_LLM_API_ENDPOINTS=true
- `/config/*` - Configuration updates
- All other administrative endpoints
+### `LITELLM_UI_API_DOC_BASE_URL`
+
+Optional override for the API Reference base URL (used in sample code/docs) when the admin UI runs on a different host than the proxy.
+
## Usage Patterns
diff --git a/litellm/proxy/management_endpoints/ui_sso.py b/litellm/proxy/management_endpoints/ui_sso.py
index ec103d773b3..0add5c02cfb 100644
--- a/litellm/proxy/management_endpoints/ui_sso.py
+++ b/litellm/proxy/management_endpoints/ui_sso.py
@@ -974,6 +974,7 @@ async def get_ui_settings(request: Request):
_proxy_base_url = os.getenv("PROXY_BASE_URL", None)
_logout_url = os.getenv("PROXY_LOGOUT_URL", None)
+ _api_doc_base_url = os.getenv("LITELLM_UI_API_DOC_BASE_URL", None)
_is_sso_enabled = _has_user_setup_sso()
disable_expensive_db_queries = (
proxy_state.get_proxy_state_variable("spend_logs_row_count")
@@ -987,6 +988,7 @@ async def get_ui_settings(request: Request):
return {
"PROXY_BASE_URL": _proxy_base_url,
"PROXY_LOGOUT_URL": _logout_url,
+ "LITELLM_UI_API_DOC_BASE_URL": _api_doc_base_url,
"DEFAULT_TEAM_DISABLED": default_team_disabled,
"SSO_ENABLED": _is_sso_enabled,
"NUM_SPEND_LOGS_ROWS": proxy_state.get_proxy_state_variable(
diff --git a/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py b/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py
index 26b34b994c5..ccf8bf13e0e 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py
@@ -2064,6 +2064,34 @@ class TestProcessSSOJWTAccessToken:
assert result.team_ids == []
+async def test_get_ui_settings_includes_api_doc_base_url():
+ """Ensure the UI settings endpoint surfaces the optional API doc override."""
+ from fastapi import Request
+ from litellm.proxy.management_endpoints.ui_sso import get_ui_settings
+
+ mock_request = Request(
+ scope={
+ "type": "http",
+ "headers": [],
+ "method": "GET",
+ "scheme": "http",
+ "server": ("testserver", 80),
+ "path": "/sso/get/ui_settings",
+ "query_string": b"",
+ }
+ )
+
+ with patch.dict(
+ os.environ,
+ {
+ "LITELLM_UI_API_DOC_BASE_URL": "https://custom.docs",
+ },
+ ):
+ response = await get_ui_settings(mock_request)
+ assert response["LITELLM_UI_API_DOC_BASE_URL"] == "https://custom.docs"
+
+
class TestGenericResponseConvertorNestedAttributes:
"""Test generic_response_convertor with nested attribute paths"""
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/api-reference/APIReferenceView.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/api-reference/APIReferenceView.test.tsx
new file mode 100644
index 00000000000..a73973bd742
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/(dashboard)/api-reference/APIReferenceView.test.tsx
@@ -0,0 +1,47 @@
+import { render } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import APIReferenceView from "./APIReferenceView";
+
+vi.mock("./components/CodeBlock", () => ({
+ __esModule: true,
+ default: ({ code }: { code: string }) => <pre data-testid="api-reference-code-block">{code}</pre>,
+}));
+
+describe("APIReferenceView", () => {
+ const codeBlockTestId = "api-reference-code-block";
+
+ it("uses the API doc base url when provided", () => {
+ const apiDocUrl = "https://docs.litellm.test";
+ const { getAllByTestId } = render(<APIReferenceView proxySettings={{ LITELLM_UI_API_DOC_BASE_URL: apiDocUrl }} />);
+
+ const codeBlocks = getAllByTestId(codeBlockTestId);
+ expect(codeBlocks[0].textContent).toContain(apiDocUrl);
+ });
+
+ it("falls back to the proxy base url when the docs url is missing", () => {
+ const proxyUrl = "https://proxy.litellm.test";
+ const { getAllByTestId } = render(<APIReferenceView proxySettings={{ PROXY_BASE_URL: proxyUrl }} />);
+
+ const codeBlocks = getAllByTestId(codeBlockTestId);
+ expect(codeBlocks[0].textContent).toContain(proxyUrl);
+ });
+
+ it("prefers the docs url when both urls are provided", () => {
+ const apiDocUrl = "https://docs-preferred.litellm.test";
+ const proxyUrl = "https://proxy-backup.litellm.test";
+
+ const { getAllByTestId } = render(
+ <APIReferenceView
+ proxySettings={{
+ LITELLM_UI_API_DOC_BASE_URL: apiDocUrl,
+ PROXY_BASE_URL: proxyUrl,
+ }}
+ />,
+ );
+
+ const codeBlocks = getAllByTestId(codeBlockTestId);
+ const renderedCode = codeBlocks[0].textContent ?? "";
+ expect(renderedCode).toContain(apiDocUrl);
+ expect(renderedCode).not.toContain(proxyUrl);
+ });
+});
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/api-reference/APIReferenceView.tsx b/ui/litellm-dashboard/src/app/(dashboard)/api-reference/APIReferenceView.tsx
index ba2596b92c3..5861cc87e5b 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/api-reference/APIReferenceView.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/api-reference/APIReferenceView.tsx
@@ -5,13 +5,18 @@ import CodeBlock from "./components/CodeBlock";
import DocLink from "@/app/(dashboard)/api-reference/components/DocLink";
interface ApiRefProps {
- proxySettings: any;
+ proxySettings: {
+ PROXY_BASE_URL?: string;
+ LITELLM_UI_API_DOC_BASE_URL?: string | null;
+ };
}
const APIReferenceView: React.FC<ApiRefProps> = ({ proxySettings }) => {
let base_url = "<your_proxy_base_url>";
-
- if (proxySettings?.PROXY_BASE_URL !== undefined && proxySettings?.PROXY_BASE_URL) {
+ const customDocBaseUrl = proxySettings?.LITELLM_UI_API_DOC_BASE_URL;
+ if (customDocBaseUrl && customDocBaseUrl.trim()) {
+ base_url = customDocBaseUrl;
+ } else if (proxySettings?.PROXY_BASE_URL) {
base_url = proxySettings.PROXY_BASE_URL;
}
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/api-reference/page.tsx b/ui/litellm-dashboard/src/app/(dashboard)/api-reference/page.tsx
index 87a342c2840..f9f26c0eac5 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/api-reference/page.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/api-reference/page.tsx
@@ -6,6 +6,7 @@ import { useState } from "react";
interface ProxySettings {
PROXY_BASE_URL: string;
PROXY_LOGOUT_URL: string;
+ LITELLM_UI_API_DOC_BASE_URL?: string | null;
}
const APIReferencePage = () => {
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/test-key/page.tsx b/ui/litellm-dashboard/src/app/(dashboard)/test-key/page.tsx
index 6324f3c5556..bdaff3406b4 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/test-key/page.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/test-key/page.tsx
@@ -2,9 +2,33 @@
import ChatUI from "@/components/chat_ui/ChatUI";
import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";
+import { useState, useEffect } from "react";
+import { fetchProxySettings } from "@/utils/proxyUtils";
+
+interface ProxySettings {
+ PROXY_BASE_URL?: string;
+ LITELLM_UI_API_DOC_BASE_URL?: string | null;
+}
const TestKeyPage = () => {
const { token, accessToken, userRole, userId, disabledPersonalKeyCreation } = useAuthorized();
+ const [proxySettings, setProxySettings] = useState<ProxySettings | undefined>(undefined);
+
+ useEffect(() => {
+ const initializeProxySettings = async () => {
+ if (accessToken) {
+ const settings = await fetchProxySettings(accessToken);
+ if (settings) {
+ setProxySettings({
+ PROXY_BASE_URL: settings.PROXY_BASE_URL || undefined,
+ LITELLM_UI_API_DOC_BASE_URL: settings.LITELLM_UI_API_DOC_BASE_URL,
+ });
+ }
+ }
+ };
+
+ initializeProxySettings();
+ }, [accessToken]);
return (
<ChatUI
@@ -13,6 +37,7 @@ const TestKeyPage = () => {
userRole={userRole}
userID={userId}
disabledPersonalKeyCreation={disabledPersonalKeyCreation}
+ proxySettings={proxySettings}
/>
);
};
diff --git a/ui/litellm-dashboard/src/app/page.tsx b/ui/litellm-dashboard/src/app/page.tsx
index 2d362803987..b0740e54961 100644
--- a/ui/litellm-dashboard/src/app/page.tsx
+++ b/ui/litellm-dashboard/src/app/page.tsx
@@ -106,6 +106,7 @@ function formatUserRole(userRole: string) {
interface ProxySettings {
PROXY_BASE_URL: string;
PROXY_LOGOUT_URL: string;
+ LITELLM_UI_API_DOC_BASE_URL?: string | null;
}
const queryClient = new QueryClient();
@@ -367,6 +368,10 @@ export default function CreateKeyPage() {
token={token}
accessToken={accessToken}
disabledPersonalKeyCreation={disabledPersonalKeyCreation}
+ proxySettings={{
+ PROXY_BASE_URL: proxySettings.PROXY_BASE_URL,
+ LITELLM_UI_API_DOC_BASE_URL: proxySettings.LITELLM_UI_API_DOC_BASE_URL,
+ }}
/>
) : page == "users" ? (
<ViewUserDashboard
diff --git a/ui/litellm-dashboard/src/components/chat_ui/ChatUI.tsx b/ui/litellm-dashboard/src/components/chat_ui/ChatUI.tsx
index b619c755b57..b65e254893f 100644
--- a/ui/litellm-dashboard/src/components/chat_ui/ChatUI.tsx
+++ b/ui/litellm-dashboard/src/components/chat_ui/ChatUI.tsx
@@ -67,9 +67,20 @@ interface ChatUIProps {
userRole: string | null;
userID: string | null;
disabledPersonalKeyCreation: boolean;
+ proxySettings?: {
+ PROXY_BASE_URL?: string;
+ LITELLM_UI_API_DOC_BASE_URL?: string | null;
+ };
}
-const ChatUI: React.FC<ChatUIProps> = ({ accessToken, token, userRole, userID, disabledPersonalKeyCreation }) => {
+const ChatUI: React.FC<ChatUIProps> = ({
+ accessToken,
+ token,
+ userRole,
+ userID,
+ disabledPersonalKeyCreation,
+ proxySettings,
+}) => {
const [isMCPToolsModalVisible, setIsMCPToolsModalVisible] = useState(false);
const [mcpTools, setMCPTools] = useState<MCPTool[]>([]);
const [selectedMCPTools, setSelectedMCPTools] = useState<string[]>(() => {
@@ -214,6 +225,7 @@ const ChatUI: React.FC<ChatUIProps> = ({ accessToken, token, userRole, userID, d
selectedModel,
selectedSdk,
selectedVoice,
+ proxySettings,
});
setGeneratedCode(code);
}
@@ -231,6 +243,7 @@ const ChatUI: React.FC<ChatUIProps> = ({ accessToken, token, userRole, userID, d
selectedMCPTools,
endpointType,
selectedModel,
+ proxySettings,
]);
useEffect(() => {
diff --git a/ui/litellm-dashboard/src/components/chat_ui/CodeSnippets.test.tsx b/ui/litellm-dashboard/src/components/chat_ui/CodeSnippets.test.tsx
index 72608ec6cba..56c5fd404e3 100644
--- a/ui/litellm-dashboard/src/components/chat_ui/CodeSnippets.test.tsx
+++ b/ui/litellm-dashboard/src/components/chat_ui/CodeSnippets.test.tsx
@@ -1,27 +1,158 @@
-import { describe, it, expect } from "vitest";
+import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { generateCodeSnippet } from "./CodeSnippets";
import { EndpointType } from "./mode_endpoint_mapping";
describe("CodeSnippets", () => {
- it("should generate the correct code snippet for embeddings", () => {
- const code = generateCodeSnippet({
- endpointType: EndpointType.EMBEDDINGS,
- inputMessage: "Hello, world!",
- selectedModel: "text-embedding-3-small",
- apiKeySource: "session",
- accessToken: "1234567890",
- apiKey: "1234567890",
- chatHistory: [],
- selectedTags: [],
- selectedVectorStores: [],
- selectedGuardrails: [],
- selectedMCPTools: [],
- selectedSdk: "openai",
- selectedVoice: "alloy",
+ const originalLocation = window.location;
+
+ beforeEach(() => {
+ // Mock window.location.origin
+ Object.defineProperty(window, "location", {
+ value: {
+ ...originalLocation,
+ origin: "http://localhost:4000",
+ },
+ writable: true,
+ });
+ });
+
+ afterEach(() => {
+ Object.defineProperty(window, "location", {
+ value: originalLocation,
+ writable: true,
});
+ });
+
+ const baseParams = {
+ endpointType: EndpointType.EMBEDDINGS,
+ inputMessage: "Hello, world!",
+ selectedModel: "text-embedding-3-small",
+ apiKeySource: "session" as const,
+ accessToken: "1234567890",
+ apiKey: "1234567890",
+ chatHistory: [],
+ selectedTags: [],
+ selectedVectorStores: [],
+ selectedGuardrails: [],
+ selectedMCPTools: [],
+ selectedSdk: "openai" as const,
+ selectedVoice: "alloy",
+ };
+
+ it("should generate the correct code snippet for embeddings", () => {
+ const code = generateCodeSnippet(baseParams);
expect(code).toContain("text-embedding-3-small");
expect(code).toContain("Hello, world!");
expect(code).toContain("client.embeddings.create");
expect(code).toContain("print(response.data[0].embedding)");
});
+
+ describe("base URL selection", () => {
+ it("should use LITELLM_UI_API_DOC_BASE_URL when provided", () => {
+ const customBaseUrl = "https://custom-doc.example.com";
+ const code = generateCodeSnippet({
+ ...baseParams,
+ proxySettings: {
+ LITELLM_UI_API_DOC_BASE_URL: customBaseUrl,
+ },
+ });
+ expect(code).toContain(`base_url="${customBaseUrl}"`);
+ });
+
+ it("should use PROXY_BASE_URL when LITELLM_UI_API_DOC_BASE_URL is not provided", () => {
+ const proxyBaseUrl = "https://proxy.example.com";
+ const code = generateCodeSnippet({
+ ...baseParams,
+ proxySettings: {
+ PROXY_BASE_URL: proxyBaseUrl,
+ },
+ });
+ expect(code).toContain(`base_url="${proxyBaseUrl}"`);
+ });
+
+ it("should prioritize LITELLM_UI_API_DOC_BASE_URL over PROXY_BASE_URL when both are provided", () => {
+ const customBaseUrl = "https://custom-doc.example.com";
+ const proxyBaseUrl = "https://proxy.example.com";
+ const code = generateCodeSnippet({
+ ...baseParams,
+ proxySettings: {
+ LITELLM_UI_API_DOC_BASE_URL: customBaseUrl,
+ PROXY_BASE_URL: proxyBaseUrl,
+ },
+ });
+ expect(code).toContain(`base_url="${customBaseUrl}"`);
+ expect(code).not.toContain(`base_url="${proxyBaseUrl}"`);
+ });
+
+ it("should fallback to window.location.origin when proxySettings is not provided", () => {
+ const code = generateCodeSnippet(baseParams);
+ expect(code).toContain(`base_url="http://localhost:4000"`);
+ });
+
+ it("should fallback to window.location.origin when proxySettings is empty", () => {
+ const code = generateCodeSnippet({
+ ...baseParams,
+ proxySettings: {},
+ });
+ expect(code).toContain(`base_url="http://localhost:4000"`);
+ });
+
+ it("should fallback to PROXY_BASE_URL when LITELLM_UI_API_DOC_BASE_URL is empty string", () => {
+ const proxyBaseUrl = "https://proxy.example.com";
+ const code = generateCodeSnippet({
+ ...baseParams,
+ proxySettings: {
+ LITELLM_UI_API_DOC_BASE_URL: "",
+ PROXY_BASE_URL: proxyBaseUrl,
+ },
+ });
+ expect(code).toContain(`base_url="${proxyBaseUrl}"`);
+ });
+
+ it("should fallback to PROXY_BASE_URL when LITELLM_UI_API_DOC_BASE_URL is whitespace only", () => {
+ const proxyBaseUrl = "https://proxy.example.com";
+ const code = generateCodeSnippet({
+ ...baseParams,
+ proxySettings: {
+ LITELLM_UI_API_DOC_BASE_URL: " ",
+ PROXY_BASE_URL: proxyBaseUrl,
+ },
+ });
+ expect(code).toContain(`base_url="${proxyBaseUrl}"`);
+ });
+
+ it("should fallback to window.location.origin when LITELLM_UI_API_DOC_BASE_URL is null", () => {
+ const code = generateCodeSnippet({
+ ...baseParams,
+ proxySettings: {
+ LITELLM_UI_API_DOC_BASE_URL: null,
+ },
+ });
+ expect(code).toContain(`base_url="http://localhost:4000"`);
+ });
+
+ it("should use LITELLM_UI_API_DOC_BASE_URL for Azure SDK", () => {
+ const customBaseUrl = "https://custom-doc.example.com";
+ const code = generateCodeSnippet({
+ ...baseParams,
+ selectedSdk: "azure",
+ proxySettings: {
+ LITELLM_UI_API_DOC_BASE_URL: customBaseUrl,
+ },
+ });
+ expect(code).toContain(`azure_endpoint="${customBaseUrl}"`);
+ });
+
+ it("should use PROXY_BASE_URL for Azure SDK when LITELLM_UI_API_DOC_BASE_URL is not provided", () => {
+ const proxyBaseUrl = "https://proxy.example.com";
+ const code = generateCodeSnippet({
+ ...baseParams,
+ selectedSdk: "azure",
+ proxySettings: {
+ PROXY_BASE_URL: proxyBaseUrl,
+ },
+ });
+ expect(code).toContain(`azure_endpoint="${proxyBaseUrl}"`);
+ });
+ });
});
diff --git a/ui/litellm-dashboard/src/components/chat_ui/CodeSnippets.tsx b/ui/litellm-dashboard/src/components/chat_ui/CodeSnippets.tsx
index f9d5c84fade..60ce6879bea 100644
--- a/ui/litellm-dashboard/src/components/chat_ui/CodeSnippets.tsx
+++ b/ui/litellm-dashboard/src/components/chat_ui/CodeSnippets.tsx
@@ -21,6 +21,10 @@ interface GenerateCodeParams {
endpointType: string;
selectedModel: string | undefined;
selectedSdk: "openai" | "azure";
+ proxySettings?: {
+ PROXY_BASE_URL?: string;
+ LITELLM_UI_API_DOC_BASE_URL?: string | null;
+ };
}
export const generateCodeSnippet = (params: GenerateCodeParams): string => {
@@ -38,9 +42,18 @@ export const generateCodeSnippet = (params: GenerateCodeParams): string => {
endpointType,
selectedModel,
selectedSdk,
+ proxySettings,
} = params;
const effectiveApiKey = apiKeySource === "session" ? accessToken : apiKey;
- const apiBase = window.location.origin;
+
+ // Determine base URL with priority: LITELLM_UI_API_DOC_BASE_URL > PROXY_BASE_URL > window.location.origin
+ let apiBase = window.location.origin;
+ const customDocBaseUrl = proxySettings?.LITELLM_UI_API_DOC_BASE_URL;
+ if (customDocBaseUrl && customDocBaseUrl.trim()) {
+ apiBase = customDocBaseUrl;
+ } else if (proxySettings?.PROXY_BASE_URL) {
+ apiBase = proxySettings.PROXY_BASE_URL;
+ }
// Always get the input message early on, regardless of what happens later
const userPrompt = inputMessage || "Your prompt here"; // Fallback if inputMessage is empty
diff --git a/ui/litellm-dashboard/src/components/user_dashboard.tsx b/ui/litellm-dashboard/src/components/user_dashboard.tsx
index b00e3547892..4f910452bd8 100644
--- a/ui/litellm-dashboard/src/components/user_dashboard.tsx
+++ b/ui/litellm-dashboard/src/components/user_dashboard.tsx
@@ -22,6 +22,7 @@ import { clearTokenCookies } from "@/utils/cookieUtils";
export interface ProxySettings {
PROXY_BASE_URL: string | null;
PROXY_LOGOUT_URL: string | null;
+ LITELLM_UI_API_DOC_BASE_URL?: string | null;
DEFAULT_TEAM_DISABLED: boolean;
SSO_ENABLED: boolean;
DISABLE_EXPENSIVE_DB_QUERIES: boolean;