🪢 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
refactor(fetchLLMCompletion): simplify interface (#9493)
Hassieb Pakzade639e866e191
diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.tsindex a4847a0238..b57e10d8ca 100644--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts@@ -25,10 +25,7 @@ import GCPServiceAccountKeySchema, {BedrockCredentialSchema,VertexAIConfigSchema,BEDROCK_USE_DEFAULT_CREDENTIALS,- BedrockCredential,} from "../../interfaces/customLLMProviderConfigSchemas";-import { processEventBatch } from "../ingestion/processEventBatch";-import { logger } from "../logger";import {ChatMessage,ChatMessageRole,@@ -41,11 +38,13 @@ import {OpenAIModel,ToolCallResponse,ToolCallResponseSchema,- TraceParams,+ TraceSinkParams,} from "./types";-import { CallbackHandler } from "langfuse-langchain";import type { BaseCallbackHandler } from "@langchain/core/callbacks/base";import { HttpsProxyAgent } from "https-proxy-agent";+import { getInternalTracingHandler } from "./getInternalTracingHandler";+import { decrypt } from "../../encryption";+import { decryptAndParseExtraHeaders } from "./utils";const isLangfuseCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);@@ -54,29 +53,6 @@ const PROVIDERS_WITH_REQUIRED_USER_MESSAGE = [LLMAdapter.Anthropic,];-const resolveBedrockCredentials = (- apiKey: string,- context: LLMCompletionContext,-): BedrockCredential | undefined => {- // Default credentials can only be used in self-hosted deployments or when credentials are managed by langfuse- const canUseDefaultCredentials =- !isLangfuseCloud || context.credentials === "langfuse";- return apiKey === BEDROCK_USE_DEFAULT_CREDENTIALS && canUseDefaultCredentials- ? undefined // undefined = use AWS SDK default credential provider chain- : BedrockCredentialSchema.parse(JSON.parse(apiKey));-};--const resolveBedrockRegion = (- context: LLMCompletionContext,- config?: Record<string, string> | null,-): string | undefined => {- if (context.credentials === "langfuse") {- return env.LANGFUSE_AWS_BEDROCK_REGION ?? undefined;- }- const { region } = BedrockConfigSchema.parse(config);- return region;-};-const transformSystemMessageToUserMessage = (messages: ChatMessage[],): BaseMessage[] => {@@ -89,30 +65,21 @@ const transformSystemMessageToUserMessage = (type ProcessTracedEvents = () => Promise<void>;-type LLMCompletionContext = {- tracing: "langfuse";- credentials: "user" | "langfuse";-};--const DEFAULT_LLM_COMPLETION_CONTEXT: LLMCompletionContext = {- tracing: "langfuse",- credentials: "user",-};-type LLMCompletionParams = {messages: ChatMessage[];modelParams: ModelParams;+ llmConnection: {+ secretKey: string;+ extraHeaders?: string | null;+ baseURL?: string | null;+ config?: Record<string, string> | null;+ };structuredOutputSchema?: ZodSchema | LLMJSONSchema;callbacks?: BaseCallbackHandler[];- baseURL?: string;- apiKey: string;- extraHeaders?: Record<string, string>;maxRetries?: number;- config?: Record<string, string> | null;- traceParams?: TraceParams;+ traceSinkParams?: TraceSinkParams;throwOnError?: boolean; // default is true- context?: LLMCompletionContext;- generationMetadata?: Record<string, unknown>;+ shouldUseLangfuseAPIKey?: boolean;};type FetchLLMCompletionParams = LLMCompletionParams & {@@ -172,75 +139,31 @@ export async function fetchLLMCompletion(| ToolCallResponse;processTracedEvents: ProcessTracedEvents;}> {- // the apiKey must never be printed to the consoleconst {messages,tools,modelParams,streaming,callbacks,- apiKey,- baseURL,+ llmConnection,maxRetries,- config,- traceParams,- extraHeaders,+ traceSinkParams,throwOnError = true,- context = DEFAULT_LLM_COMPLETION_CONTEXT,+ shouldUseLangfuseAPIKey = false,} = params;+ const { baseURL, config } = llmConnection;+ const apiKey = decrypt(llmConnection.secretKey); // the apiKey must never be printed to the console+ const extraHeaders = decryptAndParseExtraHeaders(llmConnection.extraHeaders);+let finalCallbacks: BaseCallbackHandler[] | undefined = callbacks ?? [];let processTracedEvents: ProcessTracedEvents = () => Promise.resolve();- if (traceParams) {- const handler = new CallbackHandler({- _projectId: traceParams.projectId,- _isLocalEventExportEnabled: true,- environment: traceParams.environment,- metadata: traceParams.metadata,- userId: traceParams.userId,- });-- processTracedEvents = async () => {- try {- const events = await handler.langfuse._exportLocalEvents(- traceParams.projectId,- );- // to add the prompt name and version to only generation-type observations- const processedEvents = events.map((event: any) => {- if (event.type === "generation-create" && params.generationMetadata) {- const promptName = params.generationMetadata[- "langfuse.observation.prompt.name"- ] as string;- const promptVersion = params.generationMetadata[- "langfuse.observation.prompt.version"- ] as number;-- return {- ...event,- body: {- ...event.body,- ...(promptName && { promptName }),- ...(promptVersion && { promptVersion }),- },- };- }- return event;- });+ if (traceSinkParams) {+ const internalTracingHandler = getInternalTracingHandler(traceSinkParams);+ processTracedEvents = internalTracingHandler.processTracedEvents;- await processEventBatch(- JSON.parse(JSON.stringify(processedEvents)), // stringify to emulate network event batch from network call- traceParams.authCheck,- {- isLangfuseInternal: context.tracing === "langfuse",- },- );- } catch (e) {- logger.error("Failed to process traced events", { error: e });- }- };-- finalCallbacks.push(handler);+ finalCallbacks.push(internalTracingHandler.handler);}finalCallbacks = finalCallbacks.length > 0 ? finalCallbacks : undefined;@@ -313,7 +236,7 @@ export async function fetchLLMCompletion(if (modelParams.adapter === LLMAdapter.Anthropic) {chatModel = new ChatAnthropic({anthropicApiKey: apiKey,- anthropicApiUrl: baseURL,+ anthropicApiUrl: baseURL ?? undefined,modelName: modelParams.model,temperature: modelParams.temperature,maxTokens: modelParams.max_tokens,@@ -349,7 +272,7 @@ export async function fetchLLMCompletion(} else if (modelParams.adapter === LLMAdapter.Azure) {chatModel = new AzureChatOpenAI({azureOpenAIApiKey: apiKey,- azureOpenAIBasePath: baseURL,+ azureOpenAIBasePath: baseURL ?? undefined,azureOpenAIApiDeploymentName: modelParams.model,azureOpenAIApiVersion: "2025-02-01-preview",temperature: modelParams.temperature,@@ -365,9 +288,18 @@ export async function fetchLLMCompletion(modelKwargs: modelParams.providerOptions,});} else if (modelParams.adapter === LLMAdapter.Bedrock) {+ const { region } = shouldUseLangfuseAPIKey+ ? { region: env.LANGFUSE_AWS_BEDROCK_REGION }+ : BedrockConfigSchema.parse(config);+// Handle both explicit credentials and default provider chain- const credentials = resolveBedrockCredentials(apiKey, context);- const region = resolveBedrockRegion(context, config);+ // Only allow default provider chain in self-hosted or internal AI features+ const isSelfHosted = !isLangfuseCloud;+ const credentials =+ apiKey === BEDROCK_USE_DEFAULT_CREDENTIALS &&+ (isSelfHosted || shouldUseLangfuseAPIKey)+ ? undefined // undefined = use AWS SDK default credential provider chain+ : BedrockCredentialSchema.parse(JSON.parse(apiKey));chatModel = new ChatBedrockConverse({model: modelParams.model,@@ -422,8 +354,8 @@ export async function fetchLLMCompletion(const runConfig = {callbacks: finalCallbacks,- runId: traceParams?.traceId,- runName: traceParams?.traceName,+ runId: traceSinkParams?.traceId,+ runName: traceSinkParams?.traceName,};try {diff --git a/packages/shared/src/server/llm/getInternalTracingHandler.ts b/packages/shared/src/server/llm/getInternalTracingHandler.tsnew file mode 100644index 0000000000..39b5e25114--- /dev/null+++ b/packages/shared/src/server/llm/getInternalTracingHandler.ts@@ -0,0 +1,58 @@+import CallbackHandler from "langfuse-langchain";+import { TraceSinkParams } from "./types";+import { processEventBatch } from "../ingestion/processEventBatch";+import { logger } from "../logger";++export function getInternalTracingHandler(traceSinkParams: TraceSinkParams): {+ handler: CallbackHandler;+ processTracedEvents: () => Promise<void>;+} {+ const { prompt, targetProjectId, environment, metadata, userId } =+ traceSinkParams;+ const handler = new CallbackHandler({+ _projectId: targetProjectId,+ _isLocalEventExportEnabled: true,+ environment: environment,+ metadata: metadata,+ userId: userId,+ });++ const processTracedEvents = async () => {+ try {+ const events = await handler.langfuse._exportLocalEvents(+ traceSinkParams.targetProjectId,+ );+ // to add the prompt name and version to only generation-type observations+ const processedEvents = events.map((event: any) => {+ if (event.type === "generation-create" && prompt) {+ return {+ ...event,+ body: {+ ...event.body,+ ...{ promptName: prompt.name, promptVersion: prompt.version },+ },+ };+ }+ return event;+ });++ await processEventBatch(+ JSON.parse(JSON.stringify(processedEvents)), // stringify to emulate network event batch from network call+ {+ validKey: true as const,+ scope: {+ projectId: traceSinkParams.targetProjectId, // Important: this controls into what project traces are ingested.+ accessLevel: "project",+ } as any,+ },+ {+ isLangfuseInternal: true,+ },+ );+ } catch (e) {+ logger.error("Failed to process traced events", { error: e });+ }+ };++ return { handler, processTracedEvents };+}diff --git a/packages/shared/src/server/llm/testModelCall.ts b/packages/shared/src/server/llm/testModelCall.tsindex 642056965a..68e5b5b144 100644--- a/packages/shared/src/server/llm/testModelCall.ts+++ b/packages/shared/src/server/llm/testModelCall.ts@@ -5,9 +5,7 @@ import {LLMApiKeySchema,type ModelConfig,} from "./types";-import { decrypt } from "../../encryption";import { fetchLLMCompletion } from "./fetchLLMCompletion";-import { decryptAndParseExtraHeaders } from "./utils";import z from "zod/v4";export const testModelCall = async ({@@ -26,9 +24,7 @@ export const testModelCall = async ({(await fetchLLMCompletion({streaming: false,- apiKey: decrypt(apiKey.secretKey), // decrypt the secret key- extraHeaders: decryptAndParseExtraHeaders(apiKey.extraHeaders),- baseURL: apiKey.baseURL ?? undefined,+ llmConnection: apiKey,messages: [{role: ChatMessageRole.User,@@ -46,7 +42,6 @@ export const testModelCall = async ({score: zodV3.string(),reasoning: zodV3.string(),}),- config: apiKey.config,})).completion;};diff --git a/packages/shared/src/server/llm/types.ts b/packages/shared/src/server/llm/types.tsindex 0287f44cea..1f2acfff86 100644--- a/packages/shared/src/server/llm/types.ts+++ b/packages/shared/src/server/llm/types.ts@@ -4,7 +4,6 @@ import {BedrockConfigSchema,VertexAIConfigSchema,} from "../../interfaces/customLLMProviderConfigSchemas";-import { AuthHeaderValidVerificationResult } from "../auth/types";import { JSONObjectSchema } from "../../utils/zod";/* eslint-disable no-unused-vars */@@ -492,19 +491,23 @@ export type LLMApiKey =? z.infer<typeof LLMApiKeySchema>: never;-// NOTE: This string is whitelisted in the TS SDK to allow ingestion of traces by Langfuse. Please mirror edits to this string in https://github.com/langfuse/langfuse-js/blob/main/langfuse-core/src/index.ts.-export const PROMPT_EXPERIMENT_ENVIRONMENT =- "langfuse-prompt-experiment" as const;--type PromptExperimentEnvironment = typeof PROMPT_EXPERIMENT_ENVIRONMENT;+export enum LangfuseInternalTraceEnvironment {+ PromptExperiments = "langfuse-prompt-experiment",+}-export type TraceParams = {- traceName: string;+export type TraceSinkParams = {+ /**+ * IMPORTANT: This controls into what project the resulting traces are ingested.+ */+ targetProjectId: string;traceId: string;- metadata?: Record<string, unknown>;- projectId: string;- // TODO: add more possibilities for environment re: langfuse AI features- environment: PromptExperimentEnvironment | string;- authCheck: AuthHeaderValidVerificationResult;+ traceName: string;+ // NOTE: These strings must be whitelisted in the TS SDK to allow ingestion of traces by Langfuse. Please mirror edits to this string in https://github.com/langfuse/langfuse-js/blob/main/langfuse-core/src/index.ts.+ environment: string;userId?: string;+ metadata?: Record<string, unknown>;+ prompt?: {+ name: string;+ version: number;+ };};diff --git a/web/src/features/llm-api-key/server/router.ts b/web/src/features/llm-api-key/server/router.tsindex 606038e31d..df63d29a17 100644--- a/web/src/features/llm-api-key/server/router.ts+++ b/web/src/features/llm-api-key/server/router.ts@@ -93,13 +93,16 @@ async function testLLMConnection(provider: params.provider,model,},- baseURL: params.baseURL || undefined,- apiKey: params.secretKey,- extraHeaders: params.extraHeaders,+ llmConnection: {+ secretKey: encrypt(params.secretKey),+ extraHeaders:+ params.extraHeaders && encrypt(JSON.stringify(params.extraHeaders)),+ baseURL: params.baseURL || undefined,+ config: parsedConfig,+ },messages: testMessages,streaming: false,maxRetries: 1,- config: parsedConfig,});return { success: true };diff --git a/web/src/features/natural-language-filters/server/router.ts b/web/src/features/natural-language-filters/server/router.tsindex 0f33ec7988..ef96ae6ff4 100644--- a/web/src/features/natural-language-filters/server/router.ts+++ b/web/src/features/natural-language-filters/server/router.ts@@ -8,7 +8,7 @@ import {ChatMessageType,fetchLLMCompletion,logger,- type TraceParams,+ type TraceSinkParams,} from "@langfuse/shared/src/server";import { env } from "@/src/env.mjs";import { CreateNaturalLanguageFilterCompletion } from "./validation";@@ -20,6 +20,7 @@ import {import { randomBytes } from "crypto";import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { BEDROCK_USE_DEFAULT_CREDENTIALS } from "@langfuse/shared";+import { encrypt } from "@langfuse/shared/encryption";export const naturalLanguageFilterRouter = createTRPCRouter({createCompletion: protectedProjectProcedure@@ -84,22 +85,24 @@ export const naturalLanguageFilterRouter = createTRPCRouter({{ type: "chat" },);- const traceParams: TraceParams = {+ if (!env.LANGFUSE_AI_FEATURES_PROJECT_ID) {+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Langfuse AI Features not configured.",+ });+ }++ const traceSinkParams: TraceSinkParams = {environment: getEnvironment(),traceName: "natural-language-filter",traceId: randomBytes(16).toString("hex"),- projectId: env.LANGFUSE_AI_FEATURES_PROJECT_ID as string,- authCheck: {- validKey: true as const,- scope: {- projectId: env.LANGFUSE_AI_FEATURES_PROJECT_ID,- accessLevel: "project",- } as any,- },+ targetProjectId: env.LANGFUSE_AI_FEATURES_PROJECT_ID,userId: ctx.session.user.id,metadata: {langfuse_user_id: ctx.session.user.id,+ langfuse_project_id: ctx.session.projectId,},+ prompt: promptResponse,};// Get current datetime in ISO format with day of week for AI context@@ -119,17 +122,12 @@ export const naturalLanguageFilterRouter = createTRPCRouter({type: ChatMessageType.PublicAPICreated,})),modelParams,- apiKey: BEDROCK_USE_DEFAULT_CREDENTIALS,- streaming: false,- traceParams,- context: {- tracing: "langfuse",- credentials: "langfuse",- },- generationMetadata: {- "langfuse.observation.prompt.name": promptResponse.name,- "langfuse.observation.prompt.version": promptResponse.version,+ llmConnection: {+ secretKey: encrypt(BEDROCK_USE_DEFAULT_CREDENTIALS),},+ streaming: false,+ traceSinkParams,+ shouldUseLangfuseAPIKey: true,});await llmCompletion.processTracedEvents();diff --git a/web/src/features/playground/server/chatCompletionHandler.ts b/web/src/features/playground/server/chatCompletionHandler.tsindex 3a662c9f8a..dbfc4fa813 100644--- a/web/src/features/playground/server/chatCompletionHandler.ts+++ b/web/src/features/playground/server/chatCompletionHandler.ts@@ -12,12 +12,10 @@ import { authorizeRequestOrThrow } from "./authorizeRequest";import { validateChatCompletionBody } from "./validateChatCompletionBody";import { prisma } from "@langfuse/shared/src/db";-import { decrypt } from "@langfuse/shared/encryption";import {LLMApiKeySchema,logger,fetchLLMCompletion,- decryptAndParseExtraHeaders,} from "@langfuse/shared/src/server";export default async function chatCompletionHandler(req: NextRequest) {@@ -48,14 +46,11 @@ export default async function chatCompletionHandler(req: NextRequest) {}const fetchLLMCompletionParams = {+ llmConnection: parsedKey.data,messages,modelParams,structuredOutputSchema,callbacks: [new PosthogCallbackHandler("playground", body, userId)],- apiKey: decrypt(parsedKey.data.secretKey),- extraHeaders: decryptAndParseExtraHeaders(parsedKey.data.extraHeaders),- baseURL: parsedKey.data.baseURL || undefined,- config: parsedKey.data.config,};if (structuredOutputSchema) {diff --git a/worker/src/__tests__/llmConnections.test.ts b/worker/src/__tests__/llmConnections.test.tsindex 91b87b95e8..d3cde8a00b 100644--- a/worker/src/__tests__/llmConnections.test.ts+++ b/worker/src/__tests__/llmConnections.test.ts@@ -1,5 +1,6 @@import { describe, test, expect } from "vitest";import { fetchLLMCompletion } from "@langfuse/shared/src/server";+import { encrypt } from "@langfuse/shared/encryption";import { ChatMessageType, LLMAdapter } from "@langfuse/shared";import { z } from "zod/v3";@@ -80,7 +81,9 @@ describe("LLM Connection Tests", () => {temperature: 0,max_tokens: 10,},- apiKey: process.env.LANGFUSE_LLM_CONNECTION_OPENAI_KEY!,+ llmConnection: {+ secretKey: encrypt(process.env.LANGFUSE_LLM_CONNECTION_OPENAI_KEY!),+ },});expect(typeof completion).toBe("string");@@ -108,7 +111,9 @@ describe("LLM Connection Tests", () => {max_tokens: 200,},structuredOutputSchema: evalOutputSchema,- apiKey: process.env.LANGFUSE_LLM_CONNECTION_OPENAI_KEY!,+ llmConnection: {+ secretKey: encrypt(process.env.LANGFUSE_LLM_CONNECTION_OPENAI_KEY!),+ },});const parsed = evalOutputSchema.safeParse(completion);@@ -140,7 +145,9 @@ describe("LLM Connection Tests", () => {max_tokens: 100,},tools: [weatherTool],- apiKey: process.env.LANGFUSE_LLM_CONNECTION_OPENAI_KEY!,+ llmConnection: {+ secretKey: encrypt(process.env.LANGFUSE_LLM_CONNECTION_OPENAI_KEY!),+ },});expect(completion).toHaveProperty("tool_calls");@@ -183,7 +190,11 @@ describe("LLM Connection Tests", () => {temperature: 0,max_tokens: 10,},- apiKey: process.env.LANGFUSE_LLM_CONNECTION_ANTHROPIC_KEY!,+ llmConnection: {+ secretKey: encrypt(+ process.env.LANGFUSE_LLM_CONNECTION_ANTHROPIC_KEY!,+ ),+ },});expect(typeof completion).toBe("string");@@ -211,7 +222,11 @@ describe("LLM Connection Tests", () => {max_tokens: 200,},structuredOutputSchema: evalOutputSchema,- apiKey: process.env.LANGFUSE_LLM_CONNECTION_ANTHROPIC_KEY!,+ llmConnection: {+ secretKey: encrypt(+ process.env.LANGFUSE_LLM_CONNECTION_ANTHROPIC_KEY!,+ ),+ },});const parsed = evalOutputSchema.safeParse(completion);@@ -243,7 +258,11 @@ describe("LLM Connection Tests", () => {max_tokens: 100,},tools: [weatherTool],- apiKey: process.env.LANGFUSE_LLM_CONNECTION_ANTHROPIC_KEY!,+ llmConnection: {+ secretKey: encrypt(+ process.env.LANGFUSE_LLM_CONNECTION_ANTHROPIC_KEY!,+ ),+ },});expect(completion).toHaveProperty("tool_calls");@@ -298,8 +317,10 @@ describe("LLM Connection Tests", () => {temperature: 0,max_tokens: 10,},- apiKey: process.env.LANGFUSE_LLM_CONNECTION_AZURE_KEY!,- baseURL: process.env.LANGFUSE_LLM_CONNECTION_AZURE_BASE_URL!,+ llmConnection: {+ secretKey: encrypt(process.env.LANGFUSE_LLM_CONNECTION_AZURE_KEY!),+ baseURL: process.env.LANGFUSE_LLM_CONNECTION_AZURE_BASE_URL!,+ },});expect(typeof completion).toBe("string");@@ -327,8 +348,10 @@ describe("LLM Connection Tests", () => {max_tokens: 200,},structuredOutputSchema: evalOutputSchema,- apiKey: process.env.LANGFUSE_LLM_CONNECTION_AZURE_KEY!,- baseURL: process.env.LANGFUSE_LLM_CONNECTION_AZURE_BASE_URL!,+ llmConnection: {+ secretKey: encrypt(process.env.LANGFUSE_LLM_CONNECTION_AZURE_KEY!),+ baseURL: process.env.LANGFUSE_LLM_CONNECTION_AZURE_BASE_URL!,+ },});const parsed = evalOutputSchema.safeParse(completion);@@ -360,8 +383,10 @@ describe("LLM Connection Tests", () => {max_tokens: 100,},tools: [weatherTool],- apiKey: process.env.LANGFUSE_LLM_CONNECTION_AZURE_KEY!,- baseURL: process.env.LANGFUSE_LLM_CONNECTION_AZURE_BASE_URL!,+ llmConnection: {+ secretKey: encrypt(process.env.LANGFUSE_LLM_CONNECTION_AZURE_KEY!),+ baseURL: process.env.LANGFUSE_LLM_CONNECTION_AZURE_BASE_URL!,+ },});expect(completion).toHaveProperty("tool_calls");@@ -433,8 +458,10 @@ describe("LLM Connection Tests", () => {temperature: 0,max_tokens: 10,},- apiKey: getApiKey(),- config: getConfig(),+ llmConnection: {+ secretKey: encrypt(getApiKey()),+ config: getConfig(),+ },});expect(typeof completion).toBe("string");@@ -463,8 +490,7 @@ describe("LLM Connection Tests", () => {max_tokens: 200,},structuredOutputSchema: evalOutputSchema,- apiKey: getApiKey(),- config: getConfig(),+ llmConnection: { secretKey: encrypt(getApiKey()), config: getConfig() },});const parsed = evalOutputSchema.safeParse(completion);@@ -496,8 +522,10 @@ describe("LLM Connection Tests", () => {max_tokens: 100,},tools: [weatherTool],- apiKey: getApiKey(),- config: getConfig(),+ llmConnection: {+ secretKey: encrypt(getApiKey()),+ config: getConfig(),+ },});expect(completion).toHaveProperty("tool_calls");@@ -540,8 +568,10 @@ describe("LLM Connection Tests", () => {temperature: 0,max_tokens: 10,},- apiKey: process.env.LANGFUSE_LLM_CONNECTION_VERTEXAI_KEY!,- config: null,+ llmConnection: {+ secretKey: encrypt(process.env.LANGFUSE_LLM_CONNECTION_VERTEXAI_KEY!),+ config: null,+ },});expect(typeof completion).toBe("string");@@ -569,8 +599,10 @@ describe("LLM Connection Tests", () => {max_tokens: 200,},structuredOutputSchema: evalOutputSchema,- apiKey: process.env.LANGFUSE_LLM_CONNECTION_VERTEXAI_KEY!,- config: null,+ llmConnection: {+ secretKey: encrypt(process.env.LANGFUSE_LLM_CONNECTION_VERTEXAI_KEY!),+ config: null,+ },});const parsed = evalOutputSchema.safeParse(completion);@@ -602,8 +634,10 @@ describe("LLM Connection Tests", () => {max_tokens: 100,},tools: [weatherTool],- apiKey: process.env.LANGFUSE_LLM_CONNECTION_VERTEXAI_KEY!,- config: null,+ llmConnection: {+ secretKey: encrypt(process.env.LANGFUSE_LLM_CONNECTION_VERTEXAI_KEY!),+ config: null,+ },});expect(completion).toHaveProperty("tool_calls");@@ -646,7 +680,11 @@ describe("LLM Connection Tests", () => {temperature: 0,max_tokens: 10,},- apiKey: process.env.LANGFUSE_LLM_CONNECTION_GOOGLEAISTUDIO_KEY!,+ llmConnection: {+ secretKey: encrypt(+ process.env.LANGFUSE_LLM_CONNECTION_GOOGLEAISTUDIO_KEY!,+ ),+ },});expect(typeof completion).toBe("string");@@ -674,7 +712,11 @@ describe("LLM Connection Tests", () => {max_tokens: 200,},structuredOutputSchema: evalOutputSchema,- apiKey: process.env.LANGFUSE_LLM_CONNECTION_GOOGLEAISTUDIO_KEY!,+ llmConnection: {+ secretKey: encrypt(+ process.env.LANGFUSE_LLM_CONNECTION_GOOGLEAISTUDIO_KEY!,+ ),+ },});const parsed = evalOutputSchema.safeParse(completion);@@ -706,7 +748,11 @@ describe("LLM Connection Tests", () => {max_tokens: 100,},tools: [weatherTool],- apiKey: process.env.LANGFUSE_LLM_CONNECTION_GOOGLEAISTUDIO_KEY!,+ llmConnection: {+ secretKey: encrypt(+ process.env.LANGFUSE_LLM_CONNECTION_GOOGLEAISTUDIO_KEY!,+ ),+ },});expect(completion).toHaveProperty("tool_calls");diff --git a/worker/src/features/evaluation/evalService.ts b/worker/src/features/evaluation/evalService.tsindex feafd5050b..1028b02e84 100644--- a/worker/src/features/evaluation/evalService.ts+++ b/worker/src/features/evaluation/evalService.ts@@ -55,7 +55,7 @@ import {} from "@langfuse/shared";import { kyselyPrisma, prisma } from "@langfuse/shared/src/db";import { backOff } from "exponential-backoff";-import { callStructuredLLM, compileHandlebarString } from "../utils";+import { callLLM, compileHandlebarString } from "../utils";import { env } from "../../env";import { JSONPath } from "jsonpath-plus";@@ -696,22 +696,28 @@ export const evaluate = async ({} as const,];- const parsedLLMOutput = await backOff(+ const llmOutput = await backOff(async () =>- await callStructuredLLM(- event.jobExecutionId,- modelConfig.config.apiKey,+ await callLLM({+ llmApiKey: modelConfig.config.apiKey,messages,- modelConfig.config.modelParams ?? {},- modelConfig.config.provider,- modelConfig.config.model,- evalScoreSchema,- ),+ modelParams: modelConfig.config.modelParams ?? {},+ provider: modelConfig.config.provider,+ model: modelConfig.config.model,+ structuredOutputSchema: evalScoreSchema,+ }),{numOfAttempts: 1, // turn off retries as Langchain is doing that for us already.},);+ const parsedLLMOutput = evalScoreSchema.safeParse(llmOutput);+ if (!parsedLLMOutput.success) {+ throw Error(+ `Invalid LLM response format. Model: ${modelConfig.config.model}, Response: ${llmOutput}`,+ );+ }+logger.debug(`Evaluating job ${event.jobExecutionId} Parsed LLM output ${JSON.stringify(parsedLLMOutput)}`,);@@ -724,8 +730,8 @@ export const evaluate = async ({traceId: job.job_input_trace_id,observationId: job.job_input_observation_id,name: config.score_name,- value: parsedLLMOutput.score,- comment: parsedLLMOutput.reasoning,+ value: parsedLLMOutput.data.score,+ comment: parsedLLMOutput.data.reasoning,source: ScoreSource.EVAL,environment: environment ?? "default",};@@ -790,7 +796,7 @@ export const evaluate = async ({.execute();logger.debug(- `Eval job ${job.id} for project ${event.projectId} completed with score ${parsedLLMOutput.score}`,+ `Eval job ${job.id} for project ${event.projectId} completed with score ${parsedLLMOutput.data.score}`,);};diff --git a/worker/src/features/experiments/experimentServiceClickhouse.ts b/worker/src/features/experiments/experimentServiceClickhouse.tsindex 56bbc47988..d488583c02 100644--- a/worker/src/features/experiments/experimentServiceClickhouse.ts+++ b/worker/src/features/experiments/experimentServiceClickhouse.ts@@ -1,4 +1,4 @@-import { DatasetStatus, Prisma } from "@langfuse/shared";+import { DatasetItem, DatasetStatus, Prisma } from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";import {ChatMessage,@@ -6,12 +6,13 @@ import {eventTypes,ExperimentCreateEventSchema,IngestionEventType,+ LangfuseInternalTraceEnvironment,logger,processEventBatch,- PROMPT_EXPERIMENT_ENVIRONMENT,queryClickhouse,QueueJobs,redis,+ TraceSinkParams,} from "@langfuse/shared/src/server";import { v4 } from "uuid";import z from "zod/v4";@@ -21,6 +22,7 @@ import {replaceVariablesInPrompt,validateAndSetupExperiment,validateDatasetItem,+ type PromptExperimentConfig,} from "./utils";import { backOff } from "exponential-backoff";import { callLLM } from "../utils";@@ -59,8 +61,8 @@ async function getExistingRunItemDatasetItemIds(async function processItem(projectId: string,- datasetItem: any,- config: any,+ datasetItem: DatasetItem & { input: Prisma.JsonObject },+ config: PromptExperimentConfig,): Promise<{ success: boolean }> {// Use unified trace ID to avoid creating duplicate traces between PostgreSQL and ClickHouseconst newTraceId = generateUnifiedTraceId(config.runId, datasetItem.id);@@ -146,8 +148,8 @@ async function processItem(async function processLLMCall(runItemId: string,traceId: string,- datasetItem: any,- config: any,+ datasetItem: DatasetItem & { input: Prisma.JsonObject },+ config: PromptExperimentConfig,): Promise<{ success: boolean }> {let messages: ChatMessage[] = [];// Extract and replace variables in prompt@@ -166,34 +168,28 @@ async function processLLMCall(return { success: false };}- const traceParams = {- environment: PROMPT_EXPERIMENT_ENVIRONMENT,+ const traceSinkParams: TraceSinkParams = {+ environment: LangfuseInternalTraceEnvironment.PromptExperiments,traceName: `dataset-run-item-${runItemId.slice(0, 5)}`,traceId,- projectId: config.projectId,+ targetProjectId: config.projectId, // ingest to user projectmetadata: {+ dataset_id: datasetItem.datasetId,+ dataset_item_id: datasetItem.id,structured_output_schema: config.structuredOutputSchema,},- authCheck: {- validKey: true as const,- scope: {- projectId: config.projectId,- accessLevel: "project",- } as any,- },};await backOff(async () =>- await callLLM(- config.validatedApiKey,+ await callLLM({+ llmApiKey: config.validatedApiKey,+ modelParams: config.model_params,messages,- config.model_params,- config.provider,- config.model,- traceParams,- config.structuredOutputSchema,- ),+ traceSinkParams,+ throwOnError: false,+ ...config,+ }),{numOfAttempts: 1, // Turn off retries as Langchain handles this},@@ -206,7 +202,7 @@ async function getItemsToProcess(projectId: string,datasetId: string,runId: string,- config: any,+ config: PromptExperimentConfig,) {// Fetch all dataset itemsconst datasetItems = await prisma.datasetItem.findMany({@@ -272,7 +268,7 @@ export const createExperimentJobClickhouse = async ({* INPUT VALIDATION *********************/- let experimentConfig;+ let experimentConfig: PromptExperimentConfig;try {experimentConfig = await validateAndSetupExperiment(event);} catch (error) {@@ -402,7 +398,7 @@ async function createAllDatasetRunItemsWithConfigError(timestamp,body: {id: traceId,- environment: PROMPT_EXPERIMENT_ENVIRONMENT,+ environment: LangfuseInternalTraceEnvironment.PromptExperiments,name: `dataset-run-item-${runItemId.slice(0, 5)}`,input: stringInput,},@@ -414,7 +410,7 @@ async function createAllDatasetRunItemsWithConfigError(timestamp,body: {id: generationId,- environment: PROMPT_EXPERIMENT_ENVIRONMENT,+ environment: LangfuseInternalTraceEnvironment.PromptExperiments,traceId,input: stringInput,level: "ERROR" as const,diff --git a/worker/src/features/experiments/utils.ts b/worker/src/features/experiments/utils.tsindex 4e5b400106..495aa0be4f 100644--- a/worker/src/features/experiments/utils.ts+++ b/worker/src/features/experiments/utils.ts@@ -76,9 +76,11 @@ export const parseDatasetItemInput = (value === null ? null : stringifyValue(value),]),);+return filteredInput;} catch (error) {logger.info("Error parsing dataset item input:", error);+return itemInput;}};@@ -107,10 +109,14 @@ export const fetchPrompt = async (promptId: string, projectId: string) => {export const replaceVariablesInPrompt = (prompt: PromptContent,- itemInput: Record<string, any>,+ itemInput: Record<string, any> | null,variables: string[],placeholderNames: string[] = [],): ChatMessage[] => {+ if (!itemInput) {+ throw Error("Dataset item has no input.");+ }+const processContent = (content: string) => {// Extract only Handlebars variables from itemInput (exclude message placeholders)const filteredContext = Object.fromEntries(@@ -188,6 +194,9 @@ export const replaceVariablesInPrompt = (}));};+export type PromptExperimentConfig = Awaited<+ ReturnType<typeof validateAndSetupExperiment>+>;export async function validateAndSetupExperiment(event: z.infer<typeof ExperimentCreateEventSchema>,) {diff --git a/worker/src/features/utils/utilities.ts b/worker/src/features/utils/utilities.tsindex a9e446c73e..31ff256927 100644--- a/worker/src/features/utils/utilities.ts+++ b/worker/src/features/utils/utilities.ts@@ -1,20 +1,13 @@import {ChatMessage,- decryptAndParseExtraHeaders,fetchLLMCompletion,+ LLMJSONSchema,logger,- type TraceParams,+ TraceSinkParams,} from "@langfuse/shared/src/server";-import {- ApiError,- LLMApiKeySchema,- LlmSchema,- ZodModelConfig,-} from "@langfuse/shared";+import { ApiError, LLMApiKeySchema, ZodModelConfig } from "@langfuse/shared";import { z } from "zod/v4";-import { z as zodV3 } from "zod/v3";import { ZodSchema as ZodV3Schema } from "zod/v3";-import { decrypt } from "@langfuse/shared/encryption";import Handlebars from "handlebars";/**@@ -48,52 +41,31 @@ async function withLLMErrorHandling<T>(}}-export async function callStructuredLLM<T extends ZodV3Schema>(- jeId: string,- llmApiKey: z.infer<typeof LLMApiKeySchema>,- messages: ChatMessage[],- modelParams: z.infer<typeof ZodModelConfig>,- provider: string,- model: string,- structuredOutputSchema: T,-): Promise<zodV3.infer<T>> {- return withLLMErrorHandling(async () => {- const { completion } = await fetchLLMCompletion({- streaming: false,- apiKey: decrypt(llmApiKey.secretKey), // decrypt the secret key- extraHeaders: decryptAndParseExtraHeaders(llmApiKey.extraHeaders),- baseURL: llmApiKey.baseURL || undefined,- messages,- modelParams: {- provider,- model,- adapter: llmApiKey.adapter,- ...modelParams,- },- structuredOutputSchema,- config: llmApiKey.config,- maxRetries: 1,- });-- return structuredOutputSchema.parse(completion);- }, "call LLM");-}+export async function callLLM(params: {+ llmApiKey: z.infer<typeof LLMApiKeySchema>;+ messages: ChatMessage[];+ modelParams: z.infer<typeof ZodModelConfig>;+ provider: string;+ model: string;+ traceSinkParams?: TraceSinkParams;+ structuredOutputSchema?: ZodV3Schema | LLMJSONSchema;+ throwOnError?: boolean;+}): Promise<unknown> {+ const {+ llmApiKey,+ messages,+ modelParams,+ provider,+ model,+ traceSinkParams,+ structuredOutputSchema,+ throwOnError,+ } = params;-export async function callLLM(- llmApiKey: z.infer<typeof LLMApiKeySchema>,- messages: ChatMessage[],- modelParams: z.infer<typeof ZodModelConfig>,- provider: string,- model: string,- traceParams?: TraceParams,- structuredOutputSchema?: LlmSchema,-): Promise<string> {return withLLMErrorHandling(async () => {const { completion, processTracedEvents } = await fetchLLMCompletion({streaming: false,- apiKey: decrypt(llmApiKey.secretKey),- extraHeaders: decryptAndParseExtraHeaders(llmApiKey.extraHeaders),- baseURL: llmApiKey.baseURL || undefined,+ llmConnection: llmApiKey,messages,modelParams: {provider,@@ -102,20 +74,16 @@ export async function callLLM(...modelParams,},...(structuredOutputSchema && { structuredOutputSchema }),- config: llmApiKey.config,- traceParams,+ traceSinkParams,maxRetries: 1,- throwOnError: false,+ throwOnError,});- if (traceParams) {+ if (traceSinkParams) {await processTracedEvents();}- // When structured output is used, completion is an object, stringify it- return typeof completion === "string"- ? completion- : JSON.stringify(completion);+ return completion;}, "call LLM");}