Skip to content

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

feat: add Mixpanel integration (#10013)

Marc Klingen3c67b58cd93a
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index cef871c5ac..93c3ea3c78 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -620,6 +620,14 @@ export type MembershipInvitation = {
created_at: Generated<Timestamp>;
updated_at: Generated<Timestamp>;
};
+export type MixpanelIntegration = {
+ project_id: string;
+ encrypted_mixpanel_project_token: string;
+ mixpanel_region: string;
+ last_sync_at: Timestamp | null;
+ enabled: boolean;
+ created_at: Generated<Timestamp>;
+};
export type Model = {
id: string;
created_at: Generated<Timestamp>;
@@ -880,6 +888,7 @@ export type DB = {
llm_tools: LlmTool;
media: Media;
membership_invitations: MembershipInvitation;
+ mixpanel_integrations: MixpanelIntegration;
models: Model;
observation_media: ObservationMedia;
observations: LegacyPrismaObservation;
diff --git a/packages/shared/prisma/migrations/20251024193002_add_mixpanel_integration/migration.sql b/packages/shared/prisma/migrations/20251024193002_add_mixpanel_integration/migration.sql
new file mode 100644
index 0000000000..1bcc04718d
--- /dev/null
+++ b/packages/shared/prisma/migrations/20251024193002_add_mixpanel_integration/migration.sql
@@ -0,0 +1,14 @@
+-- CreateTable
+CREATE TABLE "mixpanel_integrations" (
+ "project_id" TEXT NOT NULL,
+ "encrypted_mixpanel_project_token" TEXT NOT NULL,
+ "mixpanel_region" TEXT NOT NULL,
+ "last_sync_at" TIMESTAMP(3),
+ "enabled" BOOLEAN NOT NULL,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "mixpanel_integrations_pkey" PRIMARY KEY ("project_id")
+);
+
+-- AddForeignKey
+ALTER TABLE "mixpanel_integrations" ADD CONSTRAINT "mixpanel_integrations_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 2851c7d7bc..9bda8e2308 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -104,23 +104,23 @@ model VerificationToken {
}
model Organization {
- id String @id @default(cuid())
- name String
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- cloudConfig Json? @map("cloud_config") // Langfuse Cloud, for zod schema see @/src/features/organizations/utils/cloudConfigSchema
- metadata Json?
+ id String @id @default(cuid())
+ name String
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ cloudConfig Json? @map("cloud_config") // Langfuse Cloud, for zod schema see @/src/features/organizations/utils/cloudConfigSchema
+ metadata Json?
cloudBillingCycleAnchor DateTime? @default(now()) @map("cloud_billing_cycle_anchor")
cloudBillingCycleUpdatedAt DateTime? @map("cloud_billing_cycle_updated_at")
cloudCurrentCycleUsage Int? @map("cloud_current_cycle_usage")
cloudFreeTierUsageThresholdState String? @map("cloud_free_tier_usage_threshold_state")
- aiFeaturesEnabled Boolean @default(false) @map("ai_features_enabled")
- organizationMemberships OrganizationMembership[]
- projects Project[]
- MembershipInvitation MembershipInvitation[]
- ApiKey ApiKey[]
- surveys Survey[]
- cloudSpendAlerts CloudSpendAlert[]
+ aiFeaturesEnabled Boolean @default(false) @map("ai_features_enabled")
+ organizationMemberships OrganizationMembership[]
+ projects Project[]
+ MembershipInvitation MembershipInvitation[]
+ ApiKey ApiKey[]
+ surveys Survey[]
+ cloudSpendAlerts CloudSpendAlert[]
@@map("organizations")
}
@@ -147,6 +147,7 @@ model Project {
JobExecution JobExecution[]
LlmApiKeys LlmApiKeys[]
PosthogIntegration PosthogIntegration[]
+ MixpanelIntegration MixpanelIntegration[]
BlobStorageIntegration BlobStorageIntegration[]
scoreConfig ScoreConfig[]
BatchExport BatchExport[]
@@ -989,6 +990,18 @@ model PosthogIntegration {
@@map("posthog_integrations")
}
+model MixpanelIntegration {
+ projectId String @id @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ encryptedMixpanelProjectToken String @map("encrypted_mixpanel_project_token")
+ mixpanelRegion String @map("mixpanel_region")
+ lastSyncAt DateTime? @map("last_sync_at")
+ enabled Boolean
+ createdAt DateTime @default(now()) @map("created_at")
+
+ @@map("mixpanel_integrations")
+}
+
model BlobStorageIntegration {
projectId String @id @map("project_id")
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
@@ -1439,17 +1452,17 @@ enum SurveyName {
}
model CloudSpendAlert {
- id String @id @default(cuid())
- orgId String @map("org_id")
- org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
-
- title String // e.g., "Production Alert"
- threshold Decimal @map("threshold") // USD amount
-
+ id String @id @default(cuid())
+ orgId String @map("org_id")
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
+
+ title String // e.g., "Production Alert"
+ threshold Decimal @map("threshold") // USD amount
+
triggeredAt DateTime? @map("triggered_at") // Last trigger timestamp
-
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
@@index([orgId])
@@map("cloud_spend_alerts")
diff --git a/packages/shared/src/server/analytics-integrations/types.ts b/packages/shared/src/server/analytics-integrations/types.ts
new file mode 100644
index 0000000000..6a0b6204e3
--- /dev/null
+++ b/packages/shared/src/server/analytics-integrations/types.ts
@@ -0,0 +1,76 @@
+// Standard analytics event types for analytics integrations (PostHog, Mixpanel, etc.)
+// These represent the raw data structure from ClickHouse queries
+
+export type AnalyticsTraceEvent = {
+ langfuse_id: unknown;
+ timestamp: unknown;
+ langfuse_trace_name?: unknown;
+ langfuse_url?: unknown;
+ langfuse_user_url?: unknown;
+ langfuse_cost_usd?: unknown;
+ langfuse_count_observations?: unknown;
+ langfuse_session_id?: unknown;
+ langfuse_project_id?: unknown;
+ langfuse_user_id?: unknown;
+ langfuse_latency?: unknown;
+ langfuse_release?: unknown;
+ langfuse_version?: unknown;
+ langfuse_tags?: unknown;
+ langfuse_environment?: unknown;
+ langfuse_event_version?: unknown;
+ posthog_session_id?: unknown;
+ mixpanel_session_id?: unknown;
+};
+
+export type AnalyticsGenerationEvent = {
+ langfuse_id: unknown;
+ timestamp: unknown;
+ langfuse_generation_name?: unknown;
+ langfuse_trace_name?: unknown;
+ langfuse_trace_id?: unknown;
+ langfuse_url?: unknown;
+ langfuse_user_url?: unknown;
+ langfuse_cost_usd?: unknown;
+ langfuse_input_units?: unknown;
+ langfuse_output_units?: unknown;
+ langfuse_total_units?: unknown;
+ langfuse_session_id?: unknown;
+ langfuse_project_id?: unknown;
+ langfuse_user_id?: unknown;
+ langfuse_latency?: unknown;
+ langfuse_time_to_first_token?: unknown;
+ langfuse_release?: unknown;
+ langfuse_version?: unknown;
+ langfuse_model?: unknown;
+ langfuse_level?: unknown;
+ langfuse_tags?: unknown;
+ langfuse_environment?: unknown;
+ langfuse_event_version?: unknown;
+ posthog_session_id?: unknown;
+ mixpanel_session_id?: unknown;
+};
+
+export type AnalyticsScoreEvent = {
+ langfuse_id: unknown;
+ timestamp: unknown;
+ langfuse_score_name?: unknown;
+ langfuse_score_value?: unknown;
+ langfuse_score_comment?: unknown;
+ langfuse_score_metadata?: unknown;
+ langfuse_score_string_value?: unknown;
+ langfuse_score_data_type?: unknown;
+ langfuse_trace_name?: unknown;
+ langfuse_trace_id?: unknown;
+ langfuse_user_url?: unknown;
+ langfuse_session_id?: unknown;
+ langfuse_project_id?: unknown;
+ langfuse_user_id?: unknown;
+ langfuse_release?: unknown;
+ langfuse_tags?: unknown;
+ langfuse_environment?: unknown;
+ langfuse_event_version?: unknown;
+ langfuse_score_entity_type?: unknown;
+ langfuse_dataset_run_id?: unknown;
+ posthog_session_id?: unknown;
+ mixpanel_session_id?: unknown;
+};
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index d980f0b53d..a83f174461 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -51,6 +51,8 @@ export * from "./redis/batchActionQueue";
export * from "./redis/ingestionQueue";
export * from "./redis/postHogIntegrationQueue";
export * from "./redis/postHogIntegrationProcessingQueue";
+export * from "./redis/mixpanelIntegrationQueue";
+export * from "./redis/mixpanelIntegrationProcessingQueue";
export * from "./redis/blobStorageIntegrationQueue";
export * from "./redis/blobStorageIntegrationProcessingQueue";
export * from "./redis/dataRetentionQueue";
@@ -94,3 +96,4 @@ export * from "./dataset-run-items/addToDeleteQueue";
export * from "./test-utils";
export * from "./utils/headerUtils";
export * from "./traceDeletionProcessor";
+export * from "./analytics-integrations/types";
diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.ts
index 0578caf029..fa80b7394c 100644
--- a/packages/shared/src/server/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -92,6 +92,9 @@ export const EvalExecutionEvent = z.object({
export const PostHogIntegrationProcessingEventSchema = z.object({
projectId: z.string(),
});
+export const MixpanelIntegrationProcessingEventSchema = z.object({
+ projectId: z.string(),
+});
export const BlobStorageIntegrationProcessingEventSchema = z.object({
projectId: z.string(),
});
@@ -231,6 +234,9 @@ export type ExperimentCreateEventType = z.infer<
export type PostHogIntegrationProcessingEventType = z.infer<
typeof PostHogIntegrationProcessingEventSchema
>;
+export type MixpanelIntegrationProcessingEventType = z.infer<
+ typeof MixpanelIntegrationProcessingEventSchema
+>;
export type DataRetentionProcessingEventType = z.infer<
typeof DataRetentionProcessingEventSchema
>;
@@ -267,6 +273,8 @@ export enum QueueName {
ExperimentCreate = "experiment-create-queue",
PostHogIntegrationQueue = "posthog-integration-queue",
PostHogIntegrationProcessingQueue = "posthog-integration-processing-queue",
+ MixpanelIntegrationQueue = "mixpanel-integration-queue",
+ MixpanelIntegrationProcessingQueue = "mixpanel-integration-processing-queue",
BlobStorageIntegrationQueue = "blobstorage-integration-queue",
BlobStorageIntegrationProcessingQueue = "blobstorage-integration-processing-queue",
CoreDataS3ExportQueue = "core-data-s3-export-queue",
@@ -299,6 +307,8 @@ export enum QueueJobs {
ExperimentCreateJob = "experiment-create-job",
PostHogIntegrationJob = "posthog-integration-job",
PostHogIntegrationProcessingJob = "posthog-integration-processing-job",
+ MixpanelIntegrationJob = "mixpanel-integration-job",
+ MixpanelIntegrationProcessingJob = "mixpanel-integration-processing-job",
BlobStorageIntegrationJob = "blobstorage-integration-job",
BlobStorageIntegrationProcessingJob = "blobstorage-integration-processing-job",
CoreDataS3ExportJob = "core-data-s3-export-job",
@@ -396,6 +406,12 @@ export type TQueueJobTypes = {
payload: PostHogIntegrationProcessingEventType;
name: QueueJobs.PostHogIntegrationProcessingJob;
};
+ [QueueName.MixpanelIntegrationProcessingQueue]: {
+ timestamp: Date;
+ id: string;
+ payload: MixpanelIntegrationProcessingEventType;
+ name: QueueJobs.MixpanelIntegrationProcessingJob;
+ };
[QueueName.DataRetentionProcessingQueue]: {
timestamp: Date;
id: string;
diff --git a/packages/shared/src/server/redis/getQueue.ts b/packages/shared/src/server/redis/getQueue.ts
index b1de885136..13ed395eb0 100644
--- a/packages/shared/src/server/redis/getQueue.ts
+++ b/packages/shared/src/server/redis/getQueue.ts
@@ -12,6 +12,8 @@ import { TraceDeleteQueue } from "./traceDelete";
import { ProjectDeleteQueue } from "./projectDelete";
import { PostHogIntegrationQueue } from "./postHogIntegrationQueue";
import { PostHogIntegrationProcessingQueue } from "./postHogIntegrationProcessingQueue";
+import { MixpanelIntegrationQueue } from "./mixpanelIntegrationQueue";
+import { MixpanelIntegrationProcessingQueue } from "./mixpanelIntegrationProcessingQueue";
import { BlobStorageIntegrationQueue } from "./blobStorageIntegrationQueue";
import { BlobStorageIntegrationProcessingQueue } from "./blobStorageIntegrationProcessingQueue";
import { CoreDataS3ExportQueue } from "./coreDataS3ExportQueue";
@@ -62,6 +64,10 @@ export function getQueue(
return PostHogIntegrationQueue.getInstance();
case QueueName.PostHogIntegrationProcessingQueue:
return PostHogIntegrationProcessingQueue.getInstance();
+ case QueueName.MixpanelIntegrationQueue:
+ return MixpanelIntegrationQueue.getInstance();
+ case QueueName.MixpanelIntegrationProcessingQueue:
+ return MixpanelIntegrationProcessingQueue.getInstance();
case QueueName.BlobStorageIntegrationQueue:
return BlobStorageIntegrationQueue.getInstance();
case QueueName.BlobStorageIntegrationProcessingQueue:
diff --git a/packages/shared/src/server/redis/mixpanelIntegrationProcessingQueue.ts b/packages/shared/src/server/redis/mixpanelIntegrationProcessingQueue.ts
new file mode 100644
index 0000000000..101181afeb
--- /dev/null
+++ b/packages/shared/src/server/redis/mixpanelIntegrationProcessingQueue.ts
@@ -0,0 +1,45 @@
+import { Queue } from "bullmq";
+import { QueueName } from "../queues";
+import {
+ createNewRedisInstance,
+ redisQueueRetryOptions,
+ getQueuePrefix,
+} from "./redis";
+import { logger } from "../logger";
+
+export class MixpanelIntegrationProcessingQueue {
+ private static instance: Queue | null = null;
+
+ public static getInstance(): Queue | null {
+ if (MixpanelIntegrationProcessingQueue.instance) {
+ return MixpanelIntegrationProcessingQueue.instance;
+ }
+
+ const newRedis = createNewRedisInstance({
+ enableOfflineQueue: false,
+ ...redisQueueRetryOptions,
+ });
+
+ MixpanelIntegrationProcessingQueue.instance = newRedis
+ ? new Queue(QueueName.MixpanelIntegrationProcessingQueue, {
+ connection: newRedis,
+ prefix: getQueuePrefix(QueueName.MixpanelIntegrationProcessingQueue),
+ defaultJobOptions: {
+ removeOnComplete: true,
+ removeOnFail: 100_000,
+ attempts: 5,
+ backoff: {
+ type: "exponential",
+ delay: 5000,
+ },
+ },
+ })
+ : null;
+
+ MixpanelIntegrationProcessingQueue.instance?.on("error", (err) => {
+ logger.error("MixpanelIntegrationProcessingQueue error", err);
+ });
+
+ return MixpanelIntegrationProcessingQueue.instance;
+ }
+}
diff --git a/packages/shared/src/server/redis/mixpanelIntegrationQueue.ts b/packages/shared/src/server/redis/mixpanelIntegrationQueue.ts
new file mode 100644
index 0000000000..1a546d95cd
--- /dev/null
+++ b/packages/shared/src/server/redis/mixpanelIntegrationQueue.ts
@@ -0,0 +1,60 @@
+import { Queue } from "bullmq";
+import { QueueName, QueueJobs } from "../queues";
+import {
+ createNewRedisInstance,
+ redisQueueRetryOptions,
+ getQueuePrefix,
+} from "./redis";
+import { logger } from "../logger";
+
+export class MixpanelIntegrationQueue {
+ private static instance: Queue | null = null;
+
+ public static getInstance(): Queue | null {
+ if (MixpanelIntegrationQueue.instance) {
+ return MixpanelIntegrationQueue.instance;
+ }
+
+ const newRedis = createNewRedisInstance({
+ enableOfflineQueue: false,
+ ...redisQueueRetryOptions,
+ });
+
+ MixpanelIntegrationQueue.instance = newRedis
+ ? new Queue(QueueName.MixpanelIntegrationQueue, {
+ connection: newRedis,
+ prefix: getQueuePrefix(QueueName.MixpanelIntegrationQueue),
+ defaultJobOptions: {
+ removeOnComplete: true,
+ removeOnFail: 100,
+ attempts: 5,
+ backoff: {
+ type: "exponential",
+ delay: 5000,
+ },
+ },
+ })
+ : null;
+
+ MixpanelIntegrationQueue.instance?.on("error", (err) => {
+ logger.error("MixpanelIntegrationQueue error", err);
+ });
+
+ if (MixpanelIntegrationQueue.instance) {
+ logger.debug("Scheduling jobs for MixpanelIntegrationQueue");
+ MixpanelIntegrationQueue.instance
+ .add(
+ QueueJobs.MixpanelIntegrationJob,
+ {},
+ {
+ repeat: { pattern: "30 * * * *" }, // every hour at 30 minutes past
+ },
+ )
+ .catch((err) => {
+ logger.error("Error adding MixpanelIntegrationJob schedule", err);
+ });
+ }
+
+ return MixpanelIntegrationQueue.instance;
+ }
+}
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index b5ad80703e..17ea9c75fa 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -41,6 +41,7 @@ import {
import { env } from "../../env";
import { TracingSearchType } from "../../interfaces/search";
import { ClickHouseClientConfigOptions } from "@clickhouse/client";
+import type { AnalyticsGenerationEvent } from "../analytics-integrations/types";
import { ObservationType } from "../../domain";
import { recordDistribution } from "../instrumentation";
import { DEFAULT_RENDERING_PROPS, RenderingProps } from "../utils/rendering";
@@ -1511,7 +1512,7 @@ export const getObservationsForBlobStorageExport = function (
return records;
};
-export const getGenerationsForPostHog = async function* (
+export const getGenerationsForAnalyticsIntegrations = async function* (
projectId: string,
minTimestamp: Date,
maxTimestamp: Date,
@@ -1540,7 +1541,8 @@ export const getGenerationsForPostHog = async function* (
t.user_id as trace_user_id,
t.release as trace_release,
t.tags as trace_tags,
- t.metadata['$posthog_session_id'] as posthog_session_id
+ t.metadata['$posthog_session_id'] as posthog_session_id,
+ t.metadata['$mixpanel_session_id'] as mixpanel_session_id
FROM observations o FINAL
LEFT JOIN ${traceTable} t FINAL ON o.trace_id = t.id AND o.project_id = t.project_id
WHERE o.project_id = {projectId: String}
@@ -1582,6 +1584,9 @@ export const getGenerationsForPostHog = async function* (
langfuse_trace_name: record.trace_name,
langfuse_trace_id: record.trace_id,
langfuse_url: `${baseUrl}/project/${projectId}/traces/${encodeURIComponent(record.trace_id as string)}?observation=${encodeURIComponent(record.id as string)}`,
+ langfuse_user_url: record.trace_user_id
+ ? `${baseUrl}/project/${projectId}/users/${encodeURIComponent(record.trace_user_id as string)}`
+ : undefined,
langfuse_id: record.id,
langfuse_cost_usd: record.total_cost,
langfuse_input_units: record.input_tokens,
@@ -1599,17 +1604,9 @@ export const getGenerationsForPostHog = async function* (
langfuse_tags: record.trace_tags,
langfuse_environment: record.environment,
langfuse_event_version: "1.0.0",
- $session_id: record.posthog_session_id ?? null,
- ...(record.trace_user_id
- ? {
- $set: {
- langfuse_user_url: `${baseUrl}/project/${projectId}/users/${encodeURIComponent(record.trace_user_id as string)}`,
- },
- }
- : // Capture as anonymous PostHog event (cheaper/faster)
- // https://posthog.com/docs/data/anonymous-vs-identified-events?tab=Backend
- { $process_person_profile: false }),
- };
+ posthog_session_id: record.posthog_session_id ?? null,
+ mixpanel_session_id: record.mixpanel_session_id ?? null,
+ } satisfies AnalyticsGenerationEvent;
}
};
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index 1fd3058f91..5feee5a6e5 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -32,6 +32,7 @@ import { ScoreRecordReadType } from "./definitions";
import { env } from "../../env";
import { _handleGetScoreById, _handleGetScoresByIds } from "./scores-utils";
import { parseMetadataCHRecordToDomain } from "../utils/metadata_conversion";
+import type { AnalyticsScoreEvent } from "../analytics-integrations/types";
import { ClickHouseClientConfigOptions } from "@clickhouse/client";
import { recordDistribution } from "../instrumentation";
import { prisma } from "../../db";
@@ -1409,7 +1410,7 @@ export const getScoresForBlobStorageExport = function (
return records;
};
-export const getScoresForPostHog = async function* (
+export const getScoresForAnalyticsIntegrations = async function* (
projectId: string,
minTimestamp: Date,
maxTimestamp: Date,
@@ -1436,7 +1437,8 @@ export const getScoresForPostHog = async function* (
t.release as trace_release,
t.tags as trace_tags,
s.metadata as metadata,
- t.metadata['$posthog_session_id'] as posthog_session_id
+ t.metadata['$posthog_session_id'] as posthog_session_id,
+ t.metadata['$mixpanel_session_id'] as mixpanel_session_id
FROM scores s FINAL
LEFT JOIN ${traceTable} t FINAL ON s.trace_id = t.id AND s.project_id = t.project_id
WHERE s.project_id = {projectId: String}
@@ -1498,6 +1500,9 @@ export const getScoresForPostHog = async function* (
langfuse_score_data_type: record.data_type,
langfuse_trace_name: record.trace_name,
langfuse_trace_id: effectiveTraceId,
+ langfuse_user_url: record.trace_user_id
+ ? `${baseUrl}/project/${projectId}/users/${encodeURIComponent(record.trace_user_id as string)}`
+ : undefined,
langfuse_id: record.id,
langfuse_session_id: effectiveSessionId,
langfuse_project_id: projectId,
@@ -1514,17 +1519,9 @@ export const getScoresForPostHog = async function* (
? "dataset_run"
: "unknown",
langfuse_dataset_run_id: record.score_dataset_run_id,
- $session_id: record.posthog_session_id ?? null,
- ...(record.trace_user_id
- ? {
- $set: {
- langfuse_user_url: `${baseUrl}/project/${projectId}/users/${encodeURIComponent(record.trace_user_id as string)}`,
- },
- }
- : // Capture as anonymous PostHog event (cheaper/faster)
- // https://posthog.com/docs/data/anonymous-vs-identified-events?tab=Backend
- { $process_person_profile: false }),
- };
+ posthog_session_id: record.posthog_session_id ?? null,
+ mixpanel_session_id: record.mixpanel_session_id ?? null,
+ } satisfies AnalyticsScoreEvent;
}
};
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index 47b7ebca72..770d119161 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -31,6 +31,7 @@ import {
import { env } from "../../env";
import { ClickHouseClientConfigOptions } from "@clickhouse/client";
import { recordDistribution } from "../instrumentation";
+import type { AnalyticsTraceEvent } from "../analytics-integrations/types";
import { measureAndReturn } from "../clickhouse/measureAndReturn";
import { DEFAULT_RENDERING_PROPS, RenderingProps } from "../utils/rendering";
@@ -1236,7 +1237,7 @@ export const getTracesForBlobStorageExport = function (
});
};
-export const getTracesForPostHog = async function* (
+export const getTracesForAnalyticsIntegrations = async function* (
projectId: string,
minTimestamp: Date,
maxTimestamp: Date,
@@ -1268,6 +1269,7 @@ export const getTracesForPostHog = async function* (
t.tags as tags,
t.environment as environment,
t.metadata['$posthog_session_id'] as posthog_session_id,
+ t.metadata['$mixpanel_session_id'] as mixpanel_session_id,
o.total_cost as total_cost,
o.latency_milliseconds / 1000 as latency,
o.observation_count as observation_count
@@ -1308,6 +1310,9 @@ export const getTracesForPostHog = async function* (
langfuse_id: record.id,
langfuse_trace_name: record.name,
langfuse_url: `${baseUrl}/project/${projectId}/traces/${encodeURIComponent(record.id as string)}`,
+ langfuse_user_url: record.user_id
+ ? `${baseUrl}/project/${projectId}/users/${encodeURIComponent(record.user_id as string)}`
+ : undefined,
langfuse_cost_usd: record.total_cost,
langfuse_count_observations: record.observation_count,
langfuse_session_id: record.session_id,
@@ -1319,17 +1324,9 @@ export const getTracesForPostHog = async function* (
langfuse_tags: record.tags,
langfuse_environment: record.environment,
langfuse_event_version: "1.0.0",
- $session_id: record.posthog_session_id ?? null,
- ...(record.user_id
- ? {
- $set: {
- langfuse_user_url: `${baseUrl}/project/${projectId}/users/${encodeURIComponent(record.user_id as string)}`,
- },
- }
- : // Capture as anonymous PostHog event (cheaper/faster)
- // https://posthog.com/docs/data/anonymous-vs-identified-events?tab=Backend
- { $process_person_profile: false }),
- };
+ posthog_session_id: record.posthog_session_id ?? null,
+ mixpanel_session_id: record.mixpanel_session_id ?? null,
+ } satisfies AnalyticsTraceEvent;
}
};
diff --git a/web/src/components/MixpanelLogo.tsx b/web/src/components/MixpanelLogo.tsx
new file mode 100644
index 0000000000..1841db79a6
--- /dev/null
+++ b/web/src/components/MixpanelLogo.tsx
@@ -0,0 +1,51 @@
+// Mixpanel logo for React - adapted for currentColor, no external <style>, no extra <metadata>
+import * as React from "react";
+import { type SVGProps } from "react";
+
+export const MixpanelLogo = (props: SVGProps<SVGSVGElement>) => (
+ <svg
+ viewBox="0 0 371.61 88"
+ width="1em"
+ height="1em"
+ fill="none"
+ aria-hidden="true"
+ focusable="false"
+ {...props}
+ >
+ <path
+ d="M0,68.26h22.29v-2.37h-1.67c-3.26,0-4.04-0.89-4.04-4.14V32.36c2.27-3.85,5.33-6.32,9.18-6.32
+ c4.84,0,7.79,3.55,7.79,10.26v25.45c0,3.26-0.79,4.14-3.95,4.14h-1.78v2.37h21.8V65.9h-1.58c-3.26,0-4.04-0.89-4.04-4.14V35.21
+ c0-0.89,0-1.78-0.1-2.66c2.17-3.95,5.43-6.51,9.27-6.51c4.84,0,7.8,3.55,7.8,10.26v25.45c0,3.26-0.79,4.14-3.95,4.14h-1.78v2.37
+ h21.8V65.9h-1.48c-3.36,0-4.14-0.89-4.14-4.14V35.21c0-9.96-5.62-15.49-13.81-15.49c-6.11,0-11.44,3.36-14.3,10.06
+ c-1.67-6.51-6.61-10.06-13.12-10.06c-5.82,0-10.85,3.15-13.62,9.47v-8.29H0v2.37h1.97c3.36,0,4.14,0.89,4.14,4.14v34.33
+ c0,3.26-0.79,4.14-4.14,4.14H0V68.26z M90.17,13.02c3.55,0,6.51-2.96,6.51-6.51c0-3.55-2.96-6.51-6.51-6.51
+ c-3.55,0-6.51,2.96-6.51,6.51C83.66,10.06,86.62,13.02,90.17,13.02z M79.12,68.26h21.9v-2.37h-1.48c-3.26,0-4.04-0.89-4.04-4.14
+ V20.91H78.92v2.37h1.97c3.36,0,4.14,0.89,4.14,4.14v34.33c0,3.26-0.79,4.14-4.14,4.14h-1.78L79.12,68.26L79.12,68.26z M117,40.45
+ h6.31c-1.58-0.99-2.17-2.37-2.96-4.93l-2.37-8.78c-1.08-3.95-1.97-5.82-6.31-5.82h-9.07v2.37h1.29c2.66,0,2.96,0.99,3.75,3.95
+ l2.07,7.7C110.79,38.68,112.48,40.45,117,40.45L117,40.45z M131.61,40.45h6.31c4.54,0,6.11-1.78,7.2-5.52l2.07-7.7
+ c0.79-2.96,1.18-3.95,3.75-3.95h1.29v-2.37h-8.98c-4.44,0-5.33,1.78-6.32,5.82l-2.37,8.78C133.78,38.17,133.18,39.46,131.61,40.45z
+ M123.32,48.73h8.29v-8.29h-8.29V48.73z M102.6,68.27h9.07c4.34,0,5.23-1.88,6.31-5.82l2.37-8.78c0.79-2.56,1.38-3.95,2.96-4.93
+ H117c-4.54,0-6.22,1.78-7.3,5.52l-2.07,7.7c-0.79,2.96-1.08,3.95-3.75,3.95h-1.29L102.6,68.27L102.6,68.27z M143.24,68.27h8.98
+ V65.9h-1.29c-2.56,0-2.96-0.99-3.75-3.95l-2.07-7.7c-1.08-3.75-2.66-5.52-7.2-5.52h-6.3c1.58,0.99,2.15,2.27,2.94,4.93l2.37,8.78
+ C137.91,66.49,138.8,68.27,143.24,68.27L143.24,68.27z M153.5,88h22.88v-2.37h-2.37c-3.15,0-3.95-0.89-3.95-4.14V62.65
+ c2.86,4.24,7.7,6.81,13.42,6.81c10.75,0,19.33-9.47,19.33-25.84c0-14.8-8.09-23.87-18.55-23.87c-6.11,0-11.25,3.55-14.21,9.86
+ v-8.68h-16.58v2.37h1.97c3.26,0,4.14,0.89,4.14,4.14v54.05c0,3.26-0.89,4.14-4.14,4.14h-1.97v2.37L153.5,88z M180.54,25.85
+ c6.41,0,11.64,6.02,11.64,17.95c0,13.02-4.84,20.13-11.44,20.13c-4.25,0-7.99-2.27-10.66-6.22V33.24
+ C172.64,28.41,176.3,25.84,180.54,25.85L180.54,25.85z M218.42,69.26c6.41,0,11.54-3.06,15.39-9.96v1.08
+ c0,5.92,3.75,8.48,9.96,8.48c1.88,0,4.25-0.19,5.82-0.69v-2.47c-0.79,0.19-1.38,0.3-1.97,0.3c-2.47,0-3.26-1.48-3.26-3.85V36.9
+ c0-11.64-6.51-17.17-17.46-17.17c-7.3,0-14.4,3.36-18.94,6.91l1.58,2.77c4.74-3.26,9.37-5.13,14.4-5.13
+ c6.51,0,9.86,3.55,9.86,11.84v2.17l-12.14,4.74c-11.05,4.54-15.1,8.78-15.1,15.19C206.57,64.62,211.11,69.26,218.42,69.26
+ L218.42,69.26z M216.94,55.64c0-4.93,2.86-8.48,8.68-11.05l8.19-3.55v15.39c-3.06,4.24-6.61,6.71-10.46,6.71
+ C219.51,63.14,216.95,60.48,216.94,55.64L216.94,55.64z M251.56,68.27h22.5V65.9h-1.88c-3.26,0-4.04-0.89-4.04-4.14v-29.3
+ c2.27-3.95,5.62-6.41,9.57-6.41c5.13,0,8.39,3.55,8.39,10.26v25.45c0,3.26-0.79,4.14-3.95,4.14h-1.88v2.37h22.39V65.9h-1.97
+ c-3.36,0-4.14-0.89-4.14-4.14V35.21c0-9.96-5.92-15.49-14.3-15.49c-6.11,0-11.25,3.15-14.11,9.47v-8.29h-16.58v2.37h1.97
+ c3.36,0,4.14,0.89,4.14,4.14v34.33c0,3.26-0.79,4.14-4.14,4.14h-1.97L251.56,68.27L251.56,68.27z M328.31,69.45
+ c6.51,0,12.63-2.96,17.07-6.51l-1.48-2.17c-3.95,2.86-8.39,4.14-12.53,4.14c-10.06,0-15.98-7.1-15.98-20.91v-1.78h31.17
+ c-0.19-13.32-8.39-22.39-20.32-22.39c-11.93,0-21.51,10.75-21.51,24.96C304.74,60.39,313.62,69.46,328.31,69.45L328.31,69.45z
+ M326.34,22.29c5.92,0,9.57,6.41,10.16,17.26h-20.91C316.48,28.61,320.62,22.29,326.34,22.29L326.34,22.29z M348.73,68.26h22.88
+ v-2.37h-2.27c-3.26,0-4.04-0.89-4.04-4.14V1.18h-16.58v2.37h1.97c3.26,0,4.14,0.89,4.14,4.14v54.06c0,3.26-0.89,4.14-4.14,4.14
+ h-1.97L348.73,68.26L348.73,68.26z"
+ fill="currentColor"
+ />
+ </svg>
+);
diff --git a/web/src/features/audit-logs/auditLog.ts b/web/src/features/audit-logs/auditLog.ts
index 56f3110d39..0edbfd1b0f 100644
--- a/web/src/features/audit-logs/auditLog.ts
+++ b/web/src/features/audit-logs/auditLog.ts
@@ -30,6 +30,7 @@ export type AuditableResource =
| "job"
| "blobStorageIntegration"
| "posthogIntegration"
+ | "mixpanelIntegration"
| "llmApiKey"
| "llmTool"
| "llmSchema"
diff --git a/web/src/features/mixpanel-integration/mixpanel-integration-router.ts b/web/src/features/mixpanel-integration/mixpanel-integration-router.ts
new file mode 100644
index 0000000000..e1a755340a
--- /dev/null
+++ b/web/src/features/mixpanel-integration/mixpanel-integration-router.ts
@@ -0,0 +1,125 @@
+import { z } from "zod/v4";
+
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import {
+ createTRPCRouter,
+ protectedProjectProcedure,
+} from "@/src/server/api/trpc";
+import { decrypt, encrypt } from "@langfuse/shared/encryption";
+import { mixpanelIntegrationFormSchema } from "@/src/features/mixpanel-integration/types";
+import { TRPCError } from "@trpc/server";
+import { env } from "@/src/env.mjs";
+
+export const mixpanelIntegrationRouter = createTRPCRouter({
+ get: protectedProjectProcedure
+ .input(z.object({ projectId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "integrations:CRUD",
+ });
+ try {
+ const dbConfig = await ctx.prisma.mixpanelIntegration.findFirst({
+ where: {
+ projectId: input.projectId,
+ },
+ });
+
+ if (!dbConfig) {
+ return null;
+ }
+
+ const { encryptedMixpanelProjectToken, ...config } = dbConfig;
+
+ return {
+ ...config,
+ mixpanelProjectToken: decrypt(encryptedMixpanelProjectToken),
+ };
+ } catch (e) {
+ console.error("mixpanel integration get", e);
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ });
+ }
+ }),
+
+ update: protectedProjectProcedure
+ .input(mixpanelIntegrationFormSchema.extend({ projectId: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "integrations:CRUD",
+ });
+ if (!env.ENCRYPTION_KEY) {
+ if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Internal server error",
+ });
+ } else {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message:
+ "Missing environment variable: `ENCRYPTION_KEY`. Please consult our docs: https://langfuse.com/self-hosting",
+ });
+ }
+ }
+ await auditLog({
+ session: ctx.session,
+ action: "update",
+ resourceType: "mixpanelIntegration",
+ resourceId: input.projectId,
+ });
+ const { mixpanelProjectToken, ...config } = input;
+
+ const encryptedMixpanelProjectToken = encrypt(mixpanelProjectToken);
+
+ await ctx.prisma.mixpanelIntegration.upsert({
+ where: {
+ projectId: input.projectId,
+ },
+ create: {
+ projectId: input.projectId,
+ mixpanelRegion: config.mixpanelRegion,
+ encryptedMixpanelProjectToken,
+ enabled: config.enabled,
+ },
+ update: {
+ encryptedMixpanelProjectToken,
+ mixpanelRegion: config.mixpanelRegion,
+ enabled: config.enabled,
+ },
+ });
+ }),
+ delete: protectedProjectProcedure
+ .input(z.object({ projectId: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ try {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "integrations:CRUD",
+ });
+ await auditLog({
+ session: ctx.session,
+ action: "delete",
+ resourceType: "mixpanelIntegration",
+ resourceId: input.projectId,
+ });
+
+ await ctx.prisma.mixpanelIntegration.delete({
+ where: {
+ projectId: input.projectId,
+ },
+ });
+ } catch (e) {
+ console.log("mixpanel integration delete", e);
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ });
+ }
+ }),
+});
diff --git a/web/src/features/mixpanel-integration/types.ts b/web/src/features/mixpanel-integration/types.ts
new file mode 100644
index 0000000000..a0aa2a409e
--- /dev/null
+++ b/web/src/features/mixpanel-integration/types.ts
@@ -0,0 +1,30 @@
+import { z } from "zod/v4";
+
+export const MIXPANEL_REGIONS = [
+ {
+ subdomain: "api",
+ description: "US (api.mixpanel.com)",
+ },
+ {
+ subdomain: "api-eu",
+ description: "EU (api-eu.mixpanel.com)",
+ },
+ {
+ subdomain: "api-in",
+ description: "India (api-in.mixpanel.com)",
+ },
+] as const;
+
+export type MixpanelRegion = (typeof MIXPANEL_REGIONS)[number]["subdomain"];
+
+export const mixpanelIntegrationFormSchema = z.object({
+ mixpanelRegion: z.enum(MIXPANEL_REGIONS.map((r) => r.subdomain)),
+ mixpanelProjectToken: z
+ .string()
+ .min(1, "Project Token is required")
+ .refine(
+ (v) => v.length > 0,
+ "Mixpanel Project Token is required. You can find it in your Mixpanel project settings.",
+ ),
+ enabled: z.boolean(),
+});
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index ca5d868d1f..b7cbc45378 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -99,7 +99,11 @@ const events = {
"delete_form_open",
"delete_template_button_click",
],
- integrations: ["posthog_form_submitted", "blob_storage_form_submitted"],
+ integrations: [
+ "posthog_form_submitted",
+ "blob_storage_form_submitted",
+ "mixpanel_form_submitted",
+ ],
sign_in: ["cloud_region_switch", "button_click"],
auth: ["reset_password_email_requested", "update_password_form_submit"],
playground: [
diff --git a/web/src/pages/project/[projectId]/settings/index.tsx b/web/src/pages/project/[projectId]/settings/index.tsx
index b9630ff2f4..32d0b06400 100644
--- a/web/src/pages/project/[projectId]/settings/index.tsx
+++ b/web/src/pages/project/[projectId]/settings/index.tsx
@@ -12,6 +12,7 @@ import { MembershipInvitesPage } from "@/src/features/rbac/components/Membership
import { MembersTable } from "@/src/features/rbac/components/MembersTable";
import { JSONView } from "@/src/components/ui/CodeJsonViewer";
import { PostHogLogo } from "@/src/components/PosthogLogo";
+import { MixpanelLogo } from "@/src/components/MixpanelLogo";
import { Card } from "@/src/components/ui/card";
import { TransferProjectButton } from "@/src/features/projects/components/TransferProjectButton";
import { useHasEntitlement } from "@/src/features/entitlements/hooks";
@@ -197,7 +198,7 @@ export const getProjectSettingsPages = ({
{
title: "Integrations",
slug: "integrations",
- cmdKKeywords: ["posthog"],
+ cmdKKeywords: ["posthog", "mixpanel", "analytics"],
content: <Integrations projectId={project.id} />,
},
{
@@ -286,6 +287,31 @@ const Integrations = (props: { projectId: string }) => {
</div>
</Card>
+ <Card className="p-3">
+ <MixpanelLogo className="mb-4 w-20 text-foreground" />
+ <p className="mb-4 text-sm text-primary">
+ Integrate with Mixpanel to sync your Langfuse traces, generations,
+ and scores for advanced product analytics and insights.
+ </p>
+ <div className="flex items-center gap-2">
+ <ActionButton
+ variant="secondary"
+ hasAccess={hasAccess}
+ href={`/project/${props.projectId}/settings/integrations/mixpanel`}
+ >
+ Configure
+ </ActionButton>
+ <Button asChild variant="ghost">
+ <Link
+ href="https://langfuse.com/docs/integrations/mixpanel"
+ target="_blank"
+ >
+ Integration Docs ↗
+ </Link>
+ </Button>
+ </div>
+ </Card>
+
<Card className="p-3">
<span className="font-semibold">Blob Storage</span>
<p className="mb-4 text-sm text-primary">
diff --git a/web/src/pages/project/[projectId]/settings/integrations/mixpanel.tsx b/web/src/pages/project/[projectId]/settings/integrations/mixpanel.tsx
new file mode 100644
index 0000000000..b13756164d
--- /dev/null
+++ b/web/src/pages/project/[projectId]/settings/integrations/mixpanel.tsx
@@ -0,0 +1,278 @@
+import { MixpanelLogo } from "@/src/components/MixpanelLogo";
+import Header from "@/src/components/layouts/header";
+import ContainerPage from "@/src/components/layouts/container-page";
+import { StatusBadge } from "@/src/components/layouts/status-badge";
+import { Button } from "@/src/components/ui/button";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/src/components/ui/form";
+import { PasswordInput } from "@/src/components/ui/password-input";
+import { Switch } from "@/src/components/ui/switch";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/src/components/ui/select";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import {
+ mixpanelIntegrationFormSchema,
+ MIXPANEL_REGIONS,
+ type MixpanelRegion,
+} from "@/src/features/mixpanel-integration/types";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { api } from "@/src/utils/api";
+import { type RouterOutput } from "@/src/utils/types";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Card } from "@tremor/react";
+import Link from "next/link";
+import { useRouter } from "next/router";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { type z } from "zod/v4";
+
+export default function MixpanelIntegrationSettings() {
+ const router = useRouter();
+ const projectId = router.query.projectId as string;
+
+ const hasAccess = useHasProjectAccess({
+ projectId,
+ scope: "integrations:CRUD",
+ });
+ const state = api.mixpanelIntegration.get.useQuery(
+ { projectId },
+ {
+ enabled: hasAccess,
+ },
+ );
+
+ const status =
+ state.isInitialLoading || !hasAccess
+ ? undefined
+ : state.data?.enabled
+ ? "active"
+ : "inactive";
+
+ return (
+ <ContainerPage
+ headerProps={{
+ title: "Mixpanel Integration",
+ breadcrumb: [
+ { name: "Settings", href: `/project/${projectId}/settings` },
+ ],
+ actionButtonsLeft: <>{status && <StatusBadge type={status} />}</>,
+ actionButtonsRight: (
+ <Button asChild variant="secondary">
+ <Link href="https://langfuse.com/docs/integrations/mixpanel">
+ Integration Docs ↗
+ </Link>
+ </Button>
+ ),
+ }}
+ >
+ <p className="mb-4 text-sm text-primary">
+ Integrate with{" "}
+ <Link href="https://mixpanel.com" className="underline">
+ Mixpanel
+ </Link>{" "}
+ to sync your Langfuse traces, generations, and scores for advanced
+ product analytics. Upon activation, all historical data from your
+ project will be synced. After the initial sync, new data is
+ automatically synced every hour to keep your Mixpanel dashboards up to
+ date.
+ </p>
+ {!hasAccess && (
+ <p className="text-sm">
+ Your current role does not grant you access to these settings, please
+ reach out to your project admin or owner.
+ </p>
+ )}
+ {hasAccess && (
+ <>
+ <Header title="Configuration" />
+ <Card className="p-3">
+ <MixpanelLogo className="mb-4 w-20 text-foreground" />
+ <MixpanelIntegrationSettingsForm
+ state={state.data}
+ projectId={projectId}
+ isLoading={state.isLoading}
+ />
+ </Card>
+ </>
+ )}
+ {state.data?.enabled && (
+ <>
+ <Header title="Status" className="mt-8" />
+ <p className="text-sm text-primary">
+ Data synced until:{" "}
+ {state.data?.lastSyncAt
+ ? new Date(state.data.lastSyncAt).toLocaleString()
+ : "Never (pending)"}
+ </p>
+ </>
+ )}
+ </ContainerPage>
+ );
+}
+
+const MixpanelIntegrationSettingsForm = ({
+ state,
+ projectId,
+ isLoading,
+}: {
+ state?: RouterOutput["mixpanelIntegration"]["get"];
+ projectId: string;
+ isLoading: boolean;
+}) => {
+ const capture = usePostHogClientCapture();
+ const mixpanelForm = useForm({
+ resolver: zodResolver(mixpanelIntegrationFormSchema),
+ defaultValues: {
+ mixpanelRegion:
+ (state?.mixpanelRegion as MixpanelRegion) ??
+ MIXPANEL_REGIONS[0].subdomain,
+ mixpanelProjectToken: state?.mixpanelProjectToken ?? "",
+ enabled: state?.enabled ?? false,
+ },
+ disabled: isLoading,
+ });
+
+ useEffect(() => {
+ mixpanelForm.reset({
+ mixpanelRegion:
+ (state?.mixpanelRegion as MixpanelRegion) ??
+ MIXPANEL_REGIONS[0].subdomain,
+ mixpanelProjectToken: state?.mixpanelProjectToken ?? "",
+ enabled: state?.enabled ?? false,
+ });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [state]);
+
+ const utils = api.useUtils();
+ const mut = api.mixpanelIntegration.update.useMutation({
+ onSuccess: () => {
+ utils.mixpanelIntegration.invalidate();
+ },
+ });
+ const mutDelete = api.mixpanelIntegration.delete.useMutation({
+ onSuccess: () => {
+ utils.mixpanelIntegration.invalidate();
+ },
+ });
+
+ async function onSubmit(
+ values: z.infer<typeof mixpanelIntegrationFormSchema>,
+ ) {
+ capture("integrations:mixpanel_form_submitted");
+ mut.mutate({
+ projectId,
+ ...values,
+ });
+ }
+
+ return (
+ <Form {...mixpanelForm}>
+ <form
+ className="space-y-3"
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
+ onSubmit={mixpanelForm.handleSubmit(onSubmit)}
+ >
+ <FormField
+ control={mixpanelForm.control}
+ name="mixpanelRegion"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Mixpanel Region</FormLabel>
+ <Select onValueChange={field.onChange} value={field.value}>
+ <FormControl>
+ <SelectTrigger>
+ <SelectValue placeholder="Select a region" />
+ </SelectTrigger>
+ </FormControl>
+ <SelectContent>
+ {MIXPANEL_REGIONS.map((region) => (
+ <SelectItem key={region.subdomain} value={region.subdomain}>
+ {region.description}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FormDescription>
+ Select the Mixpanel region where your project is hosted
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={mixpanelForm.control}
+ name="mixpanelProjectToken"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Mixpanel Project Token</FormLabel>
+ <FormControl>
+ <PasswordInput {...field} />
+ </FormControl>
+ <FormDescription>
+ You can find your Project Token in your Mixpanel project
+ settings
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={mixpanelForm.control}
+ name="enabled"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Enabled</FormLabel>
+ <FormControl>
+ <Switch
+ id="mixpanel-integration-enabled"
+ checked={field.value}
+ onCheckedChange={() => {
+ field.onChange(!field.value);
+ }}
+ className="ml-4 mt-1"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </form>
+ <div className="mt-8 flex gap-2">
+ <Button
+ loading={mut.isPending}
+ onClick={mixpanelForm.handleSubmit(onSubmit)}
+ disabled={isLoading}
+ >
+ Save
+ </Button>
+ <Button
+ variant="ghost"
+ loading={mutDelete.isPending}
+ disabled={isLoading || !!!state}
+ onClick={() => {
+ if (
+ confirm(
+ "Are you sure you want to reset the Mixpanel integration for this project?",
+ )
+ )
+ mutDelete.mutate({ projectId });
+ }}
+ >
+ Reset
+ </Button>
+ </div>
+ </Form>
+ );
+};
diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.ts
index db3bdd6ff8..e5f8fd7713 100644
--- a/web/src/server/api/root.ts
+++ b/web/src/server/api/root.ts
@@ -17,6 +17,7 @@ import { promptRouter } from "@/src/features/prompts/server/routers/promptRouter
import { modelRouter } from "@/src/server/api/routers/models";
import { evalRouter } from "@/src/features/evals/server/router";
import { posthogIntegrationRouter } from "@/src/features/posthog-integration/posthog-integration-router";
+import { mixpanelIntegrationRouter } from "@/src/features/mixpanel-integration/mixpanel-integration-router";
import { blobStorageIntegrationRouter } from "@/src/features/blobstorage-integration/blobstorage-integration-router";
import { llmApiKeyRouter } from "@/src/features/llm-api-key/server/router";
import { llmSchemaRouter } from "@/src/features/llm-schemas/server/router";
@@ -81,6 +82,7 @@ export const appRouter = createTRPCRouter({
defaultLlmModel: defaultEvalModelRouter,
experiments: experimentsRouter,
posthogIntegration: posthogIntegrationRouter,
+ mixpanelIntegration: mixpanelIntegrationRouter,
blobStorageIntegration: blobStorageIntegrationRouter,
llmApiKey: llmApiKeyRouter,
llmSchemas: llmSchemaRouter,
diff --git a/worker/src/app.ts b/worker/src/app.ts
index 6b2bfde0e6..fe493ba2d6 100644
--- a/worker/src/app.ts
+++ b/worker/src/app.ts
@@ -26,6 +26,7 @@ import {
DataRetentionQueue,
MeteringDataPostgresExportQueue,
PostHogIntegrationQueue,
+ MixpanelIntegrationQueue,
QueueName,
logger,
BlobStorageIntegrationQueue,
@@ -48,6 +49,10 @@ import {
postHogIntegrationProcessingProcessor,
postHogIntegrationProcessor,
} from "./queues/postHogIntegrationQueue";
+import {
+ mixpanelIntegrationProcessingProcessor,
+ mixpanelIntegrationProcessor,
+} from "./queues/mixpanelIntegrationQueue";
import {
blobStorageIntegrationProcessingProcessor,
blobStorageIntegrationProcessor,
@@ -384,6 +389,32 @@ if (env.QUEUE_CONSUMER_POSTHOG_INTEGRATION_QUEUE_IS_ENABLED === "true") {
);
}
+if (env.QUEUE_CONSUMER_MIXPANEL_INTEGRATION_QUEUE_IS_ENABLED === "true") {
+ // Instantiate the queue to trigger scheduled jobs
+ MixpanelIntegrationQueue.getInstance();
+
+ WorkerManager.register(
+ QueueName.MixpanelIntegrationQueue,
+ mixpanelIntegrationProcessor,
+ {
+ concurrency: 1,
+ },
+ );
+
+ WorkerManager.register(
+ QueueName.MixpanelIntegrationProcessingQueue,
+ mixpanelIntegrationProcessingProcessor,
+ {
+ concurrency: 1,
+ limiter: {
+ // Process at most one Mixpanel job globally per 10s.
+ max: 1,
+ duration: 10_000,
+ },
+ },
+ );
+}
+
if (env.QUEUE_CONSUMER_BLOB_STORAGE_INTEGRATION_QUEUE_IS_ENABLED === "true") {
// Instantiate the queue to trigger scheduled jobs
BlobStorageIntegrationQueue.getInstance();
diff --git a/worker/src/env.ts b/worker/src/env.ts
index fdf95b445e..a08c53f3a1 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -199,6 +199,9 @@ const EnvSchema = z.object({
QUEUE_CONSUMER_POSTHOG_INTEGRATION_QUEUE_IS_ENABLED: z
.enum(["true", "false"])
.default("true"),
+ QUEUE_CONSUMER_MIXPANEL_INTEGRATION_QUEUE_IS_ENABLED: z
+ .enum(["true", "false"])
+ .default("true"),
QUEUE_CONSUMER_BLOB_STORAGE_INTEGRATION_QUEUE_IS_ENABLED: z
.enum(["true", "false"])
.default("true"),
diff --git a/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts b/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts
new file mode 100644
index 0000000000..793bcec2a6
--- /dev/null
+++ b/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts
@@ -0,0 +1,187 @@
+import { Job } from "bullmq";
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ QueueName,
+ TQueueJobTypes,
+ logger,
+ getTracesForAnalyticsIntegrations,
+ getGenerationsForAnalyticsIntegrations,
+ getScoresForAnalyticsIntegrations,
+ getCurrentSpan,
+} from "@langfuse/shared/src/server";
+import { decrypt } from "@langfuse/shared/encryption";
+import { MixpanelClient } from "./mixpanelClient";
+import {
+ transformTraceForMixpanel,
+ transformGenerationForMixpanel,
+ transformScoreForMixpanel,
+} from "./transformers";
+
+type MixpanelExecutionConfig = {
+ projectId: string;
+ minTimestamp: Date;
+ maxTimestamp: Date;
+ decryptedMixpanelProjectToken: string;
+ mixpanelRegion: string;
+};
+
+const processMixpanelTraces = async (config: MixpanelExecutionConfig) => {
+ const traces = getTracesForAnalyticsIntegrations(
+ config.projectId,
+ config.minTimestamp,
+ config.maxTimestamp,
+ );
+
+ logger.info(`Sending traces for project ${config.projectId} to Mixpanel`);
+
+ const mixpanel = new MixpanelClient({
+ projectToken: config.decryptedMixpanelProjectToken,
+ region: config.mixpanelRegion,
+ });
+
+ let count = 0;
+ for await (const trace of traces) {
+ count++;
+ const event = transformTraceForMixpanel(trace, config.projectId);
+ mixpanel.addEvent(event);
+
+ if (count % 1000 === 0) {
+ await mixpanel.flush();
+ logger.info(
+ `Sent ${count} traces to Mixpanel for project ${config.projectId}`,
+ );
+ }
+ }
+ await mixpanel.flush();
+ logger.info(
+ `Sent ${count} traces to Mixpanel for project ${config.projectId}`,
+ );
+};
+
+const processMixpanelGenerations = async (config: MixpanelExecutionConfig) => {
+ const generations = getGenerationsForAnalyticsIntegrations(
+ config.projectId,
+ config.minTimestamp,
+ config.maxTimestamp,
+ );
+
+ logger.info(
+ `Sending generations for project ${config.projectId} to Mixpanel`,
+ );
+
+ const mixpanel = new MixpanelClient({
+ projectToken: config.decryptedMixpanelProjectToken,
+ region: config.mixpanelRegion,
+ });
+
+ let count = 0;
+ for await (const generation of generations) {
+ count++;
+ const event = transformGenerationForMixpanel(generation, config.projectId);
+ mixpanel.addEvent(event);
+
+ if (count % 1000 === 0) {
+ await mixpanel.flush();
+ logger.info(
+ `Sent ${count} generations to Mixpanel for project ${config.projectId}`,
+ );
+ }
+ }
+ await mixpanel.flush();
+ logger.info(
+ `Sent ${count} generations to Mixpanel for project ${config.projectId}`,
+ );
+};
+
+const processMixpanelScores = async (config: MixpanelExecutionConfig) => {
+ const scores = getScoresForAnalyticsIntegrations(
+ config.projectId,
+ config.minTimestamp,
+ config.maxTimestamp,
+ );
+
+ logger.info(`Sending scores for project ${config.projectId} to Mixpanel`);
+
+ const mixpanel = new MixpanelClient({
+ projectToken: config.decryptedMixpanelProjectToken,
+ region: config.mixpanelRegion,
+ });
+
+ let count = 0;
+ for await (const score of scores) {
+ count++;
+ const event = transformScoreForMixpanel(score, config.projectId);
+ mixpanel.addEvent(event);
+
+ if (count % 1000 === 0) {
+ await mixpanel.flush();
+ logger.info(
+ `Sent ${count} scores to Mixpanel for project ${config.projectId}`,
+ );
+ }
+ }
+ await mixpanel.flush();
+ logger.info(
+ `Sent ${count} scores to Mixpanel for project ${config.projectId}`,
+ );
+};
+
+export const handleMixpanelIntegrationProjectJob = async (
+ job: Job<TQueueJobTypes[QueueName.MixpanelIntegrationProcessingQueue]>,
+) => {
+ const projectId = job.data.payload.projectId;
+
+ const span = getCurrentSpan();
+ if (span) {
+ span.setAttribute("messaging.bullmq.job.input.jobId", job.data.id);
+ span.setAttribute("messaging.bullmq.job.input.projectId", projectId);
+ }
+
+ logger.info(`Processing Mixpanel integration for project ${projectId}`);
+
+ // Fetch Mixpanel integration information for project
+ const mixpanelIntegration = await prisma.mixpanelIntegration.findFirst({
+ where: {
+ projectId,
+ enabled: true,
+ },
+ });
+
+ if (!mixpanelIntegration) {
+ logger.warn(
+ `Enabled Mixpanel integration not found for project ${projectId}`,
+ );
+ return;
+ }
+
+ // Fetch relevant data and send it to Mixpanel
+ const executionConfig: MixpanelExecutionConfig = {
+ projectId,
+ // Start from 2000-01-01 if no lastSyncAt. Workaround because 1970-01-01 leads to subtle bugs in ClickHouse
+ minTimestamp: mixpanelIntegration.lastSyncAt || new Date("2000-01-01"),
+ maxTimestamp: new Date(new Date().getTime() - 30 * 60 * 1000), // 30 minutes ago
+ decryptedMixpanelProjectToken: decrypt(
+ mixpanelIntegration.encryptedMixpanelProjectToken,
+ ),
+ mixpanelRegion: mixpanelIntegration.mixpanelRegion,
+ };
+
+ await Promise.all([
+ processMixpanelTraces(executionConfig),
+ processMixpanelGenerations(executionConfig),
+ processMixpanelScores(executionConfig),
+ ]);
+
+ // Update the last run information for the mixpanelIntegration record
+ await prisma.mixpanelIntegration.update({
+ where: {
+ projectId,
+ },
+ data: {
+ lastSyncAt: executionConfig.maxTimestamp,
+ },
+ });
+ logger.info(
+ `Mixpanel integration processing complete for project ${projectId}`,
+ );
+};
diff --git a/worker/src/features/mixpanel/handleMixpanelIntegrationSchedule.ts b/worker/src/features/mixpanel/handleMixpanelIntegrationSchedule.ts
new file mode 100644
index 0000000000..c68e098dac
--- /dev/null
+++ b/worker/src/features/mixpanel/handleMixpanelIntegrationSchedule.ts
@@ -0,0 +1,46 @@
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ MixpanelIntegrationProcessingQueue,
+ QueueJobs,
+} from "@langfuse/shared/src/server";
+import { randomUUID } from "crypto";
+
+export const handleMixpanelIntegrationSchedule = async () => {
+ const mixpanelIntegrationProjects = await prisma.mixpanelIntegration.findMany(
+ {
+ select: {
+ lastSyncAt: true,
+ projectId: true,
+ },
+ where: {
+ enabled: true,
+ },
+ },
+ );
+
+ const mixpanelIntegrationProcessingQueue =
+ MixpanelIntegrationProcessingQueue.getInstance();
+ if (!mixpanelIntegrationProcessingQueue) {
+ throw new Error("MixpanelIntegrationProcessingQueue not initialized");
+ }
+
+ await mixpanelIntegrationProcessingQueue.addBulk(
+ mixpanelIntegrationProjects.map(
+ (integration: { projectId: string; lastSyncAt: Date | null }) => ({
+ name: QueueJobs.MixpanelIntegrationProcessingJob,
+ data: {
+ id: randomUUID(),
+ name: QueueJobs.MixpanelIntegrationProcessingJob,
+ timestamp: new Date(),
+ payload: {
+ projectId: integration.projectId,
+ },
+ },
+ opts: {
+ // Use projectId and last sync as jobId to prevent duplicate jobs.
+ jobId: `${integration.projectId}-${integration.lastSyncAt?.toISOString() ?? ""}`,
+ },
+ }),
+ ),
+ );
+};
diff --git a/worker/src/features/mixpanel/mixpanelClient.ts b/worker/src/features/mixpanel/mixpanelClient.ts
new file mode 100644
index 0000000000..f5aae4408c
--- /dev/null
+++ b/worker/src/features/mixpanel/mixpanelClient.ts
@@ -0,0 +1,104 @@
+import { logger } from "@langfuse/shared/src/server";
+import { gzipSync } from "zlib";
+import type { MixpanelEvent } from "./transformers";
+
+type MixpanelClientConfig = {
+ projectToken: string;
+ /**
+ * Mixpanel region subdomain (e.g., "api", "api-eu", "api-in")
+ * Validated at API layer via MIXPANEL_REGIONS in web/src/features/mixpanel-integration/types.ts
+ */
+ region: string;
+};
+
+export class MixpanelClient {
+ private config: MixpanelClientConfig;
+ private batch: MixpanelEvent[] = [];
+ private batchSize = 1000; // Similar to PostHog's flushAt setting
+
+ constructor(config: MixpanelClientConfig) {
+ this.config = config;
+ }
+
+ /**
+ * Add an event to the batch
+ */
+ public addEvent(event: MixpanelEvent): void {
+ this.batch.push(event);
+ }
+
+ /**
+ * Send all batched events to Mixpanel
+ */
+ public async flush(): Promise<void> {
+ if (this.batch.length === 0) {
+ return;
+ }
+
+ // Send events in chunks of batchSize (max 2000 per Mixpanel API limits, we use 1000 for consistency with PostHog)
+ const chunks: MixpanelEvent[][] = [];
+ for (let i = 0; i < this.batch.length; i += this.batchSize) {
+ chunks.push(this.batch.slice(i, i + this.batchSize));
+ }
+
+ for (const chunk of chunks) {
+ await this.sendBatch(chunk);
+ }
+
+ // Clear the batch after sending
+ this.batch = [];
+ }
+
+ /**
+ * Send a batch of events to Mixpanel Import API
+ */
+ private async sendBatch(events: MixpanelEvent[]): Promise<void> {
+ const url = `https://${this.config.region}.mixpanel.com/import?strict=1`;
+ const body = JSON.stringify(events);
+
+ // Compress the body with gzip
+ const compressedBody = gzipSync(body);
+
+ // Create Basic Auth header (token as username, empty password)
+ const authHeader = `Basic ${Buffer.from(`${this.config.projectToken}:`).toString("base64")}`;
+
+ try {
+ const response = await fetch(url, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "Content-Encoding": "gzip",
+ Authorization: authHeader,
+ },
+ body: compressedBody as unknown as BodyInit,
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ logger.error(
+ `Failed to send events to Mixpanel: ${response.status} ${response.statusText}`,
+ { body: errorText },
+ );
+ throw new Error(
+ `Mixpanel API error: ${response.status} ${response.statusText}`,
+ );
+ }
+
+ const result = await response.json();
+ logger.debug("Successfully sent batch to Mixpanel", {
+ count: events.length,
+ result,
+ });
+ } catch (error) {
+ logger.error("Error sending batch to Mixpanel", error);
+ throw error;
+ }
+ }
+
+ /**
+ * Get the current batch size
+ */
+ public getBatchSize(): number {
+ return this.batch.length;
+ }
+}
diff --git a/worker/src/features/mixpanel/transformers.ts b/worker/src/features/mixpanel/transformers.ts
new file mode 100644
index 0000000000..895e32e8e8
--- /dev/null
+++ b/worker/src/features/mixpanel/transformers.ts
@@ -0,0 +1,123 @@
+import { v5 } from "uuid";
+import type {
+ AnalyticsTraceEvent,
+ AnalyticsGenerationEvent,
+ AnalyticsScoreEvent,
+} from "@langfuse/shared/src/server";
+
+// UUID v5 namespace for Mixpanel (different from PostHog)
+const MIXPANEL_UUID_NAMESPACE = "8f7c3e42-9a1b-4d5f-8e2a-1c6b9d3f4e7a";
+
+export type MixpanelEvent = {
+ event: string;
+ properties: {
+ time: number; // milliseconds since epoch
+ distinct_id: string;
+ $insert_id: string;
+ $user_id?: string;
+ session_id?: string;
+ [key: string]: unknown;
+ };
+};
+
+export const transformTraceForMixpanel = (
+ trace: AnalyticsTraceEvent,
+ projectId: string,
+): MixpanelEvent => {
+ const insertId = v5(
+ `${projectId}-${trace.langfuse_id}`,
+ MIXPANEL_UUID_NAMESPACE,
+ );
+
+ // Extract session IDs and exclude from properties
+ // eslint-disable-next-line no-unused-vars
+ const { posthog_session_id, mixpanel_session_id, ...otherProps } = trace;
+
+ return {
+ event: "[Langfuse] Trace",
+ properties: {
+ time: new Date(trace.timestamp as Date).getTime(),
+ distinct_id: trace.langfuse_user_id
+ ? (trace.langfuse_user_id as string)
+ : insertId,
+ $insert_id: insertId,
+ ...(trace.langfuse_user_id
+ ? { $user_id: trace.langfuse_user_id as string }
+ : {}),
+ session_id:
+ mixpanel_session_id || trace.langfuse_session_id
+ ? (mixpanel_session_id as string) ||
+ (trace.langfuse_session_id as string)
+ : undefined,
+ ...otherProps,
+ },
+ };
+};
+
+export const transformGenerationForMixpanel = (
+ generation: AnalyticsGenerationEvent,
+ projectId: string,
+): MixpanelEvent => {
+ const insertId = v5(
+ `${projectId}-${generation.langfuse_id}`,
+ MIXPANEL_UUID_NAMESPACE,
+ );
+
+ // Extract session IDs and exclude from properties
+ // eslint-disable-next-line no-unused-vars
+ const { posthog_session_id, mixpanel_session_id, ...otherProps } = generation;
+
+ return {
+ event: "[Langfuse] Generation",
+ properties: {
+ time: new Date(generation.timestamp as Date).getTime(),
+ distinct_id: generation.langfuse_user_id
+ ? (generation.langfuse_user_id as string)
+ : insertId,
+ $insert_id: insertId,
+ ...(generation.langfuse_user_id
+ ? { $user_id: generation.langfuse_user_id as string }
+ : {}),
+ session_id:
+ mixpanel_session_id || generation.langfuse_session_id
+ ? (mixpanel_session_id as string) ||
+ (generation.langfuse_session_id as string)
+ : undefined,
+ ...otherProps,
+ },
+ };
+};
+
+export const transformScoreForMixpanel = (
+ score: AnalyticsScoreEvent,
+ projectId: string,
+): MixpanelEvent => {
+ const insertId = v5(
+ `${projectId}-${score.langfuse_id}`,
+ MIXPANEL_UUID_NAMESPACE,
+ );
+
+ // Extract session IDs and exclude from properties
+ // eslint-disable-next-line no-unused-vars
+ const { posthog_session_id, mixpanel_session_id, ...otherProps } = score;
+
+ return {
+ event: "[Langfuse] Score",
+ properties: {
+ time: new Date(score.timestamp as Date).getTime(),
+ distinct_id: score.langfuse_user_id
+ ? (score.langfuse_user_id as string)
+ : insertId,
+ $insert_id: insertId,
+ ...(score.langfuse_user_id
+ ? { $user_id: score.langfuse_user_id as string }
+ : {}),
+ session_id:
+ mixpanel_session_id || score.langfuse_session_id
+ ? (mixpanel_session_id as string) ||
+ (score.langfuse_session_id as string)
+ : undefined,
+ ...otherProps,
+ },
+ };
+};
diff --git a/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts b/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts
index 05cf50acc0..08f0e20650 100644
--- a/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts
+++ b/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts
@@ -4,12 +4,16 @@ import {
QueueName,
TQueueJobTypes,
logger,
- getTracesForPostHog,
- getGenerationsForPostHog,
- getScoresForPostHog,
+ getTracesForAnalyticsIntegrations,
+ getGenerationsForAnalyticsIntegrations,
+ getScoresForAnalyticsIntegrations,
getCurrentSpan,
} from "@langfuse/shared/src/server";
-import { v5 } from "uuid";
+import {
+ transformTraceForPostHog,
+ transformGenerationForPostHog,
+ transformScoreForPostHog,
+} from "./transformers";
import { decrypt } from "@langfuse/shared/encryption";
import { PostHog } from "posthog-node";
@@ -21,14 +25,12 @@ type PostHogExecutionConfig = {
postHogHost: string;
};
-const POSTHOG_UUID_NAMESPACE = "0f6c91df-d035-4813-b838-9741ba38ef0b";
-
const postHogSettings = {
flushAt: 1000,
};
const processPostHogTraces = async (config: PostHogExecutionConfig) => {
- const postHogTraces = getTracesForPostHog(
+ const traces = getTracesForAnalyticsIntegrations(
config.projectId,
config.minTimestamp,
config.maxTimestamp,
@@ -52,22 +54,10 @@ const processPostHogTraces = async (config: PostHogExecutionConfig) => {
});
let count = 0;
- for await (const trace of postHogTraces) {
+ for await (const trace of traces) {
count++;
- const uuid = v5(
- `${config.projectId}-${trace.langfuse_id}`,
- POSTHOG_UUID_NAMESPACE,
- );
- posthog.capture({
- distinctId: trace.langfuse_user_id
- ? (trace.langfuse_user_id as string)
- : // use random uuid for anonymous users to maximize posthog performance, will be ignored as we set $process_person_profile to false
- uuid,
- event: "langfuse trace",
- properties: trace,
- timestamp: trace.timestamp as Date,
- uuid,
- });
+ const event = transformTraceForPostHog(trace, config.projectId);
+ posthog.capture(event);
if (count % 10000 === 0) {
await posthog.flush();
logger.info(
@@ -82,7 +72,7 @@ const processPostHogTraces = async (config: PostHogExecutionConfig) => {
};
const processPostHogGenerations = async (config: PostHogExecutionConfig) => {
- const postHogGenerations = getGenerationsForPostHog(
+ const generations = getGenerationsForAnalyticsIntegrations(
config.projectId,
config.minTimestamp,
config.maxTimestamp,
@@ -106,22 +96,10 @@ const processPostHogGenerations = async (config: PostHogExecutionConfig) => {
});
let count = 0;
- for await (const generation of postHogGenerations) {
+ for await (const generation of generations) {
count++;
- const uuid = v5(
- `${config.projectId}-${generation.langfuse_id}`,
- POSTHOG_UUID_NAMESPACE,
- );
- posthog.capture({
- distinctId: generation.langfuse_user_id
- ? (generation.langfuse_user_id as string)
- : // use random uuid for anonymous users to maximize posthog performance, will be ignored as we set $process_person_profile to false
- uuid,
- event: "langfuse generation",
- properties: generation,
- timestamp: generation.timestamp as Date,
- uuid,
- });
+ const event = transformGenerationForPostHog(generation, config.projectId);
+ posthog.capture(event);
if (count % 10000 === 0) {
await posthog.flush();
logger.info(
@@ -136,7 +114,7 @@ const processPostHogGenerations = async (config: PostHogExecutionConfig) => {
};
const processPostHogScores = async (config: PostHogExecutionConfig) => {
- const postHogScores = getScoresForPostHog(
+ const scores = getScoresForAnalyticsIntegrations(
config.projectId,
config.minTimestamp,
config.maxTimestamp,
@@ -159,22 +137,10 @@ const processPostHogScores = async (config: PostHogExecutionConfig) => {
);
});
let count = 0;
- for await (const score of postHogScores) {
+ for await (const score of scores) {
count++;
- const uuid = v5(
- `${config.projectId}-${score.langfuse_id}`,
- POSTHOG_UUID_NAMESPACE,
- );
- posthog.capture({
- distinctId: score.langfuse_user_id
- ? (score.langfuse_user_id as string)
- : // use random uuid for anonymous users to maximize posthog performance, will be ignored as we set $process_person_profile to false
- uuid,
- event: "langfuse score",
- properties: score,
- timestamp: score.timestamp as Date,
- uuid,
- });
+ const event = transformScoreForPostHog(score, config.projectId);
+ posthog.capture(event);
if (count % 10000 === 0) {
await posthog.flush();
logger.info(
diff --git a/worker/src/features/posthog/transformers.ts b/worker/src/features/posthog/transformers.ts
new file mode 100644
index 0000000000..556bcdfda8
--- /dev/null
+++ b/worker/src/features/posthog/transformers.ts
@@ -0,0 +1,122 @@
+import { v5 } from "uuid";
+import type {
+ AnalyticsTraceEvent,
+ AnalyticsGenerationEvent,
+ AnalyticsScoreEvent,
+} from "@langfuse/shared/src/server";
+
+// UUID v5 namespace for PostHog
+const POSTHOG_UUID_NAMESPACE = "0f6c91df-d035-4813-b838-9741ba38ef0b";
+
+type PostHogEvent = {
+ distinctId: string;
+ event: string;
+ properties: Record<string, unknown>;
+ timestamp: Date;
+ uuid: string;
+};
+
+export const transformTraceForPostHog = (
+ trace: AnalyticsTraceEvent,
+ projectId: string,
+): PostHogEvent => {
+ const uuid = v5(`${projectId}-${trace.langfuse_id}`, POSTHOG_UUID_NAMESPACE);
+
+ // Extract posthog_session_id and map to $session_id
+ // eslint-disable-next-line no-unused-vars
+ const { posthog_session_id, mixpanel_session_id, ...otherProps } = trace;
+
+ return {
+ distinctId: trace.langfuse_user_id
+ ? (trace.langfuse_user_id as string)
+ : uuid,
+ event: "langfuse trace",
+ properties: {
+ ...otherProps,
+ $session_id: posthog_session_id ?? null,
+ // PostHog-specific: add user profile enrichment or mark as anonymous
+ ...(trace.langfuse_user_id && trace.langfuse_user_url
+ ? {
+ $set: {
+ langfuse_user_url: trace.langfuse_user_url,
+ },
+ }
+ : // Capture as anonymous PostHog event (cheaper/faster)
+ // https://posthog.com/docs/data/anonymous-vs-identified-events?tab=Backend
+ { $process_person_profile: false }),
+ },
+ timestamp: trace.timestamp as Date,
+ uuid,
+ };
+};
+
+export const transformGenerationForPostHog = (
+ generation: AnalyticsGenerationEvent,
+ projectId: string,
+): PostHogEvent => {
+ const uuid = v5(
+ `${projectId}-${generation.langfuse_id}`,
+ POSTHOG_UUID_NAMESPACE,
+ );
+
+ // Extract posthog_session_id and map to $session_id
+ // eslint-disable-next-line no-unused-vars
+ const { posthog_session_id, mixpanel_session_id, ...otherProps } = generation;
+
+ return {
+ distinctId: generation.langfuse_user_id
+ ? (generation.langfuse_user_id as string)
+ : uuid,
+ event: "langfuse generation",
+ properties: {
+ ...otherProps,
+ $session_id: posthog_session_id ?? null,
+ // PostHog-specific: add user profile enrichment or mark as anonymous
+ ...(generation.langfuse_user_id && generation.langfuse_user_url
+ ? {
+ $set: {
+ langfuse_user_url: generation.langfuse_user_url,
+ },
+ }
+ : // Capture as anonymous PostHog event (cheaper/faster)
+ // https://posthog.com/docs/data/anonymous-vs-identified-events?tab=Backend
+ { $process_person_profile: false }),
+ },
+ timestamp: generation.timestamp as Date,
+ uuid,
+ };
+};
+
+export const transformScoreForPostHog = (
+ score: AnalyticsScoreEvent,
+ projectId: string,
+): PostHogEvent => {
+ const uuid = v5(`${projectId}-${score.langfuse_id}`, POSTHOG_UUID_NAMESPACE);
+
+ // Extract posthog_session_id and map to $session_id
+ // eslint-disable-next-line no-unused-vars
+ const { posthog_session_id, mixpanel_session_id, ...otherProps } = score;
+
+ return {
+ distinctId: score.langfuse_user_id
+ ? (score.langfuse_user_id as string)
+ : uuid,
+ event: "langfuse score",
+ properties: {
+ ...otherProps,
+ $session_id: posthog_session_id ?? null,
+ // PostHog-specific: add user profile enrichment or mark as anonymous
+ ...(score.langfuse_user_id && score.langfuse_user_url
+ ? {
+ $set: {
+ langfuse_user_url: score.langfuse_user_url,
+ },
+ }
+ : // Capture as anonymous PostHog event (cheaper/faster)
+ // https://posthog.com/docs/data/anonymous-vs-identified-events?tab=Backend
+ { $process_person_profile: false }),
+ },
+ timestamp: score.timestamp as Date,
+ uuid,
+ };
+};
diff --git a/worker/src/queues/mixpanelIntegrationQueue.ts b/worker/src/queues/mixpanelIntegrationQueue.ts
new file mode 100644
index 0000000000..54811e9307
--- /dev/null
+++ b/worker/src/queues/mixpanelIntegrationQueue.ts
@@ -0,0 +1,46 @@
+import { Processor } from "bullmq";
+import {
+ instrumentAsync,
+ logger,
+ QueueJobs,
+} from "@langfuse/shared/src/server";
+import { handleMixpanelIntegrationSchedule } from "../features/mixpanel/handleMixpanelIntegrationSchedule";
+import { handleMixpanelIntegrationProjectJob } from "../features/mixpanel/handleMixpanelIntegrationProjectJob";
+import { SpanKind } from "@opentelemetry/api";
+
+export const mixpanelIntegrationProcessor: Processor = async (job) => {
+ if (job.name === QueueJobs.MixpanelIntegrationJob) {
+ logger.info("Executing Mixpanel Integration Job");
+ try {
+ return await handleMixpanelIntegrationSchedule();
+ } catch (error) {
+ logger.error("Error executing MixpanelIntegrationJob", error);
+ throw error;
+ }
+ }
+};
+
+export const mixpanelIntegrationProcessingProcessor: Processor = async (
+ job,
+) => {
+ if (job.name === QueueJobs.MixpanelIntegrationProcessingJob) {
+ return await instrumentAsync(
+ {
+ name: "process mixpanel-integration-project",
+ startNewTrace: true,
+ spanKind: SpanKind.CONSUMER,
+ },
+ async () => {
+ try {
+ return await handleMixpanelIntegrationProjectJob(job);
+ } catch (error) {
+ logger.error(
+ "Error executing MixpanelIntegrationProcessingJob",
+ error,
+ );
+ throw error;
+ }
+ },
+ );
+ }
+};