🪢 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
chore: migrate traces all API route to Clickhouse (#4542)
Steffen Schmitzb533b1dccdae
diff --git a/packages/shared/src/server/queries/index.ts b/packages/shared/src/server/queries/index.tsindex 2a6fcb4831..f067394b7c 100644--- a/packages/shared/src/server/queries/index.ts+++ b/packages/shared/src/server/queries/index.ts@@ -20,3 +20,4 @@ export {NullFilter,type ClickhouseOperator,} from "./clickhouse-sql/clickhouse-filter";+export { orderByToClickhouseSql } from "./clickhouse-sql/orderby-factory";diff --git a/packages/shared/src/server/repositories/index.ts b/packages/shared/src/server/repositories/index.tsindex 909a6b2e96..6c9eb4c684 100644--- a/packages/shared/src/server/repositories/index.ts+++ b/packages/shared/src/server/repositories/index.ts@@ -7,3 +7,4 @@ export * from "./traces_converters";export * from "./scores_converters";export * from "./observations_converters";export * from "./clickhouse";+export * from "./constants";diff --git a/web/src/__tests__/async/traces-api.servertest.ts b/web/src/__tests__/async/traces-api.servertest.tsindex 5fad2ddb77..ff147f2f1a 100644--- a/web/src/__tests__/async/traces-api.servertest.ts+++ b/web/src/__tests__/async/traces-api.servertest.ts@@ -7,7 +7,12 @@ import {createTraces,} from "@/src/__tests__/server/repositories/clickhouse-helpers";import { makeZodVerifiedAPICall } from "@/src/__tests__/test-utils";-import { GetTraceV1Response } from "@/src/features/public-api/types/traces";+import {+ GetTracesV1Response,+ GetTraceV1Response,+} from "@/src/features/public-api/types/traces";+import { randomUUID } from "crypto";+import { snakeCase } from "lodash";describe("/api/public/traces API Endpoint", () => {it("should create and get a trace via /traces", async () => {@@ -73,4 +78,182 @@ describe("/api/public/traces API Endpoint", () => {]),);});++ it("should fetch all traces", async () => {+ const createdTrace = createTrace({+ name: "trace-name",+ 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",+ }),+ 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",+ }),+ ];++ await createTraces([createdTrace]);+ await createObservations(observations);++ const traces = await makeZodVerifiedAPICall(+ GetTracesV1Response,+ "GET",+ "/api/public/traces",+ );++ expect(traces.body.meta.totalItems).toBeGreaterThanOrEqual(1);+ expect(traces.body.data.length).toBeGreaterThanOrEqual(1);+ const trace = traces.body.data.find((t) => t.id === createdTrace.id);+ expect(trace).toBeTruthy();+ if (!trace) {+ return; // to satisfy TypeScript+ }+ expect(trace.name).toBe("trace-name");+ expect(trace.release).toBe("1.0.0");+ expect(trace.externalId).toBeNull();+ expect(trace.version).toBe("2.0.0");+ expect(trace.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");+ expect(trace.latency).toBe(100);+ expect(trace.observations.length).toBe(2);+ expect(trace.scores.length).toBe(0);+ });++ it.each([+ ["userId", randomUUID()],+ ["sessionId", randomUUID()],+ ["release", randomUUID()],+ ["version", randomUUID()],+ ["name", randomUUID()],+ ])(+ "should fetch all traces filtered by a value (%s, %s)",+ async (prop: string, value: string) => {+ const createdTrace = createTrace({+ [snakeCase(prop)]: value,+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ metadata: { key: "value" },+ });++ await createTraces([createdTrace]);++ const traces = await makeZodVerifiedAPICall(+ GetTracesV1Response,+ "GET",+ `/api/public/traces?${prop}=${value}`,+ );++ expect(traces.body.meta.totalItems).toBe(1);+ expect(traces.body.data.length).toBe(1);+ const trace = traces.body.data[0];+ expect(trace.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");+ expect((trace as any)[prop]).toBe(value);+ },+ );++ it("should fetch all traces filtered by a tag", async () => {+ const tag = randomUUID();+ const createdTrace = createTrace({+ name: "trace-name",+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ metadata: { key: "value" },+ tags: [tag],+ });++ await createTraces([createdTrace]);++ const traces = await makeZodVerifiedAPICall(+ GetTracesV1Response,+ "GET",+ `/api/public/traces?tags=${[tag]}`,+ );++ expect(traces.body.meta.totalItems).toBe(1);+ expect(traces.body.data.length).toBe(1);+ const trace = traces.body.data[0];+ expect(trace.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");+ });++ it("should fetch all traces with pagination", async () => {+ const tag = randomUUID();+ const createdTrace1 = createTrace({+ name: "trace-name",+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ metadata: { key: "value" },+ tags: [tag],+ });+ const createdTrace2 = createTrace({+ name: "trace-name",+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ metadata: { key: "value" },+ tags: [tag],+ });+ const createdTrace3 = createTrace({+ name: "trace-name",+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ metadata: { key: "value" },+ tags: [tag],+ });++ await createTraces([createdTrace1, createdTrace2, createdTrace3]);++ const traces = await makeZodVerifiedAPICall(+ GetTracesV1Response,+ "GET",+ `/api/public/traces?tags=${[tag]}&limit=1&offset=1`,+ );++ expect(traces.body.meta.totalItems).toBe(3);+ expect(traces.body.data.length).toBe(1);+ expect(traces.body.meta.totalPages).toBe(3);+ const trace = traces.body.data[0];+ expect(trace.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");+ });++ it("should fetch all traces with custom order", async () => {+ const tag = randomUUID();+ const createdTrace1 = createTrace({+ name: "trace-name1",+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ metadata: { key: "value" },+ tags: [tag],+ });+ const createdTrace2 = createTrace({+ name: "trace-name2",+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ metadata: { key: "value" },+ tags: [tag],+ });++ await createTraces([createdTrace1, createdTrace2]);++ const traces = await makeZodVerifiedAPICall(+ GetTracesV1Response,+ "GET",+ `/api/public/traces?tags=${[tag]}&orderBy=name.desc`,+ );++ expect(traces.body.meta.totalItems).toBe(2);+ expect(traces.body.data.length).toBe(2);+ const trace1 = traces.body.data[0];+ expect(trace1.name).toBe("trace-name2");+ const trace2 = traces.body.data[1];+ expect(trace2.name).toBe("trace-name1");+ });});diff --git a/web/src/features/public-api/server/filter-builder.ts b/web/src/features/public-api/server/filter-builder.tsindex be03bbae83..8c5bd6d8a8 100644--- a/web/src/features/public-api/server/filter-builder.ts+++ b/web/src/features/public-api/server/filter-builder.ts@@ -1,4 +1,3 @@-import { type ScoreQueryType } from "@/src/features/public-api/server/sores";import { filterOperators } from "@langfuse/shared";import {FilterList,@@ -20,14 +19,20 @@ export type ApiColumnMapping = {clickhousePrefix?: string;};+type BaseQueryType = {+ page: number;+ limit: number;+ projectId: string;+} & Record<string, unknown>;+export function convertApiProvidedFilterToClickhouseFilter(- filter: ScoreQueryType,+ filter: BaseQueryType,columnMapping: ApiColumnMapping[],) {const filterList = new FilterList();columnMapping.forEach((columnMapping) => {- const value = filter[columnMapping.id as keyof ScoreQueryType];+ const value = filter[columnMapping.id as keyof BaseQueryType];if (value) {let filterInstance;diff --git a/web/src/features/public-api/server/observations.ts b/web/src/features/public-api/server/observations.tsindex d55e9adaf7..20c1d68e9b 100644--- a/web/src/features/public-api/server/observations.ts+++ b/web/src/features/public-api/server/observations.ts@@ -6,7 +6,7 @@ import {convertObservationToView,} from "@langfuse/shared/src/server";-export type QueryType = {+type QueryType = {page: number;limit: number;projectId: string;diff --git a/web/src/features/public-api/server/sores.ts b/web/src/features/public-api/server/scores.tssimilarity index 100%rename from web/src/features/public-api/server/sores.tsrename to web/src/features/public-api/server/scores.tsdiff --git a/web/src/features/public-api/server/traces.ts b/web/src/features/public-api/server/traces.tsnew file mode 100644index 0000000000..d6a78e12d0--- /dev/null+++ b/web/src/features/public-api/server/traces.ts@@ -0,0 +1,227 @@+import { convertApiProvidedFilterToClickhouseFilter } from "@/src/features/public-api/server/filter-builder";+import {+ convertDateToClickhouseDateTime,+ queryClickhouse,+ TRACE_TO_OBSERVATIONS_INTERVAL,+ orderByToClickhouseSql,+ type DateTimeFilter,+} from "@langfuse/shared/src/server";+import { type OrderByState, type Trace } from "@langfuse/shared";+import { snakeCase } from "lodash";++type QueryType = {+ page: number;+ limit: number;+ projectId: string;+ traceId?: string;+ userId?: string;+ name?: string;+ type?: string;+ parentObservationId?: string;+ fromStartTime?: string;+ toStartTime?: string;+ version?: string;+};++export const generateTracesForPublicApi = async (+ props: QueryType,+ orderBy: OrderByState,+) => {+ 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 chOrderBy = orderBy+ ? orderByToClickhouseSql(orderBy, orderByColumns)+ : "ORDER BY t.timestamp desc";++ const query = `+ WITH observation_stats AS (+ SELECT+ trace_id,+ project_id,+ sum(total_cost) as total_cost,+ date_diff('milliseconds', least(min(start_time), min(end_time)), greatest(max(start_time), max(end_time))) as latency_milliseconds,+ groupArray(id) as observation_ids+ FROM observations FINAL+ WHERE project_id = {projectId: String}+ ${timeFilter ? `AND start_time >= {cteTimeFilter: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}+ GROUP BY project_id, trace_id+ ), score_stats AS (+ SELECT+ trace_id,+ project_id,+ groupArray(id) as score_ids+ FROM scores FINAL+ WHERE project_id = {projectId: String}+ ${timeFilter ? `AND timestamp >= {cteTimeFilter: DateTime64(3)}` : ""}+ GROUP BY project_id, trace_id+ )++ SELECT+ t.id as id,+ CONCAT('/project/', t.project_id, '/traces/', t.id) as "htmlPath",+ t.project_id as projectId,+ t.timestamp as timestamp,+ t.name as name,+ t.input as input,+ t.output as output,+ null as externalId,+ t.session_id as sessionId,+ t.metadata as metadata,+ t.user_id as userId,+ t.release as release,+ t.version as version,+ t.bookmarked as bookmarked,+ t.public as public,+ t.tags as tags,+ t.created_at as createdAt,+ t.updated_at as updatedAt,+ s.score_ids as scores,+ o.observation_ids as observations,+ COALESCE(o.latency_milliseconds / 1000, 0) as latency,+ COALESCE(o.total_cost, 0) as totalCost+ FROM traces t+ LEFT JOIN score_stats s ON t.id = s.trace_id AND t.project_id = s.project_id+ LEFT JOIN observation_stats o ON t.id = o.trace_id AND t.project_id = o.project_id+ WHERE t.project_id = {projectId: String}+ ${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}+ ${chOrderBy}+ LIMIT 1 by t.id, t.project_id+ ${props.limit !== undefined && props.page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}+ `;++ return queryClickhouse<+ Trace & {+ observations: string[];+ scores: string[];+ totalCost: number;+ latency: number;+ htmlPath: string;+ }+ >({+ 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),+ }+ : {}),+ },+ });+};++export const getTracesCountForPublicApi = async (props: QueryType) => {+ const filter = convertApiProvidedFilterToClickhouseFilter(+ props,+ filterParams,+ );+ const appliedFilter = filter.apply();++ const query = `+ SELECT count() 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 orderByColumns = [+ "id",+ "timestamp",+ "name",+ "userId",+ "release",+ "version",+ "public",+ "bookmarked",+ "sessionId",+].map((name) => ({+ uiTableName: name,+ uiTableId: name,+ clickhouseTableName: "traces",+ clickhouseSelect: snakeCase(name),+ queryPrefix: "t",+}));++const filterParams = [+ {+ id: "userId",+ clickhouseSelect: "user_id",+ filterType: "StringFilter",+ clickhouseTable: "traces",+ clickhousePrefix: "t",+ },+ {+ id: "name",+ clickhouseSelect: "name",+ filterType: "StringFilter",+ clickhouseTable: "traces",+ clickhousePrefix: "t",+ },+ {+ id: "tags",+ clickhouseSelect: "tags",+ filterType: "ArrayOptionsFilter",+ clickhouseTable: "traces",+ clickhousePrefix: "t",+ },+ {+ id: "sessionId",+ clickhouseSelect: "session_id",+ filterType: "StringFilter",+ clickhouseTable: "traces",+ clickhousePrefix: "t",+ },+ {+ id: "version",+ clickhouseSelect: "version",+ filterType: "StringFilter",+ clickhouseTable: "traces",+ clickhousePrefix: "t",+ },+ {+ id: "release",+ clickhouseSelect: "release",+ filterType: "StringFilter",+ 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/pages/api/public/observations/index.ts b/web/src/pages/api/public/observations/index.tsindex 32fd56709d..1a4243ea4f 100644--- a/web/src/pages/api/public/observations/index.ts+++ b/web/src/pages/api/public/observations/index.ts@@ -138,33 +138,22 @@ export default withMiddlewares({};},clickhouseExecution: async () => {+ const filterProps = {+ projectId: auth.scope.projectId,+ page: query.page ?? undefined,+ limit: query.limit ?? undefined,+ traceId: query.traceId ?? undefined,+ userId: query.userId ?? undefined,+ name: query.name ?? undefined,+ type: query.type ?? undefined,+ parentObservationId: query.parentObservationId ?? undefined,+ fromStartTime: query.fromStartTime ?? undefined,+ toStartTime: query.toStartTime ?? undefined,+ version: query.version ?? undefined,+ };const [items, count] = await Promise.all([- generateObservationsForPublicApi({- projectId: auth.scope.projectId,- page: query.page ?? undefined,- limit: query.limit ?? undefined,- traceId: query.traceId ?? undefined,- userId: query.userId ?? undefined,- name: query.name ?? undefined,- type: query.type ?? undefined,- parentObservationId: query.parentObservationId ?? undefined,- fromStartTime: query.fromStartTime ?? undefined,- toStartTime: query.toStartTime ?? undefined,- version: query.version ?? undefined,- }),- getObservationsCountForPublicApi({- projectId: auth.scope.projectId,- page: query.page ?? undefined,- limit: query.limit ?? undefined,- traceId: query.traceId ?? undefined,- userId: query.userId ?? undefined,- name: query.name ?? undefined,- type: query.type ?? undefined,- parentObservationId: query.parentObservationId ?? undefined,- fromStartTime: query.fromStartTime ?? undefined,- toStartTime: query.toStartTime ?? undefined,- version: query.version ?? undefined,- }),+ generateObservationsForPublicApi(filterProps),+ getObservationsCountForPublicApi(filterProps),]);const uniqueModels: string[] = Array.from(new Set(diff --git a/web/src/pages/api/public/scores/index.ts b/web/src/pages/api/public/scores/index.tsindex 82af43d567..ef718a865b 100644--- a/web/src/pages/api/public/scores/index.ts+++ b/web/src/pages/api/public/scores/index.ts@@ -20,7 +20,7 @@ import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";import {generateScoresForPublicApi,getScoresCountForPublicApi,-} from "@/src/features/public-api/server/sores";+} from "@/src/features/public-api/server/scores";export default withMiddlewares({POST: createAuthedAPIRoute({diff --git a/web/src/pages/api/public/traces/index.ts b/web/src/pages/api/public/traces/index.tsindex deb3f8a999..9483ea9247 100644--- a/web/src/pages/api/public/traces/index.ts+++ b/web/src/pages/api/public/traces/index.ts@@ -21,6 +21,11 @@ import {import { v4 } from "uuid";import { telemetry } from "@/src/features/telemetry";import { tracesTableCols } from "@langfuse/shared";+import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";+import {+ generateTracesForPublicApi,+ getTracesCountForPublicApi,+} from "@/src/features/public-api/server/traces";export default withMiddlewares({POST: createAuthedAPIRoute({@@ -60,141 +65,179 @@ export default withMiddlewares({querySchema: GetTracesV1Query,responseSchema: GetTracesV1Response,fn: async ({ query, auth }) => {- const skipValue = (query.page - 1) * query.limit;- const userCondition = query.userId- ? Prisma.sql`AND t."user_id" = ${query.userId}`- : Prisma.empty;- const nameCondition = query.name- ? Prisma.sql`AND t."name" = ${query.name}`- : 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 sessionCondition = query.sessionId- ? Prisma.sql`AND t."session_id" = ${query.sessionId}`- : 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 versionCondition = query.version- ? Prisma.sql`AND t."version" = ${query.version}`- : Prisma.empty;- const releaseCondition = query.release- ? Prisma.sql`AND t."release" = ${query.release}`- : Prisma.empty;-- const orderByCondition = orderByToPrismaSql(- query.orderBy ?? null,- tracesTableCols,- );+ return await measureAndReturnApi({+ input: { projectId: auth.scope.projectId, queryClickhouse: false },+ operation: "api/public/traces",+ user: null,+ pgExecution: async () => {+ const skipValue = (query.page - 1) * query.limit;+ const userCondition = query.userId+ ? Prisma.sql`AND t."user_id" = ${query.userId}`+ : Prisma.empty;+ const nameCondition = query.name+ ? Prisma.sql`AND t."name" = ${query.name}`+ : 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 sessionCondition = query.sessionId+ ? Prisma.sql`AND t."session_id" = ${query.sessionId}`+ : 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 versionCondition = query.version+ ? Prisma.sql`AND t."version" = ${query.version}`+ : Prisma.empty;+ const releaseCondition = query.release+ ? Prisma.sql`AND t."release" = ${query.release}`+ : Prisma.empty;- const traces = await prisma.$queryRaw<- Array<- Trace & {- observations: string[];- scores: string[];- totalCost: number;- latency: number;- htmlPath: string;- }- >- >(Prisma.sql`- SELECT- t.id,- CONCAT('/project/', t.project_id,'/traces/',t.id) as "htmlPath",- t.timestamp,- t.name,- t.input,- t.output,- t.project_id as "projectId",- t.session_id as "sessionId",- t.metadata,- t.external_id as "externalId",- t.user_id as "userId",- t.release,- t.version,- t.bookmarked,- t.created_at as "createdAt",- t.updated_at as "updatedAt",- t.public,- t.tags,- COALESCE(o."totalCost", 0)::DOUBLE PRECISION AS "totalCost",- COALESCE(o."latency", 0)::double precision AS "latency",- COALESCE(o."observations", ARRAY[]::text[]) AS "observations",- COALESCE(s."scores", ARRAY[]::text[]) AS "scores"- FROM (- SELECT *- FROM "traces" t- WHERE project_id = ${auth.scope.projectId}- ${fromTimestampCondition}- ${toTimestampCondition}- ${userCondition}- ${nameCondition}- ${tagsCondition}- ${versionCondition}- ${releaseCondition}- ${sessionCondition}- ${orderByCondition}- LIMIT ${query.limit} OFFSET ${skipValue}- ) AS t- LEFT JOIN LATERAL (- SELECT- SUM(o.calculated_total_cost)::DOUBLE PRECISION AS "totalCost",- EXTRACT(EPOCH FROM COALESCE(MAX(o."end_time"), MAX(o."start_time"))) - EXTRACT(EPOCH FROM MIN(o."start_time"))::DOUBLE PRECISION AS "latency",- ARRAY_AGG(DISTINCT o.id) FILTER (WHERE o.id IS NOT NULL) AS "observations"- FROM "observations_view" AS o- WHERE o.trace_id = t.id AND o.project_id = ${auth.scope.projectId}- ) AS o ON true- LEFT JOIN LATERAL (- SELECT- ARRAY_AGG(DISTINCT s.id) FILTER (WHERE s.id IS NOT NULL) AS "scores"- FROM "scores" AS s- WHERE s.trace_id = t.id AND s.project_id = ${auth.scope.projectId}- ) AS s ON true- `);+ const orderByCondition = orderByToPrismaSql(+ query.orderBy ?? null,+ tracesTableCols,+ );- const totalItems = await prisma.trace.count({- where: {- projectId: auth.scope.projectId,- name: query.name ? query.name : undefined,- userId: query.userId ? query.userId : undefined,- sessionId: query.sessionId ? query.sessionId : undefined,- version: query.version ? query.version : undefined,- release: query.release ? query.release : undefined,- timestamp: {- gte: query.fromTimestamp- ? new Date(query.fromTimestamp)- : undefined,- lt: query.toTimestamp ? new Date(query.toTimestamp) : undefined,- },- tags: query.tags- ? {- hasEvery: Array.isArray(query.tags)- ? query.tags- : query.tags.split(","),+ const traces = await prisma.$queryRaw<+ Array<+ Trace & {+ observations: string[];+ scores: string[];+ totalCost: number;+ latency: number;+ htmlPath: string;}- : undefined,+ >+ >(Prisma.sql`+ SELECT+ t.id,+ CONCAT('/project/', t.project_id,'/traces/',t.id) as "htmlPath",+ t.timestamp,+ t.name,+ t.input,+ t.output,+ t.project_id as "projectId",+ t.session_id as "sessionId",+ t.metadata,+ t.external_id as "externalId",+ t.user_id as "userId",+ t.release,+ t.version,+ t.bookmarked,+ t.created_at as "createdAt",+ t.updated_at as "updatedAt",+ t.public,+ t.tags,+ COALESCE(o."totalCost", 0)::DOUBLE PRECISION AS "totalCost",+ COALESCE(o."latency", 0)::double precision AS "latency",+ COALESCE(o."observations", ARRAY[]::text[]) AS "observations",+ COALESCE(s."scores", ARRAY[]::text[]) AS "scores"+ FROM (+ SELECT *+ FROM "traces" t+ WHERE project_id = ${auth.scope.projectId}+ ${fromTimestampCondition}+ ${toTimestampCondition}+ ${userCondition}+ ${nameCondition}+ ${tagsCondition}+ ${versionCondition}+ ${releaseCondition}+ ${sessionCondition}+ ${orderByCondition}+ LIMIT ${query.limit} OFFSET ${skipValue}+ ) AS t+ LEFT JOIN LATERAL (+ SELECT+ SUM(o.calculated_total_cost)::DOUBLE PRECISION AS "totalCost",+ EXTRACT(EPOCH FROM COALESCE(MAX(o."end_time"), MAX(o."start_time"))) - EXTRACT(EPOCH FROM MIN(o."start_time"))::DOUBLE PRECISION AS "latency",+ ARRAY_AGG(DISTINCT o.id) FILTER (WHERE o.id IS NOT NULL) AS "observations"+ FROM "observations_view" AS o+ WHERE o.trace_id = t.id AND o.project_id = ${auth.scope.projectId}+ ) AS o ON true+ LEFT JOIN LATERAL (+ SELECT+ ARRAY_AGG(DISTINCT s.id) FILTER (WHERE s.id IS NOT NULL) AS "scores"+ FROM "scores" AS s+ WHERE s.trace_id = t.id AND s.project_id = ${auth.scope.projectId}+ ) AS s ON true+ `);++ const totalItems = await prisma.trace.count({+ where: {+ projectId: auth.scope.projectId,+ name: query.name ? query.name : undefined,+ userId: query.userId ? query.userId : undefined,+ sessionId: query.sessionId ? query.sessionId : undefined,+ version: query.version ? query.version : undefined,+ release: query.release ? query.release : undefined,+ timestamp: {+ gte: query.fromTimestamp+ ? new Date(query.fromTimestamp)+ : undefined,+ lt: query.toTimestamp ? new Date(query.toTimestamp) : undefined,+ },+ tags: query.tags+ ? {+ hasEvery: Array.isArray(query.tags)+ ? query.tags+ : query.tags.split(","),+ }+ : undefined,+ },+ });++ return {+ data: traces,+ 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,+ userId: query.userId ?? undefined,+ name: query.name ?? undefined,+ tags: query.tags ?? undefined,+ sessionId: query.sessionId ?? undefined,+ version: query.version ?? undefined,+ release: query.release ?? undefined,+ fromTimestamp: query.fromTimestamp ?? undefined,+ toTimestamp: query.toTimestamp ?? undefined,+ };++ const [items, count] = await Promise.all([+ generateTracesForPublicApi(filterProps, query.orderBy ?? null),+ getTracesCountForPublicApi(filterProps),+ ]);- return {- data: traces,- meta: {- page: query.page,- limit: query.limit,- totalItems,- totalPages: Math.ceil(totalItems / query.limit),+ const finalCount = count || 0;+ return {+ data: items,+ meta: {+ page: query.page,+ limit: query.limit,+ totalItems: finalCount,+ totalPages: Math.ceil(finalCount / query.limit),+ },+ };},- };+ });},}),});