Skip to content

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

feat(ui): export traces (#3332)

marliessophiec32b84663cfa
diff --git a/packages/shared/src/features/batchExport/types.ts b/packages/shared/src/features/batchExport/types.ts
index 7bc51eecb9..efbbaa6f57 100644
--- a/packages/shared/src/features/batchExport/types.ts
+++ b/packages/shared/src/features/batchExport/types.ts
@@ -19,6 +19,7 @@ export enum BatchExportFileFormat {
export enum BatchExportTableName {
Sessions = "sessions",
+ Traces = "traces",
}
export const exportOptions: Record<
diff --git a/packages/shared/src/server/filterToPrisma.ts b/packages/shared/src/server/filterToPrisma.ts
index 826cb73ec2..fd09b804a1 100644
--- a/packages/shared/src/server/filterToPrisma.ts
+++ b/packages/shared/src/server/filterToPrisma.ts
@@ -26,7 +26,7 @@ const arrayOperatorReplacements = {
export function tableColumnsToSqlFilterAndPrefix(
filters: FilterState,
tableColumns: ColumnDefinition[],
- table: TableNames,
+ table: TableNames
): Prisma.Sql {
const sql = tableColumnsToSqlFilter(filters, tableColumns, table);
if (sql === Prisma.empty) {
@@ -42,14 +42,14 @@ export function tableColumnsToSqlFilterAndPrefix(
export function tableColumnsToSqlFilter(
filters: FilterState,
tableColumns: ColumnDefinition[],
- table: TableNames,
+ table: TableNames
): Prisma.Sql {
const internalFilters = filters.map((filter) => {
// Get column definition to map column to internal name, e.g. "t.id"
const col = tableColumns.find(
(c) =>
// TODO: Only use id instead of name
- c.name === filter.column || c.id === filter.column,
+ c.name === filter.column || c.id === filter.column
);
if (!col) {
logger.error("Invalid filter column", filter.column);
@@ -71,13 +71,13 @@ export function tableColumnsToSqlFilter(
? Prisma.raw(
arrayOperatorReplacements[
filter.operator as keyof typeof arrayOperatorReplacements
- ],
+ ]
)
: filter.operator in operatorReplacements
? Prisma.raw(
operatorReplacements[
filter.operator as keyof typeof operatorReplacements
- ],
+ ]
)
: Prisma.raw(filter.operator); //checked by zod
@@ -97,13 +97,13 @@ export function tableColumnsToSqlFilter(
break;
case "stringOptions":
valuePrisma = Prisma.sql`(${Prisma.join(
- filter.value.map((v) => Prisma.sql`${v}`),
+ filter.value.map((v) => Prisma.sql`${v}`)
)})`;
break;
case "arrayOptions":
valuePrisma = Prisma.sql`ARRAY[${Prisma.join(
filter.value.map((v) => Prisma.sql`${v}`),
- ", ",
+ ", "
)}] `;
break;
@@ -123,12 +123,12 @@ export function tableColumnsToSqlFilter(
filter.type === "string" || filter.type === "stringObject"
? [
["contains", "does not contain", "ends with"].includes(
- filter.operator,
+ filter.operator
)
? Prisma.raw("'%' || ")
: Prisma.empty,
["contains", "does not contain", "starts with"].includes(
- filter.operator,
+ filter.operator
)
? Prisma.raw(" || '%'")
: Prisma.empty,
@@ -152,7 +152,7 @@ export function tableColumnsToSqlFilter(
const castValueToPostgresTypes = (
column: ColumnDefinition,
- table: TableNames,
+ table: TableNames
) => {
return column.name === "type" &&
(table === "observations" ||
@@ -168,7 +168,7 @@ const dateOperators = filterOperators["datetime"];
export const datetimeFilterToPrismaSql = (
safeColumn: string,
operator: (typeof dateOperators)[number],
- value: Date,
+ value: Date
) => {
if (!dateOperators.includes(operator)) {
throw new Error("Invalid operator: " + operator);
@@ -178,12 +178,12 @@ export const datetimeFilterToPrismaSql = (
}
return Prisma.sql`AND ${Prisma.raw(safeColumn)} ${Prisma.raw(
- operator,
+ operator
)} ${value}::timestamp with time zone at time zone 'UTC'`;
};
export const datetimeFilterToPrisma = (
- timestampFilter: z.infer<typeof timeFilter>,
+ timestampFilter: z.infer<typeof timeFilter>
) => {
const prismaTimestampFilter =
timestampFilter.operator === ">="
diff --git a/packages/shared/src/server/queries/createTracesQuery.ts b/packages/shared/src/server/queries/createTracesQuery.ts
new file mode 100644
index 0000000000..31a4c0409f
--- /dev/null
+++ b/packages/shared/src/server/queries/createTracesQuery.ts
@@ -0,0 +1,89 @@
+import { Prisma } from "@prisma/client";
+
+export function createTracesQuery({
+ select,
+ projectId,
+ observationTimeseriesFilter = Prisma.empty,
+ page,
+ limit,
+ searchCondition = Prisma.empty,
+ filterCondition = Prisma.empty,
+ orderByCondition = Prisma.empty,
+ selectScoreValues = false,
+}: {
+ select: Prisma.Sql;
+ projectId: string;
+ observationTimeseriesFilter?: Prisma.Sql;
+ page?: number;
+ limit?: number;
+ searchCondition?: Prisma.Sql;
+ filterCondition?: Prisma.Sql;
+ orderByCondition?: Prisma.Sql;
+ selectScoreValues?: boolean;
+}) {
+ return Prisma.sql`
+ SELECT
+ ${select}
+ FROM
+ "traces" AS t
+ LEFT JOIN LATERAL (
+ SELECT
+ SUM(prompt_tokens) AS "promptTokens",
+ SUM(completion_tokens) AS "completionTokens",
+ SUM(total_tokens) AS "totalTokens",
+ SUM(calculated_total_cost) AS "calculatedTotalCost",
+ SUM(calculated_input_cost) AS "calculatedInputCost",
+ SUM(calculated_output_cost) AS "calculatedOutputCost",
+ COALESCE(
+ MAX(CASE WHEN level = 'ERROR' THEN 'ERROR' END),
+ MAX(CASE WHEN level = 'WARNING' THEN 'WARNING' END),
+ MAX(CASE WHEN level = 'DEFAULT' THEN 'DEFAULT' END),
+ 'DEBUG'
+ ) AS "level"
+ FROM
+ "observations_view"
+ WHERE
+ trace_id = t.id
+ AND "type" = 'GENERATION'
+ AND "project_id" = ${projectId}
+ ${observationTimeseriesFilter}
+ ) AS tm ON true
+ LEFT JOIN LATERAL (
+ SELECT
+ COUNT(*) AS "observationCount",
+ EXTRACT(EPOCH FROM COALESCE(MAX("end_time"), MAX("start_time"))) - EXTRACT(EPOCH FROM MIN("start_time"))::double precision AS "latency"
+ FROM
+ "observations"
+ WHERE
+ trace_id = t.id
+ AND "project_id" = ${projectId}
+ ${observationTimeseriesFilter}
+ ) AS tl ON true
+ LEFT JOIN LATERAL (
+ SELECT
+ ${selectScoreValues ? Prisma.sql`jsonb_object_agg(name::text, "values") AS "scores_values",` : Prisma.empty}
+ jsonb_object_agg(name::text, avg_value::double precision) AS "scores_avg"
+ FROM (
+ SELECT
+ name,
+ ${selectScoreValues ? Prisma.sql`array_agg(COALESCE(string_value, value::text)) AS "values",` : Prisma.empty}
+ AVG(value) avg_value
+ FROM
+ scores
+ WHERE
+ trace_id = t.id
+ AND t."project_id" = ${projectId}
+ ${selectScoreValues ? Prisma.empty : Prisma.sql`AND scores."data_type" IN ('NUMERIC', 'BOOLEAN')`}
+ GROUP BY
+ name
+ ) tmp
+ ) AS s_avg ON true
+ WHERE
+ t."project_id" = ${projectId}
+ ${searchCondition}
+ ${filterCondition}
+ ${orderByCondition}
+ ${limit ? Prisma.sql`LIMIT ${limit}` : Prisma.empty}
+ ${page && limit ? Prisma.sql`OFFSET ${page * limit}` : Prisma.empty}
+`;
+}
diff --git a/packages/shared/src/server/queries/index.ts b/packages/shared/src/server/queries/index.ts
index 08b9958178..a7c8c9922a 100644
--- a/packages/shared/src/server/queries/index.ts
+++ b/packages/shared/src/server/queries/index.ts
@@ -1 +1,2 @@
export { createSessionsAllQuery } from "./createSessionsAllQuery";
+export { createTracesQuery } from "./createTracesQuery";
diff --git a/packages/shared/src/server/services/email/batchExportSuccess/BatchExportSuccessEmailTemplate.tsx b/packages/shared/src/server/services/email/batchExportSuccess/BatchExportSuccessEmailTemplate.tsx
index c1cc416fc7..d5805dfe7f 100644
--- a/packages/shared/src/server/services/email/batchExportSuccess/BatchExportSuccessEmailTemplate.tsx
+++ b/packages/shared/src/server/services/email/batchExportSuccess/BatchExportSuccessEmailTemplate.tsx
@@ -59,6 +59,10 @@ export const BatchExportSuccessEmailTemplate = ({
download. The download link will expire in{" "}
<strong>{expiresInHours} hours</strong>.
</Text>
+ <Text className="text-sm leading-6 text-black">
+ Please note data exports do not reflect custom column ordering or
+ visibility.
+ </Text>
<Section className="mb-4 mt-8 text-center">
<Button
className="rounded bg-black px-5 py-3 text-center text-xs font-semibold text-white no-underline"
diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts
index d8a3e847fe..d719cc88b5 100644
--- a/packages/shared/src/types.ts
+++ b/packages/shared/src/types.ts
@@ -1,7 +1,8 @@
import { type z } from "zod";
-import { singleFilter } from "./interfaces/filters";
+import { singleFilter, timeFilter } from "./interfaces/filters";
// to be sent to the server
+export type TimeFilter = z.infer<typeof timeFilter>;
export type FilterCondition = z.infer<typeof singleFilter>;
export type FilterState = FilterCondition[];
diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsx
index be30919bb0..6678f4278f 100644
--- a/web/src/components/table/use-cases/traces.tsx
+++ b/web/src/components/table/use-cases/traces.tsx
@@ -33,6 +33,7 @@ import {
type TraceOptions,
tracesTableColsWithOptions,
type ObservationLevel,
+ BatchExportTableName,
} from "@langfuse/shared";
import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";
import { IOTableCell } from "@/src/components/ui/CodeJsonViewer";
@@ -47,6 +48,7 @@ import { useIndividualScoreColumns } from "@/src/features/scores/hooks/useIndivi
import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";
import { Skeleton } from "@/src/components/ui/skeleton";
import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";
+import { BatchExportTableButton } from "@/src/components/BatchExportTableButton";
export type TracesTableRow = {
bookmarked: boolean;
@@ -736,7 +738,7 @@ export default function TracesTable({
filterState={userFilterState}
setFilterState={useDebounce(setUserFilterState)}
columnsWithCustomSelect={["name", "tags"]}
- actionButtons={
+ actionButtons={[
Object.keys(selectedRows).filter((traceId) =>
traces.data?.traces.map((t) => t.id).includes(traceId),
).length > 0 ? (
@@ -750,8 +752,13 @@ export default function TracesTable({
setSelectedRows({});
}}
/>
- ) : null
- }
+ ) : null,
+ <BatchExportTableButton
+ {...{ projectId, filterState, orderByState }}
+ tableName={BatchExportTableName.Traces}
+ key="batchExport"
+ />,
+ ]}
columnVisibility={columnVisibility}
setColumnVisibility={setColumnVisibility}
columnOrder={columnOrder}
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index aec7bd7e3a..a6fa043d40 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -17,6 +17,7 @@ import {
type TraceOptions,
tracesTableCols,
} from "@langfuse/shared";
+
import {
type ObservationLevel,
type ObservationView,
@@ -29,10 +30,11 @@ import {
orderByToPrismaSql,
tableColumnsToSqlFilterAndPrefix,
traceException,
+ createTracesQuery,
} from "@langfuse/shared/src/server";
import { TRPCError } from "@trpc/server";
-
import type Decimal from "decimal.js";
+
const TraceFilterOptions = z.object({
projectId: z.string(), // Required for protectedProjectProcedure
searchQuery: z.string().nullable(),
@@ -586,86 +588,3 @@ function parseTraceAllFilters(input: TraceFilterOptions) {
searchCondition,
};
}
-
-function createTracesQuery({
- select,
- projectId,
- observationTimeseriesFilter = Prisma.empty,
- page,
- limit,
- searchCondition = Prisma.empty,
- filterCondition = Prisma.empty,
- orderByCondition = Prisma.empty,
-}: {
- select: Prisma.Sql;
- projectId: string;
- observationTimeseriesFilter?: Prisma.Sql;
- page?: number;
- limit?: number;
- searchCondition?: Prisma.Sql;
- filterCondition?: Prisma.Sql;
- orderByCondition?: Prisma.Sql;
-}) {
- return Prisma.sql`
- SELECT
- ${select}
- FROM
- "traces" AS t
- LEFT JOIN LATERAL (
- SELECT
- SUM(prompt_tokens) AS "promptTokens",
- SUM(completion_tokens) AS "completionTokens",
- SUM(total_tokens) AS "totalTokens",
- SUM(calculated_total_cost) AS "calculatedTotalCost",
- SUM(calculated_input_cost) AS "calculatedInputCost",
- SUM(calculated_output_cost) AS "calculatedOutputCost",
- COALESCE(
- MAX(CASE WHEN level = 'ERROR' THEN 'ERROR' END),
- MAX(CASE WHEN level = 'WARNING' THEN 'WARNING' END),
- MAX(CASE WHEN level = 'DEFAULT' THEN 'DEFAULT' END),
- 'DEBUG'
- ) AS "level"
- FROM
- "observations_view"
- WHERE
- trace_id = t.id
- AND "type" = 'GENERATION'
- AND "project_id" = ${projectId}
- ${observationTimeseriesFilter}
- ) AS tm ON true
- LEFT JOIN LATERAL (
- SELECT
- COUNT(*) AS "observationCount",
- EXTRACT(EPOCH FROM COALESCE(MAX("end_time"), MAX("start_time"))) - EXTRACT(EPOCH FROM MIN("start_time"))::double precision AS "latency"
- FROM
- "observations"
- WHERE
- trace_id = t.id
- AND "project_id" = ${projectId}
- ${observationTimeseriesFilter}
- ) AS tl ON true
- LEFT JOIN LATERAL (
- SELECT
- jsonb_object_agg(name::text, avg_value::double precision) AS "scores_avg"
- FROM (
- SELECT
- name,
- AVG(value) avg_value
- FROM
- scores
- WHERE
- trace_id = t.id
- AND scores."data_type" IN ('NUMERIC', 'BOOLEAN')
- GROUP BY
- name
- ) tmp
- ) AS s_avg ON true
- WHERE
- t."project_id" = ${projectId}
- ${searchCondition}
- ${filterCondition}
- ${orderByCondition}
- ${limit ? Prisma.sql`LIMIT ${limit}` : Prisma.empty}
- ${page && limit ? Prisma.sql`OFFSET ${page * limit}` : Prisma.empty}
-`;
-}
diff --git a/worker/src/features/batchExport/handleBatchExportJob.ts b/worker/src/features/batchExport/handleBatchExportJob.ts
index f32b774eaa..d07497c089 100644
--- a/worker/src/features/batchExport/handleBatchExportJob.ts
+++ b/worker/src/features/batchExport/handleBatchExportJob.ts
@@ -3,10 +3,13 @@ import { pipeline } from "stream";
import {
BatchExportFileFormat,
BatchExportQuerySchema,
+ BatchExportQueryType,
BatchExportStatus,
exportOptions,
FilterCondition,
Prisma,
+ TimeFilter,
+ tracesTableCols,
} from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import {
@@ -16,12 +19,197 @@ import {
sendBatchExportSuccessEmail,
streamTransformations,
BatchExportJobType,
+ createTracesQuery,
+ orderByToPrismaSql,
+ tableColumnsToSqlFilterAndPrefix,
} from "@langfuse/shared/src/server";
import { env } from "../../env";
import { logger } from "@langfuse/shared/src/server";
+import { BatchExportSessionsRow, BatchExportTracesRow } from "./types";
+
+const tableNameToTimeFilterColumn = {
+ sessions: "created_at",
+ traces: "timestamp",
+};
+
+const isTimestampFilter = (filter: FilterCondition): filter is TimeFilter => {
+ return filter.column === "Timestamp" && filter.type === "datetime";
+};
+
+const parseTracesOrderByAndFilter = (
+ orderBy: BatchExportQueryType["orderBy"],
+ filter: BatchExportQueryType["filter"]
+) => {
+ const orderByCondition = orderByToPrismaSql(orderBy, tracesTableCols);
+ const filterCondition = tableColumnsToSqlFilterAndPrefix(
+ filter ?? [],
+ tracesTableCols,
+ "traces"
+ );
+
+ const scoreTimestampFilter = filter?.find(isTimestampFilter);
+
+ return {
+ orderByCondition,
+ filterCondition,
+ scoreTimestampFilterCondition: scoreTimestampFilter
+ ? Prisma.sql`AND s.timestamp >= ${scoreTimestampFilter.value}`
+ : Prisma.empty,
+ };
+};
+
+const getDatabaseReadStream = async ({
+ projectId,
+ tableName,
+ filter,
+ orderBy,
+ cutoffCreatedAt,
+}: {
+ projectId: string;
+ cutoffCreatedAt: Date;
+} & BatchExportQueryType): Promise<DatabaseReadStream<unknown>> => {
+ // Set createdAt cutoff to prevent exporting data that was created after the job was queued
+ const createdAtCutoffFilter: FilterCondition = {
+ column: tableNameToTimeFilterColumn[tableName],
+ operator: "<",
+ value: cutoffCreatedAt,
+ type: "datetime",
+ };
+
+ switch (tableName) {
+ case "sessions":
+ return new DatabaseReadStream<unknown>(
+ async (pageSize: number, offset: number) => {
+ const query = createSessionsAllQuery(
+ Prisma.sql`
+ s.id,
+ s."created_at" AS "createdAt",
+ s.bookmarked,
+ s.public,
+ t."userIds",
+ t."countTraces",
+ o."sessionDuration",
+ o."inputCost" AS "inputCost",
+ o."outputCost" AS "outputCost",
+ o."totalCost" AS "totalCost",
+ o."promptTokens" AS "inputTokens",
+ o."completionTokens" AS "outputTokens",
+ o."totalTokens" AS "totalTokens",
+ t."tags" AS "traceTags",
+ (count(*) OVER ())::int AS "totalCount"
+ `,
+ {
+ projectId,
+ filter: filter
+ ? [...filter, createdAtCutoffFilter]
+ : [createdAtCutoffFilter],
+ orderBy,
+ limit: pageSize,
+ page: Math.floor(offset / pageSize),
+ }
+ );
+ const chunk = await prisma.$queryRaw<BatchExportSessionsRow[]>(query);
+
+ return chunk;
+ },
+ 1000,
+ env.BATCH_EXPORT_ROW_LIMIT
+ );
+ case "traces": {
+ const {
+ orderByCondition,
+ filterCondition,
+ scoreTimestampFilterCondition,
+ } = parseTracesOrderByAndFilter(
+ orderBy,
+ filter ? [...filter, createdAtCutoffFilter] : [createdAtCutoffFilter]
+ );
+
+ const distinctScoreNames = await prisma.$queryRaw<{ name: string }[]>`
+ SELECT DISTINCT name
+ FROM scores s
+ WHERE s.project_id = ${projectId}
+ AND s.created_at <= ${cutoffCreatedAt}
+ ${scoreTimestampFilterCondition}
+ `;
+
+ const emptyScoreColumns = distinctScoreNames.reduce(
+ (acc, { name }) => ({ ...acc, [name]: null }),
+ {}
+ );
+
+ return new DatabaseReadStream<unknown>(
+ async (pageSize: number, offset: number) => {
+ const query = createTracesQuery({
+ select: Prisma.sql`
+ t."bookmarked",
+ t."id",
+ t."timestamp",
+ t."name",
+ t."user_id" AS "userId",
+ tm."level" AS "level",
+ tl."observationCount" AS "observationCount",
+ s_avg."scores_values" AS "scores",
+ tl.latency AS "latency",
+ t."release",
+ t."version",
+ t.session_id AS "sessionId",
+ t."input",
+ t."output",
+ t."metadata",
+ t."tags",
+ COALESCE(tm."promptTokens", 0)::bigint AS "usage.promptTokens",
+ COALESCE(tm."completionTokens", 0)::bigint AS "usage.completionTokens",
+ COALESCE(tm."totalTokens", 0)::bigint AS "usage.totalTokens",
+ COALESCE(tm."calculatedInputCost", 0)::numeric AS "inputCost",
+ COALESCE(tm."calculatedOutputCost", 0)::numeric AS "outputCost",
+ COALESCE(tm."calculatedTotalCost", 0)::numeric AS "totalCost"
+ `,
+ projectId,
+ limit: pageSize,
+ page: Math.floor(offset / pageSize),
+ filterCondition,
+ orderByCondition,
+ selectScoreValues: true,
+ });
+ const chunk = await prisma.$queryRaw<BatchExportTracesRow[]>(query);
+
+ const chunkWithFlattenedScores = chunk.map((row) => {
+ const { scores, ...data } = row;
+ if (!scores) return { ...data, ...emptyScoreColumns };
+ const scoreColumns = Object.entries(scores).reduce(
+ (acc, [key, value]) => {
+ if (key in emptyScoreColumns) {
+ return {
+ ...acc,
+ [key]: value,
+ };
+ } else {
+ return acc;
+ }
+ },
+ emptyScoreColumns
+ );
+ return {
+ ...data,
+ ...scoreColumns,
+ };
+ });
+
+ return chunkWithFlattenedScores;
+ },
+ 1000,
+ env.BATCH_EXPORT_ROW_LIMIT
+ );
+ }
+ default:
+ throw new Error("Invalid table name: " + tableName);
+ }
+};
+
export const handleBatchExportJob = async (
- batchExportJob: BatchExportJobType,
+ batchExportJob: BatchExportJobType
) => {
const { projectId, batchExportId } = batchExportJob;
@@ -57,54 +245,12 @@ export const handleBatchExportJob = async (
throw new Error("Failed to parse query: " + parsedQuery.error.message);
}
- // Get database read stream
- let { filter, orderBy, tableName } = parsedQuery.data;
-
- // Set createdAt cutoff to prevent exporting data that was created after the job was queued
- const createdAtCutoffFilter: FilterCondition = {
- column: "createdAt",
- operator: "<",
- value: jobDetails.createdAt,
- type: "datetime",
- };
-
- const dbReadStream = new DatabaseReadStream<unknown>(
- async (pageSize: number, offset: number) => {
- const query = createSessionsAllQuery(
- Prisma.sql`
- s.id,
- s. "created_at" AS "createdAt",
- s.bookmarked,
- s.public,
- t. "userIds",
- t. "countTraces",
- o. "sessionDuration",
- o. "totalCost" AS "totalCost",
- o. "inputCost" AS "inputCost",
- o. "outputCost" AS "outputCost",
- o. "promptTokens" AS "promptTokens",
- o. "completionTokens" AS "completionTokens",
- o. "totalTokens" AS "totalTokens",
- (count(*) OVER ())::int AS "totalCount"
- `,
- {
- projectId,
- filter: filter
- ? [...filter, createdAtCutoffFilter]
- : [createdAtCutoffFilter],
- orderBy,
- limit: pageSize,
- page: Math.floor(offset / pageSize),
- },
- );
-
- const chunk = await prisma.$queryRaw<unknown[]>(query);
-
- return chunk;
- },
- 1000,
- env.BATCH_EXPORT_ROW_LIMIT,
- );
+ // handle db read stream
+ const dbReadStream = await getDatabaseReadStream({
+ projectId,
+ cutoffCreatedAt: jobDetails.createdAt,
+ ...parsedQuery.data,
+ });
// Transform data to desired format
const fileStream = pipeline(
@@ -114,7 +260,7 @@ export const handleBatchExportJob = async (
if (err) {
logger.error("Getting data from DB and transform failed: ", err);
}
- },
+ }
);
// Stream upload results to S3
@@ -131,7 +277,7 @@ export const handleBatchExportJob = async (
const fileDate = new Date().toISOString();
const fileExtension =
exportOptions[jobDetails.format as BatchExportFileFormat].extension;
- const fileName = `${fileDate}-lf-${tableName}-export-${projectId}.${fileExtension}`;
+ const fileName = `${fileDate}-lf-${parsedQuery.data.tableName}-export-${projectId}.${fileExtension}`;
const expiresInSeconds =
env.BATCH_EXPORT_DOWNLOAD_LINK_EXPIRATION_HOURS * 3600;
diff --git a/worker/src/features/batchExport/types.ts b/worker/src/features/batchExport/types.ts
new file mode 100644
index 0000000000..b4c5516a3f
--- /dev/null
+++ b/worker/src/features/batchExport/types.ts
@@ -0,0 +1,47 @@
+import { ObservationLevel } from "@langfuse/shared";
+import Decimal from "decimal.js";
+
+export type BatchExportSessionsRow = {
+ id: string;
+ createdAt: Date;
+ bookmarked: boolean;
+ public: boolean;
+ userIds?: string[] | null;
+ countTraces?: number | null;
+ sessionDuration?: number | null;
+ inputCost?: Decimal | null;
+ outputCost?: Decimal | null;
+ totalCost?: Decimal | null;
+ inputTokens?: bigint | null;
+ outputTokens?: bigint | null;
+ totalTokens?: bigint | null;
+ traceTags?: string[] | null;
+ totalCount: number;
+};
+
+export type BatchExportTracesRow = {
+ bookmarked: boolean;
+ id: string;
+ timestamp: Date;
+ name: string;
+ userId?: string | null;
+ level?: ObservationLevel | null;
+ observationCount?: number | null;
+ scores?: Record<string, string[] | number[]> | null;
+ latency?: number | null;
+ release?: string | null;
+ version?: string | null;
+ sessionId?: string | null;
+ input?: unknown | null;
+ output?: unknown | null;
+ metadata?: unknown | null;
+ tags: string[];
+ usage: {
+ promptTokens?: bigint | null;
+ completionTokens?: bigint | null;
+ totalTokens?: bigint | null;
+ };
+ inputCost?: Decimal | null;
+ outputCost?: Decimal | null;
+ totalCost?: Decimal | null;
+};