🪢 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
fix(evals): use evaluator ids for execution metrics (#16945)
Tobias Wochinger7489a1edf954
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex 9763d91f7e..3e4c5a5408 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -3445,25 +3445,25 @@ const costMetricFields = {},} as const;-const getCostMetricsByMetadataIds = async <+const getCostMetricsByIdentifierIds = async <const TFields extends readonly (keyof typeof costMetricFields)[],>(params: {projectId: string;- metadataIds: string[];+ identifierIds: string[];fields: TFields;identifier: "evaluator" | "rule";}) => {- if (params.metadataIds.length === 0) return [];+ if (params.identifierIds.length === 0) return [];const traceCostsBuilder = traceCostsByIdentifier({projectId: params.projectId,- identifiers: [{ identifier: params.identifier, alias: "metadata_id" }],+ identifiers: [{ identifier: params.identifier, alias: "identifier_id" }],additionalSelect: [`countIf(${evaluatorTestEventCondition}) as test_event_count`,],})- .havingRaw("metadata_id IN ({metadataIds: Array(String)})", {- metadataIds: params.metadataIds,+ .havingRaw("identifier_id IN ({identifierIds: Array(String)})", {+ identifierIds: params.identifierIds,}).havingRaw("test_event_count = 0");@@ -3471,14 +3471,14 @@ const getCostMetricsByMetadataIds = async <const queryBuilder = new CTEQueryBuilder().withCTE("trace_costs", {...traceCosts,- schema: ["trace_id", "metadata_id", "trace_total_cost"] as const,+ schema: ["trace_id", "identifier_id", "trace_total_cost"] as const,}).from("trace_costs", "tc").select(- "tc.metadata_id as metadata_id",+ "tc.identifier_id as identifier_id",...params.fields.map((field) => costMetricFields[field].select),)- .groupBy("tc.metadata_id");+ .groupBy("tc.identifier_id");const { query, params: queryParams } = queryBuilder.buildWithParams();const rows = await queryClickhouse<Record<string, string>>({@@ -3496,7 +3496,7 @@ const getCostMetricsByMetadataIds = async <]),) as Record<TFields[number], number>;- return { metadataId: row.metadata_id, ...metrics };+ return { identifierId: row.identifier_id, ...metrics };});};@@ -3504,14 +3504,14 @@ export const getAvgCostByEvaluatorIds = async (projectId: string,evaluatorIds: string[],) => {- const metrics = await getCostMetricsByMetadataIds({+ const metrics = await getCostMetricsByIdentifierIds({projectId,- metadataIds: evaluatorIds,+ identifierIds: evaluatorIds,fields: ["avgCost", "executionCount"],identifier: "evaluator",});- return metrics.map(({ metadataId, ...costs }) => ({- evaluatorId: metadataId,+ return metrics.map(({ identifierId, ...costs }) => ({+ evaluatorId: identifierId,...costs,}));};@@ -3520,14 +3520,14 @@ export const getTotalCostByRule = async (projectId: string,ruleIds: string[],) => {- const metrics = await getCostMetricsByMetadataIds({+ const metrics = await getCostMetricsByIdentifierIds({projectId,- metadataIds: ruleIds,+ identifierIds: ruleIds,fields: ["totalCost"],identifier: "rule",});- return metrics.map(({ metadataId, totalCost }) => ({- ruleId: metadataId,+ return metrics.map(({ identifierId, totalCost }) => ({+ ruleId: identifierId,totalCost,}));};@@ -3536,70 +3536,18 @@ export const getTotalCostByEvaluatorIds = async (projectId: string,evaluatorIds: string[],) => {- const metrics = await getCostMetricsByMetadataIds({+ const metrics = await getCostMetricsByIdentifierIds({projectId,- metadataIds: evaluatorIds,+ identifierIds: evaluatorIds,fields: ["totalCost"],identifier: "evaluator",});- return metrics.map(({ metadataId, totalCost }) => ({- evaluatorId: metadataId,+ return metrics.map(({ identifierId, totalCost }) => ({+ evaluatorId: identifierId,totalCost,}));};-// Prompt-experiment executions still use the trace-name fallback until every-// execution is linked to an evaluator id.-export const getTotalCostByEvaluatorTraceNames = async (- projectId: string,- traceNames: string[],-) => {- if (traceNames.length === 0) return [];-- const traceCostsBuilder = new EventsAggQueryBuilder({- projectId,- groupByColumn: "e.trace_id, e.trace_name",- selectExpression: [- "e.trace_id as trace_id",- "e.trace_name as trace_name",- "sum(e.total_cost) as trace_total_cost",- `countIf(${evaluatorTestEventCondition}) as test_event_count`,- ].join(", "),- })- .whereRaw("e.start_time > now() - INTERVAL 7 DAY")- .whereRaw("e.trace_name IN ({traceNames: Array(String)})", { traceNames })- .havingRaw("test_event_count = 0");-- const traceCosts = traceCostsBuilder.buildWithParams();- const queryBuilder = new CTEQueryBuilder()- .withCTE("trace_costs", {- ...traceCosts,- schema: ["trace_id", "trace_name", "trace_total_cost"] as const,- })- .from("trace_costs", "tc")- .select(- "tc.trace_name as trace_name",- "sum(tc.trace_total_cost) as total_cost",- )- .groupBy("tc.trace_name");-- const { query, params } = queryBuilder.buildWithParams();- const rows = await queryClickhouse<{- trace_name: string;- total_cost: string;- }>({- query,- params,- tags: { projectId },- preferredClickhouseService: "EventsReadOnly",- });-- return rows.map((row) => ({- traceName: row.trace_name,- totalCost: Number(row.total_cost),- }));-};-/** Returns the latest cost-bearing evaluator trace from the last seven days. */export const getLatestEvaluatorRunCost = async (projectId: string,@@ -3636,32 +3584,32 @@ export const getLatestEvaluatorRunCost = async (export const getRecentEvaluatorExecutionTraces = async (projectId: string,- traceNames: string[],+ evaluatorIds: string[],) => {- if (traceNames.length === 0) return [];+ if (evaluatorIds.length === 0) return [];const builder = new EventsAggQueryBuilder({projectId,- groupByColumn: "e.trace_id, e.trace_name",+ groupByColumn: "e.trace_id, e.evaluator_id",selectExpression: ["e.trace_id as id",- "e.trace_name as trace_name",+ "e.evaluator_id as evaluator_id","multiIf(countIf(e.level = 'ERROR') > 0, 'ERROR', countIf(e.level = 'WARNING') > 0, 'WARNING', 'DEFAULT') as level","min(e.start_time) as timestamp",].join(", "),}).whereRaw("e.start_time > now() - INTERVAL 7 DAY")- .whereRaw("e.trace_name IN ({traceNames: Array(String)})", {- traceNames,+ .whereRaw("e.evaluator_id IN ({evaluatorIds: Array(String)})", {+ evaluatorIds,}).havingRaw(`countIf(${evaluatorTestEventCondition}) = 0`).orderBy("ORDER BY timestamp DESC, id DESC")- .limitByCount(5, "trace_name");+ .limitByCount(5, "evaluator_id");const { query, params } = builder.buildWithParams();const rows = await queryClickhouse<{id: string;- trace_name: string;+ evaluator_id: string;level: string;timestamp: string;}>({@@ -3673,7 +3621,7 @@ export const getRecentEvaluatorExecutionTraces = async (return rows.map((row) => ({id: row.id,- traceName: row.trace_name,+ evaluatorId: row.evaluator_id,level: row.level,timestamp: parseClickhouseUTCDateTimeFormat(row.timestamp),}));diff --git a/web/src/__tests__/server/evaluator-v2-service.servertest.ts b/web/src/__tests__/server/evaluator-v2-service.servertest.tsindex 5e28b7c450..1280b1e998 100644--- a/web/src/__tests__/server/evaluator-v2-service.servertest.ts+++ b/web/src/__tests__/server/evaluator-v2-service.servertest.ts@@ -37,6 +37,7 @@ import {const mocks = vi.hoisted(() => ({generateLangfuseAIText: vi.fn(),getRecentEvaluatorExecutionTraces: vi.fn(),+ getTotalCostByEvaluatorIds: vi.fn(),invalidateProjectEvalConfigCaches: vi.fn(),assertEvaluatorConfigurationValid: vi.fn(),getEvaluatorDefinitionPreflightError: vi.fn(),@@ -54,6 +55,7 @@ vi.mock("@langfuse/shared/src/server", async (importOriginal) => ({...(await importOriginal<typeof SharedServer>()),generateLangfuseAIText: mocks.generateLangfuseAIText,getRecentEvaluatorExecutionTraces: mocks.getRecentEvaluatorExecutionTraces,+ getTotalCostByEvaluatorIds: mocks.getTotalCostByEvaluatorIds,invalidateProjectEvalConfigCaches: mocks.invalidateProjectEvalConfigCaches,}));@@ -164,6 +166,7 @@ beforeAll(async () => {beforeEach(() => {mocks.generateLangfuseAIText.mockReset();mocks.getRecentEvaluatorExecutionTraces.mockReset();+ mocks.getTotalCostByEvaluatorIds.mockReset();mocks.invalidateProjectEvalConfigCaches.mockReset();mocks.assertEvaluatorConfigurationValid.mockReset();mocks.assertEvaluatorConfigurationValid.mockResolvedValue(undefined);@@ -1185,66 +1188,62 @@ describe("EvaluatorService", () => {);});- it("returns recent traces by evaluator execution name", async () => {+ it("returns recent traces by evaluator id", async () => {const service = createService();- const [firstEvaluator, secondEvaluator, otherEvaluator] = await Promise.all(- [- service.create(llmInput("First execution evaluator"), null),- service.create(llmInput("Second execution evaluator"), null),- service.create(- {- ...llmInput("Other project execution evaluator"),- projectId: otherProjectId,- },- null,- ),- ],- );+ const evaluatorIds = [crypto.randomUUID(), crypto.randomUUID()];mocks.getRecentEvaluatorExecutionTraces.mockResolvedValue([...[7, 6, 5, 4, 3].map((day) => ({id: `first-${day}`,- traceName: "Execute evaluator: First execution evaluator",+ evaluatorId: evaluatorIds[0],level: "WARNING",timestamp: new Date(`2026-08-0${day}T00:00:00.000Z`),})),...[4, 3, 2, 1].map((day) => ({id: `second-${day}`,- traceName: "Execute evaluator: Second execution evaluator",+ evaluatorId: evaluatorIds[1],level: "DEFAULT",timestamp: new Date(`2026-08-0${day}T00:00:00.000Z`),})),]);- const result = await service.listRecent({- projectId,- evaluatorIds: [firstEvaluator.id, secondEvaluator.id, otherEvaluator.id],- });++ const result = await service.listRecent({ projectId, evaluatorIds });expect(mocks.getRecentEvaluatorExecutionTraces).toHaveBeenCalledWith(projectId,- expect.any(Array),- );- expect(mocks.getRecentEvaluatorExecutionTraces).toHaveBeenCalledTimes(1);- expect(- new Set(mocks.getRecentEvaluatorExecutionTraces.mock.calls[0]?.[1]),- ).toEqual(- new Set([- "Execute evaluator: First execution evaluator",- "Execute evaluator: Second execution evaluator",- ]),+ evaluatorIds,);- expect(result[firstEvaluator.id]?.map(({ id }) => id)).toEqual([+ expect(result[evaluatorIds[0]]?.map(({ id }) => id)).toEqual(["first-7","first-6","first-5","first-4","first-3",]);- expect(result[secondEvaluator.id]?.map(({ id }) => id)).toEqual([+ expect(result[evaluatorIds[1]]?.map(({ id }) => id)).toEqual(["second-4","second-3","second-2","second-1",]);- expect(result[otherEvaluator.id]).toEqual([]);+ });++ it("returns total costs by evaluator id", async () => {+ const service = createService();+ const evaluatorIds = [crypto.randomUUID(), crypto.randomUUID()];+ mocks.getTotalCostByEvaluatorIds.mockResolvedValue([+ { evaluatorId: evaluatorIds[0], totalCost: 1.5 },+ { evaluatorId: evaluatorIds[1], totalCost: 2.5 },+ ]);++ await expect(+ service.getTotalCosts({ projectId, evaluatorIds }),+ ).resolves.toEqual({+ [evaluatorIds[0]]: 1.5,+ [evaluatorIds[1]]: 2.5,+ });+ expect(mocks.getTotalCostByEvaluatorIds).toHaveBeenCalledWith(+ projectId,+ evaluatorIds,+ );});});diff --git a/web/src/__tests__/server/evaluator-v2-trpc.servertest.ts b/web/src/__tests__/server/evaluator-v2-trpc.servertest.tsindex 5886d7d942..0bbba67a7e 100644--- a/web/src/__tests__/server/evaluator-v2-trpc.servertest.ts+++ b/web/src/__tests__/server/evaluator-v2-trpc.servertest.ts@@ -292,7 +292,7 @@ describe("evalsV2 tRPC", () => {createEvent({project_id: projectId,trace_id: randomUUID(),- trace_name: `Execute evaluator: ${evaluator.name}`,+ evaluator_id: evaluator.id,type: "GENERATION",cost_details: { total: 0.02 },}),diff --git a/web/src/__tests__/server/repositories/event-repository.servertest.ts b/web/src/__tests__/server/repositories/event-repository.servertest.tsindex b0a2ad401e..6211e11165 100644--- a/web/src/__tests__/server/repositories/event-repository.servertest.ts+++ b/web/src/__tests__/server/repositories/event-repository.servertest.ts@@ -18,7 +18,7 @@ import {getLatestEvaluatorRunCost,getRecentEvaluatorExecutionTraces,getRecentRuleExecutionTraces,- getTotalCostByEvaluatorTraceNames,+ getTotalCostByEvaluatorIds,getTotalCostByRule,createScoresCh,createTraceScore,@@ -71,43 +71,40 @@ describe("Clickhouse Events Repository Test", () => {maybe("evaluator execution metrics", () => {it("returns evaluator costs from the last seven days excluding test runs", async () => {const evaluatorId = randomUUID();- const evaluatorTraceName = `Execute evaluator: Quality ${evaluatorId}`;const testTraceId = randomUUID();const eightDaysAgo = (Date.now() - 8 * 24 * 60 * 60 * 1000) * 1000;await createEventsCh([createEvent({project_id: projectId,- trace_name: evaluatorTraceName,+ evaluator_id: evaluatorId,cost_details: { total: 1.5 },}),createEvent({project_id: projectId,start_time: eightDaysAgo,- trace_name: evaluatorTraceName,+ evaluator_id: evaluatorId,cost_details: { total: 20 },}),createEvent({project_id: projectId,trace_id: testTraceId,- trace_name: evaluatorTraceName,type: "SPAN",- metadata_names: ["evaluator_id", "evaluator_test"],- metadata_values: [evaluatorId, "true"],+ evaluator_id: evaluatorId,+ evaluator_execution_is_test: true,cost_details: { total: 0.1 },}),createEvent({project_id: projectId,trace_id: testTraceId,- trace_name: evaluatorTraceName,type: "GENERATION",cost_details: { total: 0.9 },}),]);await expect(- getTotalCostByEvaluatorTraceNames(projectId, [evaluatorTraceName]),- ).resolves.toEqual([{ traceName: evaluatorTraceName, totalCost: 1.5 }]);+ getTotalCostByEvaluatorIds(projectId, [evaluatorId]),+ ).resolves.toEqual([{ evaluatorId, totalCost: 1.5 }]);});it("returns the latest evaluator trace cost", async () => {@@ -125,8 +122,7 @@ describe("Clickhouse Events Repository Test", () => {trace_id: traceId,start_time: now,type: "SPAN",- metadata_names: ["evaluator_id"],- metadata_values: [evaluatorId],+ evaluator_id: evaluatorId,cost_details: { total: 0.1 },}),createEvent({@@ -141,8 +137,8 @@ describe("Clickhouse Events Repository Test", () => {trace_id: earlierTestTraceId,start_time: oneHourAgo,type: "SPAN",- metadata_names: ["evaluator_id", "evaluator_test"],- metadata_values: [evaluatorId, "true"],+ evaluator_id: evaluatorId,+ evaluator_execution_is_test: true,cost_details: { total: 1 },}),createEvent({@@ -157,8 +153,7 @@ describe("Clickhouse Events Repository Test", () => {trace_id: staleTraceId,start_time: eightDaysAgo,type: "SPAN",- metadata_names: ["evaluator_id"],- metadata_values: [staleEvaluatorId],+ evaluator_id: staleEvaluatorId,cost_details: { total: 2 },}),createEvent({@@ -184,24 +179,21 @@ describe("Clickhouse Events Repository Test", () => {const failedTestSpanId = randomUUID();const untaggedTestTraceId = randomUUID();const evaluatorId = randomUUID();- const evaluatorTraceName = `Execute evaluator: Quality ${evaluatorId}`;await createEventsCh([createEvent({project_id: projectId,trace_id: traceId,- trace_name: evaluatorTraceName,type: "SPAN",level: "ERROR",- metadata_names: ["evaluator_id"],- metadata_values: [evaluatorId],+ evaluator_id: evaluatorId,cost_details: { total: 0 },}),createEvent({project_id: projectId,trace_id: testTraceId,type: "SPAN",- metadata_names: ["evaluator_id", "evaluator_test"],- metadata_values: [evaluatorId, "true"],+ evaluator_id: evaluatorId,+ evaluator_execution_is_test: true,cost_details: { total: 0 },}),createEvent({@@ -211,8 +203,7 @@ describe("Clickhouse Events Repository Test", () => {trace_id: testTraceId,type: "SPAN",level: "ERROR",- metadata_names: ["evaluator_id"],- metadata_values: [evaluatorId],+ evaluator_id: evaluatorId,cost_details: { total: 0 },}),createEvent({@@ -220,18 +211,17 @@ describe("Clickhouse Events Repository Test", () => {trace_id: untaggedTestTraceId,trace_name: "Test evaluator: Legacy code evaluator",type: "SPAN",- metadata_names: ["evaluator_id"],- metadata_values: [evaluatorId],+ evaluator_id: evaluatorId,cost_details: { total: 0 },}),]);await expect(- getRecentEvaluatorExecutionTraces(projectId, [evaluatorTraceName]),+ getRecentEvaluatorExecutionTraces(projectId, [evaluatorId]),).resolves.toEqual([expect.objectContaining({id: traceId,- traceName: evaluatorTraceName,+ evaluatorId,level: "ERROR",}),]);diff --git a/web/src/features/evals/v2/server/evaluators/evaluatorService.ts b/web/src/features/evals/v2/server/evaluators/evaluatorService.tsindex d9621bb035..253729e508 100644--- a/web/src/features/evals/v2/server/evaluators/evaluatorService.ts+++ b/web/src/features/evals/v2/server/evaluators/evaluatorService.ts@@ -21,7 +21,7 @@ import {generateLangfuseAIText,getClientInitiatedNonStreamingLlmTimeoutMs,getRecentEvaluatorExecutionTraces,- getTotalCostByEvaluatorTraceNames,+ getTotalCostByEvaluatorIds,invalidateProjectEvalConfigCaches,logger,} from "@langfuse/shared/src/server";@@ -254,64 +254,29 @@ export class EvaluatorService {) as Record<string, EvaluatorExecutionTrace[]>;if (params.evaluatorIds.length === 0) return result;- const evaluators = await repository.findEvaluatorsByIds({- prisma: this.prisma,- projectId: params.projectId,- evaluatorIds: params.evaluatorIds,- });- // Prompt-experiment executions do not always carry an evaluator id, but- // all evaluator execution paths use this trace-name convention.- const evaluatorIdsByTraceName = new Map<string, string[]>();- for (const evaluator of evaluators) {- const traceName = `Execute evaluator: ${evaluator.name}`;- evaluatorIdsByTraceName.set(traceName, [- ...(evaluatorIdsByTraceName.get(traceName) ?? []),- evaluator.id,- ]);- }- const traces = await getRecentEvaluatorExecutionTraces(params.projectId, [- ...evaluatorIdsByTraceName.keys(),- ]);+ const traces = await getRecentEvaluatorExecutionTraces(+ params.projectId,+ params.evaluatorIds,+ );for (const trace of traces) {- for (const evaluatorId of evaluatorIdsByTraceName.get(trace.traceName) ??- []) {- result[evaluatorId]?.push({- id: trace.id,- level: trace.level,- timestamp: trace.timestamp,- });- }+ result[trace.evaluatorId]?.push({+ id: trace.id,+ level: trace.level,+ timestamp: trace.timestamp,+ });}return result;}async getTotalCosts(params: { projectId: string; evaluatorIds: string[] }) {- const evaluators = await repository.findEvaluatorsByIds({- prisma: this.prisma,- projectId: params.projectId,- evaluatorIds: params.evaluatorIds,- });- const evaluatorIdsByTraceName = new Map<string, string[]>();- for (const evaluator of evaluators) {- const traceName = `Execute evaluator: ${evaluator.name}`;- evaluatorIdsByTraceName.set(traceName, [- ...(evaluatorIdsByTraceName.get(traceName) ?? []),- evaluator.id,- ]);- }-- const costs = await getTotalCostByEvaluatorTraceNames(params.projectId, [- ...evaluatorIdsByTraceName.keys(),- ]);+ const costs = await getTotalCostByEvaluatorIds(+ params.projectId,+ params.evaluatorIds,+ );return Object.fromEntries(- costs.flatMap(({ traceName, totalCost }) =>- (evaluatorIdsByTraceName.get(traceName) ?? []).map((evaluatorId) => [- evaluatorId,- totalCost,- ]),- ),+ costs.map(({ evaluatorId, totalCost }) => [evaluatorId, totalCost]),);}