πͺ’ 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 run level scores (#6676)
marliessophie159f7560a440
diff --git a/fern/apis/client/definition/score.yml b/fern/apis/client/definition/score.ymlindex 1d62dc9606..cb7c41ae7a 100644--- a/fern/apis/client/definition/score.yml+++ b/fern/apis/client/definition/score.yml@@ -17,6 +17,7 @@ types:traceId: optional<string>sessionId: optional<string>observationId: optional<string>+ datasetRunId: optional<string>name: stringvalue:type: CreateScoreValue@@ -70,64 +71,11 @@ types:name: "contextrelevant"value: "not relevant"sessionId: "abyt-1234-5678-80ab"- BaseScore:- properties:- id: string- traceId: string- name: string- source: ScoreSource- observationId: optional<string>- 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- NumericScore:- extends: BaseScore- properties:- value:- type: double- docs: The numeric value of the score- BooleanScore:- extends: BaseScore- 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"- CategoricalScore:- extends: BaseScore- 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- # Question: where is this used, if not needed remove BaseScore too- Score:- discriminant: "dataType"- union:- NUMERIC:- type: NumericScore- docs: "Score with NUMERIC data type"- CATEGORICAL:- type: CategoricalScore- docs: "Score with CATEGORICAL data type"- BOOLEAN:- type: BooleanScore- docs: "Score with BOOLEAN data type"- ScoreSource:- enum:- - ANNOTATION- - API- - EVAL+ - value:+ name: "hallucination"+ value: 0+ datasetRunId: "7891-5678-90ab-hijk"+ScoreDataType:enum:- NUMERICdiff --git a/fern/apis/server/definition/commons.yml b/fern/apis/server/definition/commons.ymlindex c99b6c5b13..b98fd085a5 100644--- a/fern/apis/server/definition/commons.yml+++ b/fern/apis/server/definition/commons.yml@@ -305,6 +305,7 @@ types:traceId: optional<string>sessionId: optional<string>observationId: optional<string>+ datasetRunId: optional<string>name: stringsource: ScoreSourcetimestamp: datetimediff --git a/fern/apis/server/definition/ingestion.yml b/fern/apis/server/definition/ingestion.ymlindex 2864b9c23a..d480a1f5f6 100644--- a/fern/apis/server/definition/ingestion.yml+++ b/fern/apis/server/definition/ingestion.yml@@ -266,6 +266,7 @@ types:traceId: optional<string>sessionId: optional<string>observationId: optional<string>+ datasetRunId: optional<string>name: stringenvironment: optional<string>value:@@ -320,6 +321,10 @@ types:name: "contextrelevant"value: "not relevant"sessionId: "abyt-1234-5678-80ab"+ - value:+ name: "hallucination"+ value: 0+ datasetRunId: "7891-5678-90ab-hijk"BaseEvent:properties:diff --git a/fern/apis/server/definition/score.yml b/fern/apis/server/definition/score.ymlindex 5c494e26d5..aefafddbd3 100644--- a/fern/apis/server/definition/score.yml+++ b/fern/apis/server/definition/score.yml@@ -27,6 +27,7 @@ types:traceId: optional<string>sessionId: optional<string>observationId: optional<string>+ datasetRunId: optional<string>name: stringvalue:type: commons.CreateScoreValuediff --git a/packages/shared/clickhouse/migrations/clustered/0017_add_run_id_column_scores.down.sql b/packages/shared/clickhouse/migrations/clustered/0017_add_run_id_column_scores.down.sqlnew file mode 100644index 0000000000..5993426be8--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0017_add_run_id_column_scores.down.sql@@ -0,0 +1 @@+ALTER TABLE scores ON CLUSTER default DROP COLUMN IF EXISTS dataset_run_id SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/clustered/0017_add_run_id_column_scores.up.sql b/packages/shared/clickhouse/migrations/clustered/0017_add_run_id_column_scores.up.sqlnew file mode 100644index 0000000000..37a3af3aa7--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0017_add_run_id_column_scores.up.sql@@ -0,0 +1 @@+ALTER TABLE scores ON CLUSTER default ADD COLUMN dataset_run_id Nullable(String) AFTER session_id SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/clustered/0018_add_scores_run_index.down.sql b/packages/shared/clickhouse/migrations/clustered/0018_add_scores_run_index.down.sqlnew file mode 100644index 0000000000..714f111830--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0018_add_scores_run_index.down.sql@@ -0,0 +1 @@+ALTER TABLE scores ON CLUSTER default DROP INDEX IF EXISTS idx_project_dataset_run SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/clustered/0018_add_scores_run_index.up.sql b/packages/shared/clickhouse/migrations/clustered/0018_add_scores_run_index.up.sqlnew file mode 100644index 0000000000..76f6c840f2--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0018_add_scores_run_index.up.sql@@ -0,0 +1,2 @@+ALTER TABLE scores ON CLUSTER default ADD INDEX IF NOT EXISTS idx_project_dataset_run (project_id, dataset_run_id) TYPE bloom_filter(0.001) GRANULARITY 1 SETTINGS mutations_sync = 2;+ALTER TABLE scores ON CLUSTER default MATERIALIZE INDEX IF EXISTS idx_project_dataset_run SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/unclustered/0017_add_run_id_column_scores.down.sql b/packages/shared/clickhouse/migrations/unclustered/0017_add_run_id_column_scores.down.sqlnew file mode 100644index 0000000000..f511371464--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0017_add_run_id_column_scores.down.sql@@ -0,0 +1 @@+ALTER TABLE scores DROP COLUMN IF EXISTS dataset_run_id SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/unclustered/0017_add_run_id_column_scores.up.sql b/packages/shared/clickhouse/migrations/unclustered/0017_add_run_id_column_scores.up.sqlnew file mode 100644index 0000000000..74f42181a8--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0017_add_run_id_column_scores.up.sql@@ -0,0 +1 @@+ALTER TABLE scores ADD COLUMN dataset_run_id Nullable(String) AFTER session_id SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/unclustered/0018_add_scores_run_index.down.sql b/packages/shared/clickhouse/migrations/unclustered/0018_add_scores_run_index.down.sqlnew file mode 100644index 0000000000..530007aa81--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0018_add_scores_run_index.down.sql@@ -0,0 +1 @@+ALTER TABLE scores DROP INDEX IF EXISTS idx_project_dataset_run SETTINGS mutations_sync = 2;diff --git a/packages/shared/clickhouse/migrations/unclustered/0018_add_scores_run_index.up.sql b/packages/shared/clickhouse/migrations/unclustered/0018_add_scores_run_index.up.sqlnew file mode 100644index 0000000000..4b36b72b52--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0018_add_scores_run_index.up.sql@@ -0,0 +1,2 @@+ALTER TABLE scores ADD INDEX IF NOT EXISTS idx_project_dataset_run (project_id, dataset_run_id) TYPE bloom_filter(0.001) GRANULARITY 1 SETTINGS mutations_sync = 2;+ALTER TABLE scores MATERIALIZE INDEX IF EXISTS idx_project_dataset_run SETTINGS mutations_sync = 2;diff --git a/packages/shared/scripts/prepareClickhouse.ts b/packages/shared/scripts/prepareClickhouse.tsindex 0732e37af4..87169326f2 100644--- a/packages/shared/scripts/prepareClickhouse.ts+++ b/packages/shared/scripts/prepareClickhouse.ts@@ -149,6 +149,7 @@ export const prepareClickhouse = async ('default' AS environment,toString(floor(randUniform(0, ${tracesPerProject}))) AS trace_id,NULL AS session_id,+ NULL AS dataset_run_id,if(rand() > 0.9,toString(floor(randUniform(0, ${observationsPerProject}))),@@ -214,6 +215,7 @@ export const prepareClickhouse = async ('default' AS environment,NULL AS trace_id,arrayElement(['${sessionsToScore.map((s) => s.session_id).join("','")}'], 1 + (number % ${sessionsToScore.length})) AS session_id,+ NULL AS dataset_run_id,NULL AS observation_id,concat('session_quality_', toString(rand() % 10)) AS name,randUniform(0, 100) AS value,diff --git a/packages/shared/src/domain/scores.ts b/packages/shared/src/domain/scores.tsindex 941de73e31..a7fcf172e7 100644--- a/packages/shared/src/domain/scores.ts+++ b/packages/shared/src/domain/scores.ts@@ -23,6 +23,7 @@ export const ScoreSchema = z.object({comment: z.string().nullable(),traceId: z.string().nullable(),sessionId: z.string().nullable(),+ datasetRunId: z.string().nullable(),metadata: MetadataDomain,observationId: z.string().nullable(),configId: z.string().nullable(),diff --git a/packages/shared/src/features/scores/interfaces/README.md b/packages/shared/src/features/scores/interfaces/README.mdindex 1c6f847381..caa79e6e8a 100644--- a/packages/shared/src/features/scores/interfaces/README.md+++ b/packages/shared/src/features/scores/interfaces/README.md@@ -28,12 +28,12 @@ interfaces/## API VersioningWe 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.+POST and DELETE APIs will continue to support all score types (trace, session, dataset run) 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+- **V2 API**: Makes `traceId` optional, adds `sessionId` and `datasetRunId` support, supports all score types (trace, session, run)- Both versions maintain compatibility for existing clients## Usage Guide@@ -65,4 +65,4 @@ import {## Type Flow-Client β `PostScoresBody` β Validation β Database β `ScoreDomain` β API response (`APIScoreV2`) β UI (`ScoreSimplified` or `LastUserScore`)+Client β `PostScoresBody` β Validation β API response (`APIScoreV2`) β UI (`ScoreSimplified` or `ScoreDomain`)diff --git a/packages/shared/src/features/scores/interfaces/api/shared.ts b/packages/shared/src/features/scores/interfaces/api/shared.tsindex 16405cc9d6..74e3c79f8e 100644--- a/packages/shared/src/features/scores/interfaces/api/shared.ts+++ b/packages/shared/src/features/scores/interfaces/api/shared.ts@@ -30,7 +30,7 @@ export const BooleanData = z.object({});/**- * 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+ * 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 and dataset run scores* @see {@link ScoreFoundationSchemaV1}, {@link ScoreFoundationSchemaV2}** Must also be extended with score data specific schema (numeric, categorical, boolean)@@ -86,7 +86,7 @@ export const GetScoresQuery = z.object({});// POST /scores-// Please note that the POST /scores endpoint supports both trace and session level scores across v1 and v2.+// Please note that the POST /scores endpoint supports all score types (trace, session, dataset run) 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`*/@@ -129,7 +129,7 @@ export const PostScoresBody = applyScoreValidation(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.+// Please note that the DELETE /scores/{scoreId} endpoint supports all score types (trace, session, dataset run) across v1 and v2.export const DeleteScoreQuery = z.object({scoreId: z.string(),});diff --git a/packages/shared/src/features/scores/interfaces/api/v2/schemas.ts b/packages/shared/src/features/scores/interfaces/api/v2/schemas.tsindex 8f1910bb84..67f985025f 100644--- a/packages/shared/src/features/scores/interfaces/api/v2/schemas.ts+++ b/packages/shared/src/features/scores/interfaces/api/v2/schemas.ts@@ -16,6 +16,7 @@ const ScoreFoundationSchemaV2 = ScoreFoundationSchema.extend({traceId: z.string().nullish(),observationId: z.string().nullish(),sessionId: z.string().nullish(),+ datasetRunId: z.string().nullish(),});export const APIScoreSchemaV2 = z.discriminatedUnion("dataType", [diff --git a/packages/shared/src/features/scores/interfaces/shared.ts b/packages/shared/src/features/scores/interfaces/shared.tsindex 0b9de8e2bf..8573be9e77 100644--- a/packages/shared/src/features/scores/interfaces/shared.ts+++ b/packages/shared/src/features/scores/interfaces/shared.ts@@ -12,6 +12,7 @@ export const PostScoreBodyFoundationSchema = z.object({name: NonEmptyString,traceId: z.string().nullish(),sessionId: z.string().nullish(),+ datasetRunId: z.string().nullish(),observationId: z.string().nullish(),comment: z.string().nullish(),metadata: jsonSchema.nullish(),diff --git a/packages/shared/src/server/ingestion/types.ts b/packages/shared/src/server/ingestion/types.tsindex ed67d9a42d..9b8ff6db3a 100644--- a/packages/shared/src/server/ingestion/types.ts+++ b/packages/shared/src/server/ingestion/types.ts@@ -319,6 +319,7 @@ const BaseScoreBody = z.object({name: NonEmptyString,traceId: z.string().nullish(),sessionId: z.string().nullish(),+ datasetRunId: z.string().nullish(),environment: EnvironmentName,observationId: z.string().nullish(),comment: z.string().nullish(),diff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.tsindex 50af5e5974..99342b015f 100644--- a/packages/shared/src/server/repositories/definitions.ts+++ b/packages/shared/src/server/repositories/definitions.ts@@ -128,6 +128,7 @@ export const scoreRecordBaseSchema = z.object({trace_id: z.string().nullish(),session_id: z.string().nullish(),observation_id: z.string().nullish(),+ dataset_run_id: z.string().nullish(),environment: z.string().default("default"),name: z.string(),value: z.number().nullish(),@@ -354,6 +355,7 @@ export const convertPostgresScoreToInsert = (project_id: score.project_id,trace_id: score.trace_id,session_id: null,+ dataset_run_id: null,observation_id: score.observation_id,environment: score.environment,name: score.name,diff --git a/packages/shared/src/server/repositories/scores-utils.ts b/packages/shared/src/server/repositories/scores-utils.tsindex 0d8c9cc7a4..19da04ec9b 100644--- a/packages/shared/src/server/repositories/scores-utils.ts+++ b/packages/shared/src/server/repositories/scores-utils.ts@@ -25,7 +25,7 @@ export const _handleGetScoreById = async ({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" : ""}+ ${scoreScope === "traces_only" ? "AND s.session_id IS NULL AND s.dataset_run_id IS NULL" : ""}ORDER BY s.event_ts DESCLIMIT 1 BY s.id, s.project_idLIMIT 1@@ -70,7 +70,7 @@ export const _handleGetScoresByIds = async ({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" : ""}+ ${scoreScope === "traces_only" ? "AND s.session_id IS NULL AND s.dataset_run_id IS NULL" : ""}ORDER BY s.event_ts DESCLIMIT 1 BY s.id, s.project_id`;diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.tsindex da40a6273b..ccbafad43d 100644--- a/packages/shared/src/server/repositories/scores.ts+++ b/packages/shared/src/server/repositories/scores.ts@@ -157,6 +157,19 @@ type GetScoresForSessionsProps<includeHasMetadata?: IncludeHasMetadata;};+type GetScoresForDatasetRunsProps<+ ExcludeMetadata extends boolean,+ IncludeHasMetadata extends boolean,+> = {+ projectId: string;+ runIds: string[];+ limit?: number;+ offset?: number;+ clickhouseConfigs?: ClickHouseClientConfigOptions;+ excludeMetadata?: ExcludeMetadata;+ includeHasMetadata?: IncludeHasMetadata;+};+const formatMetadataSelect = (excludeMetadata: boolean,includeHasMetadata: boolean,@@ -220,6 +233,55 @@ export const getScoresForSessions = async <return rows.map(convertToScore);};+export const getScoresForDatasetRuns = async <+ ExcludeMetadata extends boolean,+ IncludeHasMetadata extends boolean,+>(+ props: GetScoresForDatasetRunsProps<ExcludeMetadata, IncludeHasMetadata>,+) => {+ const {+ projectId,+ runIds,+ 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.dataset_run_id IN ({runIds: 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,+ runIds,+ 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,@@ -586,6 +648,7 @@ export async function getScoresUiTable<comment: string | null;trace_id: string | null;session_id: string | null;+ dataset_run_id: string | null;metadata: ExcludeMetadata extends true ? never : Record<string, string>;observation_id: string | null;author_user_id: string | null;@@ -617,6 +680,7 @@ export async function getScoresUiTable<traceId: row.trace_id,sessionId: row.session_id,observationId: row.observation_id,+ datasetRunId: row.dataset_run_id,traceUserId: row.user_id,traceName: row.trace_name,traceTags: row.trace_tags,diff --git a/packages/shared/src/server/repositories/scores_converters.ts b/packages/shared/src/server/repositories/scores_converters.tsindex 7e9555c5c3..cbb626860f 100644--- a/packages/shared/src/server/repositories/scores_converters.ts+++ b/packages/shared/src/server/repositories/scores_converters.ts@@ -22,6 +22,7 @@ export const convertToScore = (row: ScoreRecordReadType): ScoreDomain => {traceId: row.trace_id ?? null,sessionId: row.session_id ?? null,observationId: row.observation_id ?? null,+ datasetRunId: row.dataset_run_id ?? null,name: row.name,value: row.value ?? null,source: row.source as ScoreSourceType,diff --git a/packages/shared/src/server/test-utils/tracing-factory.ts b/packages/shared/src/server/test-utils/tracing-factory.tsindex 37df1513c7..801f9bfd54 100644--- a/packages/shared/src/server/test-utils/tracing-factory.ts+++ b/packages/shared/src/server/test-utils/tracing-factory.ts@@ -96,6 +96,7 @@ export const createTraceScore = (is_deleted: 0,...score,session_id: null,+ dataset_run_id: null,};};@@ -121,5 +122,32 @@ export const createSessionScore = (...score,observation_id: null,trace_id: null,+ dataset_run_id: null,+ };+};++export const createDatasetRunScore = (+ score: Partial<ScoreRecordInsertType>,+): ScoreRecordInsertType => {+ return {+ id: v4(),+ project_id: v4(),+ dataset_run_id: v4(),+ environment: "default",+ name: "test-run-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,+ session_id: null,};};diff --git a/packages/shared/src/utils/scores.ts b/packages/shared/src/utils/scores.tsindex 6d7bf70ce2..e132cee60d 100644--- a/packages/shared/src/utils/scores.ts+++ b/packages/shared/src/utils/scores.ts@@ -7,16 +7,21 @@ export const applyScoreValidation = <T extends z.ZodType<any, any, any>>((data) => {const hasTraceId = !!data.traceId;const hasSessionId = !!data.sessionId;+ const hasDatasetRunId = !!data.datasetRunId;return (- (hasTraceId && !hasSessionId) ||- (hasSessionId && !hasTraceId && !data.observationId)+ (hasTraceId && !hasSessionId && !hasDatasetRunId) ||+ (hasSessionId &&+ !hasTraceId &&+ !hasDatasetRunId &&+ !data.observationId) ||+ (hasDatasetRunId && !hasTraceId && !hasSessionId && !data.observationId));},{message:- "Either provide traceId (with optional observationId) or sessionId, but not both. ObservationId requires traceId.",- path: ["traceId", "sessionId", "observationId"],+ "Provide exactly one of the following: traceId (with optional observationId), sessionId or datasetRunId. ObservationId requires traceId.",+ path: ["traceId", "sessionId", "datasetRunId", "observationId"],},);};diff --git a/web/public/generated/api-client/openapi.yml b/web/public/generated/api-client/openapi.ymlindex df42018fd4..dcd9697b8f 100644--- a/web/public/generated/api-client/openapi.yml+++ b/web/public/generated/api-client/openapi.yml@@ -63,6 +63,9 @@ components:observationId:type: stringnullable: true+ datasetRunId:+ type: string+ nullable: truename:type: stringexample: novelty@@ -95,148 +98,6 @@ components:required:- name- value- BaseScore:- title: BaseScore- type: object- properties:- id:- type: string- traceId:- type: string- name:- type: string- source:- $ref: '#/components/schemas/ScoreSource'- observationId:- type: string- nullable: true- 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- required:- - id- - traceId- - name- - source- - timestamp- - createdAt- - updatedAt- NumericScore:- title: NumericScore- type: object- properties:- value:- type: number- format: double- description: The numeric value of the score- required:- - value- allOf:- - $ref: '#/components/schemas/BaseScore'- BooleanScore:- title: BooleanScore- 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/BaseScore'- CategoricalScore:- title: CategoricalScore- 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/BaseScore'- Score:- title: Score- oneOf:- - type: object- allOf:- - type: object- properties:- dataType:- type: string- enum:- - NUMERIC- - $ref: '#/components/schemas/NumericScore'- required:- - dataType- - type: object- allOf:- - type: object- properties:- dataType:- type: string- enum:- - CATEGORICAL- - $ref: '#/components/schemas/CategoricalScore'- required:- - dataType- - type: object- allOf:- - type: object- properties:- dataType:- type: string- enum:- - BOOLEAN- - $ref: '#/components/schemas/BooleanScore'- required:- - dataType- ScoreSource:- title: ScoreSource- type: string- enum:- - ANNOTATION- - API- - EVALScoreDataType:title: ScoreDataTypetype: stringdiff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.ymlindex 07bbb27b9a..f53326eb4c 100644--- a/web/public/generated/api/openapi.yml+++ b/web/public/generated/api/openapi.yml@@ -4822,6 +4822,9 @@ components:observationId:type: stringnullable: true+ datasetRunId:+ type: string+ nullable: truename:type: stringsource:@@ -5822,6 +5825,9 @@ components:observationId:type: stringnullable: true+ datasetRunId:+ type: string+ nullable: truename:type: stringexample: novelty@@ -7232,6 +7238,9 @@ components:observationId:type: stringnullable: true+ datasetRunId:+ type: string+ nullable: truename:type: stringexample: noveltydiff --git a/web/src/__tests__/async/scores-api-v2.servertest.ts b/web/src/__tests__/async/scores-api-v2.servertest.tsindex 883a0fe9de..83efe51be2 100644--- a/web/src/__tests__/async/scores-api-v2.servertest.ts+++ b/web/src/__tests__/async/scores-api-v2.servertest.ts@@ -3,6 +3,7 @@ import {createTraceScore,createTrace,createSessionScore,+ createDatasetRunScore,} from "@langfuse/shared/src/server";import {createObservationsCh,@@ -140,6 +141,52 @@ describe("/api/public/v2/scores API Endpoint", () => {sessionId,observationId: null,traceId: null,+ datasetRunId: null,+ dataType: "NUMERIC",+ });+ });++ it("should GET a run score", async () => {+ const { projectId: projectId, auth } = await createOrgProjectAndApiKey();++ const scoreId = v4();+ const runId = v4();+ const score = createDatasetRunScore({+ id: scoreId,+ project_id: projectId,+ dataset_run_id: runId,+ 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",+ datasetRunId: runId,+ observationId: null,+ traceId: null,dataType: "NUMERIC",});});@@ -158,6 +205,7 @@ describe("/api/public/v2/scores API Endpoint", () => {const traceId_3 = v4();const generationId = v4();const sessionId = v4();+ const runId = v4();const scoreId_1 = v4();const scoreId_2 = v4();const scoreId_3 = v4();@@ -165,6 +213,8 @@ describe("/api/public/v2/scores API Endpoint", () => {const scoreId_5 = v4();const scoreId_6 = v4();const scoreId_7 = v4();+ const scoreId_8 = v4();+ const scoreId_9 = v4();let authentication: string;let newProjectId: string;@@ -291,6 +341,24 @@ describe("/api/public/v2/scores API Endpoint", () => {data_type: "NUMERIC",});+ const runScore1 = createDatasetRunScore({+ id: scoreId_8,+ project_id: newProjectId,+ dataset_run_id: runId,+ name: scoreName,+ value: 100.5,+ data_type: "NUMERIC",+ });++ const runScore2 = createDatasetRunScore({+ id: scoreId_9,+ project_id: newProjectId,+ dataset_run_id: runId,+ name: scoreName,+ value: 100.5,+ data_type: "NUMERIC",+ });+await createScoresCh([score1,score2,@@ -299,6 +367,8 @@ describe("/api/public/v2/scores API Endpoint", () => {score5,sessionScore1,sessionScore2,+ runScore1,+ runScore2,]);});@@ -314,7 +384,7 @@ describe("/api/public/v2/scores API Endpoint", () => {expect(getAllScore.body.meta).toMatchObject({page: 1,limit: 50,- totalItems: 7,+ totalItems: 9,totalPages: 1,});for (const val of getAllScore.body.data) {@@ -323,10 +393,19 @@ describe("/api/public/v2/scores API Endpoint", () => {sessionId: null,});} else {- expect(val).toMatchObject({- sessionId: sessionId,- trace: null,- });+ expect(val).toEqual(+ expect.objectContaining({+ trace: null,+ ...(val.sessionId === sessionId ? { sessionId } : {}),+ ...(val.datasetRunId+ ? { datasetRunId: expect.any(String) }+ : {}),+ }),+ );+ // Check that one of the two conditions is true+ expect(+ val.sessionId === sessionId || val.datasetRunId,+ ).toBeTruthy();}}});@@ -369,7 +448,7 @@ describe("/api/public/v2/scores API Endpoint", () => {expect(getAllScore.body.meta).toMatchObject({page: 1,limit: 50,- totalItems: 5,+ totalItems: 7,totalPages: 1,});for (const val of getAllScore.body.data) {diff --git a/web/src/features/datasets/components/DatasetRunsTable.tsx b/web/src/features/datasets/components/DatasetRunsTable.tsxindex 7a951e5bdc..0d73c74b7b 100644--- a/web/src/features/datasets/components/DatasetRunsTable.tsx+++ b/web/src/features/datasets/components/DatasetRunsTable.tsx@@ -67,7 +67,8 @@ export type DatasetRunRowData = {avgLatency: number | undefined;avgTotalCost: string | undefined;// scores holds grouped column with individual scores- scores?: ScoreAggregate | undefined;+ runItemScores?: ScoreAggregate | undefined;+ runScores?: ScoreAggregate | undefined;description: string;metadata: Prisma.JsonValue;};@@ -235,10 +236,22 @@ export function DatasetRunsTable(props: {const { scoreColumns, scoreKeysAndProps, isColumnLoading } =useIndividualScoreColumns<DatasetRunRowData>({projectId: props.projectId,- scoreColumnKey: "scores",- showAggregateViewOnly: true,+ scoreColumnKey: "runItemScores",+ showAggregateViewOnly: false,+ scoreColumnPrefix: "Aggregated",});+ const {+ scoreColumns: runScoreColumns,+ scoreKeysAndProps: runScoreKeysAndProps,+ isColumnLoading: isRunScoreColumnLoading,+ } = useIndividualScoreColumns<DatasetRunRowData>({+ projectId: props.projectId,+ scoreColumnKey: "runScores",+ showAggregateViewOnly: false,+ scoreColumnPrefix: "Run-level",+ });+const scoreIdToName = useMemo(() => {return new Map(scoreKeysAndProps.map((obj) => [obj.key, obj.name]) ?? []);}, [scoreKeysAndProps]);@@ -384,7 +397,22 @@ export function DatasetRunsTable(props: {return <>{avgTotalCost}</>;},},- { ...getScoreGroupColumnProps(isColumnLoading), columns: scoreColumns },+ {+ ...getScoreGroupColumnProps(isRunScoreColumnLoading, {+ accessorKey: "runScores",+ header: "Run-level Scores",+ id: "runScores",+ }),+ columns: runScoreColumns,+ },+ {+ ...getScoreGroupColumnProps(isColumnLoading, {+ accessorKey: "runItemScores",+ header: "Aggregated Run Items Scores",+ id: "runItemScores",+ }),+ columns: scoreColumns,+ },{accessorKey: "createdAt",header: "Created",@@ -440,7 +468,7 @@ export function DatasetRunsTable(props: {];const convertToTableRow = (- item: RouterOutput["datasets"]["runsByDatasetId"]["runs"][number],+ item: DatasetsCoreOutput & Partial<DatasetsMetricOutput>,): DatasetRunRowData => {return {id: item.id,@@ -451,8 +479,19 @@ export function DatasetRunsTable(props: {avgTotalCost: item.avgTotalCost? usdFormatter(item.avgTotalCost.toNumber()): undefined,- scores: item.scores- ? verifyAndPrefixScoreDataAgainstKeys(scoreKeysAndProps, item.scores)+ runItemScores: item.scores+ ? verifyAndPrefixScoreDataAgainstKeys(+ scoreKeysAndProps,+ item.scores,+ "Aggregated",+ )+ : undefined,+ runScores: item.runScores+ ? verifyAndPrefixScoreDataAgainstKeys(+ runScoreKeysAndProps,+ item.runScores,+ "Run-level",+ ): undefined,description: item.description ?? "",metadata: item.metadata,diff --git a/web/src/features/datasets/server/service.ts b/web/src/features/datasets/server/service.tsindex 7431021c13..e01c9dc707 100644--- a/web/src/features/datasets/server/service.ts+++ b/web/src/features/datasets/server/service.ts@@ -16,6 +16,7 @@ import {getLatencyAndTotalCostForObservations,getLatencyAndTotalCostForObservationsByTraces,getObservationsById,+ getScoresForDatasetRuns,getScoresForTraces,getTracesByIds,logger,@@ -94,12 +95,19 @@ export const createDatasetRunsTable = async (input: DatasetRunsTableInput) => {// these calls need to happen sequentially as there can be only one active session with// the same session_id at the time.- const scores = await getScoresFromTempTable(+ const traceScores = await getTraceScoresFromTempTable(input,tableName,clickhouseSession,);+ const runScores = await getScoresForDatasetRuns({+ projectId: input.projectId,+ runIds: runs.map((r) => r.run_id),+ includeHasMetadata: true,+ excludeMetadata: false,+ });+const obsAgg = await getObservationLatencyAndCostForDataset(input,tableName,@@ -131,7 +139,13 @@ export const createDatasetRunsTable = async (input: DatasetRunsTableInput) => {createdAt: run.run_created_at,updatedAt: run.run_updated_at,avgLatency: trace?.latency ?? observation?.latency ?? 0,- scores: aggregateScores(scores.filter((s) => s.run_id === run.run_id)),+ scores: aggregateScores(+ traceScores.filter((s) => s.run_id === run.run_id),+ ),+ // check this one+ runScores: aggregateScores(+ runScores.filter((s) => s.datasetRunId === run.run_id),+ ),};});@@ -246,7 +260,7 @@ export const getDatasetRunsFromPostgres = async ();};-const getScoresFromTempTable = async (+const getTraceScoresFromTempTable = async (input: DatasetRunsTableInput,tableName: string,clickhouseSession: string,diff --git a/web/src/features/public-api/server/scores.ts b/web/src/features/public-api/server/scores.tsindex 66ce018830..eebc76068e 100644--- a/web/src/features/public-api/server/scores.ts+++ b/web/src/features/public-api/server/scores.ts@@ -62,7 +62,8 @@ export const _handleGenerateScoresForPublicApi = async ({s.queue_id as queue_id,s.trace_id as trace_id,s.observation_id as observation_id,- s.session_id as session_id+ s.session_id as session_id,+ s.dataset_run_id as dataset_run_idFROMscores sLEFT JOIN traces t ON s.trace_id = t.id@@ -80,14 +81,14 @@ export const _handleGenerateScoresForPublicApi = async ({WHEREs.project_id = {projectId: String}${appliedScoresFilter.query ? `AND ${appliedScoresFilter.query}` : ""}- ${scoreScope === "traces_only" ? "AND s.session_id IS NULL" : ""}+ ${scoreScope === "traces_only" ? "AND s.session_id IS NULL AND s.dataset_run_id IS NULL" : ""}ORDER BYs.timestamp descLIMIT1 BY s.id, s.project_id)))- ${scoreScope === "traces_only" ? "AND s.session_id IS NULL" : ""}+ ${scoreScope === "traces_only" ? "AND s.session_id IS NULL AND s.dataset_run_id IS NULL" : ""}${appliedScoresFilter.query ? `AND ${appliedScoresFilter.query}` : ""}${tracesFilter.length() > 0 ? `AND ${appliedTracesFilter.query}` : ""}ORDER BYdiff --git a/web/src/features/public-api/server/traces.ts b/web/src/features/public-api/server/traces.tsindex 3d766d949d..de46130e5a 100644--- a/web/src/features/public-api/server/traces.ts+++ b/web/src/features/public-api/server/traces.ts@@ -92,6 +92,7 @@ export const generateTracesForPublicApi = async ({FROM scoresWHERE project_id = {projectId: String}AND session_id IS NULL+ AND dataset_run_id IS NULL${timeFilter ? `AND timestamp >= {cteTimeFilter: DateTime64(3)}` : ""}${environmentFilter.length() > 0 ? `AND ${appliedEnvironmentFilter.query}` : ""}GROUP BY project_id, trace_iddiff --git a/web/src/features/scores/components/AnnotateDrawerContent.tsx b/web/src/features/scores/components/AnnotateDrawerContent.tsxindex 81bdadf147..5730a5d261 100644--- a/web/src/features/scores/components/AnnotateDrawerContent.tsx+++ b/web/src/features/scores/components/AnnotateDrawerContent.tsx@@ -55,7 +55,7 @@ import {isNumericDataType,isScoreUnsaved,} from "@/src/features/scores/lib/helpers";-import { getDefaultScoreData } from "@/src/features/scores/lib/getDefaultScoreData";+import { getDefaultAnnotationScoreData } from "@/src/features/scores/lib/getDefaultScoreData";import { ToggleGroup, ToggleGroupItem } from "@/src/components/ui/toggle-group";import Header from "@/src/components/layouts/header";import { MultiSelectKeyValues } from "@/src/features/scores/components/multi-select-key-values";@@ -197,7 +197,7 @@ export function AnnotateDrawerContent<Target extends ScoreTarget>({const form = useForm<AnnotateFormSchemaType>({resolver: zodResolver(AnnotateFormSchema),defaultValues: {- scoreData: getDefaultScoreData({+ scoreData: getDefaultAnnotationScoreData({scores,emptySelectedConfigIds,configs,@@ -238,7 +238,7 @@ export function AnnotateDrawerContent<Target extends ScoreTarget>({)) {form.reset({- scoreData: getDefaultScoreData({+ scoreData: getDefaultAnnotationScoreData({scores,emptySelectedConfigIds,configs,diff --git a/web/src/features/scores/components/ScoreDetailColumnHelpers.tsx b/web/src/features/scores/components/ScoreDetailColumnHelpers.tsxindex 0e77f4fb51..eef69f3903 100644--- a/web/src/features/scores/components/ScoreDetailColumnHelpers.tsx+++ b/web/src/features/scores/components/ScoreDetailColumnHelpers.tsx@@ -22,7 +22,7 @@ import { type SessionTableRow } from "@/src/components/table/use-cases/sessions"const prefixScoreColKey = (key: string,- prefix: "Trace" | "Generation",+ prefix: "Trace" | "Generation" | "Run-level" | "Aggregated",): string => `${prefix}-${key}`;export const getScoreDataTypeIcon = (dataType: ScoreDataType): string => {@@ -47,7 +47,7 @@ const parseScoreColumn = <| SessionTableRow,>(col: ScoreData,- prefix?: "Trace" | "Generation",+ prefix?: "Trace" | "Generation" | "Run-level" | "Aggregated",): LangfuseColumnDef<T> => {const { key, name, source, dataType } = col;@@ -73,7 +73,7 @@ const parseScoreColumn = <export function verifyAndPrefixScoreDataAgainstKeys(scoreKeys: ScoreData[],scoreData: ScoreAggregate,- prefix?: "Trace" | "Generation",+ prefix?: "Trace" | "Generation" | "Run-level" | "Aggregated",): ScoreAggregate {if (!Boolean(scoreKeys.length)) return {};let filteredScores: ScoreAggregate = {};@@ -102,7 +102,7 @@ export const constructIndividualScoreColumns = <scoreColumnProps: ScoreData[];scoreColumnKey: keyof T & string;showAggregateViewOnly?: boolean;- scoreColumnPrefix?: "Trace" | "Generation";+ scoreColumnPrefix?: "Trace" | "Generation" | "Run-level" | "Aggregated";cellsLoading?: boolean;}): LangfuseColumnDef<T>[] => {return scoreColumnProps.map((col) => {@@ -140,10 +140,17 @@ export const constructIndividualScoreColumns = <});};-export const getScoreGroupColumnProps = (isLoading: boolean) => ({- accessorKey: "scores",- header: "Scores",- id: "scores",+export const getScoreGroupColumnProps = (+ isLoading: boolean,+ config = {+ accessorKey: "scores",+ header: "Scores",+ id: "scores",+ },+) => ({+ accessorKey: config.accessorKey,+ header: config.header,+ id: config.id,enableHiding: true,hideByDefault: true,cell: () => {diff --git a/web/src/features/scores/hooks/useIndividualScoreColumns.ts b/web/src/features/scores/hooks/useIndividualScoreColumns.tsindex f79c48ddb8..fc54cea6e9 100644--- a/web/src/features/scores/hooks/useIndividualScoreColumns.ts+++ b/web/src/features/scores/hooks/useIndividualScoreColumns.ts@@ -19,7 +19,7 @@ export function useIndividualScoreColumns<scoreColumnKey: keyof T & string;selectedFilterOption?: TableDateRangeOptions;showAggregateViewOnly?: boolean;- scoreColumnPrefix?: "Trace" | "Generation";+ scoreColumnPrefix?: "Trace" | "Generation" | "Run-level" | "Aggregated";cellsLoading?: boolean;}) {const scoreKeysAndProps = api.scores.getScoreKeysAndProps.useQuery(diff --git a/web/src/features/scores/lib/getDefaultScoreData.ts b/web/src/features/scores/lib/getDefaultScoreData.tsindex 406a8ec187..d97e262cb0 100644--- a/web/src/features/scores/lib/getDefaultScoreData.ts+++ b/web/src/features/scores/lib/getDefaultScoreData.ts@@ -7,7 +7,7 @@ import { ScoreSource } from "@langfuse/shared";import { type APIScoreV2, type ValidatedScoreConfig } from "@langfuse/shared";import { isTraceScore } from "@/src/features/scores/lib/helpers";-const filterTraceScores =+const filterTraceAnnotationScores =({ traceId, observationId }: ScoreTargetTrace) =>(s: APIScoreV2) =>s.source === ScoreSource.ANNOTATION &&@@ -16,12 +16,12 @@ const filterTraceScores =? s.observationId === observationId: s.observationId === null);-const filterSessionScores =+const filterSessionAnnotationScores =({ sessionId }: ScoreTargetSession) =>(s: APIScoreV2) =>s.source === ScoreSource.ANNOTATION && s.sessionId === sessionId;-export const getDefaultScoreData = ({+export const getDefaultAnnotationScoreData = ({scores,emptySelectedConfigIds,configs,@@ -33,8 +33,8 @@ export const getDefaultScoreData = ({scoreTarget: ScoreTarget;}) => {const isValidScore = isTraceScore(scoreTarget)- ? filterTraceScores(scoreTarget)- : filterSessionScores(scoreTarget);+ ? filterTraceAnnotationScores(scoreTarget)+ : filterSessionAnnotationScores(scoreTarget);const populatedScores = scores.filter(isValidScore)diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.tsindex 5d9e0d3463..436455c367 100644--- a/web/src/server/api/routers/scores.ts+++ b/web/src/server/api/routers/scores.ts@@ -345,6 +345,8 @@ export const scoresRouter = createTRPCRouter({projectId: input.projectId,environment: input.environment ?? "default",...inflatedParams,+ // only trace and session scores are supported for annotation+ datasetRunId: null,value: input.value ?? null,stringValue: input.stringValue ?? null,dataType: input.dataType ?? null,diff --git a/worker/src/features/database-read-stream/getDatabaseReadStream.ts b/worker/src/features/database-read-stream/getDatabaseReadStream.tsindex b2e8b3f687..1633750191 100644--- a/worker/src/features/database-read-stream/getDatabaseReadStream.ts+++ b/worker/src/features/database-read-stream/getDatabaseReadStream.ts@@ -126,6 +126,7 @@ export const getDatabaseReadStream = async ({id: score.id,traceId: score.traceId,sessionId: score.sessionId,+ datasetRunId: score.datasetRunId,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 92b67cd7a6..99821cc700 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -185,6 +185,7 @@ export class IngestionService {source: validatedScore.source,trace_id: validatedScore.traceId,session_id: validatedScore.sessionId,+ dataset_run_id: validatedScore.datasetRunId,data_type: validatedScore.dataType,observation_id: validatedScore.observationId,comment: validatedScore.comment,