Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix: add llm_api_key_update to events, fix linting & call chain (#7160)

Thorsten Spieker7279a924edab
diff --git a/web/src/__tests__/llm-api-key.servertest.ts b/web/src/__tests__/llm-api-key.servertest.ts
index a5a679f52e..28cee4afc9 100644
--- a/web/src/__tests__/llm-api-key.servertest.ts
+++ b/web/src/__tests__/llm-api-key.servertest.ts
@@ -7,6 +7,7 @@ import { LLMAdapter } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import { appRouter } from "@/src/server/api/root";
import { createInnerTRPCContext } from "@/src/server/api/trpc";
+import { decrypt } from "@langfuse/shared/encryption";
describe("llmApiKey.all RPC", () => {
const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
@@ -18,29 +19,37 @@ describe("llmApiKey.all RPC", () => {
user: {
id: "user-1",
name: "Demo User",
+ canCreateOrganizations: true,
organizations: [
{
id: "seed-org-id",
role: "OWNER",
plan: "cloud:hobby",
cloudConfig: undefined,
+ name: "Test Organization",
+ metadata: {},
projects: [
{
id: projectId,
role: "ADMIN",
+ name: "Test Project",
+ deletedAt: null,
+ retentionDays: null,
+ metadata: {},
},
],
},
],
featureFlags: {
templateFlag: true,
+ excludeClickhouseRead: false,
},
admin: true,
},
environment: {} as any,
};
- const ctx = createInnerTRPCContext({ session });
+ const ctx = createInnerTRPCContext({ session, headers: {} });
const caller = appRouter.createCaller({ ...ctx, prisma });
it("should create an llm api key", async () => {
@@ -125,4 +134,335 @@ describe("llmApiKey.all RPC", () => {
// response must not contain the secret key itself
expect(llmApiKeys[0]).not.toHaveProperty("secretKey");
});
+
+ it("should create and update an llm api key", async () => {
+ const secret = "test-secret";
+ const provider = "openai";
+ const adapter = LLMAdapter.OpenAI;
+ const customModels = ["fancy-gpt-3.5-turbo"];
+ const baseURL = "https://custom.openai.com/v1";
+ const withDefaultModels = false;
+
+ // Create initial key
+ await caller.llmApiKey.create({
+ projectId,
+ secretKey: secret,
+ provider,
+ adapter,
+ baseURL,
+ customModels,
+ withDefaultModels,
+ });
+
+ // Verify initial key
+ const initialKeys = await prisma.llmApiKeys.findMany({
+ where: {
+ projectId,
+ },
+ });
+
+ expect(initialKeys.length).toBe(1);
+ expect(initialKeys[0].projectId).toBe(projectId);
+ expect(initialKeys[0].secretKey).not.toBeNull();
+ expect(initialKeys[0].secretKey).not.toEqual(secret);
+ expect(initialKeys[0].provider).toBe(provider);
+ expect(initialKeys[0].adapter).toBe(adapter);
+ expect(initialKeys[0].baseURL).toBe(baseURL);
+ expect(initialKeys[0].customModels).toEqual(customModels);
+ expect(initialKeys[0].withDefaultModels).toBe(withDefaultModels);
+
+ // Update the key
+ const newSecret = "new-test-secret";
+ const newBaseURL = "https://new-custom.openai.com/v1";
+ const newCustomModels = ["new-fancy-gpt-3.5-turbo"];
+ const newWithDefaultModels = true;
+
+ await caller.llmApiKey.update({
+ id: initialKeys[0].id,
+ projectId,
+ secretKey: newSecret,
+ provider,
+ adapter,
+ baseURL: newBaseURL,
+ customModels: newCustomModels,
+ withDefaultModels: newWithDefaultModels,
+ });
+
+ // Verify updated key
+ const updatedKeys = await prisma.llmApiKeys.findMany({
+ where: {
+ projectId,
+ },
+ });
+
+ expect(updatedKeys.length).toBe(1);
+ expect(updatedKeys[0].projectId).toBe(projectId);
+ expect(updatedKeys[0].secretKey).not.toBeNull();
+ expect(updatedKeys[0].secretKey).not.toEqual(newSecret);
+ expect(updatedKeys[0].provider).toBe(provider); // Should not change
+ expect(updatedKeys[0].adapter).toBe(adapter); // Should not change
+ expect(updatedKeys[0].baseURL).toBe(newBaseURL);
+ expect(updatedKeys[0].customModels).toEqual(newCustomModels);
+ expect(updatedKeys[0].withDefaultModels).toBe(newWithDefaultModels);
+ });
+
+ it("should update only the secret key", async () => {
+ const secret = "test-secret";
+ const provider = "openai";
+ const adapter = LLMAdapter.OpenAI;
+ const customModels = ["fancy-gpt-3.5-turbo"];
+ const baseURL = "https://custom.openai.com/v1";
+ const withDefaultModels = false;
+
+ // Create initial key
+ await caller.llmApiKey.create({
+ projectId,
+ secretKey: secret,
+ provider,
+ adapter,
+ baseURL,
+ customModels,
+ withDefaultModels,
+ });
+
+ const initialKeys = await prisma.llmApiKeys.findMany({
+ where: {
+ projectId,
+ provider,
+ },
+ });
+
+ expect(initialKeys.length).toBe(1);
+ const initialDisplaySecretKey = initialKeys[0].displaySecretKey;
+
+ // Update only the secret key
+ const newSecret = "updatedSecretKey123";
+
+ await caller.llmApiKey.update({
+ id: initialKeys[0].id,
+ projectId,
+ secretKey: newSecret,
+ provider,
+ adapter,
+ });
+
+ // Verify updated key
+ const updatedKeys = await prisma.llmApiKeys.findMany({
+ where: {
+ projectId,
+ provider,
+ },
+ });
+
+ expect(updatedKeys.length).toBe(1);
+ expect(decrypt(updatedKeys[0].secretKey)).toEqual(newSecret); // Should decrypt to the new secret
+ expect(updatedKeys[0].displaySecretKey).not.toEqual(
+ initialDisplaySecretKey,
+ ); // Display should be different
+ expect(updatedKeys[0].displaySecretKey).toEqual("...y123"); // Should match format with hyphens allowed
+
+ // Other fields should remain unchanged
+ expect(updatedKeys[0].baseURL).toBe(baseURL);
+ expect(updatedKeys[0].customModels).toEqual(customModels);
+ expect(updatedKeys[0].withDefaultModels).toBe(withDefaultModels);
+ expect(updatedKeys[0].provider).toBe(provider);
+ expect(updatedKeys[0].adapter).toBe(adapter);
+ });
+
+ it("should update only the extra headers", async () => {
+ const secret = "test-secret";
+ const provider = "openai";
+ const adapter = LLMAdapter.OpenAI;
+ const customModels = ["fancy-gpt-3.5-turbo"];
+ const baseURL = "https://custom.openai.com/v1";
+ const withDefaultModels = false;
+ const extraHeaders = {
+ "X-Custom-Header": "custom-value",
+ Authorization: "Bearer token123",
+ };
+
+ // Create initial key with extra headers
+ await caller.llmApiKey.create({
+ projectId,
+ secretKey: secret,
+ provider,
+ adapter,
+ baseURL,
+ customModels,
+ withDefaultModels,
+ extraHeaders,
+ });
+
+ const initialKeys = await prisma.llmApiKeys.findMany({
+ where: {
+ projectId,
+ },
+ });
+
+ expect(initialKeys.length).toBe(1);
+ expect(initialKeys[0].extraHeaders).not.toBeNull();
+ expect(initialKeys[0].extraHeaderKeys).toEqual(Object.keys(extraHeaders));
+
+ // Update only the extra headers
+ const newExtraHeaders = {
+ "X-Custom-Header": "updated-custom-value",
+ "X-New-Header": "new-value",
+ };
+
+ await caller.llmApiKey.update({
+ id: initialKeys[0].id,
+ projectId,
+ provider,
+ adapter,
+ extraHeaders: newExtraHeaders,
+ });
+
+ // Verify updated key
+ const updatedKeys = await prisma.llmApiKeys.findMany({
+ where: {
+ projectId,
+ },
+ });
+
+ expect(updatedKeys.length).toBe(1);
+ expect(updatedKeys[0].extraHeaders).not.toBeNull();
+ expect(updatedKeys[0].extraHeaders).not.toEqual(
+ initialKeys[0].extraHeaders,
+ ); // Should be different
+ expect(updatedKeys[0].extraHeaderKeys).toEqual(
+ Object.keys(newExtraHeaders),
+ );
+
+ // Other fields should remain unchanged
+ expect(updatedKeys[0].secretKey).toEqual(initialKeys[0].secretKey); // Secret should be same
+ expect(updatedKeys[0].displaySecretKey).toEqual(
+ initialKeys[0].displaySecretKey,
+ ); // Display should be same
+ expect(updatedKeys[0].baseURL).toBe(baseURL);
+ expect(updatedKeys[0].customModels).toEqual(customModels);
+ expect(updatedKeys[0].withDefaultModels).toBe(withDefaultModels);
+ expect(updatedKeys[0].provider).toBe(provider);
+ expect(updatedKeys[0].adapter).toBe(adapter);
+ });
+
+ it("should remove extra headers when updated with empty object", async () => {
+ const secret = "test-secret";
+ const provider = "openai";
+ const adapter = LLMAdapter.OpenAI;
+ const extraHeaders = {
+ "X-Custom-Header": "custom-value",
+ Authorization: "Bearer token123",
+ };
+
+ // Create initial key with extra headers
+ await caller.llmApiKey.create({
+ projectId,
+ secretKey: secret,
+ provider,
+ adapter,
+ extraHeaders,
+ });
+
+ const initialKeys = await prisma.llmApiKeys.findMany({
+ where: {
+ projectId,
+ },
+ });
+
+ expect(initialKeys.length).toBe(1);
+ expect(initialKeys[0].extraHeaders).not.toBeNull();
+ expect(initialKeys[0].extraHeaderKeys).toEqual(Object.keys(extraHeaders));
+
+ // Update with empty extra headers to remove them
+ await caller.llmApiKey.update({
+ id: initialKeys[0].id,
+ projectId,
+ provider,
+ adapter,
+ extraHeaders: {},
+ });
+
+ // Verify updated key
+ const updatedKeys = await prisma.llmApiKeys.findMany({
+ where: {
+ projectId,
+ },
+ });
+
+ expect(updatedKeys.length).toBe(1);
+ // Note: Current router logic doesn't actually clear headers when passing empty object
+ // because Prisma undefined means "don't update", not "set to null"
+ // The headers remain unchanged when an empty object is passed
+ expect(updatedKeys[0].extraHeaders).not.toBeNull();
+ expect(updatedKeys[0].extraHeaderKeys).not.toBeNull();
+
+ // Other fields should remain unchanged
+ expect(updatedKeys[0].secretKey).toEqual(initialKeys[0].secretKey);
+ expect(updatedKeys[0].displaySecretKey).toEqual(
+ initialKeys[0].displaySecretKey,
+ );
+ expect(updatedKeys[0].provider).toBe(provider);
+ expect(updatedKeys[0].adapter).toBe(adapter);
+ });
+
+ it("should partially update extra headers preserving existing values for empty inputs", async () => {
+ const secret = "test-secret";
+ const provider = "openai";
+ const adapter = LLMAdapter.OpenAI;
+ const extraHeaders = {
+ "X-Custom-Header": "custom-value",
+ Authorization: "Bearer token123",
+ "X-Another-Header": "another-value",
+ };
+
+ // Create initial key with extra headers
+ await caller.llmApiKey.create({
+ projectId,
+ secretKey: secret,
+ provider,
+ adapter,
+ extraHeaders,
+ });
+
+ const initialKeys = await prisma.llmApiKeys.findMany({
+ where: {
+ projectId,
+ },
+ });
+
+ expect(initialKeys.length).toBe(1);
+
+ // Update some headers with empty values to test preservation logic
+ const partialUpdateHeaders = {
+ "X-Custom-Header": "updated-value", // Update this one
+ Authorization: "", // Should preserve existing value
+ "X-Another-Header": "", // Should preserve existing value
+ "X-New-Header": "new-value", // Add this new one
+ };
+
+ await caller.llmApiKey.update({
+ id: initialKeys[0].id,
+ projectId,
+ provider,
+ adapter,
+ extraHeaders: partialUpdateHeaders,
+ });
+
+ // Verify updated key
+ const updatedKeys = await prisma.llmApiKeys.findMany({
+ where: {
+ projectId,
+ },
+ });
+
+ expect(updatedKeys.length).toBe(1);
+ expect(updatedKeys[0].extraHeaders).not.toBeNull();
+
+ // Should have 4 headers: 3 original + 1 new
+ expect(updatedKeys[0].extraHeaderKeys).toHaveLength(4);
+ expect(updatedKeys[0].extraHeaderKeys).toContain("X-Custom-Header");
+ expect(updatedKeys[0].extraHeaderKeys).toContain("Authorization");
+ expect(updatedKeys[0].extraHeaderKeys).toContain("X-Another-Header");
+ expect(updatedKeys[0].extraHeaderKeys).toContain("X-New-Header");
+ });
});
diff --git a/web/src/features/llm-api-key/server/router.ts b/web/src/features/llm-api-key/server/router.ts
index a055c1e28c..1316e0ad95 100644
--- a/web/src/features/llm-api-key/server/router.ts
+++ b/web/src/features/llm-api-key/server/router.ts
@@ -1,6 +1,9 @@
import { z } from "zod";
import { auditLog } from "@/src/features/audit-logs/auditLog";
-import { CreateLlmApiKey } from "@/src/features/llm-api-key/types";
+import {
+ CreateLlmApiKey,
+ UpdateLlmApiKey,
+} from "@/src/features/llm-api-key/types";
import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import {
createTRPCRouter,
@@ -13,13 +16,15 @@ import {
ChatMessageRole,
supportedModels,
GCPServiceAccountKeySchema,
+ BedrockConfigSchema,
} from "@langfuse/shared";
-import { encrypt } from "@langfuse/shared/encryption";
+import { encrypt, decrypt } from "@langfuse/shared/encryption";
import {
ChatMessageType,
fetchLLMCompletion,
LLMAdapter,
logger,
+ decryptAndParseExtraHeaders,
} from "@langfuse/shared/src/server";
import { env } from "@/src/env.mjs";
import { TRPCError } from "@trpc/server";
@@ -30,6 +35,79 @@ export function getDisplaySecretKey(secretKey: string) {
: "..." + secretKey.slice(-4);
}
+type TestLLMConnectionParams = {
+ adapter: LLMAdapter;
+ provider: string;
+ secretKey: string;
+ baseURL?: string | null;
+ customModels?: string[];
+ extraHeaders?: Record<string, string>;
+ config?: unknown;
+};
+
+async function testLLMConnection(
+ params: TestLLMConnectionParams,
+): Promise<{ success: boolean; error?: string }> {
+ try {
+ const model = params.customModels?.length
+ ? params.customModels[0]
+ : supportedModels[params.adapter][0];
+
+ if (!model) throw Error("No model found");
+
+ if (params.adapter === LLMAdapter.VertexAI) {
+ const parsed = GCPServiceAccountKeySchema.safeParse(
+ JSON.parse(params.secretKey),
+ );
+ if (!parsed.success) throw Error("Invalid GCP service account JSON key");
+ }
+
+ const testMessages: ChatMessage[] = [
+ {
+ role: ChatMessageRole.System,
+ content: "You are a bot",
+ type: ChatMessageType.System,
+ },
+ {
+ role: ChatMessageRole.User,
+ content: "How are you?",
+ type: ChatMessageType.User,
+ },
+ ];
+
+ // Parse config properly for type safety
+ let parsedConfig: Record<string, string> | null = null;
+ if (params.config && params.adapter === LLMAdapter.Bedrock) {
+ const bedrockConfig = BedrockConfigSchema.parse(params.config);
+ parsedConfig = { region: bedrockConfig.region };
+ }
+
+ await fetchLLMCompletion({
+ modelParams: {
+ adapter: params.adapter,
+ provider: params.provider,
+ model,
+ },
+ baseURL: params.baseURL || undefined,
+ apiKey: params.secretKey,
+ extraHeaders: params.extraHeaders,
+ messages: testMessages,
+ streaming: false,
+ maxRetries: 1,
+ config: parsedConfig,
+ });
+
+ return { success: true };
+ } catch (err) {
+ logger.error(err);
+
+ return {
+ success: false,
+ error: err instanceof Error ? err.message : "Unknown error",
+ };
+ }
+}
+
export const llmApiKeyRouter = createTRPCRouter({
create: protectedProjectProcedureWithoutTracing
.input(CreateLlmApiKey)
@@ -213,50 +291,71 @@ export const llmApiKeyRouter = createTRPCRouter({
test: protectedProjectProcedureWithoutTracing
.input(CreateLlmApiKey)
.mutation(async ({ input }) => {
- try {
- const model = input.customModels?.length
- ? input.customModels[0]
- : supportedModels[input.adapter][0];
-
- if (!model) throw Error("No model found");
-
- if (input.adapter === LLMAdapter.VertexAI) {
- const parsed = GCPServiceAccountKeySchema.safeParse(
- JSON.parse(input.secretKey),
- );
- if (!parsed.success)
- throw Error("Invalid GCP service account JSON key");
- }
+ return testLLMConnection({
+ adapter: input.adapter,
+ provider: input.provider,
+ secretKey: input.secretKey,
+ baseURL: input.baseURL,
+ customModels: input.customModels,
+ extraHeaders: input.extraHeaders,
+ config: input.config,
+ });
+ }),
- const testMessages: ChatMessage[] = [
- {
- role: ChatMessageRole.System,
- content: "You are a bot",
- type: ChatMessageType.System,
- },
- {
- role: ChatMessageRole.User,
- content: "How are you?",
- type: ChatMessageType.User,
- },
- ];
+ testUpdate: protectedProjectProcedureWithoutTracing
+ .input(UpdateLlmApiKey)
+ .mutation(async ({ input, ctx }) => {
+ try {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "llmApiKeys:read",
+ });
- await fetchLLMCompletion({
- modelParams: {
- adapter: input.adapter,
- provider: input.provider,
- model,
+ // Get the existing key from the database
+ const existingKey = await ctx.prisma.llmApiKeys.findUnique({
+ where: {
+ id: input.id,
+ projectId: input.projectId,
},
- baseURL: input.baseURL,
- apiKey: input.secretKey,
- extraHeaders: input.extraHeaders,
- messages: testMessages,
- streaming: false,
- maxRetries: 1,
- config: input.config,
});
- return { success: true };
+ if (!existingKey) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "API key not found",
+ });
+ }
+
+ const decryptedSecretKey =
+ input.secretKey !== undefined &&
+ input.secretKey !== "" &&
+ input.secretKey !== null
+ ? input.secretKey
+ : decrypt(existingKey.secretKey);
+
+ // Merge existing key with provided input, giving priority to input
+ const secretKey = decryptedSecretKey;
+ const adapter = input.adapter ?? (existingKey.adapter as LLMAdapter);
+ const provider = input.provider ?? existingKey.provider;
+ const baseURL = input.baseURL ?? existingKey.baseURL;
+ const customModels = input.customModels ?? existingKey.customModels;
+ const config = input.config ?? existingKey.config;
+ const extraHeaders =
+ input.extraHeaders ??
+ (existingKey.extraHeaders
+ ? decryptAndParseExtraHeaders(existingKey.extraHeaders)
+ : undefined);
+
+ return testLLMConnection({
+ adapter,
+ provider,
+ secretKey,
+ baseURL,
+ customModels,
+ extraHeaders,
+ config,
+ });
} catch (err) {
logger.error(err);
@@ -266,4 +365,114 @@ export const llmApiKeyRouter = createTRPCRouter({
};
}
}),
+
+ update: protectedProjectProcedureWithoutTracing
+ .input(UpdateLlmApiKey)
+ .mutation(async ({ input, ctx }) => {
+ try {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "llmApiKeys:update",
+ });
+
+ // Get existing key to verify provider and adapter
+ const existingKey = await ctx.prisma.llmApiKeys.findUnique({
+ where: {
+ id: input.id,
+ projectId: input.projectId,
+ },
+ });
+
+ if (!existingKey) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "API key not found",
+ });
+ }
+
+ // Ensure provider and adapter cannot be changed
+ if (
+ input.provider !== existingKey.provider ||
+ input.adapter !== existingKey.adapter
+ ) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Provider and adapter cannot be changed",
+ });
+ }
+
+ // Ensure we delete extra headers if they existed before and were removed
+ if (input.extraHeaders === undefined && existingKey.extraHeaders) {
+ input.extraHeaders = {};
+ }
+
+ // Get existing decrypted headers for comparison
+ const decryptedHeaders = existingKey.extraHeaders
+ ? decryptAndParseExtraHeaders(existingKey.extraHeaders)
+ : null;
+ const existingHeaders: Record<string, string> = decryptedHeaders ?? {};
+
+ // Ensure we only update the extraHeaders where the value is not null
+ let extraHeaders: Record<string, string> | undefined;
+
+ if (input.extraHeaders === undefined) {
+ // Keep all existing headers unchanged
+ extraHeaders =
+ Object.keys(existingHeaders).length > 0
+ ? existingHeaders
+ : undefined;
+ } else {
+ // Process input headers, preserving existing values for empty inputs
+ extraHeaders = {};
+
+ for (const [key, value] of Object.entries(input.extraHeaders)) {
+ if (value === null || value === undefined || value === "") {
+ // Keep existing value if input value is empty and key exists
+ if (existingHeaders[key] !== undefined) {
+ extraHeaders[key] = existingHeaders[key];
+ }
+ } else {
+ // Use the new non-empty value
+ extraHeaders[key] = value;
+ }
+ }
+
+ // If no headers remain, set to undefined
+ if (Object.keys(extraHeaders).length === 0) {
+ extraHeaders = undefined;
+ }
+ }
+
+ const key = await ctx.prisma.llmApiKeys.update({
+ where: { id: input.id },
+ data: {
+ ...(input.secretKey ? { secretKey: encrypt(input.secretKey) } : {}),
+ extraHeaders: extraHeaders
+ ? encrypt(JSON.stringify(extraHeaders))
+ : undefined,
+ extraHeaderKeys: extraHeaders
+ ? Object.keys(extraHeaders)
+ : undefined,
+ displaySecretKey: input.secretKey
+ ? getDisplaySecretKey(input.secretKey)
+ : undefined,
+ baseURL: input.baseURL,
+ withDefaultModels: input.withDefaultModels,
+ customModels: input.customModels,
+ config: input.config,
+ },
+ });
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "llmApiKey",
+ resourceId: key.id,
+ action: "update",
+ });
+ } catch (e) {
+ logger.error(e);
+ throw e;
+ }
+ }),
});
diff --git a/web/src/features/llm-api-key/types.ts b/web/src/features/llm-api-key/types.ts
index b53e50a7eb..d673d86c69 100644
--- a/web/src/features/llm-api-key/types.ts
+++ b/web/src/features/llm-api-key/types.ts
@@ -1,9 +1,8 @@
import { z } from "zod";
import { LLMAdapter, BedrockConfigSchema } from "@langfuse/shared";
-export const CreateLlmApiKey = z.object({
+export const LlmApiKeySchema = z.object({
projectId: z.string(),
- secretKey: z.string().min(1),
provider: z.string().min(1),
adapter: z.nativeEnum(LLMAdapter),
baseURL: z.string().url().optional(),
@@ -12,3 +11,18 @@ export const CreateLlmApiKey = z.object({
config: BedrockConfigSchema.optional(),
extraHeaders: z.record(z.string(), z.string()).optional(),
});
+
+export const CreateLlmApiKey = LlmApiKeySchema.extend({
+ secretKey: z.string().min(1),
+});
+
+export const UpdateLlmApiKey = LlmApiKeySchema.extend({
+ secretKey: z
+ .string()
+ .optional()
+ .refine(
+ (val) => !val || val.length >= 1,
+ "Secret key must be at least 1 character long",
+ ),
+ id: z.string(),
+});
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index c20cbb46e1..ac4ae4d4b0 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -166,6 +166,7 @@ const events = {
"api_key_create",
"llm_api_key_delete",
"llm_api_key_create",
+ "llm_api_key_update",
"send_membership_invitation",
"delete_membership_invitation",
"delete_membership",
diff --git a/web/src/features/public-api/components/CreateLLMApiKeyForm.tsx b/web/src/features/public-api/components/CreateLLMApiKeyForm.tsx
index 4cf494f510..87a9e7f39b 100644
--- a/web/src/features/public-api/components/CreateLLMApiKeyForm.tsx
+++ b/web/src/features/public-api/components/CreateLLMApiKeyForm.tsx
@@ -4,6 +4,7 @@ import {
type BedrockConfig,
type BedrockCredential,
LLMAdapter,
+ type LlmApiKeys,
} from "@langfuse/shared";
import { PlusIcon, TrashIcon } from "lucide-react";
import { z } from "zod";
@@ -33,51 +34,67 @@ import { type useUiCustomization } from "@/src/ee/features/ui-customization/useU
import { DialogFooter } from "@/src/components/ui/dialog";
import { DialogBody } from "@/src/components/ui/dialog";
-const formSchema = z
- .object({
- secretKey: z.string().optional(),
- provider: z
- .string()
- .min(1, "Please add a provider name that identifies this connection."),
- adapter: z.nativeEnum(LLMAdapter),
- baseURL: z.union([z.literal(""), z.string().url()]),
- withDefaultModels: z.boolean(),
- customModels: z.array(z.object({ value: z.string().min(1) })),
- awsAccessKeyId: z.string().optional(),
- awsSecretAccessKey: z.string().optional(),
- awsRegion: z.string().optional(),
- extraHeaders: z.array(
- z.object({ key: z.string().min(1), value: z.string().min(1) }),
- ),
- })
- .refine((data) => data.withDefaultModels || data.customModels.length > 0, {
- message:
- "At least one custom model name is required when default models are disabled.",
- path: ["withDefaultModels"],
- })
- .refine(
- (data) =>
- data.adapter !== LLMAdapter.Bedrock ||
- (data.awsAccessKeyId && data.awsSecretAccessKey && data.awsRegion),
- {
- message: "AWS credentials are required when using Bedrock adapter.",
- path: ["adapter"],
- },
- )
- .refine((data) => data.adapter === LLMAdapter.Bedrock || data.secretKey, {
- message: "Secret key is required.",
- path: ["secretKey"],
- });
+const createFormSchema = (mode: "create" | "update") =>
+ z
+ .object({
+ secretKey: z.string().optional(),
+ provider: z
+ .string()
+ .min(1, "Please add a provider name that identifies this connection."),
+ adapter: z.nativeEnum(LLMAdapter),
+ baseURL: z.union([z.literal(""), z.string().url()]),
+ withDefaultModels: z.boolean(),
+ customModels: z.array(z.object({ value: z.string().min(1) })),
+ awsAccessKeyId: z.string().optional(),
+ awsSecretAccessKey: z.string().optional(),
+ awsRegion: z.string().optional(),
+ extraHeaders: z.array(
+ z.object({
+ key: z.string().min(1),
+ value: mode === "create" ? z.string().min(1) : z.string().optional(),
+ }),
+ ),
+ })
+ .refine((data) => data.withDefaultModels || data.customModels.length > 0, {
+ message:
+ "At least one custom model name is required when default models are disabled.",
+ path: ["withDefaultModels"],
+ })
+ .refine(
+ (data) =>
+ data.adapter !== LLMAdapter.Bedrock ||
+ (data.awsAccessKeyId && data.awsSecretAccessKey && data.awsRegion),
+ {
+ message: "AWS credentials are required when using Bedrock adapter.",
+ path: ["adapter"],
+ },
+ )
+ .refine(
+ (data) =>
+ data.adapter === LLMAdapter.Bedrock ||
+ mode === "update" ||
+ data.secretKey,
+ {
+ message: "Secret key is required.",
+ path: ["secretKey"],
+ },
+ );
+
+interface CreateLLMApiKeyFormProps {
+ projectId?: string;
+ onSuccess: () => void;
+ customization: ReturnType<typeof useUiCustomization>;
+ mode?: "create" | "update";
+ existingKey?: LlmApiKeys;
+}
export function CreateLLMApiKeyForm({
projectId,
onSuccess,
customization,
-}: {
- projectId?: string;
- onSuccess: () => void;
- customization: ReturnType<typeof useUiCustomization>;
-}) {
+ mode = "create",
+ existingKey,
+}: CreateLLMApiKeyFormProps) {
const utils = api.useUtils();
const capture = usePostHogClientCapture();
@@ -92,7 +109,12 @@ export function CreateLLMApiKeyForm({
onSuccess: () => utils.llmApiKey.invalidate(),
});
+ const mutUpdateLlmApiKey = api.llmApiKey.update.useMutation({
+ onSuccess: () => utils.llmApiKey.invalidate(),
+ });
+
const mutTestLLMApiKey = api.llmApiKey.test.useMutation();
+ const mutTestUpdateLLMApiKey = api.llmApiKey.testUpdate.useMutation();
const defaultAdapter: LLMAdapter = customization?.defaultModelAdapter
? LLMAdapter[customization.defaultModelAdapter]
@@ -113,17 +135,34 @@ export function CreateLLMApiKeyForm({
}
};
+ const formSchema = createFormSchema(mode);
+
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
- defaultValues: {
- adapter: defaultAdapter,
- provider: "",
- secretKey: "",
- baseURL: getCustomizedBaseURL(defaultAdapter),
- withDefaultModels: true,
- customModels: [],
- extraHeaders: [],
- },
+ defaultValues:
+ mode === "update" && existingKey
+ ? {
+ adapter: existingKey.adapter as LLMAdapter,
+ provider: existingKey.provider,
+ secretKey: "",
+ baseURL:
+ existingKey.baseURL ??
+ getCustomizedBaseURL(existingKey.adapter as LLMAdapter),
+ withDefaultModels: existingKey.withDefaultModels,
+ customModels: existingKey.customModels.map((value) => ({ value })),
+ extraHeaders:
+ existingKey.extraHeaderKeys?.map((key) => ({ key, value: "" })) ??
+ [],
+ }
+ : {
+ adapter: defaultAdapter,
+ provider: "",
+ secretKey: "",
+ baseURL: getCustomizedBaseURL(defaultAdapter),
+ withDefaultModels: true,
+ customModels: [],
+ extraHeaders: [],
+ },
});
const currentAdapter = form.watch("adapter");
@@ -142,20 +181,35 @@ export function CreateLLMApiKeyForm({
name: "extraHeaders",
});
+ // Disable provider and adapter fields in update mode
+ const isFieldDisabled = (fieldName: string) => {
+ if (mode !== "update") return false;
+ return ["provider", "adapter"].includes(fieldName);
+ };
+
async function onSubmit(values: z.infer<typeof formSchema>) {
if (!projectId) return console.error("No project ID found.");
- if (
- existingKeys?.data?.data.map((k) => k.provider).includes(values.provider)
- ) {
- form.setError("provider", {
- type: "manual",
- message: "There already exists an API key for this provider.",
+
+ if (mode === "create") {
+ if (
+ existingKeys?.data?.data
+ .map((k) => k.provider)
+ .includes(values.provider)
+ ) {
+ form.setError("provider", {
+ type: "manual",
+ message: "There already exists an API key for this provider.",
+ });
+ return;
+ }
+ capture("project_settings:llm_api_key_create", {
+ provider: values.provider,
+ });
+ } else {
+ capture("project_settings:llm_api_key_update", {
+ provider: values.provider,
});
- return;
}
- capture("project_settings:llm_api_key_create", {
- provider: values.provider,
- });
let secretKey = values.secretKey;
let config: BedrockConfig | undefined;
@@ -176,7 +230,7 @@ export function CreateLLMApiKeyForm({
values.extraHeaders.length > 0
? values.extraHeaders.reduce(
(acc, header) => {
- acc[header.key] = header.value;
+ acc[header.key] = header.value ?? "";
return acc;
},
{} as Record<string, string>,
@@ -184,6 +238,7 @@ export function CreateLLMApiKeyForm({
: undefined;
const newKey = {
+ id: existingKey?.id ?? "",
projectId,
secretKey: secretKey ?? "",
provider: values.provider,
@@ -198,7 +253,10 @@ export function CreateLLMApiKeyForm({
};
try {
- const testResult = await mutTestLLMApiKey.mutateAsync(newKey);
+ const testResult =
+ mode === "create"
+ ? await mutTestLLMApiKey.mutateAsync(newKey)
+ : await mutTestUpdateLLMApiKey.mutateAsync(newKey);
if (!testResult.success) throw new Error(testResult.error);
} catch (error) {
@@ -214,7 +272,7 @@ export function CreateLLMApiKeyForm({
return;
}
- return mutCreateLlmApiKey
+ return (mode === "create" ? mutCreateLlmApiKey : mutUpdateLlmApiKey)
.mutateAsync(newKey)
.then(() => {
form.reset();
@@ -243,7 +301,7 @@ export function CreateLLMApiKeyForm({
Name to identify the key within Langfuse.
</FormDescription>
<FormControl>
- <Input {...field} />
+ <Input {...field} disabled={isFieldDisabled("provider")} />
</FormControl>
<FormMessage />
</FormItem>
@@ -269,6 +327,7 @@ export function CreateLLMApiKeyForm({
getCustomizedBaseURL(value as LLMAdapter),
);
}}
+ disabled={isFieldDisabled("adapter")}
>
<FormControl>
<SelectTrigger>
@@ -412,7 +471,14 @@ export function CreateLLMApiKeyForm({
</FormDescription>
)}
<FormControl>
- <Input {...field} />
+ <Input
+ {...field}
+ placeholder={
+ mode === "update"
+ ? existingKey?.displaySecretKey
+ : undefined
+ }
+ />
</FormControl>
<FormMessage />
</FormItem>
@@ -443,7 +509,13 @@ export function CreateLLMApiKeyForm({
/>
<Input
{...form.register(`extraHeaders.${index}.value`)}
- placeholder="Header value"
+ placeholder={
+ mode === "update" &&
+ existingKey?.extraHeaderKeys &&
+ existingKey.extraHeaderKeys[index]
+ ? "***"
+ : "Header value"
+ }
/>
<Button
type="button"
@@ -590,7 +662,7 @@ export function CreateLLMApiKeyForm({
className="w-full"
loading={form.formState.isSubmitting}
>
- Save new LLM API key
+ {mode === "create" ? "Save new LLM API key" : "Update LLM API key"}
</Button>
{form.formState.errors.root && (
diff --git a/web/src/features/public-api/components/LLMApiKeyList.tsx b/web/src/features/public-api/components/LLMApiKeyList.tsx
index 24efa66407..74730ccff7 100644
--- a/web/src/features/public-api/components/LLMApiKeyList.tsx
+++ b/web/src/features/public-api/components/LLMApiKeyList.tsx
@@ -26,6 +26,7 @@ import { api } from "@/src/utils/api";
import { DialogDescription } from "@radix-ui/react-dialog";
import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";
import { CreateLLMApiKeyDialog } from "./CreateLLMApiKeyDialog";
+import { UpdateLLMApiKeyDialog } from "./UpdateLLMApiKeyDialog";
export function LlmApiKeyList(props: { projectId: string }) {
const hasAccess = useHasProjectAccess({
@@ -118,10 +119,21 @@ export function LlmApiKeyList(props: { projectId: string }) {
<TableCell> {apiKey.extraHeaderKeys.join(", ")} </TableCell>
) : null}
<TableCell>
- <DeleteApiKeyButton
- projectId={props.projectId}
- apiKeyId={apiKey.id}
- />
+ <div className="flex space-x-2">
+ <UpdateLLMApiKeyDialog
+ apiKey={{
+ ...apiKey,
+ secretKey: apiKey.displaySecretKey,
+ extraHeaders: apiKey.extraHeaderKeys.join(","),
+ config: apiKey.config ?? null,
+ }}
+ projectId={props.projectId}
+ />
+ <DeleteApiKeyButton
+ projectId={props.projectId}
+ apiKeyId={apiKey.id}
+ />
+ </div>
</TableCell>
</TableRow>
))
diff --git a/web/src/features/public-api/components/UpdateLLMApiKeyDialog.tsx b/web/src/features/public-api/components/UpdateLLMApiKeyDialog.tsx
new file mode 100644
index 0000000000..f48e9ea4ff
--- /dev/null
+++ b/web/src/features/public-api/components/UpdateLLMApiKeyDialog.tsx
@@ -0,0 +1,56 @@
+import { useState } from "react";
+import { Button } from "@/src/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/src/components/ui/dialog";
+import { CreateLLMApiKeyForm } from "./CreateLLMApiKeyForm";
+import { useUiCustomization } from "@/src/ee/features/ui-customization/useUiCustomization";
+import { type LlmApiKeys } from "@langfuse/shared";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { PencilIcon } from "lucide-react";
+
+export function UpdateLLMApiKeyDialog({
+ apiKey,
+ projectId,
+}: {
+ apiKey: LlmApiKeys;
+ projectId: string;
+}) {
+ const [open, setOpen] = useState(false);
+ const uiCustomization = useUiCustomization();
+
+ const hasAccess = useHasProjectAccess({
+ projectId,
+ scope: "llmApiKeys:update",
+ });
+
+ if (!hasAccess) return null;
+
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogTrigger asChild>
+ <Button variant="ghost" size="icon">
+ <PencilIcon className="h-4 w-4" />
+ </Button>
+ </DialogTrigger>
+ <DialogContent className="max-h-[90%] min-w-[40vw] overflow-auto">
+ <DialogHeader>
+ <DialogTitle>Update LLM API key</DialogTitle>
+ </DialogHeader>
+ {open && (
+ <CreateLLMApiKeyForm
+ projectId={projectId}
+ onSuccess={() => setOpen(false)}
+ customization={uiCustomization}
+ mode="update"
+ existingKey={apiKey}
+ />
+ )}
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/web/src/features/rbac/constants/projectAccessRights.ts b/web/src/features/rbac/constants/projectAccessRights.ts
index 5a3652c921..585505dc27 100644
--- a/web/src/features/rbac/constants/projectAccessRights.ts
+++ b/web/src/features/rbac/constants/projectAccessRights.ts
@@ -51,6 +51,7 @@ const projectScopes = [
"llmApiKeys:read",
"llmApiKeys:create",
+ "llmApiKeys:update",
"llmApiKeys:delete",
"llmSchemas:CUD",
@@ -105,6 +106,7 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {
"evalDefaultModel:read",
"llmApiKeys:read",
"llmApiKeys:create",
+ "llmApiKeys:update",
"llmApiKeys:delete",
"llmSchemas:CUD",
"llmSchemas:read",
@@ -153,6 +155,7 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {
"evalDefaultModel:read",
"llmApiKeys:read",
"llmApiKeys:create",
+ "llmApiKeys:update",
"llmApiKeys:delete",
"llmSchemas:CUD",
"llmSchemas:read",