Skip to content

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

feat(api): add DELETE endpoint for LLM connections (#13247)

Steffen Schmitz82a4ac492633
diff --git a/fern/apis/server/definition/llm-connections.yml b/fern/apis/server/definition/llm-connections.yml
index 17746e27ca..3a3a731f0e 100644
--- a/fern/apis/server/definition/llm-connections.yml
+++ b/fern/apis/server/definition/llm-connections.yml
@@ -26,6 +26,13 @@ service:
path: /llm-connections
request: UpsertLlmConnectionRequest
response: LlmConnection
+ delete:
+ method: DELETE
+ docs: Delete an LLM connection by id. Evaluators that depend on the deleted connection are automatically paused.
+ path: /llm-connections/{id}
+ path-parameters:
+ id: string
+ response: DeleteLlmConnectionResponse
types:
LlmConnection:
@@ -96,6 +103,10 @@ types:
- **VertexAI**: Optional. If provided, must be `{"location": "<gcp-location>"}` (e.g., `{"location":"us-central1"}`)
- **Other adapters**: Not supported. Omit this field or set to null.
+ DeleteLlmConnectionResponse:
+ properties:
+ message: string
+
LlmAdapter:
enum:
- value: anthropic
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index 246ab14942..f5955638de 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -2409,6 +2409,54 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/UpsertLlmConnectionRequest'
+ /api/public/llm-connections/{id}:
+ delete:
+ description: >-
+ Delete an LLM connection by id. Evaluators that depend on the deleted
+ connection are automatically paused.
+ operationId: llmConnections_delete
+ tags:
+ - LlmConnections
+ parameters:
+ - name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/DeleteLlmConnectionResponse'
+ '400':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '401':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '403':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '404':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '405':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ security:
+ - BasicAuth: []
/api/public/media/{mediaId}:
get:
description: Get a media record
@@ -9436,6 +9484,14 @@ components:
- provider
- adapter
- secretKey
+ DeleteLlmConnectionResponse:
+ title: DeleteLlmConnectionResponse
+ type: object
+ properties:
+ message:
+ type: string
+ required:
+ - message
LlmAdapter:
title: LlmAdapter
type: string
diff --git a/web/src/__tests__/server/llm-connections-api.servertest.ts b/web/src/__tests__/server/llm-connections-api.servertest.ts
index ffaad4062f..b4447d26fc 100644
--- a/web/src/__tests__/server/llm-connections-api.servertest.ts
+++ b/web/src/__tests__/server/llm-connections-api.servertest.ts
@@ -6,6 +6,7 @@ import {
makeZodVerifiedAPICall,
} from "@/src/__tests__/test-utils";
import {
+ DeleteLlmConnectionV1Response,
GetLlmConnectionsV1Response,
PutLlmConnectionV1Response,
} from "@/src/features/public-api/types/llm-connections";
@@ -1261,6 +1262,131 @@ describe("/api/public/llm-connections API Endpoints", () => {
});
});
+ describe("DELETE /api/public/llm-connections/{id}", () => {
+ it("should delete an existing LLM connection", async () => {
+ const provider = generateUniqueProvider("delete-test");
+ const connection = await prisma.llmApiKeys.create({
+ data: {
+ projectId,
+ provider,
+ adapter: LLMAdapter.OpenAI,
+ secretKey: encrypt("sk-delete"),
+ displaySecretKey: "...lete",
+ },
+ });
+
+ const response = await makeZodVerifiedAPICall(
+ DeleteLlmConnectionV1Response,
+ "DELETE",
+ `/api/public/llm-connections/${connection.id}`,
+ undefined,
+ auth,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.message).toBe("LLM connection successfully deleted");
+
+ const dbConnection = await prisma.llmApiKeys.findUnique({
+ where: { id: connection.id },
+ });
+ expect(dbConnection).toBeNull();
+ });
+
+ it("should create an audit log entry for delete", async () => {
+ const connection = await prisma.llmApiKeys.create({
+ data: {
+ projectId,
+ provider: generateUniqueProvider("audit-delete"),
+ adapter: LLMAdapter.OpenAI,
+ secretKey: encrypt("sk-audit-delete"),
+ displaySecretKey: "...lete",
+ },
+ });
+
+ await makeZodVerifiedAPICall(
+ DeleteLlmConnectionV1Response,
+ "DELETE",
+ `/api/public/llm-connections/${connection.id}`,
+ undefined,
+ auth,
+ );
+
+ const auditLogs = await prisma.auditLog.findMany({
+ where: {
+ resourceType: "llmApiKey",
+ resourceId: connection.id,
+ action: "delete",
+ },
+ });
+ expect(auditLogs).toHaveLength(1);
+ });
+
+ it("should return 404 for non-existent connection id", async () => {
+ const response = await makeAPICall(
+ "DELETE",
+ "/api/public/llm-connections/non-existent-id",
+ undefined,
+ auth,
+ );
+
+ expect(response.status).toBe(404);
+ });
+
+ it("should not delete a connection from a different project", async () => {
+ const { projectId: otherProjectId } = await createOrgProjectAndApiKey();
+ const otherConnection = await prisma.llmApiKeys.create({
+ data: {
+ projectId: otherProjectId,
+ provider: generateUniqueProvider("cross-project-delete"),
+ adapter: LLMAdapter.OpenAI,
+ secretKey: encrypt("sk-other"),
+ displaySecretKey: "...dfg3",
+ },
+ });
+
+ const response = await makeAPICall(
+ "DELETE",
+ `/api/public/llm-connections/${otherConnection.id}`,
+ undefined,
+ auth,
+ );
+
+ expect(response.status).toBe(404);
+
+ // Verify the other project's connection is still intact
+ const stillThere = await prisma.llmApiKeys.findUnique({
+ where: { id: otherConnection.id },
+ });
+ expect(stillThere).toBeTruthy();
+ });
+
+ it("should return 401 for invalid auth", async () => {
+ const connection = await prisma.llmApiKeys.create({
+ data: {
+ projectId,
+ provider: generateUniqueProvider("delete-unauth"),
+ adapter: LLMAdapter.OpenAI,
+ secretKey: encrypt("sk-unauth"),
+ displaySecretKey: "...auth",
+ },
+ });
+
+ const response = await makeAPICall(
+ "DELETE",
+ `/api/public/llm-connections/${connection.id}`,
+ undefined,
+ "invalid-auth",
+ );
+
+ expect(response.status).toBe(401);
+
+ const stillThere = await prisma.llmApiKeys.findUnique({
+ where: { id: connection.id },
+ });
+ expect(stillThere).toBeTruthy();
+ });
+ });
+
describe("Authorization", () => {
it("should not access connections from different project", async () => {
// Create connection in different project
diff --git a/web/src/features/public-api/types/llm-connections.ts b/web/src/features/public-api/types/llm-connections.ts
index 510fedb909..6bd16bf7cc 100644
--- a/web/src/features/public-api/types/llm-connections.ts
+++ b/web/src/features/public-api/types/llm-connections.ts
@@ -131,6 +131,19 @@ export const PutLlmConnectionV1Body = PutLlmConnectionV1BodyBase.superRefine(
// PUT /api/public/llm-connections response
export const PutLlmConnectionV1Response = LlmConnectionResponse.strict();
+// DELETE /api/public/llm-connections/{id}
+export const DeleteLlmConnectionV1Query = z
+ .object({
+ id: z.string(),
+ })
+ .strict();
+
+export const DeleteLlmConnectionV1Response = z
+ .object({
+ message: z.literal("LLM connection successfully deleted"),
+ })
+ .strict();
+
// Transform database record to API response
export function transformDbLlmConnectionToAPI(dbConnection: {
id: string;
diff --git a/web/src/pages/api/public/llm-connections/[id].ts b/web/src/pages/api/public/llm-connections/[id].ts
new file mode 100644
index 0000000000..a2c17f7787
--- /dev/null
+++ b/web/src/pages/api/public/llm-connections/[id].ts
@@ -0,0 +1,144 @@
+import { prisma } from "@langfuse/shared/src/db";
+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
+import {
+ DeleteLlmConnectionV1Query,
+ DeleteLlmConnectionV1Response,
+} from "@/src/features/public-api/types/llm-connections";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import {
+ EvaluatorBlockReason,
+ getEvaluatorBlockMetadata,
+ LangfuseNotFoundError,
+} from "@langfuse/shared";
+import {
+ blockEvaluatorConfigsInTx,
+ EvaluatorBlockSource,
+ finalizeBlockedEvaluatorConfigBlocks,
+} from "@langfuse/shared/src/server";
+
+export default withMiddlewares({
+ DELETE: createAuthedProjectAPIRoute({
+ name: "Delete LLM Connection",
+ querySchema: DeleteLlmConnectionV1Query,
+ responseSchema: DeleteLlmConnectionV1Response,
+ isAdminApiKeyAuthAllowed: true,
+ fn: async ({ query, auth }) => {
+ const projectId = auth.scope.projectId;
+
+ const llmApiKey = await prisma.llmApiKeys.findFirst({
+ where: {
+ id: query.id,
+ projectId,
+ },
+ });
+
+ if (!llmApiKey) {
+ throw new LangfuseNotFoundError("LLM connection not found");
+ }
+
+ const result = await prisma.$transaction(async (tx) => {
+ const defaultModel = await tx.defaultLlmModel.findFirst({
+ where: { projectId },
+ select: { llmApiKeyId: true },
+ });
+
+ const providerBlockedJobConfigIds = new Set<string>();
+ const defaultModelBlockedJobConfigIds = new Set<string>();
+
+ if (llmApiKey.provider) {
+ const evalTemplates = await tx.evalTemplate.findMany({
+ where: {
+ OR: [{ projectId }, { projectId: null }],
+ provider: llmApiKey.provider,
+ },
+ select: { id: true },
+ });
+
+ const providerBlockResult = await blockEvaluatorConfigsInTx({
+ tx,
+ projectId,
+ where: {
+ evalTemplateId: {
+ in: evalTemplates.map((template) => template.id),
+ },
+ },
+ blockReason: EvaluatorBlockReason.LLM_CONNECTION_MISSING,
+ blockMessage: getEvaluatorBlockMetadata(
+ EvaluatorBlockReason.LLM_CONNECTION_MISSING,
+ ).message,
+ });
+
+ for (const configId of providerBlockResult.blockedJobConfigIds) {
+ providerBlockedJobConfigIds.add(configId);
+ }
+ }
+
+ if (defaultModel && defaultModel.llmApiKeyId === llmApiKey.id) {
+ const evalTemplates = await tx.evalTemplate.findMany({
+ where: {
+ OR: [{ projectId }, { projectId: null }],
+ provider: null,
+ model: null,
+ },
+ select: { id: true },
+ });
+
+ const defaultModelBlockResult = await blockEvaluatorConfigsInTx({
+ tx,
+ projectId,
+ where: {
+ evalTemplateId: {
+ in: evalTemplates.map((template) => template.id),
+ },
+ },
+ blockReason: EvaluatorBlockReason.DEFAULT_EVAL_MODEL_MISSING,
+ blockMessage: getEvaluatorBlockMetadata(
+ EvaluatorBlockReason.DEFAULT_EVAL_MODEL_MISSING,
+ ).message,
+ });
+
+ for (const configId of defaultModelBlockResult.blockedJobConfigIds) {
+ defaultModelBlockedJobConfigIds.add(configId);
+ }
+ }
+
+ await tx.llmApiKeys.delete({
+ where: { id: llmApiKey.id, projectId },
+ });
+
+ await auditLog({
+ action: "delete",
+ resourceType: "llmApiKey",
+ resourceId: llmApiKey.id,
+ projectId,
+ orgId: auth.scope.orgId,
+ apiKeyId: auth.scope.apiKeyId,
+ before: llmApiKey,
+ });
+
+ return {
+ providerBlockedJobConfigIds: Array.from(providerBlockedJobConfigIds),
+ defaultModelBlockedJobConfigIds: Array.from(
+ defaultModelBlockedJobConfigIds,
+ ),
+ };
+ });
+
+ await finalizeBlockedEvaluatorConfigBlocks({
+ projectId,
+ source: EvaluatorBlockSource.LLM_API_KEY_DELETION,
+ blockedByReason: {
+ [EvaluatorBlockReason.LLM_CONNECTION_MISSING]:
+ result.providerBlockedJobConfigIds,
+ [EvaluatorBlockReason.DEFAULT_EVAL_MODEL_MISSING]:
+ result.defaultModelBlockedJobConfigIds,
+ },
+ });
+
+ return {
+ message: "LLM connection successfully deleted" as const,
+ };
+ },
+ }),
+});