🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
chore: remove legacy v3-migration env variables (#5041)
Steffen Schmitzb85135992357
diff --git a/.env.dev.legacy.example b/.env.dev.legacy.exampledeleted file mode 100644index 8eb5c2f889..0000000000--- a/.env.dev.legacy.example+++ /dev/null@@ -1,86 +0,0 @@-# When adding additional environment variables, the schema in "/src/env.mjs"-# should be updated accordingly.--# Prisma-# https://www.prisma.io/docs/reference/database-reference/connection-urls#env-DIRECT_URL="postgresql://postgres:postgres@localhost:5432/postgres"-DATABASE_URL="postgresql://postgres:postgres@localhost:5432/postgres"--# Clickhouse-CLICKHOUSE_MIGRATION_URL="clickhouse://localhost:9000"-CLICKHOUSE_URL="http://localhost:8123"-CLICKHOUSE_USER="clickhouse"-CLICKHOUSE_PASSWORD="clickhouse"-CLICKHOUSE_CLUSTER_ENABLED="false"--# Next Auth-# You can generate a new secret on the command line with:-# openssl rand -base64 32-# https://next-auth.js.org/configuration/options#secret-# NEXTAUTH_SECRET=""-NEXTAUTH_URL="http://localhost:3000"-NEXTAUTH_SECRET="secret"--# Langfuse Cloud Environment-NEXT_PUBLIC_LANGFUSE_CLOUD_REGION="DEV"--# Langfuse experimental features-LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES="true"--# Salt for API key hashing-SALT="salt"--EMAIL_FROM_ADDRESS="" # Defines the email address to use as the from address.-SMTP_CONNECTION_URL="" # Defines the connection url for smtp server.--# S3 Batch Exports-LANGFUSE_S3_BATCH_EXPORT_ENABLED=true-LANGFUSE_S3_BATCH_EXPORT_BUCKET=langfuse-LANGFUSE_S3_BATCH_EXPORT_ACCESS_KEY_ID=minio-LANGFUSE_S3_BATCH_EXPORT_SECRET_ACCESS_KEY=miniosecret-LANGFUSE_S3_BATCH_EXPORT_REGION=us-east-1-LANGFUSE_S3_BATCH_EXPORT_ENDPOINT=http://localhost:9090-## Necessary for minio compatibility-LANGFUSE_S3_BATCH_EXPORT_FORCE_PATH_STYLE=true-LANGFUSE_S3_BATCH_EXPORT_PREFIX=exports/--# # S3 Media Upload LOCAL-LANGFUSE_S3_MEDIA_UPLOAD_BUCKET=langfuse-LANGFUSE_S3_MEDIA_UPLOAD_ACCESS_KEY_ID=minio-LANGFUSE_S3_MEDIA_UPLOAD_SECRET_ACCESS_KEY=miniosecret-LANGFUSE_S3_MEDIA_UPLOAD_REGION=us-east-1-LANGFUSE_S3_MEDIA_UPLOAD_ENDPOINT=http://localhost:9090-## Necessary for minio compatibility-LANGFUSE_S3_MEDIA_UPLOAD_FORCE_PATH_STYLE=true-LANGFUSE_S3_MEDIA_UPLOAD_PREFIX=media/--# S3 Event Bucket Upload-## Set to true to test uploading all events to S3-LANGFUSE_S3_EVENT_UPLOAD_BUCKET=langfuse-LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID=minio-LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY=miniosecret-LANGFUSE_S3_EVENT_UPLOAD_REGION=us-east-1-LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT=http://localhost:9090-## Necessary for minio compatibility-LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE=true-LANGFUSE_S3_EVENT_UPLOAD_PREFIX=events/--# Set during docker build of application-# Used to disable environment verification at build time-# DOCKER_BUILD=1--REDIS_HOST="127.0.0.1"-REDIS_PORT=6379-REDIS_AUTH="myredissecret"--# openssl rand -hex 32 used only here-ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000--# speeds up local development by not executing init scripts on server startup-NEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT="false"--LANGFUSE_READ_FROM_POSTGRES_ONLY=true-LANGFUSE_RETURN_FROM_CLICKHOUSE=false-LANGFUSE_READ_DASHBOARDS_FROM_CLICKHOUSE=false-LANGFUSE_READ_FROM_CLICKHOUSE_ONLY=falsediff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.ymlindex 63ad0849c9..f671d88665 100644--- a/.github/workflows/pipeline.yml+++ b/.github/workflows/pipeline.yml@@ -111,8 +111,9 @@ jobs:- name: Load default envrun: |cp .env.dev.example .env- grep -v -e '^LANGFUSE_S3_BATCH_EXPORT_ENABLED=' -e '^REDIS_HOST=' -e '^NEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT=' .env.dev.legacy.example > .env- echo "LANGFUSE_POSTGRES_INGESTION_ENABLED=true" >> .env+ grep -v -e '^LANGFUSE_S3_BATCH_EXPORT_ENABLED=' -e '^NEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT=' .env.dev.example > .env+ echo "LANGFUSE_INGESTION_QUEUE_DELAY_MS=1" >> .env+ echo "LANGFUSE_INGESTION_CLICKHOUSE_WRITE_INTERVAL_MS=1" >> .env- name: Run + migraterun: |docker compose -f docker-compose.dev.yml up -d@@ -184,7 +185,9 @@ jobs:- name: Load default envrun: |cp .env.dev${{ matrix.blob-provider }}.example .env- grep -v -e '^LANGFUSE_S3_BATCH_EXPORT_ENABLED=' -e '^REDIS_HOST=' -e '^NEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT=' .env.dev${{ matrix.blob-provider }}.example > .env+ grep -v -e '^LANGFUSE_S3_BATCH_EXPORT_ENABLED=' -e '^NEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT=' .env.dev${{ matrix.blob-provider }}.example > .env+ echo "LANGFUSE_INGESTION_QUEUE_DELAY_MS=1" >> .env+ echo "LANGFUSE_INGESTION_CLICKHOUSE_WRITE_INTERVAL_MS=1" >> .env- name: Run + migraterun: |docker compose -f docker-compose.dev${{ matrix.blob-provider }}.yml up -ddiff --git a/.gitignore b/.gitignoreindex 8f4ae6fb58..4055d8ff95 100644--- a/.gitignore+++ b/.gitignore@@ -39,7 +39,6 @@ yarn-error.log*!.env.dev.example!.env.dev-azure.example!.env.prod.example-!.env.dev.legacy.example# vercel.verceldiff --git a/docker-compose.yml b/docker-compose.ymlindex 8f71918607..710a389359 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -63,10 +63,6 @@ services:LANGFUSE_INIT_USER_EMAIL: ${LANGFUSE_INIT_USER_EMAIL:-}LANGFUSE_INIT_USER_NAME: ${LANGFUSE_INIT_USER_NAME:-}LANGFUSE_INIT_USER_PASSWORD: ${LANGFUSE_INIT_USER_PASSWORD:-}- LANGFUSE_SDK_CI_SYNC_PROCESSING_ENABLED: ${LANGFUSE_SDK_CI_SYNC_PROCESSING_ENABLED:-false}- LANGFUSE_READ_FROM_POSTGRES_ONLY: ${LANGFUSE_READ_FROM_POSTGRES_ONLY:-false}- LANGFUSE_READ_FROM_CLICKHOUSE_ONLY: ${LANGFUSE_READ_FROM_CLICKHOUSE_ONLY:-true}- LANGFUSE_RETURN_FROM_CLICKHOUSE: ${LANGFUSE_RETURN_FROM_CLICKHOUSE:-true}clickhouse:image: clickhouse/clickhouse-serverdiff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex 6701ddc398..145e3091b3 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -33,15 +33,6 @@ const EnvSchema = z.object({CLICKHOUSE_DB: z.string().default("default"),CLICKHOUSE_USER: z.string(),CLICKHOUSE_PASSWORD: z.string(),- LANGFUSE_SDK_CI_SYNC_PROCESSING_ENABLED: z- .enum(["true", "false"])- .default("false"),- LANGFUSE_CLICKHOUSE_INGESTION_ENABLED: z- .enum(["true", "false"])- .default("true"),- LANGFUSE_POSTGRES_INGESTION_ENABLED: z- .enum(["true", "false"])- .default("false"),LANGFUSE_INGESTION_QUEUE_DELAY_MS: z.coerce.number()diff --git a/packages/shared/src/server/ingestion/processEventBatch.ts b/packages/shared/src/server/ingestion/processEventBatch.tsindex a82f8bb35d..9356ebf376 100644--- a/packages/shared/src/server/ingestion/processEventBatch.ts+++ b/packages/shared/src/server/ingestion/processEventBatch.ts@@ -18,11 +18,9 @@ import {traceException,} from "../instrumentation";import { logger } from "../logger";-import { LegacyIngestionEventType, QueueJobs } from "../queues";+import { QueueJobs } from "../queues";import { IngestionQueue } from "../redis/ingestionQueue";-import { LegacyIngestionQueue } from "../redis/legacyIngestion";import { redis } from "../redis/redis";-import { handleBatch } from "./legacy";import {StorageService,StorageServiceFactory,@@ -185,140 +183,47 @@ export const processEventBatch = async (});});- // This is a workaround to allow us to disable async ingestion processing for SDK CI testing- // TODO: remove this block after SDKs are ready for V3 async ingestion processing- if (env.LANGFUSE_SDK_CI_SYNC_PROCESSING_ENABLED === "true") {- const result = await handleBatch(- sortedBatch,- authCheck,- tokenCountDelegate,- );-- // in case we did not return early, we return the result here- return aggregateBatchResult(- [...validationErrors, ...authenticationErrors, ...result.errors],- result.results,- authCheck.scope.projectId,+ // Send each event individually to IngestionQueue for ClickHouse processing+ if (s3UploadErrored) {+ throw new Error(+ "Failed to upload events to blob storage, aborting event processing",);}- // Send each event individually to IngestionQueue for ClickHouse processing- if (env.LANGFUSE_CLICKHOUSE_INGESTION_ENABLED === "true") {- if (s3UploadErrored) {- throw new Error(- "Failed to upload events to blob storage, aborting event processing",- );- }-- if (redis) {- const queue = IngestionQueue.getInstance();- await Promise.all(- Object.keys(sortedBatchByEventBodyId).map(async (id) =>- queue- ? queue.add(- QueueJobs.IngestionJob,- {- id: randomUUID(),- timestamp: new Date(),- name: QueueJobs.IngestionJob as const,- payload: {- data: {- type: sortedBatchByEventBodyId[id].type,- eventBodyId: sortedBatchByEventBodyId[id].eventBodyId,- },- authCheck,- },- },- {- delay: env.LANGFUSE_INGESTION_QUEUE_DELAY_MS,- },- )- : Promise.reject("Failed to instantiate queue"),- ),- );- if (env.LANGFUSE_POSTGRES_INGESTION_ENABLED !== "true") {- // If postgres ingestion is disabled, we return early- return aggregateBatchResult(- [...validationErrors, ...authenticationErrors],- sortedBatch.map((event) => ({ id: event.id, result: event })),- authCheck.scope.projectId,- );- }- }+ if (!redis) {+ throw new Error("Redis not initialized, aborting event processing");}- if (env.LANGFUSE_POSTGRES_INGESTION_ENABLED === "true") {- // As part of the legacy processing we sent the entire batch to the worker.- if (redis) {- const queue = LegacyIngestionQueue.getInstance();-- if (queue) {- let addToQueueFailed = false;-- const queuePayload: LegacyIngestionEventType = !s3UploadErrored- ? {- data: Object.keys(sortedBatchByEventBodyId).map((id) => {- const { key, type, eventBodyId } = sortedBatchByEventBodyId[id];- return {- type,- eventBodyId,- eventId: key,- };- }),- authCheck,- useS3EventStore: true,- }- : { data: sortedBatch, authCheck, useS3EventStore: false };-- try {- await queue.add(QueueJobs.LegacyIngestionJob, {- payload: queuePayload,- id: randomUUID(),- timestamp: new Date(),- name: QueueJobs.LegacyIngestionJob as const,- });- } catch (e: unknown) {- logger.warn(- "Failed to add batch to queue, falling back to sync processing",- e,- );- addToQueueFailed = true;- }-- if (!addToQueueFailed) {- return aggregateBatchResult(- // we are not sending additional server errors to the client in case of early return- [...validationErrors, ...authenticationErrors],- sortedBatch.map((event) => ({ id: event.id, result: event })),- authCheck.scope.projectId,- );- }- } else {- logger.warn(- "Ingestion queue not initialized, falling back to sync processing",- );- }- }-- /*******************- * SYNC PROCESSING *- *******************/- const result = await handleBatch(- sortedBatch,- authCheck,- tokenCountDelegate,- );-- // in case we did not return early, we return the result here- return aggregateBatchResult(- [...validationErrors, ...authenticationErrors, ...result.errors],- result.results,- authCheck.scope.projectId,- );- }+ const queue = IngestionQueue.getInstance();+ await Promise.all(+ Object.keys(sortedBatchByEventBodyId).map(async (id) =>+ queue+ ? queue.add(+ QueueJobs.IngestionJob,+ {+ id: randomUUID(),+ timestamp: new Date(),+ name: QueueJobs.IngestionJob as const,+ payload: {+ data: {+ type: sortedBatchByEventBodyId[id].type,+ eventBodyId: sortedBatchByEventBodyId[id].eventBodyId,+ },+ authCheck,+ },+ },+ {+ delay: env.LANGFUSE_INGESTION_QUEUE_DELAY_MS,+ },+ )+ : Promise.reject("Failed to instantiate queue"),+ ),+ );- throw new Error(- "Either Clickhouse or Postgres ingestion (or both) must be enabled",+ return aggregateBatchResult(+ [...validationErrors, ...authenticationErrors],+ sortedBatch.map((event) => ({ id: event.id, result: event })),+ authCheck.scope.projectId,);};diff --git a/web/src/__tests__/async/ingestion-api.servertest.ts b/web/src/__tests__/async/ingestion-api.servertest.tsnew file mode 100644index 0000000000..aac9cc4226--- /dev/null+++ b/web/src/__tests__/async/ingestion-api.servertest.ts@@ -0,0 +1,219 @@+import { randomUUID } from "crypto";+import { makeAPICall } from "@/src/__tests__/test-utils";+import waitForExpect from "wait-for-expect";+import {+ getObservationById,+ getScoreById,+ getTraceById,+} from "@langfuse/shared/src/server";+import { v4 } from "uuid";++const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";++describe("/api/public/ingestion API Endpoint", () => {+ it.each([+ [+ "plain",+ {+ id: randomUUID(),+ type: "trace-create",+ timestamp: new Date().toISOString(),+ body: {+ id: randomUUID(),+ timestamp: new Date().toISOString(),+ },+ },+ ],+ [+ "metadata+io",+ {+ id: randomUUID(),+ type: "trace-create",+ timestamp: new Date().toISOString(),+ body: {+ id: randomUUID(),+ timestamp: new Date().toISOString(),+ metadata: { hello: "world" },+ input: "input",+ output: "output",+ },+ },+ ],+ [+ "complex-io",+ {+ id: randomUUID(),+ type: "trace-create",+ timestamp: new Date().toISOString(),+ body: {+ id: randomUUID(),+ timestamp: new Date().toISOString(),+ metadata: { hello: "world" },+ input: ["hello", { world: "world" }, [1, 2, 3]],+ },+ },+ ],+ ])(+ "should create traces via the ingestion API (%s)",+ async (_name: string, entity: any) => {+ const response = await makeAPICall("POST", "/api/public/ingestion", {+ batch: [entity],+ });++ expect(response.status).toBe(207);++ await waitForExpect(async () => {+ const trace = await getTraceById(entity.body.id, projectId);+ expect(trace).toBeDefined();+ expect(trace!.id).toBe(entity.body.id);+ expect(trace!.projectId).toBe(projectId);+ expect(trace!.metadata).toEqual(entity.body?.metadata ?? {});+ expect(trace!.input).toEqual(entity.body?.input ?? null);+ expect(trace!.output).toEqual(entity.body?.output ?? null);+ });+ },+ );++ it.each([+ [+ "generation",+ "GENERATION",+ {+ id: randomUUID(),+ type: "generation-create",+ timestamp: new Date().toISOString(),+ body: {+ id: randomUUID(),+ traceId: randomUUID(),+ parentObservationId: randomUUID(),+ startTime: new Date().toISOString(),+ model: "gpt-4",+ input: { text: "input" },+ output: { text: "output" },+ },+ },+ ],+ [+ "span",+ "SPAN",+ {+ id: randomUUID(),+ type: "span-create",+ timestamp: new Date().toISOString(),+ body: {+ id: randomUUID(),+ traceId: randomUUID(),+ startTime: new Date().toISOString(),+ },+ },+ ],+ [+ "span-complex-io",+ "SPAN",+ {+ id: randomUUID(),+ type: "span-create",+ timestamp: new Date().toISOString(),+ body: {+ id: randomUUID(),+ traceId: randomUUID(),+ startTime: new Date().toISOString(),+ input: ["hello", { world: "world" }, [1, 2, 3]],+ output: ["hello", { world: [2, 3, "test"] }, [1, 2, 3]],+ },+ },+ ],+ ])(+ "should create observations via the ingestion API (%s)",+ async (_name: string, type: string, entity: any) => {+ const response = await makeAPICall("POST", "/api/public/ingestion", {+ batch: [entity],+ });++ expect(response.status).toBe(207);++ await waitForExpect(async () => {+ const observation = await getObservationById(+ entity.body.id,+ projectId,+ true,+ );+ expect(observation).toBeDefined();+ expect(observation!.id).toBe(entity.body.id);+ expect(observation!.projectId).toBe(projectId);+ expect(observation!.metadata).toEqual(entity.body?.metadata ?? {});+ expect(observation!.input).toEqual(entity.body?.input ?? null);+ expect(observation!.output).toEqual(entity.body?.output ?? null);+ expect(observation!.type).toBe(type);+ });+ },+ );++ it.each([+ [+ "plain",+ {+ id: randomUUID(),+ type: "score-create",+ timestamp: new Date().toISOString(),+ body: {+ id: randomUUID(),+ name: "score-name",+ traceId: randomUUID(),+ value: 100.5,+ observationId: randomUUID(),+ },+ },+ ],+ ])(+ "should create scores via the ingestion API (%s)",+ async (_name: string, entity: any) => {+ const response = await makeAPICall("POST", "/api/public/ingestion", {+ batch: [entity],+ });++ expect(response.status).toBe(207);++ await waitForExpect(async () => {+ const score = await getScoreById(projectId, entity.body.id);+ expect(score).toBeDefined();+ expect(score!.id).toBe(entity.body.id);+ expect(score!.projectId).toBe(projectId);+ expect(score!.value).toEqual(100.5);+ });+ },+ );++ it("should fail for long trace name", async () => {+ const traceId = v4();++ const baseString =+ "Lorem ipsum dolor sit amet, consectetur adipiscing elit. ";+ const repeatCount = Math.ceil(1500 / baseString.length);+ const name = baseString.repeat(repeatCount);++ const response = await makeAPICall("POST", "/api/public/ingestion", {+ batch: [+ {+ id: v4(),+ type: "trace-create",+ timestamp: new Date().toISOString(),+ body: {+ id: traceId,+ name,+ userId: "user-1",+ metadata: { key: "value" },+ release: "1.0.0",+ version: "2.0.0",+ },+ },+ ],+ });++ expect(response.status).toBe(207);+ expect("errors" in response.body).toBe(true);+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ expect(response.body.errors.length).toBe(1);+ expect(response.body.errors[0].message).toBe("Invalid request data");+ });+});diff --git a/web/src/__tests__/events.servertest.ts b/web/src/__tests__/events.servertest.tsdeleted file mode 100644index abdeaf16a5..0000000000--- a/web/src/__tests__/events.servertest.ts+++ /dev/null@@ -1,297 +0,0 @@-/** @jest-environment node */--import { prisma } from "@langfuse/shared/src/db";-import {- makeZodVerifiedAPICall,- pruneDatabase,-} from "@/src/__tests__/test-utils";-import { v4 as uuidv4 } from "uuid";-import { PostTracesV1Response } from "@/src/features/public-api/types/traces";-import { PostEventsV1Response } from "@/src/features/public-api/types/events";--describe("/api/public/events API Endpoint", () => {- beforeEach(async () => await pruneDatabase());-- it("should create event after trace", async () => {- await pruneDatabase();-- const traceId = uuidv4();-- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- id: traceId,- name: "trace-name",- userId: "user-1",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- metadata: { key: "value" },- release: "1.0.0",- version: "2.0.0",- },- );-- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.id).toBe(traceId);-- const eventId = uuidv4();- const createEvent = await makeZodVerifiedAPICall(- PostEventsV1Response,- "POST",- "/api/public/events",- {- id: eventId,- traceId: traceId,- name: "event-name",- startTime: "2021-01-01T00:00:00.000Z",- input: { input: "value" },- output: { output: "value" },- metadata: { meta: "value" },- version: "2.0.0",- },- );-- expect(createEvent.status).toBe(200);- const dbEvent = await prisma.observation.findUnique({- where: {- id: eventId,- },- });-- expect(dbEvent?.id).toBe(eventId);- expect(dbEvent?.traceId).toBe(traceId);- expect(dbEvent?.name).toBe("event-name");- expect(dbEvent?.startTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbEvent?.input).toEqual({ input: "value" });- expect(dbEvent?.output).toEqual({ output: "value" });- expect(dbEvent?.metadata).toEqual({ meta: "value" });- expect(dbEvent?.version).toBe("2.0.0");- });-- it("should create event before trace", async () => {- await pruneDatabase();-- const traceId = uuidv4();- const eventId = uuidv4();-- const createEvent = await makeZodVerifiedAPICall(- PostEventsV1Response,- "POST",- "/api/public/events",- {- id: eventId,- traceId: traceId,- name: "event-name",- startTime: "2021-01-01T00:00:00.000Z",- input: { input: "value" },- output: { output: "value" },- metadata: { meta: "value" },- version: "2.0.0",- },- );-- expect(createEvent.status).toBe(200);- const dbEvent = await prisma.observation.findUnique({- where: {- id: eventId,- },- });-- expect(dbEvent?.id).toBe(eventId);- expect(dbEvent?.traceId).toBe(traceId);- expect(dbEvent?.name).toBe("event-name");- expect(dbEvent?.startTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbEvent?.input).toEqual({ input: "value" });- expect(dbEvent?.output).toEqual({ output: "value" });- expect(dbEvent?.metadata).toEqual({ meta: "value" });- expect(dbEvent?.version).toBe("2.0.0");-- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- id: traceId,- name: "trace-name",- userId: "user-1",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- metadata: { key: "value" },- release: "1.0.0",- version: "2.0.0",- },- );-- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.id).toBe(traceId);- });-- it("should create trace and ignore externalId and create event afterwards", async () => {- await pruneDatabase();-- const traceId = uuidv4();-- const response = await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- externalId: traceId,- name: "trace-name",- userId: "user-1",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- metadata: { key: "value" },- release: "1.0.0",- version: "2.0.0",- },- );-- expect(response.status).toBe(200);-- const dbTrace = await prisma.trace.findMany({- where: {- name: "trace-name",- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.externalId).toBeNull();- expect(dbTrace[0]?.id).not.toBe(traceId);-- const eventId = uuidv4();- const createEvent = await makeZodVerifiedAPICall(- PostEventsV1Response,- "POST",- "/api/public/events",- {- id: eventId,- traceIdType: "EXTERNAL",- traceId: dbTrace[0]?.id,- name: "event-name",- startTime: "2021-01-01T00:00:00.000Z",- input: { input: "value" },- output: { output: "value" },- metadata: { meta: "value" },- version: "2.0.0",- },- );-- expect(createEvent.status).toBe(200);- const dbEvent = await prisma.observation.findUnique({- where: {- id: eventId,- },- });-- expect(dbEvent?.id).toBe(eventId);- expect(dbEvent?.traceId).toBe(dbTrace[0]?.id);- expect(dbEvent?.name).toBe("event-name");- expect(dbEvent?.startTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbEvent?.input).toEqual({ input: "value" });- expect(dbEvent?.output).toEqual({ output: "value" });- expect(dbEvent?.metadata).toEqual({ meta: "value" });- expect(dbEvent?.version).toBe("2.0.0");- });-- it("should create trace when creating span without existing trace", async () => {- const eventName = uuidv4();-- const spanId = uuidv4();- const createEvent = await makeZodVerifiedAPICall(- PostEventsV1Response,- "POST",- "/api/public/events",- {- id: spanId,- name: eventName,- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- input: { input: "value" },- output: { output: "value" },- metadata: { meta: "value" },- version: "2.0.0",- },- );-- const dbTrace = await prisma.trace.findMany({- where: {- name: eventName,- },- });-- expect(dbTrace.length).toBe(1);- expect(dbTrace[0]?.name).toBe(eventName);-- expect(createEvent.status).toBe(200);- const dbEvent = await prisma.observation.findUnique({- where: {- id: spanId,- },- });-- expect(dbEvent?.id).toBe(spanId);- expect(dbEvent?.traceId).toBe(dbTrace[0]?.id);- expect(dbEvent?.name).toBe(eventName);- expect(dbEvent?.startTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbEvent?.input).toEqual({ input: "value" });- expect(dbEvent?.output).toEqual({ output: "value" });- expect(dbEvent?.metadata).toEqual({ meta: "value" });- expect(dbEvent?.version).toBe("2.0.0");- });-- it("should create event when creating generation without existing trace without traceId", async () => {- const generationName = uuidv4();-- const spanId = uuidv4();- const createSpan = await makeZodVerifiedAPICall(- PostEventsV1Response,- "POST",- "/api/public/events",- {- id: spanId,- name: generationName,- startTime: "2021-01-01T00:00:00.000Z",- input: { key: "value" },- metadata: { key: "value" },- version: "2.0.0",- },- );-- const dbEvent = await prisma.observation.findFirstOrThrow({- where: {- name: generationName,- },- });-- const dbTrace = await prisma.trace.findMany({- where: {- id: dbEvent.traceId!,- },- });-- expect(dbTrace.length).toBe(1);- expect(dbTrace[0]?.name).toBe(generationName);-- expect(createSpan.status).toBe(200);-- expect(dbEvent.id).toBe(spanId);- expect(dbEvent.traceId).toBe(dbTrace[0]?.id);- expect(dbEvent.name).toBe(generationName);- expect(dbEvent.startTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbEvent.input).toEqual({ key: "value" });- expect(dbEvent.metadata).toEqual({ key: "value" });- expect(dbEvent.version).toBe("2.0.0");- });-});diff --git a/web/src/__tests__/generations.servertest.ts b/web/src/__tests__/generations.servertest.tsdeleted file mode 100644index 1f993f0b74..0000000000--- a/web/src/__tests__/generations.servertest.ts+++ /dev/null@@ -1,643 +0,0 @@-/** @jest-environment node */--import { v4 as uuidv4 } from "uuid";--import {- makeAPICall,- makeZodVerifiedAPICall,- pruneDatabase,-} from "@/src/__tests__/test-utils";-import { ModelUsageUnit } from "@langfuse/shared";-import { prisma } from "@langfuse/shared/src/db";-import { PostTracesV1Response } from "@/src/features/public-api/types/traces";-import {- PatchGenerationsV1Response,- PostGenerationsV1Body,- PostGenerationsV1Response,-} from "@/src/features/public-api/types/generations";--describe("/api/public/generations API Endpoint", () => {- beforeEach(async () => await pruneDatabase());-- [- {- usage: {- input: 100,- output: 200,- total: 100,- unit: ModelUsageUnit.Characters,- },- expectedUnit: ModelUsageUnit.Characters,- expectedPromptTokens: 100,- expectedCompletionTokens: 200,- expectedTotalTokens: 100,- },- {- usage: {- total: 100,- unit: ModelUsageUnit.Characters,- },- expectedUnit: ModelUsageUnit.Characters,- expectedPromptTokens: 0,- expectedCompletionTokens: 0,- expectedTotalTokens: 100,- },- {- usage: {- total: 100,- },- expectedUnit: null,- expectedPromptTokens: 0,- expectedCompletionTokens: 0,- expectedTotalTokens: 100,- },- {- usage: {- promptTokens: 100,- completionTokens: 200,- totalTokens: 100,- },- expectedPromptTokens: 100,- expectedCompletionTokens: 200,- expectedTotalTokens: 100,- expectedUnit: ModelUsageUnit.Tokens,- },- {- usage: {- totalTokens: 100,- },- expectedPromptTokens: 0,- expectedCompletionTokens: 0,- expectedTotalTokens: 100,- expectedUnit: ModelUsageUnit.Tokens,- },- {- usage: undefined,- expectedPromptTokens: 0,- expectedCompletionTokens: 0,- expectedTotalTokens: 0,- expectedUnit: null,- },- {- usage: null,- expectedPromptTokens: 0,- expectedCompletionTokens: 0,- expectedTotalTokens: 0,- expectedUnit: null,- },- {- usage: {},- expectedPromptTokens: 0,- expectedCompletionTokens: 0,- expectedTotalTokens: 0,- expectedUnit: null,- },- ].forEach((testConfig) => {- it(`should create generation after trace 1 ${JSON.stringify(- testConfig,- )}`, async () => {- await pruneDatabase();-- const traceId = uuidv4();-- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- id: traceId,- name: "trace-name",- userId: "user-1",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- metadata: { key: "value" },- release: "1.0.0",- version: "2.0.0",- },- );-- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.id).toBe(traceId);-- const generationId = uuidv4();- const createGeneration = await makeZodVerifiedAPICall(- PostGenerationsV1Response,- "POST",- "/api/public/generations",- {- id: generationId,- traceId: traceId,- name: "generation-name",- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- model: "model-name",- modelParameters: { key: "value" },- prompt: { key: "value" },- metadata: { key: "value" },- version: "2.0.0",- usage: testConfig.usage,- },- );-- expect(createGeneration.status).toBe(200);- const dbGeneration = await prisma.observation.findUnique({- where: {- id: generationId,- },- });-- expect(dbGeneration?.id).toBe(generationId);- expect(dbGeneration?.traceId).toBe(traceId);- expect(dbGeneration?.name).toBe("generation-name");- expect(dbGeneration?.startTime).toEqual(- new Date("2021-01-01T00:00:00.000Z"),- );- expect(dbGeneration?.endTime).toEqual(- new Date("2021-01-01T00:00:00.000Z"),- );- expect(dbGeneration?.model).toBe("model-name");- expect(dbGeneration?.modelParameters).toEqual({ key: "value" });- expect(dbGeneration?.input).toEqual({ key: "value" });- expect(dbGeneration?.metadata).toEqual({ key: "value" });- expect(dbGeneration?.version).toBe("2.0.0");- expect(dbGeneration?.unit).toBe(testConfig.expectedUnit);- expect(dbGeneration?.promptTokens).toBe(testConfig.expectedPromptTokens);- expect(dbGeneration?.completionTokens).toBe(- testConfig.expectedCompletionTokens,- );- expect(dbGeneration?.totalTokens).toBe(testConfig.expectedTotalTokens);- });- });-- it("should create generation before trace", async () => {- await pruneDatabase();-- const traceId = uuidv4();-- const generationId = uuidv4();- const createGeneration = await makeZodVerifiedAPICall(- PostGenerationsV1Body,- "POST",- "/api/public/generations",- {- id: generationId,- traceId: traceId,- name: "generation-name",- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- model: "model-name",- modelParameters: { key: "value" },- prompt: { key: "value" },- metadata: { key: "value" },- version: "2.0.0",- },- );-- expect(createGeneration.status).toBe(200);- const dbGeneration = await prisma.observation.findUnique({- where: {- id: generationId,- },- });-- expect(dbGeneration?.id).toBe(generationId);- expect(dbGeneration?.traceId).toBe(traceId);- expect(dbGeneration?.name).toBe("generation-name");- expect(dbGeneration?.startTime).toEqual(- new Date("2021-01-01T00:00:00.000Z"),- );- expect(dbGeneration?.endTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbGeneration?.model).toBe("model-name");- expect(dbGeneration?.modelParameters).toEqual({ key: "value" });- expect(dbGeneration?.input).toEqual({ key: "value" });- expect(dbGeneration?.metadata).toEqual({ key: "value" });- expect(dbGeneration?.version).toBe("2.0.0");-- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- id: traceId,- name: "trace-name",- userId: "user-1",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- metadata: { key: "value" },- release: "1.0.0",- version: "2.0.0",- },- );-- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.id).toBe(traceId);- });-- it("should create generation after trace ignoring externalId", async () => {- const traceId = uuidv4();-- const response = await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- externalId: traceId,- name: "trace-name",- userId: "user-1",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- metadata: { key: "value" },- release: "1.0.0",- version: "2.0.0",- },- );-- expect(response.status).toBe(200);-- const dbTrace = await prisma.trace.findMany({- where: {- name: "trace-name",- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.externalId).toBeNull();- expect(dbTrace[0]?.id).not.toBe(traceId);-- const generationId = uuidv4();- const createGeneration = await makeZodVerifiedAPICall(- PostGenerationsV1Body,- "POST",- "/api/public/generations",- {- id: generationId,- traceIdType: "EXTERNAL",- traceId: traceId,- name: "generation-name",- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- model: "model-name",- modelParameters: { key: "value" },- prompt: { key: "value" },- metadata: { key: "value" },- version: "2.0.0",- },- );-- expect(createGeneration.status).toBe(200);- const dbGeneration = await prisma.observation.findUnique({- where: {- id: generationId,- },- });-- expect(dbGeneration?.id).toBe(generationId);- expect(dbGeneration?.traceId).toBe(traceId);- expect(dbGeneration?.name).toBe("generation-name");- expect(dbGeneration?.startTime).toEqual(- new Date("2021-01-01T00:00:00.000Z"),- );- expect(dbGeneration?.endTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbGeneration?.model).toBe("model-name");- expect(dbGeneration?.modelParameters).toEqual({ key: "value" });- expect(dbGeneration?.input).toEqual({ key: "value" });- expect(dbGeneration?.metadata).toEqual({ key: "value" });- expect(dbGeneration?.version).toBe("2.0.0");- });-- it("should create trace when creating generation without existing trace", async () => {- const generationName = uuidv4();-- const generationId = uuidv4();- const createGeneration = await makeZodVerifiedAPICall(- PostGenerationsV1Body,- "POST",- "/api/public/generations",- {- id: generationId,- name: generationName,- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- model: "model-name",- modelParameters: { key: "value" },- prompt: { key: "value" },- metadata: { key: "value" },- version: "2.0.0",- },- );-- const dbTrace = await prisma.trace.findMany({- where: {- name: generationName,- },- });-- expect(dbTrace.length).toBe(1);- expect(dbTrace[0]?.name).toBe(generationName);-- expect(createGeneration.status).toBe(200);- const dbGeneration = await prisma.observation.findUnique({- where: {- id: generationId,- },- });-- expect(dbGeneration?.id).toBe(generationId);- expect(dbGeneration?.traceId).toBe(dbTrace[0]?.id);- expect(dbGeneration?.name).toBe(generationName);- expect(dbGeneration?.startTime).toEqual(- new Date("2021-01-01T00:00:00.000Z"),- );- expect(dbGeneration?.endTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbGeneration?.model).toBe("model-name");- expect(dbGeneration?.modelParameters).toEqual({ key: "value" });- expect(dbGeneration?.input).toEqual({ key: "value" });- expect(dbGeneration?.metadata).toEqual({ key: "value" });- expect(dbGeneration?.version).toBe("2.0.0");- });-- it("should create nested generations", async () => {- const generationName = uuidv4();-- const generationId = uuidv4();- const createGeneration = await makeZodVerifiedAPICall(- PostGenerationsV1Body,- "POST",- "/api/public/generations",- {- id: generationId,- name: generationName,- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- model: "model-name",- modelParameters: { key: "value" },- prompt: { key: "value" },- metadata: { key: "value" },- version: "2.0.0",- },- );-- expect(createGeneration.status).toBe(200);- const dbGeneration = await prisma.observation.findUnique({- where: {- id: generationId,- },- });-- expect(dbGeneration?.id).toBe(generationId);-- const generationId2 = uuidv4();- const generationName2 = uuidv4();-- const createGeneration2 = await makeZodVerifiedAPICall(- PostGenerationsV1Body,- "POST",- "/api/public/generations",- {- id: generationId2,- name: generationName2,- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- model: "model-name",- modelParameters: { key: "value" },- prompt: { key: "value" },- metadata: { key: "value" },- version: "2.0.0",- parentObservationId: generationId,- },- );- expect(createGeneration2.status).toBe(200);-- const dbGeneration2 = await prisma.observation.findUnique({- where: {- id: generationId2,- },- });-- expect(dbGeneration2?.id).toBe(generationId2);- expect(dbGeneration2?.parentObservationId).toBe(generationId);- });-- it("should not create trace when creating generation without existing trace with externalId", async () => {- const generationName = uuidv4();-- const generationId = uuidv4();- const externalTraceId = uuidv4();- const createGeneration = await makeZodVerifiedAPICall(- PostGenerationsV1Body,- "POST",- "/api/public/generations",- {- id: generationId,- traceIdType: "EXTERNAL",- traceId: externalTraceId,- name: generationName,- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- model: "model-name",- modelParameters: { key: "value" },- prompt: { key: "value" },- metadata: { key: "value" },- version: "2.0.0",- },- );-- expect(createGeneration.status).toBe(200);-- const dbGeneration = await prisma.observation.findFirstOrThrow({- where: {- name: generationName,- },- });- expect(dbGeneration.id).toBe(generationId);- expect(dbGeneration.traceId).toBe(externalTraceId);-- const dbTraces = await prisma.trace.findMany();- expect(dbTraces.length).toBe(0);- });-- it("should create trace when creating generation without existing trace without traceId", async () => {- const generationName = uuidv4();-- const generationId = uuidv4();- const createGeneration = await makeZodVerifiedAPICall(- PostGenerationsV1Body,- "POST",- "/api/public/generations",- {- id: generationId,- name: generationName,- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- model: "model-name",- modelParameters: { key: "value" },- prompt: { key: "value" },- metadata: { key: "value" },- version: "2.0.0",- },- );-- const dbGeneration = await prisma.observation.findFirstOrThrow({- where: {- name: generationName,- },- });-- const dbTrace = await prisma.trace.findMany({- where: {- id: dbGeneration.traceId!,- },- });-- expect(dbTrace.length).toBe(1);- expect(dbTrace[0]?.name).toBe(generationName);-- expect(createGeneration.status).toBe(200);-- expect(dbGeneration.id).toBe(generationId);- expect(dbGeneration.traceId).toBe(dbTrace[0]?.id);- expect(dbGeneration.name).toBe(generationName);- expect(dbGeneration.startTime).toEqual(- new Date("2021-01-01T00:00:00.000Z"),- );- expect(dbGeneration.endTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbGeneration.model).toBe("model-name");- expect(dbGeneration.modelParameters).toEqual({ key: "value" });- expect(dbGeneration.input).toEqual({ key: "value" });- expect(dbGeneration.metadata).toEqual({ key: "value" });- expect(dbGeneration.version).toBe("2.0.0");- });-- it("should update generation", async () => {- const generationName = uuidv4();-- const generationId = uuidv4();- const createGeneration = await makeZodVerifiedAPICall(- PostGenerationsV1Body,- "POST",- "/api/public/generations",- {- id: generationId,- name: generationName,- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- model: "model-name",- modelParameters: { key: "value" },- prompt: { key: "value" },- metadata: { key: "value" },- version: "2.0.0",- },- );-- expect(createGeneration.status).toBe(200);-- const updateGeneration = await makeZodVerifiedAPICall(- PatchGenerationsV1Response,- "PATCH",- "/api/public/generations",- {- generationId: generationId,- completion: "this is a great gpt response",- },- );- expect(updateGeneration.status).toBe(200);-- const dbGeneration = await prisma.observation.findUnique({- where: {- id: generationId,- },- });-- expect(dbGeneration?.id).toBe(generationId);- expect(dbGeneration?.name).toBe(generationName);- expect(dbGeneration?.startTime).toEqual(- new Date("2021-01-01T00:00:00.000Z"),- );- expect(dbGeneration?.endTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbGeneration?.model).toBe("model-name");- expect(dbGeneration?.modelParameters).toEqual({ key: "value" });- expect(dbGeneration?.input).toEqual({ key: "value" });- expect(dbGeneration?.output).toEqual("this is a great gpt response");- expect(dbGeneration?.metadata).toEqual({ key: "value" });- expect(dbGeneration?.version).toBe("2.0.0");- });-- it("should accept objects as i/o", async () => {- const generationName = uuidv4();-- const generationId = uuidv4();- const createGeneration = await makeZodVerifiedAPICall(- PostGenerationsV1Body,- "POST",- "/api/public/generations",- {- id: generationId,- name: generationName,- prompt: { key: "value" },- completion: [- {- foo: "bar",- },- ],- metadata: [- {- tags: ["example tag", "second tag"],- },- ],- },- );-- expect(createGeneration.status).toBe(200);-- const dbGeneration = await prisma.observation.findUnique({- where: {- id: generationId,- },- });-- expect(dbGeneration?.id).toBe(generationId);- expect(dbGeneration?.name).toBe(generationName);- expect(dbGeneration?.input).toEqual({ key: "value" });- expect(dbGeneration?.output).toEqual([- {- foo: "bar",- },- ]);- expect(dbGeneration?.metadata).toEqual([- {- tags: ["example tag", "second tag"],- },- ]);- });-- it("should not succeed update if generation does not exist", async () => {- const generationId = uuidv4();-- const updateGeneration = await makeAPICall(- "PATCH",- "/api/public/generations",- {- generationId: generationId,- completion: "this is a great gpt response",- },- );- expect(updateGeneration.status).toBe(404);-- const dbGeneration = await prisma.observation.findUnique({- where: {- id: generationId,- },- });-- expect(dbGeneration).toBeNull();- });-});diff --git a/web/src/__tests__/ingestion.servertest.ts b/web/src/__tests__/ingestion.servertest.tsdeleted file mode 100644index e199559938..0000000000--- a/web/src/__tests__/ingestion.servertest.ts+++ /dev/null@@ -1,1798 +0,0 @@-/** @jest-environment node */--import { v4 } from "uuid";--import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";-import { ModelUsageUnit } from "@langfuse/shared";-import { prisma } from "@langfuse/shared/src/db";-import { cleanEvent } from "@langfuse/shared/src/server";--describe("/api/public/ingestion API Endpoint", () => {- beforeEach(async () => await pruneDatabase());-- [- {- input: "Hello",- output: "World",- },- {- input: { key: "value" },- output: { key: "value" },- },- {- input: [1, 2, "hello"],- output: [3, 4, "world"],- },- // TODO: Enable test after prisma fixed https://github.com/prisma/prisma/issues/24989.- // {- // input: "Test \ud83d",- // output: "Result \ud83d",- // },- ].forEach((testConfig) => {- it(`should create generations with correct input and output ${JSON.stringify(- testConfig,- )}`, async () => {- const traceId = v4();- const generationId = v4();-- const response = await makeAPICall("POST", "/api/public/ingestion", {- metadata: {- sdk_version: "1.0.0",- sdk_name: "python",- },- batch: [- {- id: v4(),- type: "observation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- traceId: traceId,- type: "GENERATION",- name: "generation-name",- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- modelParameters: { key: "value" },- input: testConfig.input,- output: testConfig.output,- },- },- ],- });-- expect(response.status).toBe(207);-- const dbGeneration = await prisma.observation.findUnique({- where: {- id: generationId,- },- });-- expect(dbGeneration?.id).toBe(generationId);- expect(dbGeneration?.input).toStrictEqual(testConfig.input);- expect(dbGeneration?.output).toStrictEqual(testConfig.output);- });- });-- [- {- usage: {- input: 100,- output: 200,- total: 100,- unit: ModelUsageUnit.Characters,- inputCost: 123,- outputCost: 456,- totalCost: 789,- },- expectedUnit: ModelUsageUnit.Characters,- expectedPromptTokens: 100,- expectedCompletionTokens: 200,- expectedTotalTokens: 100,- },- {- usage: {- total: 100,- unit: ModelUsageUnit.Characters,- },- expectedUnit: ModelUsageUnit.Characters,- expectedPromptTokens: 0,- expectedCompletionTokens: 0,- expectedTotalTokens: 100,- },- {- usage: {- total: 100,- unit: ModelUsageUnit.Milliseconds,- },- expectedUnit: ModelUsageUnit.Milliseconds,- expectedPromptTokens: 0,- expectedCompletionTokens: 0,- expectedTotalTokens: 100,- },- {- usage: {- input: 1,- output: 2,- unit: ModelUsageUnit.Images,- },- expectedUnit: ModelUsageUnit.Images,- expectedPromptTokens: 1,- expectedCompletionTokens: 2,- expectedTotalTokens: 3,- },- {- usage: {- input: 1,- output: 2,- unit: ModelUsageUnit.Requests,- },- expectedUnit: ModelUsageUnit.Requests,- expectedPromptTokens: 1,- expectedCompletionTokens: 2,- expectedTotalTokens: 3,- },- {- usage: {- input: 30,- output: 10,- unit: ModelUsageUnit.Seconds,- },- expectedUnit: ModelUsageUnit.Seconds,- expectedPromptTokens: 30,- expectedCompletionTokens: 10,- expectedTotalTokens: 40,- },- {- usage: {- total: 100,- },- expectedUnit: null,- expectedPromptTokens: 0,- expectedCompletionTokens: 0,- expectedTotalTokens: 100,- },- {- usage: {- promptTokens: 100,- completionTokens: 200,- totalTokens: 100,- },- expectedPromptTokens: 100,- expectedCompletionTokens: 200,- expectedTotalTokens: 100,- expectedUnit: ModelUsageUnit.Tokens,- },- {- usage: {- totalTokens: 100,- },- expectedPromptTokens: 0,- expectedCompletionTokens: 0,- expectedTotalTokens: 100,- expectedUnit: ModelUsageUnit.Tokens,- },- {- usage: undefined,- expectedPromptTokens: 0,- expectedCompletionTokens: 0,- expectedTotalTokens: 0,- expectedUnit: null,- },- {- usage: null,- expectedPromptTokens: 0,- expectedCompletionTokens: 0,- expectedTotalTokens: 0,- expectedUnit: null,- },- {- usage: {},- expectedPromptTokens: 0,- expectedCompletionTokens: 0,- expectedTotalTokens: 0,- expectedUnit: null,- },- ].forEach((testConfig) => {- it(`should create trace, generation and score without matching models ${JSON.stringify(- testConfig,- )}`, async () => {- const traceId = v4();- const generationId = v4();- const spanId = v4();- const scoreId = v4();-- const response = await makeAPICall("POST", "/api/public/ingestion", {- metadata: {- sdk_verion: "1.0.0",- sdk_name: "python",- },- batch: [- {- id: v4(),- type: "trace-create",- timestamp: new Date().toISOString(),- body: {- id: traceId,- name: "trace-name",- userId: "user-1",- metadata: { key: "value" },- release: "1.0.0",- version: "2.0.0",- tags: ["tag-1", "tag-2"],- },- },- {- id: v4(),- type: "observation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- traceId: traceId,- type: "GENERATION",- name: "generation-name",- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- modelParameters: { key: "value" },- input: { key: "value" },- metadata: { key: "value" },- version: "2.0.0",- },- },- {- id: v4(),- type: "observation-update",- timestamp: new Date().toISOString(),- body: {- id: generationId,- type: "GENERATION",- output: { key: "this is a great gpt output" },- usage: testConfig.usage,- },- },- {- id: v4(),- type: "observation-create",- timestamp: new Date().toISOString(),- body: {- id: spanId,- traceId: traceId,- type: "SPAN",- name: "span-name",- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- input: { input: "value" },- metadata: { meta: "value" },- version: "2.0.0",- },- },- {- id: v4(),- type: "score-create",- timestamp: new Date().toISOString(),- body: {- id: scoreId,- name: "score-name",- value: 100.5,- traceId: traceId,- },- },- ],- });-- expect(response.status).toBe(207);-- const dbTrace = await prisma.trace.findMany({- where: {- name: "trace-name",- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.name).toBe("trace-name");- expect(dbTrace[0]?.release).toBe("1.0.0");- expect(dbTrace[0]?.externalId).toBeNull();- expect(dbTrace[0]?.version).toBe("2.0.0");- expect(dbTrace[0]?.projectId).toBe(- "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- );- expect(dbTrace[0]?.tags).toEqual(["tag-1", "tag-2"]);-- const dbGeneration = await prisma.observation.findUnique({- where: {- id: generationId,- },- });-- expect(dbGeneration?.id).toBe(generationId);- expect(dbGeneration?.traceId).toBe(traceId);- expect(dbGeneration?.name).toBe("generation-name");- expect(dbGeneration?.startTime).toEqual(- new Date("2021-01-01T00:00:00.000Z"),- );- expect(dbGeneration?.endTime).toEqual(- new Date("2021-01-01T00:00:00.000Z"),- );- expect(dbGeneration?.model).toBeNull();- expect(dbGeneration?.modelParameters).toEqual({ key: "value" });- expect(dbGeneration?.input).toEqual({ key: "value" });- expect(dbGeneration?.metadata).toEqual({ key: "value" });- expect(dbGeneration?.version).toBe("2.0.0");- expect(dbGeneration?.internalModel).toBeNull();- expect(dbGeneration?.promptTokens).toEqual(- testConfig.expectedPromptTokens,- );- expect(dbGeneration?.completionTokens).toEqual(- testConfig.expectedCompletionTokens,- );- expect(dbGeneration?.totalTokens).toEqual(testConfig.expectedTotalTokens);- expect(dbGeneration?.unit).toEqual(testConfig.expectedUnit);- expect(dbGeneration?.output).toEqual({- key: "this is a great gpt output",- });-- const dbSpan = await prisma.observation.findUnique({- where: {- id: spanId,- },- });-- expect(dbSpan?.id).toBe(spanId);- expect(dbSpan?.name).toBe("span-name");- expect(dbSpan?.startTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbSpan?.endTime).toEqual(new Date("2021-01-:00:00.000Z"));- expect(dbSpan?.input).toEqual({ input: "value" });- expect(dbSpan?.metadata).toEqual({ meta: "value" });- expect(dbSpan?.version).toBe("2.0.0");-- const dbScore = await prisma.score.findUnique({- where: {- id: scoreId,- },- });-- expect(dbScore?.id).toBe(scoreId);- expect(dbScore?.traceId).toBe(traceId);- expect(dbScore?.name).toBe("score-name");- expect(dbScore?.value).toBe(100.5);- expect(dbScore?.observationId).toBeNull();- expect(dbScore?.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");- });- });-- [- {- observationExternalModel: "gpt-3.5",- observationStartTime: new Date("2021-01-01T00:00:00.000Z"),- modelUnit: ModelUsageUnit.Tokens,- expectedInternalModel: "gpt-3.5-turbo",- expectedPromptTokens: 5,- expectedCompletionTokens: 7,- models: [- {- modelName: "gpt-3.5-turbo",- matchPattern: "(?i)^(gpt-)(35|3.5)(-turbo)?$",- startDate: new Date("2021-01-01T00:00:00.000Z"),- unit: ModelUsageUnit.Tokens,- tokenizerId: "openai",- },- ],- },- {- observationExternalModel: "gpt-3.5",- observationStartTime: new Date("2021-01-01T00:00:00.000Z"),- modelUnit: ModelUsageUnit.Tokens,- expectedInternalModel: "gpt-3.5-turbo",- expectedPromptTokens: 5,- expectedCompletionTokens: 7,- models: [- {- modelName: "gpt-3.5-turbo",- matchPattern: "(?i)^(gpt-)(35|3.5)(-turbo)?$",- startDate: null,- unit: ModelUsageUnit.Tokens,- tokenizerId: "openai",- },- ],- },- {- observationExternalModel: "GPT-3.5",- observationStartTime: new Date("2021-01-01T00:00:00.000Z"),- modelUnit: ModelUsageUnit.Tokens,- expectedInternalModel: "gpt-3.5-turbo",- expectedPromptTokens: 5,- expectedCompletionTokens: 7,- models: [- {- modelName: "gpt-3.5-turbo",- matchPattern: "(?i)^(gpt-)(35|3.5)(-turbo)?$",- startDate: new Date("2021-01-01T00:00:00.000Z"),- unit: ModelUsageUnit.Tokens,- tokenizerId: "openai",- },- ],- },- {- observationExternalModel: "GPT-3.5",- observationStartTime: new Date("2021-01-01T00:00:00.000Z"),- modelUnit: ModelUsageUnit.Tokens,- expectedInternalModel: "gpt-3.5-turbo",- expectedPromptTokens: 5,- expectedCompletionTokens: 7,- models: [- {- modelName: "gpt-3.5-turbo",- matchPattern: "(?i)^(gpt-)(35|3.5)(-turbo)?$",- startDate: new Date("2021-01-01T00:00:00.000Z"),- unit: ModelUsageUnit.Tokens,- tokenizerId: "openai",- },- {- modelName: "gpt-3.5-turbo-new",- matchPattern: "(?i)^(gpt-)(35|3.5)(-turbo)?$",- startDate: new Date("2021-01-01T10:00:00.000Z"),- unit: ModelUsageUnit.Tokens,- tokenizerId: "openai",- },- ],- },- {- observationExternalModel: "GPT-3.5",- observationStartTime: new Date("2021-01-02T00:00:00.000Z"),- modelUnit: ModelUsageUnit.Tokens,- expectedInternalModel: "gpt-3.5-turbo",- expectedPromptTokens: 5,- expectedCompletionTokens: 7,- models: [- {- modelName: "gpt-3.5-turbo-new",- matchPattern: "(?i)^(gpt-)(35|3.5)(-turbo)?$",- startDate: new Date("2021-01-01T00:00:00.000Z"),- unit: ModelUsageUnit.Tokens,- tokenizerId: "openai",- },- {- modelName: "gpt-3.5-turbo",- matchPattern: "(?i)^(gpt-)(35|3.5)(-turbo)?$",- startDate: new Date("2021-01-01T10:00:00.000Z"),- unit: ModelUsageUnit.Tokens,- tokenizerId: "openai",- tokenizerModel: "gpt-3.5-turbo",- },- ],- },- {- observationExternalModel: "ft:gpt-3.5-turbo-1106:my-org:custom_suffix:id",- observationStartTime: new Date("2022-01-01T10:00:00.000Z"),- modelUnit: ModelUsageUnit.Tokens,- expectedInternalModel: "ft:gpt-3.5-turbo-1106",- expectedPromptTokens: 0,- expectedCompletionTokens: 0,- models: [- {- modelName: "ft:gpt-3.5-turbo-1106",- matchPattern: "(?i)^(ft:)(gpt-3.5-turbo-1106:)(.+)(:)(.*)(:)(.+)$",- startDate: new Date("2022-01-01T00:00:00.000Z"),- unit: ModelUsageUnit.Tokens,- tokenizerId: "openai",- },- ],- },- {- observationExternalModel: "ft:babbage-002:my-org#2:custom_suffix-2:id",- observationStartTime: new Date("2022-01-01T10:00:00.000Z"),- modelUnit: ModelUsageUnit.Tokens,- expectedInternalModel: "ft:babbage-002",- expectedPromptTokens: 0,- expectedCompletionTokens: 0,- models: [- {- modelName: "ft:babbage-002",- matchPattern: "(?i)^(ft:)(babbage-002:)(.+)(:)(.*)(:)(.+)$",- startDate: new Date("2022-01-01T00:00:00.000Z"),- unit: ModelUsageUnit.Tokens,- tokenizerId: "openai",- },- ],- },- {- observationExternalModel: "GPT-4",- observationStartTime: new Date("2021-01-01T00:00:00.000Z"),- modelUnit: ModelUsageUnit.Tokens,- expectedInternalModel: null,- expectedPromptTokens: 0,- expectedCompletionTokens: 0,- models: [- {- modelName: "gpt-3.5-turbo",- matchPattern: "(?i)^(gpt-)(35|3.5)(-turbo)?$",- startDate: new Date("2021-01-01T00:00:00.000Z"),- unit: ModelUsageUnit.Tokens,- tokenizerId: "openai",- },- ],- },- {- observationExternalModel: "GPT-3",- observationStartTime: new Date("2021-01-01T00:00:00.000Z"),- modelUnit: ModelUsageUnit.Characters,- expectedInternalModel: null,- expectedPromptTokens: 0,- expectedCompletionTokens: 0,- models: [- {- modelName: "gpt-3.5-turbo",- matchPattern: "(?i)^(gpt-)(35|3.5)(-turbo)?$",- startDate: new Date("2021-01-01T00:00:00.000Z"),- unit: ModelUsageUnit.Tokens,- tokenizerId: "openai",- },- ],- },- ].forEach((testConfig) => {- it(`should match observations to internal models ${JSON.stringify(- testConfig,- )}`, async () => {- const traceId = v4();- const generationId = v4();-- await Promise.all(- testConfig.models.map(async (model) =>- prisma.model.create({- data: {- modelName: model.modelName,- matchPattern: model.matchPattern,- startDate: model.startDate,- unit: model.unit,- tokenizerId: model.tokenizerId,- tokenizerConfig: {- tokensPerMessage: 3,- tokensPerName: 1,- tokenizerModel:- "tokenizerModel" in model- ? model.tokenizerModel- : model.modelName,- },- },- }),- ),- );-- const response = await makeAPICall("POST", "/api/public/ingestion", {- metadata: {- sdk_verion: "1.0.0",- sdk_name: "python",- },- batch: [- {- id: v4(),- type: "trace-create",- timestamp: new Date().toISOString(),- body: {- id: traceId,- name: "trace-name",- },- },- {- id: v4(),- type: "observation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- traceId: traceId,- type: "GENERATION",- name: "generation-name",- startTime: testConfig.observationStartTime.toISOString(),- model: testConfig.observationExternalModel,- usage: {- unit: testConfig.modelUnit,- },- input: "This is a great prompt",- output: "This is a great gpt output",- },- },- ],- });-- expect(response.status).toBe(207);-- const dbGeneration = await prisma.observation.findUnique({- where: {- id: generationId,- },- });-- expect(dbGeneration?.id).toBe(generationId);- expect(dbGeneration?.traceId).toBe(traceId);- expect(dbGeneration?.name).toBe("generation-name");- expect(dbGeneration?.startTime).toEqual(testConfig.observationStartTime);- expect(dbGeneration?.model).toBe(testConfig.observationExternalModel);- expect(dbGeneration?.promptTokens).toBe(testConfig.expectedPromptTokens);- expect(dbGeneration?.completionTokens).toBe(- testConfig.expectedCompletionTokens,- );- expect(dbGeneration?.internalModel).toBe(- testConfig.expectedInternalModel,- );- });- });-- it("should create and update all events", async () => {- const traceId = v4();- const generationId = v4();- const spanId = v4();- const eventId = v4();- const scoreId = v4();-- const exception = `- ERROR langfuse:callback.py:677 'model_name'- Traceback (most recent call last):- File "/Users/maximiliandeichmann/development/github.com/langfuse/langfuse-python/langfuse/callback.py", line 674, in __on_llm_action- model_name = kwargs["invocation_params"]["model_name"]- KeyError: 'model_name'- `;-- const response = await makeAPICall("POST", "/api/public/ingestion", {- batch: [- {- id: v4(),- type: "trace-create",- timestamp: new Date().toISOString(),- body: {- id: traceId,- },- },- {- id: v4(),- type: "span-create",- timestamp: new Date().toISOString(),- body: {- id: spanId,- traceId: traceId,- },- },- {- id: v4(),- type: "span-update",- timestamp: new Date().toISOString(),- body: {- id: spanId,- traceId: traceId,- name: "span-name",- },- },- {- id: v4(),- type: "generation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- traceId: traceId,- parentObservationId: spanId,- modelParameters: { someKey: ["user-1", "user-2"] },- },- },- {- id: v4(),- type: "generation-update",- timestamp: new Date().toISOString(),- body: {- id: generationId,- name: "generation-name",- },- },- {- id: v4(),- type: "event-create",- timestamp: new Date().toISOString(),- body: {- id: eventId,- traceId: traceId,- name: "event-name",- parentObservationId: generationId,- },- },- {- id: v4(),- type: "score-create",- timestamp: new Date().toISOString(),- body: {- id: scoreId,- name: "score-name",- traceId: traceId,- value: 100.5,- observationId: generationId,- },- },- {- id: v4(),- type: "sdk-log",- timestamp: new Date().toISOString(),- body: {- log: exception,- },- },- ],- });-- expect(response.status).toBe(207);-- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");-- const dbSpan = await prisma.observation.findUnique({- where: {- id: spanId,- },- });-- expect(dbSpan?.id).toBe(spanId);- expect(dbSpan?.name).toBe("span-name");- expect(dbSpan?.traceId).toBe(traceId);-- const dbGeneration = await prisma.observation.findUnique({- where: {- id: generationId,- },- });-- expect(dbGeneration?.id).toBe(generationId);- expect(dbGeneration?.traceId).toBe(traceId);- expect(dbGeneration?.name).toBe("generation-name");- expect(dbGeneration?.parentObservationId).toBe(spanId);- expect(dbGeneration?.modelParameters).toEqual({- someKey: ["user-1", "user-2"],- });-- const dbEvent = await prisma.observation.findUnique({- where: {- id: eventId,- },- });-- expect(dbEvent?.id).toBe(eventId);- expect(dbEvent?.traceId).toBe(traceId);- expect(dbEvent?.name).toBe("event-name");- expect(dbEvent?.parentObservationId).toBe(generationId);-- const dbScore = await prisma.score.findUnique({- where: {- id: scoreId,- },- });-- expect(dbScore?.id).toBe(scoreId);- expect(dbScore?.traceId).toBe(traceId);- expect(dbScore?.observationId).toBe(generationId);- expect(dbScore?.value).toBe(100.5);- });-- it("should upsert threats", async () => {- const traceId = v4();-- const responseOne = await makeAPICall("POST", "/api/public/ingestion", {- batch: [- {- id: v4(),- type: "trace-create",- timestamp: new Date().toISOString(),- body: {- id: traceId,- name: "trace-name",- userId: "user-1",- metadata: { key: "value" },- release: "1.0.0",- version: "2.0.0",- tags: ["tag-1", "tag-2", "tag-2"],- },- },- ],- });- expect(responseOne.status).toBe(207);-- const responseTwo = await makeAPICall("POST", "/api/public/ingestion", {- batch: [- {- id: v4(),- type: "trace-create",- timestamp: new Date().toISOString(),- body: {- id: traceId,- name: "trace-name",- userId: "user-2",- tags: ["tag-1", "tag-4", "tag-3"],- },- },- ],- });-- expect(responseTwo.status).toBe(207);-- const dbTrace = await prisma.trace.findMany({- where: {- name: "trace-name",- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.name).toBe("trace-name");- expect(dbTrace[0]?.userId).toBe("user-2");- expect(dbTrace[0]?.release).toBe("1.0.0");- expect(dbTrace[0]?.externalId).toBeNull();- expect(dbTrace[0]?.version).toBe("2.0.0");- expect(dbTrace[0]?.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");- expect(dbTrace[0]?.tags).toEqual(["tag-1", "tag-2", "tag-3", "tag-4"]);- expect(dbTrace[0]?.tags.length).toBe(4);- });-- it("should upsert traces in the right order", async () => {- const traceId = v4();-- const latestEvent = new Date();- const oldEvent = new Date(latestEvent).setSeconds(- latestEvent.getSeconds() - 1,- );-- const responseOne = await makeAPICall("POST", "/api/public/ingestion", {- batch: [- {- id: v4(),- type: "trace-create",- timestamp: latestEvent,- body: {- id: traceId,- name: "trace-name",- userId: "user-1",- },- },- {- id: v4(),- type: "trace-create",- timestamp: oldEvent,- body: {- id: traceId,- name: "trace-name",- userId: "user-2",- },- },- ],- });- expect(responseOne.status).toBe(207);-- const dbTrace = await prisma.trace.findMany({- where: {- name: "trace-name",- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.name).toBe("trace-name");- expect(dbTrace[0]?.userId).toBe("user-1");- expect(dbTrace[0]?.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");- });-- it("should fail for wrong event formats", async () => {- const traceId = v4();- const scoreId = v4();-- const responseOne = await makeAPICall("POST", "/api/public/ingestion", {- batch: [- {- id: "invalid-event",- },- {- id: v4(),- type: "trace-create",- timestamp: new Date().toISOString(),- body: {- id: traceId,- name: "trace-name",- userId: "user-1",- metadata: { key: "value" },- release: "1.0.0",- version: "2.0.0",- },- },- {- id: v4(),- type: "score-create",- timestamp: new Date().toISOString(),- body: {- id: scoreId,- name: "",- traceId: traceId,- },- },- ],- });- expect(responseOne.status).toBe(207);-- expect("errors" in responseOne.body).toBe(true);- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access- expect(responseOne.body.errors.length).toBe(2);- expect("successes" in responseOne.body).toBe(true);- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access- expect(responseOne.body.successes.length).toBe(1);-- const dbTrace = await prisma.trace.findMany({- where: {- name: "trace-name",- },- });-- expect(dbTrace.length).toBe(1);- });-- it("should fail for resource not found", async () => {- const traceId = v4();-- const responseOne = await makeAPICall("POST", "/api/public/ingestion", {- batch: [- {- id: v4(),- type: "trace-create",- timestamp: new Date().toISOString(),- body: {- id: traceId,- name: "trace-name",- userId: "user-1",- metadata: { key: "value" },- release: "1.0.0",- version: "2.0.0",- },- },- {- id: v4(),- type: "observation-update",- timestamp: new Date().toISOString(),- body: {- id: "some-random-id",- type: "GENERATION",- output: { key: "this is a great gpt output" },- },- },- ],- });-- expect(responseOne.status).toBe(207);-- expect("errors" in responseOne.body).toBe(true);- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access- expect(responseOne.body.errors.length).toBe(1);- expect("successes" in responseOne.body).toBe(true);- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access- expect(responseOne.body.successes.length).toBe(1);-- const dbTrace = await prisma.trace.findMany({- where: {- name: "trace-name",- },- });-- expect(dbTrace.length).toBe(1);- });-- it("should fail for long trace name", async () => {- const traceId = v4();-- const baseString =- "Lorem ipsum dolor sit amet, consectetur adipiscing elit. ";- const repeatCount = Math.ceil(1500 / baseString.length);- const name = baseString.repeat(repeatCount);-- const response = await makeAPICall("POST", "/api/public/ingestion", {- batch: [- {- id: v4(),- type: "trace-create",- timestamp: new Date().toISOString(),- body: {- id: traceId,- name,- userId: "user-1",- metadata: { key: "value" },- release: "1.0.0",- version: "2.0.0",- },- },- ],- });-- expect(response.status).toBe(207);- expect("errors" in response.body).toBe(true);- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access- expect(response.body.errors.length).toBe(1);- expect(response.body.errors[0].message).toBe("Invalid request data");- });-- it("should update all token counts if update does not contain model name", async () => {- const traceId = v4();- const generationId = v4();-- await prisma.model.create({- data: {- modelName: "gpt-3.5",- matchPattern: "(?i)^(gpt-)(35|3.5)(-turbo)?$",- startDate: new Date("2021-01-01T00:00:00.000Z"),- unit: ModelUsageUnit.Tokens,- tokenizerId: "openai",- tokenizerConfig: {- tokensPerMessage: 3,- tokensPerName: 1,- tokenizerModel: "gpt-3.5-turbo",- },- },- });-- const responseOne = await makeAPICall("POST", "/api/public/ingestion", {- batch: [- {- id: v4(),- type: "trace-create",- timestamp: new Date().toISOString(),- body: {- id: traceId,- name: "trace-name",- userId: "user-1",- },- },- {- id: v4(),- type: "observation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- traceId: traceId,- type: "GENERATION",- name: "generation-name",- input: { key: "value" },- model: "gpt-3.5",- },- },- {- id: v4(),- type: "observation-update",- timestamp: new Date().toISOString(),- body: {- id: generationId,- type: "GENERATION",- output: { key: "this is a great gpt output" },- },- },- ],- });- expect(responseOne.status).toBe(207);-- const dbTrace = await prisma.trace.findMany({- where: {- name: "trace-name",- },- });-- expect(dbTrace.length).toEqual(1);-- const observation = await prisma.observation.findUnique({- where: {- id: generationId,- },- });-- expect(observation?.output).toEqual({- key: "this is a great gpt output",- });- expect(observation?.input).toEqual({ key: "value" });- expect(observation?.model).toEqual("gpt-3.5");- expect(observation?.output).toEqual({ key: "this is a great gpt output" });- expect(observation?.promptTokens).toEqual(5);- expect(observation?.completionTokens).toEqual(11);- });-- it("should update all token counts if update does not contain model name and events come in wrong order", async () => {- const traceId = v4();- const generationId = v4();-- await prisma.model.create({- data: {- modelName: "gpt-3.5",- matchPattern: "(?i)^(gpt-)(35|3.5)(-turbo)?$",- startDate: new Date("2021-01-01T00:00:00.000Z"),- unit: ModelUsageUnit.Tokens,- tokenizerId: "openai",- tokenizerConfig: {- tokensPerMessage: 3,- tokensPerName: 1,- tokenizerModel: "gpt-3.5-turbo",- },- },- });-- const responseOne = await makeAPICall("POST", "/api/public/ingestion", {- batch: [- {- id: v4(),- type: "trace-create",- timestamp: new Date().toISOString(),- body: {- id: traceId,- name: "trace-name",- userId: "user-1",- },- },- {- id: v4(),- type: "observation-update",- timestamp: new Date().toISOString(),- body: {- id: generationId,- type: "GENERATION",- output: { key: "this is a great gpt output" },- },- },- {- id: v4(),- type: "observation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- traceId: traceId,- type: "GENERATION",- name: "generation-name",- input: { key: "value" },- model: "gpt-3.5",- },- },- ],- });- expect(responseOne.status).toBe(207);-- const dbTrace = await prisma.trace.findMany({- where: {- name: "trace-name",- },- });-- expect(dbTrace.length).toEqual(1);-- const observation = await prisma.observation.findUnique({- where: {- id: generationId,- },- });-- expect(observation?.output).toEqual({- key: "this is a great gpt output",- });- expect(observation?.input).toEqual({ key: "value" });- expect(observation?.model).toEqual("gpt-3.5");- expect(observation?.output).toEqual({ key: "this is a great gpt output" });- expect(observation?.promptTokens).toEqual(5);- expect(observation?.completionTokens).toEqual(11);- });-- it("null does not override set values", async () => {- const traceId = v4();-- const responseOne = await makeAPICall("POST", "/api/public/ingestion", {- batch: [- {- id: v4(),- type: "trace-create",- timestamp: new Date().toISOString(),- body: {- id: traceId,- name: "trace-name",- userId: "user-1",- metadata: { key: "value" },- release: "1.0.0",- version: "2.0.0",- },- },- {- id: v4(),- type: "trace-create",- timestamp: new Date().toISOString(),- body: {- id: traceId,- name: "trace-name",- userId: "user-1",- metadata: { key: "value" },- release: null,- version: null,- },- },- ],- });- expect(responseOne.status).toBe(207);-- const dbTrace = await prisma.trace.findMany({- where: {- name: "trace-name",- },- });-- expect(dbTrace.length).toEqual(1);- expect(dbTrace[0]?.release).toBe("1.0.0");- expect(dbTrace[0]?.version).toBe("2.0.0");- });-- it("should not override a trace from a different project", async () => {- const traceId = v4();- const newProjectId = v4();- await prisma.organization.upsert({- where: { id: "other-org" },- create: { id: "other-org", name: "other-org" },- update: {},- });- await prisma.project.create({- data: {- id: newProjectId,- name: "another-project",- orgId: "other-org",- },- });-- await prisma.trace.create({- data: {- id: traceId,- project: { connect: { id: newProjectId } },- },- });-- const responseOne = await makeAPICall("POST", "/api/public/ingestion", {- batch: [- {- id: v4(),- type: "trace-create",- timestamp: new Date().toISOString(),- body: {- id: traceId,- name: "trace-name",- userId: "user-1",- metadata: { key: "value" },- release: "1.0.0",- version: "2.0.0",- },- },- ],- });- expect(responseOne.status).toBe(207);-- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access- const errors = responseOne.body.errors;-- expect(errors).toBeDefined();- console.log(errors);- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access- expect(errors.length).toBe(1);-- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toEqual(1);- expect(dbTrace[0]?.name).toBeNull();- expect(dbTrace[0]?.release).toBeNull();- expect(dbTrace[0]?.metadata).toBeNull();- expect(dbTrace[0]?.version).toBeNull();- });-- [- {- inputs: [{ a: "a" }, { b: "b" }],- output: { a: "a", b: "b" },- },- {- inputs: [[{ a: "a" }], [{ b: "b" }]],- output: [{ a: "a", b: "b" }],- },- {- inputs: [- {- a: {- "1": 1,- },- },- {- b: "b",- a: {- "2": 2,- },- },- ],- output: { a: { "1": 1, "2": 2 }, b: "b" },- },- {- inputs: [{ a: "a" }, undefined],- output: { a: "a" },- },- {- inputs: [undefined, { b: "b" }],- output: { b: "b" },- },- ].forEach(({ inputs, output }) => {- it(`merges metadata ${JSON.stringify(inputs)}, ${JSON.stringify(- output,- )}`, async () => {- const traceId = v4();- const generationId = v4();-- const responseOne = await makeAPICall("POST", "/api/public/ingestion", {- batch: [- {- id: v4(),- type: "trace-create",- timestamp: new Date().toISOString(),- body: {- id: traceId,- name: "trace-name",- userId: "user-1",- metadata: inputs[0],- },- },- {- id: v4(),- type: "trace-create",- timestamp: new Date().toISOString(),- body: {- id: traceId,- name: "trace-name",- metadata: inputs[1],- },- },- {- id: v4(),- type: "observation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- traceId: traceId,- type: "GENERATION",- name: "generation-name",- metadata: inputs[0],- },- },- {- id: v4(),- type: "observation-update",- timestamp: new Date().toISOString(),- body: {- id: generationId,- traceId: traceId,- type: "GENERATION",- metadata: inputs[1],- },- },- ],- });- expect(responseOne.status).toBe(207);-- const dbTrace = await prisma.trace.findMany({- where: {- name: "trace-name",- },- });-- expect(dbTrace.length).toEqual(1);- expect(dbTrace[0]?.metadata).toEqual(output);-- const dbGeneration = await prisma.observation.findMany({- where: {- name: "generation-name",- },- });-- expect(dbGeneration.length).toEqual(1);- expect(dbGeneration[0]?.metadata).toEqual(output);- });- });-- it("additional fields do not fail the API to support users sending traceidtype Langfuse", async () => {- const traceId = v4();- const generationId = v4();-- const responseOne = await makeAPICall("POST", "/api/public/ingestion", {- batch: [- {- id: v4(),- type: "trace-create",- timestamp: new Date().toISOString(),- body: {- id: traceId,- name: "trace-name",- },- },- {- id: v4(),- type: "observation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- traceId: traceId,- type: "GENERATION",- name: "generation-name",- traceIdType: "LANGFUSE",- },- },- ],- });- expect(responseOne.status).toBe(207);-- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toEqual(1);-- const dbGeneration = await prisma.observation.findUnique({- where: {- id: generationId,- },- });-- expect(dbGeneration).toBeTruthy();- });-- it("filters out NULL characters", async () => {- const traceId = v4();- const generationId = v4();-- const responseOne = await makeAPICall("POST", "/api/public/ingestion", {- batch: [- {- id: v4(),- type: "trace-create",- timestamp: new Date().toISOString(),- body: {- id: traceId,- name: "trace-name",- },- },- {- id: v4(),- type: "observation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- traceId: traceId,- type: "GENERATION",- name: "generation-name",- traceIdType: "LANGFUSE",- input: {- key: "IB\nibo.org Change site\nIB Home / . . . / News / News about the IB / Why ChatGPT is an opportunity for schools IB Home / News / News about the IB / Why ChatGPT is an opportunity for schools Why ChatGPT is an opportunity for schools Published: 06 March 2023 Last updated: 06 June 2023 Date published: 28 February 2023 Dr Matthew Glanville, Head of Assessment Principles and Practice Source: Why ChatGPT is an opportunity for schools | The Times Those of us who work in the schools or exam sector should not be terri \u0000 ed by ChatGPT and the rise of AI software – we should be excited. We should embrace it as an extraordinary opportunity. Contrary to some stark warnings, it is not the end of exams, nor even a huge threat to coursework, but it does bring into very sharp focus the impact that arti \u0000 ",- },- output: {- key: "제점이 있었죠. 그중 하나는 일제가 한국의 신용체계를 망가뜨린 채 한국을 떠났다는 겁니다. 해방전 일제는 조선의 신용체계를 거의 독점적으로 소유한 상황이었습니다. 1945년 6월 기준 일제는 조선의 본점을 둔 전체은행 5개의 불입자본 총액의 89.7%를",- },- },- },- ],- });- expect(responseOne.status).toBe(207);-- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toEqual(1);-- const dbGeneration = await prisma.observation.findUnique({- where: {- id: generationId,- },- });- expect(dbGeneration?.input).toStrictEqual({- key: `IB-ibo.org Change site-IB Home / . . . / News / News about the IB / Why ChatGPT is an opportunity for schools IB Home / News / News about the IB / Why ChatGPT is an opportunity for schools Why ChatGPT is an opportunity for schools Published: 06 March 2023 Last updated: 06 June 2023 Date published: 28 February 2023 Dr Matthew Glanville, Head of Assessment Principles and Practice Source: Why ChatGPT is an opportunity for schools | The Times Those of us who work in the schools or exam sector should not be terri ed by ChatGPT and the rise of AI software – we should be excited. We should embrace it as an extraordinary opportunity. Contrary to some stark warnings, it is not the end of exams, nor even a huge threat to coursework, but it does bring into very sharp focus the impact that arti `,- });- expect(dbGeneration?.output).toStrictEqual({- key: "제점이 있었죠. 그중 하나는 일제가 한국의 신용체계를 망가뜨린 채 한국을 떠났다는 겁니다. 해방전 일제는 조선의 신용체계를 거의 독점적으로 소유한 상황이었습니다. 1945년 6월 기준 일제는 조선의 본점을 둔 전체은행 5개의 불입자본 총액의 89.7%를",- });-- expect(dbGeneration).toBeTruthy();- });-- [- { input: "A\u0000hallo", expected: "Ahallo" },- { input: ["A\u0000hallo"], expected: ["Ahallo"] },- { input: { obj: ["A\u0000hallo"] }, expected: { obj: ["Ahallo"] } },- ].forEach(({ input, expected }) => {- it(`cleans events with null values ${JSON.stringify(- input,- )} ${JSON.stringify(expected)}`, () => {- const cleanedEvent = cleanEvent(input);- expect(cleanedEvent).toStrictEqual(expected);- });- });-- it("should allow score ingestion via Basic auth", async () => {- const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";- const traceId = "trace_id";-- const scoreId = "score_id";- const scoreEventId = "score_event_id";- const scoreName = "score-name";- const scoreValue = 100.5;-- // Seed db with a trace to be scored- await prisma.trace.create({- data: {- id: traceId,- name: "trace-name",- project: { connect: { id: projectId } },- },- });-- const response = await makeAPICall("POST", "/api/public/ingestion", {- batch: [- {- id: scoreEventId,- type: "score-create",- timestamp: new Date().toISOString(),- body: {- id: scoreId,- name: scoreName,- value: scoreValue,- traceId: traceId,- },- },- ],- });-- expect(response.status).toBe(207);- expect(response.body.successes.length).toBe(1);- expect(response.body.successes[0]?.id).toBe(scoreEventId);- expect(response.body.errors.length).toBe(0);-- const dbScore = await prisma.score.findUnique({- where: {- id: scoreId,- },- });-- expect(dbScore?.id).toBe(scoreId);- expect(dbScore?.traceId).toBe(traceId);- expect(dbScore?.name).toBe(scoreName);- expect(dbScore?.value).toBe(scoreValue);- });-- it("should allow score ingestion via Bearer auth", async () => {- const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";- const traceId = "trace_id";- const bearerAuth = "Bearer pk-lf-1234567890";-- const scoreId = "score_id";- const scoreEventId = "score_event_id";- const scoreName = "score-name";- const scoreValue = 100.5;-- // Seed db with a trace to be scored- await prisma.trace.create({- data: {- id: traceId,- name: "trace-name",- project: { connect: { id: projectId } },- },- });-- const response = await makeAPICall(- "POST",- "/api/public/ingestion",- {- batch: [- {- id: scoreEventId,- type: "score-create",- timestamp: new Date().toISOString(),- body: {- id: scoreId,- name: scoreName,- value: scoreValue,- traceId: traceId,- },- },- ],- },- bearerAuth,- );-- expect(response.status).toBe(207);- expect(response.body.successes.length).toEqual(1);- expect(response.body.successes[0]?.id).toBe(scoreEventId);- expect(response.body.errors.length).toBe(0);-- const dbScore = await prisma.score.findUnique({- where: {- id: scoreId,- },- });-- expect(dbScore?.id).toBe(scoreId);- expect(dbScore?.traceId).toBe(traceId);- expect(dbScore?.name).toBe(scoreName);- expect(dbScore?.value).toBe(scoreValue);- });-- it("should throw an Auth error on Bearer Auth for all events that are NOT 'score-create'", async () => {- const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";- const traceId = "trace_id";- const bearerAuth = "Bearer pk-lf-1234567890";-- const scoreId = "score_id";- const scoreEventId = "score_event_id";- const scoreName = "score-name";- const scoreValue = 100.5;-- const generationId = v4();- const spanId = v4();-- const anotherTraceId = "another_trace_id";-- // Seed db with a trace to be scored- await prisma.trace.create({- data: {- id: traceId,- name: "trace-name",- project: { connect: { id: projectId } },- },- });-- const response = await makeAPICall(- "POST",- "/api/public/ingestion",- {- metadata: {- sdk_verion: "1.0.0",- sdk_name: "python",- },- batch: [- {- id: v4(),- type: "trace-create",- timestamp: new Date().toISOString(),- body: {- id: anotherTraceId,- name: "trace-name",- userId: "user-1",- metadata: { key: "value" },- release: "1.0.0",- version: "2.0.0",- tags: ["tag-1", "tag-2"],- },- },- {- id: v4(),- type: "observation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- traceId: traceId,- type: "GENERATION",- name: "generation-name",- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- modelParameters: { key: "value" },- input: { key: "value" },- metadata: { key: "value" },- version: "2.0.0",- },- },- {- id: v4(),- type: "observation-update",- timestamp: new Date().toISOString(),- body: {- id: generationId,- type: "GENERATION",- output: { key: "this is a great gpt output" },- },- },- {- id: v4(),- type: "observation-create",- timestamp: new Date().toISOString(),- body: {- id: spanId,- traceId: traceId,- type: "SPAN",- name: "span-name",- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- input: { input: "value" },- metadata: { meta: "value" },- version: "2.0.0",- },- },- {- id: scoreEventId,- type: "score-create",- timestamp: new Date().toISOString(),- body: {- id: scoreId,- name: "score-name",- value: 100.5,- traceId: traceId,- },- },- ],- },- bearerAuth,- );-- expect(response.status).toBe(207);- expect(response.body.successes.length).toEqual(1);- expect(response.body.successes[0]?.id).toEqual(scoreEventId);-- expect(response.body.errors.length).toEqual(4);-- const dbScore = await prisma.score.findUnique({- where: {- id: scoreId,- },- });-- expect(await prisma.trace.count()).toBe(1);- expect(await prisma.trace.count({ where: { id: traceId } })).toBe(1);- expect(await prisma.observation.count()).toBe(0);-- expect(dbScore?.id).toBe(scoreId);- expect(dbScore?.traceId).toBe(traceId);- expect(dbScore?.name).toBe(scoreName);- expect(dbScore?.value).toBe(scoreValue);- });-- it("should error on wrong input", async () => {- const traceId = "trace_id";- const bearerAuth = "Bearer pk-lf-1234567890";-- const scoreId = "score_id";- const scoreEventId = "score_event_id";- const scoreName = "score-name";- const scoreValue = 100.5;-- const response = await makeAPICall(- "POST",- "/api/public/ingestion",- {- // sending data instead of batch- data: [- {- id: scoreEventId,- type: "score-create",- timestamp: new Date().toISOString(),- body: {- id: scoreId,- name: scoreName,- value: scoreValue,- traceId: traceId,- },- },- ],- },- bearerAuth,- );-- expect(response.status).toBe(400);- expect(await prisma.trace.count()).toBe(0);-- const dbScore = await prisma.score.findUnique({- where: {- id: scoreId,- },- });-- expect(dbScore).toBeNull();- });-});diff --git a/web/src/__tests__/metrics-api.servertest.ts b/web/src/__tests__/metrics-api.servertest.tsdeleted file mode 100644index 6b3f9192b8..0000000000--- a/web/src/__tests__/metrics-api.servertest.ts+++ /dev/null@@ -1,198 +0,0 @@-import {- makeZodVerifiedAPICall,- pruneDatabase,-} from "@/src/__tests__/test-utils";-import { PostGenerationsV1Response } from "@/src/features/public-api/types/generations";-import { GetMetricsDailyV1Response } from "@/src/features/public-api/types/metrics";-import { PostTracesV1Response } from "@/src/features/public-api/types/traces";-import { v4 as uuidv4 } from "uuid";--describe("/api/public/metrics/daily API Endpoint", () => {- beforeEach(async () => await pruneDatabase());- afterEach(async () => await pruneDatabase());-- it("should handle daily metrics correctly", async () => {- // Create traces with observations on different days- const traceId1 = uuidv4();- const traceId2 = uuidv4();- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- id: traceId1,- timestamp: "2021-01-01T00:00:00.000Z",- name: "trace-day-1",- userId: "user-daily-metrics",- projectId: "project-daily-metrics",- },- );- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- id: traceId2,- timestamp: "2021-01-02T00:00:00.000Z",- name: "trace-day-2",- userId: "user-daily-metrics",- projectId: "project-daily-metrics",- },- );-- // Simulate observations with usage metrics on different days- await makeZodVerifiedAPICall(- PostGenerationsV1Response,- "POST",- "/api/public/generations",- {- traceId: traceId1,- model: "modelA",- usage: { input: 100, output: 200, total: 300 },- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:01:00.000Z",- },- );- await makeZodVerifiedAPICall(- PostGenerationsV1Response,- "POST",- "/api/public/generations",- {- traceId: traceId2,- model: "modelB",- usage: { input: 333 },- startTime: "2021-01-02T00:00:00.000Z",- endTime: "2021-01-02T00:02:00.000Z",- },- );- await makeZodVerifiedAPICall(- PostGenerationsV1Response,- "POST",- "/api/public/generations",- {- traceId: traceId2,- model: "modelC",- usage: { input: 666, output: 777, totalCost: 1024.22 },- startTime: "2021-01-02T00:00:00.000Z",- endTime: "2021-01-02T00:04:00.000Z",- },- );- await makeZodVerifiedAPICall(- PostGenerationsV1Response,- "POST",- "/api/public/generations",- {- traceId: traceId2,- usage: { output: 300 },- startTime: "2021-01-02T00:00:00.000Z",- endTime: "2021-01-02T00:04:00.000Z",- },- );-- // Retrieve the daily metrics- const dailyMetricsResponse = await makeZodVerifiedAPICall(- GetMetricsDailyV1Response,- "GET",- `/api/public/metrics/daily`,- );- const dailyMetricsData = dailyMetricsResponse.body.data;-- // Check if the daily metrics are calculated correctly- expect(dailyMetricsData).toHaveLength(2); // Two days of data- if (!dailyMetricsData[0])- throw new Error("dailyMetricsData[0] is undefined");- expect(dailyMetricsData[0].date).toBe("2021-01-02"); // Latest date first- expect(dailyMetricsData[0].countTraces).toBe(1);- expect(dailyMetricsData[0].totalCost).toEqual(1024.22);- expect(dailyMetricsData[0].usage).toEqual([- {- model: "modelB",- inputUsage: 333,- outputUsage: 0,- totalUsage: 333,- countObservations: 1,- countTraces: 1,- totalCost: 0,- },- {- model: "modelC",- inputUsage: 666,- outputUsage: 777,- totalUsage: 1443,- countObservations: 1,- countTraces: 1,- totalCost: 1024.22,- },- {- model: null,- countObservations: 1,- countTraces: 1,- inputUsage: 0,- outputUsage: 300,- totalCost: 0,- totalUsage: 300,- },- ]);-- if (!dailyMetricsData[1])- throw new Error("dailyMetricsData[1] is undefined");- expect(dailyMetricsData[1].date).toBe("2021-01-01");- expect(dailyMetricsData[1].countTraces).toBe(1);- expect(dailyMetricsData[1].totalCost).toEqual(0);- expect(dailyMetricsData[1].usage).toEqual([- {- model: "modelA",- inputUsage: 100,- outputUsage: 200,- totalUsage: 300,- countObservations: 1,- countTraces: 1,- totalCost: 0,- },- ]);- });-- it("should handle daily metrics correctly when there is no data", async () => {- // Retrieve the daily metrics- const dailyMetricsResponse = await makeZodVerifiedAPICall(- GetMetricsDailyV1Response,- "GET",- `/api/public/metrics/daily`,- );- const dailyMetricsData = dailyMetricsResponse.body.data;-- // Check if the daily metrics are calculated correctly- expect(dailyMetricsData).toHaveLength(0); // No data- });-- it("should handle daily metrics correctly when there is just a trace", async () => {- const traceId1 = uuidv4();- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- id: traceId1,- timestamp: "2021-01-01T00:00:00.000Z",- name: "trace-day-1",- userId: "user-daily-metrics",- projectId: "project-daily-metrics",- },- );-- // Retrieve the daily metrics- const dailyMetricsResponse = await makeZodVerifiedAPICall(- GetMetricsDailyV1Response,- "GET",- `/api/public/metrics/daily`,- );- const dailyMetricsData = dailyMetricsResponse.body.data;-- // Check if the daily metrics are calculated correctly- expect(dailyMetricsData).toHaveLength(1);- expect(dailyMetricsData[0].date).toBe("2021-01-01");- expect(dailyMetricsData[0].countTraces).toBe(1);- expect(dailyMetricsData[0].totalCost).toEqual(0);- expect(dailyMetricsData[0].usage).toEqual([]);- });-});diff --git a/web/src/__tests__/prompts.v1.servertest.ts b/web/src/__tests__/prompts.v1.servertest.tsindex a7ddbb574a..d729e4ddb0 100644--- a/web/src/__tests__/prompts.v1.servertest.ts+++ b/web/src/__tests__/prompts.v1.servertest.ts@@ -9,6 +9,7 @@ import {PromptType,type LegacyValidatedPrompt,} from "@/src/features/prompts/server/utils/validation";+import { getObservationById } from "@langfuse/shared/src/server";describe("/api/public/prompts API Endpoint", () => {beforeEach(async () => await pruneDatabase());@@ -411,6 +412,7 @@ describe("/api/public/prompts API Endpoint", () => {const generationId = v4();const promptId = uuidv4();+ const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";await prisma.prompt.create({data: {@@ -420,7 +422,7 @@ describe("/api/public/prompts API Endpoint", () => {labels: ["production"],version: 1,project: {- connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },+ connect: { id: projectId },},createdBy: "user-1",},@@ -459,11 +461,10 @@ describe("/api/public/prompts API Endpoint", () => {expect(response.status).toBe(207);- const dbGeneration = await prisma.observation.findUnique({- where: {- id: generationId,- },- });+ // Delay to allow for async processing+ await new Promise((resolve) => setTimeout(resolve, 500));++ const dbGeneration = await getObservationById(generationId, projectId);expect(dbGeneration?.id).toBe(generationId);expect(dbGeneration?.promptId).toBe(promptId);diff --git a/web/src/__tests__/prompts.v2.servertest.ts b/web/src/__tests__/prompts.v2.servertest.tsindex b72ded3e00..af9c9bf452 100644--- a/web/src/__tests__/prompts.v2.servertest.ts+++ b/web/src/__tests__/prompts.v2.servertest.ts@@ -13,6 +13,7 @@ import {import { nanoid } from "ai";import { type PromptsMetaResponse } from "@/src/features/prompts/server/actions/getPromptsMeta";+import { getObservationById } from "@langfuse/shared/src/server";const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";const baseURI = "/api/public/v2/prompts";@@ -395,11 +396,10 @@ describe("/api/public/v2/prompts API Endpoint", () => {expect(response.status).toBe(207);- const dbGeneration = await prisma.observation.findUnique({- where: {- id: generationId,- },- });+ // Delay to allow for async processing+ await new Promise((resolve) => setTimeout(resolve, 500));++ const dbGeneration = await getObservationById(generationId, projectId);expect(dbGeneration?.id).toBe(generationId);expect(dbGeneration?.promptId).toBe(promptId);diff --git a/web/src/__tests__/scores.servertest.ts b/web/src/__tests__/scores.servertest.tsdeleted file mode 100644index a23b65175b..0000000000--- a/web/src/__tests__/scores.servertest.ts+++ /dev/null@@ -1,791 +0,0 @@-/** @jest-environment node */--import { prisma } from "@langfuse/shared/src/db";-import {- makeAPICall,- makeZodVerifiedAPICall,- pruneDatabase,-} from "@/src/__tests__/test-utils";-import { v4 as uuidv4 } from "uuid";-import { DeleteScoreResponse, GetScoreResponse } from "@langfuse/shared";-import { PostTracesV1Response } from "@/src/features/public-api/types/traces";--const traceId = "de98afa2-89dc-47e9-9924-33f1490fdaf4";--describe("/api/public/scores API Endpoint", () => {- let should_prune_db = true;- beforeEach(async () => {- if (should_prune_db) await pruneDatabase();-- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- id: traceId,- name: "trace-name",- userId: "user-1",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- metadata: { key: "value" },- release: "1.0.0",- version: "2.0.0",- },- );- }, 10000);- afterEach(async () => {- if (should_prune_db) await pruneDatabase();- });-- it("should create score for a trace", async () => {- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.id).toBe(traceId);-- const scoreId = uuidv4();- const createScore = await makeAPICall("POST", "/api/public/scores", {- id: scoreId,- name: "score-name",- value: 100.5,- traceId: traceId,- comment: "comment",- });-- expect(createScore.status).toBe(200);- const fetchedScore = await makeZodVerifiedAPICall(- GetScoreResponse,- "GET",- `/api/public/scores/${scoreId}`,- );-- expect(fetchedScore.body?.id).toBe(scoreId);- expect(fetchedScore.body?.traceId).toBe(traceId);- expect(fetchedScore.body?.name).toBe("score-name");- expect(fetchedScore.body?.value).toBe(100.5);- expect(fetchedScore.body?.observationId).toBeNull();- expect(fetchedScore.body?.comment).toBe("comment");- expect(fetchedScore.body?.source).toBe("API");- expect(fetchedScore.body?.projectId).toBe(- "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- );- });-- it("should create score for a trace with int", async () => {- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.id).toBe(traceId);-- const scoreId = uuidv4();- const createScore = await makeAPICall("POST", "/api/public/scores", {- id: scoreId,- name: "score-name",- value: 100,- traceId: traceId,- });-- expect(createScore.status).toBe(200);- const fetchedScore = await makeZodVerifiedAPICall(- GetScoreResponse,- "GET",- `/api/public/scores/${scoreId}`,- );-- expect(fetchedScore.body?.id).toBe(scoreId);- expect(fetchedScore.body?.traceId).toBe(traceId);- expect(fetchedScore.body?.name).toBe("score-name");- expect(fetchedScore.body?.value).toBe(100);- expect(fetchedScore.body?.observationId).toBeNull();- });-- it("should create score for a generation", async () => {- await pruneDatabase();-- const generationId = uuidv4();-- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/generations",- {- id: generationId,- name: "generation-name",- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- model: "model-name",- modelParameters: { key: "value" },- prompt: { key: "value" },- metadata: { key: "value" },- version: "2.0.0",- },- );-- const dbGeneration = await prisma.observation.findMany({- where: {- id: generationId,- },- });-- expect(dbGeneration.length).toBeGreaterThan(0);- expect(dbGeneration[0]?.id).toBe(generationId);-- const scoreId = uuidv4();- const scoreData = {- id: scoreId,- name: "score-name",- value: 100,- traceId: dbGeneration[0]!.traceId!,- observationId: dbGeneration[0]!.id,- };- const createScore = await makeAPICall(- "POST",- "/api/public/scores",- scoreData,- );-- expect(createScore.status).toBe(200);- const fetchedScore = await makeZodVerifiedAPICall(- GetScoreResponse,- "GET",- `/api/public/scores/${scoreId}`,- );-- expect(fetchedScore.body).toMatchObject(scoreData);- });-- it("should create numeric score if value is integer and no data type is passed", async () => {- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.id).toBe(traceId);-- const scoreId = uuidv4();- const scoreData = {- id: scoreId,- name: "accuracy",- value: 1,- traceId,- };- const createScore = await makeAPICall(- "POST",- "/api/public/scores",- scoreData,- );-- expect(createScore.status).toBe(200);- const fetchedScore = await makeZodVerifiedAPICall(- GetScoreResponse,- "GET",- `/api/public/scores/${scoreId}`,- );-- expect(fetchedScore.body).toMatchObject({- ...scoreData,- dataType: "NUMERIC",- });- });-- it("should create categorical score if value is string and no data type is passed", async () => {- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.id).toBe(traceId);-- const scoreId = uuidv4();- const scoreData = {- id: scoreId,- name: "accuracy",- value: "Good",- traceId,- };- const createScore = await makeAPICall(- "POST",- "/api/public/scores",- scoreData,- );-- expect(createScore.status).toBe(200);- const fetchedScore = await makeZodVerifiedAPICall(- GetScoreResponse,- "GET",- `/api/public/scores/${scoreId}`,- );-- expect(fetchedScore.body).toMatchObject({- ...scoreData,- value: null,- stringValue: "Good",- dataType: "CATEGORICAL",- });- });-- it("should create boolean score if boolean data type is passed", async () => {- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.id).toBe(traceId);-- const scoreId = uuidv4();- const scoreData = {- id: scoreId,- name: "score-name",- value: 1,- dataType: "BOOLEAN",- traceId,- };- const createScore = await makeAPICall(- "POST",- "/api/public/scores",- scoreData,- );-- expect(createScore.status).toBe(200);-- const fetchedScore = await makeZodVerifiedAPICall(- GetScoreResponse,- "GET",- `/api/public/scores/${scoreId}`,- );-- expect(fetchedScore.body).toMatchObject({- ...scoreData,- stringValue: "True",- });- });-- it("should infer boolean data type from boolean score config", async () => {- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.id).toBe(traceId);-- await makeAPICall("POST", "/api/public/score-configs", {- name: "accuracy",- dataType: "BOOLEAN",- });-- const dbScoreConfig = await prisma.scoreConfig.findMany({- where: {- name: "accuracy",- },- });-- expect(dbScoreConfig.length).toBeGreaterThan(0);- expect(dbScoreConfig[0]?.name).toBe("accuracy");-- const scoreId = uuidv4();- const scoreData = {- id: scoreId,- name: "accuracy",- value: 1,- configId: dbScoreConfig[0].id,- traceId,- };- const createScore = await makeAPICall(- "POST",- "/api/public/scores",- scoreData,- );-- expect(createScore.status).toBe(200);- const fetchedScore = await makeZodVerifiedAPICall(- GetScoreResponse,- "GET",- `/api/public/scores/${scoreId}`,- );-- expect(fetchedScore.body).toMatchObject({- ...scoreData,- stringValue: "True",- dataType: "BOOLEAN",- });- });-- it("should NOT create categorical score if numeric data type is passed", async () => {- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.id).toBe(traceId);-- const scoreId = uuidv4();- const scoreData = {- id: scoreId,- name: "accuracy",- value: 1,- dataType: "CATEGORICAL",- traceId,- };- const createScore = await makeAPICall(- "POST",- "/api/public/scores",- scoreData,- );-- expect(createScore.status).toBe(400);- expect(createScore.body).toMatchObject({- message: "Invalid request data",- error: [- {- code: "invalid_type",- expected: "string",- message: "Expected string, received number",- path: ["value"],- received: "number",- },- ],- });- });-- it("should NOT create numeric score if categorical data type is passed incl numeric config", async () => {- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.id).toBe(traceId);-- await makeAPICall("POST", "/api/public/score-configs", {- name: "accuracy",- dataType: "NUMERIC",- });-- const dbScoreConfig = await prisma.scoreConfig.findMany({- where: {- name: "accuracy",- },- });-- expect(dbScoreConfig.length).toBeGreaterThan(0);- expect(dbScoreConfig[0]?.name).toBe("accuracy");-- const scoreId = uuidv4();- const scoreData = {- id: scoreId,- name: "accuracy",- value: "Good",- configId: dbScoreConfig[0].id,- dataType: "CATEGORICAL",- traceId,- };- const createScore = await makeAPICall(- "POST",- "/api/public/scores",- scoreData,- );-- expect(createScore.status).toBe(400);- expect(createScore.body).toMatchObject({- message:- "Data type mismatch based on config: expected NUMERIC, got CATEGORICAL",- });- });-- it("should NOT create numeric score if config and passed data type mismatch", async () => {- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.id).toBe(traceId);-- await makeAPICall("POST", "/api/public/score-configs", {- name: "accuracy",- dataType: "CATEGORICAL",- categories: [- { label: "One", value: 1 },- { label: "Zero", value: 0 },- ],- });-- const dbScoreConfig = await prisma.scoreConfig.findMany({- where: {- name: "accuracy",- },- });-- expect(dbScoreConfig.length).toBeGreaterThan(0);- expect(dbScoreConfig[0]?.name).toBe("accuracy");-- const scoreId = uuidv4();- const scoreData = {- id: scoreId,- name: "accuracy",- value: 1,- configId: dbScoreConfig[0].id,- dataType: "NUMERIC",- traceId,- };- const createScore = await makeAPICall(- "POST",- "/api/public/scores",- scoreData,- );-- expect(createScore.status).toBe(400);- expect(createScore.body).toMatchObject({- message:- "Data type mismatch based on config: expected CATEGORICAL, got NUMERIC",- });- });-- it("should NOT create boolean score if string value is passed", async () => {- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.id).toBe(traceId);-- await makeAPICall("POST", "/api/public/score-configs", {- name: "accuracy",- dataType: "BOOLEAN",- });-- const dbScoreConfig = await prisma.scoreConfig.findMany({- where: {- name: "accuracy",- },- });-- expect(dbScoreConfig.length).toBeGreaterThan(0);- expect(dbScoreConfig[0]?.name).toBe("accuracy");-- const scoreId = uuidv4();- const scoreData = {- id: scoreId,- name: "accuracy",- value: "True",- configId: dbScoreConfig[0].id,- dataType: "BOOLEAN",- traceId,- };- const createScore = await makeAPICall(- "POST",- "/api/public/scores",- scoreData,- );-- expect(createScore.status).toBe(400);- expect(createScore.body).toMatchObject({- message: "Invalid request data",- error: [- {- code: "invalid_type",- expected: "number",- message: "Expected number, received string",- path: ["value"],- received: "string",- },- ],- });- });-- it("should NOT create boolean score with value other than 1 | 0", async () => {- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.id).toBe(traceId);-- await makeAPICall("POST", "/api/public/score-configs", {- name: "accuracy",- dataType: "BOOLEAN",- });-- const dbScoreConfig = await prisma.scoreConfig.findMany({- where: {- name: "accuracy",- },- });-- expect(dbScoreConfig.length).toBeGreaterThan(0);- expect(dbScoreConfig[0]?.name).toBe("accuracy");-- const scoreId = uuidv4();- const scoreData = {- id: scoreId,- name: "accuracy",- value: 0.5,- configId: dbScoreConfig[0].id,- dataType: "BOOLEAN",- traceId,- };- const createScore = await makeAPICall(- "POST",- "/api/public/scores",- scoreData,- );-- expect(createScore.status).toBe(400);- expect(createScore.body).toMatchObject({- message: "Invalid request data",- error: [- {- code: "custom",- message:- "Value must be a number equal to either 0 or 1 for data type BOOLEAN",- path: ["value"],- },- ],- });- });-- it("should NOT create categorical score with value not defined in config.categories", async () => {- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.id).toBe(traceId);-- await makeAPICall("POST", "/api/public/score-configs", {- name: "accuracy",- dataType: "CATEGORICAL",- categories: [- { label: "One", value: 1 },- { label: "Zero", value: 0 },- ],- });-- const dbScoreConfig = await prisma.scoreConfig.findMany({- where: {- name: "accuracy",- },- });-- expect(dbScoreConfig.length).toBeGreaterThan(0);- expect(dbScoreConfig[0]?.name).toBe("accuracy");-- const scoreId = uuidv4();- const scoreData = {- id: scoreId,- name: "accuracy",- value: 1,- configId: dbScoreConfig[0].id,- dataType: "CATEGORICAL",- traceId,- };- const createScore = await makeAPICall(- "POST",- "/api/public/scores",- scoreData,- );-- expect(createScore.status).toBe(400);- expect(createScore.body).toMatchObject({- message: "Invalid request data",- error: [- {- code: "invalid_type",- expected: "string",- message: "Expected string, received number",- path: ["value"],- received: "number",- },- ],- });- });-- it("should NOT create numeric score outside of defined range", async () => {- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.id).toBe(traceId);-- await makeAPICall("POST", "/api/public/score-configs", {- name: "accuracy",- dataType: "NUMERIC",- maxValue: 0,- });-- const dbScoreConfig = await prisma.scoreConfig.findMany({- where: {- name: "accuracy",- },- });-- expect(dbScoreConfig.length).toBeGreaterThan(0);- expect(dbScoreConfig[0]?.name).toBe("accuracy");-- const scoreId = uuidv4();- const scoreData = {- id: scoreId,- name: "accuracy",- value: 0.5,- configId: dbScoreConfig[0].id,- dataType: "NUMERIC",- traceId,- };- const createScore = await makeAPICall(- "POST",- "/api/public/scores",- scoreData,- );-- expect(createScore.status).toBe(400);- expect(createScore.body).toMatchObject({- message:- "Ingested score body not valid against provided config: - Value exceeds maximum value of 0 defined in config",- });- });-- it("should upsert a score", async () => {- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.id).toBe(traceId);-- const generationId = uuidv4();- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/generations",- {- id: generationId,- name: "generation-name",- traceId,- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- model: "model-name",- modelParameters: { key: "value" },- prompt: { key: "value" },- metadata: { key: "value" },- version: "2.0.0",- },- );-- const dbGeneration = await prisma.observation.findMany({- where: {- id: generationId,- },- });-- expect(dbGeneration.length).toBeGreaterThan(0);- expect(dbGeneration[0]?.id).toBe(generationId);-- const scoreId = uuidv4();- const createScore = await makeAPICall("POST", "/api/public/scores", {- id: scoreId,- name: "score-name",- value: 100,- traceId: traceId,- comment: "comment",- });- expect(createScore.status).toBe(200);-- const upsertScore = await makeAPICall("POST", "/api/public/scores", {- id: scoreId,- traceId: traceId,- name: "score-name-updated",- value: 200,- comment: "comment-updated",- observationId: dbGeneration[0]!.id,- });- expect(upsertScore.status).toBe(200);-- const fetchedScore = await makeZodVerifiedAPICall(- GetScoreResponse,- "GET",- `/api/public/scores/${scoreId}`,- );-- expect(fetchedScore.body?.id).toBe(scoreId);- expect(fetchedScore.body?.traceId).toBe(traceId);- expect(fetchedScore.body?.name).toBe("score-name-updated");- expect(fetchedScore.body?.value).toBe(200);- expect(fetchedScore.body?.comment).toBe("comment-updated");- expect(fetchedScore.body?.observationId).toBe(dbGeneration[0]!.id);- });-- it("should delete a score", async () => {- await pruneDatabase();-- const traceId = uuidv4();-- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- id: traceId,- },- );-- const scoreId = uuidv4();- const createScore = await makeAPICall("POST", "/api/public/scores", {- id: scoreId,- name: "score-name",- value: 100.5,- traceId: traceId,- comment: "comment",- });-- expect(createScore.status).toBe(200);- const fetchedScore = await makeZodVerifiedAPICall(- GetScoreResponse,- "GET",- `/api/public/scores/${scoreId}`,- );- expect(fetchedScore.body.id).toBe(scoreId);-- const deleteScore = await makeZodVerifiedAPICall(- DeleteScoreResponse,- "DELETE",- `/api/public/scores/${scoreId}`,- );- expect(deleteScore.status).toBe(200);- const deletedScore = await prisma.score.findUnique({- where: {- id: scoreId,- },- });- expect(deletedScore).toBeNull();- });-});diff --git a/web/src/__tests__/server/api/routers/traces.servertest.ts b/web/src/__tests__/server/api/routers/traces.servertest.tsdeleted file mode 100644index 9fa192941a..0000000000--- a/web/src/__tests__/server/api/routers/traces.servertest.ts+++ /dev/null@@ -1,145 +0,0 @@-/** @jest-environment node */-import { pruneDatabase } from "@/src/__tests__/test-utils";-import { appRouter } from "@/src/server/api/root";-import { createInnerTRPCContext } from "@/src/server/api/trpc";-import { prisma } from "@langfuse/shared/src/db";-import type { Session } from "next-auth";--describe("Traces TRPC Router", () => {- beforeEach(async () => await pruneDatabase());- afterEach(async () => await pruneDatabase());-- const session: Session = {- expires: "1",- user: {- id: "clgb17vnp000008jjere5g15i",- name: "John Doe",- organizations: [- {- id: "seed-org-id",- role: "OWNER",- plan: "cloud:hobby",- cloudConfig: undefined,- projects: [- {- id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- role: "ADMIN",- },- ],- },- ],- featureFlags: {- templateFlag: true,- },- admin: true,- },- environment: {} as any,- };-- const ctx = createInnerTRPCContext({ session });- const caller = appRouter.createCaller({ ...ctx, prisma });-- test("traces.all RPC returns an array of traces", async () => {- const trace = {- name: "trace-name",- userId: "user-1",- release: "1.0.0",- version: "2.0.0",- };- await prisma.trace.create({- data: { ...trace, projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },- });-- const traces = await caller.traces.all({- page: 0,- limit: 10,- // projectId from `seed.ts`- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- filter: null,- searchQuery: "",- orderBy: null,- });- expect(traces).toBeDefined();- expect(traces).toMatchObject({ traces: [trace] });- });-- test("traces.all RPC must not return input, output, metadata", async () => {- const trace = {- name: "trace-name",- userId: "user-1",- input: { a: 1 },- output: { b: 2 },- metadata: { c: 3 },- release: "1.0.0",- version: "2.0.0",- };- await prisma.trace.create({- data: { ...trace, projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },- });-- const traces = await caller.traces.all({- page: 0,- limit: 10,- // projectId from `seed.ts`- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- filter: null,- searchQuery: "",- orderBy: null,- });- expect(traces.traces).toBeDefined();- expect(traces.traces).toHaveLength(1);-- const returnedTrace = traces.traces[0];- expect(returnedTrace).not.toHaveProperty("input");- expect(returnedTrace).not.toHaveProperty("output");- expect(returnedTrace).not.toHaveProperty("metadata");- });-- test("traces.all RPC orders traces by userId", async () => {- const traceTmpl = {- name: "trace-name",- userId: "user-1",- release: "1.0.0",- version: "2.0.0",- };- const trace1 = traceTmpl;- const trace2 = { ...traceTmpl, userId: "user-2" };- await prisma.trace.create({- data: { ...traceTmpl, projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },- });- await prisma.trace.create({- data: {- ...trace2,- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- },- });-- const tracesASC = await caller.traces.all({- page: 0,- limit: 10,- // projectId from `seed.ts`- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- filter: null,- searchQuery: "",- orderBy: {- column: "userId",- order: "ASC",- },- });- expect(tracesASC).toMatchObject({ traces: [trace1, trace2] });-- const tracesDESC = await caller.traces.all({- page: 0,- limit: 10,- // projectId from `seed.ts`- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- filter: null,- searchQuery: "",- orderBy: {- column: "userId",- order: "DESC",- },- });- expect(tracesDESC).toMatchObject({ traces: [trace2, trace1] });- });-});diff --git a/web/src/__tests__/sessions.servertest.ts b/web/src/__tests__/sessions.servertest.tsindex 459a61c242..e0d5d8a7c9 100644--- a/web/src/__tests__/sessions.servertest.ts+++ b/web/src/__tests__/sessions.servertest.ts@@ -25,6 +25,9 @@ describe("Create and get sessions", () => {},);+ // Delay to allow for async processing+ await new Promise((resolve) => setTimeout(resolve, 500));+const dbSession = await prisma.traceSession.findFirst({where: {id: "session-id",diff --git a/web/src/__tests__/spans.servertest.ts b/web/src/__tests__/spans.servertest.tsdeleted file mode 100644index 7afa8d2498..0000000000--- a/web/src/__tests__/spans.servertest.ts+++ /dev/null@@ -1,376 +0,0 @@-/** @jest-environment node */--import { prisma } from "@langfuse/shared/src/db";-import {- makeAPICall,- makeZodVerifiedAPICall,- pruneDatabase,-} from "@/src/__tests__/test-utils";-import { v4 as uuidv4 } from "uuid";-import { PostTracesV1Response } from "@/src/features/public-api/types/traces";-import {- PatchSpansV1Response,- PostSpansV1Response,-} from "@/src/features/public-api/types/spans";--describe("/api/public/spans API Endpoint", () => {- beforeEach(async () => await pruneDatabase());- afterEach(async () => await pruneDatabase());-- it("should create span after trace", async () => {- const traceId = uuidv4();-- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- id: traceId,- name: "trace-name",- userId: "user-1",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- metadata: { key: "value" },- release: "1.0.0",- version: "2.0.0",- },- );-- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.id).toBe(traceId);-- const spanId = uuidv4();- const createSpan = await makeZodVerifiedAPICall(- PostSpansV1Response,- "POST",- "/api/public/spans",- {- id: spanId,- traceId: traceId,- name: "span-name",- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- input: { input: "value" },- metadata: { meta: "value" },- version: "2.0.0",- },- );-- expect(createSpan.status).toBe(200);- const dbSpan = await prisma.observation.findUnique({- where: {- id: spanId,- },- });-- expect(dbSpan?.id).toBe(spanId);- expect(dbSpan?.traceId).toBe(traceId);- expect(dbSpan?.name).toBe("span-name");- expect(dbSpan?.startTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbSpan?.endTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbSpan?.input).toEqual({ input: "value" });- expect(dbSpan?.metadata).toEqual({ meta: "value" });- expect(dbSpan?.version).toBe("2.0.0");- });-- it("should create span before trace", async () => {- const traceId = uuidv4();- const spanId = uuidv4();-- const createSpan = await makeZodVerifiedAPICall(- PostSpansV1Response,- "POST",- "/api/public/spans",- {- id: spanId,- traceId: traceId,- name: "span-name",- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- input: { input: "value" },- metadata: { meta: "value" },- version: "2.0.0",- },- );-- expect(createSpan.status).toBe(200);- const dbSpan = await prisma.observation.findUnique({- where: {- id: spanId,- },- });-- expect(dbSpan?.id).toBe(spanId);- expect(dbSpan?.traceId).toBe(traceId);- expect(dbSpan?.name).toBe("span-name");- expect(dbSpan?.startTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbSpan?.endTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbSpan?.input).toEqual({ input: "value" });- expect(dbSpan?.metadata).toEqual({ meta: "value" });- expect(dbSpan?.version).toBe("2.0.0");-- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- id: traceId,- name: "trace-name",- userId: "user-1",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- metadata: { key: "value" },- release: "1.0.0",- version: "2.0.0",- },- );-- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,- },- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.id).toBe(traceId);- });-- it("should create span after trace ignoring externalId", async () => {- const traceId = uuidv4();- const spanId = uuidv4();-- const response = await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- externalId: uuidv4(),- id: traceId,- name: "trace-name",- userId: "user-1",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- },- );- expect(response.status).toBe(200);- const createSpan = await makeZodVerifiedAPICall(- PostSpansV1Response,- "POST",- "/api/public/spans",- {- id: spanId,- name: "spanName",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- traceId: traceId,- externalTraceIdType: "EXTERNAL",- },- );- expect(createSpan.status).toBe(200);-- const dbSpan = await prisma.observation.findFirstOrThrow({- where: {- name: "spanName",- },- });- expect(dbSpan.id).toBe(spanId);- expect(dbSpan.traceId).toBe(traceId);- });-- it("should create trace when creating span without existing trace", async () => {- const spanName = uuidv4();-- const spanId = uuidv4();- const createSpan = await makeZodVerifiedAPICall(- PostSpansV1Response,- "POST",- "/api/public/spans",- {- id: spanId,- name: spanName,- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- input: { input: "value" },- metadata: { meta: "value" },- version: "2.0.0",- },- );-- const dbTrace = await prisma.trace.findMany({- where: {- name: spanName,- },- });-- expect(dbTrace.length).toBe(1);- expect(dbTrace[0]?.name).toBe(spanName);-- expect(createSpan.status).toBe(200);- const dbSpan = await prisma.observation.findUnique({- where: {- id: spanId,- },- });-- expect(dbSpan?.id).toBe(spanId);- expect(dbSpan?.traceId).toBe(dbTrace[0]?.id);- expect(dbSpan?.name).toBe(spanName);- expect(dbSpan?.startTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbSpan?.endTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbSpan?.input).toEqual({ input: "value" });- expect(dbSpan?.metadata).toEqual({ meta: "value" });- expect(dbSpan?.version).toBe("2.0.0");- });-- it("should create trace when creating span without existing trace with externalId", async () => {- const spanName = uuidv4();-- const spanId = uuidv4();- const traceId = uuidv4();- const createSpan = await makeZodVerifiedAPICall(- PostSpansV1Response,- "POST",- "/api/public/spans",- {- id: spanId,- traceIdType: "EXTERNAL",- traceId: traceId,- name: spanName,- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- input: { input: "value" },- metadata: { meta: "value" },- version: "2.0.0",- },- );-- expect(createSpan.status).toBe(200);-- const dbSpan = await prisma.observation.findMany({- where: {- name: spanName,- },- });- expect(dbSpan.length).toBe(1);- expect(dbSpan[0]?.name).toBe(spanName);- expect(dbSpan[0]?.id).toBe(spanId);- expect(dbSpan[0]?.traceId).toBe(traceId);-- const dbTraces = await prisma.trace.findMany();- expect(dbTraces.length).toBe(0);- });-- it("should create trace when creating span without existing trace without traceId", async () => {- const generationName = uuidv4();-- const spanId = uuidv4();- const createSpan = await makeZodVerifiedAPICall(- PostSpansV1Response,- "POST",- "/api/public/spans",- {- id: spanId,- name: generationName,- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- input: { key: "value" },- metadata: { key: "value" },- version: "2.0.0",- },- );-- const dbSpan = await prisma.observation.findFirstOrThrow({- where: {- name: generationName,- },- });-- const dbTrace = await prisma.trace.findMany({- where: {- id: dbSpan.traceId!,- },- });-- expect(dbTrace.length).toBe(1);- expect(dbTrace[0]?.name).toBe(generationName);-- expect(createSpan.status).toBe(200);-- expect(dbSpan.id).toBe(spanId);- expect(dbSpan.traceId).toBe(dbTrace[0]?.id);- expect(dbSpan.name).toBe(generationName);- expect(dbSpan.startTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbSpan.endTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbSpan.input).toEqual({ key: "value" });- expect(dbSpan.metadata).toEqual({ key: "value" });- expect(dbSpan.version).toBe("2.0.0");- });-- it("should update span", async () => {- const spanName = uuidv4();-- const spanId = uuidv4();- const createSpan = await makeZodVerifiedAPICall(- PostSpansV1Response,- "POST",- "/api/public/spans",- {- id: spanId,- name: spanName,- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- input: { input: "value" },- metadata: { meta: "value" },- version: "2.0.0",- },- );-- expect(createSpan.status).toBe(200);-- const updatedSpan = await makeZodVerifiedAPICall(- PatchSpansV1Response,- "PATCH",- "/api/public/spans",- {- spanId: spanId,- output: { key: "this is a great gpt output" },- },- );- expect(updatedSpan.status).toBe(200);-- const dbSpan = await prisma.observation.findUnique({- where: {- id: spanId,- },- });-- expect(dbSpan?.id).toBe(spanId);- expect(dbSpan?.name).toBe(spanName);- expect(dbSpan?.startTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbSpan?.endTime).toEqual(new Date("2021-01-:00:00.000Z"));- expect(dbSpan?.input).toEqual({ input: "value" });- expect(dbSpan?.output).toEqual({ key: "this is a great gpt output" });- expect(dbSpan?.metadata).toEqual({ meta: "value" });- expect(dbSpan?.version).toBe("2.0.0");- });-- it("should not upsert span if span does not exist", async () => {- const spanId = uuidv4();-- const updatedSpan = await makeAPICall("PATCH", "/api/public/spans", {- spanId: spanId,- output: { key: "this is a great gpt output" },- });- expect(updatedSpan.status).toBe(404);-- const dbSpan = await prisma.observation.findUnique({- where: {- id: spanId,- },- });-- expect(dbSpan).toBeNull();- });-});diff --git a/web/src/__tests__/tokenCost.servertest.ts b/web/src/__tests__/tokenCost.servertest.tsdeleted file mode 100644index 915e0d2a8d..0000000000--- a/web/src/__tests__/tokenCost.servertest.ts+++ /dev/null@@ -1,1408 +0,0 @@-import { nanoid } from "ai";-import Decimal from "decimal.js";-import { v4 as uuidv4 } from "uuid";--import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";-import { ModelUsageUnit } from "@langfuse/shared";-import { prisma } from "@langfuse/shared/src/db";-import { ObservationProcessor } from "@langfuse/shared/src/server";--describe("Token Cost Calculation", () => {- const modelName = "gpt-test-" + nanoid();- const matchPattern = `(?i)^(${modelName})$`;- const traceId = uuidv4();- const generationId = uuidv4();- const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";-- const tokenModelData = {- id: uuidv4(),- modelName,- matchPattern,- inputPrice: 0.01,- outputPrice: 0.02,- totalPrice: 0.03,- unit: ModelUsageUnit.Tokens,- tokenizerId: "openai",- tokenizerConfig: {- tokensPerName: 1,- tokenizerModel: "gpt-4o",- tokensPerMessage: 3,- },- };-- const imageModelData = {- id: uuidv4(),- modelName,- matchPattern,- inputPrice: 1,- outputPrice: 2,- totalPrice: 3,- unit: ModelUsageUnit.Images,- tokenizerId: "openai",- tokenizerConfig: {- tokensPerName: 1,- tokenizerModel: "gpt-4o",- tokensPerMessage: 3,- },- };-- beforeEach(async () => {- await pruneDatabase();- await Promise.all([- prisma.model.create({- data: tokenModelData,- }),- prisma.model.create({- data: imageModelData,- }),- prisma.trace.create({- data: {- id: traceId,- projectId,- },- }),- ]);- });-- it("should correctly calculate token costs with provided model prices", async () => {- const model = {- inputPrice: new Decimal(0.01),- outputPrice: new Decimal(0.02),- totalPrice: new Decimal(0.03),- };-- const tokenCounts = {- input: 100,- output: 200,- total: 300,- };-- const userProvidedCosts = {- inputCost: null,- outputCost: null,- totalCost: null,- };-- const costs = ObservationProcessor.calculateTokenCosts(- model as any,- userProvidedCosts,- tokenCounts,- );-- expect(costs.inputCost?.toNumber()).toBe(1.0); // 100 tokens * 0.01- expect(costs.outputCost?.toNumber()).toBe(4.0); // 200 tokens * 0.02- expect(costs.totalCost?.toNumber()).toBe(9.0); // 300 tokens * 0.03- });-- it("should correctly calculate token costs with user provided costs", async () => {- const model = {- inputPrice: new Decimal(0.01),- outputPrice: new Decimal(0.02),- totalPrice: new Decimal(0.03),- };-- const tokenCounts = {- input: 100,- output: 200,- total: 300,- };-- const userProvidedCosts = {- inputCost: new Decimal(2.0),- outputCost: new Decimal(3.0),- totalCost: new Decimal(5.0),- };-- const costs = ObservationProcessor.calculateTokenCosts(- model as any,- userProvidedCosts,- tokenCounts,- );-- expect(costs.inputCost?.toNumber()).toBe(2.0); // Overridden by user provided cost- expect(costs.outputCost?.toNumber()).toBe(3.0); // Overridden by user provided cost- expect(costs.totalCost?.toNumber()).toBe(5.0); // Overridden by user provided cost- });-- it("should correctly calculate token costs when only some user provided costs are given", async () => {- const model = {- inputPrice: new Decimal(1),- outputPrice: new Decimal(1),- };-- const data = [- // missing total- {- userProvidedCosts: {- input: 1,- output: 2,- total: undefined,- },- expectedCost: {- input: 1,- output: 2,- total: 3,- },- },- // only total- {- userProvidedCosts: {- input: undefined,- output: undefined,- total: 2,- },- expectedCost: {- input: undefined,- output: undefined,- total: 2,- },- },- // missing input- {- userProvidedCosts: {- input: undefined,- output: 2,- total: 2,- },- expectedCost: {- input: undefined,- output: 2,- total: 2,- },- },- // only input- {- userProvidedCosts: {- input: 1,- output: undefined,- total: undefined,- },- expectedCost: {- input: 1,- output: undefined,- total: 1,- },- },-- // missing output- {- userProvidedCosts: {- input: 1,- output: undefined,- total: 1,- },- expectedCost: {- input: 1,- output: undefined,- total: 1,- },- },-- // only output- {- userProvidedCosts: {- input: undefined,- output: 2,- total: undefined,- },- expectedCost: {- input: undefined,- output: 2,- total: 2,- },- },- ];-- for (const { userProvidedCosts, expectedCost } of data) {- const tokenCounts = {- input: 0,- output: 0,- total: 0,- };-- const userProvidedCostsDecimal = {- inputCost:- userProvidedCosts.input && new Decimal(userProvidedCosts.input),- outputCost:- userProvidedCosts.output && new Decimal(userProvidedCosts.output),- totalCost:- userProvidedCosts.total && new Decimal(userProvidedCosts.total),- };-- const costs = ObservationProcessor.calculateTokenCosts(- model as any,- userProvidedCostsDecimal as any,- tokenCounts,- );-- expect(costs.inputCost?.toNumber()).toBe(expectedCost.input);- expect(costs.outputCost?.toNumber()).toBe(expectedCost.output);- expect(costs.totalCost?.toNumber()).toBe(expectedCost.total);- }- });-- it("should return empty costs if no model is provided", async () => {- const tokenCounts = {- input: 100,- output: 200,- total: 300,- };-- const userProvidedCosts = {- inputCost: null,- outputCost: null,- totalCost: null,- };-- const costs = ObservationProcessor.calculateTokenCosts(- null,- userProvidedCosts,- tokenCounts,- );-- expect(costs.inputCost?.toNumber()).toBeUndefined();- expect(costs.outputCost?.toNumber()).toBeUndefined();- expect(costs.totalCost?.toNumber()).toBeUndefined();- });-- it("should handle zero token counts correctly", async () => {- const model = {- inputPrice: new Decimal(0.01),- outputPrice: new Decimal(0.02),- totalPrice: new Decimal(0.03),- };-- const tokenCounts = {- input: 0,- output: 0,- total: 0,- };-- const userProvidedCosts = {- inputCost: null,- outputCost: null,- totalCost: null,- };-- const costs = ObservationProcessor.calculateTokenCosts(- model as any,- userProvidedCosts,- tokenCounts,- );-- expect(costs.inputCost?.toNumber()).toBe(0); // 0 tokens * 0.01- expect(costs.outputCost?.toNumber()).toBe(0); // 0 tokens * 0.02- expect(costs.totalCost?.toNumber()).toBe(0); // 0 tokens * 0.03- });-- it("should handle missing token counts correctly", async () => {- const model = {- inputPrice: new Decimal(0.01),- outputPrice: new Decimal(0.02),- totalPrice: new Decimal(0.03),- };-- const tokenCounts = {- input: undefined,- output: undefined,- total: undefined,- };-- const userProvidedCosts = {- inputCost: null,- outputCost: null,- totalCost: null,- };-- const costs = ObservationProcessor.calculateTokenCosts(- model as any,- userProvidedCosts,- tokenCounts,- );-- expect(costs.inputCost?.toNumber()).toBeUndefined();- expect(costs.outputCost?.toNumber()).toBeUndefined();- expect(costs.totalCost?.toNumber()).toBeUndefined();- });-- it("should handle fractional token counts correctly", async () => {- const model = {- inputPrice: new Decimal(0.01),- outputPrice: new Decimal(0.02),- totalPrice: new Decimal(0.03),- };-- const tokenCounts = {- input: 150.5,- output: 250.25,- total: 400.75,- };-- const userProvidedCosts = {- inputCost: null,- outputCost: null,- totalCost: null,- };-- const costs = ObservationProcessor.calculateTokenCosts(- model as any,- userProvidedCosts,- tokenCounts,- );-- expect(costs.inputCost?.toNumber()).toBeCloseTo(1.505); // 150.5 tokens * 0.01- expect(costs.outputCost?.toNumber()).toBeCloseTo(5.005); // 250.25 tokens * 0.02- expect(costs.totalCost?.toNumber()).toBeCloseTo(12.0225); // 400.75 tokens * 0.03- });-- it("should handle large token counts correctly", async () => {- const model = {- inputPrice: new Decimal(0.01),- outputPrice: new Decimal(0.02),- totalPrice: new Decimal(0.03),- };-- const tokenCounts = {- input: 1e6,- output: 2e6,- total: 3e6,- };-- const userProvidedCosts = {- inputCost: null,- outputCost: null,- totalCost: null,- };-- const costs = ObservationProcessor.calculateTokenCosts(- model as any,- userProvidedCosts,- tokenCounts,- );-- expect(costs.inputCost?.toNumber()).toBe(10000); // 1e6 tokens * 0.01- expect(costs.outputCost?.toNumber()).toBe(40000); // 2e6 tokens * 0.02- expect(costs.totalCost?.toNumber()).toBe(90000); // 3e6 tokens * 0.03- });-- it("should correctly match model prices from the database", async () => {- const generationUsage = {- model: modelName,- usage: {- input: 100,- output: 200,- total: 300,- unit: ModelUsageUnit.Tokens,- },- };- const events = [- {- id: uuidv4(),- type: "generation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage,- },- },- ];-- const response = await makeAPICall("POST", "/api/public/ingestion", {- batch: events,- });-- expect(response.status).toBe(207);- const generation = await prisma.observation.findFirst({- where: {- id: generationId,- },- });-- expect(generation).toBeDefined();- expect(generation?.type).toBe("GENERATION");-- // Model name should be matched- expect(generation?.internalModel).toBe(tokenModelData.modelName);- expect(generation?.unit).toEqual(tokenModelData.unit);- expect(generation?.internalModelId).toBe(tokenModelData.id);-- // No user provided cost- expect(generation?.inputCost).toBeNull();- expect(generation?.outputCost).toBeNull();- expect(generation?.totalCost).toBeNull();-- // Calculated cost- expect(generation?.calculatedInputCost?.toNumber()).toBe(- generationUsage.usage.input * tokenModelData.inputPrice,- );- expect(generation?.calculatedOutputCost?.toNumber()).toBe(- generationUsage.usage.output * tokenModelData.outputPrice,- );- expect(generation?.calculatedTotalCost?.toNumber()).toBe(- generationUsage.usage.total * tokenModelData.totalPrice,- );- expect(generation?.promptTokens).toBe(generationUsage.usage.input);- expect(generation?.completionTokens).toBe(generationUsage.usage.output);- expect(generation?.totalTokens).toBe(generationUsage.usage.total);- });-- it("should overwrite costs for a generation without previous user provided costs", async () => {- const generationUsage1 = {- model: modelName,- usage: {- input: 1,- output: 2,- total: 3,- unit: ModelUsageUnit.Tokens,- },- };-- const generationUsage2 = {- model: modelName,- usage: {- input: 100,- output: 200,- total: 300,- unit: ModelUsageUnit.Tokens,- },- };-- const events = [- {- id: uuidv4(),- type: "generation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage1,- },- },- {- id: uuidv4(),- type: "generation-update",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage2,- },- },- ];-- const response = await makeAPICall("POST", "/api/public/ingestion", {- batch: events,- });-- expect(response.status).toBe(207);- const generation = await prisma.observation.findFirst({- where: {- id: generationId,- },- });-- expect(generation).toBeDefined();- expect(generation?.type).toBe("GENERATION");-- // Model name should be matched- expect(generation?.internalModel).toBe(tokenModelData.modelName);- expect(generation?.unit).toEqual(tokenModelData.unit);- expect(generation?.internalModelId).toBe(tokenModelData.id);-- // No user provided cost- expect(generation?.inputCost).toBeNull();- expect(generation?.outputCost).toBeNull();- expect(generation?.totalCost).toBeNull();-- // Calculated cost- expect(generation?.calculatedInputCost?.toNumber()).toBe(- generationUsage2.usage.input * tokenModelData.inputPrice,- );- expect(generation?.calculatedOutputCost?.toNumber()).toBe(- generationUsage2.usage.output * tokenModelData.outputPrice,- );- expect(generation?.calculatedTotalCost?.toNumber()).toBe(- generationUsage2.usage.total * tokenModelData.totalPrice,- );- expect(generation?.promptTokens).toBe(generationUsage2.usage.input);- expect(generation?.completionTokens).toBe(generationUsage2.usage.output);- expect(generation?.totalTokens).toBe(generationUsage2.usage.total);- });-- it("should correctly handle first manual tokenization and then provided tokens", async () => {- const generationUsage1 = {- model: modelName,- input: "hello world",- output: "",- usage: null,- };-- const generationUsage2 = {- output: "whassup",- usage: {- input: 100,- output: 200,- total: 300,- unit: ModelUsageUnit.Tokens,- },- };-- const events = [- {- id: uuidv4(),- type: "generation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage1,- },- },- {- id: uuidv4(),- type: "generation-update",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage2,- },- },- ];-- const response = await makeAPICall("POST", "/api/public/ingestion", {- batch: events,- });-- expect(response.status).toBe(207);- const generation = await prisma.observation.findFirst({- where: {- id: generationId,- },- });-- expect(generation).toBeDefined();- expect(generation?.type).toBe("GENERATION");-- // Model name should be matched- expect(generation?.internalModel).toBe(tokenModelData.modelName);- expect(generation?.unit).toEqual(tokenModelData.unit);- expect(generation?.internalModelId).toBe(tokenModelData.id);-- // No user provided cost- expect(generation?.inputCost).toBeNull();- expect(generation?.outputCost).toBeNull();- expect(generation?.totalCost).toBeNull();-- // Calculated cost- expect(generation?.calculatedInputCost?.toNumber()).toBe(- generationUsage2.usage.input * tokenModelData.inputPrice,- );- expect(generation?.calculatedOutputCost?.toNumber()).toBe(- generationUsage2.usage.output * tokenModelData.outputPrice,- );- expect(generation?.calculatedTotalCost?.toNumber()).toBe(- generationUsage2.usage.total * tokenModelData.totalPrice,- );- expect(generation?.promptTokens).toBe(generationUsage2.usage.input);- expect(generation?.completionTokens).toBe(generationUsage2.usage.output);- expect(generation?.totalTokens).toBe(generationUsage2.usage.total);- });-- it("should use the matched model of the previous generation call to calculate costs", async () => {- const generationUsage1 = {- model: modelName,- usage: {- input: 1,- output: 2,- total: 3,- unit: ModelUsageUnit.Tokens,- },- };-- const generationUsage2 = {- model: undefined, // No model provided- usage: {- input: 100,- output: 200,- total: 300,- unit: ModelUsageUnit.Tokens,- },- };-- const events = [- {- id: uuidv4(),- type: "generation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage1,- },- },- {- id: uuidv4(),- type: "generation-update",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage2,- },- },- ];-- const response = await makeAPICall("POST", "/api/public/ingestion", {- batch: events,- });-- expect(response.status).toBe(207);- const generation = await prisma.observation.findFirst({- where: {- id: generationId,- },- });-- expect(generation).toBeDefined();- expect(generation?.type).toBe("GENERATION");-- // Model name should be matched- expect(generation?.internalModel).toBe(tokenModelData.modelName);- expect(generation?.unit).toEqual(tokenModelData.unit);- expect(generation?.internalModelId).toBe(tokenModelData.id);-- // No user provided cost- expect(generation?.inputCost).toBeNull();- expect(generation?.outputCost).toBeNull();- expect(generation?.totalCost).toBeNull();-- // Calculated cost- expect(generation?.calculatedInputCost?.toNumber()).toBe(- generationUsage2.usage.input * tokenModelData.inputPrice,- );- expect(generation?.calculatedOutputCost?.toNumber()).toBe(- generationUsage2.usage.output * tokenModelData.outputPrice,- );- expect(generation?.calculatedTotalCost?.toNumber()).toBe(- generationUsage2.usage.total * tokenModelData.totalPrice,- );- expect(generation?.promptTokens).toBe(generationUsage2.usage.input);- expect(generation?.completionTokens).toBe(generationUsage2.usage.output);- expect(generation?.totalTokens).toBe(generationUsage2.usage.total);- });-- it("should discard model if following event has different unit", async () => {- const generationUsage1 = {- model: modelName,- };-- const generationUsage2 = {- model: modelName,- usage: {- totalCost: 10,- unit: ModelUsageUnit.Characters, // Different unit for which model is not matched- },- };-- const events = [- {- id: uuidv4(),- type: "generation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage1,- },- },- {- id: uuidv4(),- type: "generation-update",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage2,- },- },- ];-- const response = await makeAPICall("POST", "/api/public/ingestion", {- batch: events,- });-- expect(response.status).toBe(207);- const generation = await prisma.observation.findFirst({- where: {- id: generationId,- },- });-- expect(generation).toBeDefined();- expect(generation?.type).toBe("GENERATION");-- // Model name should be matched- expect(generation?.internalModel).toBe(tokenModelData.modelName);- expect(generation?.unit).toEqual(ModelUsageUnit.Characters);-- // No user provided cost- expect(generation?.inputCost).toBeNull();- expect(generation?.outputCost).toBeNull();- expect(generation?.totalCost?.toNumber()).toBe(10);-- // Calculated cost- expect(generation?.calculatedInputCost).toBeNull();- expect(generation?.calculatedOutputCost).toBeNull();- expect(generation?.calculatedTotalCost?.toNumber()).toBe(10);- });-- it("should overwrite costs if new costs are user provided", async () => {- const generationUsage1 = {- model: modelName,- usage: {- input: 1,- output: 2,- total: 3,- unit: ModelUsageUnit.Tokens,- },- };-- const generationUsage2 = {- model: modelName,- usage: {- input: 100,- output: 200,- total: 300,- inputCost: 1234,- outputCost: 23523,- totalCost: 5354,- unit: ModelUsageUnit.Tokens,- },- };-- const events = [- {- id: uuidv4(),- type: "generation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage1,- },- },- {- id: uuidv4(),- type: "generation-update",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage2,- },- },- ];-- const response = await makeAPICall("POST", "/api/public/ingestion", {- batch: events,- });-- expect(response.status).toBe(207);- const generation = await prisma.observation.findFirst({- where: {- id: generationId,- },- });-- expect(generation).toBeDefined();- expect(generation?.type).toBe("GENERATION");-- // Model name should be matched- expect(generation?.internalModel).toBe(tokenModelData.modelName);- expect(generation?.unit).toEqual(tokenModelData.unit);- expect(generation?.internalModelId).toBe(tokenModelData.id);-- // User provided cost- expect(generation?.inputCost?.toNumber()).toBe(- generationUsage2.usage.inputCost,- );- expect(generation?.outputCost?.toNumber()).toBe(- generationUsage2.usage.outputCost,- );- expect(generation?.totalCost?.toNumber()).toBe(- generationUsage2.usage.totalCost,- );-- // Calculated cost- expect(generation?.calculatedInputCost?.toNumber()).toBe(- generationUsage2.usage.inputCost,- );- expect(generation?.calculatedOutputCost?.toNumber()).toBe(- generationUsage2.usage.outputCost,- );- expect(generation?.calculatedTotalCost?.toNumber()).toBe(- generationUsage2.usage.totalCost,- );- expect(generation?.promptTokens).toBe(generationUsage2.usage.input);- expect(generation?.completionTokens).toBe(generationUsage2.usage.output);- expect(generation?.totalTokens).toBe(generationUsage2.usage.total);- });-- it("should overwrite costs if new costs are user provided and zero", async () => {- const generationUsage1 = {- model: modelName,- usage: {- input: 1,- output: 2,- total: 3,- unit: ModelUsageUnit.Tokens,- },- };-- const generationUsage2 = {- model: modelName,- usage: {- input: 100,- output: 200,- total: 300,- inputCost: 0,- outputCost: 0,- totalCost: 0,- unit: ModelUsageUnit.Tokens,- },- };-- const events = [- {- id: uuidv4(),- type: "generation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage1,- },- },- {- id: uuidv4(),- type: "generation-update",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage2,- },- },- ];-- const response = await makeAPICall("POST", "/api/public/ingestion", {- batch: events,- });-- expect(response.status).toBe(207);- const generation = await prisma.observation.findFirst({- where: {- id: generationId,- },- });-- expect(generation).toBeDefined();- expect(generation?.type).toBe("GENERATION");-- // Model name should be matched- expect(generation?.internalModel).toBe(tokenModelData.modelName);- expect(generation?.unit).toEqual(tokenModelData.unit);- expect(generation?.internalModelId).toBe(tokenModelData.id);-- // User provided cost- expect(generation?.inputCost?.toNumber()).toBe(- generationUsage2.usage.inputCost,- );- expect(generation?.outputCost?.toNumber()).toBe(- generationUsage2.usage.outputCost,- );- expect(generation?.totalCost?.toNumber()).toBe(- generationUsage2.usage.totalCost,- );-- // Calculated cost- expect(generation?.calculatedInputCost?.toNumber()).toBe(- generationUsage2.usage.inputCost,- );- expect(generation?.calculatedOutputCost?.toNumber()).toBe(- generationUsage2.usage.outputCost,- );- expect(generation?.calculatedTotalCost?.toNumber()).toBe(- generationUsage2.usage.totalCost,- );- expect(generation?.promptTokens).toBe(generationUsage2.usage.input);- expect(generation?.completionTokens).toBe(generationUsage2.usage.output);- expect(generation?.totalTokens).toBe(generationUsage2.usage.total);- });-- it("should overwrite costs if new costs are user provided and only partial", async () => {- const generationUsage1 = {- model: modelName,- usage: {- input: 1,- output: 2,- total: 3,- unit: ModelUsageUnit.Tokens,- },- };-- const generationUsage2 = {- model: modelName,- usage: {- outputCost: 1,- unit: ModelUsageUnit.Tokens,- },- };-- const events = [- {- id: uuidv4(),- type: "generation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage1,- },- },- {- id: uuidv4(),- type: "generation-update",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage2,- },- },- ];-- const response = await makeAPICall("POST", "/api/public/ingestion", {- batch: events,- });-- expect(response.status).toBe(207);- const generation = await prisma.observation.findFirst({- where: {- id: generationId,- },- });-- expect(generation).toBeDefined();- expect(generation?.type).toBe("GENERATION");-- // Model name should be matched- expect(generation?.internalModel).toBe(tokenModelData.modelName);- expect(generation?.unit).toEqual(tokenModelData.unit);- expect(generation?.internalModelId).toBe(tokenModelData.id);-- // User provided cost- expect(generation?.inputCost?.toNumber()).toBe(undefined);- expect(generation?.outputCost?.toNumber()).toBe(- generationUsage2.usage.outputCost,- );- expect(generation?.totalCost?.toNumber()).toBe(undefined);-- // Calculated cost- expect(generation?.calculatedInputCost?.toNumber()).toBe(undefined);- expect(generation?.calculatedOutputCost?.toNumber()).toBe(- generationUsage2.usage.outputCost,- );- expect(generation?.calculatedTotalCost?.toNumber()).toBe(1);- expect(generation?.promptTokens).toBe(generationUsage1.usage.input);- expect(generation?.completionTokens).toBe(generationUsage1.usage.output);- expect(generation?.totalTokens).toBe(generationUsage1.usage.total);- });-- it("should not overwrite costs if previous cost were user provided", async () => {- const generationUsage1 = {- model: modelName,- usage: {- input: 1,- output: 2,- total: 3,- inputCost: 1234,- outputCost: 23523,- totalCost: 5354,- unit: ModelUsageUnit.Tokens,- },- };-- const generationUsage2 = {- model: modelName,- usage: {- input: 100,- output: 200,- total: 300,- unit: ModelUsageUnit.Tokens,- },- };-- const events = [- {- id: uuidv4(),- type: "generation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage1,- },- },- {- id: uuidv4(),- type: "generation-update",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage2,- },- },- ];-- const response = await makeAPICall("POST", "/api/public/ingestion", {- batch: events,- });-- expect(response.status).toBe(207);- const generation = await prisma.observation.findFirst({- where: {- id: generationId,- },- });-- expect(generation).toBeDefined();- expect(generation?.type).toBe("GENERATION");-- // Model name should be matched- expect(generation?.internalModel).toBe(tokenModelData.modelName);- expect(generation?.unit).toEqual(tokenModelData.unit);- expect(generation?.internalModelId).toBe(tokenModelData.id);-- // User provided cost- expect(generation?.inputCost?.toNumber()).toBe(- generationUsage1.usage.inputCost,- );- expect(generation?.outputCost?.toNumber()).toBe(- generationUsage1.usage.outputCost,- );- expect(generation?.totalCost?.toNumber()).toBe(- generationUsage1.usage.totalCost,- );-- // Calculated cost- expect(generation?.calculatedInputCost?.toNumber()).toBe(- generationUsage1.usage.inputCost,- );- expect(generation?.calculatedOutputCost?.toNumber()).toBe(- generationUsage1.usage.outputCost,- );- expect(generation?.calculatedTotalCost?.toNumber()).toBe(- generationUsage1.usage.totalCost,- );- expect(generation?.promptTokens).toBe(generationUsage2.usage.input);- expect(generation?.completionTokens).toBe(generationUsage2.usage.output);- expect(generation?.totalTokens).toBe(generationUsage2.usage.total);- });-- it("should not calculate anything if no costs are provided and no model is matched", async () => {- const generationUsage1 = {- model: undefined, // No model provided- usage: {- input: 1,- output: 2,- total: 3,- unit: ModelUsageUnit.Tokens,- },- };-- const generationUsage2 = {- model: undefined, // No model provided- usage: {- input: 100,- output: 200,- total: 300,- unit: ModelUsageUnit.Tokens,- },- };-- const events = [- {- id: uuidv4(),- type: "generation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage1,- },- },- {- id: uuidv4(),- type: "generation-update",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage2,- },- },- ];-- const response = await makeAPICall("POST", "/api/public/ingestion", {- batch: events,- });-- expect(response.status).toBe(207);- const generation = await prisma.observation.findFirst({- where: {- id: generationId,- },- });-- expect(generation).toBeDefined();- expect(generation?.type).toBe("GENERATION");-- // Model name should not be matched- expect(generation?.internalModel).toBeNull();- expect(generation?.unit).toEqual(tokenModelData.unit);- expect(generation?.internalModelId).toBeNull();-- // No user provided cost- expect(generation?.inputCost).toBeNull();- expect(generation?.outputCost).toBeNull();- expect(generation?.totalCost).toBeNull();-- // No calculated cost- expect(generation?.calculatedInputCost).toBeNull();- expect(generation?.calculatedOutputCost).toBeNull();- expect(generation?.calculatedTotalCost).toBeNull();-- expect(generation?.promptTokens).toBe(generationUsage2.usage.input);- expect(generation?.completionTokens).toBe(generationUsage2.usage.output);- expect(generation?.totalTokens).toBe(generationUsage2.usage.total);- });-- it("should handle different model usage units correctly", async () => {- const generationUsage1 = {- model: modelName,- usage: {- input: 1,- output: 2,- total: 3,- unit: ModelUsageUnit.Tokens,- },- };-- const generationUsage2 = {- model: modelName,- usage: {- input: 100,- output: 200,- total: 300,- unit: ModelUsageUnit.Images, // Different unit- },- };-- const events = [- {- id: uuidv4(),- type: "generation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage1,- },- },- {- id: uuidv4(),- type: "generation-update",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage2,- },- },- ];-- const response = await makeAPICall("POST", "/api/public/ingestion", {- batch: events,- });-- expect(response.status).toBe(207);- const generation = await prisma.observation.findFirst({- where: {- id: generationId,- },- });-- expect(generation).toBeDefined();- expect(generation?.type).toBe("GENERATION");-- // Model name should be matched- expect(generation?.internalModel).toBe(imageModelData.modelName);- expect(generation?.unit).toEqual(imageModelData.unit);- expect(generation?.internalModelId).toBe(imageModelData.id);-- // No user provided cost- expect(generation?.inputCost).toBeNull();- expect(generation?.outputCost).toBeNull();- expect(generation?.totalCost).toBeNull();-- // Calculated cost- expect(generation?.calculatedInputCost?.toNumber()).toBe(- generationUsage2.usage.input * imageModelData.inputPrice,- );- expect(generation?.calculatedOutputCost?.toNumber()).toBe(- generationUsage2.usage.output * imageModelData.outputPrice,- );- expect(generation?.calculatedTotalCost?.toNumber()).toBe(- generationUsage2.usage.total * imageModelData.totalPrice,- );- expect(generation?.promptTokens).toBe(generationUsage2.usage.input);- expect(generation?.completionTokens).toBe(generationUsage2.usage.output);- expect(generation?.totalTokens).toBe(generationUsage2.usage.total);- });-- it("should take the latest user provided model for matching", async () => {- // Create a new model with the same name but different prices- const newModelData = {- id: uuidv4(),- modelName,- matchPattern,- startDate: new Date().toISOString(),- inputPrice: tokenModelData.inputPrice * 2,- outputPrice: tokenModelData.outputPrice * 2,- totalPrice: tokenModelData.totalPrice * 2,- unit: ModelUsageUnit.Tokens,- };-- await prisma.model.create({- data: newModelData,- });-- const generationUsage = {- model: modelName,- usage: {- input: 100,- output: 200,- total: 300,- unit: ModelUsageUnit.Tokens,- },- };-- const events = [- {- id: uuidv4(),- type: "generation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage,- },- },- ];-- const response = await makeAPICall("POST", "/api/public/ingestion", {- batch: events,- });-- expect(response.status).toBe(207);- const generation = await prisma.observation.findFirst({- where: {- id: generationId,- },- });-- expect(generation).toBeDefined();- expect(generation?.type).toBe("GENERATION");-- // Model name should be matched- expect(generation?.internalModel).toBe(newModelData.modelName);- expect(generation?.unit).toEqual(newModelData.unit);- expect(generation?.internalModelId).toBe(newModelData.id);-- // No user provided cost- expect(generation?.inputCost).toBeNull();- expect(generation?.outputCost).toBeNull();- expect(generation?.totalCost).toBeNull();-- // Calculated cost- expect(generation?.calculatedInputCost?.toNumber()).toBe(- generationUsage.usage.input * newModelData.inputPrice,- );- expect(generation?.calculatedOutputCost?.toNumber()).toBe(- generationUsage.usage.output * newModelData.outputPrice,- );- expect(generation?.calculatedTotalCost?.toNumber()).toBe(- generationUsage.usage.total * newModelData.totalPrice,- );- expect(generation?.promptTokens).toBe(generationUsage.usage.input);- expect(generation?.completionTokens).toBe(generationUsage.usage.output);- expect(generation?.totalTokens).toBe(generationUsage.usage.total);- });-- it("should use the tokens of the previous call without model if model comes with following call", async () => {- const generationUsage1 = {- model: undefined, // No model provided- usage: {- input: 1,- output: 2,- total: 3,- unit: ModelUsageUnit.Tokens,- },- };-- const generationUsage2 = {- model: modelName,- };-- const events = [- {- id: uuidv4(),- type: "generation-create",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage1,- },- },- {- id: uuidv4(),- type: "generation-update",- timestamp: new Date().toISOString(),- body: {- id: generationId,- ...generationUsage2,- },- },- ];-- const response = await makeAPICall("POST", "/api/public/ingestion", {- batch: events,- });-- expect(response.status).toBe(207);- const generation = await prisma.observation.findFirst({- where: {- id: generationId,- },- });-- expect(generation).toBeDefined();- expect(generation?.type).toBe("GENERATION");-- // Model name should be matched- expect(generation?.internalModel).toBe(tokenModelData.modelName);- expect(generation?.unit).toEqual(tokenModelData.unit);- expect(generation?.internalModelId).toBe(tokenModelData.id);-- // No user provided cost- expect(generation?.inputCost).toBeNull();- expect(generation?.outputCost).toBeNull();- expect(generation?.totalCost).toBeNull();-- // Calculated cost- expect(generation?.calculatedInputCost?.toNumber()).toBe(- generationUsage1.usage.input * tokenModelData.inputPrice,- );- expect(generation?.calculatedOutputCost?.toNumber()).toBe(- generationUsage1.usage.output * tokenModelData.outputPrice,- );- expect(generation?.calculatedTotalCost?.toNumber()).toBe(- generationUsage1.usage.total * tokenModelData.totalPrice,- );- expect(generation?.promptTokens).toBe(generationUsage1.usage.input);- expect(generation?.completionTokens).toBe(generationUsage1.usage.output);- expect(generation?.totalTokens).toBe(generationUsage1.usage.total);- });-});diff --git a/web/src/__tests__/traces.servertest.ts b/web/src/__tests__/traces.servertest.tsdeleted file mode 100644index 8c752d3fc4..0000000000--- a/web/src/__tests__/traces.servertest.ts+++ /dev/null@@ -1,358 +0,0 @@-/** @jest-environment node */--import { v4 as uuidv4 } from "uuid";--import {- makeZodVerifiedAPICall,- pruneDatabase,-} from "@/src/__tests__/test-utils";-import { PostGenerationsV1Response } from "@/src/features/public-api/types/generations";-import {- GetTracesV1Response,- GetTraceV1Response,- PostTracesV1Response,-} from "@/src/features/public-api/types/traces";-import { PostScoresResponse } from "@langfuse/shared";-import { prisma } from "@langfuse/shared/src/db";--describe("/api/public/traces API Endpoint", () => {- beforeEach(async () => await pruneDatabase());- afterEach(async () => await pruneDatabase());-- it("should upsert second trace", async () => {- await pruneDatabase();-- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- id: "trace-id",- name: "trace-name",- userId: "user-1",- metadata: { key: "value" },- release: "1.0.0",- version: "2.0.0",- public: true,- },- );-- const dbTrace1 = await prisma.trace.findFirst({- where: {- id: "trace-id",- },- });-- expect(dbTrace1).not.toBeNull();- expect(dbTrace1).toMatchObject({- name: "trace-name",- release: "1.0.0",- externalId: null,- version: "2.0.0",- public: true,- userId: "user-1",- });-- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- id: "trace-id",- metadata: { key: "value" },- timestamp: "2021-01-01T00:00:00.000Z",- release: "1.0.0",- version: "5.0.0",- public: false,- },- );-- const dbTrace2 = await prisma.trace.findFirst({- where: {- name: "trace-name",- },- });-- expect(dbTrace2).not.toBeNull();- expect(dbTrace2).toMatchObject({- name: "trace-name",- release: "1.0.0",- externalId: null,- version: "5.0.0",- public: false,- userId: "user-1",- timestamp: new Date("2021-01-01T00:00:00.000Z"),- });- });-- it("should use tags correctly on POST and GET", async () => {- await pruneDatabase();-- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- id: "trace-1",- tags: ["tag-1", "tag-2", "tag-3"],- },- );-- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- id: "trace-2",- tags: ["tag-1"],- },- );-- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- id: "trace-3",- tags: ["tag-2", "tag-3"],- },- );-- // multiple tags- const traces = await makeZodVerifiedAPICall(- GetTracesV1Response,- "GET",- "/api/public/traces?tags=tag-2&tags=tag-3",- );- const traceIds = traces.body.data.map((t) => t.id);- // check for equality ok as ordered by timestamp- expect(traceIds).toEqual(["trace-3", "trace-1"]);-- // single tag- const traces2 = await makeZodVerifiedAPICall(- GetTracesV1Response,- "GET",- "/api/public/traces?tags=tag-1",- );- const traceIds2 = traces2.body.data.map((t) => t.id);- // check for equality ok as ordered by timestamp- expect(traceIds2).toEqual(["trace-2", "trace-1"]);-- // wrong tag- const traces3 = await makeZodVerifiedAPICall(- GetTracesV1Response,- "GET",- "/api/public/traces?tags=tag-10",- );- const traceIds3 = traces3.body.data.map((t) => t.id);- // check for equality ok as ordered by timestamp- expect(traceIds3).toEqual([]);-- // no tag- const traces4 = await makeZodVerifiedAPICall(- GetTracesV1Response,- "GET",- "/api/public/traces?tags=",- );- const traceIds4 = traces4.body.data.map((t) => t.id);- // check for equality ok as ordered by timestamp- expect(traceIds4).toEqual(["trace-3", "trace-2", "trace-1"]);- });-- it("should handle metrics correctly on GET traces and GET trace", async () => {- await pruneDatabase();-- // Create a trace with some observations that have costs and latencies- const traceId = uuidv4();- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- id: traceId,- name: "trace-with-costs",- userId: "user-costs",- projectId: "project-costs",- metadata: { key: "value" },- release: "1.0.0",- version: "2.0.0",- },- );- console.log(traceId);-- // Simulate observations with costs and latencies- const generationId = uuidv4();- await makeZodVerifiedAPICall(- PostGenerationsV1Response,- "POST",- "/api/public/generations",- {- traceId: traceId,- id: generationId,- name: "Generation1",- usage: { totalCost: 10.5 },- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:10:00.000Z",- },- );- await makeZodVerifiedAPICall(- PostGenerationsV1Response,- "POST",- "/api/public/generations",- {- traceId: traceId,- usage: { totalCost: 5.25 },- startTime: "2021-01-01T00:10:00.000Z",- endTime: "2021-01-01T00:20:00.000Z",- },- );-- // Simulate scores on the trace- const scoreId1 = uuidv4();- await makeZodVerifiedAPICall(- PostScoresResponse,- "POST",- "/api/public/scores",- {- id: scoreId1,- name: "score-1",- value: 75.0,- traceId: traceId,- comment: "First score",- },- );- const scoreId2 = uuidv4();- await makeZodVerifiedAPICall(- PostScoresResponse,- "POST",- "/api/public/scores",- {- id: scoreId2,- name: "score-2",- value: 85.5,- traceId: traceId,- comment: "Second score",- },- );- const scoreId3 = uuidv4();- await makeZodVerifiedAPICall(- PostScoresResponse,- "POST",- "/api/public/scores",- {- id: scoreId3,- name: "score-3",- value: 95.0,- traceId: traceId,- comment: "Third score",- },- );-- // GET traces- // Retrieve the trace with totalCost and latency- const traces = await makeZodVerifiedAPICall(- GetTracesV1Response,- "GET",- `/api/public/traces`,- );- const traceData = traces.body.data[0];- if (!traceData) throw new Error("traceData is undefined");-- // Check if the totalCost and latency are calculated correctly- expect(traceData.totalCost).toBeCloseTo(15.75); // Sum of costs- expect(traceData.latency).toBeCloseTo(1200); // Difference in seconds between min startTime and max endTime- expect(traceData.id).toBe(traceId);- expect(traceData.htmlPath).toContain(`/traces/${traceId}`);- expect(traceData.htmlPath).toContain(`/project/`); // do not know the projectId-- // GET trace- // Retrieve the trace with total- const trace = await makeZodVerifiedAPICall(- GetTraceV1Response,- "GET",- `/api/public/traces/${traceId}`,- );- console.log(trace.body);- expect(trace.body.totalCost).toBeCloseTo(15.75);- expect(trace.body.id).toBe(traceId);- expect(trace.body.id).toBe(traceId);- expect(trace.body.htmlPath).toContain(`/traces/${traceId}`);- expect(trace.body.htmlPath).toContain(`/project/`); // do not know the projectId- expect(trace.body.scores).toHaveLength(3);- expect(trace.body.scores[0].id).toBe(scoreId3);- expect(trace.body.scores[0].name).toBe("score-3");- expect(trace.body.observations).toHaveLength(2);- expect(trace.body.observations[0].id).toBe(generationId);- expect(trace.body.observations[0].name).toBe("Generation1");- });-- it("should filter traces by session ID", async () => {- const sessionId = "test-session-id";- const anotherSessionId = "another-session-id";-- // Create traces with different session IDs- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- id: "trace-1",- name: "test-trace-1",- sessionId,- userId: "user-1",- projectId: "project-1",- metadata: { key: "value" },- release: "1.0.0",- version: "1.0.0",- },- );-- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- id: "trace-2",- name: "test-trace-2",- sessionId: anotherSessionId,- userId: "user-2",- projectId: "project-1",- metadata: { key: "value" },- release: "1.0.0",- version: "1.0.0",- },- );-- // Filter by session ID- const tracesBySessionId = await makeZodVerifiedAPICall(- GetTracesV1Response,- "GET",- `/api/public/traces?sessionId=${sessionId}`,- );-- expect(tracesBySessionId.status).toBe(200);- expect(tracesBySessionId.body.data).toHaveLength(1);- expect(tracesBySessionId.body.data[0].id).toBe("trace-1");-- // Filter by another session ID- const tracesByAnotherSessionId = await makeZodVerifiedAPICall(- GetTracesV1Response,- "GET",- `/api/public/traces?sessionId=${anotherSessionId}`,- );-- expect(tracesByAnotherSessionId.status).toBe(200);- expect(tracesByAnotherSessionId.body.data).toHaveLength(1);- expect(tracesByAnotherSessionId.body.data[0].id).toBe("trace-2");-- // Filter by non-existent session ID- const tracesByNonExistentSessionId = await makeZodVerifiedAPICall(- GetTracesV1Response,- "GET",- `/api/public/traces?sessionId=non-existent-session-id`,- );-- expect(tracesByNonExistentSessionId.status).toBe(200);- expect(tracesByNonExistentSessionId.body.data).toHaveLength(0);- });-});diff --git a/web/src/env.mjs b/web/src/env.mjsindex e32e159fb4..903a54268c 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -232,24 +232,6 @@ export const env = createEnv({);}, "LANGFUSE_ALLOWED_ORGANIZATION_CREATORS must be a comma separated list of valid email addresses"),- // TODO: Remove entire block during V3 clean up- // Settings to toggle Clickhouse vs Postgres behaviour- LANGFUSE_READ_FROM_POSTGRES_ONLY: z- .enum(["true", "false"])- .default("false"),- LANGFUSE_RETURN_FROM_CLICKHOUSE: z.enum(["true", "false"]).default("true"),- LANGFUSE_EXPERIMENT_EXCLUDED_PROJECT_IDS: z.string().optional(),- LANGFUSE_EXPERIMENT_EXCLUDED_OPERATIONS: z.string().optional(),- LANGFUSE_READ_DASHBOARDS_FROM_CLICKHOUSE: z- .enum(["true", "false"])- .default("true"),- LANGFUSE_READ_FROM_CLICKHOUSE_ONLY: z- .enum(["true", "false"])- .default("true"),- LANGFUSE_POSTGRES_INGESTION_ENABLED: z- .enum(["true", "false"])- .default("false"),-STRIPE_SECRET_KEY: z.string().optional(),STRIPE_WEBHOOK_SIGNING_SECRET: z.string().optional(),SENTRY_AUTH_TOKEN: z.string().optional(),@@ -314,8 +296,6 @@ export const env = createEnv({NEXT_PUBLIC_SIGN_UP_DISABLED: process.env.NEXT_PUBLIC_SIGN_UP_DISABLED,LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES:process.env.LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES,- LANGFUSE_EXPERIMENT_EXCLUDED_OPERATIONS:- process.env.LANGFUSE_EXPERIMENT_EXCLUDED_OPERATIONS,LANGFUSE_DISABLE_EXPENSIVE_POSTGRES_QUERIES:process.env.LANGFUSE_DISABLE_EXPENSIVE_POSTGRES_QUERIES,LANGFUSE_TEAM_SLACK_WEBHOOK: process.env.LANGFUSE_TEAM_SLACK_WEBHOOK,@@ -484,18 +464,6 @@ export const env = createEnv({process.env.LANGFUSE_CACHE_API_KEY_TTL_SECONDS,LANGFUSE_ALLOWED_ORGANIZATION_CREATORS:process.env.LANGFUSE_ALLOWED_ORGANIZATION_CREATORS,- LANGFUSE_READ_FROM_POSTGRES_ONLY:- process.env.LANGFUSE_READ_FROM_POSTGRES_ONLY,- LANGFUSE_POSTGRES_INGESTION_ENABLED:- process.env.LANGFUSE_POSTGRES_INGESTION_ENABLED,- LANGFUSE_READ_FROM_CLICKHOUSE_ONLY:- process.env.LANGFUSE_READ_FROM_CLICKHOUSE_ONLY,- LANGFUSE_RETURN_FROM_CLICKHOUSE:- process.env.LANGFUSE_RETURN_FROM_CLICKHOUSE,- LANGFUSE_EXPERIMENT_EXCLUDED_PROJECT_IDS:- process.env.LANGFUSE_EXPERIMENT_EXCLUDED_PROJECT_IDS,- LANGFUSE_READ_DASHBOARDS_FROM_CLICKHOUSE:- process.env.LANGFUSE_READ_DASHBOARDS_FROM_CLICKHOUSE,STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY,STRIPE_WEBHOOK_SIGNING_SECRET: process.env.STRIPE_WEBHOOK_SIGNING_SECRET,SENTRY_AUTH_TOKEN: process.env.SENTRY_AUTH_TOKEN,diff --git a/web/src/features/dashboard/server/dashboard-router.ts b/web/src/features/dashboard/server/dashboard-router.tsindex f547add740..5792c61f97 100644--- a/web/src/features/dashboard/server/dashboard-router.ts+++ b/web/src/features/dashboard/server/dashboard-router.ts@@ -1,10 +1,8 @@import { z } from "zod";-import { isClickhouseAdminEligible } from "@/src/server/utils/checkClickhouseAccess";import {createTRPCRouter,protectedProjectProcedure,} from "@/src/server/api/trpc";-import { executeQuery } from "@/src/server/api/services/queryBuilder";import {filterInterface,type groupByInterface,@@ -33,7 +31,6 @@ import {} from "@langfuse/shared/src/server";import { type DatabaseRow } from "@/src/server/api/services/queryBuilder";import { dashboardColumnDefinitions } from "@langfuse/shared";-import { env } from "@/src/env.mjs";export const dashboardRouter = createTRPCRouter({chart: protectedProjectProcedure@@ -64,243 +61,227 @@ export const dashboardRouter = createTRPCRouter({.nullish(),}),)- .query(async ({ input, ctx }) => {- if (- input.queryClickhouse &&- !isClickhouseAdminEligible(ctx.session.user)- ) {- throw new TRPCError({- code: "UNAUTHORIZED",- message: "Not eligible to query clickhouse",- });- }-- if (- input.queryClickhouse ||- env.LANGFUSE_READ_DASHBOARDS_FROM_CLICKHOUSE === "true"- ) {- switch (input.queryName) {- case "traces-total":- const count = await getTotalTraces(- input.projectId,- input.filter ?? [],- );- return count as DatabaseRow[];- case "traces-grouped-by-name":- return (- await getTracesGroupedByName(- input.projectId,- dashboardColumnDefinitions,- input.filter,- )- ).map(- (row) =>- ({- traceName: row.name,- countTraceId: row.count,- }) as DatabaseRow,- );- case "observations-model-cost":- const cost = await getObservationsCostGroupedByName(+ .query(async ({ input }) => {+ switch (input.queryName) {+ case "traces-total":+ const count = await getTotalTraces(+ input.projectId,+ input.filter ?? [],+ );+ return count as DatabaseRow[];+ case "traces-grouped-by-name":+ return (+ await getTracesGroupedByName(input.projectId,- input.filter ?? [],- );+ dashboardColumnDefinitions,+ input.filter,+ )+ ).map(+ (row) =>+ ({+ traceName: row.name,+ countTraceId: row.count,+ }) as DatabaseRow,+ );+ case "observations-model-cost":+ const cost = await getObservationsCostGroupedByName(+ input.projectId,+ input.filter ?? [],+ );- return cost.map((row) => ({- model: row.name,- sumCalculatedTotalCost: row.sum_cost_details,- sumTotalTokens: row.sum_usage_details,- })) as DatabaseRow[];- case "score-aggregate":- const scores = await getScoreAggregate(- input.projectId,- input.filter ?? [],- );+ return cost.map((row) => ({+ model: row.name,+ sumCalculatedTotalCost: row.sum_cost_details,+ sumTotalTokens: row.sum_usage_details,+ })) as DatabaseRow[];+ case "score-aggregate":+ const scores = await getScoreAggregate(+ input.projectId,+ input.filter ?? [],+ );- return scores.map((row) => ({- scoreName: row.name,- scoreSource: row.source,- scoreDataType: row.data_type,- avgValue: row.avg_value,- countScoreId: Number(row.count),- })) as DatabaseRow[];+ return scores.map((row) => ({+ scoreName: row.name,+ scoreSource: row.source,+ scoreDataType: row.data_type,+ avgValue: row.avg_value,+ countScoreId: Number(row.count),+ })) as DatabaseRow[];- case "traces-timeseries":- const dateTrunc = extractTimeSeries(input.groupBy);- if (!dateTrunc) {- return [];- }- const rows = await groupTracesByTime(- input.projectId,- input.filter ?? [],- dateTrunc,- );+ case "traces-timeseries":+ const dateTrunc = extractTimeSeries(input.groupBy);+ if (!dateTrunc) {+ return [];+ }+ const rows = await groupTracesByTime(+ input.projectId,+ input.filter ?? [],+ dateTrunc,+ );- return rows as DatabaseRow[];- case "observations-usage-timeseries":- const dateTruncObs = extractTimeSeries(input.groupBy);- if (!dateTruncObs) {- return [];- }- const rowsObs = await getObservationUsageByTime(- input.projectId,- input.filter ?? [],- dateTruncObs,- );+ return rows as DatabaseRow[];+ case "observations-usage-timeseries":+ const dateTruncObs = extractTimeSeries(input.groupBy);+ if (!dateTruncObs) {+ return [];+ }+ const rowsObs = await getObservationUsageByTime(+ input.projectId,+ input.filter ?? [],+ dateTruncObs,+ );- return rowsObs.map((row) => ({- startTime: row.start_time,- units: row.units,- cost: row.cost,- model: row.provided_model_name,- })) as DatabaseRow[];+ return rowsObs.map((row) => ({+ startTime: row.start_time,+ units: row.units,+ cost: row.cost,+ model: row.provided_model_name,+ })) as DatabaseRow[];- case "distinct-models":- const models = await getDistinctModels(- input.projectId,- input.filter ?? [],- );- return models as DatabaseRow[];+ case "distinct-models":+ const models = await getDistinctModels(+ input.projectId,+ input.filter ?? [],+ );+ return models as DatabaseRow[];- case "scores-aggregate-timeseries":- const dateTruncScores = extractTimeSeries(input.groupBy);- if (!dateTruncScores) {- return [];- }- const aggregatedScores = await getScoresAggregateOverTime(- input.projectId,- input.filter ?? [],- dateTruncScores,- );+ case "scores-aggregate-timeseries":+ const dateTruncScores = extractTimeSeries(input.groupBy);+ if (!dateTruncScores) {+ return [];+ }+ const aggregatedScores = await getScoresAggregateOverTime(+ input.projectId,+ input.filter ?? [],+ dateTruncScores,+ );- return aggregatedScores as DatabaseRow[];+ return aggregatedScores as DatabaseRow[];- case "observations-usage-by-users":- const rowsUsers = await getModelUsageByUser(- input.projectId,- input.filter ?? [],- );+ case "observations-usage-by-users":+ const rowsUsers = await getModelUsageByUser(+ input.projectId,+ input.filter ?? [],+ );- return rowsUsers.map((row) => ({- sumTotalTokens: row.sumUsageDetails,- sumCalculatedTotalCost: row.sumCostDetails,- user: row.userId,- })) as DatabaseRow[];+ return rowsUsers.map((row) => ({+ sumTotalTokens: row.sumUsageDetails,+ sumCalculatedTotalCost: row.sumCostDetails,+ user: row.userId,+ })) as DatabaseRow[];- case "traces-grouped-by-user":- const traces = await getTracesGroupedByUsers(- input.projectId,- input.filter ?? [],- undefined,- 1000,- 0,- dashboardColumnDefinitions,- );+ case "traces-grouped-by-user":+ const traces = await getTracesGroupedByUsers(+ input.projectId,+ input.filter ?? [],+ undefined,+ 1000,+ 0,+ dashboardColumnDefinitions,+ );- return traces.map((row) => ({- user: row.user,- countTraceId: Number(row.count),- })) as DatabaseRow[];- case "observation-latencies-aggregated":- const latencies = await getObservationLatencies(- input.projectId,- input.filter ?? [],- );+ return traces.map((row) => ({+ user: row.user,+ countTraceId: Number(row.count),+ })) as DatabaseRow[];+ case "observation-latencies-aggregated":+ const latencies = await getObservationLatencies(+ input.projectId,+ input.filter ?? [],+ );- return latencies.map((row) => ({- name: row.name,- percentile50Duration: row.p50,- percentile90Duration: row.p90,- percentile95Duration: row.p95,- percentile99Duration: row.p99,- })) as DatabaseRow[];- case "model-latencies-over-time":- const dateTruncModels = extractTimeSeries(input.groupBy);- if (!dateTruncModels) {- return [];- }- const modelLatencies = await getModelLatenciesOverTime(- input.projectId,- input.filter ?? [],- dateTruncModels,- );+ return latencies.map((row) => ({+ name: row.name,+ percentile50Duration: row.p50,+ percentile90Duration: row.p90,+ percentile95Duration: row.p95,+ percentile99Duration: row.p99,+ })) as DatabaseRow[];+ case "model-latencies-over-time":+ const dateTruncModels = extractTimeSeries(input.groupBy);+ if (!dateTruncModels) {+ return [];+ }+ const modelLatencies = await getModelLatenciesOverTime(+ input.projectId,+ input.filter ?? [],+ dateTruncModels,+ );- return modelLatencies.map((row) => ({- model: row.model,- startTime: row.start_time,- percentile50Duration: row.p50,- percentile75Duration: row.p75,- percentile90Duration: row.p90,- percentile95Duration: row.p95,- percentile99Duration: row.p99,- })) as DatabaseRow[];- case "traces-latencies-aggregated":- const traceLatencies = await getTracesLatencies(- input.projectId,- input.filter ?? [],- );+ return modelLatencies.map((row) => ({+ model: row.model,+ startTime: row.start_time,+ percentile50Duration: row.p50,+ percentile75Duration: row.p75,+ percentile90Duration: row.p90,+ percentile95Duration: row.p95,+ percentile99Duration: row.p99,+ })) as DatabaseRow[];+ case "traces-latencies-aggregated":+ const traceLatencies = await getTracesLatencies(+ input.projectId,+ input.filter ?? [],+ );- return traceLatencies.map((row) => ({- traceName: row.name,- percentile50Duration: row.p50,- percentile90Duration: row.p90,- percentile95Duration: row.p95,- percentile99Duration: row.p99,- })) as DatabaseRow[];- case "numeric-score-time-series":- const dateTruncNumericScoreTimeSeries = extractTimeSeries(- input.groupBy,- );- if (!dateTruncNumericScoreTimeSeries) {- return [];- }- const numericScoreTimeSeries = await getNumericScoreTimeSeries(+ return traceLatencies.map((row) => ({+ traceName: row.name,+ percentile50Duration: row.p50,+ percentile90Duration: row.p90,+ percentile95Duration: row.p95,+ percentile99Duration: row.p99,+ })) as DatabaseRow[];+ case "numeric-score-time-series":+ const dateTruncNumericScoreTimeSeries = extractTimeSeries(+ input.groupBy,+ );+ if (!dateTruncNumericScoreTimeSeries) {+ return [];+ }+ const numericScoreTimeSeries = await getNumericScoreTimeSeries(+ input.projectId,+ input.filter ?? [],+ dateTruncNumericScoreTimeSeries,+ );+ return numericScoreTimeSeries.map((row) => ({+ scoreTimestamp: row.score_timestamp,+ scoreName: row.score_name,+ avgValue: row.avg_value,+ })) as DatabaseRow[];+ case "categorical-score-chart":+ const dateTruncCategoricalScoreTimeSeries = extractTimeSeries(+ input.groupBy,+ );+ const categoricalScoreTimeSeries =+ await getCategoricalScoreTimeSeries(input.projectId,input.filter ?? [],- dateTruncNumericScoreTimeSeries,- );- return numericScoreTimeSeries.map((row) => ({- scoreTimestamp: row.score_timestamp,- scoreName: row.score_name,- avgValue: row.avg_value,- })) as DatabaseRow[];- case "categorical-score-chart":- const dateTruncCategoricalScoreTimeSeries = extractTimeSeries(- input.groupBy,+ dateTruncCategoricalScoreTimeSeries,);- const categoricalScoreTimeSeries =- await getCategoricalScoreTimeSeries(- input.projectId,- input.filter ?? [],- dateTruncCategoricalScoreTimeSeries,- );- return categoricalScoreTimeSeries.map((row) => ({- ...(row.score_timestamp- ? { scoreTimestamp: row.score_timestamp }- : {}),- scoreName: row.score_name || null,- scoreDataType: row.score_data_type || null,- scoreSource: row.score_source || null,- stringValue: row.score_value || null,- countStringValue: Number(row.count) || 0,- })) as DatabaseRow[];- case "observations-status-timeseries":- const timeSeriesGroupBy = extractTimeSeries(input.groupBy);+ return categoricalScoreTimeSeries.map((row) => ({+ ...(row.score_timestamp+ ? { scoreTimestamp: row.score_timestamp }+ : {}),+ scoreName: row.score_name || null,+ scoreDataType: row.score_data_type || null,+ scoreSource: row.score_source || null,+ stringValue: row.score_value || null,+ countStringValue: Number(row.count) || 0,+ })) as DatabaseRow[];+ case "observations-status-timeseries":+ const timeSeriesGroupBy = extractTimeSeries(input.groupBy);- return (await getObservationsStatusTimeSeries(- input.projectId,- input.filter ?? [],- timeSeriesGroupBy,- )) as DatabaseRow[];+ return (await getObservationsStatusTimeSeries(+ input.projectId,+ input.filter ?? [],+ timeSeriesGroupBy,+ )) as DatabaseRow[];- default:- throw new TRPCError({- code: "NOT_FOUND",- message: "Query not found",- });- }+ default:+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Query not found",+ });}- return await executeQuery(ctx.prisma, input.projectId, input);}),scoreHistogram: protectedProjectProcedure.input(@@ -310,30 +291,12 @@ export const dashboardRouter = createTRPCRouter({queryClickhouse: z.boolean().default(false),}),)- .query(async ({ input, ctx }) => {- if (- input.queryClickhouse &&- !isClickhouseAdminEligible(ctx.session.user)- ) {- throw new TRPCError({- code: "UNAUTHORIZED",- message: "Not eligible to query clickhouse",- });- }-- if (- input.queryClickhouse ||- env.LANGFUSE_READ_DASHBOARDS_FROM_CLICKHOUSE === "true"- ) {- const data = await getNumericScoreHistogram(- input.projectId,- input.filter ?? [],- input.limit ?? 10000,- );- return createHistogramData(data);- }-- const data = await executeQuery(ctx.prisma, input.projectId, input);+ .query(async ({ input }) => {+ const data = await getNumericScoreHistogram(+ input.projectId,+ input.filter ?? [],+ input.limit ?? 10000,+ );return createHistogramData(data);}),});diff --git a/web/src/pages/api/public/dataset-run-items.ts b/web/src/pages/api/public/dataset-run-items.tsindex 9ee6fd01e2..b6ce632405 100644--- a/web/src/pages/api/public/dataset-run-items.ts+++ b/web/src/pages/api/public/dataset-run-items.ts@@ -9,7 +9,6 @@ import {import { LangfuseNotFoundError, InvalidRequestError } from "@langfuse/shared";import { addDatasetRunItemsToEvalQueue } from "@/src/ee/features/evals/server/addDatasetRunItemsToEvalQueue";import { getObservationById } from "@langfuse/shared/src/server";-import { env } from "@/src/env.mjs";export default withMiddlewares({POST: createAuthedAPIRoute({@@ -51,20 +50,11 @@ export default withMiddlewares({// Backwards compatibility: historically, dataset run items were linked to observations, not tracesif (!traceId && observationId) {- const observation =- env.LANGFUSE_RETURN_FROM_CLICKHOUSE === "true"- ? await getObservationById(- observationId,- auth.scope.projectId,- true,- )- : await prisma.observation.findUnique({- where: {- id: observationId,- projectId: auth.scope.projectId,- },- });-+ const observation = await getObservationById(+ observationId,+ auth.scope.projectId,+ true,+ );if (observationId && !observation) {throw new LangfuseNotFoundError("Observation not found");}diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.tsindex 19f578757d..c52f06b955 100644--- a/web/src/server/api/routers/scores.ts+++ b/web/src/server/api/routers/scores.ts@@ -390,68 +390,6 @@ export const scoresRouter = createTRPCRouter({after: score,});- if (env.LANGFUSE_POSTGRES_INGESTION_ENABLED === "true") {- const trace = await ctx.prisma.trace.findFirst({- where: {- id: input.traceId,- projectId: input.projectId,- },- });- // Fail silently while Clickhouse is in lead and return early- if (!trace) {- if (!hasClickhouseConfigured) {- throw new InternalServerError(- "No trace with this id in this project.",- );- } else {- logger.error("No trace with this id in this project.");- return validateDbScore(score);- }- }-- const existingScore = await ctx.prisma.score.findFirst({- where: {- projectId: input.projectId,- traceId: input.traceId,- observationId: input.observationId ?? null,- source: "ANNOTATION",- // configId functions as unique constraint for scores with source ANNOTATION- configId: input.configId,- },- });-- // Fail silently while Clickhouse is in lead and return early- if (existingScore) {- if (!hasClickhouseConfigured) {- throw new InternalServerError(- `Score for name ${input.name} already exists for trace ${input.traceId} in project ${input.projectId} in Postgres`,- );- } else {- logger.error(- `Score for name ${input.name} already exists for trace ${input.traceId} in project ${input.projectId} in Postgres`,- );- return validateDbScore(score);- }- }-- try {- await ctx.prisma.score.create({- data: score,- });- } catch (error) {- if (!hasClickhouseConfigured) {- throw new InternalServerError(- `Error creating score for name ${input.name} in Postgres for trace ${input.traceId} in project ${input.projectId}`,- );- } else {- logger.error(- `Error creating score for name ${input.name} in Postgres for trace ${input.traceId} in project ${input.projectId}`,- );- return validateDbScore(score);- }- }- }-return validateDbScore(score);}),updateAnnotationScore: protectedProjectProcedure@@ -463,132 +401,65 @@ export const scoresRouter = createTRPCRouter({scope: "scores:CUD",});- const hasClickhouseConfigured = env.CLICKHOUSE_URL;let updatedScore: Score | null | undefined = null;- let updatedScorePostgres: Score | null | undefined = null;- if (hasClickhouseConfigured) {- // Fetch the current score from Clickhouse- const score = await getScoreById(- input.projectId,- input.id,- ScoreSource.ANNOTATION,+ // Fetch the current score from Clickhouse+ const score = await getScoreById(+ input.projectId,+ input.id,+ ScoreSource.ANNOTATION,+ );+ if (!score) {+ logger.warn(+ `No annotation score with id ${input.id} in project ${input.projectId} in Clickhouse`,);- if (!score) {- logger.warn(- `No annotation score with id ${input.id} in project ${input.projectId} in Clickhouse`,- );- throw new LangfuseNotFoundError(- `No annotation score with id ${input.id} in project ${input.projectId} in Clickhouse`,- );- } else {- await upsertScore({- id: input.id,- project_id: input.projectId,- timestamp: convertDateToClickhouseDateTime(score.timestamp),- value: input.value !== null ? input.value : undefined,- string_value: input.stringValue,- comment: input.comment,- author_user_id: ctx.session.user.id,- queue_id: input.queueId,- source: ScoreSource.ANNOTATION,- name: score.name,- data_type: score.dataType,- config_id: score.configId,- trace_id: score.traceId,- observation_id: score.observationId,- });-- updatedScore = {- ...score,- value: input.value ?? null,- stringValue: input.stringValue ?? null,- comment: input.comment ?? null,- authorUserId: ctx.session.user.id,- queueId: input.queueId ?? null,- };-- // Audit log only if Postgres is not enabled, as we still run PG and CH ingestion in parallel on cloud- if (env.LANGFUSE_POSTGRES_INGESTION_ENABLED === "false") {- await auditLog({- session: ctx.session,- resourceType: "score",- resourceId: input.id,- action: "update",- before: score,- after: updatedScore,- });- }- }- }-- if (env.LANGFUSE_POSTGRES_INGESTION_ENABLED === "true") {- const scorePostgres = await ctx.prisma.score.findFirst({- where: {- id: input.id,- projectId: input.projectId,- source: "ANNOTATION",- },+ throw new LangfuseNotFoundError(+ `No annotation score with id ${input.id} in project ${input.projectId} in Clickhouse`,+ );+ } else {+ await upsertScore({+ id: input.id,+ project_id: input.projectId,+ timestamp: convertDateToClickhouseDateTime(score.timestamp),+ value: input.value !== null ? input.value : undefined,+ string_value: input.stringValue,+ comment: input.comment,+ author_user_id: ctx.session.user.id,+ queue_id: input.queueId,+ source: ScoreSource.ANNOTATION,+ name: score.name,+ data_type: score.dataType,+ config_id: score.configId,+ trace_id: score.traceId,+ observation_id: score.observationId,});- // Fail silently while Clickhouse is in lead and return early- if (!scorePostgres) {- if (!hasClickhouseConfigured || !updatedScore) {- throw new InternalServerError(- "No annotation score with this id in this project in Postgres.",- );- } else {- logger.error(- "No annotation score with this id in this project in Postgres.",- );- return validateDbScore(updatedScore);- }- }- try {- updatedScorePostgres = await ctx.prisma.score.update({- where: {- id: scorePostgres.id,- projectId: input.projectId,- },- data: {- value: input.value,- stringValue: input.stringValue,- comment: input.comment,- authorUserId: ctx.session.user.id,- queueId: input.queueId,- },- });- } catch (error) {- if (!hasClickhouseConfigured || !updatedScore) {- throw new InternalServerError(- `Error updating score for name ${input.name} in Postgres for trace ${input.traceId} in project ${input.projectId}`,- );- } else {- logger.error(- `Error updating score for name ${input.name} in Postgres for trace ${input.traceId} in project ${input.projectId}`,- );- return validateDbScore(updatedScore);- }- }+ updatedScore = {+ ...score,+ value: input.value ?? null,+ stringValue: input.stringValue ?? null,+ comment: input.comment ?? null,+ authorUserId: ctx.session.user.id,+ queueId: input.queueId ?? null,+ };await auditLog({session: ctx.session,resourceType: "score",- resourceId: scorePostgres.id,+ resourceId: input.id,action: "update",- before: scorePostgres,- after: updatedScorePostgres,+ before: score,+ after: updatedScore,});}- const finalUpdatedScore = updatedScore ?? updatedScorePostgres;- if (!finalUpdatedScore) {+ if (!updatedScore) {throw new InternalServerError(`Annotation score could not be updated in project ${input.projectId}`,);}- return validateDbScore(finalUpdatedScore);+ return validateDbScore(updatedScore);}),deleteAnnotationScore: protectedProjectProcedure.input(z.object({ projectId: z.string(), id: z.string() }))@@ -599,91 +470,33 @@ export const scoresRouter = createTRPCRouter({scope: "scores:CUD",});- const hasClickhouseConfigured = env.CLICKHOUSE_URL;let score: Score | null | undefined = null;- if (hasClickhouseConfigured) {- // Fetch the current score from Clickhouse- const clickhouseScore = await getScoreById(- input.projectId,- input.id,- ScoreSource.ANNOTATION,+ // Fetch the current score from Clickhouse+ const clickhouseScore = await getScoreById(+ input.projectId,+ input.id,+ ScoreSource.ANNOTATION,+ );+ if (!clickhouseScore) {+ logger.warn(+ `No annotation score with id ${input.id} in project ${input.projectId} in Clickhouse`,);- if (!clickhouseScore) {- logger.warn(- `No annotation score with id ${input.id} in project ${input.projectId} in Clickhouse`,- );- throw new LangfuseNotFoundError(- `No annotation score with id ${input.id} in project ${input.projectId} in Clickhouse`,- );- } else {- // Audit log only if Postgres is not enabled, as we still run PG and CH ingestion in parallel on cloud- if (env.LANGFUSE_POSTGRES_INGESTION_ENABLED === "false") {- await auditLog({- session: ctx.session,- resourceType: "score",- resourceId: input.id,- action: "delete",- before: clickhouseScore,- });- }-- // Delete the score from Clickhouse- await deleteScore(input.projectId, clickhouseScore.id);- score = clickhouseScore;- }- }-- if (env.LANGFUSE_POSTGRES_INGESTION_ENABLED === "true") {- const scorePostgres = await ctx.prisma.score.findFirst({- where: {- id: input.id,- source: "ANNOTATION",- projectId: input.projectId,- },- });- // Fail silently while Clickhouse is in lead and return early- if (!scorePostgres) {- if (!hasClickhouseConfigured) {- throw new InternalServerError(- "No annotation score with this id in this project in Postgres.",- );- } else {- logger.error(- "No annotation score with this id in this project in Postgres.",- );- return;- }- }-+ throw new LangfuseNotFoundError(+ `No annotation score with id ${input.id} in project ${input.projectId} in Clickhouse`,+ );+ } else {await auditLog({session: ctx.session,resourceType: "score",- resourceId: scorePostgres.id,+ resourceId: input.id,action: "delete",- before: scorePostgres,+ before: clickhouseScore,});- // Fail silently while Clickhouse is in lead and return early- try {- // Delete the score from Postgres- await ctx.prisma.score.delete({- where: {- id: scorePostgres.id,- projectId: input.projectId,- },- });- score = hasClickhouseConfigured ? score : scorePostgres;- } catch (error) {- if (!hasClickhouseConfigured) {- throw new InternalServerError(- "Error deleting annotation score in Postgres.",- );- } else {- logger.error("Error deleting annotation score in Postgres.");- return;- }- }+ // Delete the score from Clickhouse+ await deleteScore(input.projectId, clickhouseScore.id);+ score = clickhouseScore;}if (!score) {diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.tsindex c00a95a60d..ba37cef2d8 100644--- a/web/src/server/api/routers/traces.ts+++ b/web/src/server/api/routers/traces.ts@@ -736,50 +736,27 @@ export const traceRouter = createTRPCRouter({});let trace;- if (env.LANGFUSE_POSTGRES_INGESTION_ENABLED === "true") {- trace = await ctx.prisma.trace.update({- where: {- id: input.traceId,- projectId: input.projectId,- },- data: {- bookmarked: input.bookmarked,- },- });- }- if (env.CLICKHOUSE_URL) {- const clickhouseTrace = await getTraceById(- input.traceId,- input.projectId,+ const clickhouseTrace = await getTraceById(+ input.traceId,+ input.projectId,+ );+ if (clickhouseTrace) {+ trace = clickhouseTrace;+ clickhouseTrace.bookmarked = input.bookmarked;+ await upsertTrace(convertTraceDomainToClickhouse(clickhouseTrace));+ } else {+ logger.error(+ `Trace not found in Clickhouse: ${input.traceId}. Skipping bookmark.`,);- if (clickhouseTrace) {- trace = clickhouseTrace;- clickhouseTrace.bookmarked = input.bookmarked;- await upsertTrace(convertTraceDomainToClickhouse(clickhouseTrace));- } else {- logger.error(- `Trace not found in Clickhouse: ${input.traceId}. Skipping bookmark.`,- );- }}return trace;} catch (error) {logger.error("Failed to call traces.bookmark", error);- if (- error instanceof Prisma.PrismaClientKnownRequestError &&- error.code === "P2025" // Record to update not found- ) {- throw new TRPCError({- code: "NOT_FOUND",- message: "Trace not found in project",- });- } else {- throw new TRPCError({- code: "INTERNAL_SERVER_ERROR",- });- }+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ });}}),publish: protectedProjectProcedure@@ -805,51 +782,27 @@ export const traceRouter = createTRPCRouter({after: input.public,});- if (env.LANGFUSE_POSTGRES_INGESTION_ENABLED === "true") {- await ctx.prisma.trace.update({- where: {- id: input.traceId,- projectId: input.projectId,- },- data: {- public: input.public,- },- });- }-- if (env.CLICKHOUSE_URL) {- const clickhouseTrace = await getTraceById(- input.traceId,- input.projectId,+ const clickhouseTrace = await getTraceById(+ input.traceId,+ input.projectId,+ );+ if (!clickhouseTrace) {+ logger.error(+ `Trace not found in Clickhouse: ${input.traceId}. Skipping publishing.`,);- if (!clickhouseTrace) {- logger.error(- `Trace not found in Clickhouse: ${input.traceId}. Skipping publishing.`,- );- throw new TRPCError({- code: "NOT_FOUND",- message: "Trace not found",- });- }- clickhouseTrace.public = input.public;- await upsertTrace(convertTraceDomainToClickhouse(clickhouseTrace));- return clickhouseTrace;- }- } catch (error) {- logger.error("Failed to call traces.publish", error);- if (- error instanceof Prisma.PrismaClientKnownRequestError &&- error.code === "P2025" // Record to update not found- ) {throw new TRPCError({code: "NOT_FOUND",- message: "Trace not found in project",- });- } else {- throw new TRPCError({- code: "INTERNAL_SERVER_ERROR",+ message: "Trace not found",});}+ clickhouseTrace.public = input.public;+ await upsertTrace(convertTraceDomainToClickhouse(clickhouseTrace));+ return clickhouseTrace;+ } catch (error) {+ logger.error("Failed to call traces.publish", error);+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ });}}),updateTags: protectedProjectProcedure@@ -875,34 +828,21 @@ export const traceRouter = createTRPCRouter({after: input.tags,});- if (env.LANGFUSE_POSTGRES_INGESTION_ENABLED === "true") {- await ctx.prisma.trace.update({- where: {- id: input.traceId,- projectId: input.projectId,- },- data: {- tags: {- set: input.tags,- },- },- });- }-- if (env.CLICKHOUSE_URL) {- const clickhouseTrace = await getTraceById(- input.traceId,- input.projectId,+ const clickhouseTrace = await getTraceById(+ input.traceId,+ input.projectId,+ );+ if (!clickhouseTrace) {+ logger.error(+ `Trace not found in Clickhouse: ${input.traceId}. Skipping tag update.`,);- if (!clickhouseTrace) {- logger.error(- `Trace not found in Clickhouse: ${input.traceId}. Skipping tag update.`,- );- return;- }- clickhouseTrace.tags = input.tags;- await upsertTrace(convertTraceDomainToClickhouse(clickhouseTrace));+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Trace not found",+ });}+ clickhouseTrace.tags = input.tags;+ await upsertTrace(convertTraceDomainToClickhouse(clickhouseTrace));} catch (error) {logger.error("Failed to call traces.updateTags", error);throw new TRPCError({diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.tsindex c28fb8cc63..1ffe2ffece 100644--- a/web/src/server/api/trpc.ts+++ b/web/src/server/api/trpc.ts@@ -83,8 +83,6 @@ import {getTraceById,logger,} from "@langfuse/shared/src/server";-import { isClickhouseAdminEligible } from "@/src/server/utils/checkClickhouseAccess";-import { env } from "@/src/env.mjs";setUpSuperjson();@@ -347,29 +345,7 @@ const enforceTraceAccess = t.middleware(async ({ ctx, rawInput, next }) => {const projectId = result.data.projectId;const timestamp = result.data.timestamp;- let trace;-- // first check clickhoue for admin use case if sent via the API accordingly- if (- result.data.queryClickhouse === true &&- isClickhouseAdminEligible(ctx.session?.user) // basically checks if user exists and admin- ) {- trace = await getTraceById(traceId, projectId, timestamp ?? undefined);- // check from postgres for non admins when env is set accordingly- } else if (env.LANGFUSE_READ_FROM_POSTGRES_ONLY === "true") {- trace = await prisma.trace.findFirst({- where: {- id: traceId,- projectId: projectId,- },- select: {- public: true,- },- });- // check clickhouse otherwise- } else {- trace = await getTraceById(traceId, projectId, timestamp ?? undefined);- }+ const trace = await getTraceById(traceId, projectId, timestamp ?? undefined);if (!trace) {logger.error(`Trace with id ${traceId} not found for project ${projectId}`);diff --git a/web/src/server/utils/checkClickhouseAccess.ts b/web/src/server/utils/checkClickhouseAccess.tsindex 11fecd13d4..1b6db6be95 100644--- a/web/src/server/utils/checkClickhouseAccess.ts+++ b/web/src/server/utils/checkClickhouseAccess.ts@@ -1,12 +1,5 @@import { env } from "@/src/env.mjs";-import {- instrumentAsync,- logger,- recordHistogram,-} from "@langfuse/shared/src/server";import { type User } from "next-auth";-import * as opentelemetry from "@opentelemetry/api";-import { TRPCError } from "@trpc/server";export const isClickhouseAdminEligible = (user?: User | null) => {return (@@ -27,125 +20,6 @@ export const measureAndReturnApi = async <T, Y>(args: {pgExecution: (input: T) => Promise<Y>;clickhouseExecution: (input: T) => Promise<Y>;}) => {- return instrumentAsync(- {- name: "clickhouse-experiment",- spanKind: opentelemetry.SpanKind.INTERNAL,- },- async (currentSpan) => {- const { input, user, pgExecution, clickhouseExecution } = args;-- currentSpan?.setAttribute("operation", args.operation);-- if (input.queryClickhouse && !isClickhouseAdminEligible(user)) {- throw new TRPCError({- code: "UNAUTHORIZED",- message: "Not eligible to query clickhouse",- });- }-- const excludedOperations =- env.LANGFUSE_EXPERIMENT_EXCLUDED_OPERATIONS?.split(",");-- // if operation is excluded, return postgres only- if (excludedOperations?.includes(args.operation)) {- return await pgExecution(input);- }-- // if query clickhouse, return clickhouse only. Only possible for admin users- if (input.queryClickhouse) {- return await clickhouseExecution(input);- }-- if (- env.LANGFUSE_READ_FROM_CLICKHOUSE_ONLY === "true"- // &&- // !args.operation.includes("dataset")- ) {- return await clickhouseExecution(input);- }-- // logic for regular users:- // if env.LANGFUSE_READ_FROM_POSTGRES_ONLY is true, return postgres only- // otherwise fetch both and compare timing- // if env.LANGFUSE_RETURN_FROM_CLICKHOUSE is true, return clickhouse data-- const isExcludedFromClickhouse =- user?.featureFlags.excludeClickhouseRead ?? false;-- const excludedProjects =- env.LANGFUSE_EXPERIMENT_EXCLUDED_PROJECT_IDS?.split(",") ?? [];-- const isExcludedProject = excludedProjects.includes(- input.projectId ?? "",- );-- if (- env.LANGFUSE_READ_FROM_POSTGRES_ONLY === "true" ||- isExcludedFromClickhouse ||- isExcludedProject- ) {- logger.info("Read from postgres only");- return await pgExecution(input);- }-- logger.debug("Read from postgres and clickhouse");- try {- const [[pgResult, pgDuration], [chResult, chDuration]] =- await Promise.all([- executionWrapper(input, pgExecution, currentSpan, "pg"),- executionWrapper(input, clickhouseExecution, currentSpan, "ch"),- ]);- // Positive duration difference means clickhouse is faster- const durationDifference = pgDuration - chDuration;- currentSpan?.setAttribute(- "execution-time-difference",- durationDifference,- );- currentSpan?.setAttribute("pg-duration", pgDuration);- currentSpan?.setAttribute("ch-duration", chDuration);-- recordHistogram("langfuse.clickhouse_experiment", chDuration, {- operation: args.operation,- database: "clickhouse",- });- recordHistogram("langfuse.clickhouse_experiment", pgDuration, {- operation: args.operation,- database: "postgres",- });-- // if (args.operation.includes("dataset")) {- // logger.info(- // `operation: ${args.operation} pg result: ${JSON.stringify(pgResult)}, ch result: ${JSON.stringify(chResult)}`,- // );- // return pgResult;- // }-- return env.LANGFUSE_RETURN_FROM_CLICKHOUSE === "true"- ? chResult- : pgResult;- } catch (e) {- logger.error(- "Error in clickhouse experiment wrapper. Retrying leading store.",- e,- );- return env.LANGFUSE_RETURN_FROM_CLICKHOUSE === "true"- ? clickhouseExecution(input)- : pgExecution(input);- }- },- );-};--const executionWrapper = async <T, Y>(- input: T & { queryClickhouse: boolean },- fn: (input: T) => Promise<Y>,- span?: opentelemetry.Span,- attributePrefix?: string,-): Promise<[Y, number]> => {- const startTime = Date.now();- const res = await fn(input);- const duration = Date.now() - startTime;- span?.setAttribute(`${attributePrefix}-duration`, duration);- return [res, duration];+ const { input, clickhouseExecution } = args;+ return await clickhouseExecution(input);};diff --git a/worker/src/ee/evaluation/evalService.ts b/worker/src/ee/evaluation/evalService.tsindex 94e83b788c..ac68704b91 100644--- a/worker/src/ee/evaluation/evalService.ts+++ b/worker/src/ee/evaluation/evalService.ts@@ -25,7 +25,6 @@ import {import {availableTraceEvalVariables,ChatMessageRole,- evalTraceTableCols,ForbiddenError,LangfuseNotFoundError,LLMApiKeySchema,@@ -95,32 +94,12 @@ export const createEvalJobs = async ({const validatedFilter = z.array(singleFilter).parse(config.filter);// Check whether the trace already exists in the database.- let traceExists: boolean = false;- if (env.LANGFUSE_RETURN_FROM_CLICKHOUSE === "true") {- traceExists = await checkTraceExists(- event.projectId,- event.traceId,- new Date(),- config.target_object === "trace" ? validatedFilter : [],- );- } else {- const condition = tableColumnsToSqlFilterAndPrefix(- config.target_object === "trace" ? validatedFilter : [],- evalTraceTableCols,- "traces",- );-- const joinedQuery = Prisma.sql`- SELECT id- FROM traces as t- WHERE project_id = ${event.projectId}- AND id = ${event.traceId}- ${condition}- `;-- const traces = await prisma.$queryRaw<Array<{ id: string }>>(joinedQuery);- traceExists = traces.length > 0;- }+ const traceExists = await checkTraceExists(+ event.projectId,+ event.traceId,+ new Date(),+ config.target_object === "trace" ? validatedFilter : [],+ );const isDatasetConfig = config.target_object === "dataset";let datasetItem:@@ -168,19 +147,11 @@ export const createEvalJobs = async ({? event.observationId: datasetItem?.sourceObservationId;if (observationId) {- const observationExists =- env.LANGFUSE_RETURN_FROM_CLICKHOUSE === "true"- ? await checkObservationExists(- event.projectId,- observationId,- new Date(),- )- : await kyselyPrisma.$kysely- .selectFrom("observations")- .select("id")- .where("project_id", "=", event.projectId)- .where("id", "=", observationId)- .executeTakeFirst();+ const observationExists = await checkObservationExists(+ event.projectId,+ observationId,+ new Date(),+ );if (!observationExists) {logger.warn(@@ -472,15 +443,6 @@ export const evaluate = async ({source: ScoreSource.EVAL,};- if (env.LANGFUSE_POSTGRES_INGESTION_ENABLED === "true") {- await prisma.score.create({- data: {- ...baseScore,- projectId: event.projectId,- },- });- }-// Write score to S3 and ingest into queue for Clickhouse processingtry {const s3Client = getS3StorageServiceClient(@@ -635,19 +597,10 @@ export async function extractVariablesFromTracingData({return { var: variable, value: "" };}- const trace: Record<string, unknown> | undefined =- env.LANGFUSE_RETURN_FROM_CLICKHOUSE === "true"- ? await getTraceById(traceId, projectId)- : await kyselyPrisma.$kysely- .selectFrom("traces as t")- .select(- sql`${sql.raw(safeInternalColumn.internal)}`.as(- safeInternalColumn.id,- ),- ) // query the internal column name raw- .where("id", "=", traceId)- .where("project_id", "=", projectId)- .executeTakeFirst();+ const trace: Record<string, unknown> | undefined = await getTraceById(+ traceId,+ projectId,+ );// user facing errorsif (!trace) {@@ -684,29 +637,15 @@ export async function extractVariablesFromTracingData({return { var: variable, value: "" };}- const observation: Record<string, unknown> | undefined =- env.LANGFUSE_RETURN_FROM_CLICKHOUSE === "true"- ? (- await getObservationForTraceIdByName(- traceId,- projectId,- mapping.objectName,- undefined,- true,- )- ).shift() // We only take the first match and ignore duplicate generation-names in a trace.- : await kyselyPrisma.$kysely- .selectFrom("observations as o")- .select(- sql`${sql.raw(safeInternalColumn.internal)}`.as(- safeInternalColumn.id,- ),- ) // query the internal column name raw- .where("trace_id", "=", traceId)- .where("project_id", "=", projectId)- .where("name", "=", mapping.objectName)- .orderBy("start_time", "desc")- .executeTakeFirst();+ const observation: Record<string, unknown> | undefined = (+ await getObservationForTraceIdByName(+ traceId,+ projectId,+ mapping.objectName,+ undefined,+ true,+ )+ ).shift(); // We only take the first match and ignore duplicate generation-names in a trace.// user facing errorsif (!observation) {diff --git a/worker/src/env.ts b/worker/src/env.tsindex 31b3dc28c0..f31ee3ada1 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -107,9 +107,6 @@ const EnvSchema = z.object({.default(5),STRIPE_SECRET_KEY: z.string().optional(),- // TODO: Remove for go-live- LANGFUSE_RETURN_FROM_CLICKHOUSE: z.enum(["true", "false"]).default("true"),-// Skip the read from ClickHouse within the Ingestion pipeline for the given// project ids. Applicable for projects that were created after the S3 write// was activated and which don't rely on historic updates.@@ -157,9 +154,6 @@ const EnvSchema = z.object({QUEUE_CONSUMER_POSTHOG_INTEGRATION_QUEUE_IS_ENABLED: z.enum(["true", "false"]).default("true"),- LANGFUSE_POSTGRES_INGESTION_ENABLED: z- .enum(["true", "false"])- .default("false"),// Core data S3 upload - only used internallyLANGFUSE_S3_CORE_DATA_EXPORT_IS_ENABLED: zdiff --git a/worker/src/features/batchExport/handleBatchExportJob.ts b/worker/src/features/batchExport/handleBatchExportJob.tsindex e055a1ac56..94d3eef622 100644--- a/worker/src/features/batchExport/handleBatchExportJob.ts+++ b/worker/src/features/batchExport/handleBatchExportJob.ts@@ -149,83 +149,53 @@ export const getDatabaseReadStream = async ({? [...filter, createdAtCutoffFilter]: [createdAtCutoffFilter];- if (env.LANGFUSE_RETURN_FROM_CLICKHOUSE === "false") {- 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: finalFilter,- orderBy,- limit: pageSize,- page: Math.floor(offset / pageSize),+ const sessionsFilter = await getPublicSessionsFilter(+ projectId,+ finalFilter ?? [],+ );+ const sessions = await getSessionsWithMetrics({+ projectId: projectId,+ filter: sessionsFilter,+ orderBy: orderBy,+ limit: pageSize,+ page: Math.floor(offset / pageSize),+ });++ const prismaSessionInfo = await prisma.traceSession.findMany({+ where: {+ id: {+ in: sessions.map((s) => s.session_id),},- );- return prisma.$queryRaw<BatchExportSessionsRow[]>(query);- } else {- const sessionsFilter = await getPublicSessionsFilter(- projectId,- finalFilter ?? [],- );- const sessions = await getSessionsWithMetrics({projectId: projectId,- filter: sessionsFilter,- orderBy: orderBy,- limit: pageSize,- page: Math.floor(offset / pageSize),- });-- const prismaSessionInfo = await prisma.traceSession.findMany({- where: {- id: {- in: sessions.map((s) => s.session_id),- },- projectId: projectId,- },- select: {- id: true,- bookmarked: true,- public: true,- },- });- return sessions.map((s) => {- const row: BatchExportSessionsRow = {- id: s.session_id,- userIds: s.user_ids,- countTraces: s.trace_ids.length,- sessionDuration: Number(s.duration) / 1000,- inputCost: new Decimal(s.session_input_cost),- outputCost: new Decimal(s.session_output_cost),- totalCost: new Decimal(s.session_total_cost),- totalTokens: BigInt(s.session_total_usage),- traceTags: s.trace_tags,- createdAt: new Date(s.min_timestamp),- bookmarked:- prismaSessionInfo.find((p) => p.id === s.session_id)- ?.bookmarked ?? false,- public:- prismaSessionInfo.find((p) => p.id === s.session_id)- ?.public ?? false,- totalCount: s.trace_count,- };- return row;- });- }+ },+ select: {+ id: true,+ bookmarked: true,+ public: true,+ },+ });+ return sessions.map((s) => {+ const row: BatchExportSessionsRow = {+ id: s.session_id,+ userIds: s.user_ids,+ countTraces: s.trace_ids.length,+ sessionDuration: Number(s.duration) / 1000,+ inputCost: new Decimal(s.session_input_cost),+ outputCost: new Decimal(s.session_output_cost),+ totalCost: new Decimal(s.session_total_cost),+ totalTokens: BigInt(s.session_total_usage),+ traceTags: s.trace_tags,+ createdAt: new Date(s.min_timestamp),+ bookmarked:+ prismaSessionInfo.find((p) => p.id === s.session_id)+ ?.bookmarked ?? false,+ public:+ prismaSessionInfo.find((p) => p.id === s.session_id)?.public ??+ false,+ totalCount: s.trace_count,+ };+ return row;+ });},1000,env.BATCH_EXPORT_ROW_LIMIT,@@ -244,73 +214,48 @@ export const getDatabaseReadStream = async ({return new DatabaseReadStream<unknown>(async (pageSize: number, offset: number) => {- let chunk: FullObservationsWithScores;- if (env.LANGFUSE_RETURN_FROM_CLICKHOUSE === "false") {- emptyScoreColumns = await getEmptyScoreColumns(- projectId,- cutoffCreatedAt,- filter- ? [...filter, createdAtCutoffFilter]- : [createdAtCutoffFilter],- isGenerationTimestampFilter,- );-- const query = createGenerationsQuery({- projectId,- limit: pageSize,- page: Math.floor(offset / pageSize),- filterCondition,- orderByCondition,- datetimeFilter,- selectScoreValues: true,- selectIOAndMetadata: true,- });-- chunk = await prisma.$queryRaw<FullObservationsWithScores>(query);- } else {- const distinctScoreNames = await getDistinctScoreNames(- projectId,- cutoffCreatedAt,- filter- ? [...filter, createdAtCutoffFilterCh]- : [createdAtCutoffFilterCh],- isGenerationTimestampFilter,- );-- emptyScoreColumns = distinctScoreNames.reduce(- (acc, name) => ({ ...acc, [name]: null }),- {} as Record<string, null>,- );-- const generations = await getObservationsTableWithModelData({- projectId,- limit: pageSize,- offset: offset,- filter: filter- ? [...filter, createdAtCutoffFilterCh]- : [createdAtCutoffFilterCh],- orderBy: orderBy,- selectIOAndMetadata: true,- });- const scores = await getScoresForObservations(- projectId,- generations.map((gen) => gen.id),+ const distinctScoreNames = await getDistinctScoreNames(+ projectId,+ cutoffCreatedAt,+ filter+ ? [...filter, createdAtCutoffFilterCh]+ : [createdAtCutoffFilterCh],+ isGenerationTimestampFilter,+ );++ emptyScoreColumns = distinctScoreNames.reduce(+ (acc, name) => ({ ...acc, [name]: null }),+ {} as Record<string, null>,+ );++ const generations = await getObservationsTableWithModelData({+ projectId,+ limit: pageSize,+ offset: offset,+ filter: filter+ ? [...filter, createdAtCutoffFilterCh]+ : [createdAtCutoffFilterCh],+ orderBy: orderBy,+ selectIOAndMetadata: true,+ });+ const scores = await getScoresForObservations(+ projectId,+ generations.map((gen) => gen.id),+ );++ const chunk = generations.map((generation) => {+ const filteredScores = scores.filter(+ (s) => s.observationId === generation.id,);- chunk = generations.map((generation) => {- const filteredScores = scores.filter(- (s) => s.observationId === generation.id,- );-- const outputScores: Record<string, string[] | number[]> =- prepareScoresForOutput(filteredScores);+ const outputScores: Record<string, string[] | number[]> =+ prepareScoresForOutput(filteredScores);- return {- ...generation,- scores: outputScores,- };- });- }+ return {+ ...generation,+ scores: outputScores,+ };+ });return getChunkWithFlattenedScores(chunk, emptyScoreColumns);},@@ -332,138 +277,91 @@ export const getDatabaseReadStream = async ({return new DatabaseReadStream<unknown>(async (pageSize: number, offset: number) => {- let chunk: BatchExportTracesRow[];-- if (env.LANGFUSE_RETURN_FROM_CLICKHOUSE === "true") {- const distinctScoreNames = await getDistinctScoreNames(+ const distinctScoreNames = await getDistinctScoreNames(+ projectId,+ cutoffCreatedAt,+ filter+ ? [...filter, createdAtCutoffFilter]+ : [createdAtCutoffFilter],+ isTraceTimestampFilter,+ );+ emptyScoreColumns = distinctScoreNames.reduce(+ (acc, name) => ({ ...acc, [name]: null }),+ {} as Record<string, null>,+ );++ const traces = await getTracesTable(+ projectId,+ filter+ ? [...filter, createdAtCutoffFilter]+ : [createdAtCutoffFilter],+ undefined,+ orderBy,+ pageSize,+ Math.floor(offset / pageSize),+ );++ const [metrics, fullTraces] = await Promise.all([+ getTracesTableMetrics({projectId,- cutoffCreatedAt,- filter- ? [...filter, createdAtCutoffFilter]- : [createdAtCutoffFilter],- isTraceTimestampFilter,- );- emptyScoreColumns = distinctScoreNames.reduce(- (acc, name) => ({ ...acc, [name]: null }),- {} as Record<string, null>,- );-- const traces = await getTracesTable(+ filter: [+ ...(filter ?? []),+ {+ type: "stringOptions",+ operator: "any of",+ column: "ID",+ value: traces.map((t) => t.id),+ },+ ],+ }),+ getTracesByIds(+ traces.map((t) => t.id),projectId,- filter- ? [...filter, createdAtCutoffFilter]- : [createdAtCutoffFilter],- undefined,- orderBy,- pageSize,- Math.floor(offset / pageSize),- );-- const [metrics, fullTraces] = await Promise.all([- getTracesTableMetrics({- projectId,- filter: [- ...(filter ?? []),- {- type: "stringOptions",- operator: "any of",- column: "ID",- value: traces.map((t) => t.id),- },- ],- }),- getTracesByIds(- traces.map((t) => t.id),- projectId,- traces.reduce(- (min, t) => (!min || t.timestamp < min ? t.timestamp : min),- undefined as Date | undefined,- ),+ traces.reduce(+ (min, t) => (!min || t.timestamp < min ? t.timestamp : min),+ undefined as Date | undefined,),- ]);+ ),+ ]);++ const scores = await getScoresForTraces({+ projectId,+ traceIds: traces.map((t) => t.id),+ });++ const chunk = traces.map((t) => {+ const metric = metrics.find((m) => m.id === t.id);+ const filteredScores = scores.filter((s) => s.traceId === t.id);++ const outputScores: Record<string, string[] | number[]> =+ prepareScoresForOutput(filteredScores);+ const fullTrace = fullTraces.find(+ (fullTrace) => fullTrace.id === t.id,+ );- const scores = await getScoresForTraces({- projectId,- traceIds: traces.map((t) => t.id),- });-- chunk = traces.map((t) => {- const metric = metrics.find((m) => m.id === t.id);- const filteredScores = scores.filter((s) => s.traceId === t.id);-- const outputScores: Record<string, string[] | number[]> =- prepareScoresForOutput(filteredScores);- const fullTrace = fullTraces.find(- (fullTrace) => fullTrace.id === t.id,- );-- return {- ...t,- input: fullTrace?.input,- output: fullTrace?.output,- metadata: fullTrace?.metadata,- latency: metric?.latency,- name: t.name ?? "",- usage: {- promptTokens: metric?.promptTokens,- completionTokens: metric?.completionTokens,- totalTokens: metric?.totalTokens,- },- inputCost: metric?.calculatedInputCost,- outputCost: metric?.calculatedOutputCost,- totalCost: metric?.calculatedTotalCost,- level: metric?.level,- observationCount: Number(metric?.observationCount),- scores: outputScores,- inputTokens: metric?.promptTokens,- outputTokens: metric?.completionTokens,+ return {+ ...t,+ input: fullTrace?.input,+ output: fullTrace?.output,+ metadata: fullTrace?.metadata,+ latency: metric?.latency,+ name: t.name ?? "",+ usage: {+ promptTokens: metric?.promptTokens,+ completionTokens: metric?.completionTokens,totalTokens: metric?.totalTokens,- };- });- } else {- emptyScoreColumns = await getEmptyScoreColumns(- projectId,- cutoffCreatedAt,- filter- ? [...filter, createdAtCutoffFilter]- : [createdAtCutoffFilter],- isTraceTimestampFilter,- );- const query = createTracesQuery({- select: Prisma.sql`- t."bookmarked",- t."id",- t."timestamp",- t."name",- t."user_id" AS "userId",- observation_metrics."level" AS "level",- observation_metrics."observationCount" AS "observationCount",- s_avg."scores_values" AS "scores",- observation_metrics.latency AS "latency",- t."release",- t."version",- t.session_id AS "sessionId",- t."input",- t."output",- t."metadata",- t."tags",- COALESCE(generation_metrics."promptTokens", 0)::bigint AS "usage.promptTokens",- COALESCE(generation_metrics."completionTokens", 0)::bigint AS "usage.completionTokens",- COALESCE(generation_metrics."totalTokens", 0)::bigint AS "usage.totalTokens",- COALESCE(generation_metrics."calculatedInputCost", 0)::numeric AS "inputCost",- COALESCE(generation_metrics."calculatedOutputCost", 0)::numeric AS "outputCost",- COALESCE(generation_metrics."calculatedTotalCost", 0)::numeric AS "totalCost"- `,- projectId,- limit: pageSize,- page: Math.floor(offset / pageSize),- filterCondition,- orderByCondition,- observationTimeseriesFilter,- selectScoreValues: true,- });- chunk = await prisma.$queryRaw<BatchExportTracesRow[]>(query);- }+ },+ inputCost: metric?.calculatedInputCost,+ outputCost: metric?.calculatedOutputCost,+ totalCost: metric?.calculatedTotalCost,+ level: metric?.level,+ observationCount: Number(metric?.observationCount),+ scores: outputScores,+ inputTokens: metric?.promptTokens,+ outputTokens: metric?.completionTokens,+ totalTokens: metric?.totalTokens,+ };+ });return getChunkWithFlattenedScores(chunk, emptyScoreColumns);},