🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat: adds custom LLM endpoints (#2190)
Hassieb Pakzad29f1072da414
diff --git a/.env.dev.example b/.env.dev.exampleindex 4f3820c96a..80d67b046f 100644--- a/.env.dev.example+++ b/.env.dev.example@@ -34,10 +34,6 @@ S3_SECRET_ACCESS_KEY=S3_BUCKET_NAME=S3_REGION=-# Prompt playground-OPENAI_API_KEY=""-ANTHROPIC_API_KEY=""-# Set during docker build of application# Used to disable environment verification at build time# DOCKER_BUILD=1diff --git a/.env.local.example b/.env.local.exampleindex f05702a31c..d3e03072bd 100644--- a/.env.local.example+++ b/.env.local.example@@ -13,11 +13,6 @@ NEXTAUTH_URL="http://localhost:3000"LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES="false"SALT="salt"--# Prompt playground-OPENAI_API_KEY=""-ANTHROPIC_API_KEY=""-# RedisREDIS_HOST="127.0.0.1"REDIS_PORT=6379diff --git a/.env.prod.example b/.env.prod.exampleindex d4a53ecbc7..6af5ffc340 100644--- a/.env.prod.example+++ b/.env.prod.example@@ -127,10 +127,6 @@ LANGFUSE_CSP_ENFORCE_HTTPS="true"# NEXT_PUBLIC_TURNSTILE_SITE_KEY=# TURNSTILE_SECRET_KEY=-# Prompt playground-# OPENAI_API_KEY=""-# ANTHROPIC_API_KEY=""-# Betterstack# LANGFUSE_TEAM_BETTERSTACK_TOKEN=diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.tsindex 2541d46613..c7b950291e 100644--- a/packages/shared/prisma/generated/types.ts+++ b/packages/shared/prisma/generated/types.ts@@ -152,6 +152,7 @@ export type EvalTemplate = {version: number;prompt: string;model: string;+ provider: string;model_params: unknown;vars: Generated<string[]>;output_schema: unknown;@@ -199,8 +200,12 @@ export type LlmApiKeys = {created_at: Generated<Timestamp>;updated_at: Generated<Timestamp>;provider: string;+ adapter: string;display_secret_key: string;secret_key: string;+ base_url: string | null;+ custom_models: string[];+ with_default_models: Generated<boolean>;project_id: string;};export type MembershipInvitation = {diff --git a/packages/shared/prisma/migrations/20240611105521_llm_api_keys_custom_endpoints/migration.sql b/packages/shared/prisma/migrations/20240611105521_llm_api_keys_custom_endpoints/migration.sqlnew file mode 100644index 0000000000..b43dad5668--- /dev/null+++ b/packages/shared/prisma/migrations/20240611105521_llm_api_keys_custom_endpoints/migration.sql@@ -0,0 +1,24 @@+BEGIN;++ ALTER TABLE "llm_api_keys"+ ADD COLUMN "base_url" TEXT,+ ADD COLUMN "adapter" TEXT,+ ADD COLUMN "custom_models" TEXT[] NOT NULL DEFAULT '{}'::TEXT[],+ ADD COLUMN "with_default_models" BOOLEAN NOT NULL DEFAULT true;++ UPDATE "llm_api_keys"+ SET "adapter" = "provider";++ ALTER TABLE "llm_api_keys"+ ALTER COLUMN "adapter" SET NOT NULL;++ ALTER TABLE "eval_templates"+ ADD COLUMN "provider" TEXT;++ UPDATE "eval_templates"+ SET "provider" = 'openai';++ ALTER TABLE "eval_templates"+ ALTER COLUMN "provider" SET NOT NULL;++COMMIT;\ No newline at end of filediff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex b0f98cfe92..d6c7d624ce 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -144,9 +144,13 @@ model LlmApiKeys {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")+ provider String+ adapter String // This controls the interface that is used to connect with the LLM, e.g. 'openai' or 'anthropic'+ displaySecretKey String @map("display_secret_key")+ secretKey String @map("secret_key")+ baseURL String? @map("base_url")+ customModels String[] @map("custom_models")+ withDefaultModels Boolean @default(true) @map("with_default_models")projectId String @map("project_id")project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)@@ -664,6 +668,7 @@ model EvalTemplate {version Intprompt Stringmodel String+ provider StringmodelParams Json @map("model_params")vars String[] @default([])outputSchema Json @map("output_schema")diff --git a/packages/shared/prisma/seed.ts b/packages/shared/prisma/seed.tsindex 2fa24eff35..010c7db3f4 100644--- a/packages/shared/prisma/seed.ts+++ b/packages/shared/prisma/seed.ts@@ -184,6 +184,7 @@ async function main() {secretKey: encrypt(OPENAI_API_KEY),displaySecretKey: getDisplaySecretKey(OPENAI_API_KEY),provider: "openai",+ adapter: "openai",},});} else {@@ -209,6 +210,7 @@ async function main() {"Please evaluate the toxicity of the following text {{input}} {{output}}",model: "gpt-3.5-turbo",vars: ["input", "output"],+ provider: "openai",outputSchema: {score: "provide a score between 0 and 1",reasoning: "one sentence reasoning for the score",diff --git a/packages/shared/src/features/evals/types.ts b/packages/shared/src/features/evals/types.tsindex 48f6fbfadd..637e914cb7 100644--- a/packages/shared/src/features/evals/types.ts+++ b/packages/shared/src/features/evals/types.ts@@ -1,5 +1,5 @@import z from "zod";-import { ModelProvider, UIModelParams } from "../..";+import { LLMAdapter } from "../..";export const langfuseObjects = ["trace",@@ -77,38 +77,15 @@ export const availableEvalVariables = [},];-export const evalLLMModels: UIModelParams[] = [- {- provider: { value: ModelProvider.OpenAI, enabled: true },- model: { value: "gpt-3.5-turbo", enabled: true },- temperature: { value: 1, enabled: true },- maxTemperature: { value: 2, enabled: true },- max_tokens: { value: 256, enabled: true },- top_p: { value: 1, enabled: true },- },- {- provider: { value: ModelProvider.OpenAI, enabled: true },- model: { value: "gpt-4-turbo-preview", enabled: true },- temperature: { value: 1, enabled: true },- maxTemperature: { value: 2, enabled: true },- max_tokens: { value: 256, enabled: true },- top_p: { value: 1, enabled: true },- },- {- provider: { value: ModelProvider.OpenAI, enabled: true },- model: { value: "gpt-4o", enabled: true },- temperature: { value: 1, enabled: true },- maxTemperature: { value: 2, enabled: true },- max_tokens: { value: 256, enabled: true },- top_p: { value: 1, enabled: true },- },-] as const;--export const EvalModelNames = z.enum([- "gpt-3.5-turbo",- "gpt-4-turbo-preview",- "gpt-4o",-]);+export const evalModelsByAdapter: Record<LLMAdapter, string[]> = {+ [LLMAdapter.OpenAI]: [+ "gpt-4o",+ "gpt-4-turbo-preview",+ "gpt-3.5-turbo",+ ] as const,+ [LLMAdapter.Anthropic]: [] as const,+ [LLMAdapter.Azure]: [] as const,+};export const OutputSchema = z.object({reasoning: z.string(),diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.tsindex 7936348f87..68647182c9 100644--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts@@ -17,7 +17,7 @@ import {ChatMessageRole,LLMFunctionCall,ModelParams,- ModelProvider,+ LLMAdapter,} from "./types";import zodToJsonSchema from "zod-to-json-schema";import { JsonOutputFunctionsParser } from "langchain/output_parsers";@@ -27,7 +27,9 @@ type LLMCompletionParams = {modelParams: ModelParams;functionCall?: LLMFunctionCall;callbacks?: BaseCallbackHandler[];+ baseURL?: string;apiKey?: string;+ maxRetries?: number;};type FetchLLMCompletionParams = LLMCompletionParams & {@@ -57,7 +59,16 @@ export async function fetchLLMCompletion(params: FetchLLMCompletionParams): Promise<string | IterableReadableStream<Uint8Array> | unknown> {// the apiKey must never be printed to the console- const { messages, modelParams, streaming, callbacks, apiKey } = params;+ const {+ messages,+ modelParams,+ streaming,+ callbacks,+ apiKey,+ baseURL,+ maxRetries,+ } = params;+const finalMessages = messages.map((message) => {if (message.role === ChatMessageRole.User)return new HumanMessage(message.content);@@ -68,16 +79,18 @@ export async function fetchLLMCompletion(});let chatModel: ChatOpenAI | ChatAnthropic;- if (modelParams.provider === ModelProvider.Anthropic) {+ if (modelParams.adapter === LLMAdapter.Anthropic) {chatModel = new ChatAnthropic({anthropicApiKey: apiKey,+ anthropicApiUrl: baseURL,modelName: modelParams.model,temperature: modelParams.temperature,maxTokens: modelParams.max_tokens,topP: modelParams.top_p,callbacks,+ clientOptions: { maxRetries },});- } else if (modelParams.provider === ModelProvider.OpenAI) {+ } else if (modelParams.adapter === LLMAdapter.OpenAI) {chatModel = new ChatOpenAI({openAIApiKey: apiKey,modelName: modelParams.model,@@ -85,15 +98,29 @@ export async function fetchLLMCompletion(maxTokens: modelParams.max_tokens,topP: modelParams.top_p,callbacks,+ maxRetries,+ configuration: {+ baseURL,+ },+ });+ } else if (modelParams.adapter === LLMAdapter.Azure) {+ chatModel = new ChatOpenAI({+ azureOpenAIApiKey: apiKey,+ azureOpenAIBasePath: baseURL,+ azureOpenAIApiDeploymentName: modelParams.model,+ azureOpenAIApiVersion: "2024-02-01",+ temperature: modelParams.temperature,+ maxTokens: modelParams.max_tokens,+ topP: modelParams.top_p,+ callbacks,+ maxRetries,});} else {// eslint-disable-next-line no-unused-vars- const _exhaustiveCheck: never = modelParams;+ const _exhaustiveCheck: never = modelParams.adapter;throw new Error("This model provider is not supported.");}- console.log("Making LLM call with params: ", modelParams);-if (params.functionCall) {const functionCallingModel = chatModel.bind({functions: [diff --git a/packages/shared/src/server/llm/types.ts b/packages/shared/src/server/llm/types.tsindex 1ff153f544..f419061fcc 100644--- a/packages/shared/src/server/llm/types.ts+++ b/packages/shared/src/server/llm/types.ts@@ -1,3 +1,4 @@+import { LlmApiKeys } from "@prisma/client";import z from "zod";export type PromptVariable = { name: string; value: string; isUsed: boolean };@@ -9,9 +10,10 @@ export type ChatMessage = {export type ChatMessageWithId = ChatMessage & { id: string };-export enum ModelProvider {+export enum LLMAdapter {Anthropic = "anthropic",OpenAI = "openai",+ Azure = "azure",}export enum ChatMessageRole {@@ -19,32 +21,30 @@ export enum ChatMessageRole {User = "user",Assistant = "assistant",}-export type ModelParams = AnthropicModelParams | OpenAIModelParams;++export type ModelParams = {+ provider: string;+ adapter: LLMAdapter;+ model: string;+} & ModelConfig;type RecordWithEnabledFlag<T> = {[K in keyof T]: { value: T[K]; enabled: boolean };};export type UIModelParams = RecordWithEnabledFlag<- Required<AnthropicModelParams | OpenAIModelParams> & {+ Required<ModelParams> & {maxTemperature: number;}>;// Generic configexport type ModelConfig = z.infer<typeof ZodModelConfig>;-export const ZodModelConfig = z.object({max_tokens: z.coerce.number().optional(),temperature: z.coerce.number().optional(),top_p: z.coerce.number().optional(),});-// OpenAI-export type OpenAIModelParams = {- provider: ModelProvider.OpenAI;- model: OpenAIModel;-} & ModelConfig;-export const openAIModels = ["gpt-4o","gpt-4o-2024-05-13",@@ -64,12 +64,6 @@ export const openAIModels = [export type OpenAIModel = (typeof openAIModels)[number];-// Anthropic-export type AnthropicModelParams = {- provider: ModelProvider.Anthropic;- model: AnthropicModel;-} & ModelConfig;-export const anthropicModels = ["claude-3-opus-20240229","claude-3-sonnet-20240229",@@ -81,8 +75,9 @@ export const anthropicModels = [export type AnthropicModel = (typeof anthropicModels)[number];export const supportedModels = {- [ModelProvider.Anthropic]: anthropicModels,- [ModelProvider.OpenAI]: openAIModels,+ [LLMAdapter.Anthropic]: anthropicModels,+ [LLMAdapter.OpenAI]: openAIModels,+ [LLMAdapter.Azure]: [],} as const;export type LLMFunctionCall = {@@ -90,3 +85,26 @@ export type LLMFunctionCall = {description: string;parameters: z.ZodTypeAny; // this has to be a json schema for OpenAI};++export const LLMApiKeySchema = z+ .object({+ id: z.string(),+ projectId: z.string(),+ createdAt: z.date(),+ updatedAt: z.date(),+ adapter: z.nativeEnum(LLMAdapter),+ provider: z.string(),+ displaySecretKey: z.string(),+ secretKey: z.string(),+ baseURL: z.string().nullable(),+ customModels: z.array(z.string()),+ withDefaultModels: z.boolean(),+ })+ // strict mode to prevent extra keys. Thorws error otherwise+ // https://github.com/colinhacks/zod?tab=readme-ov-file#strict+ .strict();++export type LLMApiKey =+ z.infer<typeof LLMApiKeySchema> extends LlmApiKeys+ ? z.infer<typeof LLMApiKeySchema>+ : never;diff --git a/web/src/__tests__/llm-api-key.servertest.ts b/web/src/__tests__/llm-api-key.servertest.tsindex e38b0dc5bf..610555e311 100644--- a/web/src/__tests__/llm-api-key.servertest.ts+++ b/web/src/__tests__/llm-api-key.servertest.ts@@ -3,7 +3,7 @@import type { Session } from "next-auth";import { pruneDatabase } from "@/src/__tests__/test-utils";-import { ModelProvider } from "@langfuse/shared";+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";@@ -38,11 +38,20 @@ describe("llmApiKey.all RPC", () => {it("should create 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;await caller.llmApiKey.create({projectId,secretKey: secret,- provider: ModelProvider.OpenAI,+ provider,+ adapter,+ baseURL,+ customModels,+ withDefaultModels,});const llmApiKeys = await prisma.llmApiKeys.findMany({@@ -55,18 +64,31 @@ describe("llmApiKey.all RPC", () => {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);+ expect(llmApiKeys[0].provider).toBe(provider);+ expect(llmApiKeys[0].adapter).toBe(adapter);+ expect(llmApiKeys[0].baseURL).toBe(baseURL);+ expect(llmApiKeys[0].customModels).toEqual(customModels);+ expect(llmApiKeys[0].withDefaultModels).toBe(withDefaultModels);// this has to be 3 dots and the last 4 characters of the secretexpect(llmApiKeys[0].displaySecretKey).toMatch(/^...[a-zA-Z0-9]{4}$/);});it("should create and get 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;await caller.llmApiKey.create({projectId,secretKey: secret,- provider: ModelProvider.OpenAI,+ provider,+ adapter,+ baseURL,+ customModels,+ withDefaultModels,});const dbLlmApiKeys = await prisma.llmApiKeys.findMany({@@ -77,16 +99,23 @@ describe("llmApiKey.all RPC", () => {expect(dbLlmApiKeys.length).toBe(1);- const llmApiKeys = await caller.llmApiKey.all({+ const { data: llmApiKeys } = await caller.llmApiKey.all({projectId,});- expect(llmApiKeys.data.length).toBe(1);- expect(llmApiKeys.data[0].provider).toBe(ModelProvider.OpenAI);+ 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(provider);+ expect(llmApiKeys[0].adapter).toBe(adapter);+ expect(llmApiKeys[0].baseURL).toBe(baseURL);+ expect(llmApiKeys[0].customModels).toEqual(customModels);+ expect(llmApiKeys[0].withDefaultModels).toBe(withDefaultModels);// 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}$/);+ expect(llmApiKeys[0].displaySecretKey).toMatch(/^...[a-zA-Z0-9]{4}$/);// response must not contain the secret key itself- expect(llmApiKeys.data[0]).not.toHaveProperty("secretKey");+ expect(llmApiKeys[0]).not.toHaveProperty("secretKey");});});diff --git a/web/src/components/ModelParameters/LLMApiKeyComponent.tsx b/web/src/components/ModelParameters/LLMApiKeyComponent.tsxindex 0ac49cc2f4..915bd52b22 100644--- a/web/src/components/ModelParameters/LLMApiKeyComponent.tsx+++ b/web/src/components/ModelParameters/LLMApiKeyComponent.tsx@@ -3,7 +3,7 @@ import Link from "next/link";import { Label } from "@/src/components/ui/label";import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";import { api } from "@/src/utils/api";-import { supportedModels, type UIModelParams } from "@langfuse/shared";+import { type UIModelParams } from "@langfuse/shared";import { ArrowTopRightIcon } from "@radix-ui/react-icons";export const LLMApiKeyComponent = (p: {@@ -39,11 +39,7 @@ export const LLMApiKeyComponent = (p: {);}- const model = p.modelParams.model.value;- const modelProvider = Object.entries(supportedModels).find((providerData) =>- (providerData[1] as any as string[]).includes(model),- )?.[0];-+ const modelProvider = p.modelParams.provider.value;const apiKey = apiKeys.data?.data.find((k) => k.provider === modelProvider);return (@@ -51,9 +47,11 @@ export const LLMApiKeyComponent = (p: {<Label className="text-xs font-semibold">API key</Label><div>{apiKey ? (- <span className="mr-2 rounded-sm bg-input p-1 text-xs">- {apiKey.displaySecretKey}- </span>+ <Link href={`/project/${p.projectId}/settings`}>+ <span className="mr-2 rounded-sm bg-input p-1 text-xs">+ {apiKey.displaySecretKey}+ </span>+ </Link>) : undefined}</div>{/* Custom form message to include a link to the already existing prompt */}diff --git a/web/src/components/ModelParameters/index.tsx b/web/src/components/ModelParameters/index.tsxindex 2c8b26ee4b..ded3d396bb 100644--- a/web/src/components/ModelParameters/index.tsx+++ b/web/src/components/ModelParameters/index.tsx@@ -8,11 +8,12 @@ import {} from "@/src/components/ui/select";import { Slider } from "@/src/components/ui/slider";import { Switch } from "@/src/components/ui/switch";+import { CreateLLMApiKeyDialog } from "@/src/features/public-api/components/CreateLLMApiKeyDialog";import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";import { cn } from "@/src/utils/tailwind";import {- ModelProvider,- supportedModels,+ type LLMAdapter,+ type supportedModels,type UIModelParams,} from "@langfuse/shared";@@ -20,7 +21,8 @@ import { LLMApiKeyComponent } from "./LLMApiKeyComponent";export type ModelParamsContext = {modelParams: UIModelParams;- availableModels?: UIModelParams[];+ availableProviders: string[];+ availableModels: string[];updateModelParamValue: <Key extends keyof UIModelParams>(key: Key,value: UIModelParams[Key]["value"],@@ -31,6 +33,7 @@ export type ModelParamsContext = {export const ModelParameters: React.FC<ModelParamsContext> = ({modelParams,+ availableProviders,availableModels,updateModelParamValue,setModelParamEnabled,@@ -43,76 +46,71 @@ export const ModelParameters: React.FC<ModelParamsContext> = ({return (<div className="flex flex-col space-y-4"><p className="font-semibold">Model</p>- <div className="space-y-4">- <ModelParamsSelect- title="Provider"- modelParamsKey="provider"- disabled={formDisabled}- value={modelParams.provider.value}- options={- availableModels- ? [...new Set(availableModels.map((m) => m.provider.value))]- : Object.values(ModelProvider)- }- updateModelParam={updateModelParamValue}- />- <ModelParamsSelect- title="Model name"- modelParamsKey="model"- disabled={formDisabled}- value={modelParams.model.value}- options={Object.values(- availableModels- ? availableModels- .filter(- (m) => m.provider.value === modelParams.provider.value,- )- .map((m) => m.model.value)- : supportedModels[modelParams.provider.value],- )}- updateModelParam={updateModelParamValue}- />- <ModelParamsSlider- title="Temperature"- modelParamsKey="temperature"- formDisabled={formDisabled}- enabled={modelParams.temperature.enabled}- setModelParamEnabled={setModelParamEnabled}- value={modelParams.temperature.value}- min={0}- max={modelParams.maxTemperature.value}- step={0.01}- tooltip="The sampling temperature. Higher values will make the output more random, while lower values will make it more focused and deterministic."- updateModelParam={updateModelParamValue}- />- <ModelParamsSlider- title="Output token limit"- modelParamsKey="max_tokens"- formDisabled={formDisabled}- enabled={modelParams.max_tokens.enabled}- setModelParamEnabled={setModelParamEnabled}- value={modelParams.max_tokens.value}- min={1}- max={4096}- step={1}- tooltip="The maximum number of tokens that can be generated in the chat completion."- updateModelParam={updateModelParamValue}- />- <ModelParamsSlider- title="Top P"- modelParamsKey="top_p"- formDisabled={formDisabled}- enabled={modelParams.top_p.enabled}- setModelParamEnabled={setModelParamEnabled}- value={modelParams.top_p.value}- min={0}- max={1}- step={0.01}- tooltip="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both."- updateModelParam={updateModelParamValue}- />- <LLMApiKeyComponent {...{ projectId, modelParams }} />- </div>+ {availableProviders.length === 0 ? (+ <>+ <p className="text-sm">No LLM API key set in project.</p>+ <CreateLLMApiKeyDialog />+ </>+ ) : (+ <div className="space-y-4">+ <ModelParamsSelect+ title="Provider"+ modelParamsKey="provider"+ disabled={formDisabled}+ value={modelParams.provider.value}+ options={availableProviders}+ updateModelParam={updateModelParamValue}+ />+ <ModelParamsSelect+ title="Model name"+ modelParamsKey="model"+ disabled={formDisabled}+ value={modelParams.model.value}+ options={availableModels}+ updateModelParam={updateModelParamValue}+ />+ <ModelParamsSlider+ title="Temperature"+ modelParamsKey="temperature"+ formDisabled={formDisabled}+ enabled={modelParams.temperature.enabled}+ setModelParamEnabled={setModelParamEnabled}+ value={modelParams.temperature.value}+ min={0}+ max={modelParams.maxTemperature.value}+ step={0.01}+ tooltip="The sampling temperature. Higher values will make the output more random, while lower values will make it more focused and deterministic."+ updateModelParam={updateModelParamValue}+ />+ <ModelParamsSlider+ title="Output token limit"+ modelParamsKey="max_tokens"+ formDisabled={formDisabled}+ enabled={modelParams.max_tokens.enabled}+ setModelParamEnabled={setModelParamEnabled}+ value={modelParams.max_tokens.value}+ min={1}+ max={4096}+ step={1}+ tooltip="The maximum number of tokens that can be generated in the chat completion."+ updateModelParam={updateModelParamValue}+ />+ <ModelParamsSlider+ title="Top P"+ modelParamsKey="top_p"+ formDisabled={formDisabled}+ enabled={modelParams.top_p.enabled}+ setModelParamEnabled={setModelParamEnabled}+ value={modelParams.top_p.value}+ min={0}+ max={1}+ step={0.01}+ tooltip="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both."+ updateModelParam={updateModelParamValue}+ />+ <LLMApiKeyComponent {...{ projectId, modelParams }} />+ </div>+ )}</div>);};@@ -148,7 +146,7 @@ const ModelParamsSelect = ({onValueChange={(value) =>updateModelParam(modelParamsKey,- value as (typeof supportedModels)[ModelProvider][number],+ value as (typeof supportedModels)[LLMAdapter][number],)}value={value}diff --git a/web/src/ee/features/evals/components/template-form.tsx b/web/src/ee/features/evals/components/template-form.tsxindex e95b21140b..eee17eed20 100644--- a/web/src/ee/features/evals/components/template-form.tsx+++ b/web/src/ee/features/evals/components/template-form.tsx@@ -1,4 +1,4 @@-import { useEffect, useState, useMemo } from "react";+import { useEffect, useState } from "react";import { useForm } from "react-hook-form";import * as z from "zod";import { Input } from "@/src/components/ui/input";@@ -18,19 +18,12 @@ import { zodResolver } from "@hookform/resolvers/zod";import { extractVariables, getIsCharOrUnderscore } from "@/src/utils/string";import router from "next/router";import { type EvalTemplate } from "@prisma/client";+import { ModelParameters } from "@/src/components/ModelParameters";import {- ModelParameters,- type ModelParamsContext,-} from "@/src/components/ModelParameters";-import {- EvalModelNames,OutputSchema,- evalLLMModels,type UIModelParams,- ModelProvider,- type OpenAIModel,- type OpenAIModelParams,type ModelParams,+ ZodModelConfig,} from "@langfuse/shared";import { PromptDescription } from "@/src/features/prompts/components/prompt-description";import {@@ -43,6 +36,7 @@ import {import { TEMPLATES } from "@/src/ee/features/evals/components/templates";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { getFinalModelParams } from "@/src/ee/utils/getFinalModelParams";+import { useModelParams } from "@/src/ee/features/playground/page/hooks/useModelParams";export const EvalTemplateForm = (props: {projectId: string;@@ -102,15 +96,6 @@ export const EvalTemplateForm = (props: {score: currentTemplate?.outputScore?.trim() ?? "",reasoning: currentTemplate?.outputReasoning?.trim() ?? "",},- model: "gpt-3.5-turbo",- modelParams: {- model: "gpt-3.5-turbo",- provider: ModelProvider.OpenAI,- temperature: 1,- maxTemperature: 2,- max_tokens: 256,- top_p: 1,- },}: props.existingEvalTemplate? {@@ -121,10 +106,13 @@ export const EvalTemplateForm = (props: {score: string;reasoning: string;},- model: props.existingEvalTemplate.model as OpenAIModel,- modelParams: props.existingEvalTemplate- .modelParams as OpenAIModelParams & {- maxTemperature: number;+ selectedModel: {+ provider: props.existingEvalTemplate.provider,+ model: props.existingEvalTemplate.model,+ modelParams: props.existingEvalTemplate+ .modelParams as ModelParams & {+ maxTemperature: number;+ },},}: undefined@@ -135,6 +123,12 @@ export const EvalTemplateForm = (props: {);};+const selectedModelSchema = z.object({+ provider: z.string().min(1, "Select a provider"),+ model: z.string().min(1, "Select a model"),+ modelParams: ZodModelConfig,+});+const formSchema = z.object({name: z.string().min(1, "Enter a name"),prompt: z@@ -167,9 +161,12 @@ export type EvalTemplateFormPreFill = {score: string;reasoning: string;};- model: OpenAIModel;- modelParams: OpenAIModelParams & {- maxTemperature: number;+ selectedModel?: {+ provider: string;+ model: string;+ modelParams: ModelParams & {+ maxTemperature: number;+ };};};@@ -186,27 +183,41 @@ export const InnerEvalTemplateForm = (props: {}) => {const capture = usePostHogClientCapture();const [formError, setFormError] = useState<string | null>(null);- const preFilledModel = useMemo(- () => getModelParamsWithEnabledFlag(props.preFilledFormValues),- [props.preFilledFormValues],- );// updates the model params based on the pre-filled data// either form update or from langfuse-generated template- const [modelParams, setModelParams] = useState<UIModelParams>(preFilledModel);- const updateModelParamValue: ModelParamsContext["updateModelParamValue"] = (- key,- value,- ) => {- setModelParams((prev) => ({ ...prev, [key]: { ...prev[key], value } }));- };+ const {+ modelParams,+ setModelParams,+ updateModelParamValue,+ setModelParamEnabled,+ availableModels,+ availableProviders,+ } = useModelParams({ evalModelsOnly: true });- const setModelParamEnabled: ModelParamsContext["setModelParamEnabled"] = (- key,- enabled,- ) => {- setModelParams((prev) => ({ ...prev, [key]: { ...prev[key], enabled } }));- };+ useEffect(() => {+ if (props.preFilledFormValues?.selectedModel) {+ const { provider, model, modelParams } =+ props.preFilledFormValues.selectedModel;++ const modelConfig = Object.entries(modelParams).reduce(+ (acc, [key, value]) => {+ return {+ ...acc,+ [key]: { value, enabled: true },+ };+ },+ {} as UIModelParams,+ );++ setModelParams((prev) => ({+ ...prev,+ ...modelConfig,+ provider: { value: provider, enabled: true },+ model: { value: model, enabled: true },+ }));+ }+ }, [props.preFilledFormValues?.selectedModel, setModelParams]);// updates the form based on the pre-filled data// either form update or from langfuse-generated template@@ -243,33 +254,8 @@ export const InnerEvalTemplateForm = (props: {outputScore: OutputSchema.parse(props.preFilledFormValues.outputSchema).score,});-- // state for the model params is outside of the form, hence needs to be handled individually- // also set the context for the playground- const model = EvalModelNames.parse(preFilledModel.model.value);- updateModelParamValue("model", model);- setModelParams((prev) => ({- ...prev,- ...preFilledModel,- }));-- const modelProvider = evalLLMModels.find((m) => m.model.value === model)- ?.provider.value;-- if (modelProvider) {- updateModelParamValue("provider", modelProvider); // updating the provider based on the model- updateModelParamValue(- "maxTemperature",- modelProvider === ModelProvider.OpenAI ? 2 : 1,- ); // setting the max value of the slider based on the provider- }}- }, [- props.preFilledFormValues,- preFilledModel,- form,- props.existingEvalTemplateName,- ]);+ }, [props.preFilledFormValues, form, props.existingEvalTemplateName]);const extractedVariables = form.watch("prompt")? extractVariables(form.watch("prompt")).filter(getIsCharOrUnderscore)@@ -288,26 +274,31 @@ export const InnerEvalTemplateForm = (props: {: "eval_templates:new_form_submit",);- const model = EvalModelNames.safeParse(modelParams.model.value);+ const evalTemplate = {+ name: values.name,+ projectId: props.projectId,+ prompt: values.prompt,+ provider: modelParams.provider.value,+ model: modelParams.model.value,+ modelParams: getFinalModelParams(modelParams),+ vars: extractedVariables ?? [],+ outputSchema: {+ score: values.outputScore,+ reasoning: values.outputReasoning,+ },+ };++ const parsedModel = selectedModelSchema.safeParse(evalTemplate);- if (!model.success) {- setFormError("Please select a model.");+ if (!parsedModel.success) {+ setFormError(+ `${parsedModel.error.errors[0].path}: ${parsedModel.error.errors[0].message}`,+ );return;}createEvalTemplateMutation- .mutateAsync({- name: values.name,- projectId: props.projectId,- prompt: values.prompt,- model: model.data,- modelParams: getFinalModelParams(modelParams),- vars: extractedVariables ?? [],- outputSchema: {- score: values.outputScore,- reasoning: values.outputReasoning,- },- })+ .mutateAsync(evalTemplate).then((res) => {props.onFormSuccess?.();form.reset();@@ -429,10 +420,11 @@ export const InnerEvalTemplateForm = (props: {<ModelParameters{...{modelParams,+ availableModels,+ availableProviders,updateModelParamValue: updateModelParamValue,setModelParamEnabled,}}- availableModels={[...evalLLMModels]}formDisabled={!props.isEditing}/></div>@@ -456,33 +448,3 @@ export const InnerEvalTemplateForm = (props: {</Form>);};--function getModelParamsWithEnabledFlag(- evalPreFill?: EvalTemplateFormPreFill,-): UIModelParams {- const defaultModelParams: ModelParams & { maxTemperature: number } = {- model: evalPreFill?.model ?? "gpt-3.5-turbo",- provider: ModelProvider.OpenAI,- max_tokens: 100,- maxTemperature:- evalPreFill?.modelParams?.provider === ModelProvider.OpenAI ? 2 : 1,- top_p: 1,- temperature: 1,- };-- return Object.entries({- ...defaultModelParams,- ...evalPreFill?.modelParams,- }).reduce(- (params, [key, value]) => ({- ...params,- [key]: {- enabled: Boolean(- !evalPreFill || evalPreFill.modelParams[key as keyof UIModelParams],- ),- value,- },- }),- {} as UIModelParams,- );-}diff --git a/web/src/ee/features/evals/server/router.ts b/web/src/ee/features/evals/server/router.tsindex ce97839a3b..03b01683a0 100644--- a/web/src/ee/features/evals/server/router.ts+++ b/web/src/ee/features/evals/server/router.ts@@ -8,7 +8,6 @@ import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";import { auditLog } from "@/src/features/audit-logs/auditLog";import { DEFAULT_TRACE_JOB_DELAY, EvalTargetObject } from "@langfuse/shared";import {- EvalModelNames,ZodModelConfig,singleFilter,variableMapping,@@ -19,7 +18,8 @@ export const CreateEvalTemplate = z.object({name: z.string().min(1),projectId: z.string(),prompt: z.string(),- model: EvalModelNames,+ provider: z.string(),+ model: z.string(),modelParams: ZodModelConfig,vars: z.array(z.string()),outputSchema: z.object({@@ -332,6 +332,7 @@ export const evalRouter = createTRPCRouter({modelParams: input.modelParams,vars: input.vars,outputSchema: input.outputSchema,+ provider: input.provider,},});diff --git a/web/src/ee/features/playground/page/context/index.tsx b/web/src/ee/features/playground/page/context/index.tsxindex dd8d291d30..d350fd562d 100644--- a/web/src/ee/features/playground/page/context/index.tsx+++ b/web/src/ee/features/playground/page/context/index.tsx@@ -11,6 +11,7 @@ import { v4 as uuidv4 } from "uuid";import { createEmptyMessage } from "@/src/components/ChatMessages/utils/createEmptyMessage";import useCommandEnter from "@/src/ee/features/playground/page/hooks/useCommandEnter";+import { useModelParams } from "@/src/ee/features/playground/page/hooks/useModelParams";import usePlaygroundCache from "@/src/ee/features/playground/page/hooks/usePlaygroundCache";import { getFinalModelParams } from "@/src/ee/utils/getFinalModelParams";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";@@ -19,7 +20,6 @@ import { extractVariables } from "@/src/utils/string";import {ChatMessageRole,type ChatMessageWithId,- ModelProvider,type PromptVariable,type UIModelParams,} from "@langfuse/shared";@@ -68,9 +68,14 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({createEmptyMessage(ChatMessageRole.System),createEmptyMessage(ChatMessageRole.User),]);- const [modelParams, setModelParams] = useState<UIModelParams>(- getDefaultModelParams(ModelProvider.OpenAI),- );+ const {+ modelParams,+ setModelParams,+ availableProviders,+ availableModels,+ updateModelParamValue,+ setModelParamEnabled,+ } = useModelParams();// Load state from cacheuseEffect(() => {@@ -97,11 +102,7 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({if (cachedPromptVariables) {setPromptVariables(cachedPromptVariables);}- }, [playgroundCache]);-- useEffect(() => {- setModelParams(getDefaultModelParams(modelParams.provider.value));- }, [modelParams.provider.value]);+ }, [playgroundCache, setModelParams]);const updatePromptVariables = useCallback(() => {const messageContents = messages.map((m) => m.content).join("\n");@@ -169,6 +170,10 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({finalMessages.map((m) => m.content).join("\n"),);+ if (!modelParams.provider.value || !modelParams.model.value) {+ throw new Error("Please select a model");+ }+if (leftOverVariables.length > 0) {throw Error("Error replacing variables. Please check your inputs.");}@@ -210,24 +215,6 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({useCommandEnter(!isStreaming, handleSubmit);- const updateModelParamValue: PlaygroundContextType["updateModelParamValue"] =- (key, value) => {- setModelParams((prev) => ({- ...prev,- [key]: { ...prev[key], value },- }));- };-- const setModelParamEnabled: PlaygroundContextType["setModelParamEnabled"] = (- key,- enabled,- ) => {- setModelParams((prev) => ({- ...prev,- [key]: { ...prev[key], enabled },- }));- };-const updatePromptVariableValue = (variable: string, value: string) => {setPromptVariables((prev) =>prev.map((v) => (v.name === variable ? { ...v, value } : v)),@@ -258,6 +245,9 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({outputJson,handleSubmit,isStreaming,++ availableProviders,+ availableModels,}}>{children}@@ -342,38 +332,6 @@ function getFinalMessages(return finalMessages;}-function getDefaultModelParams(provider: ModelProvider): UIModelParams {- switch (provider) {- // Docs: https://platform.openai.com/docs/api-reference/chat/create- case ModelProvider.OpenAI:- return {- provider: {- value: provider,- enabled: true,- },- model: { value: "gpt-3.5-turbo", enabled: true },- temperature: { value: 1, enabled: true },- maxTemperature: { value: 2, enabled: true },- max_tokens: { value: 256, enabled: true },- top_p: { value: 1, enabled: true },- };-- // Docs: https://docs.anthropic.com/claude/reference/messages_post- case ModelProvider.Anthropic:- return {- provider: {- value: provider,- enabled: true,- },- model: { value: "claude-3-opus-20240229", enabled: true },- temperature: { value: 0, enabled: true },- maxTemperature: { value: 1, enabled: true },- max_tokens: { value: 256, enabled: true },- top_p: { value: 1, enabled: true },- };- }-}-function getOutputJson(output: string,messages: ChatMessageWithId[],diff --git a/web/src/ee/features/playground/page/hooks/useModelParams.ts b/web/src/ee/features/playground/page/hooks/useModelParams.tsnew file mode 100644index 0000000000..9250ff5729--- /dev/null+++ b/web/src/ee/features/playground/page/hooks/useModelParams.ts@@ -0,0 +1,170 @@+import { useEffect, useMemo, useState } from "react";++import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";+import { api } from "@/src/utils/api";+import {+ LLMAdapter,+ evalModelsByAdapter,+ supportedModels,+ type UIModelParams,+} from "@langfuse/shared";+import { type ModelParamsContext } from "@/src/components/ModelParameters";++export const useModelParams = ({+ evalModelsOnly,+}: {+ evalModelsOnly?: boolean;+} = {}) => {+ const [modelParams, setModelParams] = useState<UIModelParams>({+ ...getDefaultAdapterParams(LLMAdapter.OpenAI),+ provider: { value: "", enabled: true },+ model: { value: "", enabled: true },+ });++ // Set initial model params+ const projectId = useProjectIdFromURL();+ const availableLLMApiKeys = api.llmApiKey.all.useQuery(+ {+ projectId: projectId as string,+ },+ { enabled: Boolean(projectId) },+ );++ const availableProviders = useMemo(() => {+ return availableLLMApiKeys.data?.data.map((key) => key.provider) ?? [];+ }, [availableLLMApiKeys]);++ const selectedProviderApiKey = availableLLMApiKeys.data?.data.find(+ (key) => key.provider === modelParams.provider.value,+ );++ const availableModels = useMemo(+ () =>+ !selectedProviderApiKey+ ? []+ : evalModelsOnly+ ? [+ ...evalModelsByAdapter[selectedProviderApiKey.adapter],+ ...selectedProviderApiKey.customModels,+ ]+ : selectedProviderApiKey.withDefaultModels+ ? [+ ...selectedProviderApiKey.customModels,+ ...supportedModels[selectedProviderApiKey.adapter],+ ]+ : selectedProviderApiKey.customModels,+ [selectedProviderApiKey, evalModelsOnly],+ );++ const updateModelParamValue: ModelParamsContext["updateModelParamValue"] = (+ key,+ value,+ ) => {+ setModelParams((prev) => ({+ ...prev,+ [key]: { ...prev[key], value },+ }));+ };++ const setModelParamEnabled: ModelParamsContext["setModelParamEnabled"] = (+ key,+ enabled,+ ) => {+ setModelParams((prev) => ({+ ...prev,+ [key]: { ...prev[key], enabled },+ }));+ };++ // Set default provider and model+ useEffect(() => {+ if (availableProviders.length > 0 && !modelParams.provider.value) {+ updateModelParamValue("provider", availableProviders[0]);+ }+ }, [availableProviders, modelParams.provider.value]);++ useEffect(() => {+ if (+ (availableModels.length > 0 && !modelParams.model.value) ||+ !availableModels.includes(modelParams.model.value)+ ) {+ updateModelParamValue("model", availableModels[0]);+ }+ }, [availableModels, modelParams.model.value]);++ // Update adapter and max temperature when provider changes+ useEffect(() => {+ if (selectedProviderApiKey?.adapter) {+ setModelParams((prev) => ({+ ...prev,+ adapter: {+ value: selectedProviderApiKey.adapter,+ enabled: true,+ },+ maxTemperature: getDefaultAdapterParams(selectedProviderApiKey.adapter)+ .maxTemperature,+ temperature: {+ value: Math.min(+ prev.temperature.value,+ getDefaultAdapterParams(selectedProviderApiKey.adapter)+ .maxTemperature.value,+ ),+ enabled: true,+ },+ }));+ }+ }, [selectedProviderApiKey?.adapter]);++ return {+ modelParams,+ setModelParams,+ availableProviders,+ availableModels,+ updateModelParamValue,+ setModelParamEnabled,+ };+};++function getDefaultAdapterParams(+ adapter: LLMAdapter,+): Omit<UIModelParams, "provider" | "model"> {+ switch (adapter) {+ // Docs: https://platform.openai.com/docs/api-reference/chat/create+ case LLMAdapter.OpenAI:+ return {+ adapter: {+ value: adapter,+ enabled: true,+ },+ temperature: { value: 0, enabled: true },+ maxTemperature: { value: 2, enabled: true },+ max_tokens: { value: 256, enabled: true },+ top_p: { value: 1, enabled: true },+ };++ case LLMAdapter.Azure:+ return {+ adapter: {+ value: adapter,+ enabled: true,+ },+ temperature: { value: 0, enabled: true },+ maxTemperature: { value: 2, enabled: true },+ max_tokens: { value: 256, enabled: true },+ top_p: { value: 1, enabled: true },+ };++ // Docs: https://docs.anthropic.com/claude/reference/messages_post+ case LLMAdapter.Anthropic:+ return {+ adapter: {+ value: adapter,+ enabled: true,+ },+ temperature: { value: 0, enabled: true },+ maxTemperature: { value: 1, enabled: true },+ max_tokens: { value: 256, enabled: true },+ top_p: { value: 1, enabled: true },+ };+ }+}diff --git a/web/src/ee/features/playground/server/chatCompletionHandler.ts b/web/src/ee/features/playground/server/chatCompletionHandler.tsindex f7fe958611..da88ac1b13 100644--- a/web/src/ee/features/playground/server/chatCompletionHandler.ts+++ b/web/src/ee/features/playground/server/chatCompletionHandler.ts@@ -39,6 +39,7 @@ export default async function chatCompletionHandler(req: NextRequest) {streaming: true,callbacks: [new PosthogCallbackHandler("playground", body, userId)],apiKey: decrypt(LLMApiKey.secretKey),+ baseURL: LLMApiKey.baseURL || undefined,});return new StreamingTextResponse(stream);diff --git a/web/src/ee/features/playground/server/validateChatCompletionBody.ts b/web/src/ee/features/playground/server/validateChatCompletionBody.tsindex 6a8b51d24e..d562ed0654 100644--- a/web/src/ee/features/playground/server/validateChatCompletionBody.ts+++ b/web/src/ee/features/playground/server/validateChatCompletionBody.ts@@ -1,31 +1,14 @@import { z } from "zod";-import {- ChatMessageRole,- ModelProvider,- anthropicModels,- openAIModels,-} from "@langfuse/shared";+import { ChatMessageRole, LLMAdapter } from "@langfuse/shared";-const OpenAIModelSchema = z.enum([...openAIModels]);-const AnthropicModelSchema = z.enum([...anthropicModels]);-const OpenAIModelParamsSchema = z.object({- provider: z.literal(ModelProvider.OpenAI),- model: OpenAIModelSchema,- max_tokens: z.number().optional(),- temperature: z.number().optional(),- top_p: z.number().optional(),-});-const AnthropicModelParamsSchema = z.object({- provider: z.literal(ModelProvider.Anthropic),- model: AnthropicModelSchema,+const ModelParamsSchema = z.object({+ provider: z.string(),+ adapter: z.nativeEnum(LLMAdapter),+ model: z.string(),temperature: z.number().optional(),max_tokens: z.number().optional(),top_p: z.number().optional(),});-const ModelParamsSchema = z.union([- OpenAIModelParamsSchema,- AnthropicModelParamsSchema,-]);const MessageSchema = z.object({role: z.nativeEnum(ChatMessageRole),content: z.string(),diff --git a/web/src/env.mjs b/web/src/env.mjsindex 787e239bed..4f774ef374 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -30,14 +30,20 @@ export const env = createEnv({LANGFUSE_NEW_USER_SIGNUP_WEBHOOK: z.string().url().optional(),// Add `.min(1) on ID and SECRET if you want to make sure they're not emptyLANGFUSE_ENABLE_EXPERIMENTAL_FEATURES: z.enum(["true", "false"]).optional(),- LANGFUSE_DEFAULT_TABLE_DATETIME_OFFSET: z.string().optional().refine((v) =>- v === undefined || !isNaN(Number.parseInt(v))- , {- message: "LANGFUSE_DEFAULT_TABLE_DATETIME_OFFSET must be a number when set"- }).transform((v) =>- v === undefined ? undefined : -Number.parseInt(v) // negative offset+ LANGFUSE_DEFAULT_TABLE_DATETIME_OFFSET: z+ .string()+ .optional()+ .refine((v) => v === undefined || !isNaN(Number.parseInt(v)), {+ message:+ "LANGFUSE_DEFAULT_TABLE_DATETIME_OFFSET must be a number when set",+ })+ .transform(+ (v) => (v === undefined ? undefined : -Number.parseInt(v)), // negative offset),- LANGFUSE_DISABLE_EXPENSIVE_POSTGRES_QUERIES: z.enum(["true", "false"]).optional().default("false"),+ LANGFUSE_DISABLE_EXPENSIVE_POSTGRES_QUERIES: z+ .enum(["true", "false"])+ .optional()+ .default("false"),SALT: z.string({required_error:"A strong Salt is required to encrypt API keys securely. See: https://langfuse.com/docs/deployment/self-host#deploy-the-container",@@ -93,9 +99,6 @@ export const env = createEnv({// WorkerLANGFUSE_WORKER_HOST: z.string().optional(),LANGFUSE_WORKER_PASSWORD: z.string().optional(),- // Prompt playground- OPENAI_API_KEY: z.string().optional(),- ANTHROPIC_API_KEY: z.string().optional(),TURNSTILE_SECRET_KEY: z.string().optional(),// DB event logENABLE_EVENT_LOG: z.enum(["true", "false"]).optional().default("true"),@@ -179,7 +182,8 @@ export const env = createEnv({AUTH_COGNITO_CLIENT_ID: process.env.AUTH_COGNITO_CLIENT_ID,AUTH_COGNITO_CLIENT_SECRET: process.env.AUTH_COGNITO_CLIENT_SECRET,AUTH_COGNITO_ISSUER: process.env.AUTH_COGNITO_ISSUER,- AUTH_COGNITO_ALLOW_ACCOUNT_LINKING: process.env.AUTH_COGNITO_ALLOW_ACCOUNT_LINKING,+ AUTH_COGNITO_ALLOW_ACCOUNT_LINKING:+ process.env.AUTH_COGNITO_ALLOW_ACCOUNT_LINKING,AUTH_CUSTOM_CLIENT_ID: process.env.AUTH_CUSTOM_CLIENT_ID,AUTH_CUSTOM_CLIENT_SECRET: process.env.AUTH_CUSTOM_CLIENT_SECRET,AUTH_CUSTOM_ISSUER: process.env.AUTH_CUSTOM_ISSUER,@@ -204,9 +208,6 @@ export const env = createEnv({// WorkerLANGFUSE_WORKER_HOST: process.env.LANGFUSE_WORKER_HOST,LANGFUSE_WORKER_PASSWORD: process.env.LANGFUSE_WORKER_PASSWORD,- // Prompt playground- OPENAI_API_KEY: process.env.OPENAI_API_KEY,- ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY,TURNSTILE_SECRET_KEY: process.env.TURNSTILE_SECRET_KEY,NEXT_PUBLIC_TURNSTILE_SITE_KEY: process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY,NEXT_PUBLIC_POSTHOG_KEY: process.env.NEXT_PUBLIC_POSTHOG_KEY,diff --git a/web/src/features/llm-api-key/server/router.ts b/web/src/features/llm-api-key/server/router.tsindex 385c2cf314..8ce90256fd 100644--- a/web/src/features/llm-api-key/server/router.ts+++ b/web/src/features/llm-api-key/server/router.ts@@ -1,32 +1,26 @@import { z } from "zod";+import { env } from "@/src/env.mjs";+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { CreateLlmApiKey } from "@/src/features/llm-api-key/types";+import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";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 {+ type ChatMessage,+ LLMApiKeySchema,+ fetchLLMCompletion,+ ChatMessageRole,+ supportedModels,+} from "@langfuse/shared";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)@@ -45,8 +39,12 @@ export const llmApiKeyRouter = createTRPCRouter({data: {projectId: input.projectId,secretKey: encrypt(input.secretKey),+ adapter: input.adapter,displaySecretKey: getDisplaySecretKey(input.secretKey),provider: input.provider,+ baseURL: input.baseURL,+ withDefaultModels: input.withDefaultModels,+ customModels: input.customModels,},});@@ -109,22 +107,28 @@ export const llmApiKeyRouter = createTRPCRouter({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 apiKeys = z+ .array(LLMApiKeySchema.extend({ secretKey: z.undefined() }))+ .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,+ adapter: true,+ baseURL: true,+ customModels: true,+ withDefaultModels: true,+ },+ where: {+ projectId: input.projectId,+ },+ }),+ );const count = await ctx.prisma.llmApiKeys.count({where: {@@ -137,4 +141,47 @@ export const llmApiKeyRouter = createTRPCRouter({totalCount: count,};}),++ test: protectedProjectProcedure+ .input(CreateLlmApiKey)+ .mutation(async ({ input }) => {+ if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined) {+ throw new Error("Evals available in cloud only");+ }++ try {+ const model = input.customModels?.length+ ? input.customModels[0]+ : supportedModels[input.adapter][0];++ if (!model) throw Error("No model found");++ const testMessages: ChatMessage[] = [+ { role: ChatMessageRole.System, content: "You are a bot" },+ { role: ChatMessageRole.User, content: "How are you?" },+ ];++ await fetchLLMCompletion({+ modelParams: {+ adapter: input.adapter,+ provider: input.provider,+ model,+ },+ baseURL: input.baseURL,+ apiKey: input.secretKey,+ messages: testMessages,+ streaming: false,+ maxRetries: 1,+ });++ return { success: true };+ } catch (err) {+ console.log(err);++ return {+ success: false,+ error: err instanceof Error ? err.message : "Unknown error",+ };+ }+ }),});diff --git a/web/src/features/llm-api-key/types.ts b/web/src/features/llm-api-key/types.tsindex 074ac617f9..cd49021688 100644--- a/web/src/features/llm-api-key/types.ts+++ b/web/src/features/llm-api-key/types.ts@@ -1,8 +1,12 @@import { z } from "zod";-import { ModelProvider } from "@langfuse/shared";+import { LLMAdapter } from "@langfuse/shared";export const CreateLlmApiKey = z.object({projectId: z.string(),secretKey: z.string().min(1),- provider: z.nativeEnum(ModelProvider),+ provider: z.string().min(3),+ adapter: z.nativeEnum(LLMAdapter),+ baseURL: z.string().url().optional(),+ withDefaultModels: z.boolean().optional(),+ customModels: z.array(z.string()).optional(),});diff --git a/web/src/features/public-api/components/CreateLLMApiKeyDialog.tsx b/web/src/features/public-api/components/CreateLLMApiKeyDialog.tsxnew file mode 100644index 0000000000..0dfba8c3fc--- /dev/null+++ b/web/src/features/public-api/components/CreateLLMApiKeyDialog.tsx@@ -0,0 +1,379 @@+import { PlusIcon, TrashIcon } from "lucide-react";+import { useState } from "react";+import { useFieldArray, useForm } from "react-hook-form";+import { z } from "zod";++import { Button } from "@/src/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@/src/components/ui/dialog";+import {+ Form,+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/src/components/ui/form";+import { Input } from "@/src/components/ui/input";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";+import { Switch } from "@/src/components/ui/switch";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { api } from "@/src/utils/api";+import { cn } from "@/src/utils/tailwind";+import { zodResolver } from "@hookform/resolvers/zod";+import { LLMAdapter } from "@langfuse/shared";+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";++const formSchema = z+ .object({+ secretKey: z.string().min(1),+ provider: z.string().min(1),+ 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) })),+ })+ .refine((data) => data.withDefaultModels || data.customModels.length > 0, {+ message:+ "At least one custom model name is required when default models are disabled.",+ path: ["withDefaultModels"],+ });++export function CreateLLMApiKeyDialog() {+ const projectId = useProjectIdFromURL();+ const capture = usePostHogClientCapture();+ const utils = api.useUtils();+ const [open, setOpen] = useState(false);+ const hasAccess = useHasAccess({+ projectId,+ scope: "llmApiKeys:create",+ });++ const existingKeys = api.llmApiKey.all.useQuery(+ {+ projectId: projectId as string,+ },+ { enabled: Boolean(projectId) },+ );++ const mutCreateLlmApiKey = api.llmApiKey.create.useMutation({+ onSuccess: () => utils.llmApiKey.invalidate(),+ });++ const mutTestLLMApiKey = api.llmApiKey.test.useMutation();++ const form = useForm<z.infer<typeof formSchema>>({+ resolver: zodResolver(formSchema),+ defaultValues: {+ adapter: LLMAdapter.OpenAI,+ provider: "",+ secretKey: "",+ baseURL: "",+ withDefaultModels: true,+ customModels: [],+ },+ });++ const currentAdapter = form.watch("adapter");++ const { fields, append, remove } = useFieldArray({+ control: form.control,+ name: "customModels",+ });++ if (!hasAccess) return null;++ 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.",+ });+ return;+ }+ capture("project_settings:llm_api_key_create", {+ provider: values.provider,+ });++ const newKey = {+ projectId,+ secretKey: values.secretKey,+ provider: values.provider,+ adapter: values.adapter,+ baseURL: values.baseURL || undefined,+ withDefaultModels: values.withDefaultModels,+ customModels: values.customModels+ .map((m) => m.value.trim())+ .filter(Boolean),+ };++ try {+ const testResult = await mutTestLLMApiKey.mutateAsync(newKey);++ if (!testResult.success) throw new Error(testResult.error);+ } catch (error) {+ console.error(error);+ form.setError("secretKey", {+ type: "manual",+ message:+ error instanceof Error+ ? error.message+ : "Could not verify the API key.",+ });++ return;+ }++ return mutCreateLlmApiKey+ .mutateAsync(newKey)+ .then(() => {+ form.reset();+ setOpen(false);+ })+ .catch((error) => {+ console.error(error);+ });+ }++ return (+ <Dialog+ open={open}+ onOpenChange={(isOpen) => {+ form.reset();+ setOpen(isOpen);+ }}+ >+ <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 className="h-[90%] min-w-[40vw]">+ <DialogHeader>+ <DialogTitle>Add new LLM API key</DialogTitle>+ </DialogHeader>+ <Form {...form}>+ <form+ className={cn("flex flex-col gap-6 overflow-auto pb-2 pl-1 pr-4")}+ onSubmit={form.handleSubmit(onSubmit)}+ >+ {/* Provider name */}+ <FormField+ control={form.control}+ name="provider"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Provider name</FormLabel>+ <FormDescription>+ Name to identify the key within Langfuse.+ </FormDescription>+ <FormControl>+ <Input {...field} placeholder="OpenAI" />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />++ {/* LLM adapter */}+ <FormField+ control={form.control}+ name="adapter"+ render={({ field }) => (+ <FormItem>+ <FormLabel>LLM adapter</FormLabel>+ <FormDescription>+ Schema that is accepted at that provider endpoint.+ </FormDescription>+ <Select+ defaultValue={field.value}+ onValueChange={(value) =>+ field.onChange(value as LLMAdapter)+ }+ >+ <FormControl>+ <SelectTrigger>+ <SelectValue placeholder="Select a LLM provider" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ {Object.values(LLMAdapter).map((provider) => (+ <SelectItem value={provider} key={provider}>+ {provider}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FormMessage />+ </FormItem>+ )}+ />++ {/* baseURL */}+ <FormField+ control={form.control}+ name="baseURL"+ render={({ field }) => (+ <FormItem>+ <FormLabel>API Base URL</FormLabel>+ <FormDescription>+ Leave blank to use the default base URL for the given LLM+ adapter.+ </FormDescription>++ {currentAdapter === LLMAdapter.Azure && (+ <FormDescription className="text-yellow-700">+ For Azure, please add the base URL in the following+ format:+ https://{instanceName}.openai.azure.com/openai/deployments+ </FormDescription>+ )}++ <FormControl>+ <Input {...field} placeholder="default" />+ </FormControl>++ <FormMessage />+ </FormItem>+ )}+ />++ {/* API key */}+ <FormField+ control={form.control}+ name="secretKey"+ render={({ field }) => (+ <FormItem>+ <FormLabel>API Key</FormLabel>+ <FormDescription>+ Your API keys are stored encrypted on our servers.+ </FormDescription>+ <FormControl>+ <Input placeholder="sk-proj-...Uwj9" {...field} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />++ {/* With default models */}+ <FormField+ control={form.control}+ name="withDefaultModels"+ render={({ field }) => (+ <FormItem>+ <span className="row flex">+ <span className="flex-1">+ <FormLabel>Enable default models</FormLabel>+ <FormDescription>+ Default models for the selected adapter will be+ available in Langfuse features.+ </FormDescription>+ {currentAdapter === LLMAdapter.Azure && (+ <FormDescription className="text-yellow-700">+ Azure LLM adapter does not support default models.+ Please add a custom model with your deployment name.+ </FormDescription>+ )}+ </span>++ <FormControl>+ <Switch+ disabled={currentAdapter === LLMAdapter.Azure}+ checked={+ currentAdapter === LLMAdapter.Azure+ ? false+ : field.value+ }+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </span>++ <FormMessage />+ </FormItem>+ )}+ />++ {/* Custom model names */}+ <FormField+ control={form.control}+ name="customModels"+ render={() => (+ <FormItem>+ <FormLabel>Custom models</FormLabel>+ <FormDescription>+ Custom model names accepted by given endpoint.+ </FormDescription>+ {currentAdapter === LLMAdapter.Azure && (+ <FormDescription className="text-yellow-700">+ {+ "For Azure, the model name should be the same as the deployment name in Azure."+ }+ </FormDescription>+ )}++ {fields.map((customModel, index) => (+ <span key={index} className="flex flex-row space-x-2">+ <Input+ {...form.register(`customModels.${index}.value`)}+ placeholder={`Custom model name ${index + 1}`}+ />+ <Button+ type="button"+ variant="ghost"+ onClick={() => remove(index)}+ >+ <TrashIcon className="h-4 w-4" />+ </Button>+ </span>+ ))}++ <Button+ type="button"+ variant="ghost"+ onClick={() => append({ value: "" })}+ className="w-full"+ >+ <PlusIcon+ className="-ml-0.5 mr-1.5 h-5 w-5"+ aria-hidden="true"+ />+ Add custom model name+ </Button>+ </FormItem>+ )}+ />++ <Button+ type="submit"+ className="w-full"+ loading={form.formState.isSubmitting}+ >+ Save new LLM API key+ </Button>++ <FormMessage />+ </form>+ </Form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/web/src/features/public-api/components/LLMApiKeyList.tsx b/web/src/features/public-api/components/LLMApiKeyList.tsxindex 81411aed92..e302d14b6e 100644--- a/web/src/features/public-api/components/LLMApiKeyList.tsx+++ b/web/src/features/public-api/components/LLMApiKeyList.tsx@@ -1,3 +1,6 @@+import { TrashIcon } from "lucide-react";+import { useState } from "react";+import Header from "@/src/components/layouts/header";import { Button } from "@/src/components/ui/button";import { Card } from "@/src/components/ui/card";@@ -9,23 +12,6 @@ import {DialogTitle,DialogTrigger,} from "@/src/components/ui/dialog";-import {- FormControl,- FormField,- FormItem,- FormLabel,- FormMessage,- Form,- FormDescription,-} 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,@@ -38,15 +24,9 @@ import { env } from "@/src/env.mjs";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";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 { useState } from "react";-import { useForm } from "react-hook-form";-import { z } from "zod";++import { CreateLLMApiKeyDialog } from "./CreateLLMApiKeyDialog";export function LlmApiKeyList(props: { projectId: string }) {const hasAccess = useHasAccess({@@ -79,6 +59,12 @@ export function LlmApiKeyList(props: { projectId: string }) {<TableHead className="hidden text-primary md:table-cell">Provider</TableHead>+ <TableHead className="hidden text-primary md:table-cell">+ Adapter+ </TableHead>+ <TableHead className="hidden text-primary md:table-cell">+ Base URL+ </TableHead><TableHead className="text-primary">Secret Key</TableHead><TableHead /></TableRow>@@ -90,6 +76,10 @@ export function LlmApiKeyList(props: { projectId: string }) {{apiKey.createdAt.toLocaleDateString()}</TableCell><TableCell className="font-mono">{apiKey.provider}</TableCell>+ <TableCell className="font-mono">{apiKey.adapter}</TableCell>+ <TableCell className="font-mono">+ {apiKey.baseURL ?? "default"}+ </TableCell><TableCell className="font-mono">{apiKey.displaySecretKey}</TableCell>@@ -104,10 +94,7 @@ export function LlmApiKeyList(props: { projectId: string }) {</TableBody></Table></Card>- <CreateLlmApiKeyComponent- projectId={props.projectId}- existingApiKeys={apiKeys.data?.data ?? []}- />+ <CreateLLMApiKeyDialog /></div>);}@@ -137,11 +124,11 @@ function DeleteApiKeyButton(props: { projectId: string; apiKeyId: string }) {</DialogTrigger><DialogContent><DialogHeader>- <DialogTitle className="mb-5">Delete API key</DialogTitle>+ <DialogTitle className="mb-5">Delete LLM provider</DialogTitle></DialogHeader><DialogDescription>- Are you sure you want to delete this API key? This action cannot be- undone.+ Are you sure you want to delete this LLM provider? This action cannot+ be undone.</DialogDescription><DialogFooter><Button@@ -172,143 +159,3 @@ function DeleteApiKeyButton(props: { projectId: string; apiKeyId: string }) {</Dialog>);}--const formSchema = z.object({- secretKey: z.string().min(1),- provider: z.nativeEnum(ModelProvider),-});--export function CreateLlmApiKeyComponent(props: {- projectId: string;- existingApiKeys: RouterOutput["llmApiKey"]["all"]["data"];-}) {- const capture = usePostHogClientCapture();- 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;- }- capture("project_settings:llm_api_key_create", {- provider: values.provider,- });-- 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>- <FormDescription>- Your API keys are stored encrypted on our servers.- </FormDescription>- <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)- }- >- <FormControl>- <SelectTrigger>- <SelectValue placeholder="Select a LLM provider" />- </SelectTrigger>- </FormControl>- <SelectContent>- {Object.values(ModelProvider).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/worker/src/__tests__/eval-service.test.ts b/worker/src/__tests__/eval-service.test.tsindex 7ba589bda6..963a38a85a 100644--- a/worker/src/__tests__/eval-service.test.ts+++ b/worker/src/__tests__/eval-service.test.ts@@ -9,7 +9,11 @@ import { randomUUID } from "crypto";import Decimal from "decimal.js";import { pruneDatabase } from "./utils";import { sql } from "kysely";-import { LangfuseNotFoundError, variableMappingList } from "@langfuse/shared";+import {+ LLMAdapter,+ LangfuseNotFoundError,+ variableMappingList,+} from "@langfuse/shared";import { encrypt } from "@langfuse/shared/encryption";import { OpenAIServer } from "./network";import { afterEach } from "node:test";@@ -275,6 +279,7 @@ describe("execute evals", () => {version: 1,prompt: "Please evaluate toxicity {{input}} {{output}}",model: "gpt-3.5-turbo",+ provider: "openai",model_params: {},output_schema: {reasoning: "Please explain your reasoning",@@ -326,6 +331,8 @@ describe("execute evals", () => {project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",secret_key: encrypt(String(OPENAI_API_KEY)),provider: "openai",+ adapter: LLMAdapter.OpenAI,+ custom_models: [],display_secret_key: "123456",}).execute();@@ -387,6 +394,7 @@ describe("execute evals", () => {version: 1,prompt: "Please evaluate toxicity {{input}} {{output}}",model: "gpt-3.5-turbo",+ provider: "openai",model_params: {},output_schema: {reasoning: "Please explain your reasoning",@@ -480,6 +488,7 @@ describe("execute evals", () => {version: 1,prompt: "Please evaluate toxicity {{input}} {{output}}",model: "gpt-3.5-turbo",+ provider: "openai",model_params: {},output_schema: {reasoning: "Please explain your reasoning",diff --git a/worker/src/features/evaluation/eval-service.ts b/worker/src/features/evaluation/eval-service.tsindex f00d647619..907e714054 100644--- a/worker/src/features/evaluation/eval-service.ts+++ b/worker/src/features/evaluation/eval-service.ts@@ -8,13 +8,11 @@ import {availableEvalVariables,ChatMessageRole,EvalExecutionEvent,- evalLLMModels,- EvalModelNames,evalTableCols,fetchLLMCompletion,ForbiddenError,LangfuseNotFoundError,- ModelProvider,+ LLMApiKeySchema,Prisma,QueueJobs,QueueName,@@ -249,34 +247,21 @@ export const evaluate = async ({reasoning: z.string().describe(parsedOutputSchema.reasoning),});- const evalModel = EvalModelNames.parse(template.model);- const provider = evalLLMModels.find((m) => m.model.value === evalModel)- ?.provider.value;const modelParams = ZodModelConfig.parse(template.model_params);- if (!provider) {- throw new LangfuseNotFoundError(`Model ${evalModel} provider not found`);- }-- if (provider !== ModelProvider.OpenAI) {- // Needed for type checking downstream in the fetchLLMCompletion function- throw new ForbiddenError(- `Model ${evalModel} provider ${provider} not supported`- );- }-// 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();+ const apiKey = await prisma.llmApiKeys.findFirst({+ where: {+ projectId: event.projectId,+ provider: template.provider,+ },+ });+ const parsedKey = LLMApiKeySchema.safeParse(apiKey);- if (!apiKey) {+ if (!parsedKey.success) {// this will fail the eval execution if a user deletes the API key.throw new LangfuseNotFoundError(- `API key for provider ${provider} and project ${event.projectId} not found.`+ `API key for provider ${template.provider} and project ${event.projectId} not found.`);}@@ -284,11 +269,13 @@ export const evaluate = async ({try {completion = await fetchLLMCompletion({streaming: false,- apiKey: decrypt(apiKey.secret_key), // decrypt the secret key+ apiKey: decrypt(parsedKey.data.secretKey), // decrypt the secret key+ baseURL: parsedKey.data.baseURL || undefined,messages: [{ role: ChatMessageRole.System, content: prompt }],modelParams: {- provider,- model: evalModel,+ provider: template.provider,+ model: template.model,+ adapter: parsedKey.data.adapter,...modelParams,},functionCall: {