🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(scores): support session level scores (#6367)
marliessophie0f06a066df46
diff --git a/fern/apis/client/definition/score.yml b/fern/apis/client/definition/score.ymlindex 12b1a632dd..1d62dc9606 100644--- a/fern/apis/client/definition/score.yml+++ b/fern/apis/client/definition/score.yml@@ -14,12 +14,13 @@ types:CreateScoreRequest:properties:id: optional<string>- traceId: string+ traceId: optional<string>+ sessionId: optional<string>+ observationId: optional<string>name: stringvalue:type: CreateScoreValuedocs: The value of the score. Must be passed as string for categorical scores, and numeric for boolean and numeric scores. Boolean score values must equal either 1 or 0 (true or false)- observationId: optional<string>comment: optional<string>metadata: optional<unknown>dataType:@@ -65,6 +66,10 @@ types:dataType: "BOOLEAN"configId: "1234-5678-90ab-cdef"traceId: "cdef-1234-5678-90ab"+ - value:+ name: "contextrelevant"+ value: "not relevant"+ sessionId: "abyt-1234-5678-80ab"BaseScore:properties:id: string@@ -105,6 +110,7 @@ types:stringValue:type: stringdocs: The string representation of the score value. If no config is linked, can be any string. Otherwise, must map to a config category+ # Question: where is this used, if not needed remove BaseScore tooScore:discriminant: "dataType"union:diff --git a/fern/apis/server/definition/commons.yml b/fern/apis/server/definition/commons.ymlindex f38a7be019..c99b6c5b13 100644--- a/fern/apis/server/definition/commons.yml+++ b/fern/apis/server/definition/commons.yml@@ -75,7 +75,7 @@ types:type: list<ObservationsView>docs: List of observationsscores:- type: list<Score>+ type: list<ScoreV1>docs: List of scoresSession:properties:@@ -240,7 +240,7 @@ types:properties:value: doublelabel: string- BaseScore:+ BaseScoreV1:properties:id: stringtraceId: string@@ -262,6 +262,66 @@ types:environment:type: optional<string>docs: The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.+ NumericScoreV1:+ extends: BaseScoreV1+ properties:+ value:+ type: double+ docs: The numeric value of the score+ BooleanScoreV1:+ extends: BaseScoreV1+ properties:+ value:+ type: double+ docs: The numeric value of the score. Equals 1 for "True" and 0 for "False"+ stringValue:+ type: string+ docs: The string representation of the score value. Is inferred from the numeric value and equals "True" or "False"+ CategoricalScoreV1:+ extends: BaseScoreV1+ properties:+ value:+ type: optional<double>+ docs: Only defined if a config is linked. Represents the numeric category mapping of the stringValue+ stringValue:+ type: string+ docs: The string representation of the score value. If no config is linked, can be any string. Otherwise, must map to a config category+ ScoreV1:+ discriminant: "dataType"+ union:+ NUMERIC:+ type: NumericScoreV1+ docs: "Score with NUMERIC data type"+ CATEGORICAL:+ type: CategoricalScoreV1+ docs: "Score with CATEGORICAL data type"+ BOOLEAN:+ type: BooleanScoreV1+ docs: "Score with BOOLEAN data type"++ BaseScore:+ properties:+ id: string+ traceId: optional<string>+ sessionId: optional<string>+ observationId: optional<string>+ name: string+ source: ScoreSource+ timestamp: datetime+ createdAt: datetime+ updatedAt: datetime+ authorUserId: optional<string>+ comment: optional<string>+ metadata: optional<unknown>+ configId:+ type: optional<string>+ docs: Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range+ queueId:+ type: optional<string>+ docs: Reference an annotation queue on a score. Populated if the score was initially created in an annotation queue.+ environment:+ type: optional<string>+ docs: The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.NumericScore:extends: BaseScoreproperties:diff --git a/fern/apis/server/definition/ingestion.yml b/fern/apis/server/definition/ingestion.ymlindex 0d7832674f..2864b9c23a 100644--- a/fern/apis/server/definition/ingestion.yml+++ b/fern/apis/server/definition/ingestion.yml@@ -263,13 +263,14 @@ types:ScoreBody:properties:id: optional<string>- traceId: string+ traceId: optional<string>+ sessionId: optional<string>+ observationId: optional<string>name: stringenvironment: optional<string>value:type: commons.CreateScoreValuedocs: The value of the score. Must be passed as string for categorical scores, and numeric for boolean and numeric scores. Boolean score values must equal either 1 or 0 (true or false)- observationId: optional<string>comment: optional<string>metadata: optional<unknown>dataType:@@ -315,6 +316,10 @@ types:dataType: "BOOLEAN"configId: "1234-5678-90ab-cdef"traceId: "cdef-1234-5678-90ab"+ - value:+ name: "contextrelevant"+ value: "not relevant"+ sessionId: "abyt-1234-5678-80ab"BaseEvent:properties:diff --git a/fern/apis/server/definition/score-v2.yml b/fern/apis/server/definition/score-v2.ymlnew file mode 100644index 0000000000..8863faf6fb--- /dev/null+++ b/fern/apis/server/definition/score-v2.yml@@ -0,0 +1,112 @@+# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json+imports:+ pagination: ./utils/pagination.yml+ commons: ./commons.yml+service:+ auth: true+ base-path: /api/public/v2+ endpoints:+ get:+ docs: Get a list of scores (supports both trace and session scores)+ method: GET+ path: /scores+ request:+ name: GetScoresRequest+ query-parameters:+ page:+ type: optional<integer>+ docs: Page number, starts at 1.+ limit:+ type: optional<integer>+ docs: Limit of items per page. If you encounter api issues due to too large page sizes, try to reduce the limit.+ userId:+ type: optional<string>+ docs: Retrieve only scores with this userId associated to the trace.+ name:+ type: optional<string>+ docs: Retrieve only scores with this name.+ fromTimestamp:+ type: optional<datetime>+ docs: Optional filter to only include scores created on or after a certain datetime (ISO 8601)+ toTimestamp:+ type: optional<datetime>+ docs: Optional filter to only include scores created before a certain datetime (ISO 8601)+ environment:+ type: optional<string>+ allow-multiple: true+ docs: Optional filter for scores where the environment is one of the provided values.+ source:+ type: optional<commons.ScoreSource>+ docs: Retrieve only scores from a specific source.+ operator:+ type: optional<string>+ docs: Retrieve only scores with <operator> value.+ value:+ type: optional<double>+ docs: Retrieve only scores with <operator> value.+ scoreIds:+ type: optional<string>+ docs: Comma-separated list of score IDs to limit the results to.+ configId:+ type: optional<string>+ docs: Retrieve only scores with a specific configId.+ queueId:+ type: optional<string>+ docs: Retrieve only scores with a specific annotation queueId.+ dataType:+ type: optional<commons.ScoreDataType>+ docs: Retrieve only scores with a specific dataType.+ traceTags:+ type: optional<string>+ allow-multiple: true+ docs: Only scores linked to traces that include all of these tags will be returned.+ response: GetScoresResponse+ get-by-id:+ docs: Get a score (supports both trace and session scores)+ method: GET+ path: /scores/{scoreId}+ path-parameters:+ scoreId:+ type: string+ docs: The unique langfuse identifier of a score+ response: commons.Score++types:+ GetScoresResponseTraceData:+ properties:+ userId:+ type: optional<string>+ docs: The user ID associated with the trace referenced by score+ tags:+ type: optional<list<string>>+ docs: A list of tags associated with the trace referenced by score+ environment:+ type: optional<string>+ docs: The environment of the trace referenced by score++ GetScoresResponseDataNumeric:+ extends: commons.NumericScore+ properties:+ trace: optional<GetScoresResponseTraceData>++ GetScoresResponseDataCategorical:+ extends: commons.CategoricalScore+ properties:+ trace: optional<GetScoresResponseTraceData>++ GetScoresResponseDataBoolean:+ extends: commons.BooleanScore+ properties:+ trace: optional<GetScoresResponseTraceData>++ GetScoresResponseData:+ discriminant: dataType+ union:+ NUMERIC: GetScoresResponseDataNumeric+ CATEGORICAL: GetScoresResponseDataCategorical+ BOOLEAN: GetScoresResponseDataBoolean++ GetScoresResponse:+ properties:+ data: list<GetScoresResponseData>+ meta: pagination.MetaResponsediff --git a/fern/apis/server/definition/score.yml b/fern/apis/server/definition/score.ymlindex 0ddcce3703..5c494e26d5 100644--- a/fern/apis/server/definition/score.yml+++ b/fern/apis/server/definition/score.yml@@ -7,77 +7,13 @@ service:base-path: /api/publicendpoints:create:- docs: Create a score+ docs: Create a score (supports both trace and session scores)method: POSTpath: /scoresrequest: CreateScoreRequestresponse: CreateScoreResponse- get:- docs: Get a list of scores- method: GET- path: /scores- request:- name: GetScoresRequest- query-parameters:- page:- type: optional<integer>- docs: Page number, starts at 1.- limit:- type: optional<integer>- docs: Limit of items per page. If you encounter api issues due to too large page sizes, try to reduce the limit.- userId:- type: optional<string>- docs: Retrieve only scores with this userId associated to the trace.- name:- type: optional<string>- docs: Retrieve only scores with this name.- fromTimestamp:- type: optional<datetime>- docs: Optional filter to only include scores created on or after a certain datetime (ISO 8601)- toTimestamp:- type: optional<datetime>- docs: Optional filter to only include scores created before a certain datetime (ISO 8601)- environment:- type: optional<string>- allow-multiple: true- docs: Optional filter for scores where the environment is one of the provided values.- source:- type: optional<commons.ScoreSource>- docs: Retrieve only scores from a specific source.- operator:- type: optional<string>- docs: Retrieve only scores with <operator> value.- value:- type: optional<double>- docs: Retrieve only scores with <operator> value.- scoreIds:- type: optional<string>- docs: Comma-separated list of score IDs to limit the results to.- configId:- type: optional<string>- docs: Retrieve only scores with a specific configId.- queueId:- type: optional<string>- docs: Retrieve only scores with a specific annotation queueId.- dataType:- type: optional<commons.ScoreDataType>- docs: Retrieve only scores with a specific dataType.- traceTags:- type: optional<string>- allow-multiple: true- docs: Only scores linked to traces that include all of these tags will be returned.- response: GetScoresResponse- get-by-id:- docs: Get a score- method: GET- path: /scores/{scoreId}- path-parameters:- scoreId:- type: string- docs: The unique langfuse identifier of a score- response: commons.Scoredelete:- docs: Delete a score+ docs: Delete a score (supports both trace and session scores)method: DELETEpath: /scores/{scoreId}path-parameters:@@ -88,12 +24,13 @@ types:CreateScoreRequest:properties:id: optional<string>- traceId: string+ traceId: optional<string>+ sessionId: optional<string>+ observationId: optional<string>name: stringvalue:type: commons.CreateScoreValuedocs: The value of the score. Must be passed as string for categorical scores, and numeric for boolean and numeric scores. Boolean score values must equal either 1 or 0 (true or false)- observationId: optional<string>comment: optional<string>metadata: optional<unknown>environment:@@ -149,41 +86,3 @@ types:id:type: stringdocs: The id of the created object in Langfuse- GetScoresResponseTraceData:- properties:- userId:- type: optional<string>- docs: The user ID associated with the trace referenced by score- tags:- type: optional<list<string>>- docs: A list of tags associated with the trace referenced by score- environment:- type: optional<string>- docs: The environment of the trace referenced by score-- GetScoresResponseDataNumeric:- extends: commons.NumericScore- properties:- trace: GetScoresResponseTraceData-- GetScoresResponseDataCategorical:- extends: commons.CategoricalScore- properties:- trace: GetScoresResponseTraceData-- GetScoresResponseDataBoolean:- extends: commons.BooleanScore- properties:- trace: GetScoresResponseTraceData-- GetScoresResponseData:- discriminant: dataType- union:- NUMERIC: GetScoresResponseDataNumeric- CATEGORICAL: GetScoresResponseDataCategorical- BOOLEAN: GetScoresResponseDataBoolean-- GetScoresResponse:- properties:- data: list<GetScoresResponseData>- meta: pagination.MetaResponsediff --git a/packages/shared/clickhouse/migrations/clustered/0012_add_session_id_column_scores.down.sql b/packages/shared/clickhouse/migrations/clustered/0012_add_session_id_column_scores.down.sqlnew file mode 100644index 0000000000..2b8ef556f4--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0012_add_session_id_column_scores.down.sql@@ -0,0 +1 @@+ALTER TABLE scores ON CLUSTER default DROP COLUMN IF EXISTS session_id SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/clustered/0012_add_session_id_column_scores.up.sql b/packages/shared/clickhouse/migrations/clustered/0012_add_session_id_column_scores.up.sqlnew file mode 100644index 0000000000..7837f8bdfb--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0012_add_session_id_column_scores.up.sql@@ -0,0 +1 @@+ALTER TABLE scores ON CLUSTER default ADD COLUMN session_id Nullable(String) AFTER trace_id SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/clustered/0013_drop_scores_trace_id_index.down.sql b/packages/shared/clickhouse/migrations/clustered/0013_drop_scores_trace_id_index.down.sqlnew file mode 100644index 0000000000..ccce41843e--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0013_drop_scores_trace_id_index.down.sql@@ -0,0 +1,2 @@+ALTER TABLE scores ON CLUSTER default ADD INDEX IF NOT EXISTS idx_project_trace_observation (project_id, trace_id, observation_id) TYPE bloom_filter(0.001) GRANULARITY 1 SETTINGS mutations_sync = 2;+ALTER TABLE scores ON CLUSTER default MATERIALIZE INDEX IF EXISTS idx_project_trace_observation SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/clustered/0013_drop_scores_trace_id_index.up.sql b/packages/shared/clickhouse/migrations/clustered/0013_drop_scores_trace_id_index.up.sqlnew file mode 100644index 0000000000..8a8bb8becd--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0013_drop_scores_trace_id_index.up.sql@@ -0,0 +1,2 @@+ALTER TABLE scores ON CLUSTER default DROP INDEX IF EXISTS idx_project_trace_observation SETTINGS mutations_sync = 2;+diff --git a/packages/shared/clickhouse/migrations/clustered/0014_scores_modify_nullable_trace_id_column.down.sql b/packages/shared/clickhouse/migrations/clustered/0014_scores_modify_nullable_trace_id_column.down.sqlnew file mode 100644index 0000000000..954e58dead--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0014_scores_modify_nullable_trace_id_column.down.sql@@ -0,0 +1 @@+ALTER TABLE scores ON CLUSTER default MODIFY COLUMN trace_id Nullable(String) SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/clustered/0014_scores_modify_nullable_trace_id_column.up.sql b/packages/shared/clickhouse/migrations/clustered/0014_scores_modify_nullable_trace_id_column.up.sqlnew file mode 100644index 0000000000..954e58dead--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0014_scores_modify_nullable_trace_id_column.up.sql@@ -0,0 +1 @@+ALTER TABLE scores ON CLUSTER default MODIFY COLUMN trace_id Nullable(String) SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/clustered/0015_add_scores_trace_index.down.sql b/packages/shared/clickhouse/migrations/clustered/0015_add_scores_trace_index.down.sqlnew file mode 100644index 0000000000..bd86b182c3--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0015_add_scores_trace_index.down.sql@@ -0,0 +1 @@+ALTER TABLE scores ON CLUSTER default DROP INDEX IF EXISTS idx_project_trace_observation SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/clustered/0015_add_scores_trace_index.up.sql b/packages/shared/clickhouse/migrations/clustered/0015_add_scores_trace_index.up.sqlnew file mode 100644index 0000000000..ccce41843e--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0015_add_scores_trace_index.up.sql@@ -0,0 +1,2 @@+ALTER TABLE scores ON CLUSTER default ADD INDEX IF NOT EXISTS idx_project_trace_observation (project_id, trace_id, observation_id) TYPE bloom_filter(0.001) GRANULARITY 1 SETTINGS mutations_sync = 2;+ALTER TABLE scores ON CLUSTER default MATERIALIZE INDEX IF EXISTS idx_project_trace_observation SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/clustered/0016_add_scores_session_index.down.sql b/packages/shared/clickhouse/migrations/clustered/0016_add_scores_session_index.down.sqlnew file mode 100644index 0000000000..abba171aad--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0016_add_scores_session_index.down.sql@@ -0,0 +1 @@+ALTER TABLE scores ON CLUSTER default DROP INDEX IF EXISTS idx_project_session SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/clustered/0016_add_scores_session_index.up.sql b/packages/shared/clickhouse/migrations/clustered/0016_add_scores_session_index.up.sqlnew file mode 100644index 0000000000..1e4fe8aa74--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0016_add_scores_session_index.up.sql@@ -0,0 +1,2 @@+ALTER TABLE scores ON CLUSTER default ADD INDEX IF NOT EXISTS idx_project_session (project_id, session_id) TYPE bloom_filter(0.001) GRANULARITY 1 SETTINGS mutations_sync = 2;+ALTER TABLE scores ON CLUSTER default MATERIALIZE INDEX IF EXISTS idx_project_session SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/unclustered/0012_add_session_id_column_scores.down.sql b/packages/shared/clickhouse/migrations/unclustered/0012_add_session_id_column_scores.down.sqlnew file mode 100644index 0000000000..1967d45f8b--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0012_add_session_id_column_scores.down.sql@@ -0,0 +1 @@+ALTER TABLE scores DROP COLUMN IF EXISTS session_id SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/unclustered/0012_add_session_id_column_scores.up.sql b/packages/shared/clickhouse/migrations/unclustered/0012_add_session_id_column_scores.up.sqlnew file mode 100644index 0000000000..3c8c9098c5--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0012_add_session_id_column_scores.up.sql@@ -0,0 +1 @@+ALTER TABLE scores ADD COLUMN session_id Nullable(String) AFTER trace_id SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/unclustered/0013_drop_scores_trace_id_index.down.sql b/packages/shared/clickhouse/migrations/unclustered/0013_drop_scores_trace_id_index.down.sqlnew file mode 100644index 0000000000..a5fb46bf03--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0013_drop_scores_trace_id_index.down.sql@@ -0,0 +1,2 @@+ALTER TABLE scores ADD INDEX IF NOT EXISTS idx_project_trace_observation (project_id, trace_id, observation_id) TYPE bloom_filter(0.001) GRANULARITY 1 SETTINGS mutations_sync = 2;+ALTER TABLE scores MATERIALIZE INDEX IF EXISTS idx_project_trace_observation SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/unclustered/0013_drop_scores_trace_id_index.up.sql b/packages/shared/clickhouse/migrations/unclustered/0013_drop_scores_trace_id_index.up.sqlnew file mode 100644index 0000000000..eeb81267d8--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0013_drop_scores_trace_id_index.up.sql@@ -0,0 +1,2 @@+ALTER TABLE scores DROP INDEX IF EXISTS idx_project_trace_observation SETTINGS mutations_sync = 2;+diff --git a/packages/shared/clickhouse/migrations/unclustered/0014_scores_modify_nullable_trace_id_column.down.sql b/packages/shared/clickhouse/migrations/unclustered/0014_scores_modify_nullable_trace_id_column.down.sqlnew file mode 100644index 0000000000..5938637ec5--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0014_scores_modify_nullable_trace_id_column.down.sql@@ -0,0 +1 @@+ALTER TABLE scores MODIFY COLUMN trace_id Nullable(String) SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/unclustered/0014_scores_modify_nullable_trace_id_column.up.sql b/packages/shared/clickhouse/migrations/unclustered/0014_scores_modify_nullable_trace_id_column.up.sqlnew file mode 100644index 0000000000..5938637ec5--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0014_scores_modify_nullable_trace_id_column.up.sql@@ -0,0 +1 @@+ALTER TABLE scores MODIFY COLUMN trace_id Nullable(String) SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/unclustered/0015_add_scores_trace_index.down.sql b/packages/shared/clickhouse/migrations/unclustered/0015_add_scores_trace_index.down.sqlnew file mode 100644index 0000000000..fd7ba11787--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0015_add_scores_trace_index.down.sql@@ -0,0 +1 @@+ALTER TABLE scores DROP INDEX IF EXISTS idx_project_trace_observation SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/unclustered/0015_add_scores_trace_index.up.sql b/packages/shared/clickhouse/migrations/unclustered/0015_add_scores_trace_index.up.sqlnew file mode 100644index 0000000000..3cb554b4b7--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0015_add_scores_trace_index.up.sql@@ -0,0 +1,2 @@+ALTER TABLE scores ADD INDEX IF NOT EXISTS idx_project_trace_observation (project_id, trace_id, observation_id) TYPE bloom_filter(0.001) GRANULARITY 1 SETTINGS mutations_sync = 2;+ALTER TABLE scores MATERIALIZE INDEX IF EXISTS idx_project_trace_observation SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/unclustered/0016_add_scores_session_index.down.sql b/packages/shared/clickhouse/migrations/unclustered/0016_add_scores_session_index.down.sqlnew file mode 100644index 0000000000..9f60ffbdd3--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0016_add_scores_session_index.down.sql@@ -0,0 +1 @@+ALTER TABLE scores DROP INDEX IF EXISTS idx_project_session SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/unclustered/0016_add_scores_session_index.up.sql b/packages/shared/clickhouse/migrations/unclustered/0016_add_scores_session_index.up.sqlnew file mode 100644index 0000000000..a0a39e9226--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0016_add_scores_session_index.up.sql@@ -0,0 +1,2 @@+ALTER TABLE scores ADD INDEX IF NOT EXISTS idx_project_session (project_id, session_id) TYPE bloom_filter(0.001) GRANULARITY 1 SETTINGS mutations_sync = 2;+ALTER TABLE scores MATERIALIZE INDEX IF EXISTS idx_project_session SETTINGS mutations_sync = 2;diff --git a/packages/shared/scripts/prepareClickhouse.ts b/packages/shared/scripts/prepareClickhouse.tsindex 4962b7f7a3..cf783ebc06 100644--- a/packages/shared/scripts/prepareClickhouse.ts+++ b/packages/shared/scripts/prepareClickhouse.ts@@ -141,8 +141,6 @@ export const prepareClickhouse = async (FROM numbers(${observationsPerProject});`;- console.log(observationsQuery);-const scoresQuery = `INSERT INTO scoresSELECT toString(number) AS id,@@ -150,6 +148,7 @@ export const prepareClickhouse = async ('${projectId}' AS project_id,'default' AS environment,toString(floor(randUniform(0, ${tracesPerProject}))) AS trace_id,+ NULL AS session_id,if(rand() > 0.9,toString(floor(randUniform(0, ${observationsPerProject}))),@@ -200,6 +199,47 @@ export const prepareClickhouse = async (project_id: string;}>();+ const sessionsToScore = sessionData+ .filter(() => Math.random() < 0.5)+ .slice(0, Math.min(500, sessionData.length));++ if (sessionsToScore.length > 0) {+ // Generate session scores query with specific session IDs+ const sessionScoresQuery = `+ INSERT INTO scores+ SELECT+ concat('session-', toString(number)) AS id,+ toDateTime(now() - randUniform(0, ${opts.numberOfDays} * 24 * 60 * 60)) AS timestamp,+ '${projectId}' AS project_id,+ 'default' AS environment,+ NULL AS trace_id,+ arrayElement(['${sessionsToScore.map((s) => s.session_id).join("','")}'], 1 + (number % ${sessionsToScore.length})) AS session_id,+ NULL AS observation_id,+ concat('session_quality_', toString(rand() % 10)) AS name,+ randUniform(0, 100) AS value,+ 'API' AS source,+ 'Session-level assessment score' AS comment,+ map('key', 'value') AS metadata,+ toString(rand() % 100) AS author_user_id,+ toString(rand() % 100) AS config_id,+ if(rand() < 0.33, 'NUMERIC', if(rand() < 0.5, 'CATEGORICAL', 'BOOLEAN')) AS data_type,+ toString(rand() % 100) AS string_value,+ NULL AS queue_id,+ timestamp AS created_at,+ timestamp AS updated_at,+ timestamp AS event_ts,+ 0 AS is_deleted+ FROM numbers(${sessionsToScore.length})+ `;++ await clickhouseClient().command({+ query: sessionScoresQuery,+ clickhouse_settings: {+ wait_end_of_query: 1,+ },+ });+ }+const idProjectIdCombinations = sessionData.map((session) => ({id: session.session_id,projectId: session.project_id,diff --git a/packages/shared/src/domain/scores.ts b/packages/shared/src/domain/scores.tsindex 15b54107d4..941de73e31 100644--- a/packages/shared/src/domain/scores.ts+++ b/packages/shared/src/domain/scores.ts@@ -21,8 +21,9 @@ export const ScoreSchema = z.object({source: ScoreSourceDomain,authorUserId: z.string().nullable(),comment: z.string().nullable(),+ traceId: z.string().nullable(),+ sessionId: z.string().nullable(),metadata: MetadataDomain,- traceId: z.string(),observationId: z.string().nullable(),configId: z.string().nullable(),stringValue: z.string().nullable(),diff --git a/packages/shared/src/features/annotation/types.ts b/packages/shared/src/features/annotation/types.tsindex 11e68a9220..0b8455900d 100644--- a/packages/shared/src/features/annotation/types.ts+++ b/packages/shared/src/features/annotation/types.ts@@ -25,13 +25,33 @@ const BooleanData = z.object({dataType: z.literal("BOOLEAN"),});+const ScoreTargetTrace = z.object({+ type: z.literal("trace"),+ traceId: z.string(),+ observationId: z.string().optional(),+});++const ScoreTargetSession = z.object({+ type: z.literal("session"),+ sessionId: z.string(),+});++// Your existing ScoreTarget remains the same, but can now use these components+const ScoreTarget = z.discriminatedUnion("type", [+ ScoreTargetTrace,+ ScoreTargetSession,+]);++export type ScoreTargetTrace = z.infer<typeof ScoreTargetTrace>;+export type ScoreTargetSession = z.infer<typeof ScoreTargetSession>;+export type ScoreTarget = z.infer<typeof ScoreTarget>;+const CreateAnnotationScoreBase = z.object({name: z.string(),projectId: z.string(),environment: z.string().default("default"),- traceId: z.string(),+ scoreTarget: ScoreTarget,configId: z.string().optional(),- observationId: z.string().optional(),comment: z.string().nullish(),queueId: z.string().nullish(),});diff --git a/packages/shared/src/features/scores/index.ts b/packages/shared/src/features/scores/index.tsindex fbcc893744..fd2059c3e1 100644--- a/packages/shared/src/features/scores/index.ts+++ b/packages/shared/src/features/scores/index.ts@@ -1,3 +1,2 @@-export * from "./scoreTypes";-export * from "./types";+export * from "./interfaces";export * from "./scoreConfigTypes";diff --git a/packages/shared/src/features/scores/interfaces/README.md b/packages/shared/src/features/scores/interfaces/README.mdnew file mode 100644index 0000000000..1c6f847381--- /dev/null+++ b/packages/shared/src/features/scores/interfaces/README.md@@ -0,0 +1,68 @@+# Score Interfaces++This directory contains all type definitions, schemas, and validation logic for Langfuse scores.++## Structure++```+interfaces/+├── api/ # API-specific schemas and validations+│ ├── v1/ # Legacy API types (trace-focused)+│ │ ├── endpoints.ts # Endpoint types and schemas+│ │ ├── schemas.ts # Type definitions+│ │ └── validation.ts # Validation logic+│ ├── v2/ # Current API types (supports traces, sessions)+│ │ ├── endpoints.ts # Endpoint types and schemas+│ │ ├── schemas.ts # Type definitions+│ │ └── validation.ts # Validation logic+│ └── shared.ts # Common schemas used across API versions+├── application/ # Internal application logic+│ └── validation.ts # Validation functions for application layers+├── ingestion/ # Types for data ingestion+│ └── validation.ts # Validation for ingestion endpoints+├── ui/ # Simplified types for UI components+│ └── types.ts # UI-specific type definitions+└── index.ts # Exports all interfaces+```++## API Versioning++We have added a new v2 api and will continue to support the v1 api for the foreseeable future.+POST and DELETE APIs will continue to support both trace and session level scores across v1 and v2.++For GET APIs:++- **V1 API**: Requires `traceId`, ONLY supports trace-level scores+- **V2 API**: Makes `traceId` optional, adds `sessionId` support, supports BOTH trace and session level scores+- Both versions maintain compatibility for existing clients++## Usage Guide++### When building API endpoints:++- **New endpoints**: Use types from `api/v2/schemas.ts`+- **Legacy compatibility**: Use types from `api/v1/schemas.ts`+- **Validation**: Use validators from the corresponding `validation.ts` files++### When building UI components:++Use the simplified types from `ui/types.ts` which are optimized for frontend use:++```typescript+import { ScoreSimplified, LastUserScore } from "../interfaces/ui/types";+```++### When working with internal application logic:++Use the validation functions from `application/validation.ts`:++```typescript+import {+ validateDbScore,+ filterAndValidateDbScoreList,+} from "../interfaces/application/validation";+```++## Type Flow++Client → `PostScoresBody` → Validation → Database → `ScoreDomain` → API response (`APIScoreV2`) → UI (`ScoreSimplified` or `LastUserScore`)diff --git a/packages/shared/src/features/scores/interfaces/api/index.ts b/packages/shared/src/features/scores/interfaces/api/index.tsnew file mode 100644index 0000000000..1218100135--- /dev/null+++ b/packages/shared/src/features/scores/interfaces/api/index.ts@@ -0,0 +1,6 @@+export * from "./v1/schemas";+export * from "./v1/validation";+export * from "./v1/endpoints";+export * from "./v2/schemas";+export * from "./v2/validation";+export * from "./v2/endpoints";diff --git a/packages/shared/src/features/scores/interfaces/api/shared.ts b/packages/shared/src/features/scores/interfaces/api/shared.tsnew file mode 100644index 0000000000..16405cc9d6--- /dev/null+++ b/packages/shared/src/features/scores/interfaces/api/shared.ts@@ -0,0 +1,139 @@+import { z } from "zod";+import { jsonSchema, publicApiPaginationZod } from "../../../../utils/zod";+import { stringDateTime } from "../../../../utils/typeChecks";+import { applyScoreValidation } from "../../../../utils/scores";+import { PostScoreBodyFoundationSchema } from "../shared";++const operators = ["<", ">", "<=", ">=", "!=", "="] as const;+const ScoreDataType = ["NUMERIC", "CATEGORICAL", "BOOLEAN"] as const;+const ScoreSource = ["API", "EVAL", "ANNOTATION"] as const;++/**+ * Objects+ */+export const NumericData = z.object({+ value: z.number(),+ stringValue: z.undefined().nullish(),+ dataType: z.literal("NUMERIC"),+});++export const CategoricalData = z.object({+ value: z.number().nullish(),+ stringValue: z.string(),+ dataType: z.literal("CATEGORICAL"),+});++export const BooleanData = z.object({+ value: z.number(),+ stringValue: z.string(),+ dataType: z.literal("BOOLEAN"),+});++/**+ * Foundation schema for all score types, needs to be extended with entity score may be associated with. Note there are two API versions, where v1 allows only trace and observation scores, while v2 additionally allows session scores+ * @see {@link ScoreFoundationSchemaV1}, {@link ScoreFoundationSchemaV2}+ *+ * Must also be extended with score data specific schema (numeric, categorical, boolean)+ * @see {@link NumericData}, {@link CategoricalData}, {@link BooleanData}+ */+export const ScoreFoundationSchema = z.object({+ id: z.string(),+ timestamp: z.coerce.date(),+ projectId: z.string(),+ environment: z.string().default("default"),+ name: z.string(),+ source: z.enum(ScoreSource),+ authorUserId: z.string().nullish(),+ comment: z.string().nullish(),+ metadata: jsonSchema.nullish(),+ configId: z.string().nullish(),+ createdAt: z.coerce.date(),+ updatedAt: z.coerce.date(),+ queueId: z.string().nullish(),+});++/**+ * Endpoints+ */++// GET /scores/{scoreId}+export const GetScoreQuery = z.object({+ scoreId: z.string(),+});++// GET /scores+export const GetScoresQuery = z.object({+ ...publicApiPaginationZod,+ userId: z.string().nullish(),+ dataType: z.enum(ScoreDataType).nullish(),+ configId: z.string().nullish(),+ queueId: z.string().nullish(),+ traceTags: z.union([z.array(z.string()), z.string()]).nullish(),+ environment: z.union([z.array(z.string()), z.string()]).nullish(),+ name: z.string().nullish(),+ fromTimestamp: stringDateTime,+ toTimestamp: stringDateTime,+ source: z.enum(ScoreSource).nullish(),+ value: z.coerce.number().nullish(),+ operator: z.enum(operators).nullish(),+ scoreIds: z+ .string()+ .transform((str) => str.split(",").map((id) => id.trim())) // Split the comma-separated string+ .refine((arr) => arr.every((id) => typeof id === "string"), {+ message: "Each score ID must be a string",+ })+ .nullish(),+});++// POST /scores+// Please note that the POST /scores endpoint supports both trace and session level scores across v1 and v2.+/**+ * PostScoresBody is copied for the ingestion API as `ScoreBody`. Please copy any changes here in `packages/shared/src/features/ingestion/types.ts`+ */+export const PostScoresBody = applyScoreValidation(+ z.discriminatedUnion("dataType", [+ PostScoreBodyFoundationSchema.merge(+ z.object({+ value: z.number(),+ dataType: z.literal("NUMERIC"),+ configId: z.string().nullish(),+ }),+ ),+ PostScoreBodyFoundationSchema.merge(+ z.object({+ value: z.string(),+ dataType: z.literal("CATEGORICAL"),+ configId: z.string().nullish(),+ }),+ ),+ PostScoreBodyFoundationSchema.merge(+ z.object({+ value: z.number().refine((value) => value === 0 || value === 1, {+ message:+ "Value must be a number equal to either 0 or 1 for data type BOOLEAN",+ }),+ dataType: z.literal("BOOLEAN"),+ configId: z.string().nullish(),+ }),+ ),+ PostScoreBodyFoundationSchema.merge(+ z.object({+ value: z.union([z.string(), z.number()]),+ dataType: z.undefined(),+ configId: z.string().nullish(),+ }),+ ),+ ]),+);++export const PostScoresResponse = z.object({ id: z.string() });++// DELETE /scores/{scoreId}+// Please note that the DELETE /scores/{scoreId} endpoint supports both trace and session level scores across v1 and v2.+export const DeleteScoreQuery = z.object({+ scoreId: z.string(),+});++export const DeleteScoreResponse = z.object({+ message: z.string(),+});diff --git a/packages/shared/src/features/scores/interfaces/api/v1/endpoints.ts b/packages/shared/src/features/scores/interfaces/api/v1/endpoints.tsnew file mode 100644index 0000000000..a1c4ccf6ee--- /dev/null+++ b/packages/shared/src/features/scores/interfaces/api/v1/endpoints.ts@@ -0,0 +1,44 @@+import { z } from "zod";+import { paginationMetaResponseZod } from "../../../../../utils/zod";+import {+ DeleteScoreQuery,+ DeleteScoreResponse,+ GetScoreQuery,+ GetScoresQuery,+ PostScoresBody,+ PostScoresResponse,+} from "../shared";+import { APIScoreSchemaV1 } from "./schemas";++// GET /scores/{scoreId}+export const GetScoreQueryV1 = GetScoreQuery;+export const GetScoreResponseV1 = APIScoreSchemaV1;++// DELETE /scores/{scoreId}+export const DeleteScoreQueryV1 = DeleteScoreQuery;+export const DeleteScoreResponseV1 = DeleteScoreResponse;++// GET /scores+export const GetScoresQueryV1 = GetScoresQuery;++// GetScoreResponseDataV1 is only used for response of GET /scores list endpoint+export const GetScoreResponseDataV1 = z.intersection(+ APIScoreSchemaV1,+ z.object({+ trace: z.object({+ userId: z.string().nullish(),+ tags: z.array(z.string()).nullish(),+ environment: z.string().nullish(),+ }),+ }),+);++export const GetScoresResponseV1 = z.object({+ data: z.array(GetScoreResponseDataV1),+ meta: paginationMetaResponseZod,+});++// POST /scores+export const PostScoresBodyV1 = PostScoresBody;++export const PostScoresResponseV1 = PostScoresResponse;diff --git a/packages/shared/src/features/scores/interfaces/api/v1/schemas.ts b/packages/shared/src/features/scores/interfaces/api/v1/schemas.tsnew file mode 100644index 0000000000..68d0de376a--- /dev/null+++ b/packages/shared/src/features/scores/interfaces/api/v1/schemas.ts@@ -0,0 +1,26 @@+import { z } from "zod";+import {+ CategoricalData,+ NumericData,+ BooleanData,+ ScoreFoundationSchema,+} from "../shared";++/**+ * Foundation schema for scores API v1 i.e. trace and observation scores ONLY+ *+ * Must be extended with score data specific schema (numeric, categorical, boolean)+ * @see {@link NumericData}, {@link CategoricalData}, {@link BooleanData}+ */+const ScoreFoundationSchemaV1 = ScoreFoundationSchema.extend({+ traceId: z.string(),+ observationId: z.string().nullish(),+});++export const APIScoreSchemaV1 = z.discriminatedUnion("dataType", [+ ScoreFoundationSchemaV1.merge(NumericData),+ ScoreFoundationSchemaV1.merge(CategoricalData),+ ScoreFoundationSchemaV1.merge(BooleanData),+]);++export type APIScoreV1 = z.infer<typeof APIScoreSchemaV1>;diff --git a/packages/shared/src/features/scores/interfaces/api/v1/validation.ts b/packages/shared/src/features/scores/interfaces/api/v1/validation.tsnew file mode 100644index 0000000000..18c087d810--- /dev/null+++ b/packages/shared/src/features/scores/interfaces/api/v1/validation.ts@@ -0,0 +1,29 @@+import z from "zod";+import { GetScoreResponseDataV1 } from "./endpoints";++/**+ * @deprecated+ * Use `filterAndValidateV2GetScoreList` instead. This function is only used for the legacy v1 API where scores were only associated with traces.+ * Use this function when pulling a list of scores from the database before returning to the public API to ensure type safety.+ * All scores are expected to pass the validation. If a score fails validation, it will be logged to Otel.+ * @param scores+ * @returns list of validated scores with trace information+ */+export const filterAndValidateV1GetScoreList = (+ scores: unknown[],+ // eslint-disable-next-line no-unused-vars+ onParseError?: (error: z.ZodError) => void,+): z.infer<typeof GetScoreResponseDataV1>[] =>+ scores.reduce(+ (acc: z.infer<typeof GetScoreResponseDataV1>[], ts) => {+ const result = GetScoreResponseDataV1.safeParse(ts);+ if (result.success) {+ acc.push(result.data);+ } else {+ console.error(`Score parsing error ${JSON.stringify(result.error)}`);+ onParseError?.(result.error);+ }+ return acc;+ },+ [] as z.infer<typeof GetScoreResponseDataV1>[],+ );diff --git a/packages/shared/src/features/scores/interfaces/api/v2/endpoints.ts b/packages/shared/src/features/scores/interfaces/api/v2/endpoints.tsnew file mode 100644index 0000000000..920d42fc5e--- /dev/null+++ b/packages/shared/src/features/scores/interfaces/api/v2/endpoints.ts@@ -0,0 +1,28 @@+import z from "zod";+import { paginationMetaResponseZod } from "../../../../../utils/zod";+import { GetScoreQuery, GetScoresQuery } from "../shared";+import { APIScoreSchemaV2 } from "./schemas";++// GET /scores/{scoreId} v2+export const GetScoreQueryV2 = GetScoreQuery;+export const GetScoreResponseV2 = APIScoreSchemaV2;++// GET /scores v2+export const GetScoresQueryV2 = GetScoresQuery;+export const GetScoreResponseDataV2 = z.intersection(+ APIScoreSchemaV2,+ z.object({+ trace: z+ .object({+ userId: z.string().nullish(),+ tags: z.array(z.string()).nullish(),+ environment: z.string().nullish(),+ })+ .nullish(),+ }),+);++export const GetScoresResponseV2 = z.object({+ data: z.array(GetScoreResponseDataV2),+ meta: paginationMetaResponseZod,+});diff --git a/packages/shared/src/features/scores/interfaces/api/v2/schemas.ts b/packages/shared/src/features/scores/interfaces/api/v2/schemas.tsnew file mode 100644index 0000000000..8f1910bb84--- /dev/null+++ b/packages/shared/src/features/scores/interfaces/api/v2/schemas.ts@@ -0,0 +1,27 @@+import { z } from "zod";+import {+ CategoricalData,+ NumericData,+ BooleanData,+ ScoreFoundationSchema,+} from "../shared";++/**+ * Foundation schema for scores API v2 i.e. trace, observation AND session scores+ *+ * Must be extended with score data specific schema (numeric, categorical, boolean)+ * @see {@link NumericData}, {@link CategoricalData}, {@link BooleanData}+ */+const ScoreFoundationSchemaV2 = ScoreFoundationSchema.extend({+ traceId: z.string().nullish(),+ observationId: z.string().nullish(),+ sessionId: z.string().nullish(),+});++export const APIScoreSchemaV2 = z.discriminatedUnion("dataType", [+ ScoreFoundationSchemaV2.merge(NumericData),+ ScoreFoundationSchemaV2.merge(CategoricalData),+ ScoreFoundationSchemaV2.merge(BooleanData),+]);++export type APIScoreV2 = z.infer<typeof APIScoreSchemaV2>;diff --git a/packages/shared/src/features/scores/interfaces/api/v2/validation.ts b/packages/shared/src/features/scores/interfaces/api/v2/validation.tsnew file mode 100644index 0000000000..b6c37fc67d--- /dev/null+++ b/packages/shared/src/features/scores/interfaces/api/v2/validation.ts@@ -0,0 +1,27 @@+import z from "zod";+import { GetScoreResponseDataV2 } from "./endpoints";++/**+ * Use this function when pulling a list of scores from the database before returning to the public API to ensure type safety.+ * All scores are expected to pass the validation. If a score fails validation, it will be logged to Otel.+ * @param scores+ * @returns list of validated scores with optional trace information in case of trace scores+ */+export const filterAndValidateV2GetScoreList = (+ scores: unknown[],+ // eslint-disable-next-line no-unused-vars+ onParseError?: (error: z.ZodError) => void,+): z.infer<typeof GetScoreResponseDataV2>[] =>+ scores.reduce(+ (acc: z.infer<typeof GetScoreResponseDataV2>[], ts) => {+ const result = GetScoreResponseDataV2.safeParse(ts);+ if (result.success) {+ acc.push(result.data);+ } else {+ console.error("Score parsing error: ", result.error);+ onParseError?.(result.error);+ }+ return acc;+ },+ [] as z.infer<typeof GetScoreResponseDataV2>[],+ );diff --git a/packages/shared/src/features/scores/interfaces/application/validation.ts b/packages/shared/src/features/scores/interfaces/application/validation.tsnew file mode 100644index 0000000000..0ba499e743--- /dev/null+++ b/packages/shared/src/features/scores/interfaces/application/validation.ts@@ -0,0 +1,94 @@+import z from "zod";+import { APIScoreSchemaV2, APIScoreV2 } from "../api/v2/schemas";+import { APIScoreSchemaV1, APIScoreV1 } from "../api/v1/schemas";+import { ScoreDomain } from "../../../../domain";++type ValidatedAPIScore<IncludeHasMetadata extends boolean> = APIScoreV2 & {+ hasMetadata: IncludeHasMetadata extends true ? boolean : never;+};++type InputScore = ScoreDomain & { hasMetadata?: boolean };++/**+ * Use this function when pulling a single score from the database before using in the application to ensure type safety.+ * The score is expected to pass the validation. If a score fails validation, an error will be thrown.+ * @param score+ * @returns validated score+ * @throws error if score fails validation+ */+export const validateDbScore = (score: ScoreDomain): APIScoreV2 =>+ APIScoreSchemaV2.parse(score);++/**+ * Use this function when pulling a list of scores from the database before using in the application to ensure type safety.+ * All scores are expected to pass the validation. If a score fails validation, it will be logged to Otel.+ * @param scores+ * @returns list of validated scores+ */+export const filterAndValidateDbScoreList = <+ IncludeHasMetadata extends boolean,+>({+ scores,+ includeHasMetadata = false as IncludeHasMetadata,+ onParseError,+}: {+ scores: InputScore[];+ includeHasMetadata?: IncludeHasMetadata;+ // eslint-disable-next-line no-unused-vars+ onParseError?: (error: z.ZodError) => void;+}): ValidatedAPIScore<IncludeHasMetadata>[] => {+ return scores.reduce((acc, ts) => {+ const result = APIScoreSchemaV2.safeParse(ts);+ if (result.success) {+ const score = { ...result.data };+ if (includeHasMetadata) {+ Object.assign(score, { hasMetadata: ts.hasMetadata ?? false });+ }+ acc.push(score as ValidatedAPIScore<IncludeHasMetadata>);+ } else {+ console.error("Score parsing error: ", result.error);+ onParseError?.(result.error);+ }+ return acc;+ }, [] as ValidatedAPIScore<IncludeHasMetadata>[]);+};++type ValidatedAPITraceScore<IncludeHasMetadata extends boolean> = APIScoreV1 & {+ hasMetadata: IncludeHasMetadata extends true ? boolean : never;+};++/**+ * @deprecated+ * Use `filterAndValidateDbScoreList` instead. This function is only used for the legacy v1 API where scores were only associated with traces.+ * Use this function when pulling a list of scores from the database before using in the application to ensure type safety.+ * All scores are expected to pass the validation. If a score fails validation, it will be logged to Otel.+ * @param scores+ * @returns list of validated scores+ */+export const filterAndValidateDbTraceScoreList = <+ IncludeHasMetadata extends boolean,+>({+ scores,+ includeHasMetadata = false as IncludeHasMetadata,+ onParseError,+}: {+ scores: InputScore[];+ includeHasMetadata?: IncludeHasMetadata;+ // eslint-disable-next-line no-unused-vars+ onParseError?: (error: z.ZodError) => void;+}): ValidatedAPITraceScore<IncludeHasMetadata>[] => {+ return scores.reduce((acc, ts) => {+ const result = APIScoreSchemaV1.safeParse(ts);+ if (result.success) {+ const score = { ...result.data };+ if (includeHasMetadata) {+ Object.assign(score, { hasMetadata: ts.hasMetadata ?? false });+ }+ acc.push(score as ValidatedAPITraceScore<IncludeHasMetadata>);+ } else {+ console.error("Score parsing error: ", result.error);+ onParseError?.(result.error);+ }+ return acc;+ }, [] as ValidatedAPITraceScore<IncludeHasMetadata>[]);+};diff --git a/packages/shared/src/features/scores/interfaces/index.ts b/packages/shared/src/features/scores/interfaces/index.tsnew file mode 100644index 0000000000..64bb80d390--- /dev/null+++ b/packages/shared/src/features/scores/interfaces/index.ts@@ -0,0 +1,4 @@+export * from "./api";+export * from "./application/validation";+export * from "./ingestion/validation";+export * from "./ui/types";diff --git a/packages/shared/src/features/scores/interfaces/ingestion/validation.ts b/packages/shared/src/features/scores/interfaces/ingestion/validation.tsnew file mode 100644index 0000000000..15832efd77--- /dev/null+++ b/packages/shared/src/features/scores/interfaces/ingestion/validation.ts@@ -0,0 +1,78 @@+import z from "zod";+import { applyScoreValidation } from "../../../../utils/scores";+import { PostScoreBodyFoundationSchema } from "../shared";+import { isPresent } from "../../../../utils/typeChecks";+import { Category as ConfigCategory } from "../../scoreConfigTypes";++export const ScoreBodyWithoutConfig = applyScoreValidation(+ z.discriminatedUnion("dataType", [+ PostScoreBodyFoundationSchema.merge(+ z.object({+ value: z.number(),+ dataType: z.literal("NUMERIC"),+ }),+ ),+ PostScoreBodyFoundationSchema.merge(+ z.object({+ value: z.string(),+ dataType: z.literal("CATEGORICAL"),+ }),+ ),+ PostScoreBodyFoundationSchema.merge(+ z.object({+ value: z.number().refine((val) => val === 0 || val === 1, {+ message: "Value must be either 0 or 1",+ }),+ dataType: z.literal("BOOLEAN"),+ }),+ ),+ ]),+);++const ScorePropsAgainstConfigNumeric = z+ .object({+ value: z.number(),+ maxValue: z.number().optional(),+ minValue: z.number().optional(),+ dataType: z.literal("NUMERIC"),+ })+ .superRefine((data, ctx) => {+ if (isPresent(data.maxValue) && data.value >= data.maxValue) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Value exceeds maximum value of ${data.maxValue} defined in config`,+ });+ }+ if (isPresent(data.minValue) && data.value <= data.minValue) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Value is below minimum value of ${data.minValue} defined in config`,+ });+ }+ });++const ScorePropsAgainstConfigCategorical = z+ .object({+ value: z.string(),+ categories: z.array(ConfigCategory),+ dataType: z.literal("CATEGORICAL"),+ })+ .superRefine((data, ctx) => {+ if (!data.categories.some(({ label }) => label === data.value)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Value ${data.value} does not map to a valid category. Pass a valid category value.`,+ });+ }+ });++export const ScorePropsAgainstConfig = z.union([+ ScorePropsAgainstConfigNumeric,+ ScorePropsAgainstConfigCategorical,+ z.object({+ value: z.number().refine((val) => val === 0 || val === 1, {+ message: "Value must be either 0 or 1",+ }),+ dataType: z.literal("BOOLEAN"),+ }),+]);diff --git a/packages/shared/src/features/scores/interfaces/shared.ts b/packages/shared/src/features/scores/interfaces/shared.tsnew file mode 100644index 0000000000..0b9de8e2bf--- /dev/null+++ b/packages/shared/src/features/scores/interfaces/shared.ts@@ -0,0 +1,19 @@+import { jsonSchema } from "../../../utils/zod";+import z from "zod";+import { NonEmptyString } from "../../../utils/zod";++/**+ * Foundation schema for all score types. Used for ingestion and public API. Supports trace, observation and session scores.+ * Needs to be extended with with score data specific schema (numeric, categorical, boolean)+ * @see {@link NumericData}, {@link CategoricalData}, {@link BooleanData}+ */+export const PostScoreBodyFoundationSchema = z.object({+ id: z.string().nullish(),+ name: NonEmptyString,+ traceId: z.string().nullish(),+ sessionId: z.string().nullish(),+ observationId: z.string().nullish(),+ comment: z.string().nullish(),+ metadata: jsonSchema.nullish(),+ environment: z.string().default("default"),+});diff --git a/packages/shared/src/features/scores/types.ts b/packages/shared/src/features/scores/interfaces/ui/types.tssimilarity index 92%rename from packages/shared/src/features/scores/types.tsrename to packages/shared/src/features/scores/interfaces/ui/types.tsindex 41333c251d..1b46324652 100644--- a/packages/shared/src/features/scores/types.ts+++ b/packages/shared/src/features/scores/interfaces/ui/types.ts@@ -1,5 +1,5 @@import { ScoreDataType } from "@prisma/client";-import { ScoreSourceType, type MetadataDomain } from "../../domain";+import { MetadataDomain, ScoreSourceType } from "../../../../domain";export type BaseAggregate = {comment?: string | null;diff --git a/packages/shared/src/features/scores/scoreTypes.ts b/packages/shared/src/features/scores/scoreTypes.tsdeleted file mode 100644index ed816db53c..0000000000--- a/packages/shared/src/features/scores/scoreTypes.ts+++ /dev/null@@ -1,328 +0,0 @@-import { z } from "zod";--import { isPresent, stringDateTime } from "../../utils/typeChecks";-import {- jsonSchema,- NonEmptyString,- paginationMetaResponseZod,- publicApiPaginationZod,-} from "../../utils/zod";-import { Category as ConfigCategory } from "./scoreConfigTypes";-import { ScoreDomain } from "../../domain";--/**- * Types to use across codebase- */-export type APIScore = z.infer<typeof APIScoreSchema>;--/**- * Helpers- */--const ScoreSource = ["API", "EVAL", "ANNOTATION"] as const;-const ScoreDataType = ["NUMERIC", "CATEGORICAL", "BOOLEAN"] as const;--const operators = ["<", ">", "<=", ">=", "!=", "="] as const;--const NumericData = z.object({- value: z.number(),- stringValue: z.undefined().nullish(),- dataType: z.literal("NUMERIC"),-});--const CategoricalData = z.object({- value: z.number().nullish(),- stringValue: z.string(),- dataType: z.literal("CATEGORICAL"),-});--const BooleanData = z.object({- value: z.number(),- stringValue: z.string(),- dataType: z.literal("BOOLEAN"),-});--const ScoreBase = z.object({- id: z.string(),- timestamp: z.coerce.date(),- projectId: z.string(),- environment: z.string().default("default"),- name: z.string(),- source: z.enum(ScoreSource),- authorUserId: z.string().nullish(),- comment: z.string().nullish(),- metadata: jsonSchema.nullish(),- traceId: z.string(),- observationId: z.string().nullish(),- configId: z.string().nullish(),- createdAt: z.coerce.date(),- updatedAt: z.coerce.date(),- queueId: z.string().nullish(),-});--const BaseScoreBody = z.object({- id: z.string().nullish(),- name: NonEmptyString,- traceId: z.string(),- observationId: z.string().nullish(),- comment: z.string().nullish(),- metadata: jsonSchema.nullish(),- environment: z.string().default("default"),-});--/**- * Objects- */--export const APIScoreSchema = z.discriminatedUnion("dataType", [- ScoreBase.merge(NumericData),- ScoreBase.merge(CategoricalData),- ScoreBase.merge(BooleanData),-]);--/**- * Validation objects- */-export const ScoreBodyWithoutConfig = z.discriminatedUnion("dataType", [- BaseScoreBody.merge(- z.object({- value: z.number(),- dataType: z.literal("NUMERIC"),- }),- ),- BaseScoreBody.merge(- z.object({- value: z.string(),- dataType: z.literal("CATEGORICAL"),- }),- ),- BaseScoreBody.merge(- z.object({- value: z.number().refine((val) => val === 0 || val === 1, {- message: "Value must be either 0 or 1",- }),- dataType: z.literal("BOOLEAN"),- }),- ),-]);--const ScorePropsAgainstConfigNumeric = z- .object({- value: z.number(),- maxValue: z.number().optional(),- minValue: z.number().optional(),- dataType: z.literal("NUMERIC"),- })- .superRefine((data, ctx) => {- if (isPresent(data.maxValue) && data.value >= data.maxValue) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- message: `Value exceeds maximum value of ${data.maxValue} defined in config`,- });- }- if (isPresent(data.minValue) && data.value <= data.minValue) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- message: `Value is below minimum value of ${data.minValue} defined in config`,- });- }- });--const ScorePropsAgainstConfigCategorical = z- .object({- value: z.string(),- categories: z.array(ConfigCategory),- dataType: z.literal("CATEGORICAL"),- })- .superRefine((data, ctx) => {- if (!data.categories.some(({ label }) => label === data.value)) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- message: `Value ${data.value} does not map to a valid category. Pass a valid category value.`,- });- }- });--export const ScorePropsAgainstConfig = z.union([- ScorePropsAgainstConfigNumeric,- ScorePropsAgainstConfigCategorical,- z.object({- value: z.number().refine((val) => val === 0 || val === 1, {- message: "Value must be either 0 or 1",- }),- dataType: z.literal("BOOLEAN"),- }),-]);--/**- * Transformations- */--type ValidatedAPIScore<IncludeHasMetadata extends boolean> = APIScore & {- hasMetadata: IncludeHasMetadata extends true ? boolean : never;-};--type InputScore = ScoreDomain & { hasMetadata?: boolean };--/**- * Use this function when pulling a list of scores from the database before using in the application to ensure type safety.- * All scores are expected to pass the validation. If a score fails validation, it will be logged to Otel.- * @param scores- * @returns list of validated scores- */-export const filterAndValidateDbScoreList = <- IncludeHasMetadata extends boolean,->({- scores,- includeHasMetadata = false as IncludeHasMetadata,- onParseError,-}: {- scores: InputScore[];- includeHasMetadata?: IncludeHasMetadata;- // eslint-disable-next-line no-unused-vars- onParseError?: (error: z.ZodError) => void;-}): ValidatedAPIScore<IncludeHasMetadata>[] => {- return scores.reduce((acc, ts) => {- const result = APIScoreSchema.safeParse(ts);- if (result.success) {- const score = { ...result.data };- if (includeHasMetadata) {- Object.assign(score, { hasMetadata: ts.hasMetadata ?? false });- }- acc.push(score as ValidatedAPIScore<IncludeHasMetadata>);- } else {- console.error("Score parsing error: ", result.error);- onParseError?.(result.error);- }- return acc;- }, [] as ValidatedAPIScore<IncludeHasMetadata>[]);-};--/**- * Use this function when pulling a single score from the database before using in the application to ensure type safety.- * The score is expected to pass the validation. If a score fails validation, an error will be thrown.- * @param score- * @returns validated score- * @throws error if score fails validation- */-export const validateDbScore = (score: ScoreDomain): APIScore =>- APIScoreSchema.parse(score);--/**- * Endpoints- */--// POST /scores-/**- * PostScoresBody is copied for the ingestion API as `ScoreBody`. Please copy any changes here in `packages/shared/src/features/ingestion/types.ts`- */-export const PostScoresBody = z.discriminatedUnion("dataType", [- BaseScoreBody.merge(- z.object({- value: z.number(),- dataType: z.literal("NUMERIC"),- configId: z.string().nullish(),- }),- ),- BaseScoreBody.merge(- z.object({- value: z.string(),- dataType: z.literal("CATEGORICAL"),- configId: z.string().nullish(),- }),- ),- BaseScoreBody.merge(- z.object({- value: z.number().refine((value) => value === 0 || value === 1, {- message:- "Value must be a number equal to either 0 or 1 for data type BOOLEAN",- }),- dataType: z.literal("BOOLEAN"),- configId: z.string().nullish(),- }),- ),- BaseScoreBody.merge(- z.object({- value: z.union([z.string(), z.number()]),- dataType: z.undefined(),- configId: z.string().nullish(),- }),- ),-]);--export const PostScoresResponse = z.object({ id: z.string() });--// GET /scores-export const GetScoresQuery = z.object({- ...publicApiPaginationZod,- userId: z.string().nullish(),- dataType: z.enum(ScoreDataType).nullish(),- configId: z.string().nullish(),- queueId: z.string().nullish(),- traceTags: z.union([z.array(z.string()), z.string()]).nullish(),- environment: z.union([z.array(z.string()), z.string()]).nullish(),- name: z.string().nullish(),- fromTimestamp: stringDateTime,- toTimestamp: stringDateTime,- source: z.enum(ScoreSource).nullish(),- value: z.coerce.number().nullish(),- operator: z.enum(operators).nullish(),- scoreIds: z- .string()- .transform((str) => str.split(",").map((id) => id.trim())) // Split the comma-separated string- .refine((arr) => arr.every((id) => typeof id === "string"), {- message: "Each score ID must be a string",- })- .nullish(),-});--// LegacyGetScoreResponseDataV1 is only used for response of GET /scores list endpoint-const LegacyGetScoreResponseDataV1 = z.intersection(- APIScoreSchema,- z.object({- trace: z.object({- userId: z.string().nullish(),- tags: z.array(z.string()).nullish(),- environment: z.string().nullish(),- }),- }),-);-export const GetScoresResponse = z.object({- data: z.array(LegacyGetScoreResponseDataV1),- meta: paginationMetaResponseZod,-});--export const legacyFilterAndValidateV1GetScoreList = (- scores: unknown[],- // eslint-disable-next-line no-unused-vars- onParseError?: (error: z.ZodError) => void,-): z.infer<typeof LegacyGetScoreResponseDataV1>[] =>- scores.reduce(- (acc: z.infer<typeof LegacyGetScoreResponseDataV1>[], ts) => {- const result = LegacyGetScoreResponseDataV1.safeParse(ts);- if (result.success) {- acc.push(result.data);- } else {- console.error(`Score parsing error ${JSON.stringify(result.error)}`);- onParseError?.(result.error);- }- return acc;- },- [] as z.infer<typeof LegacyGetScoreResponseDataV1>[],- );--// GET /scores/{scoreId}-export const GetScoreQuery = z.object({- scoreId: z.string(),-});--export const GetScoreResponse = APIScoreSchema;--// DELETE /scores/{scoreId}-export const DeleteScoreQuery = z.object({- scoreId: z.string(),-});--export const DeleteScoreResponse = z.object({- message: z.string(),-});diff --git a/packages/shared/src/server/ingestion/types.ts b/packages/shared/src/server/ingestion/types.tsindex 727e1ee683..ed67d9a42d 100644--- a/packages/shared/src/server/ingestion/types.ts+++ b/packages/shared/src/server/ingestion/types.ts@@ -4,6 +4,7 @@ import { z } from "zod";import { NonEmptyString, jsonSchema } from "../../utils/zod";import { ModelUsageUnit } from "../../constants";import { ScoreSourceType } from "../../domain";+import { applyScoreValidation } from "../../utils/scores";export const idSchema = z.string()@@ -316,7 +317,8 @@ export const UpdateGenerationBody = UpdateSpanBody.extend({const BaseScoreBody = z.object({id: idSchema.nullish(),name: NonEmptyString,- traceId: z.string(),+ traceId: z.string().nullish(),+ sessionId: z.string().nullish(),environment: EnvironmentName,observationId: z.string().nullish(),comment: z.string().nullish(),@@ -329,39 +331,41 @@ const BaseScoreBody = z.object({/*** ScoreBody exactly mirrors `PostScoresBody` in the public API. Please refer there for source of truth.*/-export const ScoreBody = z.discriminatedUnion("dataType", [- BaseScoreBody.merge(- z.object({- value: z.number(),- dataType: z.literal("NUMERIC"),- configId: z.string().nullish(),- }),- ),- BaseScoreBody.merge(- z.object({- value: z.string(),- dataType: z.literal("CATEGORICAL"),- configId: z.string().nullish(),- }),- ),- BaseScoreBody.merge(- z.object({- value: z.number().refine((value) => value === 0 || value === 1, {- message:- "Value must be a number equal to either 0 or 1 for data type BOOLEAN",+export const ScoreBody = applyScoreValidation(+ z.discriminatedUnion("dataType", [+ BaseScoreBody.merge(+ z.object({+ value: z.number(),+ dataType: z.literal("NUMERIC"),+ configId: z.string().nullish(),}),- dataType: z.literal("BOOLEAN"),- configId: z.string().nullish(),- }),- ),- BaseScoreBody.merge(- z.object({- value: z.union([z.string(), z.number()]),- dataType: z.undefined(),- configId: z.string().nullish(),- }),- ),-]);+ ),+ BaseScoreBody.merge(+ z.object({+ value: z.string(),+ dataType: z.literal("CATEGORICAL"),+ configId: z.string().nullish(),+ }),+ ),+ BaseScoreBody.merge(+ z.object({+ value: z.number().refine((value) => value === 0 || value === 1, {+ message:+ "Value must be a number equal to either 0 or 1 for data type BOOLEAN",+ }),+ dataType: z.literal("BOOLEAN"),+ configId: z.string().nullish(),+ }),+ ),+ BaseScoreBody.merge(+ z.object({+ value: z.union([z.string(), z.number()]),+ dataType: z.undefined(),+ configId: z.string().nullish(),+ }),+ ),+ ]),+);// LEGACY, only required for backwards compatibilityexport const LegacySpanPostSchema = z.object({diff --git a/packages/shared/src/server/queries/clickhouse-sql/factory.ts b/packages/shared/src/server/queries/clickhouse-sql/factory.tsindex 92b3f7e040..688797ccee 100644--- a/packages/shared/src/server/queries/clickhouse-sql/factory.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/factory.ts@@ -121,6 +121,7 @@ export const createFilterFromFilterState = (tablePrefix: column.queryPrefix,});default:+ // eslint-disable-next-line no-case-declarationsconst exhaustiveCheck: never = frontEndFilter;logger.error(`Invalid filter type: ${JSON.stringify(exhaustiveCheck)}`);throw new QueryBuilderError(`Invalid filter type`);diff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.tsindex dd041a87ad..50af5e5974 100644--- a/packages/shared/src/server/repositories/definitions.ts+++ b/packages/shared/src/server/repositories/definitions.ts@@ -125,7 +125,8 @@ export type TraceRecordInsertType = z.infer<typeof traceRecordInsertSchema>;export const scoreRecordBaseSchema = z.object({id: z.string(),project_id: z.string(),- trace_id: z.string(),+ trace_id: z.string().nullish(),+ session_id: z.string().nullish(),observation_id: z.string().nullish(),environment: z.string().default("default"),name: z.string(),@@ -352,6 +353,7 @@ export const convertPostgresScoreToInsert = (timestamp: score.timestamp?.getTime(),project_id: score.project_id,trace_id: score.trace_id,+ session_id: null,observation_id: score.observation_id,environment: score.environment,name: score.name,diff --git a/packages/shared/src/server/repositories/index.ts b/packages/shared/src/server/repositories/index.tsindex eb0d7bff08..600902e68e 100644--- a/packages/shared/src/server/repositories/index.ts+++ b/packages/shared/src/server/repositories/index.ts@@ -9,5 +9,6 @@ export * from "./observations_converters";export * from "./clickhouse";export * from "./constants";export * from "./trace-sessions";+export * from "./scores-utils";export * from "./blobStorageLog";export * from "./environments";diff --git a/packages/shared/src/server/repositories/scores-utils.ts b/packages/shared/src/server/repositories/scores-utils.tsnew file mode 100644index 0000000000..0d8c9cc7a4--- /dev/null+++ b/packages/shared/src/server/repositories/scores-utils.ts@@ -0,0 +1,93 @@+import { ScoreSourceType } from "../../domain";+import { queryClickhouse } from "./clickhouse";+import { ScoreRecordReadType } from "./definitions";+import { convertToScore } from "./scores_converters";++/**+ * @internal+ * Internal utility function for getting scores by ID.+ * Do not use directly - use ScoresApiService or repository functions instead.+ */+export const _handleGetScoreById = async ({+ projectId,+ scoreId,+ source,+ scoreScope,+}: {+ projectId: string;+ scoreId: string;+ source?: ScoreSourceType;+ scoreScope: "traces_only" | "all";+}) => {+ const query = `+ SELECT *+ FROM scores s+ WHERE s.project_id = {projectId: String}+ AND s.id = {scoreId: String}+ ${source ? `AND s.source = {source: String}` : ""}+ ${scoreScope === "traces_only" ? "AND s.session_id IS NULL" : ""}+ ORDER BY s.event_ts DESC+ LIMIT 1 BY s.id, s.project_id+ LIMIT 1+`;++ const rows = await queryClickhouse<ScoreRecordReadType>({+ query,+ params: {+ projectId,+ scoreId,+ ...(source !== undefined ? { source } : {}),+ },+ tags: {+ feature: "tracing",+ type: "score",+ kind: "byId",+ projectId,+ },+ });+ return rows.map(convertToScore).shift();+};++/**+ * @internal+ * Internal utility function for getting scores by ID.+ * Do not use directly - use ScoresApiService or repository functions instead.+ */+export const _handleGetScoresByIds = async ({+ projectId,+ scoreId,+ source,+ scoreScope,+}: {+ projectId: string;+ scoreId: string[];+ source?: ScoreSourceType;+ scoreScope: "traces_only" | "all";+}) => {+ const query = `+ SELECT *+ FROM scores s+ WHERE s.project_id = {projectId: String}+ AND s.id IN ({scoreId: Array(String)})+ ${source ? `AND s.source = {source: String}` : ""}+ ${scoreScope === "traces_only" ? "AND s.session_id IS NULL" : ""}+ ORDER BY s.event_ts DESC+ LIMIT 1 BY s.id, s.project_id+`;++ const rows = await queryClickhouse<ScoreRecordReadType>({+ query,+ params: {+ projectId,+ scoreId,+ ...(source !== undefined ? { source } : {}),+ },+ tags: {+ feature: "tracing",+ type: "score",+ kind: "byId",+ projectId,+ },+ });+ return rows.map(convertToScore);+};diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.tsindex 0448112a90..0e561fe62c 100644--- a/packages/shared/src/server/repositories/scores.ts+++ b/packages/shared/src/server/repositories/scores.ts@@ -27,19 +27,22 @@ import { SCORE_TO_TRACE_OBSERVATIONS_INTERVAL } from "./constants";import { convertDateToClickhouseDateTime } from "../clickhouse/client";import { ScoreRecordReadType } from "./definitions";import { env } from "../../env";+import { _handleGetScoreById, _handleGetScoresByIds } from "./scores-utils";import { parseMetadataCHRecordToDomain } from "../utils/metadata_conversion";import { ClickHouseClientConfigOptions } from "@clickhouse/client";export const searchExistingAnnotationScore = async (projectId: string,- traceId: string,observationId: string | null,+ traceId: string | null,+ sessionId: string | null,name: string | undefined,configId: string | undefined,) => {if (!name && !configId) {throw new Error("Either name or configId (or both) must be provided.");}+const query = `SELECT *FROM scores s@@ -76,37 +79,21 @@ export const searchExistingAnnotationScore = async (return rows.map((row) => convertToScore(row)).shift();};-export const getScoreById = async (- projectId: string,- scoreId: string,- source?: ScoreSourceType,-) => {- const query = `- SELECT *- FROM scores s- WHERE s.project_id = {projectId: String}- AND s.id = {scoreId: String}- ${source ? `AND s.source = {source: String}` : ""}- ORDER BY s.event_ts DESC- LIMIT 1 BY s.id, s.project_id- LIMIT 1- `;-- const rows = await queryClickhouse<ScoreRecordReadType>({- query,- params: {- projectId,- scoreId,- ...(source !== undefined ? { source } : {}),- },- tags: {- feature: "tracing",- type: "score",- kind: "byId",- projectId,- },+export const getScoreById = async ({+ projectId,+ scoreId,+ source,+}: {+ projectId: string;+ scoreId: string;+ source?: ScoreSourceType;+}) => {+ return _handleGetScoreById({+ projectId,+ scoreId,+ source,+ scoreScope: "all",});- return rows.map(convertToScore).shift();};export const getScoresByIds = async (@@ -114,31 +101,12 @@ export const getScoresByIds = async (scoreId: string[],source?: ScoreSourceType,) => {- const query = `- SELECT *- FROM scores s- WHERE s.project_id = {projectId: String}- AND s.id IN ({scoreId: Array(String)})- ${source ? `AND s.source = {source: String}` : ""}- ORDER BY s.event_ts DESC- LIMIT 1 BY s.id, s.project_id- `;-- const rows = await queryClickhouse<ScoreRecordReadType>({- query,- params: {- projectId,- scoreId,- ...(source !== undefined ? { source } : {}),- },- tags: {- feature: "tracing",- type: "score",- kind: "byId",- projectId,- },+ return _handleGetScoresByIds({+ projectId,+ scoreId,+ source,+ scoreScope: "all",});- return rows.map(convertToScore);};/**@@ -176,6 +144,82 @@ export type GetScoresForTracesProps<includeHasMetadata?: IncludeHasMetadata;};+type GetScoresForSessionsProps<+ ExcludeMetadata extends boolean,+ IncludeHasMetadata extends boolean,+> = {+ projectId: string;+ sessionIds: string[];+ limit?: number;+ offset?: number;+ clickhouseConfigs?: ClickHouseClientConfigOptions;+ excludeMetadata?: ExcludeMetadata;+ includeHasMetadata?: IncludeHasMetadata;+};++const formatMetadataSelect = (+ excludeMetadata: boolean,+ includeHasMetadata: boolean,+) => {+ return [+ !excludeMetadata ? "*" : "* EXCEPT (metadata)",+ includeHasMetadata+ ? "length(mapKeys(s.metadata)) > 0 AS has_metadata"+ : null,+ ]+ .filter((s) => s != null)+ .join(", ");+};++export const getScoresForSessions = async <+ ExcludeMetadata extends boolean,+ IncludeHasMetadata extends boolean,+>(+ props: GetScoresForSessionsProps<ExcludeMetadata, IncludeHasMetadata>,+) => {+ const {+ projectId,+ sessionIds,+ limit,+ offset,+ clickhouseConfigs,+ excludeMetadata = false,+ includeHasMetadata = false,+ } = props;++ const select = formatMetadataSelect(excludeMetadata, includeHasMetadata);++ const query = `+ select+ ${select}+ from scores s+ WHERE s.project_id = {projectId: String}+ AND s.session_id IN ({sessionIds: Array(String)})+ ORDER BY s.event_ts DESC+ LIMIT 1 BY s.id, s.project_id+ ${limit && offset ? `limit {limit: Int32} offset {offset: Int32}` : ""}+ `;++ const rows = await queryClickhouse<ScoreRecordReadType>({+ query: query,+ params: {+ projectId,+ sessionIds,+ limit,+ offset,+ },+ tags: {+ feature: "sessions",+ type: "score",+ kind: "list",+ projectId,+ },+ clickhouseConfigs,+ });++ return rows.map(convertToScore);+};+// Used in multiple places, including the public API, hence the non-default exclusion of metadata via excludeMetadata flagexport const getScoresForTraces = async <ExcludeMetadata extends boolean,@@ -194,14 +238,7 @@ export const getScoresForTraces = async <includeHasMetadata = false,} = props;- const select = [- !excludeMetadata ? "*" : "* EXCEPT (metadata)",- includeHasMetadata- ? "length(mapKeys(s.metadata)) > 0 AS has_metadata"- : null,- ]- .filter((s) => s != null)- .join(", ");+ const select = formatMetadataSelect(excludeMetadata, includeHasMetadata);const query = `select@@ -547,8 +584,9 @@ export async function getScoresUiTable<source: string;data_type: string;comment: string | null;+ trace_id: string | null;+ session_id: string | null;metadata: ExcludeMetadata extends true ? never : Record<string, string>;- trace_id: string;observation_id: string | null;author_user_id: string | null;user_id: string | null;@@ -572,39 +610,38 @@ export async function getScoresUiTable<...rest,});- return rows.map((row) => {- return {- projectId: row.project_id,- environment: row.environment,- authorUserId: row.author_user_id,- traceId: row.trace_id,- observationId: row.observation_id,- traceUserId: row.user_id,- traceName: row.trace_name,- traceTags: row.trace_tags,- configId: row.config_id,- queueId: row.queue_id,- createdAt: parseClickhouseUTCDateTimeFormat(row.created_at),- updatedAt: parseClickhouseUTCDateTimeFormat(row.updated_at),- stringValue: row.string_value,- comment: row.comment,- dataType: row.data_type as ScoreDataType,- source: row.source as ScoreSourceType,- name: row.name,- value: row.value,- timestamp: parseClickhouseUTCDateTimeFormat(row.timestamp),- id: row.id,- metadata: (excludeMetadata- ? undefined- : (parseMetadataCHRecordToDomain(row.metadata ?? {}) ??- {})) as ExcludeMetadata extends true- ? never- : NonNullable<ReturnType<typeof parseMetadataCHRecordToDomain>>,- hasMetadata: (includeHasMetadataFlag- ? !!row.has_metadata- : undefined) as IncludeHasMetadata extends true ? boolean : never,- };- });+ return rows.map((row) => ({+ projectId: row.project_id,+ environment: row.environment,+ authorUserId: row.author_user_id,+ traceId: row.trace_id,+ sessionId: row.session_id,+ observationId: row.observation_id,+ traceUserId: row.user_id,+ traceName: row.trace_name,+ traceTags: row.trace_tags,+ configId: row.config_id,+ queueId: row.queue_id,+ createdAt: parseClickhouseUTCDateTimeFormat(row.created_at),+ updatedAt: parseClickhouseUTCDateTimeFormat(row.updated_at),+ stringValue: row.string_value,+ comment: row.comment,+ dataType: row.data_type as ScoreDataType,+ source: row.source as ScoreSourceType,+ name: row.name,+ value: row.value,+ timestamp: parseClickhouseUTCDateTimeFormat(row.timestamp),+ id: row.id,+ metadata: (excludeMetadata+ ? undefined+ : (parseMetadataCHRecordToDomain(row.metadata ?? {}) ??+ {})) as ExcludeMetadata extends true+ ? never+ : NonNullable<ReturnType<typeof parseMetadataCHRecordToDomain>>,+ hasMetadata: (includeHasMetadataFlag+ ? !!row.has_metadata+ : undefined) as IncludeHasMetadata extends true ? boolean : never,+ }));}const getScoresUiGeneric = async <T>(props: {diff --git a/packages/shared/src/server/repositories/scores_converters.ts b/packages/shared/src/server/repositories/scores_converters.tsindex d390b5f84a..7e9555c5c3 100644--- a/packages/shared/src/server/repositories/scores_converters.ts+++ b/packages/shared/src/server/repositories/scores_converters.ts@@ -19,7 +19,8 @@ export const convertToScore = (row: ScoreRecordReadType): ScoreDomain => {timestamp: new Date(row.timestamp),projectId: row.project_id,environment: row.environment,- traceId: row.trace_id,+ traceId: row.trace_id ?? null,+ sessionId: row.session_id ?? null,observationId: row.observation_id ?? null,name: row.name,value: row.value ?? null,diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.tsindex 0b1496a7a6..94b7c39b6b 100644--- a/packages/shared/src/server/repositories/traces.ts+++ b/packages/shared/src/server/repositories/traces.ts@@ -1007,3 +1007,32 @@ export const getTracesByIdsForAnyProject = async (traceIds: string[]) => {projectId: record.project_id,}));};++export const traceWithSessionIdExists = async (+ projectId: string,+ sessionId: string,+) => {+ const query = `+ SELECT id, project_id+ FROM traces+ WHERE session_id = {sessionId: String}+ AND project_id = {projectId: String}+ LIMIT 1+ `;++ const result = await queryClickhouse<{ id: string; project_id: string }>({+ query,+ params: {+ sessionId,+ projectId,+ },+ tags: {+ feature: "tracing",+ type: "trace",+ kind: "exists",+ projectId,+ },+ });++ return result.length > 0;+};diff --git a/packages/shared/src/server/test-utils/tracing-factory.ts b/packages/shared/src/server/test-utils/tracing-factory.tsindex 1e3bc19bbe..37df1513c7 100644--- a/packages/shared/src/server/test-utils/tracing-factory.ts+++ b/packages/shared/src/server/test-utils/tracing-factory.ts@@ -74,7 +74,7 @@ export const createObservation = (};};-export const createScore = (+export const createTraceScore = (score: Partial<ScoreRecordInsertType>,): ScoreRecordInsertType => {return {@@ -95,5 +95,31 @@ export const createScore = (event_ts: Date.now(),is_deleted: 0,...score,+ session_id: null,+ };+};++export const createSessionScore = (+ score: Partial<ScoreRecordInsertType>,+): ScoreRecordInsertType => {+ return {+ id: v4(),+ project_id: v4(),+ session_id: v4(),+ environment: "default",+ name: "test-session-score" + v4(),+ timestamp: Date.now(),+ value: 100.5,+ source: "API",+ comment: "comment",+ metadata: { "test-key": "test-value" },+ data_type: "NUMERIC" as const,+ created_at: Date.now(),+ updated_at: Date.now(),+ event_ts: Date.now(),+ is_deleted: 0,+ ...score,+ observation_id: null,+ trace_id: null,};};diff --git a/packages/shared/src/utils/scores.ts b/packages/shared/src/utils/scores.tsnew file mode 100644index 0000000000..6d7bf70ce2--- /dev/null+++ b/packages/shared/src/utils/scores.ts@@ -0,0 +1,22 @@+import z from "zod";++export const applyScoreValidation = <T extends z.ZodType<any, any, any>>(+ schema: T,+) => {+ return schema.refine(+ (data) => {+ const hasTraceId = !!data.traceId;+ const hasSessionId = !!data.sessionId;++ return (+ (hasTraceId && !hasSessionId) ||+ (hasSessionId && !hasTraceId && !data.observationId)+ );+ },+ {+ message:+ "Either provide traceId (with optional observationId) or sessionId, but not both. ObservationId requires traceId.",+ path: ["traceId", "sessionId", "observationId"],+ },+ );+};diff --git a/web/public/generated/api-client/openapi.yml b/web/public/generated/api-client/openapi.ymlindex 45e926636e..df42018fd4 100644--- a/web/public/generated/api-client/openapi.yml+++ b/web/public/generated/api-client/openapi.yml@@ -56,7 +56,13 @@ components:nullable: truetraceId:type: string- example: cdef-1234-5678-90ab+ nullable: true+ sessionId:+ type: string+ nullable: true+ observationId:+ type: string+ nullable: truename:type: stringexample: novelty@@ -66,9 +72,6 @@ components:The value of the score. Must be passed as string for categoricalscores, and numeric for boolean and numeric scores. Boolean scorevalues must equal either 1 or 0 (true or false)- observationId:- type: string- nullable: truecomment:type: stringnullable: true@@ -90,7 +93,6 @@ components:config category. Numeric scores might be constrained by the scoreconfig's max and min valuesrequired:- - traceId- name- valueBaseScore:diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.ymlindex 1a576a47ff..07bbb27b9a 100644--- a/web/public/generated/api/openapi.yml+++ b/web/public/generated/api/openapi.yml@@ -3318,58 +3318,12 @@ paths:schema: {}security:- BasicAuth: []- /api/public/scores:- post:- description: Create a score- operationId: score_create- tags:- - Score- parameters: []- responses:- '200':- description: ''- content:- application/json:- schema:- $ref: '#/components/schemas/CreateScoreResponse'- '400':- description: ''- content:- application/json:- schema: {}- '401':- description: ''- content:- application/json:- schema: {}- '403':- description: ''- content:- application/json:- schema: {}- '404':- description: ''- content:- application/json:- schema: {}- '405':- description: ''- content:- application/json:- schema: {}- security:- - BasicAuth: []- requestBody:- required: true- content:- application/json:- schema:- $ref: '#/components/schemas/CreateScoreRequest'+ /api/public/v2/scores:get:- description: Get a list of scores- operationId: score_get+ description: Get a list of scores (supports both trace and session scores)+ operationId: scoreV2_gettags:- - Score+ - ScoreV2parameters:- name: pagein: query@@ -3527,12 +3481,12 @@ paths:schema: {}security:- BasicAuth: []- /api/public/scores/{scoreId}:+ /api/public/v2/scores/{scoreId}:get:- description: Get a score- operationId: score_get-by-id+ description: Get a score (supports both trace and session scores)+ operationId: scoreV2_get-by-idtags:- - Score+ - ScoreV2parameters:- name: scoreIdin: path@@ -3574,8 +3528,56 @@ paths:schema: {}security:- BasicAuth: []+ /api/public/scores:+ post:+ description: Create a score (supports both trace and session scores)+ operationId: score_create+ tags:+ - Score+ parameters: []+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/CreateScoreResponse'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ security:+ - BasicAuth: []+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/CreateScoreRequest'+ /api/public/scores/{scoreId}:delete:- description: Delete a score+ description: Delete a score (supports both trace and session scores)operationId: score_deletetags:- Score@@ -4343,7 +4345,7 @@ components:scores:type: arrayitems:- $ref: '#/components/schemas/Score'+ $ref: '#/components/schemas/ScoreV1'description: List of scoresrequired:- htmlPath@@ -4657,8 +4659,8 @@ components:required:- value- label- BaseScore:- title: BaseScore+ BaseScoreV1:+ title: BaseScoreV1type: objectproperties:id:@@ -4717,6 +4719,157 @@ components:- timestamp- createdAt- updatedAt+ NumericScoreV1:+ title: NumericScoreV1+ type: object+ properties:+ value:+ type: number+ format: double+ description: The numeric value of the score+ required:+ - value+ allOf:+ - $ref: '#/components/schemas/BaseScoreV1'+ BooleanScoreV1:+ title: BooleanScoreV1+ type: object+ properties:+ value:+ type: number+ format: double+ description: >-+ The numeric value of the score. Equals 1 for "True" and 0 for+ "False"+ stringValue:+ type: string+ description: >-+ The string representation of the score value. Is inferred from the+ numeric value and equals "True" or "False"+ required:+ - value+ - stringValue+ allOf:+ - $ref: '#/components/schemas/BaseScoreV1'+ CategoricalScoreV1:+ title: CategoricalScoreV1+ type: object+ properties:+ value:+ type: number+ format: double+ nullable: true+ description: >-+ Only defined if a config is linked. Represents the numeric category+ mapping of the stringValue+ stringValue:+ type: string+ description: >-+ The string representation of the score value. If no config is+ linked, can be any string. Otherwise, must map to a config category+ required:+ - stringValue+ allOf:+ - $ref: '#/components/schemas/BaseScoreV1'+ ScoreV1:+ title: ScoreV1+ oneOf:+ - type: object+ allOf:+ - type: object+ properties:+ dataType:+ type: string+ enum:+ - NUMERIC+ - $ref: '#/components/schemas/NumericScoreV1'+ required:+ - dataType+ - type: object+ allOf:+ - type: object+ properties:+ dataType:+ type: string+ enum:+ - CATEGORICAL+ - $ref: '#/components/schemas/CategoricalScoreV1'+ required:+ - dataType+ - type: object+ allOf:+ - type: object+ properties:+ dataType:+ type: string+ enum:+ - BOOLEAN+ - $ref: '#/components/schemas/BooleanScoreV1'+ required:+ - dataType+ BaseScore:+ title: BaseScore+ type: object+ properties:+ id:+ type: string+ traceId:+ type: string+ nullable: true+ sessionId:+ type: string+ nullable: true+ observationId:+ type: string+ nullable: true+ name:+ type: string+ source:+ $ref: '#/components/schemas/ScoreSource'+ timestamp:+ type: string+ format: date-time+ createdAt:+ type: string+ format: date-time+ updatedAt:+ type: string+ format: date-time+ authorUserId:+ type: string+ nullable: true+ comment:+ type: string+ nullable: true+ metadata:+ nullable: true+ configId:+ type: string+ nullable: true+ description: >-+ Reference a score config on a score. When set, config and score name+ must be equal and value must comply to optionally defined numerical+ range+ queueId:+ type: string+ nullable: true+ description: >-+ Reference an annotation queue on a score. Populated if the score was+ initially created in an annotation queue.+ environment:+ type: string+ nullable: true+ description: >-+ The environment from which this score originated. Can be any+ lowercase alphanumeric string with hyphens and underscores that does+ not start with 'langfuse'.+ required:+ - id+ - name+ - source+ - timestamp+ - createdAt+ - updatedAtNumericScore:title: NumericScoretype: object@@ -5662,7 +5815,13 @@ components:nullable: truetraceId:type: string- example: cdef-1234-5678-90ab+ nullable: true+ sessionId:+ type: string+ nullable: true+ observationId:+ type: string+ nullable: truename:type: stringexample: novelty@@ -5675,9 +5834,6 @@ components:The value of the score. Must be passed as string for categoricalscores, and numeric for boolean and numeric scores. Boolean scorevalues must equal either 1 or 0 (true or false)- observationId:- type: string- nullable: truecomment:type: stringnullable: true@@ -5699,7 +5855,6 @@ components:config category. Numeric scores might be constrained by the scoreconfig's max and min valuesrequired:- - traceId- name- valueBaseEvent:@@ -6967,67 +7122,6 @@ components:required:- name- dataType- CreateScoreRequest:- title: CreateScoreRequest- type: object- properties:- id:- type: string- nullable: true- traceId:- type: string- example: cdef-1234-5678-90ab- name:- type: string- example: novelty- value:- $ref: '#/components/schemas/CreateScoreValue'- description: >-- The value of the score. Must be passed as string for categorical- scores, and numeric for boolean and numeric scores. Boolean score- values must equal either 1 or 0 (true or false)- observationId:- type: string- nullable: true- comment:- type: string- nullable: true- metadata:- nullable: true- environment:- type: string- nullable: true- description: >-- The environment of the score. Can be any lowercase alphanumeric- string with hyphens and underscores that does not start with- 'langfuse'.- dataType:- $ref: '#/components/schemas/ScoreDataType'- nullable: true- description: >-- The data type of the score. When passing a configId this field is- inferred. Otherwise, this field must be passed or will default to- numeric.- configId:- type: string- nullable: true- description: >-- Reference a score config on a score. The unique langfuse identifier- of a score config. When passing this field, the dataType and- stringValue fields are automatically populated.- required:- - traceId- - name- - value- CreateScoreResponse:- title: CreateScoreResponse- type: object- properties:- id:- type: string- description: The id of the created object in Langfuse- required:- - idGetScoresResponseTraceData:title: GetScoresResponseTraceDatatype: object@@ -7052,8 +7146,7 @@ components:properties:trace:$ref: '#/components/schemas/GetScoresResponseTraceData'- required:- - trace+ nullable: trueallOf:- $ref: '#/components/schemas/NumericScore'GetScoresResponseDataCategorical:@@ -7062,8 +7155,7 @@ components:properties:trace:$ref: '#/components/schemas/GetScoresResponseTraceData'- required:- - trace+ nullable: trueallOf:- $ref: '#/components/schemas/CategoricalScore'GetScoresResponseDataBoolean:@@ -7072,8 +7164,7 @@ components:properties:trace:$ref: '#/components/schemas/GetScoresResponseTraceData'- required:- - trace+ nullable: trueallOf:- $ref: '#/components/schemas/BooleanScore'GetScoresResponseData:@@ -7125,6 +7216,69 @@ components:required:- data- meta+ CreateScoreRequest:+ title: CreateScoreRequest+ type: object+ properties:+ id:+ type: string+ nullable: true+ traceId:+ type: string+ nullable: true+ sessionId:+ type: string+ nullable: true+ observationId:+ type: string+ nullable: true+ name:+ type: string+ example: novelty+ value:+ $ref: '#/components/schemas/CreateScoreValue'+ description: >-+ The value of the score. Must be passed as string for categorical+ scores, and numeric for boolean and numeric scores. Boolean score+ values must equal either 1 or 0 (true or false)+ comment:+ type: string+ nullable: true+ metadata:+ nullable: true+ environment:+ type: string+ nullable: true+ description: >-+ The environment of the score. Can be any lowercase alphanumeric+ string with hyphens and underscores that does not start with+ 'langfuse'.+ dataType:+ $ref: '#/components/schemas/ScoreDataType'+ nullable: true+ description: >-+ The data type of the score. When passing a configId this field is+ inferred. Otherwise, this field must be passed or will default to+ numeric.+ configId:+ type: string+ nullable: true+ description: >-+ Reference a score config on a score. The unique langfuse identifier+ of a score config. When passing this field, the dataType and+ stringValue fields are automatically populated.+ required:+ - name+ - value+ CreateScoreResponse:+ title: CreateScoreResponse+ type: object+ properties:+ id:+ type: string+ description: The id of the created object in Langfuse+ required:+ - idPaginatedSessions:title: PaginatedSessionstype: objectdiff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.jsonindex 3039e88673..f27df52605 100644--- a/web/public/generated/postman/collection.json+++ b/web/public/generated/postman/collection.json@@ -2460,54 +2460,22 @@{"_type": "container","description": null,- "name": "Score",+ "name": "Score V 2","item": [- {- "_type": "endpoint",- "name": "Create",- "request": {- "description": "Create a score",- "url": {- "raw": "{{baseUrl}}/api/public/scores",- "host": [- "{{baseUrl}}"- ],- "path": [- "api",- "public",- "scores"- ],- "query": [],- "variable": []- },- "header": [],- "method": "POST",- "auth": null,- "body": {- "mode": "raw",- "raw": "{\n \"name\": \"novelty\",\n \"value\": 0.9,\n \"traceId\": \"cdef-1234-5678-90ab\"\n}",- "options": {- "raw": {- "language": "json"- }- }- }- },- "response": []- },{"_type": "endpoint","name": "Get","request": {- "description": "Get a list of scores",+ "description": "Get a list of scores (supports both trace and session scores)","url": {- "raw": "{{baseUrl}}/api/public/scores?page=&limit=&userId=&name=&fromTimestamp=&toTimestamp=&environment=&source=&operator=&value=&scoreIds=&configId=&queueId=&dataType=&traceTags=",+ "raw": "{{baseUrl}}/api/public/v2/scores?page=&limit=&userId=&name=&fromTimestamp=&toTimestamp=&environment=&source=&operator=&value=&scoreIds=&configId=&queueId=&dataType=&traceTags=","host": ["{{baseUrl}}"],"path": ["api","public",+ "v2","scores"],"query": [@@ -2600,15 +2568,16 @@"_type": "endpoint","name": "Get By Id","request": {- "description": "Get a score",+ "description": "Get a score (supports both trace and session scores)","url": {- "raw": "{{baseUrl}}/api/public/scores/:scoreId",+ "raw": "{{baseUrl}}/api/public/v2/scores/:scoreId","host": ["{{baseUrl}}"],"path": ["api","public",+ "v2","scores",":scoreId"],@@ -2627,12 +2596,52 @@"body": null},"response": []+ }+ ]+ },+ {+ "_type": "container",+ "description": null,+ "name": "Score",+ "item": [+ {+ "_type": "endpoint",+ "name": "Create",+ "request": {+ "description": "Create a score (supports both trace and session scores)",+ "url": {+ "raw": "{{baseUrl}}/api/public/scores",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "public",+ "scores"+ ],+ "query": [],+ "variable": []+ },+ "header": [],+ "method": "POST",+ "auth": null,+ "body": {+ "mode": "raw",+ "raw": "{\n \"name\": \"novelty\",\n \"value\": 0.9,\n \"traceId\": \"cdef-1234-5678-90ab\"\n}",+ "options": {+ "raw": {+ "language": "json"+ }+ }+ }+ },+ "response": []},{"_type": "endpoint","name": "Delete","request": {- "description": "Delete a score",+ "description": "Delete a score (supports both trace and session scores)","url": {"raw": "{{baseUrl}}/api/public/scores/:scoreId","host": [diff --git a/web/src/__tests__/aggregateScores.clienttest.ts b/web/src/__tests__/aggregateScores.clienttest.tsindex 9d2d53d4a6..9bc70c1511 100644--- a/web/src/__tests__/aggregateScores.clienttest.ts+++ b/web/src/__tests__/aggregateScores.clienttest.ts@@ -1,9 +1,9 @@import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";-import { type APIScore } from "@langfuse/shared";+import { type APIScoreV2 } from "@langfuse/shared";describe("aggregateScores", () => {it("should return an empty object for an empty array", () => {- const scores: APIScore[] = [];+ const scores: APIScoreV2[] = [];expect(aggregateScores(scores)).toEqual({});});@@ -16,7 +16,7 @@ describe("aggregateScores", () => {value: 5,comment: "test comment",},- ] as APIScore[];+ ] as APIScoreV2[];expect(aggregateScores(scores)).toEqual({"test-API-NUMERIC": {type: "NUMERIC",@@ -43,7 +43,7 @@ describe("aggregateScores", () => {value: 7,comment: "another comment",},- ] as APIScore[];+ ] as APIScoreV2[];expect(aggregateScores(scores)).toEqual({"test-API-NUMERIC": {type: "NUMERIC",@@ -70,7 +70,7 @@ describe("aggregateScores", () => {value: 5,comment: "another comment",},- ] as APIScore[];+ ] as APIScoreV2[];expect(aggregateScores(scores)).toEqual({"test-API-NUMERIC": {type: "NUMERIC",@@ -82,7 +82,7 @@ describe("aggregateScores", () => {});it("should correctly aggregate scores with different keys", () => {- const scores: APIScore[] = [+ const scores: APIScoreV2[] = [{name: "test1",source: "API",@@ -97,7 +97,7 @@ describe("aggregateScores", () => {value: 7,comment: "another comment",},- ] as APIScore[];+ ] as APIScoreV2[];expect(aggregateScores(scores)).toEqual({"test1-API-NUMERIC": {type: "NUMERIC",@@ -123,7 +123,7 @@ describe("aggregateScores", () => {stringValue: "good",comment: "test comment",},- ] as APIScore[];+ ] as APIScoreV2[];expect(aggregateScores(scores)).toEqual({"test-ANNOTATION-CATEGORICAL": {type: "CATEGORICAL",@@ -150,7 +150,7 @@ describe("aggregateScores", () => {stringValue: "False",comment: "another comment",},- ] as APIScore[];+ ] as APIScoreV2[];expect(aggregateScores(scores)).toEqual({"test-API-BOOLEAN": {type: "CATEGORICAL",@@ -194,7 +194,7 @@ describe("aggregateScores", () => {stringValue: "good",comment: "last comment",},- ] as APIScore[];+ ] as APIScoreV2[];expect(aggregateScores(scores)).toEqual({"test-API-NUMERIC": {type: "NUMERIC",diff --git a/web/src/__tests__/async/dataset-service.servertest.ts b/web/src/__tests__/async/dataset-service.servertest.tsindex bc0a3f1563..c4318a036f 100644--- a/web/src/__tests__/async/dataset-service.servertest.ts+++ b/web/src/__tests__/async/dataset-service.servertest.ts@@ -7,7 +7,7 @@ import { v4 } from "uuid";import { prisma } from "@langfuse/shared/src/db";import {createObservation,- createScore,+ createTraceScore,createTrace,} from "@langfuse/shared/src/server";import {@@ -159,14 +159,14 @@ describe("Fetch datasets for UI presentation", () => {observation4,observation5,]);- const score = createScore({+ const score = createTraceScore({id: scoreId,observation_id: observationId,trace_id: traceId,project_id: projectId,name: scoreName,});- const score2 = createScore({+ const score2 = createTraceScore({id: scoreId2,observation_id: null,trace_id: traceId,@@ -178,7 +178,7 @@ describe("Fetch datasets for UI presentation", () => {const observationId2 = v4(); // this one is not related to a runconst anotherScoreName = v4();- const score3 = createScore({+ const score3 = createTraceScore({id: scoreId3,observation_id: observationId2,trace_id: traceId,@@ -320,7 +320,7 @@ describe("Fetch datasets for UI presentation", () => {});const scoreName = v4();- const score = createScore({+ const score = createTraceScore({id: scoreId,observation_id: null,trace_id: traceId,@@ -467,7 +467,7 @@ describe("Fetch datasets for UI presentation", () => {await createObservationsCh([observation]);- const score = createScore({+ const score = createTraceScore({observation_id: observation2.id,trace_id: traceId2,project_id: projectId,diff --git a/web/src/__tests__/async/ingestion-api.servertest.ts b/web/src/__tests__/async/ingestion-api.servertest.tsindex a6ae2fba26..3ed69fb9d9 100644--- a/web/src/__tests__/async/ingestion-api.servertest.ts+++ b/web/src/__tests__/async/ingestion-api.servertest.ts@@ -273,7 +273,10 @@ describe("/api/public/ingestion API Endpoint", () => {expect(response.status).toBe(207);await waitForExpect(async () => {- const score = await getScoreById(projectId, entity.body.id);+ const score = await getScoreById({+ projectId,+ scoreId: entity.body.id,+ });expect(score).toBeDefined();expect(score!.id).toBe(entity.body.id);expect(score!.projectId).toBe(projectId);@@ -611,7 +614,7 @@ describe("/api/public/ingestion API Endpoint", () => {expect(response.status).toBe(207);await waitForExpect(async () => {- const score = await getScoreById(projectId, scoreId);+ const score = await getScoreById({ projectId, scoreId });expect(score).toBeDefined();expect(score!.id).toBe(scoreId);expect(JSON.stringify(score!.metadata)).toBe(@@ -658,7 +661,7 @@ describe("/api/public/ingestion API Endpoint", () => {expect(response.status).toBe(207);await waitForExpect(async () => {- const score = await getScoreById(projectId, scoreId);+ const score = await getScoreById({ projectId, scoreId });expect(score).toBeDefined();expect(score!.id).toBe(scoreId);expect(score!.projectId).toBe(projectId);diff --git a/web/src/__tests__/async/repositories/score-repository.servertest.ts b/web/src/__tests__/async/repositories/score-repository.servertest.tsindex 382d91e91f..015fb26da4 100644--- a/web/src/__tests__/async/repositories/score-repository.servertest.ts+++ b/web/src/__tests__/async/repositories/score-repository.servertest.ts@@ -1,8 +1,6 @@-import { createScoresCh } from "@langfuse/shared/src/server";+import { createScoresCh, getScoreById } from "@langfuse/shared/src/server";import { pruneDatabase } from "@/src/__tests__/test-utils";-import { getScoreById } from "@langfuse/shared/src/server";import { v4 } from "uuid";-const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";describe("Clickhouse Scores Repository Test", () => {@@ -11,14 +9,17 @@ describe("Clickhouse Scores Repository Test", () => {});it("should return null if no scores are found", async () => {- const result = await getScoreById(projectId, v4());+ const result = await getScoreById({+ projectId,+ scoreId: v4(),+ });expect(result).toBeUndefined();});it("should return a score if it exists", async () => {const scoreId = v4();- // Assuming createScore is a helper function to insert a score into the database+ // Assuming createTraceScore is a helper function to insert a score into the databaseconst score = {id: scoreId,project_id: projectId,@@ -31,11 +32,15 @@ describe("Clickhouse Scores Repository Test", () => {updated_at: Date.now(),event_ts: Date.now(),is_deleted: 0,+ environment: "default",};await createScoresCh([score]);- const result = await getScoreById(projectId, scoreId);+ const result = await getScoreById({+ projectId,+ scoreId,+ });expect(result).not.toBeNull();if (!result) {return;diff --git a/web/src/__tests__/async/scores-api.servertest.ts b/web/src/__tests__/async/scores-api-v1.servertest.tssimilarity index 91%rename from web/src/__tests__/async/scores-api.servertest.tsrename to web/src/__tests__/async/scores-api-v1.servertest.tsindex f33ecd5cf7..b83470e1cd 100644--- a/web/src/__tests__/async/scores-api.servertest.ts+++ b/web/src/__tests__/async/scores-api-v1.servertest.ts@@ -1,7 +1,8 @@import {createObservation,- createScore,+ createTraceScore,createTrace,+ createSessionScore,getScoresByIds,} from "@langfuse/shared/src/server";import {@@ -12,9 +13,9 @@ import {} from "@langfuse/shared/src/server";import { makeZodVerifiedAPICall } from "@/src/__tests__/test-utils";import {- DeleteScoreResponse,- GetScoreResponse,- GetScoresResponse,+ DeleteScoreResponseV1,+ GetScoreResponseV1,+ GetScoresResponseV1,} from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";import { v4 } from "uuid";@@ -28,7 +29,7 @@ describe("/api/public/scores API Endpoint", () => {const scoreId = v4();const traceId = v4();- const score = createScore({+ const score = createTraceScore({id: scoreId,environment: "default",project_id: projectId,@@ -50,7 +51,7 @@ describe("/api/public/scores API Endpoint", () => {await createScoresCh([score]);const getScore = await makeZodVerifiedAPICall(- GetScoreResponse,+ GetScoreResponseV1,"GET",`/api/public/scores/${scoreId}`,undefined,@@ -84,7 +85,7 @@ describe("/api/public/scores API Endpoint", () => {const minimalScoreId = v4();- const score = createScore({+ const score = createTraceScore({id: minimalScoreId,project_id: projectId,trace_id: minimalTraceId,@@ -97,7 +98,7 @@ describe("/api/public/scores API Endpoint", () => {await createScoresCh([score]);const fetchedScore = await makeZodVerifiedAPICall(- GetScoreResponse,+ GetScoreResponseV1,"GET",`/api/public/scores/${minimalScoreId}`,undefined,@@ -115,7 +116,7 @@ describe("/api/public/scores API Endpoint", () => {const scoreId = v4();- const score = createScore({+ const score = createTraceScore({id: scoreId,project_id: projectId,});@@ -123,7 +124,7 @@ describe("/api/public/scores API Endpoint", () => {// Whenconst deleteResponse = await makeZodVerifiedAPICall(- DeleteScoreResponse,+ DeleteScoreResponseV1,"DELETE",`/api/public/scores/${scoreId}`,undefined,@@ -154,7 +155,7 @@ describe("/api/public/scores API Endpoint", () => {const scoreId = v4();- const score = createScore({+ const score = createTraceScore({id: scoreId,project_id: projectId,trace_id: traceId,@@ -169,7 +170,7 @@ describe("/api/public/scores API Endpoint", () => {await createScoresCh([score]);const fetchedScore = await makeZodVerifiedAPICall(- GetScoreResponse,+ GetScoreResponseV1,"GET",`/api/public/scores/${scoreId}`,undefined,@@ -201,7 +202,7 @@ describe("/api/public/scores API Endpoint", () => {const scoreId = v4();- const score = createScore({+ const score = createTraceScore({id: scoreId,project_id: projectId,trace_id: traceId,@@ -223,7 +224,7 @@ describe("/api/public/scores API Endpoint", () => {await createScoresCh([updatedScore]);const fetchedScore = await makeZodVerifiedAPICall(- GetScoreResponse,+ GetScoreResponseV1,"GET",`/api/public/scores/${scoreId}`,undefined,@@ -272,7 +273,7 @@ describe("/api/public/scores API Endpoint", () => {for (let i = 0; i < totalScores; i++) {scores.push(- createScore({+ createTraceScore({id: v4(),project_id: projectId,trace_id: traceId,@@ -295,7 +296,7 @@ describe("/api/public/scores API Endpoint", () => {// Fetch all pages and verify count matcheswhile (hasMorePages) {const response = await makeZodVerifiedAPICall(- GetScoresResponse,+ GetScoresResponseV1,"GET",`/api/public/scores?limit=${pageSize}&page=${page}`,undefined,@@ -345,11 +346,14 @@ describe("/api/public/scores API Endpoint", () => {const traceId_2 = v4();const traceId_3 = v4();const generationId = v4();+ const sessionId = v4();const scoreId_1 = v4();const scoreId_2 = v4();const scoreId_3 = v4();const scoreId_4 = v4();const scoreId_5 = v4();+ const scoreId_6 = v4();+ const scoreId_7 = v4();let authentication: string;let newProjectId: string;@@ -401,7 +405,7 @@ describe("/api/public/scores API Endpoint", () => {configId = config.id;- const score1 = createScore({+ const score1 = createTraceScore({id: scoreId_1,project_id: newProjectId,trace_id: traceId,@@ -413,7 +417,7 @@ describe("/api/public/scores API Endpoint", () => {comment: "comment",});- const score2 = createScore({+ const score2 = createTraceScore({id: scoreId_2,project_id: newProjectId,trace_id: traceId,@@ -424,7 +428,7 @@ describe("/api/public/scores API Endpoint", () => {comment: "comment",});- const score3 = createScore({+ const score3 = createTraceScore({id: scoreId_3,project_id: newProjectId,trace_id: traceId,@@ -435,7 +439,7 @@ describe("/api/public/scores API Endpoint", () => {comment: "comment",});- const score4 = createScore({+ const score4 = createTraceScore({id: scoreId_4,project_id: newProjectId,trace_id: traceId_2,@@ -446,7 +450,7 @@ describe("/api/public/scores API Endpoint", () => {comment: "comment",});- const score5 = createScore({+ const score5 = createTraceScore({id: scoreId_5,project_id: newProjectId,trace_id: traceId_3,@@ -458,14 +462,40 @@ describe("/api/public/scores API Endpoint", () => {environment: "production",});- await createScoresCh([score1, score2, score3, score4, score5]);+ const sessionScore1 = createSessionScore({+ id: scoreId_6,+ project_id: newProjectId,+ session_id: sessionId,+ name: scoreName,+ value: 100.5,+ data_type: "NUMERIC",+ });++ const sessionScore2 = createSessionScore({+ id: scoreId_7,+ project_id: newProjectId,+ session_id: sessionId,+ name: "session-score-name",+ value: 100.5,+ data_type: "NUMERIC",+ });++ await createScoresCh([+ score1,+ score2,+ score3,+ score4,+ score5,+ sessionScore1,+ sessionScore2,+ ]);});- it("get all scores", async () => {+ it("get all trace scores", async () => {const getAllScore = await makeZodVerifiedAPICall(- GetScoresResponse,+ GetScoresResponseV1,"GET",- `/api/public/scores?${queryUserName}`,+ `/api/public/scores`,undefined,authentication,);@@ -473,20 +503,19 @@ describe("/api/public/scores API Endpoint", () => {expect(getAllScore.body.meta).toMatchObject({page: 1,limit: 50,- totalItems: 3,+ totalItems: 5, // 7 scores in total, but only 5 are trace scorestotalPages: 1,});for (const val of getAllScore.body.data) {expect(val).toMatchObject({- traceId: traceId,- observationId: generationId,+ traceId: expect.any(String),});}});it("get all scores for config", async () => {const getAllScore = await makeZodVerifiedAPICall(- GetScoresResponse,+ GetScoresResponseV1,"GET",`/api/public/scores?configId=${configId}`,undefined,@@ -511,7 +540,7 @@ describe("/api/public/scores API Endpoint", () => {it("get all scores for numeric data type", async () => {const getAllScore = await makeZodVerifiedAPICall(- GetScoresResponse,+ GetScoresResponseV1,"GET",`/api/public/scores?dataType=NUMERIC`,undefined,@@ -536,7 +565,7 @@ describe("/api/public/scores API Endpoint", () => {it("get all scores for trace tag 'prod'", async () => {const getAllScore = await makeZodVerifiedAPICall(- GetScoresResponse,+ GetScoresResponseV1,"GET",`/api/public/scores?traceTags=prod`,undefined,@@ -560,7 +589,7 @@ describe("/api/public/scores API Endpoint", () => {it("get all scores for environment 'production'", async () => {const getAllScore = await makeZodVerifiedAPICall(- GetScoresResponse,+ GetScoresResponseV1,"GET",`/api/public/scores?environment=production`,undefined,@@ -589,7 +618,7 @@ describe("/api/public/scores API Endpoint", () => {it("get all scores for trace tags 'staging' and 'dev'", async () => {const getAllScore = await makeZodVerifiedAPICall(- GetScoresResponse,+ GetScoresResponseV1,"GET",`/api/public/scores?traceTags=${["staging", "dev"]}`,undefined,@@ -620,7 +649,7 @@ describe("/api/public/scores API Endpoint", () => {beforeEach(async () => {queueId = v4();- const score = createScore({+ const score = createTraceScore({id: v4(),project_id: newProjectId,trace_id: traceId,@@ -631,7 +660,7 @@ describe("/api/public/scores API Endpoint", () => {observation_id: generationId,queue_id: queueId,});- const score2 = createScore({+ const score2 = createTraceScore({id: v4(),project_id: newProjectId,trace_id: traceId,@@ -648,7 +677,7 @@ describe("/api/public/scores API Endpoint", () => {it("get all scores for queueId", async () => {const getAllScore = await makeZodVerifiedAPICall(- GetScoresResponse,+ GetScoresResponseV1,"GET",`/api/public/scores?queueId=${queueId}`,undefined,@@ -676,7 +705,7 @@ describe("/api/public/scores API Endpoint", () => {describe("should use score operators correctly", () => {it("test only operator", async () => {const getScore = await makeZodVerifiedAPICall(- GetScoresResponse,+ GetScoresResponseV1,"GET",`/api/public/scores?${queryUserName}&operator=<`,undefined,@@ -693,7 +722,7 @@ describe("/api/public/scores API Endpoint", () => {it("test only value", async () => {const getScore = await makeZodVerifiedAPICall(- GetScoresResponse,+ GetScoresResponseV1,"GET",`/api/public/scores?${queryUserName}&value=0.8`,undefined,@@ -710,7 +739,7 @@ describe("/api/public/scores API Endpoint", () => {it("test operator <", async () => {const getScore = await makeZodVerifiedAPICall(- GetScoresResponse,+ GetScoresResponseV1,"GET",`/api/public/scores?${queryUserName}&operator=<&value=50`,undefined,@@ -734,7 +763,7 @@ describe("/api/public/scores API Endpoint", () => {it("test operator >", async () => {const getScore = await makeZodVerifiedAPICall(- GetScoresResponse,+ GetScoresResponseV1,"GET",`/api/public/scores?${queryUserName}&operator=>&value=100`,undefined,@@ -758,7 +787,7 @@ describe("/api/public/scores API Endpoint", () => {it("test operator <=", async () => {const getScore = await makeZodVerifiedAPICall(- GetScoresResponse,+ GetScoresResponseV1,"GET",`/api/public/scores?${queryUserName}&operator=<=&value=50.5`,undefined,@@ -789,7 +818,7 @@ describe("/api/public/scores API Endpoint", () => {it("test operator >=", async () => {const getScore = await makeZodVerifiedAPICall(- GetScoresResponse,+ GetScoresResponseV1,"GET",`/api/public/scores?${queryUserName}&operator=>=&value=50.5`,undefined,@@ -820,7 +849,7 @@ describe("/api/public/scores API Endpoint", () => {it("test operator !=", async () => {const getScore = await makeZodVerifiedAPICall(- GetScoresResponse,+ GetScoresResponseV1,"GET",`/api/public/scores?${queryUserName}&operator=!=&value=50.5`,undefined,@@ -851,7 +880,7 @@ describe("/api/public/scores API Endpoint", () => {it("test operator =", async () => {const getScore = await makeZodVerifiedAPICall(- GetScoresResponse,+ GetScoresResponseV1,"GET",`/api/public/scores?${queryUserName}&operator==&value=50.5`,undefined,@@ -914,7 +943,7 @@ describe("/api/public/scores API Endpoint", () => {it("should filter scores by score IDs", async () => {const getScore = await makeZodVerifiedAPICall(- GetScoresResponse,+ GetScoresResponseV1,"GET",`/api/public/scores?scoreIds=${scoreId_1},${scoreId_2}`,undefined,diff --git a/web/src/__tests__/async/scores-api-v2.servertest.ts b/web/src/__tests__/async/scores-api-v2.servertest.tsnew file mode 100644index 0000000000..883a0fe9de--- /dev/null+++ b/web/src/__tests__/async/scores-api-v2.servertest.ts@@ -0,0 +1,792 @@+import {+ createObservation,+ createTraceScore,+ createTrace,+ createSessionScore,+} from "@langfuse/shared/src/server";+import {+ createObservationsCh,+ createScoresCh,+ createTracesCh,+ createOrgProjectAndApiKey,+} from "@langfuse/shared/src/server";+import { makeZodVerifiedAPICall } from "@/src/__tests__/test-utils";+import { GetScoreResponseV2, GetScoresResponseV2 } from "@langfuse/shared";+import { prisma } from "@langfuse/shared/src/db";+import { v4 } from "uuid";+import { z } from "zod";++describe("/api/public/v2/scores API Endpoint", () => {+ describe("GET /api/public/v2/scores/:scoreId", () => {+ it("should GET a trace score", async () => {+ const { projectId: projectId, auth } = await createOrgProjectAndApiKey();++ const scoreId = v4();+ const traceId = v4();+ const score = createTraceScore({+ id: scoreId,+ project_id: projectId,+ trace_id: traceId,+ name: "Test Score",+ timestamp: Date.now(),+ observation_id: v4(),+ value: 100.5,+ source: "API",+ comment: "comment",+ data_type: "NUMERIC" as const,+ created_at: Date.now(),+ updated_at: Date.now(),+ event_ts: Date.now(),+ is_deleted: 0,+ });++ await createScoresCh([score]);++ const getScore = await makeZodVerifiedAPICall(+ GetScoreResponseV2,+ "GET",+ `/api/public/v2/scores/${scoreId}`,+ undefined,+ auth,+ );++ expect(getScore.status).toBe(200);+ expect(getScore.body).toMatchObject({+ id: scoreId,+ name: "Test Score",+ value: 100.5,+ comment: "comment",+ source: "API",+ traceId,+ observationId: score.observation_id,+ dataType: "NUMERIC",+ });+ });++ it("should GET score with minimal score data and minimal trace data", async () => {+ const { projectId, auth } = await createOrgProjectAndApiKey();++ const minimalTraceId = v4();++ const trace = createTrace({+ id: minimalTraceId,+ project_id: projectId,+ });+ await createTracesCh([trace]);++ const minimalScoreId = v4();++ const score = createTraceScore({+ id: minimalScoreId,+ project_id: projectId,+ trace_id: minimalTraceId,+ name: "score-name",+ value: 100.5,+ source: "API",+ comment: null,+ observation_id: null,+ });+ await createScoresCh([score]);++ const fetchedScore = await makeZodVerifiedAPICall(+ GetScoreResponseV2,+ "GET",+ `/api/public/v2/scores/${minimalScoreId}`,+ undefined,+ auth,+ );++ expect(fetchedScore.status).toBe(200);+ });++ it("should GET a session score", async () => {+ const { projectId: projectId, auth } = await createOrgProjectAndApiKey();++ const scoreId = v4();+ const sessionId = v4();+ const score = createSessionScore({+ id: scoreId,+ project_id: projectId,+ session_id: sessionId,+ name: "Test Score",+ timestamp: Date.now(),+ value: 100.5,+ source: "API",+ comment: "comment",+ data_type: "NUMERIC" as const,+ created_at: Date.now(),+ updated_at: Date.now(),+ event_ts: Date.now(),+ is_deleted: 0,+ });++ await createScoresCh([score]);++ const getScore = await makeZodVerifiedAPICall(+ GetScoreResponseV2,+ "GET",+ `/api/public/v2/scores/${scoreId}`,+ undefined,+ auth,+ );++ expect(getScore.status).toBe(200);+ expect(getScore.body).toMatchObject({+ id: scoreId,+ name: "Test Score",+ value: 100.5,+ comment: "comment",+ source: "API",+ sessionId,+ observationId: null,+ traceId: null,+ dataType: "NUMERIC",+ });+ });+ });++ describe("GET /api/public/scores", () => {+ describe("should Filter scores", () => {+ let configId = "";+ const userId = "user-name";+ const traceTags = ["prod", "test"];+ const traceTags_2 = ["staging", "dev"];+ const scoreName = "score-name";+ const queryUserName = `userId=${userId}&name=${scoreName}`;+ const traceId = v4();+ const traceId_2 = v4();+ const traceId_3 = v4();+ const generationId = v4();+ const sessionId = v4();+ const scoreId_1 = v4();+ const scoreId_2 = v4();+ const scoreId_3 = v4();+ const scoreId_4 = v4();+ const scoreId_5 = v4();+ const scoreId_6 = v4();+ const scoreId_7 = v4();+ let authentication: string;+ let newProjectId: string;++ beforeEach(async () => {+ const { projectId, auth } = await createOrgProjectAndApiKey();+ authentication = auth;+ newProjectId = projectId;++ const trace = createTrace({+ id: traceId,+ project_id: newProjectId,+ user_id: userId,+ tags: traceTags,+ });++ const trace_2 = createTrace({+ id: traceId_2,+ project_id: newProjectId,+ user_id: userId,+ tags: traceTags_2,+ });++ const trace_3 = createTrace({+ id: traceId_3,+ project_id: newProjectId,+ user_id: userId,+ tags: ["staging"],+ environment: "production",+ });++ await createTracesCh([trace, trace_2, trace_3]);++ const generation = createObservation({+ id: generationId,+ project_id: newProjectId,+ type: "GENERATION",+ });++ await createObservationsCh([generation]);++ const config = await prisma.scoreConfig.create({+ data: {+ name: scoreName,+ dataType: "NUMERIC",+ maxValue: 100,+ projectId: newProjectId,+ },+ });++ configId = config.id;++ const score1 = createTraceScore({+ id: scoreId_1,+ project_id: newProjectId,+ trace_id: traceId,+ name: scoreName,+ value: 10.5,+ data_type: "NUMERIC",+ observation_id: generationId,+ config_id: config.id,+ comment: "comment",+ });++ const score2 = createTraceScore({+ id: scoreId_2,+ project_id: newProjectId,+ trace_id: traceId,+ name: scoreName,+ value: 50.5,+ data_type: "NUMERIC",+ observation_id: generationId,+ comment: "comment",+ });++ const score3 = createTraceScore({+ id: scoreId_3,+ project_id: newProjectId,+ trace_id: traceId,+ name: scoreName,+ value: 100.8,+ data_type: "NUMERIC",+ observation_id: generationId,+ comment: "comment",+ });++ const score4 = createTraceScore({+ id: scoreId_4,+ project_id: newProjectId,+ trace_id: traceId_2,+ name: "other-score-name",+ value: 0,+ string_value: "best",+ data_type: "CATEGORICAL",+ comment: "comment",+ });++ const score5 = createTraceScore({+ id: scoreId_5,+ project_id: newProjectId,+ trace_id: traceId_3,+ name: "other-score-name",+ value: 0,+ data_type: "CATEGORICAL",+ string_value: "test",+ comment: "comment",+ environment: "production",+ });++ const sessionScore1 = createSessionScore({+ id: scoreId_6,+ project_id: newProjectId,+ session_id: sessionId,+ name: scoreName,+ value: 100.5,+ data_type: "NUMERIC",+ });++ const sessionScore2 = createSessionScore({+ id: scoreId_7,+ project_id: newProjectId,+ session_id: sessionId,+ name: "session-score-name",+ value: 100.5,+ data_type: "NUMERIC",+ });++ await createScoresCh([+ score1,+ score2,+ score3,+ score4,+ score5,+ sessionScore1,+ sessionScore2,+ ]);+ });++ it("get all scores", async () => {+ const getAllScore = await makeZodVerifiedAPICall(+ GetScoresResponseV2,+ "GET",+ `/api/public/v2/scores`,+ undefined,+ authentication,+ );+ expect(getAllScore.status).toBe(200);+ expect(getAllScore.body.meta).toMatchObject({+ page: 1,+ limit: 50,+ totalItems: 7,+ totalPages: 1,+ });+ for (const val of getAllScore.body.data) {+ if (val.traceId) {+ expect(val).toMatchObject({+ sessionId: null,+ });+ } else {+ expect(val).toMatchObject({+ sessionId: sessionId,+ trace: null,+ });+ }+ }+ });++ it("get all scores for config", async () => {+ const getAllScore = await makeZodVerifiedAPICall(+ GetScoresResponseV2,+ "GET",+ `/api/public/v2/scores?configId=${configId}`,+ undefined,+ authentication,+ );++ expect(getAllScore.status).toBe(200);+ expect(getAllScore.body.meta).toMatchObject({+ page: 1,+ limit: 50,+ totalItems: 1,+ totalPages: 1,+ });+ for (const val of getAllScore.body.data) {+ expect(val).toMatchObject({+ traceId: traceId,+ observationId: generationId,+ configId: configId,+ });+ }+ });++ it("get all scores for numeric data type", async () => {+ const getAllScore = await makeZodVerifiedAPICall(+ GetScoresResponseV2,+ "GET",+ `/api/public/v2/scores?dataType=NUMERIC`,+ undefined,+ authentication,+ );++ expect(getAllScore.status).toBe(200);+ expect(getAllScore.body.meta).toMatchObject({+ page: 1,+ limit: 50,+ totalItems: 5,+ totalPages: 1,+ });+ for (const val of getAllScore.body.data) {+ expect(val).toMatchObject({+ dataType: "NUMERIC",+ });+ }+ });++ it("get all scores for trace tag 'prod'", async () => {+ const getAllScore = await makeZodVerifiedAPICall(+ GetScoresResponseV2,+ "GET",+ `/api/public/v2/scores?traceTags=prod`,+ undefined,+ authentication,+ );++ expect(getAllScore.status).toBe(200);+ expect(getAllScore.body.meta).toMatchObject({+ page: 1,+ limit: 50,+ totalItems: 3,+ totalPages: 1,+ });+ for (const val of getAllScore.body.data) {+ expect(val).toMatchObject({+ traceId: traceId,+ trace: { tags: ["prod", "test"], userId: "user-name" },+ });+ }+ });++ it("get all scores for environment 'production'", async () => {+ const getAllScore = await makeZodVerifiedAPICall(+ GetScoresResponseV2,+ "GET",+ `/api/public/v2/scores?environment=production`,+ undefined,+ authentication,+ );++ expect(getAllScore.status).toBe(200);+ expect(getAllScore.body.meta).toMatchObject({+ page: 1,+ limit: 50,+ totalItems: 1,+ totalPages: 1,+ });+ for (const val of getAllScore.body.data) {+ expect(val).toMatchObject({+ traceId: traceId_3,+ trace: {+ userId: "user-name",+ tags: ["staging"],+ environment: "production",+ },+ environment: "production",+ });+ }+ });++ it("get all scores for trace tags 'staging' and 'dev'", async () => {+ const getAllScore = await makeZodVerifiedAPICall(+ GetScoresResponseV2,+ "GET",+ `/api/public/v2/scores?traceTags=${["staging", "dev"]}`,+ undefined,+ authentication,+ );++ expect(getAllScore.status).toBe(200);+ expect(getAllScore.body.meta).toMatchObject({+ page: 1,+ limit: 50,+ totalItems: 1,+ totalPages: 1,+ });+ for (const val of getAllScore.body.data) {+ expect(val).toMatchObject({+ traceId: traceId_2,+ trace: {+ tags: expect.arrayContaining(["dev", "staging"]),+ userId: "user-name",+ },+ });+ }+ });++ describe("should Filter scores by queueId", () => {+ describe("queueId filtering", () => {+ let queueId: string;++ beforeEach(async () => {+ queueId = v4();+ const score = createTraceScore({+ id: v4(),+ project_id: newProjectId,+ trace_id: traceId,+ name: "score-name",+ value: 100.5,+ source: "ANNOTATION",+ comment: "comment",+ observation_id: generationId,+ queue_id: queueId,+ });+ const score2 = createTraceScore({+ id: v4(),+ project_id: newProjectId,+ trace_id: traceId,+ name: "score-name",+ value: 75.0,+ source: "ANNOTATION",+ comment: "comment",+ observation_id: generationId,+ queue_id: queueId,+ });++ await createScoresCh([score, score2]);+ });++ it("get all scores for queueId", async () => {+ const getAllScore = await makeZodVerifiedAPICall(+ GetScoresResponseV2,+ "GET",+ `/api/public/v2/scores?queueId=${queueId}`,+ undefined,+ authentication,+ );+ expect(getAllScore.status).toBe(200);+ expect(getAllScore.body.meta).toMatchObject({+ page: 1,+ limit: 50,+ totalItems: 2,+ totalPages: 1,+ });+ for (const val of getAllScore.body.data) {+ expect(val).toMatchObject({+ traceId: traceId,+ observationId: generationId,+ queueId: queueId,+ source: "ANNOTATION",+ });+ }+ });+ });+ });++ describe("should use score operators correctly", () => {+ it("test only operator", async () => {+ const getScore = await makeZodVerifiedAPICall(+ GetScoresResponseV2,+ "GET",+ `/api/public/v2/scores?${queryUserName}&operator=<`,+ undefined,+ authentication,+ );+ expect(getScore.status).toBe(200);+ expect(getScore.body.meta).toMatchObject({+ page: 1,+ limit: 50,+ totalItems: 3,+ totalPages: 1,+ });+ });++ it("test only value", async () => {+ const getScore = await makeZodVerifiedAPICall(+ GetScoresResponseV2,+ "GET",+ `/api/public/v2/scores?${queryUserName}&value=0.8`,+ undefined,+ authentication,+ );+ expect(getScore.status).toBe(200);+ expect(getScore.body.meta).toMatchObject({+ page: 1,+ limit: 50,+ totalItems: 3,+ totalPages: 1,+ });+ });++ it("test operator <", async () => {+ const getScore = await makeZodVerifiedAPICall(+ GetScoresResponseV2,+ "GET",+ `/api/public/v2/scores?${queryUserName}&operator=<&value=50`,+ undefined,+ authentication,+ );+ expect(getScore.status).toBe(200);+ expect(getScore.body.meta).toMatchObject({+ page: 1,+ limit: 50,+ totalItems: 1,+ totalPages: 1,+ });+ expect(getScore.body.data).toMatchObject([+ {+ id: scoreId_1,+ name: scoreName,+ value: 10.5,+ },+ ]);+ });++ it("test operator >", async () => {+ const getScore = await makeZodVerifiedAPICall(+ GetScoresResponseV2,+ "GET",+ `/api/public/v2/scores?${queryUserName}&operator=>&value=100`,+ undefined,+ authentication,+ );+ expect(getScore.status).toBe(200);+ expect(getScore.body.meta).toMatchObject({+ page: 1,+ limit: 50,+ totalItems: 1,+ totalPages: 1,+ });+ expect(getScore.body.data).toMatchObject([+ {+ id: scoreId_3,+ name: scoreName,+ value: 100.8,+ },+ ]);+ });++ it("test operator <=", async () => {+ const getScore = await makeZodVerifiedAPICall(+ GetScoresResponseV2,+ "GET",+ `/api/public/v2/scores?${queryUserName}&operator=<=&value=50.5`,+ undefined,+ authentication,+ );+ expect(getScore.status).toBe(200);+ expect(getScore.body.meta).toMatchObject({+ page: 1,+ limit: 50,+ totalItems: 2,+ totalPages: 1,+ });+ expect(getScore.body.data).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: scoreId_2,+ name: scoreName,+ value: 50.5,+ }),+ expect.objectContaining({+ id: scoreId_1,+ name: scoreName,+ value: 10.5,+ }),+ ]),+ );+ });++ it("test operator >=", async () => {+ const getScore = await makeZodVerifiedAPICall(+ GetScoresResponseV2,+ "GET",+ `/api/public/v2/scores?${queryUserName}&operator=>=&value=50.5`,+ undefined,+ authentication,+ );+ expect(getScore.status).toBe(200);+ expect(getScore.body.meta).toMatchObject({+ page: 1,+ limit: 50,+ totalItems: 2,+ totalPages: 1,+ });+ expect(getScore.body.data).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: scoreId_3,+ name: scoreName,+ value: 100.8,+ }),+ expect.objectContaining({+ id: scoreId_2,+ name: scoreName,+ value: 50.5,+ }),+ ]),+ );+ });++ it("test operator !=", async () => {+ const getScore = await makeZodVerifiedAPICall(+ GetScoresResponseV2,+ "GET",+ `/api/public/v2/scores?${queryUserName}&operator=!=&value=50.5`,+ undefined,+ authentication,+ );+ expect(getScore.status).toBe(200);+ expect(getScore.body.meta).toMatchObject({+ page: 1,+ limit: 50,+ totalItems: 2,+ totalPages: 1,+ });+ expect(getScore.body.data).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: scoreId_3,+ name: scoreName,+ value: 100.8,+ }),+ expect.objectContaining({+ id: scoreId_1,+ name: scoreName,+ value: 10.5,+ }),+ ]),+ );+ });++ it("test operator =", async () => {+ const getScore = await makeZodVerifiedAPICall(+ GetScoresResponseV2,+ "GET",+ `/api/public/v2/scores?${queryUserName}&operator==&value=50.5`,+ undefined,+ authentication,+ );+ expect(getScore.status).toBe(200);+ expect(getScore.body.meta).toMatchObject({+ page: 1,+ limit: 50,+ totalItems: 1,+ totalPages: 1,+ });+ expect(getScore.body.data).toMatchObject([+ {+ id: scoreId_2,+ name: scoreName,+ value: 50.5,+ },+ ]);+ });++ it("test invalid operator", async () => {+ try {+ await makeZodVerifiedAPICall(+ z.object({+ message: z.string(),+ error: z.array(z.object({})),+ }),+ "GET",+ `/api/public/v2/scores?${queryUserName}&operator=op&value=50.5`,+ undefined,+ authentication,+ );+ } catch (error) {+ expect((error as Error).message).toBe(+ `API call did not return 200, returned status 400, body {\"message\":\"Invalid request data\",\"error\":[{\"received\":\"op\",\"code\":\"invalid_enum_value\",\"options\":[\"<\",\">\",\"<=\",\">=\",\"!=\",\"=\"],\"path\":[\"operator\"],\"message\":\"Invalid enum value. Expected '<' | '>' | '<=' | '>=' | '!=' | '=', received 'op'\"}]}`,+ );+ }+ });++ it("test invalid value", async () => {+ try {+ await makeZodVerifiedAPICall(+ z.object({+ message: z.string(),+ error: z.array(z.object({})),+ }),+ "GET",+ `/api/public/v2/scores?${queryUserName}&operator=<&value=myvalue`,+ undefined,+ authentication,+ );+ } catch (error) {+ expect((error as Error).message).toBe(+ 'API call did not return 200, returned status 400, body {"message":"Invalid request data","error":[{"code":"invalid_type","expected":"number","received":"nan","path":["value"],"message":"Expected number, received nan"}]}',+ );+ }+ });+ });++ it("should filter scores by score IDs", async () => {+ const getScore = await makeZodVerifiedAPICall(+ GetScoresResponseV2,+ "GET",+ `/api/public/v2/scores?scoreIds=${scoreId_1},${scoreId_2}`,+ undefined,+ authentication,+ );+ expect(getScore.status).toBe(200);+ expect(getScore.body.meta).toMatchObject({+ page: 1,+ limit: 50,+ totalItems: 2,+ totalPages: 1,+ });+ expect(getScore.body.data).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: scoreId_2,+ name: scoreName,+ value: 50.5,+ }),+ expect.objectContaining({+ id: scoreId_1,+ name: scoreName,+ value: 10.5,+ }),+ ]),+ );+ });+ });+ });+});diff --git a/web/src/__tests__/async/scores-trpc.servertest.ts b/web/src/__tests__/async/scores-trpc.servertest.tsindex 973ec945e2..ae31f3343c 100644--- a/web/src/__tests__/async/scores-trpc.servertest.ts+++ b/web/src/__tests__/async/scores-trpc.servertest.ts@@ -27,7 +27,7 @@ import { prisma } from "@langfuse/shared/src/db";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";import {- createScore,+ createTraceScore,createScoresCh,ScoreDeleteQueue,BatchActionQueue,@@ -79,7 +79,7 @@ describe("scores trpc", () => {describe("scores.deleteMany", () => {it("should delete scores by ids", async () => {// Setup- const createdScore = createScore({+ const createdScore = createTraceScore({project_id: projectId,});await createScoresCh([createdScore]);@@ -108,7 +108,7 @@ describe("scores trpc", () => {it("should delete scores via batch query", async () => {// Setupconst scoreName = randomUUID();- const createdScore = createScore({+ const createdScore = createTraceScore({project_id: projectId,name: scoreName,});diff --git a/web/src/__tests__/async/traces-api.servertest.ts b/web/src/__tests__/async/traces-api.servertest.tsindex 300581ba53..8abd061065 100644--- a/web/src/__tests__/async/traces-api.servertest.ts+++ b/web/src/__tests__/async/traces-api.servertest.ts@@ -1,6 +1,7 @@import {createObservation,- createScore,+ createTraceScore,+ createSessionScore,createScoresCh,createTrace,getTraceById,@@ -218,13 +219,13 @@ describe("/api/public/traces API Endpoint", () => {]);await createScoresCh([- createScore({+ createTraceScore({trace_id: traceId,environment,project_id: projectId,}),// Create one that does not belong to the same environment- createScore({+ createTraceScore({trace_id: traceId,environment: "default",project_id: projectId,@@ -245,6 +246,67 @@ describe("/api/public/traces API Endpoint", () => {expect(trace.scores.length).toBe(1);});+ it("should fetch traces with trace scores only", async () => {+ const environment = randomUUID();+ const traceId = randomUUID();+ const createdTrace = createTrace({+ id: traceId,+ name: "trace-name",+ project_id: projectId,+ metadata: { key: "value" },+ environment,+ });++ await createTracesCh([createdTrace]);++ await createObservationsCh([+ createObservation({+ trace_id: traceId,+ environment,+ project_id: projectId,+ }),+ // Create one that does not belong to the same environment+ createObservation({+ trace_id: traceId,+ environment: "default",+ project_id: projectId,+ }),+ ]);++ await createScoresCh([+ createTraceScore({+ trace_id: traceId,+ environment,+ project_id: projectId,+ }),+ // Create one that does not belong to the same environment+ createTraceScore({+ trace_id: traceId,+ environment: "default",+ project_id: projectId,+ }),+ createSessionScore({+ session_id: randomUUID(),+ environment,+ project_id: projectId,+ }),+ ]);++ const traces = await makeZodVerifiedAPICall(+ GetTracesV1Response,+ "GET",+ `/api/public/traces?environment=${environment}`,+ );++ expect(traces.body.meta.totalItems).toBe(1);+ expect(traces.body.data.length).toBe(1);+ const trace = traces.body.data[0];+ expect(trace.projectId).toBe(projectId);+ expect(trace.observations.length).toBe(1);+ // Despite having the correct environment, the session score is not included in the response+ expect(trace.scores.length).toBe(1);+ });+it("should fetch all traces filtered by a tag", async () => {const tag = randomUUID();const createdTrace = createTrace({@@ -345,6 +407,16 @@ describe("/api/public/traces API Endpoint", () => {expect(response.status).toBe(400);});+ it("should return 400 error when page=0", async () => {+ const response = await makeZodVerifiedAPICallSilent(+ GetTracesV1Response,+ "GET",+ "/api/public/traces?page=0&limit=10",+ );++ expect(response.status).toBe(400);+ });+it("LFE-3699: should fetch a single trace with unescaped metadata via traces list", async () => {const traceId = randomUUID();const trace = createTrace({diff --git a/web/src/__tests__/queryBuilder.servertest.ts b/web/src/__tests__/queryBuilder.servertest.tsindex 1639e4df1c..60816c8089 100644--- a/web/src/__tests__/queryBuilder.servertest.ts+++ b/web/src/__tests__/queryBuilder.servertest.ts@@ -6,7 +6,7 @@ import {createObservation,createTracesCh,createObservationsCh,- createScore,+ createTraceScore,createScoresCh,} from "@langfuse/shared/src/server";import { randomUUID } from "crypto";@@ -291,7 +291,7 @@ describe("queryBuilder", () => {for (const data of scoresData) {scores.push(- createScore({+ createTraceScore({project_id: projectId,trace_id: data.traceId,observation_id: data.observationId,diff --git a/web/src/components/grouped-score-badge.tsx b/web/src/components/grouped-score-badge.tsxindex fb6f3c620b..81ceb0f922 100644--- a/web/src/components/grouped-score-badge.tsx+++ b/web/src/components/grouped-score-badge.tsx@@ -4,12 +4,11 @@ import {HoverCardContent,HoverCardTrigger,} from "@/src/components/ui/hover-card";+import { type LastUserScore, type APIScoreV2 } from "@langfuse/shared";import { BracesIcon, MessageCircleMoreIcon } from "lucide-react";--import { type APIScore, type LastUserScore } from "@langfuse/shared";import { JSONView } from "@/src/components/ui/CodeJsonViewer";-const partitionScores = <T extends APIScore | LastUserScore>(+const partitionScores = <T extends APIScoreV2 | LastUserScore>(scores: Record<string, T[]>,maxVisible?: number,) => {@@ -23,7 +22,7 @@ const partitionScores = <T extends APIScore | LastUserScore>(return { visibleScores, hiddenScores };};-const ScoreGroupBadge = <T extends APIScore | LastUserScore>({+const ScoreGroupBadge = <T extends APIScoreV2 | LastUserScore>({name,scores,}: {@@ -74,7 +73,7 @@ const ScoreGroupBadge = <T extends APIScore | LastUserScore>({);};-export const GroupedScoreBadges = <T extends APIScore | LastUserScore>({+export const GroupedScoreBadges = <T extends APIScoreV2 | LastUserScore>({scores,maxVisible,}: {diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsxindex b63672b682..9c014f5c77 100644--- a/web/src/components/session/index.tsx+++ b/web/src/components/session/index.tsx@@ -25,6 +25,7 @@ import {} from "@/src/components/ui/popover";import { ScrollArea } from "@/src/components/ui/scroll-area";import { Label } from "@/src/components/ui/label";+import { type APIScoreV2 } from "@langfuse/shared";// some projects have thousands of traces in a sessions, paginate to avoid rendering all at onceconst PAGE_SIZE = 50;@@ -120,6 +121,13 @@ export function SessionUsers({);}+const SessionScores = ({ scores }: { scores: APIScoreV2[] }) => {+ return (+ <div className="flex flex-wrap gap-1">+ <GroupedScoreBadges scores={scores} />+ </div>+ );+};export const SessionPage: React.FC<{sessionId: string;projectId: string;@@ -127,7 +135,7 @@ export const SessionPage: React.FC<{const { setDetailPageList } = useDetailPageLists();const userSession = useSession();const [visibleTraces, setVisibleTraces] = useState(PAGE_SIZE);- const session = api.sessions.byId.useQuery(+ const session = api.sessions.byIdWithScores.useQuery({sessionId,projectId: projectId,@@ -239,6 +247,17 @@ export const SessionPage: React.FC<{objectType="SESSION"count={sessionCommentCounts.data?.get(sessionId)}/>+ <AnnotateDrawer+ projectId={projectId}+ scoreTarget={{+ type: "session",+ sessionId,+ }}+ scores={session.data?.scores ?? []}+ emptySelectedConfigIds={emptySelectedConfigIds}+ setEmptySelectedConfigIds={setEmptySelectedConfigIds}+ buttonVariant="outline"+ /></>),}}@@ -251,6 +270,7 @@ export const SessionPage: React.FC<{Total cost: {usdFormatter(session.data.totalCost, 2)}</Badge>)}+ <SessionScores scores={session.data?.scores ?? []} /></div><div className="mt-5 flex flex-col gap-2 border-t pt-5">{session.data?.traces.slice(0, visibleTraces).map((trace) => (@@ -284,13 +304,15 @@ export const SessionPage: React.FC<{<div className="flex items-center gap-1"><AnnotateDrawerprojectId={projectId}- traceId={trace.id}+ scoreTarget={{+ type: "trace",+ traceId: trace.id,+ }}scores={trace.scores}emptySelectedConfigIds={emptySelectedConfigIds}setEmptySelectedConfigIds={setEmptySelectedConfigIds}variant="badge"- type="session"- source="SessionDetail"+ analyticsData={{ type: "trace", source: "SessionDetail" }}key={"annotation-drawer" + trace.id}environment={trace.environment}/>diff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsxindex 727a2506e9..bcc1f5e36d 100644--- a/web/src/components/table/use-cases/scores.tsx+++ b/web/src/components/table/use-cases/scores.tsx@@ -47,7 +47,7 @@ import { TableSelectionManager } from "@/src/features/table/components/TableSeleexport type ScoresTableRow = {id: string;- traceId: string;+ traceId?: string;timestamp: Date;source: string;name: string;@@ -564,7 +564,7 @@ export default function ScoresTable({},comment: score.comment ?? undefined,observationId: score.observationId ?? undefined,- traceId: score.traceId,+ traceId: score.traceId ?? undefined,traceName: score.traceName ?? undefined,userId: score.traceUserId ?? undefined,jobConfigurationId: score.jobConfigurationId ?? undefined,diff --git a/web/src/components/table/use-cases/sessions.tsx b/web/src/components/table/use-cases/sessions.tsxindex 5fc64f8d57..ee3fbb0e47 100644--- a/web/src/components/table/use-cases/sessions.tsx+++ b/web/src/components/table/use-cases/sessions.tsx@@ -35,6 +35,12 @@ import {convertSelectedEnvironmentsToFilter,} from "@/src/hooks/use-environment-filter";import { Badge } from "@/src/components/ui/badge";+import { type ScoreAggregate } from "@langfuse/shared";+import { useIndividualScoreColumns } from "@/src/features/scores/hooks/useIndividualScoreColumns";+import {+ getScoreGroupColumnProps,+ verifyAndPrefixScoreDataAgainstKeys,+} from "@/src/features/scores/components/ScoreDetailColumnHelpers";export type SessionTableRow = {id: string;@@ -51,6 +57,7 @@ export type SessionTableRow = {totalTokens: number | undefined;traceTags: string[] | undefined;environment?: string;+ scores?: ScoreAggregate;};export type SessionTableProps = {@@ -155,6 +162,14 @@ export default function SessionsTable({const sessions = api.sessions.all.useQuery(payloadGetAll);const sessionCountQuery = api.sessions.countAll.useQuery(payloadCount);+ const { scoreColumns, scoreKeysAndProps, isColumnLoading } =+ useIndividualScoreColumns<SessionTableRow>({+ projectId,+ scoreColumnKey: "scores",+ selectedFilterOption: selectedOption,+ cellsLoading: !sessions.data,+ });+const sessionMetrics = api.sessions.metrics.useQuery({projectId,@@ -229,6 +244,7 @@ export default function SessionsTable({},enableSorting: false,},+{accessorKey: "id",id: "id",@@ -295,6 +311,10 @@ export default function SessionsTable({) : null;},},+ {+ ...getScoreGroupColumnProps(isColumnLoading || !sessions.data),+ columns: scoreColumns,+ },{accessorKey: "userIds",enableColumnFilter: !omittedFilter.find((f) => f === "userIds"),@@ -561,8 +581,8 @@ export default function SessionsTable({: {isLoading: false,isError: false,- data: sessionRowData.rows?.map<SessionTableRow>(- (session) => ({+ data: sessionRowData.rows?.map<SessionTableRow>((session) => {+ return {id: session.id,bookmarked: session.bookmarked,createdAt: session.createdAt,@@ -577,8 +597,14 @@ export default function SessionsTable({totalTokens: session.totalTokens,traceTags: session.traceTags,environment: session.environment,- }),- ),+ scores: session.scores+ ? verifyAndPrefixScoreDataAgainstKeys(+ scoreKeysAndProps,+ session.scores,+ )+ : undefined,+ };+ }),}}pagination={{diff --git a/web/src/components/trace/ObservationPreview.tsx b/web/src/components/trace/ObservationPreview.tsxindex 20376cfb07..6283fc03b4 100644--- a/web/src/components/trace/ObservationPreview.tsx+++ b/web/src/components/trace/ObservationPreview.tsx@@ -1,5 +1,5 @@import { JSONView } from "@/src/components/ui/CodeJsonViewer";-import { AnnotationQueueObjectType, type APIScore } from "@langfuse/shared";+import { AnnotationQueueObjectType, type APIScoreV2 } from "@langfuse/shared";import { Badge } from "@/src/components/ui/badge";import { type ObservationReturnType } from "@/src/server/api/routers/traces";import { api } from "@/src/utils/api";@@ -47,7 +47,7 @@ export const ObservationPreview = ({}: {observations: Array<ObservationReturnType>;projectId: string;- scores: APIScore[];+ scores: APIScoreV2[];currentObservationId: string;traceId: string;commentCounts?: Map<string, number>;@@ -148,12 +148,14 @@ export const ObservationPreview = ({<AnnotateDrawerkey={"annotation-drawer" + preloadedObservation.id}projectId={projectId}- traceId={traceId}- observationId={preloadedObservation.id}+ scoreTarget={{+ type: "trace",+ traceId: traceId,+ observationId: preloadedObservation.id,+ }}scores={scores}emptySelectedConfigIds={emptySelectedConfigIds}setEmptySelectedConfigIds={setEmptySelectedConfigIds}- type="observation"hasGroupedButton={hasEntitlement}environment={preloadedObservation.environment}/>diff --git a/web/src/components/trace/ObservationTree.tsx b/web/src/components/trace/ObservationTree.tsxindex 1fb346e0b1..85f682c761 100644--- a/web/src/components/trace/ObservationTree.tsx+++ b/web/src/components/trace/ObservationTree.tsx@@ -1,7 +1,7 @@import { type NestedObservation } from "@/src/utils/types";import { cn } from "@/src/utils/tailwind";import {- type APIScore,+ type APIScoreV2,ObservationLevel,type ObservationLevelType,type TraceDomain,@@ -47,7 +47,7 @@ export const ObservationTree = ({input: string | null;output: string | null;};- scores: APIScore[];+ scores: APIScoreV2[];currentObservationId: string | undefined;setCurrentObservationId: (id: string | undefined) => void;showMetrics: boolean;@@ -135,7 +135,7 @@ const ObservationTreeTraceNode = (props: {};expandAll: () => void;collapseAll: () => void;- scores: APIScore[];+ scores: APIScoreV2[];comments: Map<string, number> | undefined;currentObservationId: string | undefined;setCurrentObservationId: (id: string | undefined) => void;@@ -239,7 +239,7 @@ const ObservationTreeNode = (props: {observations: NestedObservation[];collapsedObservations: string[];toggleCollapsedObservation: (id: string) => void;- scores: APIScore[];+ scores: APIScoreV2[];comments?: Map<string, number> | undefined;indentationLevel: number;currentObservationId: string | undefined;@@ -312,7 +312,7 @@ const ObservationTreeNodeCard = ({observation: NestedObservation;collapsed: boolean;toggleCollapsedObservation: (id: string) => void;- scores: APIScore[];+ scores: APIScoreV2[];comments?: Map<string, number> | undefined;indentationLevel: number;currentObservationId: string | undefined;diff --git a/web/src/components/trace/TracePreview.tsx b/web/src/components/trace/TracePreview.tsxindex aba7ff0682..a2f24abc68 100644--- a/web/src/components/trace/TracePreview.tsx+++ b/web/src/components/trace/TracePreview.tsx@@ -1,6 +1,6 @@import { JSONView } from "@/src/components/ui/CodeJsonViewer";import {- type APIScore,+ type APIScoreV2,type TraceDomain,AnnotationQueueObjectType,} from "@langfuse/shared";@@ -50,7 +50,7 @@ export const TracePreview = ({output: string | null;};observations: ObservationReturnTypeWithMetadata[];- scores: APIScore[];+ scores: APIScoreV2[];commentCounts?: Map<string, number>;viewType?: "detailed" | "focused";}) => {@@ -129,7 +129,10 @@ export const TracePreview = ({<AnnotateDrawerkey={"annotation-drawer" + trace.id}projectId={trace.projectId}- traceId={trace.id}+ scoreTarget={{+ type: "trace",+ traceId: trace.id,+ }}scores={scores}emptySelectedConfigIds={emptySelectedConfigIds}setEmptySelectedConfigIds={setEmptySelectedConfigIds}diff --git a/web/src/components/trace/TraceTimelineView.tsx b/web/src/components/trace/TraceTimelineView.tsxindex 5c3eff0324..1bf19d4530 100644--- a/web/src/components/trace/TraceTimelineView.tsx+++ b/web/src/components/trace/TraceTimelineView.tsx@@ -1,7 +1,7 @@import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";import {isPresent,- type APIScore,+ type APIScoreV2,type TraceDomain,ObservationLevel,type ObservationLevelType,@@ -85,7 +85,7 @@ function TreeItemInner({showScores?: boolean;showComments?: boolean;colorCodeMetrics?: boolean;- scores?: APIScore[];+ scores?: APIScoreV2[];commentCount?: number;parentTotalDuration?: number;totalCost?: Decimal;@@ -283,7 +283,7 @@ function TraceTreeItem({traceStartTime: Date;totalScaleSpan: number;projectId: string;- scores: APIScore[];+ scores: APIScoreV2[];observations: Array<ObservationReturnTypeWithMetadata>;cardWidth: number;commentCounts?: Map<string, number>;@@ -419,7 +419,7 @@ export function TraceTimelineView({};observations: Array<ObservationReturnTypeWithMetadata>;projectId: string;- scores: APIScore[];+ scores: APIScoreV2[];currentObservationId: string | null;setCurrentObservationId: (id: string | null) => void;expandedItems: string[];diff --git a/web/src/components/trace/index.tsx b/web/src/components/trace/index.tsxindex 56be25f012..20fffada1d 100644--- a/web/src/components/trace/index.tsx+++ b/web/src/components/trace/index.tsx@@ -14,7 +14,7 @@ import { Settings2, ChevronsUpDown, ChevronsDownUp } from "lucide-react";import { useCallback, useState } from "react";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { TraceTimelineView } from "@/src/components/trace/TraceTimelineView";-import { type APIScore, ObservationLevel } from "@langfuse/shared";+import { type APIScoreV2, ObservationLevel } from "@langfuse/shared";import { useIsAuthenticatedAndProjectMember } from "@/src/features/auth/hooks";import { TraceGraphView } from "@/src/features/trace-graph-view/components/TraceGraphView";import { isLanggraphTrace } from "@/src/features/trace-graph-view/utils/isLanggraphTrace";@@ -57,7 +57,7 @@ export function Trace(props: {input: string | null;output: string | null;};- scores: APIScore[];+ scores: APIScoreV2[];projectId: string;viewType?: "detailed" | "focused";isValidObservationId?: boolean;diff --git a/web/src/ee/features/annotation-queues/components/AnnotationQueueItemPage.tsx b/web/src/ee/features/annotation-queues/components/AnnotationQueueItemPage.tsxindex 228a497354..9c897842f4 100644--- a/web/src/ee/features/annotation-queues/components/AnnotationQueueItemPage.tsx+++ b/web/src/ee/features/annotation-queues/components/AnnotationQueueItemPage.tsx@@ -165,14 +165,20 @@ const AnnotateIOView = ({<div className="w-full overflow-auto"><AnnotateDrawerContentkey={"annotation-drawer-content" + item.objectId}- traceId={traceId}+ scoreTarget={{+ type: "trace",+ traceId: traceId,+ observationId: item.parentTraceId ? item.objectId : undefined,+ }}scores={trace.data?.scores ?? []}- observationId={item.parentTraceId ? item.objectId : undefined}configs={configs}emptySelectedConfigIds={emptySelectedConfigIds}setEmptySelectedConfigIds={() => {}}projectId={item.projectId}- type={item.objectType.toLowerCase() as "trace" | "observation"}+ analyticsData={{+ type: "trace",+ source: "AnnotationQueue",+ }}isSelectHiddenqueueId={item.queueId}showSaving={showSaving}@@ -188,6 +194,7 @@ const AnnotateIOView = ({</div>) : undefined}+ isDrawerOpen={true}/></div><div className="relative max-h-64 overflow-auto">diff --git a/web/src/features/public-api/server/scores-api-service.ts b/web/src/features/public-api/server/scores-api-service.tsnew file mode 100644index 0000000000..f0461a6044--- /dev/null+++ b/web/src/features/public-api/server/scores-api-service.ts@@ -0,0 +1,51 @@+import {+ _handleGenerateScoresForPublicApi,+ _handleGetScoresCountForPublicApi,+ type ScoreQueryType,+} from "@/src/features/public-api/server/scores";+import { type ScoreSourceType } from "@langfuse/shared";+import { _handleGetScoreById } from "@langfuse/shared/src/server";++export class ScoresApiService {+ constructor(private readonly apiVersion: "v1" | "v2") {}++ /**+ * Get a specific score by ID+ */+ async getScoreById({+ projectId,+ scoreId,+ source,+ }: {+ projectId: string;+ scoreId: string;+ source?: ScoreSourceType;+ }) {+ return _handleGetScoreById({+ projectId,+ scoreId,+ source,+ scoreScope: this.apiVersion === "v1" ? "traces_only" : "all",+ });+ }++ /**+ * Get list of scores with version-aware filtering+ */+ async generateScoresForPublicApi(props: ScoreQueryType) {+ return _handleGenerateScoresForPublicApi({+ props,+ scoreScope: this.apiVersion === "v1" ? "traces_only" : "all",+ });+ }++ /**+ * Get count of scores with version-aware filtering+ */+ async getScoresCountForPublicApi(props: ScoreQueryType) {+ return _handleGetScoresCountForPublicApi({+ props,+ scoreScope: this.apiVersion === "v1" ? "traces_only" : "all",+ });+ }+}diff --git a/web/src/features/public-api/server/scores.ts b/web/src/features/public-api/server/scores.tsindex 9dcfa539f1..66ce018830 100644--- a/web/src/features/public-api/server/scores.ts+++ b/web/src/features/public-api/server/scores.ts@@ -1,13 +1,7 @@-import {- type ApiColumnMapping,- convertApiProvidedFilterToClickhouseFilter,-} from "@/src/features/public-api/server/filter-builder";-import {- convertToScore,- queryClickhouse,- StringFilter,- type ScoreRecordReadType,-} from "@langfuse/shared/src/server";+import { convertApiProvidedFilterToClickhouseFilter } from "@/src/features/public-api/server/filter-builder";+import { convertToScore, StringFilter } from "@langfuse/shared/src/server";+import { type ScoreRecordReadType } from "@langfuse/shared/src/server";+import { queryClickhouse } from "@langfuse/shared/src/server";export type ScoreQueryType = {page: number;@@ -29,7 +23,18 @@ export type ScoreQueryType = {dataType?: string;};-export const generateScoresForPublicApi = async (props: ScoreQueryType) => {+/**+ * @internal+ * Internal utility function for getting scores by ID.+ * Do not use directly - use ScoresApiService or repository functions instead.+ */+export const _handleGenerateScoresForPublicApi = async ({+ props,+ scoreScope,+}: {+ props: ScoreQueryType;+ scoreScope: "traces_only" | "all";+}) => {const { scoresFilter, tracesFilter } = generateScoreFilter(props);const appliedScoresFilter = scoresFilter.apply();const appliedTracesFilter = tracesFilter.apply();@@ -56,24 +61,33 @@ export const generateScoresForPublicApi = async (props: ScoreQueryType) => {s.config_id as config_id,s.queue_id as queue_id,s.trace_id as trace_id,- s.observation_id as observation_id+ s.observation_id as observation_id,+ s.session_id as session_idFROM- traces t- JOIN scores s ON s.trace_id = t.id+ scores s+ LEFT JOIN traces t ON s.trace_id = t.idAND s.project_id = t.project_idWHERE- t.project_id = {projectId: String}- AND s.project_id = {projectId: String}- AND (t.id, t.project_id) IN (+ s.project_id = {projectId: String}+ AND (+ ${scoreScope === "traces_only" ? "" : "s.trace_id IS NULL OR "}+ (s.trace_id IS NOT NULL AND (t.id, t.project_id) IN (SELECT- trace_id,- project_id+ trace_id,+ project_idFROM- scores s+ scores sWHERE- s.project_id = {projectId: String}- ${appliedScoresFilter.query ? `AND ${appliedScoresFilter.query}` : ""}+ s.project_id = {projectId: String}+ ${appliedScoresFilter.query ? `AND ${appliedScoresFilter.query}` : ""}+ ${scoreScope === "traces_only" ? "AND s.session_id IS NULL" : ""}+ ORDER BY+ s.timestamp desc+ LIMIT+ 1 BY s.id, s.project_id+ )))+ ${scoreScope === "traces_only" ? "AND s.session_id IS NULL" : ""}${appliedScoresFilter.query ? `AND ${appliedScoresFilter.query}` : ""}${tracesFilter.length() > 0 ? `AND ${appliedTracesFilter.query}` : ""}ORDER BY@@ -104,15 +118,29 @@ export const generateScoresForPublicApi = async (props: ScoreQueryType) => {return records.map((record) => ({...convertToScore(record),- trace: {- userId: record.user_id,- tags: record.tags,- environment: record.trace_environment,- },+ trace:+ record.trace_id !== null+ ? {+ userId: record.user_id,+ tags: record.tags,+ environment: record.trace_environment,+ }+ : null,}));};-export const getScoresCountForPublicApi = async (props: ScoreQueryType) => {+/**+ * @internal+ * Internal utility function for getting scores by ID.+ * Do not use directly - use ScoresApiService or repository functions instead.+ */+export const _handleGetScoresCountForPublicApi = async ({+ props,+ scoreScope,+}: {+ props: ScoreQueryType;+ scoreScope: "traces_only" | "all";+}) => {const { scoresFilter, tracesFilter } = generateScoreFilter(props);const appliedScoresFilter = scoresFilter.apply();const appliedTracesFilter = tracesFilter.apply();@@ -122,13 +150,14 @@ export const getScoresCountForPublicApi = async (props: ScoreQueryType) => {SELECTcount() as countFROM- traces t- JOIN scores s ON s.trace_id = t.id+ scores s+ LEFT JOIN traces t ON s.trace_id = t.idAND s.project_id = t.project_idWHERE- t.project_id = {projectId: String}- AND s.project_id = {projectId: String}- AND (t.id, t.project_id) IN (+ s.project_id = {projectId: String}+ AND (+ ${scoreScope === "traces_only" ? "" : "s.trace_id IS NULL OR "}+ (s.trace_id IS NOT NULL AND (t.id, t.project_id) IN (SELECTtrace_id,project_id@@ -137,13 +166,15 @@ export const getScoresCountForPublicApi = async (props: ScoreQueryType) => {WHEREs.project_id = {projectId: String}${appliedScoresFilter.query ? `AND ${appliedScoresFilter.query}` : ""}+ ${scoreScope === "traces_only" ? "AND s.session_id IS NULL" : ""}ORDER BYs.timestamp descLIMIT1 BY s.id, s.project_id- )- ${appliedScoresFilter.query ? `AND ${appliedScoresFilter.query}` : ""}- ${tracesFilter.length() > 0 ? `AND ${appliedTracesFilter.query}` : ""}+ ))+ )+ ${appliedScoresFilter.query ? `AND ${appliedScoresFilter.query}` : ""}+ ${tracesFilter.length() > 0 ? `AND ${appliedTracesFilter.query}` : ""}`;const records = await queryClickhouse<{ count: string }>({@@ -157,7 +188,7 @@ export const getScoresCountForPublicApi = async (props: ScoreQueryType) => {return records.map((record) => Number(record.count)).shift();};-const secureScoreFilterOptions: ApiColumnMapping[] = [+const secureScoreFilterOptions = [{id: "traceId",clickhouseSelect: "trace_id",diff --git a/web/src/features/public-api/server/traces.ts b/web/src/features/public-api/server/traces.tsindex 283e00b3d7..3d766d949d 100644--- a/web/src/features/public-api/server/traces.ts+++ b/web/src/features/public-api/server/traces.ts@@ -11,7 +11,7 @@ import {import { type OrderByState } from "@langfuse/shared";import { snakeCase } from "lodash";-type QueryType = {+export type TraceQueryType = {page: number;limit: number;projectId: string;@@ -28,10 +28,13 @@ type QueryType = {toTimestamp?: string;};-export const generateTracesForPublicApi = async (- props: QueryType,- orderBy: OrderByState,-) => {+export const generateTracesForPublicApi = async ({+ props,+ orderBy,+}: {+ props: TraceQueryType;+ orderBy: OrderByState;+}) => {const filter = convertApiProvidedFilterToClickhouseFilter(props,filterParams,@@ -88,6 +91,7 @@ export const generateTracesForPublicApi = async (groupUniqArray(id) as score_idsFROM scoresWHERE project_id = {projectId: String}+ AND session_id IS NULL${timeFilter ? `AND timestamp >= {cteTimeFilter: DateTime64(3)}` : ""}${environmentFilter.length() > 0 ? `AND ${appliedEnvironmentFilter.query}` : ""}GROUP BY project_id, trace_id@@ -162,7 +166,11 @@ export const generateTracesForPublicApi = async (}));};-export const getTracesCountForPublicApi = async (props: QueryType) => {+export const getTracesCountForPublicApi = async ({+ props,+}: {+ props: TraceQueryType;+}) => {const filter = convertApiProvidedFilterToClickhouseFilter(props,filterParams,diff --git a/web/src/features/public-api/types/traces.ts b/web/src/features/public-api/types/traces.tsindex 513b8d997f..67745d4489 100644--- a/web/src/features/public-api/types/traces.ts+++ b/web/src/features/public-api/types/traces.ts@@ -1,6 +1,6 @@import { APIObservation } from "@/src/features/public-api/types/observations";import {- APIScoreSchema,+ APIScoreSchemaV1,paginationMetaResponseZod,orderBy,publicApiPaginationZod,@@ -85,7 +85,7 @@ export const GetTraceV1Query = z.object({traceId: z.string(),});export const GetTraceV1Response = APIExtendedTrace.extend({- scores: z.array(APIScoreSchema),+ scores: z.array(APIScoreSchemaV1),observations: z.array(APIObservation),}).strict();diff --git a/web/src/features/scores/components/AnnotateDrawer.tsx b/web/src/features/scores/components/AnnotateDrawer.tsxindex af962c1017..aeb31fcd20 100644--- a/web/src/features/scores/components/AnnotateDrawer.tsx+++ b/web/src/features/scores/components/AnnotateDrawer.tsx@@ -8,7 +8,6 @@ import {DrawerTitle,DrawerTrigger,} from "@/src/components/ui/drawer";-import { type APIScore } from "@langfuse/shared";import { api } from "@/src/utils/api";import Header from "@/src/components/layouts/header";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";@@ -16,34 +15,27 @@ import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccesimport { AnnotateDrawerContent } from "@/src/features/scores/components/AnnotateDrawerContent";import { useIsMutating } from "@tanstack/react-query";import { z } from "zod";+import { type AnnotateDrawerProps } from "@/src/features/scores/types";+import { type ScoreTarget } from "@/src/features/scores/types";+import { formatAnnotateDescription } from "@/src/features/scores/lib/helpers";const mutationKeySchema = z.array(z.array(z.string()));-export function AnnotateDrawer({- traceId,+export function AnnotateDrawer<Target extends ScoreTarget>({+ scoreTarget,scores,emptySelectedConfigIds,setEmptySelectedConfigIds,- observationId,projectId,+ analyticsData = {+ type: "trace",+ source: "TraceDetail",+ },variant = "button",- type = "trace",- source = "TraceDetail",+ buttonVariant = "secondary",hasGroupedButton = false,environment,-}: {- traceId: string;- scores: APIScore[];- emptySelectedConfigIds: string[];- setEmptySelectedConfigIds: (ids: string[]) => void;- observationId?: string;- projectId: string;- variant?: "button" | "badge";- type?: "trace" | "observation" | "session";- source?: "TraceDetail" | "SessionDetail";- hasGroupedButton?: boolean;- environment?: string;-}) {+}: AnnotateDrawerProps<Target>) {const [isDrawerOpen, setIsDrawerOpen] = useState(false);const [showSaving, setShowSaving] = useState(false);const capture = usePostHogClientCapture();@@ -51,6 +43,7 @@ export function AnnotateDrawer({projectId,scope: "scores:CUD",});+ const description = formatAnnotateDescription(scoreTarget);const configsData = api.scoreConfigs.all.useQuery({@@ -102,7 +95,7 @@ export function AnnotateDrawer({<DrawerTrigger asChild>{variant === "button" ? (<Button- variant="secondary"+ variant={buttonVariant}disabled={!hasAccess || showSaving}className={hasGroupedButton ? "rounded-r-none" : ""}onClick={() => {@@ -111,10 +104,7 @@ export function AnnotateDrawer({Boolean(scores.length)? "score:update_form_open": "score:create_form_open",- {- type: type,- source: source,- },+ analyticsData,);}}>@@ -137,10 +127,7 @@ export function AnnotateDrawer({Boolean(scores.length)? "score:update_form_open": "score:create_form_open",- {- type: type,- source: source,- },+ analyticsData,);}}>@@ -155,7 +142,7 @@ export function AnnotateDrawer({<Headertitle="Annotate"help={{- description: `Annotate ${observationId ? "observation" : "trace"} with scores to capture human evaluation across different dimensions.`,+ description,href: "https://langfuse.com/docs/scores/manually",}}></Header>@@ -169,15 +156,13 @@ export function AnnotateDrawer({</DrawerHeader>) : (<AnnotateDrawerContent- traceId={traceId}scores={scores}+ scoreTarget={scoreTarget}configs={configs}emptySelectedConfigIds={emptySelectedConfigIds}setEmptySelectedConfigIds={setEmptySelectedConfigIds}- observationId={observationId}projectId={projectId}- type={type}- source={source}+ analyticsData={analyticsData}showSaving={showSaving}setShowSaving={setShowSaving}isDrawerOpen={isDrawerOpen}diff --git a/web/src/features/scores/components/AnnotateDrawerContent.tsx b/web/src/features/scores/components/AnnotateDrawerContent.tsxindex c4603b290e..efb4608817 100644--- a/web/src/features/scores/components/AnnotateDrawerContent.tsx+++ b/web/src/features/scores/components/AnnotateDrawerContent.tsx@@ -1,4 +1,4 @@-import React, { useCallback, useEffect, useRef, useState } from "react";+import React, { useEffect, useRef } from "react";import { Button } from "@/src/components/ui/button";import {MessageCircleMore,@@ -25,15 +25,13 @@ import {} from "@/src/components/ui/form";import { DrawerHeader, DrawerTitle } from "@/src/components/ui/drawer";import {- type APIScore,+ type APIScoreV2,isPresent,- ScoreDataType,CreateAnnotationScoreData,UpdateAnnotationScoreData,type ValidatedScoreConfig,type ConfigCategory,} from "@langfuse/shared";-import { z } from "zod";import { Input } from "@/src/components/ui/input";import {Popover,@@ -41,7 +39,6 @@ import {PopoverContent,PopoverTrigger,} from "@/src/components/ui/popover";-import { api } from "@/src/utils/api";import {Select,SelectContent,@@ -54,6 +51,7 @@ import { HoverCardContent } from "@radix-ui/react-hover-card";import { HoverCard, HoverCardTrigger } from "@/src/components/ui/hover-card";import { ScoreConfigDetails } from "@/src/features/scores/components/ScoreConfigDetails";import {+ formatAnnotateDescription,isNumericDataType,isScoreUnsaved,} from "@/src/features/scores/lib/helpers";@@ -66,23 +64,15 @@ import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePosimport { cn } from "@/src/utils/tailwind";import { getScoreDataTypeIcon } from "@/src/features/scores/components/ScoreDetailColumnHelpers";import { DropdownMenuItem } from "@/src/components/ui/dropdown-menu";--const AnnotationScoreDataSchema = z.object({- name: z.string(),- scoreId: z.string().optional(),- value: z.number().nullable().optional(),- stringValue: z.string().optional(),- dataType: z.nativeEnum(ScoreDataType),- configId: z.string().optional(),- comment: z.string().optional(),-});--const AnnotateFormSchema = z.object({- scoreData: z.array(AnnotationScoreDataSchema),-});--type AnnotateFormSchemaType = z.infer<typeof AnnotateFormSchema>;-type AnnotationScoreSchemaType = z.infer<typeof AnnotationScoreDataSchema>;+import {+ type ScoreTarget,+ type AnnotateDrawerProps,+ type AnnotateFormSchemaType,+ type AnnotationScoreSchemaType,+} from "@/src/features/scores/types";+import { useScoreValues } from "@/src/features/scores/hooks/useScoreValues";+import { useScoreMutations } from "@/src/features/scores/hooks/useScoreMutations";+import { AnnotateFormSchema } from "@/src/features/scores/schema";const CHAR_CUTOFF = 6;@@ -141,17 +131,17 @@ function handleOnKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {function AnnotateHeader({showSaving,actionButtons,- observationId,+ description,}: {showSaving: boolean;actionButtons: React.ReactNode;- observationId?: string;+ description: string;}) {return (<Headertitle="Annotate"help={{- description: `Annotate ${observationId ? "observation" : "trace"} with scores to capture human evaluation across different dimensions.`,+ description,href: "https://langfuse.com/docs/scores/manually",className: "leading-relaxed",}}@@ -174,57 +164,33 @@ function AnnotateHeader({);}-function useCustomOptimistic<State, Action>(- initialState: State,- reducer: (state: State, action: Action) => State,-): [State, (action: Action) => void] {- const [state, setState] = useState<State>(initialState);-- const dispatch = useCallback(- (action: Action) => {- setState((currentState) => reducer(currentState, action));- },- [reducer],- );-- return [state, dispatch];-}+type AnnotateDrawerContentProps<Target extends ScoreTarget> =+ AnnotateDrawerProps<Target> & {+ configs: ValidatedScoreConfig[];+ isDrawerOpen: boolean;+ showSaving: boolean;+ setShowSaving: (showSaving: boolean) => void;+ isSelectHidden?: boolean;+ queueId?: string;+ actionButtons?: React.ReactNode;+ };-export function AnnotateDrawerContent({- traceId,+export function AnnotateDrawerContent<Target extends ScoreTarget>({+ scoreTarget,scores,configs,+ analyticsData,emptySelectedConfigIds,setEmptySelectedConfigIds,- observationId,projectId,showSaving,setShowSaving,isDrawerOpen = true,- type = "trace",- source = "TraceDetail",isSelectHidden = false,queueId,actionButtons,environment,-}: {- traceId: string;- scores: APIScore[];- configs: ValidatedScoreConfig[];- emptySelectedConfigIds: string[];- setEmptySelectedConfigIds: (ids: string[]) => void;- observationId?: string;- projectId: string;- showSaving: boolean;- setShowSaving: (showSaving: boolean) => void;- isDrawerOpen?: boolean;- type?: "trace" | "observation" | "session";- source?: "TraceDetail" | "SessionDetail";- isSelectHidden?: boolean;- queueId?: string;- actionButtons?: React.ReactNode;- environment?: string;-}) {+}: AnnotateDrawerContentProps<Target>) {const capture = usePostHogClientCapture();const router = useRouter();@@ -235,46 +201,11 @@ export function AnnotateDrawerContent({scores,emptySelectedConfigIds,configs,- traceId,- observationId,+ scoreTarget,}),},});- const [optimisticScores, setOptimisticScore] = useCustomOptimistic<- AnnotateFormSchemaType["scoreData"],- {- index: number;- value: number | null;- stringValue: string | null;- name?: string | null;- dataType?: ScoreDataType | null;- configId?: string | null;- }- >(form.getValues().scoreData, (state, updatedScore) => {- const stateCopy = state.map((score, idx) =>- idx === updatedScore.index- ? {- ...score,- value: updatedScore.value,- stringValue: updatedScore.stringValue ?? undefined,- }- : score,- );-- if (updatedScore.index === stateCopy.length) {- const newScore = {- name: updatedScore.name ?? "",- dataType: updatedScore.dataType ?? ScoreDataType.NUMERIC,- configId: updatedScore.configId ?? undefined,- value: updatedScore.value,- stringValue: updatedScore.stringValue ?? undefined,- };- return [...stateCopy, newScore];- }- return stateCopy;- });-const { fields, remove, update, replace } = useFieldArray({control: form.control,name: "scoreData",@@ -282,6 +213,21 @@ export function AnnotateDrawerContent({const prevEmptySelectedConfigIdsRef = useRef(emptySelectedConfigIds);+ const { optimisticScores, setOptimisticScore } = useScoreValues({+ getValues: form.getValues,+ });++ const { createMutation, updateMutation, deleteMutation } = useScoreMutations(+ scoreTarget,+ projectId,+ fields,+ update,+ remove,+ configs,+ isDrawerOpen,+ setShowSaving,+ );+useEffect(() => {// Only reset the form if emptySelectedConfigIds has changed, compare by value not referenceif (@@ -296,93 +242,16 @@ export function AnnotateDrawerContent({scores,emptySelectedConfigIds,configs,- traceId,- observationId,+ scoreTarget,}),});}prevEmptySelectedConfigIdsRef.current = emptySelectedConfigIds;- }, [emptySelectedConfigIds, scores, configs, traceId, observationId, form]);-- const mutDeleteScore = api.scores.deleteAnnotationScore.useMutation({- onSettled: async (data, error) => {- if (!data || error) return;+ }, [emptySelectedConfigIds, scores, configs, scoreTarget, form]);- const { id, name, dataType, configId } = data;- const updatedScoreIndex = fields.findIndex(- (field) => field.scoreId === id,- );-- const config = configs.find((config) => config.id === configId);- if (config && config.isArchived) {- remove(updatedScoreIndex);- } else {- update(updatedScoreIndex, {- name,- dataType,- configId: configId ?? undefined,- value: null,- scoreId: undefined,- stringValue: undefined,- comment: undefined,- });- }-- await Promise.all([- utils.scores.invalidate(),- utils.traces.invalidate(),- utils.sessions.invalidate(),- ]);-- if (!isDrawerOpen) setShowSaving(false);- },- });-- const utils = api.useUtils();-- const onSettledUpsert = async (data?: APIScore, error?: unknown) => {- if (!data || error) return;-- const { id, value, stringValue, name, dataType, configId, comment } = data;- const updatedScoreIndex = fields.findIndex(- (field) => field.configId === configId,- );-- update(updatedScoreIndex, {- value,- name,- dataType,- scoreId: id,- stringValue: stringValue ?? undefined,- configId: configId ?? undefined,- comment: comment ?? undefined,- });-- await Promise.all([- utils.scores.invalidate(),- utils.traces.byIdWithObservationsAndScores.invalidate(- { projectId, traceId },- {- type: "all",- refetchType: "all",- },- ),- utils.sessions.invalidate(),- ]);-- if (!isDrawerOpen) setShowSaving(false);- };-- const mutCreateScores = api.scores.createAnnotationScore.useMutation({- onSettled: onSettledUpsert,- });-- const mutUpdateScores = api.scores.updateAnnotationScore.useMutation({- onSettled: onSettledUpsert,- });-- const pendingCreates = useRef(new Map<number, Promise<APIScore>>());+ const pendingCreates = useRef(new Map<number, Promise<APIScoreV2>>());+ const description = formatAnnotateDescription(scoreTarget);async function handleScoreChange(score: AnnotationScoreSchemaType,@@ -403,25 +272,23 @@ export function AnnotateDrawerContent({const validatedScore = UpdateAnnotationScoreData.parse({id: score.scoreId,projectId,- traceId,+ scoreTarget,name: score.name,dataType: score.dataType,configId: score.configId,stringValue: stringValue ?? score.stringValue,comment: score.comment,- observationId,value,queueId,environment,});- await mutUpdateScores.mutateAsync({+ await updateMutation.mutateAsync({...validatedScore,});capture("score:update", {- type: type,- source: source,+ ...analyticsData,dataType: score.dataType,});} else {@@ -433,50 +300,46 @@ export function AnnotateDrawerContent({const validatedScore = UpdateAnnotationScoreData.parse({id: createdScore.id,projectId,- traceId,+ scoreTarget,name: score.name,dataType: score.dataType,configId: score.configId,stringValue: stringValue ?? score.stringValue,comment: score.comment,- observationId,value,queueId,environment,});- await mutUpdateScores.mutateAsync({+ await updateMutation.mutateAsync({...validatedScore,});capture("score:update", {- type: type,- source: source,+ ...analyticsData,dataType: score.dataType,});} else {// If no pending create, straightforward createconst validatedScore = CreateAnnotationScoreData.parse({projectId,- traceId,+ scoreTarget,name: score.name,dataType: score.dataType,configId: score.configId,stringValue: stringValue ?? score.stringValue,comment: score.comment,- observationId,value,queueId,environment,});- const createPromise = mutCreateScores.mutateAsync({+ const createPromise = createMutation.mutateAsync({...validatedScore,});capture("score:create", {- type: type,- source: source,+ ...analyticsData,dataType: score.dataType,});@@ -545,18 +408,18 @@ export function AnnotateDrawerContent({useEffect(() => {if (- mutUpdateScores.isLoading ||- mutCreateScores.isLoading ||- mutDeleteScore.isLoading+ updateMutation.isLoading ||+ createMutation.isLoading ||+ deleteMutation.isLoading) {setShowSaving(true);} else {setShowSaving(false);}}, [- mutUpdateScores.isLoading,- mutCreateScores.isLoading,- mutDeleteScore.isLoading,+ updateMutation.isLoading,+ createMutation.isLoading,+ deleteMutation.isLoading,setShowSaving,]);@@ -646,26 +509,25 @@ export function AnnotateDrawerContent({const validatedScore = UpdateAnnotationScoreData.parse({id: scoreId,projectId,- traceId,+ scoreTarget,name: score.name,dataType: score.dataType,configId: score.configId,stringValue: score.stringValue,- observationId,value,comment,queueId,environment,});- await mutUpdateScores.mutateAsync({+ await updateMutation.mutateAsync({...validatedScore,});- capture(comment ? "score:update_comment" : "score:delete_comment", {- type: type,- source: source,- });+ capture(+ comment ? "score:update_comment" : "score:delete_comment",+ analyticsData,+ );}};}@@ -677,14 +539,14 @@ export function AnnotateDrawerContent({<AnnotateHeadershowSaving={showSaving}actionButtons={actionButtons}- observationId={observationId}+ description={description}/>) : (<DrawerTitle><AnnotateHeadershowSaving={showSaving}actionButtons={actionButtons}- observationId={observationId}+ description={description}/></DrawerTitle>)}@@ -714,7 +576,7 @@ export function AnnotateDrawerContent({optimisticScores.some((score) => score.configId === config.id && !!score.value,) ||- mutDeleteScore.isLoading,+ deleteMutation.isLoading,isArchived: config.isArchived,}))}values={fields@@ -726,10 +588,10 @@ export function AnnotateDrawerContent({controlButtons={<DropdownMenuItemonSelect={() => {- capture("score_configs:manage_configs_item_click", {- type: type,- source: source,- });+ capture(+ "score_configs:manage_configs_item_click",+ analyticsData,+ );router.push(`/project/${projectId}/settings/scores`);}}>@@ -875,9 +737,7 @@ export function AnnotateDrawerContent({!field.value ||config.isArchived}- loading={- mutUpdateScores.isLoading- }+ loading={updateMutation.isLoading}onClick={handleCommentUpdate({field,score,@@ -898,9 +758,7 @@ export function AnnotateDrawerContent({disabled={!field.value || !score.comment}- loading={- mutUpdateScores.isLoading- }+ loading={updateMutation.isLoading}onClick={handleCommentUpdate({field,score,@@ -1074,7 +932,7 @@ export function AnnotateDrawerContent({<Buttontype="button"variant="destructive"- loading={mutDeleteScore.isLoading}+ loading={deleteMutation.isLoading}onClick={async () => {if (score.scoreId) {setOptimisticScore({@@ -1082,14 +940,11 @@ export function AnnotateDrawerContent({value: null,stringValue: null,});- await mutDeleteScore.mutateAsync({+ await deleteMutation.mutateAsync({id: score.scoreId,projectId,});- capture("score:delete", {- type: type,- source: source,- });+ capture("score:delete", analyticsData);form.clearErrors(`scoreData.${index}.value`,);@@ -1109,10 +964,10 @@ export function AnnotateDrawerContent({title="Delete score from trace/observation"disabled={isScoreUnsaved(score.scoreId) ||- mutUpdateScores.isLoading+ updateMutation.isLoading}loading={- mutDeleteScore.isLoading &&+ deleteMutation.isLoading &&!optimisticScores.some((s) => s.scoreId === score.scoreId,) &&@@ -1125,14 +980,11 @@ export function AnnotateDrawerContent({value: null,stringValue: null,});- await mutDeleteScore.mutateAsync({+ await deleteMutation.mutateAsync({id: score.scoreId,projectId,});- capture("score:delete", {- type: type,- source: source,- });+ capture("score:delete", analyticsData);form.clearErrors(`scoreData.${index}.value`);}}}diff --git a/web/src/features/scores/components/ScoreDetailColumnHelpers.tsx b/web/src/features/scores/components/ScoreDetailColumnHelpers.tsxindex fde274e210..0e77f4fb51 100644--- a/web/src/features/scores/components/ScoreDetailColumnHelpers.tsx+++ b/web/src/features/scores/components/ScoreDetailColumnHelpers.tsx@@ -18,6 +18,7 @@ import {type ScoreData,type TableRowTypesWithIndividualScoreColumns,} from "@/src/features/scores/lib/types";+import { type SessionTableRow } from "@/src/components/table/use-cases/sessions";const prefixScoreColKey = (key: string,@@ -42,7 +43,8 @@ const parseScoreColumn = <| ObservationsTableRow| DatasetRunRowData| DatasetRunItemRowData- | PromptVersionTableRow,+ | PromptVersionTableRow+ | SessionTableRow,>(col: ScoreData,prefix?: "Trace" | "Generation",diff --git a/web/src/features/scores/hooks/useScoreCustomOptimistic.ts b/web/src/features/scores/hooks/useScoreCustomOptimistic.tsnew file mode 100644index 0000000000..9165e7f031--- /dev/null+++ b/web/src/features/scores/hooks/useScoreCustomOptimistic.ts@@ -0,0 +1,17 @@+import { useCallback, useState } from "react";++export function useScoreCustomOptimistic<State, Action>(+ initialState: State,+ reducer: (state: State, action: Action) => State,+): [State, (action: Action) => void] {+ const [state, setState] = useState<State>(initialState);++ const dispatch = useCallback(+ (action: Action) => {+ setState((currentState) => reducer(currentState, action));+ },+ [reducer],+ );++ return [state, dispatch];+}diff --git a/web/src/features/scores/hooks/useScoreMutations.ts b/web/src/features/scores/hooks/useScoreMutations.tsnew file mode 100644index 0000000000..4d622f877b--- /dev/null+++ b/web/src/features/scores/hooks/useScoreMutations.ts@@ -0,0 +1,211 @@+import { api } from "@/src/utils/api";+import { type AnnotateFormSchemaType, type ScoreTarget } from "../types";+import { type ValidatedScoreConfig, type APIScoreV2 } from "@langfuse/shared";+import {+ type UseFieldArrayUpdate,+ type UseFieldArrayRemove,+ type FieldArrayWithId,+ type useFieldArray,+} from "react-hook-form";+import { isTraceScore } from "@/src/features/scores/lib/helpers";++const onTraceScoreSettledUpsert =+ ({+ projectId,+ traceId,+ utils,+ fields,+ update,+ isDrawerOpen,+ setShowSaving,+ }: {+ projectId: string;+ traceId: string;+ utils: ReturnType<typeof api.useUtils>;+ fields: FieldArrayWithId<AnnotateFormSchemaType, "scoreData", "id">[];+ update: UseFieldArrayUpdate<AnnotateFormSchemaType>;+ isDrawerOpen: boolean;+ setShowSaving: (showSaving: boolean) => void;+ }) =>+ async (data?: APIScoreV2, error?: unknown) => {+ if (!data || error) return;++ const { id, value, stringValue, name, dataType, configId, comment } = data;+ const updatedScoreIndex = fields.findIndex(+ (field) => field.configId === configId,+ );++ update(updatedScoreIndex, {+ value,+ name,+ dataType,+ scoreId: id,+ stringValue: stringValue ?? undefined,+ configId: configId ?? undefined,+ comment: comment ?? undefined,+ });++ console.log("invalidating traces");++ await Promise.all([+ utils.scores.invalidate(),+ utils.traces.byIdWithObservationsAndScores.invalidate(+ { projectId, traceId },+ {+ type: "all",+ refetchType: "all",+ },+ ),+ utils.sessions.invalidate(),+ ]);++ if (!isDrawerOpen) setShowSaving(false);+ };++const onScoreSettledDelete =+ ({+ utils,+ fields,+ update,+ configs,+ remove,+ isDrawerOpen,+ setShowSaving,+ }: {+ utils: ReturnType<typeof api.useUtils>;+ fields: FieldArrayWithId<AnnotateFormSchemaType, "scoreData", "id">[];+ update: UseFieldArrayUpdate<AnnotateFormSchemaType>;+ configs: ValidatedScoreConfig[];+ remove: ReturnType<typeof useFieldArray>["remove"];+ isDrawerOpen: boolean;+ setShowSaving: (showSaving: boolean) => void;+ }) =>+ async (data?: APIScoreV2, error?: unknown) => {+ if (!data || error) return;++ const { id, name, dataType, configId } = data;+ const updatedScoreIndex = fields.findIndex((field) => field.scoreId === id);++ const config = configs.find((config) => config.id === configId);+ if (config && config.isArchived) {+ remove(updatedScoreIndex);+ } else {+ update(updatedScoreIndex, {+ name,+ dataType,+ configId: configId ?? undefined,+ value: null,+ scoreId: undefined,+ stringValue: undefined,+ comment: undefined,+ });+ }++ await Promise.all([+ utils.scores.invalidate(),+ utils.traces.invalidate(),+ utils.sessions.invalidate(),+ ]);++ if (!isDrawerOpen) setShowSaving(false);+ };++const onSessionScoreSettledUpsert =+ ({+ utils,+ fields,+ update,+ isDrawerOpen,+ setShowSaving,+ }: {+ utils: ReturnType<typeof api.useUtils>;+ fields: FieldArrayWithId<AnnotateFormSchemaType, "scoreData", "id">[];+ update: UseFieldArrayUpdate<AnnotateFormSchemaType>;+ isDrawerOpen: boolean;+ setShowSaving: (showSaving: boolean) => void;+ }) =>+ async (data?: APIScoreV2, error?: unknown) => {+ if (!data || error) return;++ const { id, value, stringValue, name, dataType, configId, comment } = data;+ const updatedScoreIndex = fields.findIndex(+ (field) => field.configId === configId,+ );++ update(updatedScoreIndex, {+ value,+ name,+ dataType,+ scoreId: id,+ stringValue: stringValue ?? undefined,+ configId: configId ?? undefined,+ comment: comment ?? undefined,+ });++ await Promise.all([+ utils.scores.invalidate(),+ utils.sessions.byIdWithScores.invalidate(),+ ]);++ if (!isDrawerOpen) setShowSaving(false);+ };++export function useScoreMutations(+ scoreTarget: ScoreTarget,+ projectId: string,+ fields: FieldArrayWithId<AnnotateFormSchemaType, "scoreData", "id">[],+ update: UseFieldArrayUpdate<AnnotateFormSchemaType>,+ remove: UseFieldArrayRemove,+ configs: ValidatedScoreConfig[],+ isDrawerOpen: boolean,+ setShowSaving: (showSaving: boolean) => void,+) {+ const utils = api.useUtils();++ const onSettledUpsert = isTraceScore(scoreTarget)+ ? onTraceScoreSettledUpsert({+ projectId,+ traceId: scoreTarget.traceId,+ utils,+ fields,+ update,+ isDrawerOpen,+ setShowSaving,+ })+ : onSessionScoreSettledUpsert({+ utils,+ fields,+ update,+ isDrawerOpen,+ setShowSaving,+ });++ const onSettledDelete = onScoreSettledDelete({+ utils,+ fields,+ update,+ remove,+ configs,+ isDrawerOpen,+ setShowSaving,+ });++ // Create mutations with shared invalidation logic+ const createMutation = api.scores.createAnnotationScore.useMutation({+ onSettled: onSettledUpsert,+ });++ const updateMutation = api.scores.updateAnnotationScore.useMutation({+ onSettled: onSettledUpsert,+ });++ const deleteMutation = api.scores.deleteAnnotationScore.useMutation({+ onSuccess: onSettledDelete,+ });++ return {+ createMutation,+ updateMutation,+ deleteMutation,+ };+}diff --git a/web/src/features/scores/hooks/useScoreValues.ts b/web/src/features/scores/hooks/useScoreValues.tsnew file mode 100644index 0000000000..9ee0305d65--- /dev/null+++ b/web/src/features/scores/hooks/useScoreValues.ts@@ -0,0 +1,46 @@+import { useScoreCustomOptimistic } from "@/src/features/scores/hooks/useScoreCustomOptimistic";+import { type AnnotateFormSchemaType } from "@/src/features/scores/types";+import { ScoreDataType } from "@langfuse/shared";+import { type UseFormGetValues } from "react-hook-form";++export function useScoreValues({+ getValues,+}: {+ getValues: UseFormGetValues<AnnotateFormSchemaType>;+}) {+ const [optimisticScores, setOptimisticScore] = useScoreCustomOptimistic<+ AnnotateFormSchemaType["scoreData"],+ {+ index: number;+ value: number | null;+ stringValue: string | null;+ name?: string | null;+ dataType?: ScoreDataType | null;+ configId?: string | null;+ }+ >(getValues().scoreData, (state, updatedScore) => {+ const stateCopy = state.map((score, idx) =>+ idx === updatedScore.index+ ? {+ ...score,+ value: updatedScore.value,+ stringValue: updatedScore.stringValue ?? undefined,+ }+ : score,+ );++ if (updatedScore.index === stateCopy.length) {+ const newScore = {+ name: updatedScore.name ?? "",+ dataType: updatedScore.dataType ?? ScoreDataType.NUMERIC,+ configId: updatedScore.configId ?? undefined,+ value: updatedScore.value,+ stringValue: updatedScore.stringValue ?? undefined,+ };+ return [...stateCopy, newScore];+ }+ return stateCopy;+ });++ return { optimisticScores, setOptimisticScore };+}diff --git a/web/src/features/scores/lib/aggregateScores.ts b/web/src/features/scores/lib/aggregateScores.tsindex 162837dc11..4c2d4b7d02 100644--- a/web/src/features/scores/lib/aggregateScores.ts+++ b/web/src/features/scores/lib/aggregateScores.ts@@ -1,7 +1,7 @@import {type ScoreAggregate,type ScoreSimplified,- type APIScore,+ type APIScoreV2,type ScoreSourceType,type ScoreDataType,} from "@langfuse/shared";@@ -20,7 +20,7 @@ export const composeAggregateScoreKey = ({return `${formattedName}-${source}-${dataType}`;};-type ScoreToAggregate = (APIScore | ScoreSimplified) & {+type ScoreToAggregate = (APIScoreV2 | ScoreSimplified) & {hasMetadata?: boolean;};diff --git a/web/src/features/scores/lib/getDefaultScoreData.ts b/web/src/features/scores/lib/getDefaultScoreData.tsindex 9a545071f2..406a8ec187 100644--- a/web/src/features/scores/lib/getDefaultScoreData.ts+++ b/web/src/features/scores/lib/getDefaultScoreData.ts@@ -1,28 +1,43 @@+import {+ type ScoreTarget,+ type ScoreTargetTrace,+ type ScoreTargetSession,+} from "@langfuse/shared";import { ScoreSource } from "@langfuse/shared";-import { type APIScore, type ValidatedScoreConfig } from "@langfuse/shared";+import { type APIScoreV2, type ValidatedScoreConfig } from "@langfuse/shared";+import { isTraceScore } from "@/src/features/scores/lib/helpers";++const filterTraceScores =+ ({ traceId, observationId }: ScoreTargetTrace) =>+ (s: APIScoreV2) =>+ s.source === ScoreSource.ANNOTATION &&+ s.traceId === traceId &&+ (observationId !== undefined+ ? s.observationId === observationId+ : s.observationId === null);++const filterSessionScores =+ ({ sessionId }: ScoreTargetSession) =>+ (s: APIScoreV2) =>+ s.source === ScoreSource.ANNOTATION && s.sessionId === sessionId;export const getDefaultScoreData = ({scores,emptySelectedConfigIds,configs,- traceId,- observationId,+ scoreTarget,}: {- scores: APIScore[];+ scores: APIScoreV2[];emptySelectedConfigIds: string[];configs: ValidatedScoreConfig[];- traceId: string;- observationId?: string;+ scoreTarget: ScoreTarget;}) => {+ const isValidScore = isTraceScore(scoreTarget)+ ? filterTraceScores(scoreTarget)+ : filterSessionScores(scoreTarget);+const populatedScores = scores- .filter(- (s) =>- s.source === ScoreSource.ANNOTATION &&- s.traceId === traceId &&- (observationId !== undefined- ? s.observationId === observationId- : s.observationId === null),- )+ .filter(isValidScore).map(({id,diff --git a/web/src/features/scores/lib/helpers.ts b/web/src/features/scores/lib/helpers.tsindex 8a708bda9b..b8ce553421 100644--- a/web/src/features/scores/lib/helpers.ts+++ b/web/src/features/scores/lib/helpers.ts@@ -1,5 +1,10 @@import { type ScoreData } from "./types";-import { ScoreDataType } from "@langfuse/shared";+import {+ ScoreDataType,+ type ScoreTargetTrace,+ type ScoreTarget,+ type ScoreTargetSession,+} from "@langfuse/shared";export const isNumericDataType = (dataType: ScoreDataType) =>dataType === ScoreDataType.NUMERIC;@@ -14,3 +19,21 @@ export const isScoreUnsaved = (scoreId?: string): boolean => !scoreId;export const toOrderedScoresList = (list: ScoreData[]): ScoreData[] =>list.sort((a, b) => a.key.localeCompare(b.key));++export const isTraceScore = (+ scoreTarget: ScoreTarget,+): scoreTarget is ScoreTargetTrace => scoreTarget.type === "trace";++export const isSessionScore = (+ scoreTarget: ScoreTarget,+): scoreTarget is ScoreTargetSession => scoreTarget.type === "session";++export const formatAnnotateDescription = <Target extends ScoreTarget>(+ scoreTarget: Target,+): string => {+ let sourceEntity = "session";+ if (isTraceScore(scoreTarget)) {+ sourceEntity = scoreTarget.observationId ? "observation" : "trace";+ }+ return `Annotate ${sourceEntity} with scores to capture human evaluation across different dimensions.`;+};diff --git a/web/src/features/scores/lib/types.ts b/web/src/features/scores/lib/types.tsindex 03d3c87211..aee884a9ba 100644--- a/web/src/features/scores/lib/types.ts+++ b/web/src/features/scores/lib/types.ts@@ -1,4 +1,5 @@import { type ObservationsTableRow } from "@/src/components/table/use-cases/observations";+import { type SessionTableRow } from "@/src/components/table/use-cases/sessions";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";@@ -10,7 +11,8 @@ export type TableRowTypesWithIndividualScoreColumns =| TracesTableRow| DatasetRunItemRowData| DatasetRunRowData- | PromptVersionTableRow;+ | PromptVersionTableRow+ | SessionTableRow;export type ScoreData = {key: string;diff --git a/web/src/features/scores/schema.ts b/web/src/features/scores/schema.tsnew file mode 100644index 0000000000..2e5e6f46bf--- /dev/null+++ b/web/src/features/scores/schema.ts@@ -0,0 +1,16 @@+import { ScoreDataType } from "@langfuse/shared";+import { z } from "zod";++export const AnnotationScoreDataSchema = z.object({+ name: z.string(),+ scoreId: z.string().optional(),+ value: z.number().nullable().optional(),+ stringValue: z.string().optional(),+ dataType: z.nativeEnum(ScoreDataType),+ configId: z.string().optional(),+ comment: z.string().optional(),+});++export const AnnotateFormSchema = z.object({+ scoreData: z.array(AnnotationScoreDataSchema),+});diff --git a/web/src/features/scores/types.ts b/web/src/features/scores/types.tsindex 90395fc747..adadcb8d7f 100644--- a/web/src/features/scores/types.ts+++ b/web/src/features/scores/types.ts@@ -1,4 +1,7 @@-import { type ScoreDataType } from "@langfuse/shared";+import { type AnnotationScoreDataSchema } from "@/src/features/scores/schema";+import { type AnnotateFormSchema } from "@/src/features/scores/schema";+import { type APIScoreV2, type ScoreDataType } from "@langfuse/shared";+import { type z } from "zod";export type HistogramBin = { binLabel: string; count: number };export type CategoryCounts = Record<string, number>;@@ -29,3 +32,37 @@ export type ScoreData = {export interface TimeseriesDataTransformer {toChartData(): ChartData;}++export type SessionScoreTarget = {+ type: "session";+ sessionId: string;+};++export type TraceScoreTarget = {+ type: "trace";+ traceId: string;+ observationId?: string;+};++export type ScoreTarget = SessionScoreTarget | TraceScoreTarget;++export type AnnotateDrawerProps<Target extends ScoreTarget> = {+ projectId: string;+ scoreTarget: Target;+ scores: APIScoreV2[];+ emptySelectedConfigIds: string[];+ setEmptySelectedConfigIds: (ids: string[]) => void;+ analyticsData?: {+ type: "trace" | "session";+ source: "TraceDetail" | "SessionDetail" | "AnnotationQueue";+ };+ variant?: "button" | "badge";+ buttonVariant?: "secondary" | "outline";+ hasGroupedButton?: boolean;+ environment?: string;+};++export type AnnotateFormSchemaType = z.infer<typeof AnnotateFormSchema>;+export type AnnotationScoreSchemaType = z.infer<+ typeof AnnotationScoreDataSchema+>;diff --git a/web/src/features/trace-graph-view/components/TraceGraphView.tsx b/web/src/features/trace-graph-view/components/TraceGraphView.tsxindex d471675eb1..c2208170cd 100644--- a/web/src/features/trace-graph-view/components/TraceGraphView.tsx+++ b/web/src/features/trace-graph-view/components/TraceGraphView.tsx@@ -1,6 +1,6 @@import React, { useEffect, useState, useMemo, useCallback } from "react";import { StringParam, useQueryParam } from "use-query-params";-import type { APIScore, TraceDomain } from "@langfuse/shared";+import type { APIScoreV2, TraceDomain } from "@langfuse/shared";import type { ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";import { TraceGraphCanvas } from "./TraceGraphCanvas";@@ -18,7 +18,7 @@ type TraceGraphViewProps = {input: string | null;output: string | null;};- scores: APIScore[];+ scores: APIScoreV2[];projectId: string;};diff --git a/web/src/pages/api/public/scores/[scoreId].ts b/web/src/pages/api/public/scores/[scoreId].tsindex 2c78d7217a..b808a0cb96 100644--- a/web/src/pages/api/public/scores/[scoreId].ts+++ b/web/src/pages/api/public/scores/[scoreId].ts@@ -1,15 +1,14 @@import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import {- DeleteScoreQuery,- DeleteScoreResponse,- GetScoreQuery,- GetScoreResponse,+ DeleteScoreQueryV1,+ DeleteScoreResponseV1,+ GetScoreQueryV1,+ GetScoreResponseV1,InternalServerError,LangfuseNotFoundError,} from "@langfuse/shared";import {- getScoreById,logger,traceException,ScoreDeleteQueue,@@ -17,20 +16,25 @@ import {import { auditLog } from "@/src/features/audit-logs/auditLog";import { QueueJobs } from "@langfuse/shared/src/server";import { randomUUID } from "crypto";+import { ScoresApiService } from "@/src/features/public-api/server/scores-api-service";export default withMiddlewares({GET: createAuthedProjectAPIRoute({name: "Get Score",- querySchema: GetScoreQuery,- responseSchema: GetScoreResponse,+ querySchema: GetScoreQueryV1,+ responseSchema: GetScoreResponseV1,fn: async ({ query, auth }) => {- const score = await getScoreById(auth.scope.projectId, query.scoreId);+ const scoresApiService = new ScoresApiService("v1");+ const score = await scoresApiService.getScoreById({+ projectId: auth.scope.projectId,+ scoreId: query.scoreId,+ });if (!score) {throw new LangfuseNotFoundError("Score not found");}- const parsedScore = GetScoreResponse.safeParse(score);+ const parsedScore = GetScoreResponseV1.safeParse(score);if (!parsedScore.success) {traceException(parsedScore.error);@@ -43,8 +47,8 @@ export default withMiddlewares({}),DELETE: createAuthedProjectAPIRoute({name: "Delete Score",- querySchema: DeleteScoreQuery,- responseSchema: DeleteScoreResponse,+ querySchema: DeleteScoreQueryV1,+ responseSchema: DeleteScoreResponseV1,successStatusCode: 202,fn: async ({ query, auth }) => {const { scoreId } = query;diff --git a/web/src/pages/api/public/scores/index.ts b/web/src/pages/api/public/scores/index.tsindex e79f496f59..c619b0f9ed 100644--- a/web/src/pages/api/public/scores/index.ts+++ b/web/src/pages/api/public/scores/index.ts@@ -3,27 +3,24 @@ import { v4 } from "uuid";import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import {- GetScoresQuery,- GetScoresResponse,- legacyFilterAndValidateV1GetScoreList,- PostScoresBody,- PostScoresResponse,+ GetScoresQueryV1,+ GetScoresResponseV1,+ filterAndValidateV1GetScoreList,+ PostScoresBodyV1,+ PostScoresResponseV1,} from "@langfuse/shared";import {eventTypes,logger,processEventBatch,} from "@langfuse/shared/src/server";-import {- generateScoresForPublicApi,- getScoresCountForPublicApi,-} from "@/src/features/public-api/server/scores";+import { ScoresApiService } from "@/src/features/public-api/server/scores-api-service";export default withMiddlewares({POST: createAuthedProjectAPIRoute({name: "Create Score",- bodySchema: PostScoresBody,- responseSchema: PostScoresResponse,+ bodySchema: PostScoresBodyV1,+ responseSchema: PostScoresResponseV1,fn: async ({ body, auth, res }) => {const event = {id: v4(),@@ -51,9 +48,11 @@ export default withMiddlewares({}),GET: createAuthedProjectAPIRoute({name: "/api/public/scores",- querySchema: GetScoresQuery,- responseSchema: GetScoresResponse,+ querySchema: GetScoresQueryV1,+ responseSchema: GetScoresResponseV1,fn: async ({ query, auth }) => {+ const scoresApiService = new ScoresApiService("v1");+const scoreParams = {projectId: auth.scope.projectId,page: query.page ?? undefined,@@ -74,14 +73,16 @@ export default withMiddlewares({scoreIds: query.scoreIds ?? undefined,};const [items, count] = await Promise.all([- generateScoresForPublicApi(scoreParams),- getScoresCountForPublicApi(scoreParams),+ scoresApiService.generateScoresForPublicApi(scoreParams),+ scoresApiService.getScoresCountForPublicApi(scoreParams),]);const finalCount = count ? count : 0;return {- data: legacyFilterAndValidateV1GetScoreList(items),+ // As these are traces scores, we expect all scores to have a traceId set+ // For type consistency, we validate the scores against the v1 schema which requires a traceId+ data: filterAndValidateV1GetScoreList(items),meta: {page: query.page,limit: query.limit,diff --git a/web/src/pages/api/public/traces/[traceId].ts b/web/src/pages/api/public/traces/[traceId].tsindex 26fbc7b3c2..f2da7afbfa 100644--- a/web/src/pages/api/public/traces/[traceId].ts+++ b/web/src/pages/api/public/traces/[traceId].ts@@ -8,7 +8,7 @@ import {DeleteTraceV1Response,} from "@/src/features/public-api/types/traces";import {- filterAndValidateDbScoreList,+ filterAndValidateDbTraceScoreList,LangfuseNotFoundError,} from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";@@ -100,7 +100,9 @@ export default withMiddlewares({});const outObservations = observationsView.map(transformDbToApiObservation);- const validatedScores = filterAndValidateDbScoreList({+ // As these are traces scores, we expect all scores to have a traceId set+ // For type consistency, we validate the scores against the v1 schema which requires a traceId+ const validatedScores = filterAndValidateDbTraceScoreList({scores,onParseError: traceException,});diff --git a/web/src/pages/api/public/traces/index.ts b/web/src/pages/api/public/traces/index.tsindex f241053c4f..b0c28c284f 100644--- a/web/src/pages/api/public/traces/index.ts+++ b/web/src/pages/api/public/traces/index.ts@@ -9,23 +9,21 @@ import {import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { processEventBatch } from "@langfuse/shared/src/server";-import {eventTypes,logger,QueueJobs,TraceDeleteQueue,} from "@langfuse/shared/src/server";-import { v4 } from "uuid";import { telemetry } from "@/src/features/telemetry";+import { TRPCError } from "@trpc/server";+import { randomUUID } from "crypto";+import { auditLog } from "@/src/features/audit-logs/auditLog";import {generateTracesForPublicApi,getTracesCountForPublicApi,} from "@/src/features/public-api/server/traces";-import { TRPCError } from "@trpc/server";-import { randomUUID } from "crypto";-import { auditLog } from "@/src/features/audit-logs/auditLog";export default withMiddlewares({POST: createAuthedProjectAPIRoute({@@ -81,8 +79,11 @@ export default withMiddlewares({};const [items, count] = await Promise.all([- generateTracesForPublicApi(filterProps, query.orderBy ?? null),- getTracesCountForPublicApi(filterProps),+ generateTracesForPublicApi({+ props: filterProps,+ orderBy: query.orderBy ?? null,+ }),+ getTracesCountForPublicApi({ props: filterProps }),]);const finalCount = count || 0;diff --git a/web/src/pages/api/public/v2/scores/[scoreId].ts b/web/src/pages/api/public/v2/scores/[scoreId].tsnew file mode 100644index 0000000000..79bf537fbe--- /dev/null+++ b/web/src/pages/api/public/v2/scores/[scoreId].ts@@ -0,0 +1,39 @@+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";+import { ScoresApiService } from "@/src/features/public-api/server/scores-api-service";+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";+import {+ GetScoreQueryV2,+ GetScoreResponseV2,+ InternalServerError,+ LangfuseNotFoundError,+} from "@langfuse/shared";+import { logger, traceException } from "@langfuse/shared/src/server";++export default withMiddlewares({+ GET: createAuthedProjectAPIRoute({+ name: "Get Score",+ querySchema: GetScoreQueryV2,+ responseSchema: GetScoreResponseV2,+ fn: async ({ query, auth }) => {+ const scoresApiService = new ScoresApiService("v2");+ const score = await scoresApiService.getScoreById({+ projectId: auth.scope.projectId,+ scoreId: query.scoreId,+ });++ if (!score) {+ throw new LangfuseNotFoundError("Score not found");+ }++ const parsedScore = GetScoreResponseV2.safeParse(score);++ if (!parsedScore.success) {+ traceException(parsedScore.error);+ logger.error(`Incorrect score return type ${parsedScore.error}`);+ throw new InternalServerError("Requested score is corrupted");+ }++ return parsedScore.data;+ },+ }),+});diff --git a/web/src/pages/api/public/v2/scores/index.ts b/web/src/pages/api/public/v2/scores/index.tsnew file mode 100644index 0000000000..e36eca6295--- /dev/null+++ b/web/src/pages/api/public/v2/scores/index.ts@@ -0,0 +1,54 @@+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";+import {+ GetScoresQueryV2,+ GetScoresResponseV2,+ filterAndValidateV2GetScoreList,+} from "@langfuse/shared";+import { ScoresApiService } from "@/src/features/public-api/server/scores-api-service";++export default withMiddlewares({+ GET: createAuthedProjectAPIRoute({+ name: "/api/public/scores",+ querySchema: GetScoresQueryV2,+ responseSchema: GetScoresResponseV2,+ fn: async ({ query, auth }) => {+ const scoreParams = {+ projectId: auth.scope.projectId,+ page: query.page ?? undefined,+ limit: query.limit ?? undefined,+ userId: query.userId ?? undefined,+ name: query.name ?? undefined,+ configId: query.configId ?? undefined,+ queueId: query.queueId ?? undefined,+ traceTags: query.traceTags ?? undefined,+ dataType: query.dataType ?? undefined,+ fromTimestamp: query.fromTimestamp ?? undefined,+ toTimestamp: query.toTimestamp ?? undefined,+ environment: query.environment ?? undefined,+ traceEnvironment: query.environment ?? undefined,+ source: query.source ?? undefined,+ value: query.value ?? undefined,+ operator: query.operator ?? undefined,+ scoreIds: query.scoreIds ?? undefined,+ };+ const scoresApiService = new ScoresApiService("v2");+ const [items, count] = await Promise.all([+ scoresApiService.generateScoresForPublicApi(scoreParams),+ scoresApiService.getScoresCountForPublicApi(scoreParams),+ ]);++ const finalCount = count ? count : 0;++ return {+ data: filterAndValidateV2GetScoreList(items),+ meta: {+ page: query.page,+ limit: query.limit,+ totalItems: finalCount,+ totalPages: Math.ceil(finalCount / query.limit),+ },+ };+ },+ }),+});diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.tsindex b2f80c01b7..57f7df816b 100644--- a/web/src/server/api/routers/scores.ts+++ b/web/src/server/api/routers/scores.ts@@ -12,7 +12,6 @@ import {protectedProjectProcedure,} from "@/src/server/api/trpc";import {- CreateAnnotationScoreData,orderBy,paginationZod,singleFilter,@@ -26,6 +25,7 @@ import {BatchActionType,BatchExportTableName,type ScoreDomain,+ CreateAnnotationScoreData,} from "@langfuse/shared";import {getScoresGroupedByNameSourceType,@@ -44,12 +44,14 @@ import {QueueJobs,getScoreMetadataById,deleteScores,+ traceWithSessionIdExists,} from "@langfuse/shared/src/server";import { v4 } from "uuid";import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";import { createBatchActionJob } from "@/src/features/table/server/createBatchActionJob";import { TRPCError } from "@trpc/server";import { randomUUID } from "crypto";+import { isTraceScore } from "@/src/features/scores/lib/helpers";const ScoreFilterOptions = z.object({projectId: z.string(), // Required for protectedProjectProcedure@@ -140,7 +142,10 @@ export const scoresRouter = createTRPCRouter({}),).query(async ({ input }) => {- const score = await getScoreById(input.projectId, input.scoreId);+ const score = await getScoreById({+ projectId: input.projectId,+ scoreId: input.scoreId,+ });if (!score) {throw new TRPCError({code: "NOT_FOUND",@@ -270,24 +275,53 @@ export const scoresRouter = createTRPCRouter({scope: "scores:CUD",});- const clickhouseTrace = await getTraceById({- traceId: input.traceId,- projectId: input.projectId,- });+ const inflatedParams = isTraceScore(input.scoreTarget)+ ? {+ observationId: input.scoreTarget.observationId ?? null,+ traceId: input.scoreTarget.traceId,+ sessionId: null,+ }+ : {+ observationId: null,+ traceId: null,+ sessionId: input.scoreTarget.sessionId,+ };- if (!clickhouseTrace) {- logger.error(- `No trace with id ${input.traceId} in project ${input.projectId} in Clickhouse`,- );- throw new LangfuseNotFoundError(- `No trace with id ${input.traceId} in project ${input.projectId} in Clickhouse`,+ if (inflatedParams.traceId) {+ const clickhouseTrace = await getTraceById({+ traceId: inflatedParams.traceId,+ projectId: input.projectId,+ });++ if (!clickhouseTrace) {+ logger.error(+ `No trace with id ${inflatedParams.traceId} in project ${input.projectId} in Clickhouse`,+ );+ throw new LangfuseNotFoundError(+ `No trace with id ${inflatedParams.traceId} in project ${input.projectId} in Clickhouse`,+ );+ }+ } else if (inflatedParams.sessionId) {+ // We consider no longer writing all sessions into postgres, hence we should search for traces with the session id+ const isSessionReferenced = await traceWithSessionIdExists(+ input.projectId,+ inflatedParams.sessionId,);+ if (!isSessionReferenced) {+ logger.error(+ `No trace referencing session with id ${inflatedParams.sessionId} in project ${input.projectId} in Clickhouse`,+ );+ throw new LangfuseNotFoundError(+ `No trace referencing session with id ${inflatedParams.sessionId} in project ${input.projectId} in Clickhouse`,+ );+ }}const clickhouseScore = await searchExistingAnnotationScore(input.projectId,- input.traceId,- input.observationId ?? null,+ inflatedParams.observationId,+ inflatedParams.traceId,+ inflatedParams.sessionId,input.name,input.configId,);@@ -307,8 +341,7 @@ export const scoresRouter = createTRPCRouter({id: v4(),projectId: input.projectId,environment: input.environment ?? "default",- traceId: input.traceId,- observationId: input.observationId ?? null,+ ...inflatedParams,value: input.value ?? null,stringValue: input.stringValue ?? null,dataType: input.dataType ?? null,@@ -329,8 +362,9 @@ export const scoresRouter = createTRPCRouter({timestamp: convertDateToClickhouseDateTime(new Date()),project_id: input.projectId,environment: input.environment ?? "default",- trace_id: input.traceId,- observation_id: input.observationId,+ trace_id: inflatedParams.traceId,+ observation_id: inflatedParams.observationId,+ session_id: inflatedParams.sessionId,name: input.name,value: input.value !== null ? input.value : undefined,source: ScoreSource.ANNOTATION,@@ -364,11 +398,11 @@ export const scoresRouter = createTRPCRouter({let updatedScore: ScoreDomain | null | undefined = null;// Fetch the current score from Clickhouse- const score = await getScoreById(- input.projectId,- input.id,- ScoreSource.ANNOTATION,- );+ const score = await getScoreById({+ projectId: input.projectId,+ scoreId: input.id,+ source: ScoreSource.ANNOTATION,+ });if (!score) {logger.warn(`No annotation score with id ${input.id} in project ${input.projectId} in Clickhouse`,@@ -392,6 +426,7 @@ export const scoresRouter = createTRPCRouter({config_id: score.configId,trace_id: score.traceId,observation_id: score.observationId,+ session_id: score.sessionId,});updatedScore = {@@ -432,11 +467,11 @@ export const scoresRouter = createTRPCRouter({});// Fetch the current score from Clickhouse- const clickhouseScore = await getScoreById(- input.projectId,- input.id,- ScoreSource.ANNOTATION,- );+ const clickhouseScore = await getScoreById({+ projectId: input.projectId,+ scoreId: input.id,+ source: ScoreSource.ANNOTATION,+ });if (!clickhouseScore) {logger.warn(`No annotation score with id ${input.id} in project ${input.projectId} in Clickhouse`,diff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.tsindex 9b6b5138e4..03d6f43cd5 100644--- a/web/src/server/api/routers/sessions.ts+++ b/web/src/server/api/routers/sessions.ts@@ -11,6 +11,7 @@ import {type FilterState,orderBy,paginationZod,+ type PrismaClient,singleFilter,timeFilter,tracesTableUiColumnDefinitions,@@ -31,8 +32,10 @@ import {logger,getSessionsWithMetrics,hasAnySession,+ getScoresForSessions,} from "@langfuse/shared/src/server";import { chunk } from "lodash";+import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";const SessionFilterOptions = z.object({projectId: z.string(), // Required for protectedProjectProcedure@@ -41,6 +44,83 @@ const SessionFilterOptions = z.object({...paginationZod,});+const handleGetSessionById = async (input: {+ sessionId: string;+ projectId: string;+ ctx: {+ prisma: PrismaClient;+ };+}) => {+ const postgresSession = await input.ctx.prisma.traceSession.findFirst({+ where: {+ id: input.sessionId,+ projectId: input.projectId,+ },+ });++ if (!postgresSession) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Session not found in project",+ });+ }++ const clickhouseTraces = await getTracesIdentifierForSession(+ input.projectId,+ input.sessionId,+ );++ const chunks = chunk(clickhouseTraces, 500);++ // in the below queries, take the lowest timestamp as a filter condition+ // to improve performance+ const [scores, costs] = await Promise.all([+ Promise.all(+ chunks.map((chunk) =>+ getScoresForTraces({+ projectId: input.projectId,+ traceIds: chunk.map((t) => t.id),+ timestamp: new Date(+ Math.min(...chunk.map((t) => t.timestamp.getTime())),+ ),+ }),+ ),+ ).then((results) => results.flat()),+ Promise.all(+ chunks.map((chunk) =>+ getCostForTraces(+ input.projectId,+ new Date(Math.min(...chunk.map((t) => t.timestamp.getTime()))),+ chunk.map((t) => t.id),+ ),+ ),+ ).then((results) =>+ results.reduce((sum, cost) => (sum ?? 0) + (cost ?? 0), 0),+ ),+ ]);++ const costData = costs;++ const validatedScores = filterAndValidateDbScoreList({+ scores,+ onParseError: traceException,+ });++ return {+ ...postgresSession,+ traces: clickhouseTraces.map((t) => ({+ ...t,+ scores: validatedScores.filter((s) => s.traceId === t.id),+ })),+ totalCost: costData ?? 0,+ users: [+ ...new Set(+ clickhouseTraces.map((t) => t.userId).filter((t) => t !== null),+ ),+ ],+ };+};+export const sessionRouter = createTRPCRouter({hasAny: protectedProjectProcedure.input(@@ -67,6 +147,18 @@ export const sessionRouter = createTRPCRouter({limit: input.limit,});+ const scores = await getScoresForSessions({+ projectId: ctx.session.projectId,+ sessionIds: sessions.map((s) => s.session_id),+ limit: 1000,+ offset: 0,+ });++ const validatedScores = filterAndValidateDbScoreList({+ scores,+ onParseError: traceException,+ });+const prismaSessionInfo = await ctx.prisma.traceSession.findMany({where: {id: {@@ -87,6 +179,11 @@ export const sessionRouter = createTRPCRouter({userIds: s.user_ids,countTraces: s.trace_count,traceTags: s.trace_tags,+ scores: aggregateScores(+ validatedScores.filter(+ (score) => score.sessionId === s.session_id,+ ),+ ),createdAt: new Date(s.min_timestamp),bookmarked:prismaSessionInfo.find((p) => p.id === s.session_id)@@ -270,82 +367,41 @@ export const sessionRouter = createTRPCRouter({}),).query(async ({ input, ctx }) => {- try {- const postgresSession = await ctx.prisma.traceSession.findFirst({- where: {- id: input.sessionId,- projectId: input.projectId,- },- });-- if (!postgresSession) {- throw new TRPCError({- code: "NOT_FOUND",- message: "Session not found in project",- });- }-- const clickhouseTraces = await getTracesIdentifierForSession(- input.projectId,- input.sessionId,- );-- const chunks = chunk(clickhouseTraces, 500);-- // in the below queries, take the lowest timestamp as a filter condition- // to improve performance- const [scores, costs] = await Promise.all([- Promise.all(- chunks.map((chunk) =>- getScoresForTraces({- projectId: input.projectId,- traceIds: chunk.map((t) => t.id),- timestamp: new Date(- Math.min(...chunk.map((t) => t.timestamp.getTime())),- ),- }),- ),- ).then((results) => results.flat()),- Promise.all(- chunks.map((chunk) =>- getCostForTraces(- input.projectId,- new Date(Math.min(...chunk.map((t) => t.timestamp.getTime()))),- chunk.map((t) => t.id),- ),- ),- ).then((results) =>- results.reduce((sum, cost) => (sum ?? 0) + (cost ?? 0), 0),- ),- ]);-- const costData = costs;+ return await handleGetSessionById({+ sessionId: input.sessionId,+ projectId: input.projectId,+ ctx,+ });+ }),+ byIdWithScores: protectedGetSessionProcedure+ .input(+ z.object({+ sessionId: z.string(), // used for security check+ projectId: z.string(), // used for security check+ }),+ )+ .query(async ({ input, ctx }) => {+ const [scores, session] = await Promise.all([+ getScoresForSessions({+ projectId: input.projectId,+ sessionIds: [input.sessionId],+ }),+ handleGetSessionById({+ sessionId: input.sessionId,+ projectId: input.projectId,+ ctx,+ }),+ ]);- const validatedScores = filterAndValidateDbScoreList({- scores,- onParseError: traceException,- });+ const validatedScores = filterAndValidateDbScoreList({+ scores,+ onParseError: traceException,+ });- return {- ...postgresSession,- traces: clickhouseTraces.map((t) => ({- ...t,- scores: validatedScores.filter((s) => s.traceId === t.id),- })),- totalCost: costData ?? 0,- users: [- ...new Set(- clickhouseTraces.map((t) => t.userId).filter((t) => t !== null),- ),- ],- };- } catch (e) {- logger.error("Unable to get sessions.byId", e);- throw new TRPCError({- code: "INTERNAL_SERVER_ERROR",- message: "unable to get session",- });- }+ return {+ ...session,+ scores: validatedScores,+ };}),bookmark: protectedProjectProcedure.input(diff --git a/worker/src/__tests__/batchAction.test.ts b/worker/src/__tests__/batchAction.test.tsindex 07ef7729a0..59e3a2e444 100644--- a/worker/src/__tests__/batchAction.test.ts+++ b/worker/src/__tests__/batchAction.test.ts@@ -6,7 +6,7 @@ import { handleBatchActionJob } from "../features/batchAction/handleBatchActionJimport { getDatabaseReadStream } from "../features/database-read-stream/getDatabaseReadStream";import {createOrgProjectAndApiKey,- createScore,+ createTraceScore,createScoresCh,createTrace,createTracesCh,@@ -129,7 +129,7 @@ describe("select all test suite", () => {// Setupconst { projectId } = await createOrgProjectAndApiKey();- const score = createScore({ project_id: projectId });+ const score = createTraceScore({ project_id: projectId });await createScoresCh([score]);// Whendiff --git a/worker/src/__tests__/batchExport.test.ts b/worker/src/__tests__/batchExport.test.tsindex 610ed6c661..2f3ac91118 100644--- a/worker/src/__tests__/batchExport.test.ts+++ b/worker/src/__tests__/batchExport.test.ts@@ -4,7 +4,7 @@ import {createObservation,createObservationsCh,createOrgProjectAndApiKey,- createScore,+ createTraceScore,createScoresCh,createTrace,createTracesCh,@@ -35,7 +35,7 @@ describe("batch export test suite", () => {}),];- const score = createScore({+ const score = createTraceScore({project_id: projectId,trace_id: randomUUID(),observation_id: observations[0].id,@@ -190,7 +190,7 @@ describe("batch export test suite", () => {}),];- const score = createScore({+ const score = createTraceScore({project_id: projectId,trace_id: randomUUID(),observation_id: generations[0].id,@@ -375,7 +375,7 @@ describe("batch export test suite", () => {}),];- const score = createScore({+ const score = createTraceScore({project_id: projectId,trace_id: traces[0].id,observation_id: generations[0].id,@@ -383,7 +383,7 @@ describe("batch export test suite", () => {value: 123,});- const qualitativeScore = createScore({+ const qualitativeScore = createTraceScore({project_id: projectId,trace_id: traces[0].id,observation_id: generations[0].id,@@ -545,7 +545,7 @@ describe("batch export test suite", () => {// Create scores with different names and valuesconst scores = [- createScore({+ createTraceScore({project_id: projectId,trace_id: traces[0].id,observation_id: observations[0].id,@@ -553,7 +553,7 @@ describe("batch export test suite", () => {value: 0.85,timestamp: new Date("2024-01-01").getTime(),}),- createScore({+ createTraceScore({project_id: projectId,trace_id: traces[0].id,observation_id: observations[0].id,@@ -561,7 +561,7 @@ describe("batch export test suite", () => {value: 0.75,timestamp: new Date("2024-01-01").getTime(),}),- createScore({+ createTraceScore({project_id: projectId,trace_id: traces[1].id,observation_id: observations[1].id,@@ -569,7 +569,7 @@ describe("batch export test suite", () => {value: 0.92,timestamp: new Date("2024-01-02").getTime(),}),- createScore({+ createTraceScore({project_id: projectId,trace_id: traces[1].id,observation_id: observations[1].id,@@ -645,14 +645,14 @@ describe("batch export test suite", () => {// Create scores with string valuesconst scores = [- createScore({+ createTraceScore({project_id: projectId,trace_id: trace.id,observation_id: observation.id,name: "category",string_value: "excellent",}),- createScore({+ createTraceScore({project_id: projectId,trace_id: trace.id,observation_id: observation.id,@@ -728,7 +728,7 @@ describe("batch export test suite", () => {// Create scores with different timestampsconst scores = [- createScore({+ createTraceScore({project_id: projectId,trace_id: trace.id,observation_id: observation.id,@@ -736,7 +736,7 @@ describe("batch export test suite", () => {value: 0.5,timestamp: new Date("2024-01-01T10:00:00Z").getTime(),}),- createScore({+ createTraceScore({project_id: projectId,trace_id: trace.id,observation_id: observation.id,@@ -744,7 +744,7 @@ describe("batch export test suite", () => {value: 0.6,timestamp: new Date("2024-01-15T10:00:00Z").getTime(),}),- createScore({+ createTraceScore({project_id: projectId,trace_id: trace.id,observation_id: observation.id,@@ -834,7 +834,7 @@ describe("batch export test suite", () => {// Create scores with different attributesconst scores = [- createScore({+ createTraceScore({project_id: projectId,trace_id: traces[0].id,observation_id: observations[0].id,@@ -842,7 +842,7 @@ describe("batch export test suite", () => {value: 0.7,source: "API",}),- createScore({+ createTraceScore({project_id: projectId,trace_id: traces[0].id,observation_id: observations[0].id,@@ -850,7 +850,7 @@ describe("batch export test suite", () => {value: 0.8,source: "UI",}),- createScore({+ createTraceScore({project_id: projectId,trace_id: traces[1].id,observation_id: observations[1].id,@@ -858,7 +858,7 @@ describe("batch export test suite", () => {value: 0.9,source: "API",}),- createScore({+ createTraceScore({project_id: projectId,trace_id: traces[1].id,observation_id: observations[1].id,diff --git a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts b/worker/src/__tests__/blobStorageIntegrationProcessing.test.tsindex d7d7a1ca10..291dd46f21 100644--- a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts+++ b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts@@ -5,7 +5,7 @@ import {createObservation,createObservationsCh,createOrgProjectAndApiKey,- createScore,+ createTraceScore,createScoresCh,createTrace,createTracesCh,@@ -122,7 +122,7 @@ describe("BlobStorageIntegrationProcessingJob", () => {}),]),createScoresCh([- createScore({+ createTraceScore({id: scoreId,trace_id: traceId,project_id: projectId,@@ -334,7 +334,7 @@ describe("BlobStorageIntegrationProcessingJob", () => {}),]),createScoresCh([- createScore({+ createTraceScore({id: scoreId,trace_id: traceId,project_id: projectId,diff --git a/worker/src/__tests__/dataRetentionProcessing.test.ts b/worker/src/__tests__/dataRetentionProcessing.test.tsindex 7b66b233b4..8505e0c2de 100644--- a/worker/src/__tests__/dataRetentionProcessing.test.ts+++ b/worker/src/__tests__/dataRetentionProcessing.test.ts@@ -5,7 +5,7 @@ import {clickhouseClient,createObservation,createObservationsCh,- createScore,+ createTraceScore,createScoresCh,createTrace,createTracesCh,@@ -311,12 +311,12 @@ describe("DataRetentionProcessingJob", () => {// Setupconst baseId = randomUUID();await createScoresCh([- createScore({+ createTraceScore({id: `${baseId}-score-old`,project_id: projectId,timestamp: new Date(Date.now() - 1000 * 60 * 60 * 24 * 30).getTime(), // 30 days in the past}),- createScore({+ createTraceScore({id: `${baseId}-score-new`,project_id: projectId,}),@@ -328,9 +328,15 @@ describe("DataRetentionProcessingJob", () => {} as Job);// Then- const scoresOld = await getScoreById(projectId, `${baseId}-score-old`);+ const scoresOld = await getScoreById({+ projectId,+ scoreId: `${baseId}-score-old`,+ });expect(scoresOld).toBeUndefined();- const scoresNew = await getScoreById(projectId, `${baseId}-score-new`);+ const scoresNew = await getScoreById({+ projectId,+ scoreId: `${baseId}-score-new`,+ });expect(scoresNew).toBeDefined();});});diff --git a/worker/src/__tests__/projectDeletionProcessing.test.ts b/worker/src/__tests__/projectDeletionProcessing.test.tsindex bc71a17ea3..b2c4b466af 100644--- a/worker/src/__tests__/projectDeletionProcessing.test.ts+++ b/worker/src/__tests__/projectDeletionProcessing.test.ts@@ -5,7 +5,7 @@ import {convertDateToClickhouseDateTime,createObservation,createObservationsCh,- createScore,+ createTraceScore,createScoresCh,createTrace,createTracesCh,@@ -121,7 +121,7 @@ describe("ProjectDeletionProcessingJob", () => {}),]),createScoresCh([- createScore({+ createTraceScore({id: `${baseId}-score`,trace_id: `${baseId}-trace`,project_id: projectId,@@ -140,7 +140,7 @@ describe("ProjectDeletionProcessingJob", () => {expect(() =>getObservationById(`${baseId}-observation`, projectId),).rejects.toThrowError("not found");- const score = await getScoreById(projectId, `${baseId}-score`);+ const score = await getScoreById({ projectId, scoreId: `${baseId}-score` });expect(score).toBeUndefined();});diff --git a/worker/src/__tests__/scoreDeletion.test.ts b/worker/src/__tests__/scoreDeletion.test.tsindex ae5c0e58e4..063b4e1df8 100644--- a/worker/src/__tests__/scoreDeletion.test.ts+++ b/worker/src/__tests__/scoreDeletion.test.ts@@ -2,7 +2,7 @@ import { expect, describe, it, beforeAll } from "vitest";import {clickhouseClient,createOrgProjectAndApiKey,- createScore,+ createTraceScore,createScoresCh,getBlobStorageByProjectId,getScoresByIds,@@ -31,7 +31,7 @@ describe("score deletion", () => {// Setupconst { projectId } = await createOrgProjectAndApiKey();- const score = createScore({ project_id: projectId });+ const score = createTraceScore({ project_id: projectId });await createScoresCh([score]);// When@@ -47,7 +47,9 @@ describe("score deletion", () => {const { projectId } = await createOrgProjectAndApiKey();const scoreId = randomUUID();- await createScoresCh([createScore({ id: scoreId, project_id: projectId })]);+ await createScoresCh([+ createTraceScore({ id: scoreId, project_id: projectId }),+ ]);const fileType = "application/json";const data = JSON.stringify({ hello: "world" });diff --git a/worker/src/__tests__/traceDeletion.test.ts b/worker/src/__tests__/traceDeletion.test.tsindex 1234df84a3..3eff618fbf 100644--- a/worker/src/__tests__/traceDeletion.test.ts+++ b/worker/src/__tests__/traceDeletion.test.ts@@ -4,7 +4,7 @@ import {createObservation,createObservationsCh,createOrgProjectAndApiKey,- createScore,+ createTraceScore,createScoresCh,createTrace,createTracesCh,@@ -51,7 +51,7 @@ describe("trace deletion", () => {const traceId = randomUUID();await createTracesCh([createTrace({ id: traceId })]);await createObservationsCh([createObservation({ trace_id: traceId })]);- await createScoresCh([createScore({ trace_id: traceId })]);+ await createScoresCh([createTraceScore({ trace_id: traceId })]);// Whenawait processClickhouseTraceDelete("projectId", [traceId]);@@ -262,7 +262,11 @@ describe("trace deletion", () => {}),]);await createScoresCh([- createScore({ id: scoreId, trace_id: traceId, project_id: projectId }),+ createTraceScore({+ id: scoreId,+ trace_id: traceId,+ project_id: projectId,+ }),]);const fileType = "application/json";diff --git a/worker/src/features/database-read-stream/getDatabaseReadStream.ts b/worker/src/features/database-read-stream/getDatabaseReadStream.tsindex bbee056d8a..b2e8b3f687 100644--- a/worker/src/features/database-read-stream/getDatabaseReadStream.ts+++ b/worker/src/features/database-read-stream/getDatabaseReadStream.ts@@ -125,6 +125,7 @@ export const getDatabaseReadStream = async ({return scores.map((score) => ({id: score.id,traceId: score.traceId,+ sessionId: score.sessionId,timestamp: score.timestamp,source: score.source,name: score.name,diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex ecad02c454..92b67cd7a6 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -184,6 +184,7 @@ export class IngestionService {value: validatedScore.value,source: validatedScore.source,trace_id: validatedScore.traceId,+ session_id: validatedScore.sessionId,data_type: validatedScore.dataType,observation_id: validatedScore.observationId,comment: validatedScore.comment,