Skip to content

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

chore: migrate /metrics/daily API route to Clickhouse (#4546)

Steffen Schmitz0c9070f78f50
diff --git a/web/src/__tests__/async/daily-metrics-api.servertest.ts b/web/src/__tests__/async/daily-metrics-api.servertest.ts
new file mode 100644
index 0000000000..7cb4c94578
--- /dev/null
+++ b/web/src/__tests__/async/daily-metrics-api.servertest.ts
@@ -0,0 +1,75 @@
+import {
+ createObservation,
+ createTrace,
+} from "@/src/__tests__/fixtures/tracing-factory";
+import {
+ createObservations,
+ createTraces,
+} from "@/src/__tests__/server/repositories/clickhouse-helpers";
+import { makeZodVerifiedAPICall } from "@/src/__tests__/test-utils";
+import { randomUUID } from "crypto";
+import { GetMetricsDailyV1Response } from "@/src/features/public-api/types/metrics";
+
+describe("/api/public/metrics/daily API Endpoint", () => {
+ it("should get correct results from daily metrics", async () => {
+ const traceName = randomUUID();
+ const createdTrace = createTrace({
+ name: traceName,
+ user_id: "user-1",
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ });
+
+ const observations = [
+ createObservation({
+ trace_id: createdTrace.id,
+ project_id: createdTrace.project_id,
+ name: "observation-name",
+ end_time: new Date().getTime(),
+ start_time: new Date().getTime() - 1000,
+ input: "input",
+ output: "output",
+ provided_model_name: "model-1",
+ }),
+ createObservation({
+ trace_id: createdTrace.id,
+ project_id: createdTrace.project_id,
+ name: "observation-name-2",
+ end_time: new Date().getTime(),
+ start_time: new Date().getTime() - 100000,
+ input: "input-2",
+ output: "output-2",
+ provided_model_name: "model-2",
+ }),
+ ];
+
+ await createTraces([createdTrace]);
+ await createObservations(observations);
+
+ const metrics = await makeZodVerifiedAPICall(
+ GetMetricsDailyV1Response,
+ "GET",
+ `/api/public/metrics/daily?traceName=${traceName}`,
+ );
+
+ expect(metrics.body.meta.totalItems).toBe(1);
+ expect(metrics.body.meta.totalPages).toBe(1);
+
+ const metric = metrics.body.data[0];
+ expect(metric.countTraces).toBe(1);
+ expect(metric.countObservations).toBe(2);
+ expect(metric.usage).toHaveLength(2);
+ expect(metric.totalCost).toBe(600);
+ for (const usage of metric.usage) {
+ expect(usage.model).toMatch(/model-\d/g);
+ expect(usage.inputUsage).toBe(1234);
+ expect(usage.outputUsage).toBe(5678);
+ expect(usage.totalUsage).toBe(6912);
+ expect(usage.countObservations).toBe(1);
+ expect(usage.countTraces).toBe(1);
+ expect(usage.totalCost).toBe(300);
+ }
+ });
+});
diff --git a/web/src/features/public-api/server/dailyMetrics.ts b/web/src/features/public-api/server/dailyMetrics.ts
new file mode 100644
index 0000000000..e4cce6e7d4
--- /dev/null
+++ b/web/src/features/public-api/server/dailyMetrics.ts
@@ -0,0 +1,188 @@
+import { convertApiProvidedFilterToClickhouseFilter } from "@/src/features/public-api/server/filter-builder";
+import {
+ convertDateToClickhouseDateTime,
+ queryClickhouse,
+ TRACE_TO_OBSERVATIONS_INTERVAL,
+ type DateTimeFilter,
+} from "@langfuse/shared/src/server";
+
+type QueryType = {
+ page: number;
+ limit: number;
+ projectId: string;
+ userId?: string;
+ tags?: string | string[];
+ traceName?: string;
+ fromTimestamp?: string;
+ toTimestamp?: string;
+};
+
+export const generateDailyMetrics = async (props: QueryType) => {
+ const filter = convertApiProvidedFilterToClickhouseFilter(
+ props,
+ filterParams,
+ );
+ const appliedFilter = filter.apply();
+
+ const timeFilter = filter.find(
+ (f) =>
+ f.clickhouseTable === "traces" &&
+ f.field.includes("timestamp") &&
+ (f.operator === ">=" || f.operator === ">"),
+ ) as DateTimeFilter | undefined;
+
+ const query = `
+ WITH model_usage AS (
+ SELECT
+ toDate(o.start_time) as date,
+ o.provided_model_name as model,
+ count(o.id) as countObservations,
+ count(distinct t.id) as countTraces,
+ sumMap(o.usage_details)['input'] as inputUsage,
+ sumMap(o.usage_details)['output'] as outputUsage,
+ sumMap(o.usage_details)['total'] as totalUsage,
+ sum(coalesce(o.total_cost, 0)) as totalCost
+ FROM traces t FINAL
+ LEFT JOIN observations o FINAL on o.trace_id = t.id AND o.project_id = t.project_id
+ WHERE o.project_id = {projectId: String}
+ ${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}
+ ${timeFilter ? `AND start_time >= {cteTimeFilter: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
+ GROUP BY date, model
+ ), daily_model_usage AS (
+ SELECT
+ "date",
+ sum(mu.countObservations) as countObservations,
+ sum(mu.totalCost) as totalCost,
+ groupArray(tuple(
+ mu.model,
+ mu.inputUsage,
+ mu.outputUsage,
+ mu.totalUsage,
+ mu.totalCost,
+ mu.countObservations,
+ mu.countTraces
+ )) as daily_usage_tuple
+ FROM model_usage mu
+ GROUP BY date
+ ), trace_usage AS (
+ SELECT
+ toDate(t.timestamp) as date,
+ count(t.id) as countTraces
+ FROM traces t FINAL
+ WHERE t.project_id = {projectId: String}
+ ${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}
+ GROUP BY date
+ )
+
+ SELECT
+ COALESCE(dmu.date, tu.date) as date,
+ COALESCE(tu.countTraces, 0) as countTraces,
+ COALESCE(dmu.countObservations, 0) as countObservations,
+ COALESCE(dmu.totalCost, 0) as totalCost,
+ dmu.daily_usage_tuple as usage
+ FROM daily_model_usage dmu
+ FULL OUTER JOIN trace_usage tu ON dmu.date = tu.date
+ ORDER BY date DESC
+ ${props.limit !== undefined && props.page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
+ `;
+
+ const result = await queryClickhouse<{
+ date: string;
+ countTraces: number;
+ countObservations: number;
+ totalCost: number;
+ usage: (string | null)[][];
+ }>({
+ query,
+ params: {
+ ...appliedFilter.params,
+ projectId: props.projectId,
+ ...(props.limit !== undefined ? { limit: props.limit } : {}),
+ ...(props.page !== undefined
+ ? { offset: (props.page - 1) * props.limit }
+ : {}),
+ ...(timeFilter
+ ? {
+ cteTimeFilter: convertDateToClickhouseDateTime(timeFilter.value),
+ }
+ : {}),
+ },
+ });
+
+ return result.map((record) => ({
+ date: record.date,
+ countTraces: Number(record.countTraces),
+ countObservations: Number(record.countObservations),
+ totalCost: Number(record.totalCost),
+ usage: record.usage.map((u) => ({
+ model: u[0],
+ inputUsage: Number(u[1]),
+ outputUsage: Number(u[2]),
+ totalUsage: Number(u[3]),
+ totalCost: Number(u[4]),
+ countObservations: Number(u[5]),
+ countTraces: Number(u[6]),
+ })),
+ }));
+};
+
+export const getDailyMetricsCount = async (props: QueryType) => {
+ const filter = convertApiProvidedFilterToClickhouseFilter(
+ props,
+ filterParams,
+ );
+ const appliedFilter = filter.apply();
+
+ const query = `
+ SELECT count(distinct toDate(timestamp)) as count
+ FROM traces t
+ WHERE project_id = {projectId: String}
+ ${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}
+ `;
+
+ const records = await queryClickhouse<{ count: string }>({
+ query,
+ params: { ...appliedFilter.params, projectId: props.projectId },
+ });
+ return records.map((record) => Number(record.count)).shift();
+};
+
+const filterParams = [
+ {
+ id: "userId",
+ clickhouseSelect: "user_id",
+ filterType: "StringFilter",
+ clickhouseTable: "traces",
+ clickhousePrefix: "t",
+ },
+ {
+ id: "traceName",
+ clickhouseSelect: "name",
+ filterType: "StringFilter",
+ clickhouseTable: "traces",
+ clickhousePrefix: "t",
+ },
+ {
+ id: "tags",
+ clickhouseSelect: "tags",
+ filterType: "ArrayOptionsFilter",
+ clickhouseTable: "traces",
+ clickhousePrefix: "t",
+ },
+ {
+ id: "fromTimestamp",
+ clickhouseSelect: "timestamp",
+ operator: ">=" as const,
+ filterType: "DateTimeFilter",
+ clickhouseTable: "traces",
+ clickhousePrefix: "t",
+ },
+ {
+ id: "toTimestamp",
+ clickhouseSelect: "timestamp",
+ operator: "<" as const,
+ filterType: "DateTimeFilter",
+ clickhouseTable: "traces",
+ clickhousePrefix: "t",
+ },
+];
diff --git a/web/src/features/public-api/server/traces.ts b/web/src/features/public-api/server/traces.ts
index d6a78e12d0..e0217147ff 100644
--- a/web/src/features/public-api/server/traces.ts
+++ b/web/src/features/public-api/server/traces.ts
@@ -17,10 +17,12 @@ type QueryType = {
userId?: string;
name?: string;
type?: string;
- parentObservationId?: string;
- fromStartTime?: string;
- toStartTime?: string;
+ sessionId?: string;
version?: string;
+ release?: string;
+ tags?: string | string[];
+ fromTimestamp?: string;
+ toTimestamp?: string;
};
export const generateTracesForPublicApi = async (
diff --git a/web/src/pages/api/public/metrics/daily.ts b/web/src/pages/api/public/metrics/daily.ts
index d1d2c8d70a..c2fc7ba25a 100644
--- a/web/src/pages/api/public/metrics/daily.ts
+++ b/web/src/pages/api/public/metrics/daily.ts
@@ -7,6 +7,11 @@ import { withMiddlewares } from "@/src/features/public-api/server/withMiddleware
import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
import { type z } from "zod";
import { env } from "@/src/env.mjs";
+import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
+import {
+ generateDailyMetrics,
+ getDailyMetricsCount,
+} from "@/src/features/public-api/server/dailyMetrics";
export default withMiddlewares({
GET: createAuthedAPIRoute({
@@ -15,134 +20,162 @@ export default withMiddlewares({
responseSchema: GetMetricsDailyV1Response,
rateLimitResource: "public-api-metrics",
fn: async ({ query, auth }) => {
- const traceNameCondition = query.traceName
- ? Prisma.sql`AND t.name = ${query.traceName}`
- : Prisma.empty;
- const userCondition = query.userId
- ? Prisma.sql`AND t."user_id" = ${query.userId}`
- : Prisma.empty;
- const tagsCondition = query.tags
- ? Prisma.sql`AND ARRAY[${Prisma.join(
- (Array.isArray(query.tags) ? query.tags : query.tags.split(',')).map(
- (v) => Prisma.sql`${v}`,
- ),
- ", ",
- )}] <@ t."tags"`
- : Prisma.empty;
- const fromTimestampCondition = query.fromTimestamp
- ? Prisma.sql`AND t."timestamp" >= ${query.fromTimestamp}::timestamp with time zone at time zone 'UTC'`
- : Prisma.empty;
- const toTimestampCondition = query.toTimestamp
- ? Prisma.sql`AND t."timestamp" < ${query.toTimestamp}::timestamp with time zone at time zone 'UTC'`
- : Prisma.empty;
- const fromObservationStartTimeCondition = query.fromTimestamp
- ? Prisma.sql`AND o."start_time" >= ${query.fromTimestamp}::timestamp with time zone at time zone 'UTC' - INTERVAL '1 day'`
- : Prisma.empty;
- const toObservationStartTimeCondition = query.toTimestamp
- ? Prisma.sql`AND o."start_time" < ${query.toTimestamp}::timestamp with time zone at time zone 'UTC' + INTERVAL '1 day'`
- : Prisma.empty;
+ return measureAndReturnApi({
+ input: { projectId: auth.scope.projectId, queryClickhouse: false },
+ operation: "api/public/metrics/daily",
+ user: null,
+ pgExecution: async () => {
+ const traceNameCondition = query.traceName
+ ? Prisma.sql`AND t.name = ${query.traceName}`
+ : Prisma.empty;
+ const userCondition = query.userId
+ ? Prisma.sql`AND t."user_id" = ${query.userId}`
+ : Prisma.empty;
+ const tagsCondition = query.tags
+ ? Prisma.sql`AND ARRAY[${Prisma.join(
+ (Array.isArray(query.tags)
+ ? query.tags
+ : query.tags.split(",")
+ ).map((v) => Prisma.sql`${v}`),
+ ", ",
+ )}] <@ t."tags"`
+ : Prisma.empty;
+ const fromTimestampCondition = query.fromTimestamp
+ ? Prisma.sql`AND t."timestamp" >= ${query.fromTimestamp}::timestamp with time zone at time zone 'UTC'`
+ : Prisma.empty;
+ const toTimestampCondition = query.toTimestamp
+ ? Prisma.sql`AND t."timestamp" < ${query.toTimestamp}::timestamp with time zone at time zone 'UTC'`
+ : Prisma.empty;
+ const fromObservationStartTimeCondition = query.fromTimestamp
+ ? Prisma.sql`AND o."start_time" >= ${query.fromTimestamp}::timestamp with time zone at time zone 'UTC' - INTERVAL '1 day'`
+ : Prisma.empty;
+ const toObservationStartTimeCondition = query.toTimestamp
+ ? Prisma.sql`AND o."start_time" < ${query.toTimestamp}::timestamp with time zone at time zone 'UTC' + INTERVAL '1 day'`
+ : Prisma.empty;
+
+ // TODO: We can use observations as soon as we compute costs on write and backfill self-hosters
+ const observationtable =
+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined
+ ? Prisma.sql`observations_view`
+ : Prisma.sql`observations`;
- // TODO: We can use observations as soon as we compute costs on write and backfill self-hosters
- const observationtable =
- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined
- ? Prisma.sql`observations_view`
- : Prisma.sql`observations`;
+ const [usage, totalItemsRes] = await Promise.all([
+ prisma.$queryRaw`
+ WITH model_usage AS (
+ SELECT DATE_TRUNC('DAY', o.start_time) "date",
+ o.model,
+ count(o.id)::integer as "countObservations",
+ count(distinct t.id)::integer as "countTraces",
+ SUM(o.prompt_tokens) "inputUsage",
+ SUM(o.completion_tokens) "outputUsage",
+ SUM(o.total_tokens) "totalUsage",
+ COALESCE(SUM(o.calculated_total_cost), 0)::DOUBLE PRECISION as "totalCost"
+ FROM traces t
+ LEFT JOIN ${observationtable} o
+ ON o.trace_id = t.id
+ AND o.project_id = t.project_id
+ WHERE o.start_time IS NOT NULL
+ AND t.project_id = ${auth.scope.projectId}
+ ${traceNameCondition}
+ ${userCondition}
+ ${tagsCondition}
+ ${fromTimestampCondition}
+ ${toTimestampCondition}
+ ${fromObservationStartTimeCondition}
+ ${toObservationStartTimeCondition}
+ GROUP BY 1, 2),
+ daily_model_usage AS (
+ SELECT "date",
+ sum("countObservations")::integer "countObservations",
+ sum("totalCost")::DOUBLE PRECISION "totalCost",
+ json_agg(json_build_object(
+ 'model', "model",
+ 'inputUsage', "inputUsage",
+ 'outputUsage', "outputUsage",
+ 'totalUsage', "totalUsage",
+ 'totalCost', "totalCost",
+ 'countObservations', "countObservations",
+ 'countTraces', "countTraces"
+ )) daily_usage_json
+ FROM model_usage
+ GROUP BY 1),
+ trace_usage AS (
+ SELECT DATE_TRUNC('DAY', t.timestamp) "date",
+ count(t.id)::integer as "countTraces"
+ FROM traces t
+ WHERE t.project_id = ${auth.scope.projectId}
+ ${traceNameCondition}
+ ${userCondition}
+ ${tagsCondition}
+ ${fromTimestampCondition}
+ ${toTimestampCondition}
+ GROUP BY 1)
+
+ SELECT TO_CHAR(COALESCE(trace_usage.date, daily_model_usage.date), 'YYYY-MM-DD') AS "date",
+ COALESCE(trace_usage."countTraces", 0) "countTraces",
+ COALESCE("countObservations", 0) "countObservations",
+ COALESCE("totalCost", 0) "totalCost",
+ COALESCE(daily_usage_json, '[]'::JSON) usage
+ FROM daily_model_usage
+ FULL OUTER JOIN trace_usage
+ ON daily_model_usage."date" = trace_usage."date"
+ ORDER BY 1 DESC
+ LIMIT ${query.limit} OFFSET ${(query.page - 1) * query.limit}
+ `,
+ prisma.$queryRaw<{ count: number }[]>`
+ SELECT COUNT(DISTINCT DATE_TRUNC('DAY', t.timestamp))::integer
+ FROM traces t
+ WHERE t.project_id = ${auth.scope.projectId}
+ ${traceNameCondition}
+ ${userCondition}
+ ${tagsCondition}
+ ${fromTimestampCondition}
+ ${toTimestampCondition}
+ `,
+ ]);
- const [usage, totalItemsRes] = await Promise.all([
- prisma.$queryRaw`
- WITH model_usage AS (
- SELECT
- DATE_TRUNC('DAY', o.start_time) "date",
- o.model,
- count(o.id)::integer as "countObservations",
- count(distinct t.id)::integer as "countTraces",
- SUM(o.prompt_tokens) "inputUsage",
- SUM(o.completion_tokens) "outputUsage",
- SUM(o.total_tokens) "totalUsage",
- COALESCE(SUM(o.calculated_total_cost), 0)::DOUBLE PRECISION as "totalCost"
- FROM traces t
- LEFT JOIN ${observationtable} o
- ON o.trace_id = t.id
- AND o.project_id = t.project_id
- WHERE o.start_time IS NOT NULL
- AND t.project_id = ${auth.scope.projectId}
- ${traceNameCondition}
- ${userCondition}
- ${tagsCondition}
- ${fromTimestampCondition}
- ${toTimestampCondition}
- ${fromObservationStartTimeCondition}
- ${toObservationStartTimeCondition}
- GROUP BY 1, 2
- ),
- daily_model_usage AS (
- SELECT
- "date",
- sum("countObservations")::integer "countObservations",
- sum("totalCost")::DOUBLE PRECISION "totalCost",
- json_agg(json_build_object(
- 'model', "model",
- 'inputUsage', "inputUsage",
- 'outputUsage', "outputUsage",
- 'totalUsage', "totalUsage",
- 'totalCost', "totalCost",
- 'countObservations', "countObservations",
- 'countTraces', "countTraces"
- )) daily_usage_json
- FROM
- model_usage
- GROUP BY 1
- ),
- trace_usage AS (
- SELECT
- DATE_TRUNC('DAY', t.timestamp) "date",
- count(t.id)::integer as "countTraces"
- FROM traces t
- WHERE t.project_id = ${auth.scope.projectId}
- ${traceNameCondition}
- ${userCondition}
- ${tagsCondition}
- ${fromTimestampCondition}
- ${toTimestampCondition}
- GROUP BY 1
- )
- SELECT
- TO_CHAR(COALESCE(trace_usage.date, daily_model_usage.date), 'YYYY-MM-DD') AS "date",
- COALESCE(trace_usage."countTraces", 0) "countTraces",
- COALESCE("countObservations", 0) "countObservations",
- COALESCE("totalCost", 0) "totalCost",
- COALESCE(daily_usage_json, '[]'::JSON) usage
- FROM daily_model_usage
- FULL OUTER JOIN trace_usage
- ON daily_model_usage."date" = trace_usage."date"
- ORDER BY 1 DESC
- LIMIT ${query.limit} OFFSET ${(query.page - 1) * query.limit}
- `,
- prisma.$queryRaw<{ count: number }[]>`
- SELECT
- COUNT(DISTINCT DATE_TRUNC('DAY', t.timestamp))::integer
- FROM traces t
- WHERE t.project_id = ${auth.scope.projectId}
- ${traceNameCondition}
- ${userCondition}
- ${tagsCondition}
- ${fromTimestampCondition}
- ${toTimestampCondition}
- `,
- ]);
+ const totalItems = totalItemsRes[0]?.count ?? 0;
+
+ return {
+ // cannot use type warnings due to query raw, covered by tests
+ data: usage as z.infer<typeof GetMetricsDailyV1Response>["data"],
+ meta: {
+ page: query.page,
+ limit: query.limit,
+ totalItems,
+ totalPages: Math.ceil(totalItems / query.limit),
+ },
+ };
+ },
+ clickhouseExecution: async () => {
+ const filterProps = {
+ projectId: auth.scope.projectId,
+ page: query.page ?? undefined,
+ limit: query.limit ?? undefined,
+ traceName: query.traceName ?? undefined,
+ userId: query.userId ?? undefined,
+ tags: query.tags ?? undefined,
+ fromTimestamp: query.fromTimestamp ?? undefined,
+ toTimestamp: query.toTimestamp ?? undefined,
+ };
- const totalItems = totalItemsRes[0]?.count ?? 0;
+ const [usage, count] = await Promise.all([
+ generateDailyMetrics(filterProps),
+ getDailyMetricsCount(filterProps),
+ ]);
- return {
- // cannot use type warnings due to query raw, covered by tests
- data: usage as z.infer<typeof GetMetricsDailyV1Response>["data"],
- meta: {
- page: query.page,
- limit: query.limit,
- totalItems,
- totalPages: Math.ceil(totalItems / query.limit),
+ const finalCount = count || 0;
+ return {
+ data: usage,
+ meta: {
+ page: query.page,
+ limit: query.limit,
+ totalItems: finalCount,
+ totalPages: Math.ceil(finalCount / query.limit),
+ },
+ };
},
- };
+ });
},
}),
});