Skip to content

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

feat: add json and jsonl support for scheduled blob exports (#6313)

Steffen Schmitzbef666a694c5
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 3d94d11007..156dbbbf80 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -33,7 +33,7 @@
"scripts": {
"build": "tsc",
"dev": "tsc --watch",
- "lint": "eslint . --ext .js,.jsx,.ts,.tsx --max-warnings 64",
+ "lint": "eslint . --ext .js,.jsx,.ts,.tsx --max-warnings 65",
"lint:fix": "eslint . --ext .js,.jsx,.ts,.tsx --fix",
"db:migrate": "DISABLE_ERD=false dotenv -e ../../.env -- npx prisma migrate dev",
"db:push": "DISABLE_ERD=false dotenv -e ../../.env -- npx prisma db push",
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index f551a7954d..4f6091cb5b 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -80,6 +80,12 @@ export const JobExecutionStatus = {
CANCELLED: "CANCELLED"
} as const;
export type JobExecutionStatus = (typeof JobExecutionStatus)[keyof typeof JobExecutionStatus];
+export const BlobStorageIntegrationFileType = {
+ JSON: "JSON",
+ CSV: "CSV",
+ JSONL: "JSONL"
+} as const;
+export type BlobStorageIntegrationFileType = (typeof BlobStorageIntegrationFileType)[keyof typeof BlobStorageIntegrationFileType];
export const BlobStorageIntegrationType = {
S3: "S3",
S3_COMPATIBLE: "S3_COMPATIBLE",
@@ -208,6 +214,7 @@ export type BlobStorageIntegration = {
last_sync_at: Timestamp | null;
enabled: boolean;
export_frequency: string;
+ file_type: Generated<BlobStorageIntegrationFileType>;
created_at: Generated<Timestamp>;
updated_at: Generated<Timestamp>;
};
diff --git a/packages/shared/prisma/migrations/20250402142320_add_blobstorage_integration_file_type/migration.sql b/packages/shared/prisma/migrations/20250402142320_add_blobstorage_integration_file_type/migration.sql
new file mode 100644
index 0000000000..cb835eac14
--- /dev/null
+++ b/packages/shared/prisma/migrations/20250402142320_add_blobstorage_integration_file_type/migration.sql
@@ -0,0 +1,5 @@
+-- CreateEnum
+CREATE TYPE "BlobStorageIntegrationFileType" AS ENUM ('JSON', 'CSV', 'JSONL');
+
+-- AlterTable
+ALTER TABLE "blob_storage_integrations" ADD COLUMN "file_type" "BlobStorageIntegrationFileType" NOT NULL DEFAULT 'CSV';
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index b02390aaaa..f5c1841e2b 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -693,7 +693,6 @@ model PromptProtectedLabels {
label String
@@unique([projectId, label])
-
@@map("prompt_protected_labels")
}
@@ -908,10 +907,11 @@ model BlobStorageIntegration {
forcePathStyle Boolean @map("force_path_style")
// Integration Config
- nextSyncAt DateTime? @map("next_sync_at")
- lastSyncAt DateTime? @map("last_sync_at")
+ nextSyncAt DateTime? @map("next_sync_at")
+ lastSyncAt DateTime? @map("last_sync_at")
enabled Boolean
- exportFrequency String @map("export_frequency")
+ exportFrequency String @map("export_frequency")
+ fileType BlobStorageIntegrationFileType @default(CSV) @map("file_type")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
@@ -919,6 +919,14 @@ model BlobStorageIntegration {
@@map("blob_storage_integrations")
}
+enum BlobStorageIntegrationFileType {
+ JSON
+ CSV
+ JSONL
+
+ @@map("BlobStorageIntegrationFileType")
+}
+
enum BlobStorageIntegrationType {
S3
S3_COMPATIBLE
diff --git a/packages/shared/src/features/batchExport/types.ts b/packages/shared/src/features/batchExport/types.ts
index 7f1d9d9563..f21766c367 100644
--- a/packages/shared/src/features/batchExport/types.ts
+++ b/packages/shared/src/features/batchExport/types.ts
@@ -15,6 +15,7 @@ export enum BatchExportStatus {
export enum BatchExportFileFormat {
JSON = "JSON",
CSV = "CSV",
+ JSONL = "JSONL",
}
export enum BatchExportTableName {
@@ -35,6 +36,11 @@ export const exportOptions: Record<
> = {
CSV: { label: "CSV", extension: "csv", fileType: "text/csv" },
JSON: { label: "JSON", extension: "json", fileType: "application/json" },
+ JSONL: {
+ label: "JSONL",
+ extension: "jsonl",
+ fileType: "application/x-ndjson",
+ },
} as const;
export const BatchExportQuerySchema = z.object({
diff --git a/packages/shared/src/server/utils/transforms/index.ts b/packages/shared/src/server/utils/transforms/index.ts
index 2e93509479..b3031a0c67 100644
--- a/packages/shared/src/server/utils/transforms/index.ts
+++ b/packages/shared/src/server/utils/transforms/index.ts
@@ -3,6 +3,7 @@ import { Transform } from "stream";
import { BatchExportFileFormat } from "../../../features/batchExport/types";
import { transformStreamToCsv } from "./transformStreamToCsv";
import { transformStreamToJson } from "./transformStreamToJson";
+import { transformStreamToJsonl } from "./transformStreamToJsonl";
export const streamTransformations: Record<
BatchExportFileFormat,
@@ -10,4 +11,5 @@ export const streamTransformations: Record<
> = {
CSV: transformStreamToCsv,
JSON: transformStreamToJson,
+ JSONL: transformStreamToJsonl,
};
diff --git a/packages/shared/src/server/utils/transforms/transformStreamToJsonl.ts b/packages/shared/src/server/utils/transforms/transformStreamToJsonl.ts
new file mode 100644
index 0000000000..4ece5c4890
--- /dev/null
+++ b/packages/shared/src/server/utils/transforms/transformStreamToJsonl.ts
@@ -0,0 +1,17 @@
+import { Transform, type TransformCallback } from "stream";
+import { stringify } from "./stringify";
+
+export function transformStreamToJsonl(): Transform {
+ return new Transform({
+ objectMode: true,
+
+ transform(
+ row: Record<string, any>,
+ encoding: BufferEncoding,
+ callback: TransformCallback,
+ ): void {
+ this.push(stringify(row) + "\n");
+ callback();
+ },
+ });
+}
diff --git a/web/src/features/blobstorage-integration/blobstorage-integration-router.ts b/web/src/features/blobstorage-integration/blobstorage-integration-router.ts
index 976c278283..4ad0f61afb 100644
--- a/web/src/features/blobstorage-integration/blobstorage-integration-router.ts
+++ b/web/src/features/blobstorage-integration/blobstorage-integration-router.ts
@@ -84,6 +84,7 @@ export const blobStorageIntegrationRouter = createTRPCRouter({
exportFrequency,
enabled,
forcePathStyle,
+ fileType,
} = input;
const data: Partial<BlobStorageIntegration> = {
@@ -96,6 +97,7 @@ export const blobStorageIntegrationRouter = createTRPCRouter({
enabled,
accessKeyId,
forcePathStyle: forcePathStyle || false,
+ fileType,
};
// Use a transaction to check if record exists, then create or update
diff --git a/web/src/features/blobstorage-integration/types.ts b/web/src/features/blobstorage-integration/types.ts
index a4ac28c375..c1c71ab0e8 100644
--- a/web/src/features/blobstorage-integration/types.ts
+++ b/web/src/features/blobstorage-integration/types.ts
@@ -1,5 +1,8 @@
import { z } from "zod";
-import { BlobStorageIntegrationType } from "@langfuse/shared";
+import {
+ BlobStorageIntegrationType,
+ BlobStorageIntegrationFileType,
+} from "@langfuse/shared";
export const blobStorageIntegrationFormSchema = z.object({
type: z.nativeEnum(BlobStorageIntegrationType),
@@ -11,16 +14,19 @@ export const blobStorageIntegrationFormSchema = z.object({
.string()
.min(1, { message: "Secret access key is required" })
.nullable(), // Only required on create
- prefix: z.string()
- .refine(
- (value) => !value || value === "" || value.endsWith("/"),
- { message: "Prefix must end with a forward slash (/)" }
- )
+ prefix: z
+ .string()
+ .refine((value) => !value || value === "" || value.endsWith("/"), {
+ message: "Prefix must end with a forward slash (/)",
+ })
.optional()
.or(z.literal("")),
exportFrequency: z.enum(["hourly", "daily", "weekly"]),
enabled: z.boolean(),
forcePathStyle: z.boolean(),
+ fileType: z
+ .nativeEnum(BlobStorageIntegrationFileType)
+ .default(BlobStorageIntegrationFileType.JSONL),
});
export type BlobStorageIntegrationFormSchema = z.infer<
diff --git a/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx b/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx
index 32452d83d5..6ce2f1e79d 100644
--- a/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx
+++ b/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx
@@ -37,6 +37,7 @@ import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import {
BlobStorageIntegrationType,
+ BlobStorageIntegrationFileType,
type BlobStorageIntegration,
} from "@langfuse/shared";
@@ -150,6 +151,7 @@ const BlobStorageIntegrationSettingsForm = ({
| "hourly",
enabled: state?.enabled || false,
forcePathStyle: state?.forcePathStyle || false,
+ fileType: state?.fileType || BlobStorageIntegrationFileType.JSONL,
},
disabled: isLoading,
});
@@ -169,6 +171,7 @@ const BlobStorageIntegrationSettingsForm = ({
| "hourly",
enabled: state?.enabled || false,
forcePathStyle: state?.forcePathStyle || false,
+ fileType: state?.fileType || BlobStorageIntegrationFileType.JSONL,
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [state]);
@@ -438,6 +441,35 @@ const BlobStorageIntegrationSettingsForm = ({
)}
/>
+ <FormField
+ control={blobStorageForm.control}
+ name="fileType"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>File Type</FormLabel>
+ <FormControl>
+ <Select
+ defaultValue={field.value}
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Select file type" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="JSONL">JSONL</SelectItem>
+ <SelectItem value="CSV">CSV</SelectItem>
+ <SelectItem value="JSON">JSON</SelectItem>
+ </SelectContent>
+ </Select>
+ </FormControl>
+ <FormDescription>
+ The file format for exported data.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
<FormField
control={blobStorageForm.control}
name="enabled"
diff --git a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts
index 8bb4484024..d7d7a1ca10 100644
--- a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts
+++ b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts
@@ -15,7 +15,10 @@ import {
import { prisma } from "@langfuse/shared/src/db";
import { Job } from "bullmq";
import { handleBlobStorageIntegrationProjectJob } from "../ee/integrations/blobstorage/handleBlobStorageIntegrationProjectJob";
-import { BlobStorageIntegrationType } from "@langfuse/shared";
+import {
+ BlobStorageIntegrationType,
+ BlobStorageIntegrationFileType,
+} from "@langfuse/shared";
import { encrypt } from "@langfuse/shared/encryption";
describe("BlobStorageIntegrationProcessingJob", () => {
@@ -300,4 +303,140 @@ describe("BlobStorageIntegrationProcessingJob", () => {
// All files should have the prefix
expect(projectFiles.every((f) => f.file.startsWith(prefix))).toBe(true);
});
+
+ it("should handle CSV, JSON, and JSONL file types correctly", async () => {
+ // Setup
+ const { projectId } = await createOrgProjectAndApiKey();
+ const now = new Date();
+ const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);
+
+ // Create test data
+ const traceId = randomUUID();
+ const observationId = randomUUID();
+ const scoreId = randomUUID();
+
+ await Promise.all([
+ createTracesCh([
+ createTrace({
+ id: traceId,
+ project_id: projectId,
+ timestamp: now.getTime() - 40 * 60 * 1000, // 40 min before now
+ name: "Test Trace",
+ }),
+ ]),
+ createObservationsCh([
+ createObservation({
+ id: observationId,
+ trace_id: traceId,
+ project_id: projectId,
+ start_time: now.getTime() - 35 * 60 * 1000, // 35 minutes before now
+ name: "Test Observation",
+ }),
+ ]),
+ createScoresCh([
+ createScore({
+ id: scoreId,
+ trace_id: traceId,
+ project_id: projectId,
+ timestamp: now.getTime() - 35 * 60 * 1000, // 35 minutes before now
+ name: "Test Score",
+ value: 0.95,
+ }),
+ ]),
+ ]);
+
+ // Test each file type
+ for (const fileType of [
+ BlobStorageIntegrationFileType.CSV,
+ BlobStorageIntegrationFileType.JSON,
+ BlobStorageIntegrationFileType.JSONL,
+ ]) {
+ // Create integration with specific file type
+ await prisma.blobStorageIntegration.upsert({
+ where: { projectId },
+ update: {
+ prefix: `${fileType.toLowerCase()}-test/`,
+ fileType,
+ lastSyncAt: oneHourAgo,
+ },
+ create: {
+ projectId,
+ type: BlobStorageIntegrationType.S3,
+ bucketName,
+ prefix: `${fileType.toLowerCase()}-test/`,
+ accessKeyId,
+ secretAccessKey: encrypt(secretAccessKey),
+ region: region ? region : "auto",
+ endpoint: endpoint ? endpoint : null,
+ forcePathStyle:
+ env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",
+ enabled: true,
+ exportFrequency: "hourly",
+ fileType,
+ lastSyncAt: oneHourAgo,
+ },
+ });
+
+ // Process the integration
+ await handleBlobStorageIntegrationProjectJob({
+ data: { payload: { projectId } },
+ } as Job);
+
+ // Get files for this file type
+ const files = await storageService.listFiles("");
+ const projectFiles = files.filter(
+ (f) =>
+ f.file.includes(projectId) &&
+ f.file.includes(`${fileType.toLowerCase()}-test/`),
+ );
+
+ // Should have 3 files (traces, observations, scores)
+ expect(projectFiles).toHaveLength(3);
+
+ // Check file extensions
+ const expectedExtension = fileType.toLowerCase();
+ expect(
+ projectFiles.every((f) => f.file.endsWith(`.${expectedExtension}`)),
+ ).toBe(true);
+
+ // Check file contents for each type
+ for (const file of projectFiles) {
+ const content = await storageService.download(file.file);
+
+ // Verify content based on file type
+ if (file.file.includes("/traces/")) {
+ expect(content).toContain(traceId);
+ expect(content).toContain("Test Trace");
+ } else if (file.file.includes("/observations/")) {
+ expect(content).toContain(observationId);
+ expect(content).toContain("Test Observation");
+ } else if (file.file.includes("/scores/")) {
+ expect(content).toContain(scoreId);
+ expect(content).toContain("Test Score");
+ expect(content).toContain("0.95");
+ }
+
+ // Verify format based on file type
+ switch (fileType) {
+ case BlobStorageIntegrationFileType.CSV:
+ // CSV should have commas and newlines
+ expect(content).toContain(",");
+ break;
+ case BlobStorageIntegrationFileType.JSON:
+ // JSON should be parseable and have array brackets
+ expect(content.trim().startsWith("[")).toBe(true);
+ expect(content.trim().endsWith("]")).toBe(true);
+ expect(() => JSON.parse(content)).not.toThrow();
+ break;
+ case BlobStorageIntegrationFileType.JSONL:
+ // JSONL should have newlines and each line should be parseable JSON
+ const lines = content.trim().split("\n");
+ expect(lines.length).toBeGreaterThan(0);
+ // Check first line is valid JSON
+ expect(() => JSON.parse(lines[0])).not.toThrow();
+ break;
+ }
+ }
+ }
+ });
});
diff --git a/worker/src/ee/integrations/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/ee/integrations/blobstorage/handleBlobStorageIntegrationProjectJob.ts
index 249843521d..01d91eb187 100644
--- a/worker/src/ee/integrations/blobstorage/handleBlobStorageIntegrationProjectJob.ts
+++ b/worker/src/ee/integrations/blobstorage/handleBlobStorageIntegrationProjectJob.ts
@@ -12,9 +12,36 @@ import {
getTracesForBlobStorageExport,
getScoresForBlobStorageExport,
} from "@langfuse/shared/src/server";
-import { BlobStorageIntegrationType } from "@langfuse/shared";
+import {
+ BlobStorageIntegrationType,
+ BlobStorageIntegrationFileType,
+} from "@langfuse/shared";
import { decrypt } from "@langfuse/shared/encryption";
+const getFileTypeProperties = (fileType: BlobStorageIntegrationFileType) => {
+ switch (fileType) {
+ case BlobStorageIntegrationFileType.JSON:
+ return {
+ contentType: "application/json",
+ extension: "json",
+ };
+ case BlobStorageIntegrationFileType.CSV:
+ return {
+ contentType: "text/csv",
+ extension: "csv",
+ };
+ case BlobStorageIntegrationFileType.JSONL:
+ return {
+ contentType: "application/x-ndjson",
+ extension: "jsonl",
+ };
+ default:
+ // eslint-disable-next-line no-case-declarations, no-unused-vars
+ const exhaustiveCheck: never = fileType;
+ throw new Error(`Unsupported file type: ${fileType}`);
+ }
+};
+
const processBlobStorageExport = async (config: {
projectId: string;
minTimestamp: Date;
@@ -28,6 +55,7 @@ const processBlobStorageExport = async (config: {
forcePathStyle?: boolean;
type: BlobStorageIntegrationType;
table: "traces" | "observations" | "scores";
+ fileType: BlobStorageIntegrationFileType;
}) => {
logger.info(
`Processing ${config.table} export for project ${config.projectId}`,
@@ -45,12 +73,14 @@ const processBlobStorageExport = async (config: {
});
try {
+ const blobStorageProps = getFileTypeProperties(config.fileType);
+
// Create the file path with prefix if available
const timestamp = config.maxTimestamp
.toISOString()
.replace(/:/g, "-")
.substring(0, 19);
- const filePath = `${config.prefix ?? ""}${config.projectId}/${config.table}/${timestamp}.csv`;
+ const filePath = `${config.prefix ?? ""}${config.projectId}/${config.table}/${timestamp}.${blobStorageProps.extension}`;
// Fetch data based on table type
let dataStream: AsyncGenerator<Record<string, unknown>>;
@@ -83,7 +113,7 @@ const processBlobStorageExport = async (config: {
const fileStream = pipeline(
dataStream,
- streamTransformations["CSV"](),
+ streamTransformations[config.fileType](),
(err) => {
if (err) {
logger.error(
@@ -97,7 +127,7 @@ const processBlobStorageExport = async (config: {
// Upload the file to cloud storage
await storageService.uploadFile({
fileName: filePath,
- fileType: "text/csv",
+ fileType: blobStorageProps.contentType,
data: fileStream,
expiresInSeconds: 3600, // 1 hour expiry for the signed URL - is ignored
});
@@ -158,6 +188,7 @@ export const handleBlobStorageIntegrationProjectJob = async (
prefix: blobStorageIntegration.prefix || undefined,
forcePathStyle: blobStorageIntegration.forcePathStyle || undefined,
type: blobStorageIntegration.type,
+ fileType: blobStorageIntegration.fileType,
};
await Promise.all([