Skip to content

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

feat: bring your own llm api key (#1796)

Max Deichmanne0e346dccb66
diff --git a/.env.dev.example b/.env.dev.example
index 7cdfca9aea..4ddeb63284 100644
--- a/.env.dev.example
+++ b/.env.dev.example
@@ -46,4 +46,6 @@ REDIS_HOST="127.0.0.1"
REDIS_PORT=6379
REDIS_AUTH="myredissecret"
-LANGFUSE_WORKER_PASSWORD=mybasicauthsecret
\ No newline at end of file
+LANGFUSE_WORKER_PASSWORD=mybasicauthsecret
+# openssl rand -base64 32 used only here
+ENCRYPTION_KEY=6c16874e5c0f0cc74ddec00425fa99fbe9ffbe412b7d5d906a4b00005df91403
\ No newline at end of file
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml
index c9e30e7b80..68f01aa44e 100644
--- a/.github/workflows/pipeline.yml
+++ b/.github/workflows/pipeline.yml
@@ -111,6 +111,7 @@ jobs:
node-version: [20]
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
+ ENCRYPTION_KEY: ${{ secrets.ENCRYPTION_KEY }}
steps:
- name: Set Swap Space
uses: pierotofy/set-swap-space@master
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index 713a384a02..b40883983b 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -199,6 +199,15 @@ export type JobExecution = {
job_input_trace_id: string | null;
job_output_score_id: string | null;
};
+export type LlmApiKeys = {
+ id: string;
+ created_at: Generated<Timestamp>;
+ updated_at: Generated<Timestamp>;
+ provider: string;
+ display_secret_key: string;
+ secret_key: string;
+ project_id: string;
+};
export type Membership = {
project_id: string;
user_id: string;
@@ -425,6 +434,7 @@ export type DB = {
events: Events;
job_configurations: JobConfiguration;
job_executions: JobExecution;
+ llm_api_keys: LlmApiKeys;
membership_invitations: MembershipInvitation;
memberships: Membership;
models: Model;
diff --git a/packages/shared/prisma/migrations/20240423192655_add_llm_api_keys/migration.sql b/packages/shared/prisma/migrations/20240423192655_add_llm_api_keys/migration.sql
new file mode 100644
index 0000000000..341eb3f701
--- /dev/null
+++ b/packages/shared/prisma/migrations/20240423192655_add_llm_api_keys/migration.sql
@@ -0,0 +1,24 @@
+-- CreateTable
+CREATE TABLE "llm_api_keys" (
+ "id" TEXT NOT NULL,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "provider" TEXT NOT NULL,
+ "display_secret_key" TEXT NOT NULL,
+ "secret_key" TEXT NOT NULL,
+ "project_id" TEXT NOT NULL,
+
+ CONSTRAINT "llm_api_keys_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "llm_api_keys_id_key" ON "llm_api_keys"("id");
+
+-- CreateIndex
+CREATE INDEX "llm_api_keys_project_id_provider_idx" ON "llm_api_keys"("project_id", "provider");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "llm_api_keys_project_id_provider_key" ON "llm_api_keys"("project_id", "provider");
+
+-- AddForeignKey
+ALTER TABLE "llm_api_keys" ADD CONSTRAINT "llm_api_keys_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 43168e299f..3e6282d1ee 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -111,6 +111,7 @@ model Project {
EvalTemplate EvalTemplate[]
JobConfiguration JobConfiguration[]
JobExecution JobExecution[]
+ LlmApiKeys LlmApiKeys[]
PosthogIntegration PosthogIntegration[]
@@map("projects")
@@ -136,6 +137,23 @@ model ApiKey {
@@map("api_keys")
}
+model LlmApiKeys {
+ id String @id @unique @default(cuid())
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+
+ provider String
+ displaySecretKey String @map("display_secret_key")
+ secretKey String @map("secret_key")
+
+ projectId String @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+
+ @@unique([projectId, provider])
+ @@index([projectId, provider])
+ @@map("llm_api_keys")
+}
+
model Membership {
projectId String @map("project_id")
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.ts
index 27376b3a91..234b0168f1 100644
--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts
+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts
@@ -27,6 +27,7 @@ type LLMCompletionParams = {
modelParams: ModelParams;
functionCall?: LLMFunctionCall;
callbacks?: BaseCallbackHandler[];
+ apiKey?: string;
};
type FetchLLMCompletionParams = LLMCompletionParams & {
@@ -55,7 +56,8 @@ export async function fetchLLMCompletion(
export async function fetchLLMCompletion(
params: FetchLLMCompletionParams
): Promise<string | IterableReadableStream<Uint8Array> | unknown> {
- const { messages, modelParams, streaming, callbacks } = params;
+ // the apiKey must never be printed to the console
+ const { messages, modelParams, streaming, callbacks, apiKey } = params;
const finalMessages = messages.map((message) => {
if (message.role === ChatMessageRole.User)
return new HumanMessage(message.content);
@@ -68,7 +70,7 @@ export async function fetchLLMCompletion(
let chatModel: ChatOpenAI | ChatAnthropic;
if (modelParams.provider === ModelProvider.Anthropic) {
chatModel = new ChatAnthropic({
- anthropicApiKey: process.env.ANTHROPIC_API_KEY,
+ anthropicApiKey: apiKey,
modelName: modelParams.model,
temperature: modelParams.temperature,
maxTokens: modelParams.max_tokens,
@@ -77,7 +79,7 @@ export async function fetchLLMCompletion(
});
} else {
chatModel = new ChatOpenAI({
- openAIApiKey: process.env.OPENAI_API_KEY,
+ openAIApiKey: apiKey,
modelName: modelParams.model,
temperature: modelParams.temperature,
maxTokens: modelParams.max_tokens,
diff --git a/packages/shared/src/server/llm/types.ts b/packages/shared/src/server/llm/types.ts
index 57b63d29cb..8e479d9522 100644
--- a/packages/shared/src/server/llm/types.ts
+++ b/packages/shared/src/server/llm/types.ts
@@ -13,6 +13,7 @@ export enum ModelProvider {
Anthropic = "anthropic",
OpenAI = "openai",
}
+
export enum ChatMessageRole {
System = "system",
User = "user",
diff --git a/web/src/__tests__/llm-api-key.servertest.ts b/web/src/__tests__/llm-api-key.servertest.ts
new file mode 100644
index 0000000000..e38b0dc5bf
--- /dev/null
+++ b/web/src/__tests__/llm-api-key.servertest.ts
@@ -0,0 +1,92 @@
+/** @jest-environment node */
+/* eslint-disable @typescript-eslint/no-unsafe-member-access */
+
+import type { Session } from "next-auth";
+import { pruneDatabase } from "@/src/__tests__/test-utils";
+import { ModelProvider } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { appRouter } from "@/src/server/api/root";
+import { createInnerTRPCContext } from "@/src/server/api/trpc";
+
+describe("llmApiKey.all RPC", () => {
+ const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+
+ beforeEach(async () => await pruneDatabase());
+
+ const session: Session = {
+ expires: "1",
+ user: {
+ id: "user-1",
+ name: "Demo User",
+ projects: [
+ {
+ id: projectId,
+ role: "ADMIN",
+ name: "test",
+ },
+ ],
+ featureFlags: {
+ templateFlag: true,
+ evals: true,
+ },
+ admin: true,
+ },
+ };
+
+ const ctx = createInnerTRPCContext({ session });
+ const caller = appRouter.createCaller({ ...ctx, prisma });
+
+ it("should create an llm api key", async () => {
+ const secret = "test-secret";
+
+ await caller.llmApiKey.create({
+ projectId,
+ secretKey: secret,
+ provider: ModelProvider.OpenAI,
+ });
+
+ const llmApiKeys = await prisma.llmApiKeys.findMany({
+ where: {
+ projectId,
+ },
+ });
+
+ expect(llmApiKeys.length).toBe(1);
+ expect(llmApiKeys[0].projectId).toBe(projectId);
+ expect(llmApiKeys[0].secretKey).not.toBeNull();
+ expect(llmApiKeys[0].secretKey).not.toEqual(secret);
+ expect(llmApiKeys[0].provider).toBe(ModelProvider.OpenAI);
+ // this has to be 3 dots and the last 4 characters of the secret
+ expect(llmApiKeys[0].displaySecretKey).toMatch(/^...[a-zA-Z0-9]{4}$/);
+ });
+
+ it("should create and get an llm api key", async () => {
+ const secret = "test-secret";
+
+ await caller.llmApiKey.create({
+ projectId,
+ secretKey: secret,
+ provider: ModelProvider.OpenAI,
+ });
+
+ const dbLlmApiKeys = await prisma.llmApiKeys.findMany({
+ where: {
+ projectId,
+ },
+ });
+
+ expect(dbLlmApiKeys.length).toBe(1);
+
+ const llmApiKeys = await caller.llmApiKey.all({
+ projectId,
+ });
+
+ expect(llmApiKeys.data.length).toBe(1);
+ expect(llmApiKeys.data[0].provider).toBe(ModelProvider.OpenAI);
+ // this has to be 3 dots and the last 4 characters of the secret
+ expect(llmApiKeys.data[0].displaySecretKey).toMatch(/^...[a-zA-Z0-9]{4}$/);
+
+ // response must not contain the secret key itself
+ expect(llmApiKeys.data[0]).not.toHaveProperty("secretKey");
+ });
+});
diff --git a/web/src/__tests__/test-utils.ts b/web/src/__tests__/test-utils.ts
index 7911898a40..cac341b2b0 100644
--- a/web/src/__tests__/test-utils.ts
+++ b/web/src/__tests__/test-utils.ts
@@ -12,6 +12,7 @@ export const pruneDatabase = async () => {
await prisma.prompt.deleteMany();
await prisma.events.deleteMany();
await prisma.model.deleteMany();
+ await prisma.llmApiKeys.deleteMany();
};
export function createBasicAuthHeader(
diff --git a/web/src/ee/features/playground/server/chatCompletionHandler.ts b/web/src/ee/features/playground/server/chatCompletionHandler.ts
index 242ed08d76..fc8c38edd2 100644
--- a/web/src/ee/features/playground/server/chatCompletionHandler.ts
+++ b/web/src/ee/features/playground/server/chatCompletionHandler.ts
@@ -60,6 +60,10 @@ export default async function chatCompletionHandler(req: NextRequest) {
modelParams,
streaming: true,
callbacks: [new PosthogCallbackHandler("playground", body, token.sub)],
+ apiKey:
+ modelParams.provider === "openai"
+ ? env.OPENAI_API_KEY
+ : env.ANTHROPIC_API_KEY,
});
return new StreamingTextResponse(stream);
diff --git a/web/src/features/audit-logs/auditLog.ts b/web/src/features/audit-logs/auditLog.ts
index 1e4237e03d..6901aa4ba6 100644
--- a/web/src/features/audit-logs/auditLog.ts
+++ b/web/src/features/audit-logs/auditLog.ts
@@ -16,7 +16,8 @@ export type AuditableResource =
| "apiKey"
| "evalTemplate"
| "job"
- | "posthogIntegration";
+ | "posthogIntegration"
+ | "llmApiKey";
type AuditLog = {
resourceType: AuditableResource;
diff --git a/web/src/features/evals/components/eval-config-form.tsx b/web/src/features/evals/components/eval-config-form.tsx
index c89d14ce99..47288f0e04 100644
--- a/web/src/features/evals/components/eval-config-form.tsx
+++ b/web/src/features/evals/components/eval-config-form.tsx
@@ -120,7 +120,7 @@ export const EvalConfigForm = (props: {
});
function onSubmit(values: z.infer<typeof formSchema>) {
- posthog.capture("models:new_template_form");
+ posthog.capture("evals:new_config_form");
if (!getSelectedEvalTemplate) {
form.setError("evalTemplateId", {
diff --git a/web/src/features/evals/components/eval-template-detail.tsx b/web/src/features/evals/components/eval-template-detail.tsx
index 6f06d59438..d97084feee 100644
--- a/web/src/features/evals/components/eval-template-detail.tsx
+++ b/web/src/features/evals/components/eval-template-detail.tsx
@@ -44,6 +44,10 @@ export const EvalTemplateDetail = () => {
},
);
+ const llmApiKeys = api.llmApiKey.all.useQuery({
+ projectId: projectId,
+ });
+
return (
<div className="md:container">
<Header
@@ -72,12 +76,16 @@ export const EvalTemplateDetail = () => {
)
}
/>
- {allTemplates.isLoading || !allTemplates.data ? (
+ {allTemplates.isLoading ||
+ !allTemplates.data ||
+ llmApiKeys.isLoading ||
+ !llmApiKeys.data ? (
<div>Loading...</div>
) : (
<EvalTemplateForm
projectId={projectId}
existingEvalTemplate={template.data ?? undefined}
+ existingLlmApiKeys={llmApiKeys.data?.data ?? []}
isEditing={isEditing}
setIsEditing={setIsEditing}
/>
diff --git a/web/src/features/evals/components/template-form.tsx b/web/src/features/evals/components/template-form.tsx
index 3fec0d58cf..7e119417e2 100644
--- a/web/src/features/evals/components/template-form.tsx
+++ b/web/src/features/evals/components/template-form.tsx
@@ -1,5 +1,5 @@
import { usePostHog } from "posthog-js/react";
-import { useEffect, useState } from "react";
+import { useCallback, useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { Input } from "@/src/components/ui/input";
@@ -14,7 +14,7 @@ import {
FormMessage,
} from "@/src/components/ui/form";
import { Textarea } from "@/src/components/ui/textarea";
-import { api } from "@/src/utils/api";
+import { type RouterOutputs, api } from "@/src/utils/api";
import { zodResolver } from "@hookform/resolvers/zod";
import { extractVariables, getIsCharOrUnderscore } from "@/src/utils/string";
import router from "next/router";
@@ -30,6 +30,8 @@ import {
type UIModelParams,
} from "@langfuse/shared";
import { PromptDescription } from "@/src/features/prompts/components/prompt-description";
+import Link from "next/dist/client/link";
+import { ArrowTopRightIcon } from "@radix-ui/react-icons";
const formSchema = z.object({
name: z.string().min(1, "Enter a name"),
@@ -54,11 +56,13 @@ const formSchema = z.object({
model: EvalModelNames,
outputScore: z.string(),
outputReasoning: z.string(),
+ apiKey: z.string({ required_error: "No LLM API key found." }),
});
export const EvalTemplateForm = (props: {
projectId: string;
existingEvalTemplate?: EvalTemplate;
+ existingLlmApiKeys: RouterOutputs["llmApiKey"]["all"]["data"];
onFormSuccess?: () => void;
isEditing?: boolean;
setIsEditing?: (isEditing: boolean) => void;
@@ -76,14 +80,25 @@ export const EvalTemplateForm = (props: {
setModelParams((prev) => ({ ...prev, [key]: value }));
};
+ const getModelProvider = useCallback((model: string) => {
+ return evalLLMModels.find((m) => m.model === model)?.provider;
+ }, []);
+
+ const getApiKeyForModel = useCallback(
+ (model: string) => {
+ const modelProvider = getModelProvider(model);
+ return props.existingLlmApiKeys.find((k) => k.provider === modelProvider);
+ },
+ [getModelProvider, props.existingLlmApiKeys],
+ );
+
+ const defaultModel = props.existingEvalTemplate?.model ?? "gpt-3.5-turbo";
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
disabled: !props.isEditing,
defaultValues: {
name: props.existingEvalTemplate?.name ?? "",
- model: EvalModelNames.parse(
- props.existingEvalTemplate?.model ?? "gpt-3.5-turbo",
- ),
+ model: EvalModelNames.parse(defaultModel),
prompt: props.existingEvalTemplate?.prompt ?? undefined,
variables: props.existingEvalTemplate?.vars ?? [],
outputReasoning: props.existingEvalTemplate
@@ -92,6 +107,7 @@ export const EvalTemplateForm = (props: {
outputScore: props.existingEvalTemplate
? OutputSchema.parse(props.existingEvalTemplate?.outputSchema).score
: undefined,
+ apiKey: defaultModel ? getApiKeyForModel(defaultModel)?.id : undefined,
},
});
@@ -139,8 +155,7 @@ export const EvalTemplateForm = (props: {
});
function onSubmit(values: z.infer<typeof formSchema>) {
- console.log("submitting", values);
- posthog.capture("models:new_template_form");
+ posthog.capture("evals:new_template_form");
createEvalTemplateMutation
.mutateAsync({
@@ -272,11 +287,57 @@ export const EvalTemplateForm = (props: {
/>
</div>
<div className="col-span-1 row-span-3">
- <ModelParameters
- {...{ modelParams, updateModelParam }}
- availableModels={[...evalLLMModels]}
- disabled={!props.isEditing}
- />
+ <div className="flex flex-col gap-6">
+ <ModelParameters
+ {...{ modelParams, updateModelParam }}
+ availableModels={[...evalLLMModels]}
+ disabled={!props.isEditing}
+ />
+ <FormField
+ control={form.control}
+ name="apiKey"
+ render={({ field }) => {
+ const errorMessage =
+ form.getFieldState("apiKey").error?.message;
+
+ return (
+ <FormItem>
+ <FormLabel>API key</FormLabel>
+ <Input
+ {...field}
+ value={
+ getApiKeyForModel(form.getValues("model"))
+ ?.displaySecretKey
+ }
+ type="text"
+ disabled
+ />
+ {/* Custom form message to include a link to the already existing prompt */}
+
+ {form.getFieldState("apiKey").error ? (
+ <div className="flex flex-col text-sm font-medium text-destructive">
+ <p className="text-sm font-medium text-destructive">
+ {errorMessage}
+ </p>
+ {errorMessage?.includes("No LLM API key found.") ? (
+ <Link
+ href={`/project/${props.projectId}/settings`}
+ className="flex flex-row"
+ >
+ Create a new API key here. <ArrowTopRightIcon />
+ </Link>
+ ) : null}
+ </div>
+ ) : null}
+ <FormDescription>
+ The API key is used for each evaluation and will incur
+ costs.
+ </FormDescription>
+ </FormItem>
+ );
+ }}
+ />
+ </div>
</div>
{props.isEditing && (
diff --git a/web/src/features/llm-api-key/server/router.ts b/web/src/features/llm-api-key/server/router.ts
new file mode 100644
index 0000000000..385c2cf314
--- /dev/null
+++ b/web/src/features/llm-api-key/server/router.ts
@@ -0,0 +1,140 @@
+import { z } from "zod";
+
+import {
+ createTRPCRouter,
+ protectedProjectProcedure,
+} from "@/src/server/api/trpc";
+import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { env } from "@/src/env.mjs";
+import { CreateLlmApiKey } from "@/src/features/llm-api-key/types";
+import { encrypt } from "@langfuse/shared/encryption";
+
+export function getDisplaySecretKey(secretKey: string) {
+ return "..." + secretKey.slice(-4);
+}
+
+export const LlmApiKey = z
+ .object({
+ id: z.string(),
+ projectId: z.string(),
+ provider: z.string(),
+ createdAt: z.date(),
+ updatedAt: z.date(),
+ displaySecretKey: z.string(),
+ })
+ // strict mode to prevent extra keys. Thorws error otherwise
+ // https://github.com/colinhacks/zod?tab=readme-ov-file#strict
+ .strict();
+
+export const llmApiKeyRouter = createTRPCRouter({
+ create: protectedProjectProcedure
+ .input(CreateLlmApiKey)
+ .mutation(async ({ input, ctx }) => {
+ try {
+ if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined) {
+ throw new Error("Evals available in cloud only");
+ }
+ throwIfNoAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "llmApiKeys:create",
+ });
+
+ const key = await ctx.prisma.llmApiKeys.create({
+ data: {
+ projectId: input.projectId,
+ secretKey: encrypt(input.secretKey),
+ displaySecretKey: getDisplaySecretKey(input.secretKey),
+ provider: input.provider,
+ },
+ });
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "llmApiKey",
+ resourceId: key.id,
+ action: "create",
+ });
+ } catch (e) {
+ console.log(e);
+ throw e;
+ }
+ }),
+ delete: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ id: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined) {
+ throw new Error("Evals available in cloud only");
+ }
+ throwIfNoAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "llmApiKeys:delete",
+ });
+
+ await ctx.prisma.llmApiKeys.delete({
+ where: {
+ id: input.id,
+ projectId: input.projectId,
+ },
+ });
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "llmApiKey",
+ resourceId: input.id,
+ action: "delete",
+ });
+ }),
+ all: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined) {
+ throw new Error("Evals available in cloud only");
+ }
+
+ throwIfNoAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "llmApiKeys:read",
+ });
+
+ const apiKeys = z.array(LlmApiKey).parse(
+ await ctx.prisma.llmApiKeys.findMany({
+ // we must not return the secret key via the API, hence not selected
+ select: {
+ id: true,
+ createdAt: true,
+ updatedAt: true,
+ provider: true,
+ displaySecretKey: true,
+ projectId: true,
+ },
+ where: {
+ projectId: input.projectId,
+ },
+ }),
+ );
+
+ const count = await ctx.prisma.llmApiKeys.count({
+ where: {
+ projectId: input.projectId,
+ },
+ });
+
+ return {
+ data: apiKeys, // does not contain the secret key
+ totalCount: count,
+ };
+ }),
+});
diff --git a/web/src/features/llm-api-key/types.ts b/web/src/features/llm-api-key/types.ts
new file mode 100644
index 0000000000..561fe7eac8
--- /dev/null
+++ b/web/src/features/llm-api-key/types.ts
@@ -0,0 +1,13 @@
+import { z } from "zod";
+import { ModelProvider } from "@langfuse/shared";
+
+export const ZodModelProvider = z.enum([
+ ModelProvider.Anthropic,
+ ModelProvider.OpenAI,
+]);
+
+export const CreateLlmApiKey = z.object({
+ projectId: z.string(),
+ secretKey: z.string().min(1),
+ provider: z.literal(ModelProvider.OpenAI),
+});
diff --git a/web/src/features/public-api/components/LLMApiKeyList.tsx b/web/src/features/public-api/components/LLMApiKeyList.tsx
new file mode 100644
index 0000000000..1e1b6edac9
--- /dev/null
+++ b/web/src/features/public-api/components/LLMApiKeyList.tsx
@@ -0,0 +1,310 @@
+import Header from "@/src/components/layouts/header";
+import { Button } from "@/src/components/ui/button";
+import { Card } from "@/src/components/ui/card";
+import {
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/src/components/ui/dialog";
+import {
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+ Form,
+} from "@/src/components/ui/form";
+import { Input } from "@/src/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/src/components/ui/select";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/src/components/ui/table";
+import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
+import { api } from "@/src/utils/api";
+import { cn } from "@/src/utils/tailwind";
+import { type RouterOutput } from "@/src/utils/types";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { ModelProvider, evalLLMModels } from "@langfuse/shared";
+import { DialogDescription } from "@radix-ui/react-dialog";
+import { PlusIcon, TrashIcon } from "lucide-react";
+import { usePostHog } from "posthog-js/react";
+import { useState } from "react";
+import { useForm } from "react-hook-form";
+import { z } from "zod";
+
+export function LlmApiKeyList(props: { projectId: string }) {
+ const hasAccess = useHasAccess({
+ projectId: props.projectId,
+ scope: "llmApiKeys:read",
+ });
+
+ const apiKeys = api.llmApiKey.all.useQuery(
+ {
+ projectId: props.projectId,
+ },
+ {
+ enabled: hasAccess,
+ },
+ );
+
+ if (!hasAccess) return null;
+
+ return (
+ <div>
+ <Header title="LLM API keys" level="h3" />
+ <Card className="mb-4">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="hidden text-gray-900 md:table-cell">
+ Created
+ </TableHead>
+ <TableHead className="hidden text-gray-900 md:table-cell">
+ Provider
+ </TableHead>
+ <TableHead className="text-gray-900">Secret Key</TableHead>
+ <TableHead />
+ </TableRow>
+ </TableHeader>
+ <TableBody className="text-gray-500">
+ {apiKeys.data?.data.map((apiKey) => (
+ <TableRow key={apiKey.id} className="hover:bg-transparent">
+ <TableCell className="hidden md:table-cell">
+ {apiKey.createdAt.toLocaleDateString()}
+ </TableCell>
+ <TableCell className="font-mono">{apiKey.provider}</TableCell>
+ <TableCell className="font-mono">
+ {apiKey.displaySecretKey}
+ </TableCell>
+ <TableCell>
+ <DeleteApiKeyButton
+ projectId={props.projectId}
+ apiKeyId={apiKey.id}
+ />
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </Card>
+ <CreateLlmApiKeyComponent
+ projectId={props.projectId}
+ existingApiKeys={apiKeys.data?.data ?? []}
+ />
+ </div>
+ );
+}
+
+// show dialog to let user confirm that this is a destructive action
+function DeleteApiKeyButton(props: { projectId: string; apiKeyId: string }) {
+ const posthog = usePostHog();
+ const hasAccess = useHasAccess({
+ projectId: props.projectId,
+ scope: "llmApiKeys:delete",
+ });
+
+ const utils = api.useUtils();
+ const mutDeleteApiKey = api.llmApiKey.delete.useMutation({
+ onSuccess: () => utils.llmApiKey.invalidate(),
+ });
+ const [open, setOpen] = useState(false);
+
+ if (!hasAccess) return null;
+
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogTrigger asChild>
+ <Button variant="ghost" size="icon">
+ <TrashIcon className="h-4 w-4" />
+ </Button>
+ </DialogTrigger>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle className="mb-5">Delete API key</DialogTitle>
+ </DialogHeader>
+ <DialogDescription>
+ Are you sure you want to delete this API key? This action cannot be
+ undone.
+ </DialogDescription>
+ <DialogFooter>
+ <Button
+ variant="destructive"
+ onClick={() => {
+ mutDeleteApiKey
+ .mutateAsync({
+ projectId: props.projectId,
+ id: props.apiKeyId,
+ })
+ .then(() => {
+ posthog.capture("project_settings:llm_api_key_delete");
+ setOpen(false);
+ })
+ .catch((error) => {
+ console.error(error);
+ });
+ }}
+ loading={mutDeleteApiKey.isLoading}
+ >
+ Permanently delete
+ </Button>
+ <Button variant="ghost" onClick={() => setOpen(false)}>
+ Cancel
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+const formSchema = z.object({
+ secretKey: z.string().min(1),
+ provider: z.literal(ModelProvider.OpenAI),
+});
+
+export function CreateLlmApiKeyComponent(props: {
+ projectId: string;
+ existingApiKeys: RouterOutput["llmApiKey"]["all"]["data"];
+}) {
+ const posthog = usePostHog();
+ const [open, setOpen] = useState(false);
+ const hasAccess = useHasAccess({
+ projectId: props.projectId,
+ scope: "llmApiKeys:create",
+ });
+
+ const utils = api.useUtils();
+ const mutCreateLlmApiKey = api.llmApiKey.create.useMutation({
+ onSuccess: () => utils.llmApiKey.invalidate(),
+ });
+
+ const form = useForm<z.infer<typeof formSchema>>({
+ resolver: zodResolver(formSchema),
+ defaultValues: {
+ secretKey: "",
+ provider: ModelProvider.OpenAI,
+ },
+ });
+
+ if (!hasAccess) return null;
+
+ function onSubmit(values: z.infer<typeof formSchema>) {
+ if (
+ props.existingApiKeys.map((k) => k.provider).includes(values.provider)
+ ) {
+ form.setError("provider", {
+ type: "manual",
+ message: "There already exists an API key for this provider.",
+ });
+ return;
+ }
+ posthog.capture("project_settings:llm_api_key_create");
+
+ return mutCreateLlmApiKey
+ .mutateAsync({
+ projectId: props.projectId,
+ secretKey: values.secretKey,
+ provider: values.provider,
+ })
+ .then(() => {
+ form.reset();
+ setOpen(false);
+ })
+ .catch((error) => {
+ console.error(error);
+ });
+ }
+
+ return (
+ <>
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogTrigger asChild>
+ <Button variant="secondary" loading={mutCreateLlmApiKey.isLoading}>
+ <PlusIcon className="-ml-0.5 mr-1.5 h-5 w-5" aria-hidden="true" />
+ Add new LLM API key
+ </Button>
+ </DialogTrigger>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Store a LLM API Key</DialogTitle>
+ </DialogHeader>
+ <Form {...form}>
+ <form
+ className={cn("flex flex-col gap-6")}
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
+ onSubmit={form.handleSubmit(onSubmit)}
+ >
+ <FormField
+ control={form.control}
+ name="secretKey"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>API Key</FormLabel>
+ <FormControl>
+ <Input placeholder="sk-proj-...Uwj9" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="provider"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>LLM Provider</FormLabel>
+ <Select
+ defaultValue={field.value}
+ onValueChange={(value) =>
+ field.onChange(value as ModelProvider[number])
+ }
+ >
+ <FormControl>
+ <SelectTrigger>
+ <SelectValue placeholder="Select a LLM provider" />
+ </SelectTrigger>
+ </FormControl>
+ <SelectContent>
+ {Array.from(
+ new Set(
+ evalLLMModels.map((models) => models.provider),
+ ),
+ ).map((provider) => (
+ <SelectItem value={provider} key={provider}>
+ {provider}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <Button
+ type="submit"
+ className="w-full"
+ loading={form.formState.isSubmitting}
+ >
+ Create API key
+ </Button>
+ <FormMessage />
+ </form>
+ </Form>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+}
diff --git a/web/src/features/rbac/constants/roleAccessRights.ts b/web/src/features/rbac/constants/roleAccessRights.ts
index e938f0045b..93d2902f19 100644
--- a/web/src/features/rbac/constants/roleAccessRights.ts
+++ b/web/src/features/rbac/constants/roleAccessRights.ts
@@ -33,6 +33,10 @@ const scopes = [
"evalTemplate:read",
"job:read",
"job:CUD",
+
+ "llmApiKeys:read",
+ "llmApiKeys:create",
+ "llmApiKeys:delete",
] as const;
// type string of all Resource:Action, e.g. "members:read"
@@ -63,6 +67,9 @@ export const roleAccessRights: Record<MembershipRole, Scope[]> = {
"evalTemplate:read",
"job:CUD",
"job:read",
+ "llmApiKeys:read",
+ "llmApiKeys:create",
+ "llmApiKeys:delete",
],
ADMIN: [
"project:update",
@@ -86,6 +93,9 @@ export const roleAccessRights: Record<MembershipRole, Scope[]> = {
"evalTemplate:read",
"job:CUD",
"job:read",
+ "llmApiKeys:read",
+ "llmApiKeys:create",
+ "llmApiKeys:delete",
],
MEMBER: [
"members:read",
diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.ts
index ce4fa74c73..25ebba74c7 100644
--- a/web/src/pages/api/public/ingestion.ts
+++ b/web/src/pages/api/public/ingestion.ts
@@ -427,8 +427,7 @@ export const sendToWorkerIfEnvironmentConfigured = async (
if (
env.LANGFUSE_WORKER_HOST &&
env.LANGFUSE_WORKER_PASSWORD &&
- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION &&
- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== "DEV"
+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION
) {
const traceEvents = batchResults
.filter((result) => result.type === eventTypes.TRACE_CREATE) // we only have create, no update.
diff --git a/web/src/pages/project/[projectId]/evals/templates/new.tsx b/web/src/pages/project/[projectId]/evals/templates/new.tsx
index a6b0c5b036..cf1e0dc00f 100644
--- a/web/src/pages/project/[projectId]/evals/templates/new.tsx
+++ b/web/src/pages/project/[projectId]/evals/templates/new.tsx
@@ -1,5 +1,7 @@
import Header from "@/src/components/layouts/header";
import { EvalTemplateForm } from "@/src/features/evals/components/template-form";
+import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
+import { api } from "@/src/utils/api";
import { useRouter } from "next/router";
@@ -7,10 +9,26 @@ export default function NewTemplatesPage() {
const router = useRouter();
const projectId = router.query.projectId as string;
- return (
+ const hasAccess = useHasAccess({ projectId, scope: "llmApiKeys:read" });
+
+ if (!hasAccess) {
+ return null;
+ }
+
+ const llmApiKeys = api.llmApiKey.all.useQuery({
+ projectId: projectId,
+ });
+
+ return llmApiKeys.isLoading || !llmApiKeys.data ? (
+ <div>Loading...</div>
+ ) : (
<div className="md:container">
<Header title="Create eval template" />
- <EvalTemplateForm projectId={projectId} isEditing={true} />
+ <EvalTemplateForm
+ projectId={projectId}
+ isEditing={true}
+ existingLlmApiKeys={llmApiKeys.data?.data ?? []}
+ />
</div>
);
}
diff --git a/web/src/pages/project/[projectId]/settings.tsx b/web/src/pages/project/[projectId]/settings.tsx
index 1bcfd3d70e..fe298d9137 100644
--- a/web/src/pages/project/[projectId]/settings.tsx
+++ b/web/src/pages/project/[projectId]/settings.tsx
@@ -15,6 +15,7 @@ import { env } from "@/src/env.mjs";
import { Card } from "@tremor/react";
import { Button } from "@/src/components/ui/button";
import Link from "next/link";
+import { LlmApiKeyList } from "@/src/features/public-api/components/LLMApiKeyList";
export default function SettingsPage() {
const router = useRouter();
@@ -25,6 +26,7 @@ export default function SettingsPage() {
<div className="flex flex-col gap-10">
<HostNameProject />
<ApiKeyList projectId={projectId} />
+ <LlmApiKeyList projectId={projectId} />
<ProjectMembersTable projectId={projectId} />
<ProjectUsageChart projectId={projectId} />
<Integrations projectId={projectId} />
diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.ts
index 4bb1db549e..e861e371fb 100644
--- a/web/src/server/api/root.ts
+++ b/web/src/server/api/root.ts
@@ -16,6 +16,7 @@ import { promptRouter } from "@/src/features/prompts/server/prompt-router";
import { modelRouter } from "@/src/server/api/routers/models";
import { evalRouter } from "@/src/features/evals/server/router";
import { posthogIntegrationRouter } from "@/src/features/posthog-integration/posthog-integration-router";
+import { llmApiKeyRouter } from "@/src/features/llm-api-key/server/router";
/**
* This is the primary router for your server.
@@ -40,6 +41,7 @@ export const appRouter = createTRPCRouter({
models: modelRouter,
evals: evalRouter,
posthogIntegration: posthogIntegrationRouter,
+ llmApiKey: llmApiKeyRouter,
});
// export type definition of API
diff --git a/worker/src/__tests__/eval-service.test.ts b/worker/src/__tests__/eval-service.test.ts
index 053a57179c..eaa0a0aad5 100644
--- a/worker/src/__tests__/eval-service.test.ts
+++ b/worker/src/__tests__/eval-service.test.ts
@@ -10,6 +10,7 @@ import Decimal from "decimal.js";
import { pruneDatabase } from "./utils";
import { sql } from "kysely";
import { variableMappingList } from "@langfuse/shared";
+import { encrypt } from "@langfuse/shared/encryption";
vi.mock("../redis/consumer", () => ({
evalQueue: {
@@ -232,7 +233,7 @@ describe("create eval jobs", () => {
});
describe("execute evals", () => {
- test("evals a valid eval event", async () => {
+ test("evals a valid event", async () => {
await pruneDatabase();
const traceId = randomUUID();
@@ -301,6 +302,17 @@ describe("execute evals", () => {
})
.execute();
+ await kyselyPrisma.$kysely
+ .insertInto("llm_api_keys")
+ .values({
+ id: randomUUID(),
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ secret_key: encrypt(String(process.env.OPENAI_API_KEY)),
+ provider: "openai",
+ display_secret_key: "123456",
+ })
+ .execute();
+
const payload = {
projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
jobExecutionId: jobExecutionId,
@@ -332,6 +344,97 @@ describe("execute evals", () => {
expect(scores[0].comment).not.toBeNull();
}, 10_000);
+ test("fails to eval without llm api key", async () => {
+ await pruneDatabase();
+ const traceId = randomUUID();
+
+ await kyselyPrisma.$kysely
+ .insertInto("traces")
+ .values({
+ id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ user_id: "a",
+ input: { input: "This is a great prompt" },
+ output: { output: "This is a great response" },
+ })
+ .execute();
+
+ const templateId = randomUUID();
+ await kyselyPrisma.$kysely
+ .insertInto("eval_templates")
+ .values({
+ id: templateId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ name: "test-template",
+ version: 1,
+ prompt: "Please evaluate toxicity {{input}} {{output}}",
+ model: "gpt-3.5-turbo",
+ model_params: {},
+ output_schema: {
+ reasoning: "Please explain your reasoning",
+ score: "Please provide a score between 0 and 1",
+ },
+ })
+ .executeTakeFirst();
+
+ const jobConfiguration = await prisma.jobConfiguration.create({
+ data: {
+ id: randomUUID(),
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ filter: [
+ {
+ type: "string",
+ value: "a",
+ column: "User ID",
+ operator: "contains",
+ },
+ ],
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: "traces",
+ scoreName: "score",
+ variableMapping: JSON.parse("[]"),
+ evalTemplateId: templateId,
+ },
+ });
+
+ const jobExecutionId = randomUUID();
+
+ await kyselyPrisma.$kysely
+ .insertInto("job_executions")
+ .values({
+ id: jobExecutionId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ job_configuration_id: jobConfiguration.id,
+ status: sql`'PENDING'::"JobExecutionStatus"`,
+ start_time: new Date(),
+ job_input_trace_id: traceId,
+ })
+ .execute();
+
+ const payload = {
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ jobExecutionId: jobExecutionId,
+ };
+
+ await expect(evaluate({ event: payload })).rejects.toThrowError(
+ "API key for provider openai and project 7a88fb47-b4e2-43b8-a06c-a5ce950dc53a not found."
+ );
+
+ const jobs = await kyselyPrisma.$kysely
+ .selectFrom("job_executions")
+ .selectAll()
+ .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .execute();
+
+ expect(jobs.length).toBe(1);
+ expect(jobs[0].project_id).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+ expect(jobs[0].job_input_trace_id).toBe(traceId);
+ // the job will be failed when the exception is caught in the worker consumer
+ expect(jobs[0].status.toString()).toBe("PENDING");
+ }, 10_000);
+
test("evals should cancel if job is cancelled", async () => {
await pruneDatabase();
const traceId = randomUUID();
diff --git a/worker/src/__tests__/utils.ts b/worker/src/__tests__/utils.ts
index e70a01b6e9..848f536ab8 100644
--- a/worker/src/__tests__/utils.ts
+++ b/worker/src/__tests__/utils.ts
@@ -15,4 +15,5 @@ export const pruneDatabase = async () => {
await prisma.jobExecution.deleteMany();
await prisma.jobConfiguration.deleteMany();
await prisma.evalTemplate.deleteMany();
+ await prisma.llmApiKeys.deleteMany();
};
diff --git a/worker/src/eval-service.ts b/worker/src/eval-service.ts
index fc3313ebc6..00a3ecff49 100644
--- a/worker/src/eval-service.ts
+++ b/worker/src/eval-service.ts
@@ -17,6 +17,7 @@ import {
availableEvalVariables,
} from "@langfuse/shared";
import { Prisma } from "@langfuse/shared";
+import { decrypt } from "@langfuse/shared/encryption";
import { kyselyPrisma, prisma } from "@langfuse/shared/src/db";
import { randomUUID } from "crypto";
import { evalQueue } from "./redis/consumer";
@@ -250,8 +251,27 @@ export const evaluate = async ({
throw new Error(`Model ${evalModel} provider not found`);
}
+ // the apiKey.secret_key must never be printed to the console or returned to the client.
+ const apiKey = await kyselyPrisma.$kysely
+ .selectFrom("llm_api_keys")
+ .selectAll()
+ .where("project_id", "=", event.projectId)
+ .where("provider", "=", provider)
+ .executeTakeFirst();
+
+ if (!apiKey) {
+ console.log(
+ `API key for provider ${provider} and project ${event.projectId} not found.`
+ );
+ // this will fail the eval execution if a user deletes the API key.
+ throw new Error(
+ `API key for provider ${provider} and project ${event.projectId} not found.`
+ );
+ }
+
const completion = await fetchLLMCompletion({
streaming: false,
+ apiKey: decrypt(apiKey.secret_key), // decrypt the secret key
messages: [{ role: ChatMessageRole.System, content: prompt }],
modelParams: {
provider: provider,
diff --git a/worker/tsconfig.json b/worker/tsconfig.json
index f3f996ca1c..f10a6b15b5 100644
--- a/worker/tsconfig.json
+++ b/worker/tsconfig.json
@@ -2,8 +2,8 @@
"extends": "@repo/typescript-config/base.json",
"compilerOptions": {
"esModuleInterop": true,
- "moduleResolution": "Node",
- "module": "commonjs",
+ "moduleResolution": "Node16",
+ "module": "Node16",
"declaration": false,
"declarationMap": false,
"lib": ["ES2015"],