Skip to content

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

chore: remove prisma references to traces, observations, scores (#5672)

Steffen Schmitzb8d0a4bbe8d1
diff --git a/packages/shared/package.json b/packages/shared/package.json
index bc58429732..7a7675deb8 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -33,7 +33,7 @@
"scripts": {
"build": "tsc",
"dev": "tsc --watch",
- "lint": "eslint . --ext .js,.jsx,.ts,.tsx --max-warnings 106",
+ "lint": "eslint . --ext .js,.jsx,.ts,.tsx --max-warnings 64",
"lint:fix": "eslint . --ext .js,.jsx,.ts,.tsx --fix",
"db:migrate": "DISABLE_ERD=false dotenv -e ../../.env -- npx prisma migrate dev",
"db:push": "DISABLE_ERD=false dotenv -e ../../.env -- npx prisma db push",
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index 13f7d56ca4..45178c36cb 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -12,25 +12,25 @@ export const Role = {
NONE: "NONE"
} as const;
export type Role = (typeof Role)[keyof typeof Role];
-export const ObservationType = {
+export const LegacyPrismaObservationType = {
SPAN: "SPAN",
EVENT: "EVENT",
GENERATION: "GENERATION"
} as const;
-export type ObservationType = (typeof ObservationType)[keyof typeof ObservationType];
-export const ObservationLevel = {
+export type LegacyPrismaObservationType = (typeof LegacyPrismaObservationType)[keyof typeof LegacyPrismaObservationType];
+export const LegacyPrismaObservationLevel = {
DEBUG: "DEBUG",
DEFAULT: "DEFAULT",
WARNING: "WARNING",
ERROR: "ERROR"
} as const;
-export type ObservationLevel = (typeof ObservationLevel)[keyof typeof ObservationLevel];
-export const ScoreSource = {
+export type LegacyPrismaObservationLevel = (typeof LegacyPrismaObservationLevel)[keyof typeof LegacyPrismaObservationLevel];
+export const LegacyPrismaScoreSource = {
ANNOTATION: "ANNOTATION",
API: "API",
EVAL: "EVAL"
} as const;
-export type ScoreSource = (typeof ScoreSource)[keyof typeof ScoreSource];
+export type LegacyPrismaScoreSource = (typeof LegacyPrismaScoreSource)[keyof typeof LegacyPrismaScoreSource];
export const ScoreDataType = {
CATEGORICAL: "CATEGORICAL",
NUMERIC: "NUMERIC",
@@ -284,6 +284,77 @@ export type JobExecution = {
job_input_dataset_item_id: string | null;
job_output_score_id: string | null;
};
+export type LegacyPrismaObservation = {
+ id: string;
+ trace_id: string | null;
+ project_id: string;
+ type: LegacyPrismaObservationType;
+ start_time: Generated<Timestamp>;
+ end_time: Timestamp | null;
+ name: string | null;
+ metadata: unknown | null;
+ parent_observation_id: string | null;
+ level: Generated<LegacyPrismaObservationLevel>;
+ status_message: string | null;
+ version: string | null;
+ created_at: Generated<Timestamp>;
+ updated_at: Generated<Timestamp>;
+ model: string | null;
+ internal_model: string | null;
+ internal_model_id: string | null;
+ modelParameters: unknown | null;
+ input: unknown | null;
+ output: unknown | null;
+ prompt_tokens: Generated<number>;
+ completion_tokens: Generated<number>;
+ total_tokens: Generated<number>;
+ unit: string | null;
+ input_cost: string | null;
+ output_cost: string | null;
+ total_cost: string | null;
+ calculated_input_cost: string | null;
+ calculated_output_cost: string | null;
+ calculated_total_cost: string | null;
+ completion_start_time: Timestamp | null;
+ prompt_id: string | null;
+};
+export type LegacyPrismaScore = {
+ id: string;
+ timestamp: Generated<Timestamp>;
+ project_id: string;
+ name: string;
+ value: number | null;
+ source: LegacyPrismaScoreSource;
+ author_user_id: string | null;
+ comment: string | null;
+ trace_id: string;
+ observation_id: string | null;
+ config_id: string | null;
+ string_value: string | null;
+ queue_id: string | null;
+ created_at: Generated<Timestamp>;
+ updated_at: Generated<Timestamp>;
+ data_type: Generated<ScoreDataType>;
+};
+export type LegacyPrismaTrace = {
+ id: string;
+ external_id: string | null;
+ timestamp: Generated<Timestamp>;
+ name: string | null;
+ user_id: string | null;
+ metadata: unknown | null;
+ release: string | null;
+ version: string | null;
+ project_id: string;
+ public: Generated<boolean>;
+ bookmarked: Generated<boolean>;
+ tags: Generated<string[]>;
+ input: unknown | null;
+ output: unknown | null;
+ session_id: string | null;
+ created_at: Generated<Timestamp>;
+ updated_at: Generated<Timestamp>;
+};
export type LlmApiKeys = {
id: string;
created_at: Generated<Timestamp>;
@@ -340,40 +411,6 @@ export type Model = {
tokenizer_id: string | null;
tokenizer_config: unknown | null;
};
-export type Observation = {
- id: string;
- trace_id: string | null;
- project_id: string;
- type: ObservationType;
- start_time: Generated<Timestamp>;
- end_time: Timestamp | null;
- name: string | null;
- metadata: unknown | null;
- parent_observation_id: string | null;
- level: Generated<ObservationLevel>;
- status_message: string | null;
- version: string | null;
- created_at: Generated<Timestamp>;
- updated_at: Generated<Timestamp>;
- model: string | null;
- internal_model: string | null;
- internal_model_id: string | null;
- modelParameters: unknown | null;
- input: unknown | null;
- output: unknown | null;
- prompt_tokens: Generated<number>;
- completion_tokens: Generated<number>;
- total_tokens: Generated<number>;
- unit: string | null;
- input_cost: string | null;
- output_cost: string | null;
- total_cost: string | null;
- calculated_input_cost: string | null;
- calculated_output_cost: string | null;
- calculated_total_cost: string | null;
- completion_start_time: Timestamp | null;
- prompt_id: string | null;
-};
export type ObservationMedia = {
id: string;
project_id: string;
@@ -384,43 +421,6 @@ export type ObservationMedia = {
observation_id: string;
field: string;
};
-export type ObservationView = {
- id: string;
- trace_id: string | null;
- project_id: string;
- type: ObservationType;
- start_time: Timestamp;
- end_time: Timestamp | null;
- name: string | null;
- metadata: unknown | null;
- parent_observation_id: string | null;
- level: Generated<ObservationLevel>;
- status_message: string | null;
- version: string | null;
- created_at: Timestamp;
- updated_at: Timestamp;
- model: string | null;
- modelParameters: unknown | null;
- input: unknown | null;
- output: unknown | null;
- prompt_tokens: Generated<number>;
- completion_tokens: Generated<number>;
- total_tokens: Generated<number>;
- unit: string | null;
- completion_start_time: Timestamp | null;
- prompt_id: string | null;
- prompt_name: string | null;
- prompt_version: number | null;
- model_id: string | null;
- input_price: string | null;
- output_price: string | null;
- total_price: string | null;
- calculated_input_cost: string | null;
- calculated_output_cost: string | null;
- calculated_total_cost: string | null;
- latency: number | null;
- time_to_first_token: number | null;
-};
export type Organization = {
id: string;
name: string;
@@ -492,24 +492,6 @@ export type QueueBackUp = {
content: unknown;
created_at: Generated<Timestamp>;
};
-export type Score = {
- id: string;
- timestamp: Generated<Timestamp>;
- project_id: string;
- name: string;
- value: number | null;
- source: ScoreSource;
- author_user_id: string | null;
- comment: string | null;
- trace_id: string;
- observation_id: string | null;
- config_id: string | null;
- string_value: string | null;
- queue_id: string | null;
- created_at: Generated<Timestamp>;
- updated_at: Generated<Timestamp>;
- data_type: Generated<ScoreDataType>;
-};
export type ScoreConfig = {
id: string;
created_at: Generated<Timestamp>;
@@ -536,25 +518,6 @@ export type SsoConfig = {
auth_provider: string;
auth_config: unknown | null;
};
-export type Trace = {
- id: string;
- external_id: string | null;
- timestamp: Generated<Timestamp>;
- name: string | null;
- user_id: string | null;
- metadata: unknown | null;
- release: string | null;
- version: string | null;
- project_id: string;
- public: Generated<boolean>;
- bookmarked: Generated<boolean>;
- tags: Generated<string[]>;
- input: unknown | null;
- output: unknown | null;
- session_id: string | null;
- created_at: Generated<Timestamp>;
- updated_at: Generated<Timestamp>;
-};
export type TraceMedia = {
id: string;
project_id: string;
@@ -573,26 +536,6 @@ export type TraceSession = {
public: Generated<boolean>;
environment: Generated<string>;
};
-export type TraceView = {
- id: string;
- external_id: string | null;
- timestamp: Generated<Timestamp>;
- name: string | null;
- user_id: string | null;
- metadata: unknown | null;
- release: string | null;
- version: string | null;
- project_id: string;
- public: Generated<boolean>;
- bookmarked: Generated<boolean>;
- tags: Generated<string[]>;
- input: unknown | null;
- output: unknown | null;
- session_id: string | null;
- created_at: Timestamp;
- updated_at: Timestamp;
- duration: number | null;
-};
export type User = {
id: string;
name: string | null;
@@ -633,8 +576,7 @@ export type DB = {
membership_invitations: MembershipInvitation;
models: Model;
observation_media: ObservationMedia;
- observations: Observation;
- observations_view: ObservationView;
+ observations: LegacyPrismaObservation;
organization_memberships: OrganizationMembership;
organizations: Organization;
posthog_integrations: PosthogIntegration;
@@ -644,13 +586,12 @@ export type DB = {
prompts: Prompt;
queue_backups: QueueBackUp;
score_configs: ScoreConfig;
- scores: Score;
+ scores: LegacyPrismaScore;
Session: Session;
sso_configs: SsoConfig;
trace_media: TraceMedia;
trace_sessions: TraceSession;
- traces: Trace;
- traces_view: TraceView;
+ traces: LegacyPrismaTrace;
users: User;
verification_tokens: VerificationToken;
};
diff --git a/packages/shared/prisma/migrations/20250221143400_drop_trace_view_observation_view/migration.sql b/packages/shared/prisma/migrations/20250221143400_drop_trace_view_observation_view/migration.sql
new file mode 100644
index 0000000000..8a68f74479
--- /dev/null
+++ b/packages/shared/prisma/migrations/20250221143400_drop_trace_view_observation_view/migration.sql
@@ -0,0 +1,2 @@
+DROP VIEW IF EXISTS "observations_view";
+DROP VIEW IF EXISTS "traces_view";
\ No newline at end of file
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 686eb5fc1b..6e37a46b6c 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -109,17 +109,15 @@ model Organization {
}
model Project {
- id String @id @default(cuid())
- orgId String @map("org_id")
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- deletedAt DateTime? @map("deleted_at")
+ id String @id @default(cuid())
+ orgId String @map("org_id")
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ deletedAt DateTime? @map("deleted_at")
name String
- retentionDays Int? @map("retention_days")
+ retentionDays Int? @map("retention_days")
projectMembers ProjectMembership[]
- organization Organization @relation(fields: [orgId], references: [id], onUpdate: Cascade, onDelete: Cascade)
- traces Trace[]
- observations Observation[]
+ organization Organization @relation(fields: [orgId], references: [id], onUpdate: Cascade, onDelete: Cascade)
apiKeys ApiKey[]
dataset Dataset[]
invitations MembershipInvitation[]
@@ -131,7 +129,6 @@ model Project {
JobExecution JobExecution[]
LlmApiKeys LlmApiKeys[]
PosthogIntegration PosthogIntegration[]
- Score Score[]
scoreConfig ScoreConfig[]
BatchExport BatchExport[]
comment Comment[]
@@ -140,6 +137,9 @@ model Project {
TraceMedia TraceMedia[]
Media Media[]
ObservationMedia ObservationMedia[]
+ LegacyTrace LegacyPrismaTrace[]
+ LegacyObservation LegacyPrismaObservation[]
+ LegacyScore LegacyPrismaScore[]
@@index([orgId])
@@map("projects")
@@ -283,9 +283,7 @@ model TraceSession {
@@map("trace_sessions")
}
-// Update TraceView below when making changes to this model!
-
-model Trace {
+model LegacyPrismaTrace {
id String @id @default(cuid())
externalId String? @map("external_id")
timestamp DateTime @default(now())
@@ -295,7 +293,6 @@ model Trace {
release String?
version String?
projectId String @map("project_id")
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
public Boolean @default(false)
bookmarked Boolean @default(false)
tags String[] @default([])
@@ -304,6 +301,7 @@ model Trace {
sessionId String? @map("session_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ project Project @relation(fields: [projectId], references: [id])
@@index([projectId, timestamp])
@@index([sessionId])
@@ -316,80 +314,43 @@ model Trace {
@@map("traces")
}
-// This view is based on the trace table. Once prisma supports
-// inheritance, we should remove code duplication here.
-view TraceView {
- // trace fields
- id String @id @default(cuid())
- externalId String? @map("external_id")
- timestamp DateTime @default(now())
- name String?
- userId String? @map("user_id")
- metadata Json?
- release String?
- version String?
- projectId String @map("project_id")
- public Boolean @default(false)
- bookmarked Boolean @default(false)
- tags String[] @default([])
- input Json?
- output Json?
- sessionId String? @map("session_id")
- createdAt DateTime @map("created_at")
- updatedAt DateTime @map("updated_at")
-
- // calculated fields
- duration Float? @map("duration") // can be null if no observations in trace
-
- @@map("traces_view")
-}
-
-// Update ObservationView below when making changes to this model!
-// traceId is optional only due to timing during data injestion
-// (traceId is not necessarily known at the time of observation creation)
-model Observation {
- id String @id @default(cuid())
- traceId String? @map("trace_id")
- projectId String @map("project_id")
- type ObservationType
- startTime DateTime @default(now()) @map("start_time")
- endTime DateTime? @map("end_time")
- name String?
- metadata Json?
- parentObservationId String? @map("parent_observation_id")
- level ObservationLevel @default(DEFAULT)
- statusMessage String? @map("status_message")
- version String?
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
-
+model LegacyPrismaObservation {
+ id String @id @default(cuid())
+ traceId String? @map("trace_id")
+ projectId String @map("project_id")
+ type LegacyPrismaObservationType
+ startTime DateTime @default(now()) @map("start_time")
+ endTime DateTime? @map("end_time")
+ name String?
+ metadata Json?
+ parentObservationId String? @map("parent_observation_id")
+ level LegacyPrismaObservationLevel @default(DEFAULT)
+ statusMessage String? @map("status_message")
+ version String?
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
// GENERATION ONLY
- model String? // user-provided model attribute
- internalModel String? @map("internal_model") // matched model.name that is matched at ingestion time, to be deprecated
- internalModelId String? @map("internal_model_id") // matched model.id that is matched at ingestion time
-
- modelParameters Json?
- input Json?
- output Json?
- promptTokens Int @default(0) @map("prompt_tokens")
- completionTokens Int @default(0) @map("completion_tokens")
- totalTokens Int @default(0) @map("total_tokens")
- unit String?
-
+ model String? // user-provided model attribute
+ internalModel String? @map("internal_model") // matched model.name that is matched at ingestion time, to be deprecated
+ internalModelId String? @map("internal_model_id") // matched model.id that is matched at ingestion time
+ modelParameters Json?
+ input Json?
+ output Json?
+ promptTokens Int @default(0) @map("prompt_tokens")
+ completionTokens Int @default(0) @map("completion_tokens")
+ totalTokens Int @default(0) @map("total_tokens")
+ unit String?
// User provided cost at ingestion
- inputCost Decimal? @map("input_cost")
- outputCost Decimal? @map("output_cost")
- totalCost Decimal? @map("total_cost")
-
+ inputCost Decimal? @map("input_cost")
+ outputCost Decimal? @map("output_cost")
+ totalCost Decimal? @map("total_cost")
// Calculated cost
- calculatedInputCost Decimal? @map("calculated_input_cost")
- calculatedOutputCost Decimal? @map("calculated_output_cost")
- calculatedTotalCost Decimal? @map("calculated_total_cost")
-
- completionStartTime DateTime? @map("completion_start_time")
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
-
- promptId String? @map("prompt_id") // no fk constraint, prompt can be deleted
+ calculatedInputCost Decimal? @map("calculated_input_cost")
+ calculatedOutputCost Decimal? @map("calculated_output_cost")
+ calculatedTotalCost Decimal? @map("calculated_total_cost")
+ completionStartTime DateTime? @map("completion_start_time")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ promptId String? @map("prompt_id") // no fk constraint, prompt can be deleted
@@unique([id, projectId])
@@index([projectId, internalModel, startTime, unit])
@@ -406,88 +367,38 @@ model Observation {
@@map("observations")
}
-// This view is a mix of the observation and model. Once prisma supports
-// inheritance, we should remove code duplication here.
-view ObservationView {
- id String @id @default(cuid())
- traceId String? @map("trace_id")
- projectId String @map("project_id")
- type ObservationType
- startTime DateTime @map("start_time")
- endTime DateTime? @map("end_time")
- name String?
- metadata Json?
- parentObservationId String? @map("parent_observation_id")
- level ObservationLevel @default(DEFAULT)
- statusMessage String? @map("status_message")
- version String?
- createdAt DateTime @map("created_at")
- updatedAt DateTime @map("updated_at")
-
- // GENERATION ONLY
- model String?
- modelParameters Json?
- input Json?
- output Json?
- promptTokens Int @default(0) @map("prompt_tokens")
- completionTokens Int @default(0) @map("completion_tokens")
- totalTokens Int @default(0) @map("total_tokens")
- unit String?
- completionStartTime DateTime? @map("completion_start_time")
-
- // prompts
- promptId String? @map("prompt_id")
- promptName String? @map("prompt_name")
- promptVersion Int? @map("prompt_version")
-
- // model fields
- modelId String? @map("model_id")
- inputPrice Decimal? @map("input_price")
- outputPrice Decimal? @map("output_price")
- totalPrice Decimal? @map("total_price")
-
- // calculated fields
- calculatedInputCost Decimal? @map("calculated_input_cost")
- calculatedOutputCost Decimal? @map("calculated_output_cost")
- calculatedTotalCost Decimal? @map("calculated_total_cost")
- latency Float? @map("latency")
- timeToFirstToken Float? @map("time_to_first_token")
-
- @@map("observations_view")
-}
-
-enum ObservationType {
+enum LegacyPrismaObservationType {
SPAN
EVENT
GENERATION
}
-enum ObservationLevel {
+enum LegacyPrismaObservationLevel {
DEBUG
DEFAULT
WARNING
ERROR
}
-model Score {
- id String @id @default(cuid())
- timestamp DateTime @default(now())
- projectId String @map("project_id")
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+model LegacyPrismaScore {
+ id String @id @default(cuid())
+ timestamp DateTime @default(now())
+ projectId String @map("project_id")
name String
value Float? // always defined if data type is NUMERIC or BOOLEAN, optional for CATEGORICAL
- source ScoreSource
- authorUserId String? @map("author_user_id")
+ source LegacyPrismaScoreSource
+ authorUserId String? @map("author_user_id")
comment String?
- traceId String @map("trace_id")
- observationId String? @map("observation_id")
- configId String? @map("config_id")
- stringValue String? @map("string_value") // always defined if data type is CATEGORICAL or BOOLEAN, null for NUMERIC
- queueId String? @map("queue_id")
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- dataType ScoreDataType @default(NUMERIC) @map("data_type")
- scoreConfig ScoreConfig? @relation(fields: [configId], references: [id], onDelete: SetNull)
+ traceId String @map("trace_id")
+ observationId String? @map("observation_id")
+ configId String? @map("config_id")
+ stringValue String? @map("string_value") // always defined if data type is CATEGORICAL or BOOLEAN, null for NUMERIC
+ queueId String? @map("queue_id")
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ dataType ScoreDataType @default(NUMERIC) @map("data_type")
+ scoreConfig ScoreConfig? @relation(fields: [configId], references: [id], onDelete: SetNull)
+ project Project @relation(fields: [projectId], references: [id])
@@unique([id, projectId]) // used for upserts via prisma
@@index(timestamp)
@@ -502,26 +413,26 @@ model Score {
@@map("scores")
}
-enum ScoreSource {
+enum LegacyPrismaScoreSource {
ANNOTATION
API
EVAL
}
model ScoreConfig {
- id String @id @default(cuid())
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- projectId String @map("project_id")
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ id String @id @default(cuid())
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ projectId String @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
name String
- dataType ScoreDataType @map("data_type")
- isArchived Boolean @default(false) @map("is_archived")
- minValue Float? @map("min_value")
- maxValue Float? @map("max_value")
- categories Json? @map("categories")
+ dataType ScoreDataType @map("data_type")
+ isArchived Boolean @default(false) @map("is_archived")
+ minValue Float? @map("min_value")
+ maxValue Float? @map("max_value")
+ categories Json? @map("categories")
description String?
- score Score[]
+ legacyScore LegacyPrismaScore[]
@@unique([id, projectId]) // used for upserts via prisma
@@index([dataType])
diff --git a/packages/shared/prisma/seed.ts b/packages/shared/prisma/seed.ts
index d30eab424e..4010485832 100644
--- a/packages/shared/prisma/seed.ts
+++ b/packages/shared/prisma/seed.ts
@@ -2,8 +2,6 @@ import {
PrismaClient,
type Project,
type Prisma,
- ObservationType,
- ScoreSource,
ScoreDataType,
AnnotationQueueObjectType,
} from "../src/index";
@@ -266,38 +264,23 @@ async function main() {
const traceVolume = environment === "load" ? LOAD_TRACE_VOLUME : 100;
- const {
- traces,
- observations,
- scores,
- sessions,
- events,
- comments,
- queueItems,
- } = createObjects(
- traceVolume,
- envTags,
- colorTags,
- project1,
- project2,
- promptIds,
- queueIds,
- configIdsAndNames,
- );
+ const { traces, observations, scores, sessions, comments, queueItems } =
+ createObjects(
+ traceVolume,
+ envTags,
+ colorTags,
+ project1,
+ project2,
+ promptIds,
+ queueIds,
+ configIdsAndNames,
+ );
logger.info(
`Seeding ${traces.length} traces, ${observations.length} observations, and ${scores.length} scores`,
);
- await uploadObjects(
- traces,
- observations,
- scores,
- sessions,
- events,
- comments,
- queueItems,
- );
+ await uploadObjects(sessions, comments, queueItems);
// If openai key is in environment, add it to the projects LLM API keys
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
@@ -420,7 +403,7 @@ export async function createDatasets(
updatedAt: Date;
name: string;
},
- observations: Prisma.ObservationCreateManyInput[],
+ observations: { id?: string; projectId?: string; traceId?: string | null }[],
) {
for (let datasetNumber = 0; datasetNumber < 2; datasetNumber++) {
for (const projectId of [project1.id, project2.id]) {
@@ -532,11 +515,7 @@ export async function createDatasets(
}
async function uploadObjects(
- traces: Prisma.TraceCreateManyInput[],
- observations: Prisma.ObservationCreateManyInput[],
- scores: Prisma.ScoreCreateManyInput[],
sessions: Prisma.TraceSessionCreateManyInput[],
- events: Prisma.ObservationCreateManyInput[],
comments: Prisma.CommentCreateManyInput[],
queueItems: Prisma.AnnotationQueueItemCreateManyInput[],
) {
@@ -564,73 +543,6 @@ async function uploadObjects(
await promises[i];
}
- promises = [];
-
- chunk(traces, chunkSize).forEach((chunk) => {
- promises.push(
- prisma.trace.createMany({
- data: chunk,
- }),
- );
- });
- for (let i = 0; i < promises.length; i++) {
- if (i + 1 >= promises.length || i % Math.ceil(promises.length / 10) === 0)
- logger.info(
- `Seeding of Traces ${((i + 1) / promises.length) * 100}% complete`,
- );
- await promises[i];
- }
-
- promises = [];
- chunk(observations, chunkSize).forEach((chunk) => {
- promises.push(
- prisma.observation.createMany({
- data: chunk,
- }),
- );
- });
-
- for (let i = 0; i < promises.length; i++) {
- if (i + 1 >= promises.length || i % Math.ceil(promises.length / 10) === 0)
- logger.info(
- `Seeding of Observations ${((i + 1) / promises.length) * 100}% complete`,
- );
- await promises[i];
- }
-
- promises = [];
- chunk(events, chunkSize).forEach((chunk) => {
- promises.push(
- prisma.observation.createMany({
- data: chunk,
- }),
- );
- });
-
- for (let i = 0; i < promises.length; i++) {
- if (i + 1 >= promises.length || i % Math.ceil(promises.length / 10) === 0)
- logger.info(
- `Seeding of Events ${((i + 1) / promises.length) * 100}% complete`,
- );
- await promises[i];
- }
-
- promises = [];
- chunk(scores, chunkSize).forEach((chunk) => {
- promises.push(
- prisma.score.createMany({
- data: chunk,
- }),
- );
- });
- for (let i = 0; i < promises.length; i++) {
- if (i + 1 >= promises.length || i % Math.ceil(promises.length / 10) === 0)
- logger.info(
- `Seeding of Scores ${((i + 1) / promises.length) * 100}% complete`,
- );
- await promises[i];
- }
-
promises = [];
chunk(comments, chunkSize).forEach((chunk) => {
promises.push(
@@ -682,11 +594,11 @@ function createObjects(
}[]
>,
) {
- const traces: Prisma.TraceCreateManyInput[] = [];
- const observations: Prisma.ObservationCreateManyInput[] = [];
- const scores: Prisma.ScoreCreateManyInput[] = [];
+ const traces: any[] = [];
+ const observations: any[] = [];
+ const scores: any[] = [];
const sessions: Prisma.TraceSessionCreateManyInput[] = [];
- const events: Prisma.ObservationCreateManyInput[] = [];
+ const events: any[] = [];
const configs: Prisma.ScoreConfigCreateManyInput[] = [];
const comments: Prisma.CommentCreateManyInput[] = [];
const queueItems: Prisma.AnnotationQueueItemCreateManyInput[] = [];
@@ -795,7 +707,7 @@ function createObjects(
name: annotationScoreName,
timestamp: traceTs,
createdAt: traceTs,
- source: ScoreSource.ANNOTATION,
+ source: "ANNOTATION",
projectId,
authorUserId: `user-${i}`,
dataType,
@@ -812,7 +724,7 @@ function createObjects(
value: Math.floor(Math.random() * 10) - 5,
timestamp: traceTs,
createdAt: traceTs,
- source: ScoreSource.API,
+ source: "API",
projectId,
dataType: ScoreDataType.NUMERIC,
},
@@ -825,7 +737,7 @@ function createObjects(
name: "Completeness",
timestamp: traceTs,
createdAt: traceTs,
- source: ScoreSource.API,
+ source: "API",
projectId,
dataType: ScoreDataType.CATEGORICAL,
stringValue:
@@ -859,7 +771,7 @@ function createObjects(
);
const span = {
- type: ObservationType.SPAN,
+ type: "SPAN",
id: `span-${v4()}`,
startTime: spanTsStart,
createdAt: spanTsStart,
@@ -933,7 +845,7 @@ function createObjects(
const { input, output } = getGenerationInputOutput();
const generation = {
- type: ObservationType.GENERATION,
+ type: "GENERATION",
id: `generation-${v4()}`,
startTime: generationTsStart,
createdAt: generationTsStart,
@@ -978,7 +890,7 @@ function createObjects(
value: Math.random() * 2 - 1,
observationId: generation.id,
traceId: trace.id,
- source: ScoreSource.API,
+ source: "API",
projectId: trace.projectId,
timestamp: generationTsEnd,
createdAt: traceTs,
@@ -989,7 +901,7 @@ function createObjects(
value: Math.random() * 2 - 1,
observationId: generation.id,
traceId: trace.id,
- source: ScoreSource.API,
+ source: "API",
projectId: trace.projectId,
timestamp: generationTsEnd,
createdAt: traceTs,
@@ -1013,7 +925,7 @@ function createObjects(
);
events.push({
- type: ObservationType.EVENT,
+ type: "EVENT",
id: `event-${v4()}`,
startTime: eventTs,
createdAt: eventTs,
diff --git a/packages/shared/src/features/scores/scoreTypes.ts b/packages/shared/src/features/scores/scoreTypes.ts
index b618aa7ff9..81a9e50d08 100644
--- a/packages/shared/src/features/scores/scoreTypes.ts
+++ b/packages/shared/src/features/scores/scoreTypes.ts
@@ -1,8 +1,7 @@
import { z } from "zod";
-import { Score } from "@prisma/client";
-
import { isPresent, stringDateTime } from "../../utils/typeChecks";
+import { Score } from "../../server";
import {
NonEmptyString,
paginationMetaResponseZod,
diff --git a/packages/shared/src/features/scores/types.ts b/packages/shared/src/features/scores/types.ts
index ae969ac710..8f656b4b63 100644
--- a/packages/shared/src/features/scores/types.ts
+++ b/packages/shared/src/features/scores/types.ts
@@ -1,4 +1,5 @@
-import { ScoreDataType, ScoreSource } from "@prisma/client";
+import { ScoreDataType } from "@prisma/client";
+import { ScoreSourceType } from "../../server";
export type CategoricalAggregate = {
type: "CATEGORICAL";
@@ -22,7 +23,7 @@ export type ScoreAggregate = Record<
export type ScoreSimplified = {
name: string;
dataType: ScoreDataType;
- source: ScoreSource;
+ source: ScoreSourceType;
value?: number | null;
comment?: string | null;
stringValue?: string | null;
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index f3b71d72b8..e837e5155e 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -41,6 +41,7 @@ export * from "./features/experiments/utils";
// export db types only
export * from "@prisma/client";
export { type DB } from "../prisma/generated/types";
+export * from "./server/repositories/types";
// errors
export * from "./errors/index";
diff --git a/packages/shared/src/observationsTable.ts b/packages/shared/src/observationsTable.ts
index 0f78ad9c92..f73a21d62c 100644
--- a/packages/shared/src/observationsTable.ts
+++ b/packages/shared/src/observationsTable.ts
@@ -1,8 +1,8 @@
-import { ObservationLevel } from "@prisma/client";
import {
type OptionsDefinition,
type ColumnDefinition,
-} from "./tableDefinitions/types";
+} from "./tableDefinitions";
+import { ObservationLevelType } from "./server";
// to be used server side
export const observationsTableCols: ColumnDefinition[] = [
@@ -102,7 +102,12 @@ export const observationsTableCols: ColumnDefinition[] = [
id: "level",
type: "stringOptions",
internal: 'o."level"::text',
- options: Object.values(ObservationLevel).map((value) => ({ value })),
+ options: [
+ { value: "DEBUG" },
+ { value: "DEFAULT" },
+ { value: "WARNING" },
+ { value: "ERROR" },
+ ] as { value: ObservationLevelType }[],
},
{
name: "Status Message",
diff --git a/packages/shared/src/server/ingestion/modelMatch.ts b/packages/shared/src/server/ingestion/modelMatch.ts
index bd0222efce..62226aa4cd 100644
--- a/packages/shared/src/server/ingestion/modelMatch.ts
+++ b/packages/shared/src/server/ingestion/modelMatch.ts
@@ -1,5 +1,6 @@
-import { Model, Observation, Prisma } from "@prisma/client";
+import { Model, Prisma } from "@prisma/client";
import { prisma } from "../../db";
+import { Observation } from "../repositories";
export async function findModel(p: {
event: {
diff --git a/packages/shared/src/server/ingestion/types.ts b/packages/shared/src/server/ingestion/types.ts
index 20185175fa..c0f86972fc 100644
--- a/packages/shared/src/server/ingestion/types.ts
+++ b/packages/shared/src/server/ingestion/types.ts
@@ -3,7 +3,9 @@ import { z } from "zod";
import { NonEmptyString, jsonSchema } from "../../utils/zod";
import { ModelUsageUnit } from "../../constants";
-import { ObservationLevel, ScoreSource } from "@prisma/client";
+import { type ScoreSourceType } from "../repositories";
+
+const ObservationLevel = z.enum(["DEBUG", "DEFAULT", "WARNING", "ERROR"]);
export const Usage = z.object({
input: z.number().int().nullish(),
@@ -142,7 +144,7 @@ export const OptionalObservationBody = z.object({
metadata: jsonSchema.nullish(),
input: z.any().nullish(),
output: z.any().nullish(),
- level: z.nativeEnum(ObservationLevel).nullish(),
+ level: ObservationLevel.nullish(),
statusMessage: z.string().nullish(),
parentObservationId: z.string().nullish(),
version: z.string().nullish(),
@@ -230,7 +232,9 @@ const BaseScoreBody = z.object({
traceId: z.string(),
observationId: z.string().nullish(),
comment: z.string().nullish(),
- source: z.nativeEnum(ScoreSource).default(ScoreSource.API),
+ source: z
+ .enum(["API", "EVAL", "ANNOTATION"])
+ .default("API" as ScoreSourceType),
});
/**
@@ -281,7 +285,7 @@ export const LegacySpanPostSchema = z.object({
input: jsonSchema.nullish(),
output: jsonSchema.nullish(),
parentObservationId: z.string().nullish(),
- level: z.nativeEnum(ObservationLevel).nullish(),
+ level: ObservationLevel.nullish(),
statusMessage: z.string().nullish(),
version: z.string().nullish(),
});
@@ -295,7 +299,7 @@ export const LegacySpanPatchSchema = z.object({
metadata: jsonSchema.nullish(),
input: jsonSchema.nullish(),
output: jsonSchema.nullish(),
- level: z.nativeEnum(ObservationLevel).nullish(),
+ level: ObservationLevel.nullish(),
statusMessage: z.string().nullish(),
version: z.string().nullish(),
});
@@ -319,7 +323,7 @@ export const LegacyGenerationsCreateSchema = z.object({
usage: usage,
metadata: jsonSchema.nullish(),
parentObservationId: z.string().nullish(),
- level: z.nativeEnum(ObservationLevel).nullish(),
+ level: ObservationLevel.nullish(),
statusMessage: z.string().nullish(),
version: z.string().nullish(),
});
@@ -342,7 +346,7 @@ export const LegacyGenerationPatchSchema = z.object({
completion: jsonSchema.nullish(),
usage: usage,
metadata: jsonSchema.nullish(),
- level: z.nativeEnum(ObservationLevel).nullish(),
+ level: ObservationLevel.nullish(),
statusMessage: z.string().nullish(),
version: z.string().nullish(),
});
@@ -369,7 +373,7 @@ export const LegacyObservationBody = z.object({
costDetails: UsageOrCostDetails,
metadata: jsonSchema.nullish(),
parentObservationId: z.string().nullish(),
- level: z.nativeEnum(ObservationLevel).nullish(),
+ level: ObservationLevel.nullish(),
statusMessage: z.string().nullish(),
version: z.string().nullish(),
});
diff --git a/packages/shared/src/server/ingestion/validateAndInflateScore.ts b/packages/shared/src/server/ingestion/validateAndInflateScore.ts
index 71e0c87a13..064e5abd7c 100644
--- a/packages/shared/src/server/ingestion/validateAndInflateScore.ts
+++ b/packages/shared/src/server/ingestion/validateAndInflateScore.ts
@@ -4,7 +4,8 @@ import {
validateDbScoreConfigSafe,
ValidatedScoreConfig,
} from "../../../src";
-import { prisma, Score, ScoreDataType } from "../../db";
+import { prisma, ScoreDataType } from "../../db";
+import { Score } from "../repositories";
import { InvalidRequestError, LangfuseNotFoundError } from "../../errors";
diff --git a/packages/shared/src/server/queries/createGenerationsQuery.ts b/packages/shared/src/server/queries/createGenerationsQuery.ts
index 3f929c0b8c..9d67de3a7c 100644
--- a/packages/shared/src/server/queries/createGenerationsQuery.ts
+++ b/packages/shared/src/server/queries/createGenerationsQuery.ts
@@ -1,4 +1,4 @@
-import { ObservationView } from "@prisma/client";
+import { ObservationView } from "../repositories";
type AdditionalObservationFields = {
traceName: string | null;
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index a1cd3dc480..4eed945a2a 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -5,7 +5,6 @@ import {
queryClickhouseStream,
upsertClickhouse,
} from "./clickhouse";
-import { ObservationLevel } from "@prisma/client";
import { logger } from "../logger";
import { InternalServerError, LangfuseNotFoundError } from "../../errors";
import { prisma } from "../../db";
diff --git a/packages/shared/src/server/repositories/observations_converters.ts b/packages/shared/src/server/repositories/observations_converters.ts
index c4ca7d960f..9577c0df3c 100644
--- a/packages/shared/src/server/repositories/observations_converters.ts
+++ b/packages/shared/src/server/repositories/observations_converters.ts
@@ -1,14 +1,14 @@
-import {
- Observation,
- ObservationView,
- ObservationType,
- ObservationLevel,
- Prisma,
-} from "@prisma/client";
+import { Prisma } from "@prisma/client";
import Decimal from "decimal.js";
import { parseClickhouseUTCDateTimeFormat } from "./clickhouse";
import { ObservationRecordReadType } from "./definitions";
import { parseJsonPrioritised } from "../../utils/json";
+import {
+ Observation,
+ ObservationView,
+ ObservationType,
+ ObservationLevelType,
+} from "./types";
export const convertObservationToView = (
record: ObservationRecordReadType,
@@ -69,7 +69,7 @@ export const convertObservation = (
val && parseJsonPrioritised(val),
]),
),
- level: record.level as ObservationLevel,
+ level: record.level as ObservationLevelType,
statusMessage: record.status_message ?? null,
version: record.version ?? null,
input: (record.input
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index ce2ef4da6b..05012cbca9 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -1,4 +1,5 @@
-import { Score, ScoreDataType, ScoreSource } from "@prisma/client";
+import { ScoreDataType } from "@prisma/client";
+import { Score, ScoreSourceType } from "./types";
import {
commandClickhouse,
parseClickhouseUTCDateTimeFormat,
@@ -6,7 +7,7 @@ import {
queryClickhouseStream,
upsertClickhouse,
} from "./clickhouse";
-import { FilterList } from "../queries/clickhouse-sql/clickhouse-filter";
+import { FilterList, orderByToClickhouseSql } from "../queries";
import { FilterCondition, FilterState, TimeFilter } from "../../types";
import {
createFilterFromFilterState,
@@ -17,7 +18,6 @@ import {
dashboardColumnDefinitions,
scoresTableUiColumnDefinitions,
} from "../../tableDefinitions";
-import { orderByToClickhouseSql } from "../queries/clickhouse-sql/orderby-factory";
import {
convertScoreAggregation,
convertToScore,
@@ -77,7 +77,7 @@ export const searchExistingAnnotationScore = async (
export const getScoreById = async (
projectId: string,
scoreId: string,
- source?: ScoreSource,
+ source?: ScoreSourceType,
) => {
const query = `
SELECT *
@@ -110,7 +110,7 @@ export const getScoreById = async (
export const getScoresByIds = async (
projectId: string,
scoreId: string[],
- source?: ScoreSource,
+ source?: ScoreSourceType,
) => {
const query = `
SELECT *
@@ -281,7 +281,7 @@ export const getScoresGroupedByNameSourceType = async (
return rows.map((row) => ({
name: row.name,
- source: row.source as ScoreSource,
+ source: row.source as ScoreSourceType,
dataType: row.data_type as ScoreDataType,
}));
};
@@ -437,7 +437,7 @@ export const getScoresUiTable = async (props: {
stringValue: row.string_value,
comment: row.comment,
dataType: row.data_type as ScoreDataType,
- source: row.source as ScoreSource,
+ source: row.source as ScoreSourceType,
name: row.name,
value: row.value,
timestamp: parseClickhouseUTCDateTimeFormat(row.timestamp),
diff --git a/packages/shared/src/server/repositories/scores_converters.ts b/packages/shared/src/server/repositories/scores_converters.ts
index 06b8d64ba7..b52a586735 100644
--- a/packages/shared/src/server/repositories/scores_converters.ts
+++ b/packages/shared/src/server/repositories/scores_converters.ts
@@ -1,5 +1,6 @@
-import { ScoreSource, ScoreDataType, Score } from "@prisma/client";
+import { ScoreDataType } from "@prisma/client";
import { ScoreRecordReadType } from "./definitions";
+import { Score, ScoreSourceType } from "./types";
export type ScoreAggregation = {
id: string;
@@ -20,7 +21,7 @@ export const convertToScore = (row: ScoreRecordReadType): Score => {
observationId: row.observation_id ?? null,
name: row.name,
value: row.value ?? null,
- source: row.source as ScoreSource,
+ source: row.source as ScoreSourceType,
comment: row.comment ?? null,
authorUserId: row.author_user_id ?? null,
configId: row.config_id ?? null,
@@ -38,7 +39,7 @@ export const convertScoreAggregation = (row: ScoreAggregation) => {
name: row.name,
stringValue: row.string_value,
value: Number(row.value),
- source: row.source as ScoreSource,
+ source: row.source as ScoreSourceType,
dataType: row.data_type as ScoreDataType,
comment: row.comment,
};
diff --git a/packages/shared/src/server/repositories/traces_converters.ts b/packages/shared/src/server/repositories/traces_converters.ts
index 5f4c04b0e3..2185906aaf 100644
--- a/packages/shared/src/server/repositories/traces_converters.ts
+++ b/packages/shared/src/server/repositories/traces_converters.ts
@@ -1,8 +1,9 @@
-import { Prisma, Trace } from "@prisma/client";
+import { Prisma } from "@prisma/client";
import { parseClickhouseUTCDateTimeFormat } from "./clickhouse";
import { TraceRecordReadType } from "./definitions";
import { convertDateToClickhouseDateTime } from "../clickhouse/client";
import { parseJsonPrioritised } from "../../utils/json";
+import { Trace } from "./types";
export const convertTraceDomainToClickhouse = (
trace: Trace,
diff --git a/packages/shared/src/server/repositories/types.ts b/packages/shared/src/server/repositories/types.ts
index 9c62aeeebb..548836f6d6 100644
--- a/packages/shared/src/server/repositories/types.ts
+++ b/packages/shared/src/server/repositories/types.ts
@@ -1,3 +1,140 @@
+import { Prisma, ScoreDataType } from "@prisma/client";
+import Decimal from "decimal.js";
+
export type TableCount = {
count: number;
};
+
+export const ObservationType = {
+ SPAN: "SPAN",
+ EVENT: "EVENT",
+ GENERATION: "GENERATION",
+} as const;
+export type ObservationType =
+ (typeof ObservationType)[keyof typeof ObservationType];
+export const ObservationLevel = {
+ DEBUG: "DEBUG",
+ DEFAULT: "DEFAULT",
+ WARNING: "WARNING",
+ ERROR: "ERROR",
+} as const;
+export type ObservationLevelType =
+ (typeof ObservationLevel)[keyof typeof ObservationLevel];
+export const ScoreSource = {
+ ANNOTATION: "ANNOTATION",
+ API: "API",
+ EVAL: "EVAL",
+} as const;
+export type ScoreSourceType = (typeof ScoreSource)[keyof typeof ScoreSource];
+
+export type Observation = {
+ id: string;
+ traceId: string | null;
+ projectId: string;
+ type: ObservationType;
+ startTime: Date;
+ endTime: Date | null;
+ name: string | null;
+ metadata: Prisma.JsonValue | null;
+ parentObservationId: string | null;
+ level: ObservationLevelType;
+ statusMessage: string | null;
+ version: string | null;
+ createdAt: Date;
+ updatedAt: Date;
+ model: string | null;
+ internalModel: string | null;
+ internalModelId: string | null;
+ modelParameters: unknown | null;
+ input: unknown | null;
+ output: unknown | null;
+ promptTokens: number;
+ completionTokens: number;
+ totalTokens: number;
+ unit: string | null;
+ inputCost: Decimal | null;
+ outputCost: Decimal | null;
+ totalCost: Decimal | null;
+ calculatedInputCost: Decimal | null;
+ calculatedOutputCost: Decimal | null;
+ calculatedTotalCost: Decimal | null;
+ completionStartTime: Date | null;
+ promptId: string | null;
+};
+
+export type ObservationView = {
+ id: string;
+ traceId: string | null;
+ projectId: string;
+ type: ObservationType;
+ startTime: Date;
+ endTime: Date | null;
+ name: string | null;
+ metadata: Prisma.JsonValue | null;
+ parentObservationId: string | null;
+ level: ObservationLevelType;
+ statusMessage: string | null;
+ version: string | null;
+ createdAt: Date;
+ updatedAt: Date;
+ model: string | null;
+ modelParameters: unknown | null;
+ input: unknown | null;
+ output: unknown | null;
+ promptTokens: number;
+ completionTokens: number;
+ totalTokens: number;
+ unit: string | null;
+ completionStartTime: Date | null;
+ promptId: string | null;
+ promptName: string | null;
+ promptVersion: number | null;
+ modelId: string | null;
+ inputPrice: Decimal | null;
+ outputPrice: Decimal | null;
+ totalPrice: Decimal | null;
+ calculatedInputCost: Decimal | null;
+ calculatedOutputCost: Decimal | null;
+ calculatedTotalCost: Decimal | null;
+ latency: number | null;
+ timeToFirstToken: number | null;
+};
+
+export type Score = {
+ id: string;
+ timestamp: Date;
+ projectId: string;
+ name: string;
+ value: number | null;
+ source: ScoreSourceType;
+ authorUserId: string | null;
+ comment: string | null;
+ traceId: string;
+ observationId: string | null;
+ configId: string | null;
+ stringValue: string | null;
+ queueId: string | null;
+ createdAt: Date;
+ updatedAt: Date;
+ dataType: ScoreDataType;
+};
+
+export type Trace = {
+ id: string;
+ timestamp: Date;
+ name: string | null;
+ userId: string | null;
+ metadata: Prisma.JsonValue | null;
+ release: string | null;
+ version: string | null;
+ projectId: string;
+ public: boolean;
+ bookmarked: boolean;
+ tags: string[];
+ input: unknown | null;
+ output: unknown | null;
+ sessionId: string | null;
+ createdAt: Date;
+ updatedAt: Date;
+ externalId: string | null;
+};
diff --git a/packages/shared/src/server/services/traces-ui-table-service.ts b/packages/shared/src/server/services/traces-ui-table-service.ts
index f56e1d9591..9e6c406964 100644
--- a/packages/shared/src/server/services/traces-ui-table-service.ts
+++ b/packages/shared/src/server/services/traces-ui-table-service.ts
@@ -1,4 +1,3 @@
-import { ObservationLevel } from "@prisma/client";
import { OrderByState } from "../../interfaces/orderBy";
import { tracesTableUiColumnDefinitions } from "../../tableDefinitions";
import { FilterState } from "../../types";
@@ -13,18 +12,17 @@ import {
} from "../queries/clickhouse-sql/factory";
import { orderByToClickhouseSql } from "../queries/clickhouse-sql/orderby-factory";
import { clickhouseSearchCondition } from "../queries/clickhouse-sql/search";
-import {
- parseClickhouseUTCDateTimeFormat,
- queryClickhouse,
-} from "../repositories/clickhouse";
import { TraceRecordReadType } from "../repositories/definitions";
+import Decimal from "decimal.js";
+import { ScoreAggregate } from "../../features/scores";
import {
OBSERVATIONS_TO_TRACE_INTERVAL,
SCORE_TO_TRACE_OBSERVATIONS_INTERVAL,
-} from "../repositories/constants";
-import Decimal from "decimal.js";
-import { ScoreAggregate } from "../../features/scores";
-import { reduceUsageOrCostDetails } from "../repositories";
+ ObservationLevelType,
+ reduceUsageOrCostDetails,
+ parseClickhouseUTCDateTimeFormat,
+ queryClickhouse,
+} from "../repositories";
export type TracesTableReturnType = Pick<
TraceRecordReadType,
@@ -62,7 +60,7 @@ export type TracesMetricsUiReturnType = {
completionTokens: bigint;
totalTokens: bigint;
latency: number | null;
- level: ObservationLevel;
+ level: ObservationLevelType;
observationCount: bigint;
calculatedTotalCost: Decimal | null;
calculatedInputCost: Decimal | null;
@@ -140,7 +138,7 @@ export type TracesTableMetricsClickhouseReturnType = {
id: string;
project_id: string;
timestamp: Date;
- level: ObservationLevel;
+ level: ObservationLevelType;
observation_count: number | null;
latency: string | null;
usage_details: Record<string, number>;
diff --git a/packages/shared/src/tableDefinitions/tracesTable.ts b/packages/shared/src/tableDefinitions/tracesTable.ts
index 457adeb331..760a362057 100644
--- a/packages/shared/src/tableDefinitions/tracesTable.ts
+++ b/packages/shared/src/tableDefinitions/tracesTable.ts
@@ -1,4 +1,4 @@
-import { ObservationLevel } from "@prisma/client";
+import { ObservationLevelType } from "../server";
import { ColumnDefinition, OptionsDefinition } from "..";
export const tracesOnlyCols: ColumnDefinition[] = [
@@ -62,7 +62,12 @@ export const tracesOnlyCols: ColumnDefinition[] = [
id: "level",
type: "stringOptions",
internal: '"level"',
- options: Object.values(ObservationLevel).map((value) => ({ value })),
+ options: [
+ { value: "DEBUG" },
+ { value: "DEFAULT" },
+ { value: "WARNING" },
+ { value: "ERROR" },
+ ] as { value: ObservationLevelType }[],
},
{
name: "Tags",
diff --git a/web/src/__tests__/api-auth.servertest.ts b/web/src/__tests__/api-auth.servertest.ts
index 1a32c33666..5e8c6ea758 100644
--- a/web/src/__tests__/api-auth.servertest.ts
+++ b/web/src/__tests__/api-auth.servertest.ts
@@ -10,15 +10,9 @@ import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
describe("Authenticate API calls", () => {
beforeEach(async () => {
- await prisma.score.deleteMany();
- await prisma.observation.deleteMany();
- await prisma.trace.deleteMany();
await prisma.apiKey.deleteMany();
});
afterEach(async () => {
- await prisma.score.deleteMany();
- await prisma.observation.deleteMany();
- await prisma.trace.deleteMany();
await prisma.apiKey.deleteMany();
});
diff --git a/web/src/__tests__/cost.servertest.ts b/web/src/__tests__/cost.servertest.ts
deleted file mode 100644
index 3808e1afec..0000000000
--- a/web/src/__tests__/cost.servertest.ts
+++ /dev/null
@@ -1,664 +0,0 @@
-/** @jest-environment node */
-
-import { pruneDatabase } from "@/src/__tests__/test-utils";
-import { ModelUsageUnit } from "@langfuse/shared";
-import { prisma } from "@langfuse/shared/src/db";
-
-describe("cost retrieval tests", () => {
- beforeEach(async () => await pruneDatabase());
-
- [
- {
- testDescription: "prompt and completion tokens",
- promptTokens: 200,
- completionTokens: 3000,
- totalTokens: undefined,
- inputPrice: "0.0000010",
- outputPrice: "0.0000020",
- totalPrice: undefined,
- expectedPromptTokens: 200,
- expectedCompletionTokens: 3000,
- expectedTotalTokens: 0,
- expectedInputCost: "0.0002", // 200 / 1000 * 0.0010
- expectedOutputCost: "0.006", // 3000 / 1000 * 0.0020
- expectedTotalCost: "0.0062", // 0.0002 + 0.006
- },
- {
- testDescription: "missing completion tokens",
- promptTokens: 200,
- completionTokens: undefined,
- totalTokens: undefined,
- inputPrice: "0.0000010",
- outputPrice: "0.0000020",
- totalPrice: undefined,
- expectedPromptTokens: 200,
- expectedCompletionTokens: 0,
- expectedTotalTokens: 0,
- expectedInputCost: "0.0002",
- expectedOutputCost: "0", // completionTokens are set to 0 when ingesting undefined, hence 0 cost
- expectedTotalCost: "0.0002",
- },
- {
- testDescription: "missing prompt tokens",
- promptTokens: undefined,
- completionTokens: 3000,
- totalTokens: undefined,
- inputPrice: "0.0000010",
- outputPrice: "0.0000020",
- totalPrice: undefined,
- expectedPromptTokens: 0,
- expectedCompletionTokens: 3000,
- expectedTotalTokens: 0,
- expectedInputCost: "0", // promptTokens are set to 0 when ingesting undefined, hence 0 cost
- expectedOutputCost: "0.006",
- expectedTotalCost: "0.006",
- },
- {
- testDescription: "prompt and completion and total",
- promptTokens: 200,
- completionTokens: 3000,
- totalTokens: 3200,
- inputPrice: "0.0000010",
- outputPrice: "0.0000020",
- totalPrice: undefined,
- expectedPromptTokens: 200,
- expectedCompletionTokens: 3000,
- expectedTotalTokens: 3200,
- expectedInputCost: "0.0002", // 200 / 1000 * 0.0010
- expectedOutputCost: "0.006", // 3000 / 1000 * 0.0020
- expectedTotalCost: "0.0062", // 0.0002 + 0.006
- },
- {
- testDescription: "total only without price",
- promptTokens: undefined,
- completionTokens: undefined,
- totalTokens: 3200,
- inputPrice: "0.0000010",
- outputPrice: "0.0000020",
- totalPrice: undefined,
- expectedPromptTokens: 0,
- expectedCompletionTokens: 0,
- expectedTotalTokens: 3200,
- expectedInputCost: "0",
- expectedOutputCost: "0",
- expectedTotalCost: "0",
- },
- {
- testDescription: "total only",
- promptTokens: undefined,
- completionTokens: undefined,
- totalTokens: 3200,
- inputPrice: "0.0000010",
- outputPrice: "0.0000020",
- totalPrice: "0.1",
- expectedPromptTokens: 0,
- expectedCompletionTokens: 0,
- expectedTotalTokens: 3200,
- expectedInputCost: "0",
- expectedOutputCost: "0",
- expectedTotalCost: "320",
- },
- ].forEach((input) => {
- it(`should calculate cost correctly ${input.testDescription}`, async () => {
- await pruneDatabase();
-
- await prisma.model.create({
- data: {
- modelName: "gpt-3.5-turbo",
- inputPrice: input.inputPrice,
- outputPrice: input.outputPrice,
- totalPrice: input.totalPrice,
- matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
- projectId: null,
- startDate: new Date("2023-12-01"),
- tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
- unit: ModelUsageUnit.Tokens,
- },
- });
-
- const dbTrace = await prisma.trace.create({
- data: {
- name: "trace-name",
- project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },
- },
- });
-
- await prisma.observation.create({
- data: {
- traceId: dbTrace.id,
- type: "GENERATION",
- project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },
- model: "gpt-3.5-turbo",
- internalModel: "gpt-3.5-turbo",
- startTime: new Date("2024-01-01T00:00:00.000Z"),
- unit: ModelUsageUnit.Tokens,
- promptTokens: input.promptTokens,
- completionTokens: input.completionTokens,
- totalTokens: input.totalTokens,
- },
- });
-
- const view = await prisma.observationView.findFirst({
- where: { traceId: dbTrace.id },
- });
-
- expect(view?.promptTokens).toBe(input.expectedPromptTokens);
- expect(view?.completionTokens).toBe(input.expectedCompletionTokens);
- expect(view?.totalTokens).toBe(input.expectedTotalTokens);
-
- // calculated cost fields
- expect(view?.calculatedInputCost?.toString()).toBe(
- input.expectedInputCost,
- );
- expect(view?.calculatedOutputCost?.toString()).toBe(
- input.expectedOutputCost,
- );
- expect(view?.calculatedTotalCost?.toString()).toBe(
- input.expectedTotalCost,
- );
- });
- });
-
- [
- {
- testDescription: "overwriting project specific model",
- expectedInputCost: "0.0004", // 200 / 1000 * 0.0010
- expectedOutputCost: "0.012", // 3000 / 1000 * 0.0020
- expectedTotalCost: "0.0124", // 0.0002 + 0.006
- expectedModelId: "model-2",
- },
- ].forEach((input) => {
- it(`should calculate cost correctly with multiple models ${input.testDescription}`, async () => {
- await pruneDatabase();
-
- await prisma.model.create({
- data: {
- id: "model-1",
- modelName: "gpt-3.5-turbo",
- inputPrice: "0.0000010",
- outputPrice: "0.0000020",
- totalPrice: "0.1",
- matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
- projectId: null,
- startDate: new Date("2023-12-01"),
- tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
- unit: ModelUsageUnit.Tokens,
- },
- });
- await prisma.model.create({
- data: {
- id: "model-2",
- modelName: "gpt-3.5-turbo",
- inputPrice: "0.0000020",
- outputPrice: "0.0000040",
- totalPrice: undefined,
- matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
- startDate: new Date("2023-12-01"),
- tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
- unit: ModelUsageUnit.Tokens,
- project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },
- },
- });
-
- const dbTrace = await prisma.trace.create({
- data: {
- name: "trace-name",
- project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },
- },
- });
-
- await prisma.observation.create({
- data: {
- traceId: dbTrace.id,
- type: "GENERATION",
- project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },
- model: "gpt-3.5-turbo",
- internalModel: "gpt-3.5-turbo",
- startTime: new Date("2024-01-01T00:00:00.000Z"),
- unit: ModelUsageUnit.Tokens,
- promptTokens: 200,
- completionTokens: 3000,
- totalTokens: undefined,
- },
- });
-
- const view = await prisma.observationView.findFirst({
- where: { traceId: dbTrace.id },
- });
-
- // calculated cost fields
- expect(view?.modelId).toBe(input.expectedModelId);
- expect(view?.calculatedInputCost?.toString()).toBe(
- input.expectedInputCost,
- );
- expect(view?.calculatedOutputCost?.toString()).toBe(
- input.expectedOutputCost,
- );
- expect(view?.calculatedTotalCost?.toString()).toBe(
- input.expectedTotalCost,
- );
- });
- });
-
- it(`should prioritize latest models`, async () => {
- await pruneDatabase();
- await prisma.model.create({
- data: {
- id: "model-0",
- modelName: "gpt-3.5-turbo",
- inputPrice: "0.0000000",
- outputPrice: "0.0000000",
- totalPrice: "0.1",
- matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
- projectId: null,
- startDate: null,
- tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
- unit: ModelUsageUnit.Tokens,
- },
- });
-
- await prisma.model.create({
- data: {
- id: "model-1",
- modelName: "gpt-3.5-turbo",
- inputPrice: "0.0000010",
- outputPrice: "0.0000020",
- totalPrice: "0.1",
- matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
- projectId: null,
- startDate: new Date("2023-12-01"),
- tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
- unit: ModelUsageUnit.Tokens,
- },
- });
- await prisma.model.create({
- data: {
- id: "model-2",
- modelName: "gpt-3.5-turbo",
- inputPrice: "0.0000020",
- outputPrice: "0.0000040",
- totalPrice: undefined,
- matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
- startDate: new Date("2023-12-02"),
- tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
- unit: ModelUsageUnit.Tokens,
- },
- });
-
- const dbTrace = await prisma.trace.create({
- data: {
- name: "trace-name",
- project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },
- },
- });
-
- await prisma.observation.create({
- data: {
- traceId: dbTrace.id,
- type: "GENERATION",
- project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },
- model: "gpt-3.5-turbo",
- internalModel: "gpt-3.5-turbo",
- startTime: new Date("2024-01-01T00:00:00.000Z"),
- unit: ModelUsageUnit.Tokens,
- promptTokens: 200,
- completionTokens: 3000,
- totalTokens: undefined,
- },
- });
-
- const view = await prisma.observationView.findFirst({
- where: { traceId: dbTrace.id },
- });
-
- console.log(view);
-
- // calculated cost fields
- expect(view?.modelId).toBe("model-2");
- expect(view?.calculatedInputCost?.toString()).toBe("0.0004");
- expect(view?.calculatedOutputCost?.toString()).toBe("0.012");
- expect(view?.calculatedTotalCost?.toString()).toBe("0.0124");
- });
-
- it(`should take old model for old observations`, async () => {
- await prisma.model.create({
- data: {
- id: "model-0",
- modelName: "gpt-3.5-turbo",
- inputPrice: "0.0000000",
- outputPrice: "0.0000000",
- totalPrice: "0.1",
- matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
- projectId: null,
- startDate: null,
- tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
- unit: ModelUsageUnit.Tokens,
- },
- });
-
- await prisma.model.create({
- data: {
- id: "model-1",
- modelName: "gpt-3.5-turbo",
- inputPrice: "0.0000010",
- outputPrice: "0.0000020",
- totalPrice: "0.1",
- matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
- projectId: null,
- startDate: new Date("2023-12-01"),
- tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
- unit: ModelUsageUnit.Tokens,
- },
- });
- await prisma.model.create({
- data: {
- id: "model-2",
- modelName: "gpt-3.5-turbo",
- inputPrice: "0.0000020",
- outputPrice: "0.0000040",
- totalPrice: undefined,
- matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
- startDate: new Date("2023-12-02"),
- tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
- unit: ModelUsageUnit.Tokens,
- },
- });
-
- const dbTrace = await prisma.trace.create({
- data: {
- name: "trace-name",
- project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },
- },
- });
-
- await prisma.observation.create({
- data: {
- traceId: dbTrace.id,
- type: "GENERATION",
- project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },
- model: "gpt-3.5-turbo",
- internalModel: "gpt-3.5-turbo",
- startTime: new Date("2023-01-01T00:00:00.000Z"),
- unit: ModelUsageUnit.Tokens,
- promptTokens: 200,
- completionTokens: 3000,
- totalTokens: undefined,
- },
- });
-
- const view = await prisma.observationView.findFirst({
- where: { traceId: dbTrace.id },
- });
-
- console.log(view);
-
- // calculated cost fields
- expect(view?.modelId).toBe("model-0");
- expect(view?.calculatedInputCost?.toString()).toBe("0");
- expect(view?.calculatedOutputCost?.toString()).toBe("0");
- expect(view?.calculatedTotalCost?.toString()).toBe("0");
- });
-
- it(`should prioritize own models`, async () => {
- await pruneDatabase();
- await prisma.model.create({
- data: {
- id: "model-0",
- modelName: "gpt-3.5-turbo",
- inputPrice: "0.0000000",
- outputPrice: "0.0000000",
- totalPrice: "0.1",
- matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
- projectId: null,
- startDate: null,
- tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
- unit: ModelUsageUnit.Tokens,
- },
- });
-
- await prisma.model.create({
- data: {
- id: "model-1",
- modelName: "gpt-3.5-turbo",
- inputPrice: "0.0000010",
- outputPrice: "0.0000020",
- totalPrice: "0.1",
- matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
- startDate: null,
- project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },
- tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
- unit: ModelUsageUnit.Tokens,
- },
- });
-
- const dbTrace = await prisma.trace.create({
- data: {
- name: "trace-name",
- project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },
- },
- });
-
- await prisma.observation.create({
- data: {
- traceId: dbTrace.id,
- type: "GENERATION",
- project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },
- model: "gpt-3.5-turbo",
- internalModel: "gpt-3.5-turbo",
- startTime: new Date("2024-01-01T00:00:00.000Z"),
- unit: ModelUsageUnit.Tokens,
- promptTokens: 200,
- completionTokens: 3000,
- totalTokens: undefined,
- },
- });
-
- const view = await prisma.observationView.findFirst({
- where: { traceId: dbTrace.id },
- });
-
- console.log(view);
-
- // calculated cost fields
- expect(view?.modelId).toBe("model-1");
- });
-
- it(`should prioritize old model if the latest model is not own one`, async () => {
- await prisma.model.create({
- data: {
- id: "model-1",
- modelName: "gpt-3.5-turbo",
- inputPrice: "0.0010",
- outputPrice: "0.0020",
- totalPrice: "0.1",
- matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
- startDate: new Date("2023-12-02"),
- tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
- unit: ModelUsageUnit.Tokens,
- },
- });
- await prisma.model.create({
- data: {
- id: "model-2",
- modelName: "gpt-3.5-turbo",
- inputPrice: "0.0000020",
- outputPrice: "0.0000040",
- totalPrice: undefined,
- matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
- startDate: new Date("2023-12-01"),
- tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
- project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },
- unit: ModelUsageUnit.Tokens,
- },
- });
-
- const dbTrace = await prisma.trace.create({
- data: {
- name: "trace-name",
- project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },
- },
- });
-
- await prisma.observation.create({
- data: {
- traceId: dbTrace.id,
- type: "GENERATION",
- project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },
- model: "gpt-3.5-turbo",
- internalModel: "gpt-3.5-turbo",
- startTime: new Date("2024-01-01T00:00:00.000Z"),
- unit: ModelUsageUnit.Tokens,
- promptTokens: 200,
- completionTokens: 3000,
- totalTokens: undefined,
- },
- });
-
- const view = await prisma.observationView.findFirst({
- where: { traceId: dbTrace.id },
- });
-
- console.log(view);
-
- // calculated cost fields
- expect(view?.modelId).toBe("model-2");
- expect(view?.calculatedInputCost?.toString()).toBe("0.0004");
- expect(view?.calculatedOutputCost?.toString()).toBe("0.012");
- expect(view?.calculatedTotalCost?.toString()).toBe("0.0124");
- });
-
- it(`should prioritize new model if the latest model is own one`, async () => {
- await pruneDatabase();
-
- await prisma.model.create({
- data: {
- id: "model-1",
- modelName: "gpt-3.5-turbo",
- inputPrice: "0.0010",
- outputPrice: "0.0020",
- totalPrice: "0.1",
- matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
- startDate: null,
- tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
- unit: ModelUsageUnit.Tokens,
- },
- });
- await prisma.model.create({
- data: {
- id: "model-2",
- modelName: "gpt-3.5-turbo",
- inputPrice: "0.0000020",
- outputPrice: "0.0000040",
- totalPrice: undefined,
- matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
- startDate: new Date("2023-12-01"),
- tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
- project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },
- unit: ModelUsageUnit.Tokens,
- },
- });
-
- const dbTrace = await prisma.trace.create({
- data: {
- name: "trace-name",
- project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },
- },
- });
-
- await prisma.observation.create({
- data: {
- traceId: dbTrace.id,
- type: "GENERATION",
- project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },
- model: "gpt-3.5-turbo",
- internalModel: "gpt-3.5-turbo",
- startTime: new Date("2024-01-01T00:00:00.000Z"),
- unit: ModelUsageUnit.Tokens,
- promptTokens: 200,
- completionTokens: 3000,
- totalTokens: undefined,
- },
- });
-
- const view = await prisma.observationView.findFirst({
- where: { traceId: dbTrace.id },
- });
-
- console.log(view);
-
- // calculated cost fields
- expect(view?.modelId).toBe("model-2");
- expect(view?.calculatedInputCost?.toString()).toBe("0.0004");
- expect(view?.calculatedOutputCost?.toString()).toBe("0.012");
- expect(view?.calculatedTotalCost?.toString()).toBe("0.0124");
- });
-
- it(`should prioritize user provided cost`, async () => {
- await pruneDatabase();
-
- await prisma.model.create({
- data: {
- id: "model-1",
- modelName: "gpt-3.5-turbo",
- inputPrice: "0.0010",
- outputPrice: "0.0020",
- totalPrice: "0.1",
- matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
- startDate: new Date("2023-12-02"),
- tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
- unit: ModelUsageUnit.Tokens,
- },
- });
- await prisma.model.create({
- data: {
- id: "model-2",
- modelName: "gpt-3.5-turbo",
- inputPrice: "0.0020",
- outputPrice: "0.0040",
- totalPrice: undefined,
- matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
- startDate: new Date("2023-12-01"),
- tokenizerConfig: { tokensPerMessage: 3, tokensPerName: 1 },
- project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },
- unit: ModelUsageUnit.Tokens,
- },
- });
-
- const dbTrace = await prisma.trace.create({
- data: {
- name: "trace-name",
- project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },
- },
- });
-
- await prisma.observation.create({
- data: {
- traceId: dbTrace.id,
- type: "GENERATION",
- project: { connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" } },
- model: "gpt-3.5-turbo",
- internalModel: "gpt-3.5-turbo",
- startTime: new Date("2024-01-01T00:00:00.000Z"),
- unit: ModelUsageUnit.Tokens,
- promptTokens: 200,
- completionTokens: 3000,
- totalTokens: undefined,
- inputCost: "1",
- outputCost: "2",
- totalCost: "3",
- },
- });
-
- const view = await prisma.observationView.findFirst({
- where: { traceId: dbTrace.id },
- });
-
- console.log(view);
-
- // calculated cost fields
- expect(view?.modelId).toBe("model-2");
- expect(view?.calculatedInputCost?.toString()).toBe("1");
- expect(view?.calculatedOutputCost?.toString()).toBe("2");
- expect(view?.calculatedTotalCost?.toString()).toBe("3");
- });
-});
diff --git a/web/src/__tests__/prompts.v1.servertest.ts b/web/src/__tests__/prompts.v1.servertest.ts
index d729e4ddb0..f355add0d2 100644
--- a/web/src/__tests__/prompts.v1.servertest.ts
+++ b/web/src/__tests__/prompts.v1.servertest.ts
@@ -522,13 +522,9 @@ describe("/api/public/prompts API Endpoint", () => {
expect(response.status).toBe(207);
- const dbGeneration = await prisma.observation.findUnique({
- where: {
- id: generationId,
- },
- });
-
- expect(dbGeneration).toBeNull();
+ expect(
+ getObservationById(generationId, "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a"),
+ ).rejects.toThrow("not found");
});
it("should create empty object if no config is provided", async () => {
diff --git a/web/src/__tests__/query-builder.servertest.ts b/web/src/__tests__/query-builder.servertest.ts
index 0193175a2c..cc50f2e0a0 100644
--- a/web/src/__tests__/query-builder.servertest.ts
+++ b/web/src/__tests__/query-builder.servertest.ts
@@ -2,12 +2,7 @@ import { pruneDatabase } from "@/src/__tests__/test-utils";
import {
createQuery,
enrichAndCreateQuery,
- executeQuery,
} from "@/src/server/api/services/queryBuilder";
-import { type aggregations } from "@/src/server/api/services/sqlInterface";
-import { prisma } from "@langfuse/shared/src/db";
-import { type z } from "zod";
-
describe("Build valid SQL queries", () => {
beforeEach(async () => await pruneDatabase());
@@ -179,445 +174,4 @@ describe("Build valid SQL queries", () => {
).toThrow('Column "unknown" not found in table traces');
});
});
-
- describe("should retrieve data", () => {
- it("should get a simple trace", async () => {
- await prisma.organization.upsert({
- where: { id: "other-org" },
- create: { id: "other-org", name: "other-org" },
- update: {},
- });
- await prisma.project.upsert({
- where: { id: "different-project-id" },
- create: {
- id: "different-project-id",
- name: "test-project",
- orgId: "other-org",
- },
- update: { name: "test-project", orgId: "other-org" },
- });
-
- await prisma.trace.createMany({
- data: [
- {
- id: "trace-1",
- name: "trace-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- userId: "user-1",
- metadata: { key: "value" },
- release: "1.0.0",
- version: "2.0.0",
- },
- {
- id: "trace-2",
- name: "trace-1",
- projectId: "different-project-id",
- userId: "user-1",
- metadata: { key: "value" },
- release: "1.0.0",
- version: "2.0.0",
- },
- ],
- });
-
- const result = await executeQuery(
- prisma,
- "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- {
- from: "traces",
- select: [{ column: "traceId" }],
- },
- );
-
- expect(result).toEqual([{ traceId: "trace-1" }]);
- });
-
- [
- {
- agg: "SUM",
- first: { sumCompletionTokens: 8, name: "trace-1" },
- second: { sumCompletionTokens: 4, name: "trace-2" },
- },
- {
- agg: "AVG",
- first: { avgCompletionTokens: 4, name: "trace-1" },
- second: { avgCompletionTokens: 4, name: "trace-2" },
- },
- {
- agg: "MIN",
- first: { minCompletionTokens: 3, name: "trace-1" },
- second: { minCompletionTokens: 4, name: "trace-2" },
- },
- {
- agg: "MAX",
- first: { maxCompletionTokens: 5, name: "trace-1" },
- second: { maxCompletionTokens: 4, name: "trace-2" },
- },
- {
- agg: "COUNT",
- first: { countCompletionTokens: 2, name: "trace-1" },
- second: { countCompletionTokens: 1, name: "trace-2" },
- },
- ].forEach((prop) => {
- it(`should group by name and aggregate ${prop.agg}`, async () => {
- await prisma.trace.create({
- data: {
- id: "trace-1",
- name: "trace-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- },
- });
-
- await prisma.observation.createMany({
- data: [
- {
- traceId: "trace-1",
- name: "trace-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- type: "GENERATION",
- completionTokens: 5,
- },
- {
- traceId: "trace-1",
- name: "trace-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- type: "GENERATION",
- completionTokens: 3,
- },
- {
- traceId: "trace-1",
- name: "trace-2",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- type: "GENERATION",
- completionTokens: 4,
- },
- ],
- });
-
- const result = await executeQuery(
- prisma,
- "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- {
- from: "observations",
- groupBy: [{ type: "string", column: "name" }],
- select: [
- { column: "completionTokens", agg: prop.agg as "SUM" | "AVG" },
- { column: "name" },
- ],
- },
- );
-
- expect(result[0]!).toStrictEqual(prop.first);
- expect(result[1]!).toStrictEqual(prop.second);
- });
- });
-
- it("should order by a column", async () => {
- await prisma.trace.create({
- data: {
- id: "trace-1",
- name: "trace-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- },
- });
-
- await prisma.observation.createMany({
- data: [
- {
- traceId: "trace-1",
- name: "trace-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- type: "GENERATION",
- completionTokens: 5,
- startTime: new Date("2021-01-01T00:00:00.000Z"),
- },
- {
- traceId: "trace-1",
- name: "trace-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- type: "GENERATION",
- completionTokens: 3,
- startTime: new Date("2021-01-01T00:00:00.000Z"),
- },
- {
- traceId: "trace-1",
- name: "trace-2",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- type: "GENERATION",
- completionTokens: 4,
- startTime: new Date("2021-01-02T00:00:00.000Z"),
- },
- ],
- });
-
- const result = await executeQuery(
- prisma,
- "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- {
- from: "observations",
- filter: [
- {
- type: "datetime",
- column: "startTime",
- operator: ">=",
- value: new Date("2021-01-01T00:00:00.000Z"),
- },
- {
- type: "datetime",
- column: "startTime",
- operator: "<=",
- value: new Date("2021-01-04T00:00:00.000Z"),
- },
- ],
-
- select: [{ column: "completionTokens" }],
- orderBy: [{ column: "completionTokens", direction: "ASC" }],
- },
- );
-
- expect(result).toStrictEqual([
- { completionTokens: 3 },
- { completionTokens: 4 },
- { completionTokens: 5 },
- ]);
- });
-
- [{ agg: "SUM", one: 8, two: 4 }].forEach((prop) => {
- it(`should aggregate time series ${prop.agg}`, async () => {
- await prisma.trace.create({
- data: {
- id: "trace-1",
- name: "trace-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- },
- });
-
- await prisma.observation.createMany({
- data: [
- {
- traceId: "trace-1",
- name: "trace-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- type: "GENERATION",
- completionTokens: 5,
- startTime: new Date("2021-01-01T00:00:00.000Z"),
- },
- {
- traceId: "trace-1",
- name: "trace-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- type: "GENERATION",
- completionTokens: 3,
- startTime: new Date("2021-01-01T00:00:00.000Z"),
- },
- {
- traceId: "trace-1",
- name: "trace-2",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- type: "GENERATION",
- completionTokens: 4,
- startTime: new Date("2021-01-02T00:00:00.000Z"),
- },
- ],
- });
-
- const result = await executeQuery(
- prisma,
- "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- {
- from: "observations",
- filter: [
- {
- type: "datetime",
- column: "startTime",
- operator: ">=",
- value: new Date("2021-01-01T00:00:00.000Z"),
- },
- {
- type: "datetime",
- column: "startTime",
- operator: "<=",
- value: new Date("2021-01-04T00:00:00.000Z"),
- },
- ],
- groupBy: [
- { type: "datetime", column: "startTime", temporalUnit: "day" },
- ],
- select: [
- { column: "completionTokens", agg: prop.agg as "SUM" | "AVG" },
- ],
- },
- );
-
- expect(result).toStrictEqual([
- {
- startTime: new Date("2021-01-01T00:00:00.000Z"),
- sumCompletionTokens: 8,
- },
- {
- startTime: new Date("2021-01-02T00:00:00.000Z"),
- sumCompletionTokens: 4,
- },
- {
- startTime: new Date("2021-01-03T00:00:00.000Z"),
- sumCompletionTokens: null,
- },
- {
- startTime: new Date("2021-01-04T00:00:00.000Z"),
- sumCompletionTokens: null,
- },
- ]);
- });
- });
-
- [
- {
- percentile: "50thPercentile",
- expectedOutcome: [
- {
- startTime: new Date("2021-01-01T00:00:00.000Z"),
- percentile50Duration: 8,
- },
- {
- startTime: new Date("2021-01-02T00:00:00.000Z"),
- percentile50Duration: 5,
- },
- {
- startTime: new Date("2021-01-03T00:00:00.000Z"),
- percentile50Duration: null,
- },
- {
- startTime: new Date("2021-01-04T00:00:00.000Z"),
- percentile50Duration: null,
- },
- ],
- },
- {
- percentile: "99thPercentile",
- expectedOutcome: [
- {
- startTime: new Date("2021-01-01T00:00:00.000Z"),
- percentile99Duration: 10,
- },
- {
- startTime: new Date("2021-01-02T00:00:00.000Z"),
- percentile99Duration: 5,
- },
- {
- startTime: new Date("2021-01-03T00:00:00.000Z"),
- percentile99Duration: null,
- },
- {
- startTime: new Date("2021-01-04T00:00:00.000Z"),
- percentile99Duration: null,
- },
- ],
- },
- {
- percentile: "90thPercentile",
- expectedOutcome: [
- {
- startTime: new Date("2021-01-01T00:00:00.000Z"),
- percentile90Duration: 10,
- },
- {
- startTime: new Date("2021-01-02T00:00:00.000Z"),
- percentile90Duration: 5,
- },
- {
- startTime: new Date("2021-01-03T00:00:00.000Z"),
- percentile90Duration: null,
- },
- {
- startTime: new Date("2021-01-04T00:00:00.000Z"),
- percentile90Duration: null,
- },
- ],
- },
- ].forEach((props) => {
- it(`should calculate right percentiles ${props.percentile}`, async () => {
- await prisma.trace.create({
- data: {
- id: "trace-1",
- name: "trace-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- },
- });
-
- await prisma.observation.createMany({
- data: [
- {
- traceId: "trace-1",
- name: "trace-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- type: "GENERATION",
- completionTokens: 5,
- startTime: new Date("2021-01-01T00:00:00.000Z"),
- endTime: new Date("2021-01-01T00:00:10.000Z"),
- },
- {
- traceId: "trace-1",
- name: "trace-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- type: "GENERATION",
- completionTokens: 3,
- startTime: new Date("2021-01-01T00:00:00.000Z"),
- endTime: new Date("2021-01-01T00:00:08.000Z"),
- },
- {
- traceId: "trace-1",
- name: "trace-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- type: "GENERATION",
- completionTokens: 3,
- startTime: new Date("2021-01-01T00:00:00.000Z"),
- endTime: new Date("2021-01-01T00:00:01.000Z"),
- },
- {
- traceId: "trace-1",
- name: "trace-2",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- type: "GENERATION",
- completionTokens: 4,
- startTime: new Date("2021-01-02T00:00:00.000Z"),
- endTime: new Date("2021-01-02T00:00:05.000Z"),
- },
- ],
- });
-
- const result = await executeQuery(
- prisma,
- "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- {
- from: "observations",
- filter: [
- {
- type: "datetime",
- column: "startTime",
- operator: ">=",
- value: new Date("2021-01-01T00:00:00.000Z"),
- },
- {
- type: "datetime",
- column: "startTime",
- operator: "<=",
- value: new Date("2021-01-04T00:00:00.000Z"),
- },
- ],
- groupBy: [
- { type: "datetime", column: "startTime", temporalUnit: "day" },
- ],
- select: [
- {
- column: "duration",
- agg: props.percentile as z.infer<typeof aggregations>,
- },
- ],
- },
- );
-
- expect(result).toStrictEqual(props.expectedOutcome);
- });
- });
- });
});
diff --git a/web/src/__tests__/test-utils.ts b/web/src/__tests__/test-utils.ts
index a7356f42e5..73f671d9c7 100644
--- a/web/src/__tests__/test-utils.ts
+++ b/web/src/__tests__/test-utils.ts
@@ -11,10 +11,7 @@ export const pruneDatabase = async () => {
throw new Error("You cannot prune database unless running on localhost.");
}
- await prisma.score.deleteMany();
await prisma.scoreConfig.deleteMany();
- await prisma.observation.deleteMany();
- await prisma.trace.deleteMany();
await prisma.traceSession.deleteMany();
await prisma.datasetItem.deleteMany();
await prisma.dataset.deleteMany();
diff --git a/web/src/components/level-colors.tsx b/web/src/components/level-colors.tsx
index 4b649813e5..94ca11e235 100644
--- a/web/src/components/level-colors.tsx
+++ b/web/src/components/level-colors.tsx
@@ -1,4 +1,4 @@
-import { type ObservationLevel } from "@langfuse/shared";
+import { type ObservationLevelType } from "@langfuse/shared";
export const LevelColors = {
DEFAULT: { text: "", bg: "" },
@@ -15,5 +15,5 @@ export const LevelSymbols = {
};
export const formatAsLabel = (countLabel: string) => {
- return countLabel.replace(/Count$/, "").toUpperCase() as ObservationLevel;
+ return countLabel.replace(/Count$/, "").toUpperCase() as ObservationLevelType;
};
diff --git a/web/src/components/table/use-cases/observations.tsx b/web/src/components/table/use-cases/observations.tsx
index d1cf9f1f20..ef9dbdb5e3 100644
--- a/web/src/components/table/use-cases/observations.tsx
+++ b/web/src/components/table/use-cases/observations.tsx
@@ -16,7 +16,7 @@ import { formatIntervalSeconds } from "@/src/utils/dates";
import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
import { type LangfuseColumnDef } from "@/src/components/table/types";
import {
- type ObservationLevel,
+ type ObservationLevelType,
type FilterState,
type ObservationOptions,
BatchExportTableName,
@@ -51,7 +51,7 @@ export type ObservationsTableRow = {
id: string;
traceId?: string;
startTime: Date;
- level?: ObservationLevel;
+ level?: ObservationLevelType;
statusMessage?: string;
endTime?: Date;
completionStartTime?: Date;
@@ -452,7 +452,7 @@ export default function ObservationsTable({
},
enableHiding: true,
cell({ row }) {
- const value: ObservationLevel | undefined = row.getValue("level");
+ const value: ObservationLevelType | undefined = row.getValue("level");
return value ? (
<span
className={cn(
diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsx
index 96e98200b3..77b8068ad5 100644
--- a/web/src/components/table/use-cases/traces.tsx
+++ b/web/src/components/table/use-cases/traces.tsx
@@ -34,7 +34,7 @@ import {
type FilterState,
type TraceOptions,
tracesTableColsWithOptions,
- type ObservationLevel,
+ type ObservationLevelType,
BatchExportTableName,
AnnotationQueueObjectType,
BatchActionType,
@@ -81,7 +81,7 @@ export type TracesTableRow = {
timestamp: Date;
name: string;
userId: string;
- level?: ObservationLevel;
+ level?: ObservationLevelType;
observationCount?: bigint;
levelCounts: {
errorCount?: bigint;
diff --git a/web/src/components/trace/ObservationPreview.tsx b/web/src/components/trace/ObservationPreview.tsx
index 3faaaa4c08..7bf6eb73b7 100644
--- a/web/src/components/trace/ObservationPreview.tsx
+++ b/web/src/components/trace/ObservationPreview.tsx
@@ -2,7 +2,7 @@ import { JSONView } from "@/src/components/ui/CodeJsonViewer";
import {
AnnotationQueueObjectType,
type APIScore,
- type ScoreSource,
+ type ScoreSourceType,
} from "@langfuse/shared";
import {
Card,
@@ -128,7 +128,7 @@ export const ObservationPreview = ({
}
acc.get(score.source)?.push(score);
return acc;
- }, new Map<ScoreSource, APIScore[]>());
+ }, new Map<ScoreSourceType, APIScore[]>());
return (
<Card
diff --git a/web/src/components/trace/ObservationTree.tsx b/web/src/components/trace/ObservationTree.tsx
index 684f4cf563..82980bb17f 100644
--- a/web/src/components/trace/ObservationTree.tsx
+++ b/web/src/components/trace/ObservationTree.tsx
@@ -3,8 +3,9 @@ import { cn } from "@/src/utils/tailwind";
import {
type APIScore,
type Trace,
- type $Enums,
ObservationLevel,
+ type ObservationLevelType,
+ type ObservationType,
} from "@langfuse/shared";
import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
import { Fragment, useMemo, useRef, useEffect } from "react";
@@ -54,8 +55,8 @@ export const ObservationTree = ({
traceCommentCounts?: Map<string, number>;
className?: string;
showExpandControls?: boolean;
- minLevel?: ObservationLevel;
- setMinLevel?: React.Dispatch<React.SetStateAction<ObservationLevel>>;
+ minLevel?: ObservationLevelType;
+ setMinLevel?: React.Dispatch<React.SetStateAction<ObservationLevelType>>;
}) => {
const { nestedObservations, hiddenObservationsCount } = useMemo(
() => nestObservations(props.observations, props.minLevel),
@@ -450,7 +451,7 @@ const ObservationTreeNodeCard = ({
};
export const ColorCodedObservationType = (props: {
- observationType: $Enums.ObservationType;
+ observationType: ObservationType;
}) => {
return (
<span
diff --git a/web/src/components/trace/TracePreview.tsx b/web/src/components/trace/TracePreview.tsx
index 82429610bb..c07c97e72f 100644
--- a/web/src/components/trace/TracePreview.tsx
+++ b/web/src/components/trace/TracePreview.tsx
@@ -2,7 +2,7 @@ import { JSONView } from "@/src/components/ui/CodeJsonViewer";
import {
type APIScore,
type Trace,
- type ScoreSource,
+ type ScoreSourceType,
AnnotationQueueObjectType,
} from "@langfuse/shared";
import {
@@ -80,7 +80,7 @@ export const TracePreview = ({
}
acc.get(score.source)?.push(score);
return acc;
- }, new Map<ScoreSource, APIScore[]>());
+ }, new Map<ScoreSourceType, APIScore[]>());
const traceMedia = api.media.getByTraceOrObservationId.useQuery(
{
traceId: trace.id,
diff --git a/web/src/components/trace/index.tsx b/web/src/components/trace/index.tsx
index dc958fedea..647aac0a1b 100644
--- a/web/src/components/trace/index.tsx
+++ b/web/src/components/trace/index.tsx
@@ -39,7 +39,11 @@ import { useCallback, useState } from "react";
import { DeleteButton } from "@/src/components/deleteButton";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { TraceTimelineView } from "@/src/components/trace/TraceTimelineView";
-import { type APIScore, ObservationLevel } from "@langfuse/shared";
+import {
+ ObservationLevel,
+ type APIScore,
+ type ObservationLevelType,
+} from "@langfuse/shared";
import { calculateDisplayTotalCost } from "@/src/components/trace/lib/helpers";
import { useIsAuthenticatedAndProjectMember } from "@/src/features/auth/hooks";
import {
@@ -63,7 +67,7 @@ export function Trace(props: {
projectId: string;
viewType?: "detailed" | "focused";
isValidObservationId?: boolean;
- defaultMinObservationLevel?: ObservationLevel;
+ defaultMinObservationLevel?: ObservationLevelType;
}) {
const viewType = props.viewType ?? "detailed";
const isValidObservationId = props.isValidObservationId ?? true;
@@ -88,7 +92,7 @@ export function Trace(props: {
);
const [minObservationLevel, setMinObservationLevel] =
- useState<ObservationLevel>(
+ useState<ObservationLevelType>(
props.defaultMinObservationLevel ?? ObservationLevel.DEFAULT,
);
@@ -242,7 +246,9 @@ export function Trace(props: {
<Percent className="h-4 w-4" />
</Toggle>
<Select
- onValueChange={(v: ObservationLevel) => setMinObservationLevel(v)}
+ onValueChange={(v: ObservationLevelType) =>
+ setMinObservationLevel(v)
+ }
value={minObservationLevel}
>
<SelectTrigger
diff --git a/web/src/components/trace/lib/helpers.ts b/web/src/components/trace/lib/helpers.ts
index a4f519544b..e1fa74faf5 100644
--- a/web/src/components/trace/lib/helpers.ts
+++ b/web/src/components/trace/lib/helpers.ts
@@ -1,4 +1,8 @@
-import { ObservationLevel, ObservationType } from "@langfuse/shared";
+import {
+ ObservationLevel,
+ type ObservationLevelType,
+ ObservationType,
+} from "@langfuse/shared";
import { type NestedObservation } from "@/src/utils/types";
import { type ObservationReturnType } from "@/src/server/api/routers/traces";
import Decimal from "decimal.js";
@@ -14,7 +18,7 @@ export const treeItemColors: Map<TreeItemType, string> = new Map([
export function nestObservations(
list: ObservationReturnType[],
- minLevel?: ObservationLevel,
+ minLevel?: ObservationLevelType,
): {
nestedObservations: NestedObservation[];
hiddenObservationsCount: number;
@@ -146,7 +150,7 @@ export function calculateDisplayTotalCost(p: {
return totalCost;
}
-function getObservationLevels(minLevel: ObservationLevel | undefined) {
+function getObservationLevels(minLevel: ObservationLevelType | undefined) {
const ascendingLevels = [
ObservationLevel.DEBUG,
ObservationLevel.DEFAULT,
diff --git a/web/src/features/comments/validateCommentReferenceObject.ts b/web/src/features/comments/validateCommentReferenceObject.ts
index d7d2e40a6b..cc96d4a222 100644
--- a/web/src/features/comments/validateCommentReferenceObject.ts
+++ b/web/src/features/comments/validateCommentReferenceObject.ts
@@ -1,37 +1,7 @@
-import {
- CommentObjectType,
- type PrismaClient,
- type CreateCommentData,
-} from "@langfuse/shared";
+import { CommentObjectType, type CreateCommentData } from "@langfuse/shared";
import { type z } from "zod";
import { getObservationById, getTraceById } from "@langfuse/shared/src/server";
-type PrismaModelName = keyof Omit<
- PrismaClient,
- | "$connect"
- | "$disconnect"
- | "$on"
- | "$transaction"
- | "$use"
- | "$extends"
- | "$executeRaw"
- | "$executeRawUnsafe"
- | "$queryRaw"
- | "$queryRawUnsafe"
- | "$metrics"
- | symbol
->;
-
-const COMMENT_OBJECT_TYPE_TO_PRISMA_MODEL: Record<
- CommentObjectType,
- PrismaModelName
-> = {
- [CommentObjectType.TRACE]: "trace",
- [CommentObjectType.OBSERVATION]: "observation",
- [CommentObjectType.SESSION]: "traceSession",
- [CommentObjectType.PROMPT]: "prompt",
-} as const;
-
const isObservationOrTrace = (objectType: CommentObjectType) => {
return (
objectType === CommentObjectType.OBSERVATION ||
@@ -62,7 +32,12 @@ export const validateCommentReferenceObject = async ({
errorMessage: `Reference object, ${objectType}: ${objectId} not found in Clickhouse. Skipping creating comment.`,
};
} else {
- const prismaModel = COMMENT_OBJECT_TYPE_TO_PRISMA_MODEL[objectType];
+ const prismaModel =
+ objectType === CommentObjectType.SESSION
+ ? "traceSession"
+ : objectType === CommentObjectType.PROMPT
+ ? "prompt"
+ : null;
if (!prismaModel) {
return {
diff --git a/web/src/features/dashboard/components/ScoresTable.tsx b/web/src/features/dashboard/components/ScoresTable.tsx
index 233f13e0e6..a8895255a2 100644
--- a/web/src/features/dashboard/components/ScoresTable.tsx
+++ b/web/src/features/dashboard/components/ScoresTable.tsx
@@ -2,7 +2,7 @@ import { DashboardCard } from "@/src/features/dashboard/components/cards/Dashboa
import { DashboardTable } from "@/src/features/dashboard/components/cards/DashboardTable";
import {
type ScoreDataType,
- type ScoreSource,
+ type ScoreSourceType,
type FilterState,
} from "@langfuse/shared";
import { api } from "@/src/utils/api";
@@ -26,7 +26,11 @@ const dropValuesForCategoricalScores = (
};
const scoreNameSourceDataTypeMatch =
- (scoreName: string, scoreSource: ScoreSource, scoreDataType: ScoreDataType) =>
+ (
+ scoreName: string,
+ scoreSource: ScoreSourceType,
+ scoreDataType: ScoreDataType,
+ ) =>
(item: DatabaseRow) =>
item.scoreName === scoreName &&
item.scoreSource === scoreSource &&
@@ -139,7 +143,7 @@ export const ScoresTable = ({
return metrics.data.map((metric) => {
const scoreName = metric.scoreName as string;
- const scoreSource = metric.scoreSource as ScoreSource;
+ const scoreSource = metric.scoreSource as ScoreSourceType;
const scoreDataType = metric.scoreDataType as ScoreDataType;
const zeroValueScore = zeroValueScores.data.find(
diff --git a/web/src/features/dashboard/components/score-analytics/NumericScoreHistogram.tsx b/web/src/features/dashboard/components/score-analytics/NumericScoreHistogram.tsx
index e6266c1e71..a354214b89 100644
--- a/web/src/features/dashboard/components/score-analytics/NumericScoreHistogram.tsx
+++ b/web/src/features/dashboard/components/score-analytics/NumericScoreHistogram.tsx
@@ -1,7 +1,7 @@
import { api } from "@/src/utils/api";
import {
- type ScoreSource,
+ type ScoreSourceType,
type FilterState,
type ScoreDataType,
} from "@langfuse/shared";
@@ -16,7 +16,7 @@ import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";
export function NumericScoreHistogram(props: {
projectId: string;
name: string;
- source: ScoreSource;
+ source: ScoreSourceType;
dataType: ScoreDataType;
globalFilterState: FilterState;
}) {
diff --git a/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx b/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx
index 65d4c82661..d681667601 100644
--- a/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx
+++ b/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx
@@ -3,7 +3,7 @@ import { api } from "@/src/utils/api";
import { BaseTimeSeriesChart } from "@/src/features/dashboard/components/BaseTimeSeriesChart";
import { Card } from "@/src/components/ui/card";
import {
- type ScoreSource,
+ type ScoreSourceType,
type FilterState,
type ScoreDataType,
} from "@langfuse/shared";
@@ -22,7 +22,7 @@ import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";
export function NumericScoreTimeSeriesChart(props: {
projectId: string;
- source: ScoreSource;
+ source: ScoreSourceType;
dataType: ScoreDataType;
name: string;
agg: DashboardDateRangeAggregationOption;
diff --git a/web/src/features/otel/server/index.ts b/web/src/features/otel/server/index.ts
index 4d318e35ff..1b53ecd837 100644
--- a/web/src/features/otel/server/index.ts
+++ b/web/src/features/otel/server/index.ts
@@ -1,6 +1,6 @@
import { type IngestionEventType } from "@langfuse/shared/src/server";
import { randomUUID } from "crypto";
-import { ObservationLevel } from "@prisma/client";
+import { ObservationLevel } from "@langfuse/shared";
const convertNanoTimestampToISO = (
timestamp:
diff --git a/web/src/features/public-api/server/apiScope.ts b/web/src/features/public-api/server/apiScope.ts
deleted file mode 100644
index c9c724e85c..0000000000
--- a/web/src/features/public-api/server/apiScope.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import { prisma } from "@langfuse/shared/src/db";
-import { type ApiAccessScope, logger } from "@langfuse/shared/src/server";
-
-type Resource = {
- type: "project" | "trace" | "observation" | "score";
- id: string;
-};
-
-export async function checkApiAccessScope(
- scope: ApiAccessScope,
- resources: Resource[],
- action?: "score",
-): Promise<boolean> {
- // ACCESS LEVEL
- // If the access level is "scores", the only action allowed is "score"
- if (scope.accessLevel === "scores" && action !== "score") return false;
-
- // RESOURCE within project of scope
- // If the resource is a project, it must match the project of the scope
- const checks = await Promise.all(
- resources.map((resource) => isResourceInProject(resource, scope.projectId)),
- );
- return checks.every((result) => result);
-}
-
-async function isResourceInProject(resource: Resource, projectId: string) {
- switch (resource.type) {
- case "project":
- const projectCheck = resource.id === projectId;
- if (!projectCheck)
- logger.warn("project check", projectCheck, resource.id, projectId);
- return projectCheck;
-
- case "trace":
- const traceCheck =
- (await prisma.trace.count({
- where: { id: resource.id, projectId },
- })) === 1;
- if (!traceCheck)
- logger.warn("trace check", traceCheck, resource.id, projectId);
- return traceCheck;
-
- case "observation":
- const observationCheck =
- (await prisma.observation.count({
- where: { id: resource.id, projectId },
- })) === 1;
- if (!observationCheck)
- logger.warn(
- "observation check",
- observationCheck,
- resource.id,
- projectId,
- );
- return observationCheck;
-
- case "score":
- const scoreCheck =
- (await prisma.score.count({
- where: {
- id: resource.id,
- projectId,
- },
- })) === 1;
- if (!scoreCheck)
- logger.warn("score check", scoreCheck, resource.id, projectId);
- return scoreCheck;
- default:
- return false;
- }
-}
diff --git a/web/src/features/scores/lib/aggregateScores.ts b/web/src/features/scores/lib/aggregateScores.ts
index c2c2160325..422249655e 100644
--- a/web/src/features/scores/lib/aggregateScores.ts
+++ b/web/src/features/scores/lib/aggregateScores.ts
@@ -2,7 +2,7 @@ import {
type ScoreAggregate,
type ScoreSimplified,
type APIScore,
- type ScoreSource,
+ type ScoreSourceType,
type ScoreDataType,
} from "@langfuse/shared";
@@ -12,7 +12,7 @@ export const composeAggregateScoreKey = ({
dataType,
}: {
name: string;
- source: ScoreSource;
+ source: ScoreSourceType;
dataType: ScoreDataType;
keyPrefix?: string;
}): string => {
diff --git a/web/src/features/scores/lib/types.ts b/web/src/features/scores/lib/types.ts
index e81fffdcf0..03d3c87211 100644
--- a/web/src/features/scores/lib/types.ts
+++ b/web/src/features/scores/lib/types.ts
@@ -3,7 +3,7 @@ import { type TracesTableRow } from "@/src/components/table/use-cases/traces";
import { type DatasetRunItemRowData } from "@/src/features/datasets/components/DatasetRunItemsTable";
import { type DatasetRunRowData } from "@/src/features/datasets/components/DatasetRunsTable";
import { type PromptVersionTableRow } from "@/src/pages/project/[projectId]/prompts/[promptName]/metrics";
-import { type ScoreDataType, type ScoreSource } from "@langfuse/shared";
+import { type ScoreDataType, type ScoreSourceType } from "@langfuse/shared";
export type TableRowTypesWithIndividualScoreColumns =
| ObservationsTableRow
@@ -16,5 +16,5 @@ export type ScoreData = {
key: string;
name: string;
dataType: ScoreDataType;
- source: ScoreSource;
+ source: ScoreSourceType;
};
diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.ts
index c924218efd..8ad36ed0ac 100644
--- a/web/src/server/api/routers/scores.ts
+++ b/web/src/server/api/routers/scores.ts
@@ -20,11 +20,11 @@ import {
UpdateAnnotationScoreData,
validateDbScore,
ScoreSource,
+ type Score,
LangfuseNotFoundError,
InvalidRequestError,
InternalServerError,
} from "@langfuse/shared";
-import { type Score } from "@langfuse/shared/src/db";
import {
getScoresGroupedByNameSourceType,
getScoresUiCount,
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index ef128a5855..abf4bc2675 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -18,7 +18,7 @@ import {
timeFilter,
tracesTableUiColumnDefinitions,
} from "@langfuse/shared";
-import { type ObservationView } from "@langfuse/shared/src/db";
+import { type ObservationView } from "@langfuse/shared";
import {
traceException,
getTracesTable,
diff --git a/web/src/utils/types.ts b/web/src/utils/types.ts
index 3f19421c3c..127c6be5a9 100644
--- a/web/src/utils/types.ts
+++ b/web/src/utils/types.ts
@@ -1,4 +1,4 @@
-import { type Observation } from "@langfuse/shared/src/db";
+import { type Observation } from "@langfuse/shared";
import { type inferRouterInputs, type inferRouterOutputs } from "@trpc/server";
import { type AppRouter } from "@/src/server/api/root";
import { type ObservationReturnType } from "@/src/server/api/routers/traces";
diff --git a/worker/package.json b/worker/package.json
index f1bb802e1a..c088dfd02b 100644
--- a/worker/package.json
+++ b/worker/package.json
@@ -13,7 +13,7 @@
"start": "dotenv -e ../.env -- node dist/index.js",
"build": "tsc",
"dev": "dotenv -e ../.env -- nodemon src/index.ts",
- "lint": "eslint . --ext .js,.jsx,.ts,.tsx --max-warnings 33",
+ "lint": "eslint . --ext .js,.jsx,.ts,.tsx --max-warnings 31",
"lint:fix": "eslint . --ext .js,.jsx,.ts,.tsx --fix",
"refill-ingestion-events": "dotenv -e ../.env -- tsx src/scripts/refill-ingestion-events.ts",
"refill-billing-event": "dotenv -e ../.env -- tsx src/scripts/refill-billing-event.ts"
diff --git a/worker/src/__tests__/evalService.test.ts b/worker/src/__tests__/evalService.test.ts
index 8ad89d42ad..3cd6958b1e 100644
--- a/worker/src/__tests__/evalService.test.ts
+++ b/worker/src/__tests__/evalService.test.ts
@@ -68,14 +68,6 @@ describe("eval service tests", () => {
test("creates new 'trace' eval job", async () => {
const traceId = randomUUID();
- await kyselyPrisma.$kysely
- .insertInto("traces")
- .values({
- id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- })
- .execute();
-
await upsertTrace({
id: traceId,
project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
@@ -124,14 +116,6 @@ describe("eval service tests", () => {
const datasetId = randomUUID();
const datasetItemId = randomUUID();
- await kyselyPrisma.$kysely
- .insertInto("traces")
- .values({
- id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- })
- .execute();
-
await upsertTrace({
id: traceId,
project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
@@ -140,16 +124,6 @@ describe("eval service tests", () => {
updated_at: convertDateToClickhouseDateTime(new Date()),
});
- await kyselyPrisma.$kysely
- .insertInto("observations")
- .values({
- id: observationId,
- trace_id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- type: sql`'GENERATION'::"ObservationType"`,
- })
- .execute();
-
await upsertObservation({
id: observationId,
trace_id: traceId,
@@ -296,14 +270,6 @@ describe("eval service tests", () => {
expect(jobsAfterDataset.length).toBe(0);
// Now upsert the trace and validate that the job was created.
- await kyselyPrisma.$kysely
- .insertInto("traces")
- .values({
- id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- })
- .execute();
-
await upsertTrace({
id: traceId,
project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
@@ -350,14 +316,6 @@ describe("eval service tests", () => {
.execute();
// Create the trace and send the trace event. No job should be created
- await kyselyPrisma.$kysely
- .insertInto("traces")
- .values({
- id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- })
- .execute();
-
await upsertTrace({
id: traceId,
project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
@@ -435,14 +393,6 @@ describe("eval service tests", () => {
test("does not create job for inactive config", async () => {
const traceId = randomUUID();
- await kyselyPrisma.$kysely
- .insertInto("traces")
- .values({
- id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- })
- .execute();
-
await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
@@ -477,14 +427,6 @@ describe("eval service tests", () => {
test("does not create eval job for existing job execution", async () => {
const traceId = randomUUID();
- await kyselyPrisma.$kysely
- .insertInto("traces")
- .values({
- id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- })
- .execute();
-
await upsertTrace({
id: traceId,
project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
@@ -545,14 +487,6 @@ describe("eval service tests", () => {
test("does not create job for inactive config", async () => {
const traceId = randomUUID();
- await kyselyPrisma.$kysely
- .insertInto("traces")
- .values({
- id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- })
- .execute();
-
await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
@@ -587,14 +521,6 @@ describe("eval service tests", () => {
test("does not create eval job for 0 sample rate", async () => {
const traceId = randomUUID();
- await kyselyPrisma.$kysely
- .insertInto("traces")
- .values({
- id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- })
- .execute();
-
await kyselyPrisma.$kysely
.insertInto("llm_api_keys")
.values({
@@ -641,15 +567,6 @@ describe("eval service tests", () => {
test("cancels a job if the second event deselects", async () => {
const traceId = randomUUID();
- await kyselyPrisma.$kysely
- .insertInto("traces")
- .values({
- id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- user_id: "a",
- })
- .execute();
-
await upsertTrace({
id: traceId,
project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
@@ -724,12 +641,6 @@ describe("eval service tests", () => {
await new Promise((resolve) => setTimeout(resolve, 500));
// update the trace to deselect the trace
- await kyselyPrisma.$kysely
- .updateTable("traces")
- .set("user_id", "b")
- .where("id", "=", traceId)
- .execute();
-
await upsertTrace({
id: traceId,
project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
@@ -1024,17 +935,6 @@ describe("eval service tests", () => {
test("fails to eval without llm api key", async () => {
const traceId = randomUUID();
- await kyselyPrisma.$kysely
- .insertInto("traces")
- .values({
- id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- user_id: "a",
- input: { input: "This is a great prompt" },
- output: { output: "This is a great response" },
- })
- .execute();
-
const templateId = randomUUID();
await kyselyPrisma.$kysely
.insertInto("eval_templates")
@@ -1230,17 +1130,6 @@ describe("eval service tests", () => {
test("evals should cancel if job is cancelled", async () => {
const traceId = randomUUID();
- await kyselyPrisma.$kysely
- .insertInto("traces")
- .values({
- id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- user_id: "a",
- input: { input: "This is a great prompt" },
- output: { output: "This is a great response" },
- })
- .execute();
-
const templateId = randomUUID();
await kyselyPrisma.$kysely
.insertInto("eval_templates")
@@ -1316,17 +1205,6 @@ describe("eval service tests", () => {
openAIServer.respondWithDefault();
const traceId = randomUUID();
- await kyselyPrisma.$kysely
- .insertInto("traces")
- .values({
- id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- user_id: "a",
- input: { input: "This is a great prompt" },
- output: { output: "This is a great response" },
- })
- .execute();
-
const templateId = randomUUID();
await kyselyPrisma.$kysely
.insertInto("eval_templates")
@@ -1424,17 +1302,6 @@ describe("eval service tests", () => {
const datasetItemId = randomUUID();
const traceId = randomUUID();
- await kyselyPrisma.$kysely
- .insertInto("traces")
- .values({
- id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- user_id: "a",
- input: { input: "This is a great prompt" },
- output: { output: "This is a great response" },
- })
- .execute();
-
await kyselyPrisma.$kysely
.insertInto("datasets")
.values({
@@ -1491,17 +1358,6 @@ describe("eval service tests", () => {
test("extracts variables from a trace", async () => {
const traceId = randomUUID();
- await kyselyPrisma.$kysely
- .insertInto("traces")
- .values({
- id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- user_id: "a",
- input: { input: "This is a great prompt" },
- output: { output: "This is a great response" },
- })
- .execute();
-
await upsertTrace({
id: traceId,
project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
@@ -1548,17 +1404,6 @@ describe("eval service tests", () => {
test("extracts variables from a observation", async () => {
const traceId = randomUUID();
- await kyselyPrisma.$kysely
- .insertInto("traces")
- .values({
- id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- user_id: "a",
- input: { input: "This is a great prompt" },
- output: { output: "This is a great response" },
- })
- .execute();
-
await upsertTrace({
id: traceId,
project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
@@ -1570,19 +1415,6 @@ describe("eval service tests", () => {
updated_at: convertDateToClickhouseDateTime(new Date()),
});
- await kyselyPrisma.$kysely
- .insertInto("observations")
- .values({
- id: randomUUID(),
- trace_id: traceId,
- name: "great-llm-name",
- type: sql`'GENERATION'::"ObservationType"`,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- input: { huhu: "This is a great prompt" },
- output: { haha: "This is a great response" },
- })
- .execute();
-
await upsertObservation({
id: randomUUID(),
trace_id: traceId,
@@ -1633,17 +1465,6 @@ describe("eval service tests", () => {
test("fails if observation is not present", async () => {
const traceId = randomUUID();
- await kyselyPrisma.$kysely
- .insertInto("traces")
- .values({
- id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- user_id: "a",
- input: { input: "This is a great prompt" },
- output: { output: "This is a great response" },
- })
- .execute();
-
const variableMapping = variableMappingList.parse([
{
langfuseObject: "generation",
@@ -1676,17 +1497,6 @@ describe("eval service tests", () => {
test("does not fail if observation data is null", async () => {
const traceId = randomUUID();
- await kyselyPrisma.$kysely
- .insertInto("traces")
- .values({
- id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- user_id: "a",
- input: { input: "This is a great prompt" },
- output: { output: "This is a great response" },
- })
- .execute();
-
await upsertTrace({
id: traceId,
project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
@@ -1699,17 +1509,6 @@ describe("eval service tests", () => {
});
// fetching input and output for an observation which has NULL values
- await kyselyPrisma.$kysely
- .insertInto("observations")
- .values({
- id: randomUUID(),
- trace_id: traceId,
- name: "great-llm-name",
- type: sql`'GENERATION'::"ObservationType"`,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- })
- .execute();
-
await upsertObservation({
id: randomUUID(),
trace_id: traceId,
@@ -1758,17 +1557,6 @@ describe("eval service tests", () => {
test("extracts variables from a youngest observation", async () => {
const traceId = randomUUID();
- await kyselyPrisma.$kysely
- .insertInto("traces")
- .values({
- id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- user_id: "a",
- input: { input: "This is a great prompt" },
- output: { output: "This is a great response" },
- })
- .execute();
-
await upsertTrace({
id: traceId,
project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
@@ -1780,20 +1568,6 @@ describe("eval service tests", () => {
updated_at: convertDateToClickhouseDateTime(new Date()),
});
- await kyselyPrisma.$kysely
- .insertInto("observations")
- .values({
- id: randomUUID(),
- trace_id: traceId,
- name: "great-llm-name",
- start_time: new Date("2022-01-01T00:00:00.000Z"),
- type: sql`'GENERATION'::"ObservationType"`,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- input: { huhu: "This is a great prompt" },
- output: { haha: "This is a great response" },
- })
- .execute();
-
await upsertObservation({
id: randomUUID(),
trace_id: traceId,
@@ -1809,20 +1583,6 @@ describe("eval service tests", () => {
updated_at: convertDateToClickhouseDateTime(new Date()),
});
- await kyselyPrisma.$kysely
- .insertInto("observations")
- .values({
- id: randomUUID(),
- trace_id: traceId,
- name: "great-llm-name",
- start_time: new Date("2022-01-02T00:00:00.000Z"),
- type: sql`'GENERATION'::"ObservationType"`,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- input: { huhu: "This is a great prompt again" },
- output: { haha: "This is a great response again" },
- })
- .execute();
-
await upsertObservation({
id: randomUUID(),
trace_id: traceId,
diff --git a/worker/src/__tests__/utils.ts b/worker/src/__tests__/utils.ts
index 8b615a11d0..d9ab4c9789 100644
--- a/worker/src/__tests__/utils.ts
+++ b/worker/src/__tests__/utils.ts
@@ -8,9 +8,6 @@ export const pruneDatabase = async () => {
}
logger.info("Pruning database");
- await prisma.score.deleteMany();
- await prisma.observation.deleteMany();
- await prisma.trace.deleteMany();
await prisma.datasetItem.deleteMany();
await prisma.dataset.deleteMany();
await prisma.datasetRuns.deleteMany();
diff --git a/worker/src/ee/evaluation/evalService.ts b/worker/src/ee/evaluation/evalService.ts
index a4cc670d18..d6d0787035 100644
--- a/worker/src/ee/evaluation/evalService.ts
+++ b/worker/src/ee/evaluation/evalService.ts
@@ -1,8 +1,9 @@
import { randomUUID } from "crypto";
import { sql } from "kysely";
import { z } from "zod";
-import { ScoreSource, JobConfigState } from "@prisma/client";
+import { JobConfigState } from "@prisma/client";
import {
+ ScoreSource,
QueueJobs,
QueueName,
EvalExecutionEvent,
diff --git a/worker/src/features/batchExport/handleBatchExportJob.ts b/worker/src/features/batchExport/handleBatchExportJob.ts
index 69072dba87..f8c1b470f4 100644
--- a/worker/src/features/batchExport/handleBatchExportJob.ts
+++ b/worker/src/features/batchExport/handleBatchExportJob.ts
@@ -6,11 +6,11 @@ import {
BatchExportStatus,
exportOptions,
FilterCondition,
- Score,
TimeFilter,
} from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import {
+ Score,
DatabaseReadStream,
StorageServiceFactory,
sendBatchExportSuccessEmail,
diff --git a/worker/src/features/batchExport/types.ts b/worker/src/features/batchExport/types.ts
index b4c5516a3f..61699771e8 100644
--- a/worker/src/features/batchExport/types.ts
+++ b/worker/src/features/batchExport/types.ts
@@ -1,4 +1,4 @@
-import { ObservationLevel } from "@langfuse/shared";
+import { ObservationLevelType } from "@langfuse/shared/src/server";
import Decimal from "decimal.js";
export type BatchExportSessionsRow = {
@@ -25,7 +25,7 @@ export type BatchExportTracesRow = {
timestamp: Date;
name: string;
userId?: string | null;
- level?: ObservationLevel | null;
+ level?: ObservationLevelType | null;
observationCount?: number | null;
scores?: Record<string, string[] | number[]> | null;
latency?: number | null;
diff --git a/worker/src/features/traces/processPostgresTraceDelete.ts b/worker/src/features/traces/processPostgresTraceDelete.ts
index b2187cf157..e836eef9bb 100644
--- a/worker/src/features/traces/processPostgresTraceDelete.ts
+++ b/worker/src/features/traces/processPostgresTraceDelete.ts
@@ -9,49 +9,22 @@ export const processPostgresTraceDelete = async (
`Deleting traces ${JSON.stringify(traceIds)} in project ${projectId} from Postgres`,
);
try {
- await prisma.$transaction([
- prisma.trace.deleteMany({
- where: {
- id: {
- in: traceIds,
- },
- projectId: projectId,
+ await prisma.jobExecution.updateMany({
+ where: {
+ jobInputTraceId: {
+ in: traceIds,
},
- }),
- prisma.observation.deleteMany({
- where: {
- traceId: {
- in: traceIds,
- },
- projectId: projectId,
+ projectId: projectId,
+ },
+ data: {
+ jobInputTraceId: {
+ set: null,
},
- }),
- prisma.score.deleteMany({
- where: {
- traceId: {
- in: traceIds,
- },
- projectId: projectId,
+ jobInputObservationId: {
+ set: null,
},
- }),
- // given traces and observations live in ClickHouse we cannot enforce a fk relationship and onDelete: setNull
- prisma.jobExecution.updateMany({
- where: {
- jobInputTraceId: {
- in: traceIds,
- },
- projectId: projectId,
- },
- data: {
- jobInputTraceId: {
- set: null,
- },
- jobInputObservationId: {
- set: null,
- },
- },
- }),
- ]);
+ },
+ });
} catch (e) {
logger.error(
`Error deleting trace ${JSON.stringify(traceIds)} in project ${projectId} from Postgres`,
diff --git a/worker/src/queues/projectDelete.ts b/worker/src/queues/projectDelete.ts
index 715cb70d0c..1e258a13f3 100644
--- a/worker/src/queues/projectDelete.ts
+++ b/worker/src/queues/projectDelete.ts
@@ -100,26 +100,6 @@ export const projectDeleteProcessor: Processor = async (
deleteEventLogByProjectId(projectId),
]);
- // Try to delete traces, observations, and scores from Prisma individually
- // as those will take the longest time and might kill a transaction
- await Promise.all([
- prisma.trace.deleteMany({
- where: {
- projectId,
- },
- }),
- prisma.observation.deleteMany({
- where: {
- projectId,
- },
- }),
- prisma.score.deleteMany({
- where: {
- projectId,
- },
- }),
- ]);
-
// Finally, delete the project itself which should delete all related
// resources due to the referential actions defined via Prisma
try {
diff --git a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
index 1511b84a46..0acbbf2e28 100644
--- a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
+++ b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
@@ -1115,54 +1115,6 @@ describe("Ingestion end-to-end tests", () => {
expect(trace.project_id).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
});
- it("should upsert traces from event and postgres in right order", async () => {
- const traceId = randomUUID();
-
- const latestEvent = new Date();
- const oldEvent = new Date(latestEvent).setSeconds(
- latestEvent.getSeconds() - 1,
- );
-
- await prisma.trace.create({
- data: {
- id: traceId,
- name: "trace-name",
- userId: "user-2",
- projectId,
- timestamp: new Date(oldEvent),
- },
- });
-
- const traceEventList: TraceEventType[] = [
- {
- id: randomUUID(),
- type: "trace-create",
- timestamp: latestEvent.toISOString(),
- body: {
- id: traceId,
- timestamp: latestEvent.toISOString(),
- name: "trace-name",
- userId: "user-1",
- },
- },
- ];
-
- await ingestionService.processTraceEventList({
- projectId,
- entityId: traceId,
- createdAtTimestamp: new Date(),
- traceEventList,
- });
-
- await clickhouseWriter.flushAll(true);
-
- const trace = await getClickhouseRecord(TableName.Traces, traceId);
-
- expect(trace.name).toBe("trace-name");
- expect(trace.user_id).toBe("user-1");
- expect(trace.project_id).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
- });
-
it("should merge observations and set negative tokens and cost to null", async () => {
await prisma.model.create({
data: {
@@ -1200,29 +1152,6 @@ describe("Ingestion end-to-end tests", () => {
},
});
- await prisma.observation.create({
- data: {
- id: "c8d30f61-4097-407f-a337-5fb1e0c100f2",
- name: "extract_location",
- startTime: "2024-11-04T16:13:51.495868Z",
- endTime: "2024-11-04T16:13:52.156248Z",
- type: "GENERATION",
- traceId: "82c480bc-1c4e-4ba8-a153-0bd9f9e1a28e",
- internalModel: "gpt-4o-mini-2024-07-18",
- internalModelId: "clyrjpbe20000t0mzcbwc42rg",
- modelParameters: {
- temperature: "0.4",
- max_tokens: 1000,
- },
- input: "Sample input",
- output: "Sample output",
- projectId,
- completionTokens: -7,
- promptTokens: 4,
- totalTokens: -3,
- },
- });
-
const observationId = "c8d30f61-4097-407f-a337-5fb1e0c100f2";
const observationEventList: ObservationEvent[] = [
{
@@ -1337,32 +1266,6 @@ describe("Ingestion end-to-end tests", () => {
},
});
- await prisma.observation.create({
- data: {
- id: "c8d30f61-4097-407f-a337-5fb1e0c100f2",
- name: "extract_location",
- startTime: "2024-11-04T16:13:51.495868Z",
- endTime: "2024-11-04T16:13:52.156248Z",
- type: "GENERATION",
- traceId: "82c480bc-1c4e-4ba8-a153-0bd9f9e1a28e",
- internalModel: "gpt-4o-mini-2024-07-18",
- internalModelId: "clyrjpbe20000t0mzcbwc42rg",
- modelParameters: {
- temperature: "0.4",
- max_tokens: 1000,
- },
- input: "Sample input",
- output: "Sample output",
- projectId,
- completionTokens: 18,
- promptTokens: 1295,
- totalTokens: 1313,
- calculatedInputCost: 0.00019425,
- calculatedOutputCost: 0.0000108,
- calculatedTotalCost: 0.00020505,
- },
- });
-
const observationId = "c8d30f61-4097-407f-a337-5fb1e0c100f2";
const observationEventList: ObservationEvent[] = [
{
diff --git a/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts b/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts
index 6ea88a680f..a071e4a06e 100644
--- a/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts
+++ b/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts
@@ -1,8 +1,8 @@
import Decimal from "decimal.js";
import { v4 as uuidv4 } from "uuid";
-import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
-import { ModelUsageUnit, Price } from "@langfuse/shared";
+import { Price } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import { pruneDatabase } from "../../../__tests__/utils";
@@ -81,12 +81,6 @@ describe("Token Cost Calculation", () => {
price: price.price,
})),
}),
- prisma.trace.create({
- data: {
- id: traceId,
- projectId,
- },
- }),
]);
vi.clearAllMocks();
});