🪢 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: add environment properties on api routes (#5781)
Steffen Schmitz1ec1bdf849b4
diff --git a/fern/apis/server/definition/commons.yml b/fern/apis/server/definition/commons.ymlindex d87ed8796a..de5bbeb1bc 100644--- a/fern/apis/server/definition/commons.yml+++ b/fern/apis/server/definition/commons.yml@@ -82,6 +82,9 @@ types:id: stringcreatedAt: datetimeprojectId: string+ environment:+ type: optional<string>+ docs: The environment from which this session originated.SessionWithTraces:extends: Sessionproperties:diff --git a/fern/apis/server/definition/ingestion.yml b/fern/apis/server/definition/ingestion.ymlindex 911cbfd131..3c979cc604 100644--- a/fern/apis/server/definition/ingestion.yml+++ b/fern/apis/server/definition/ingestion.yml@@ -47,6 +47,7 @@ service:body:id: abcdef-1234-5678-90abtimestamp: "2022-01-01T00:00:00.000Z"+ environment: "production"name: "My Trace"userId: "1234-5678-90ab-cdef"input: "My input"@@ -74,6 +75,7 @@ service:id: abcdef-1234-5678-90abtraceId: "1234-5678-90ab-cdef"startTime: "2022-01-01T00:00:00.000Z"+ environment: "test"response:body:successes:@@ -92,6 +94,7 @@ service:traceId: "1234-5678-90ab-cdef"name: "My Score"value: 0.9+ environment: "default"response:body:successes:diff --git a/fern/apis/server/definition/metrics.yml b/fern/apis/server/definition/metrics.ymlindex 498df37af3..20fd7ac421 100644--- a/fern/apis/server/definition/metrics.yml+++ b/fern/apis/server/definition/metrics.yml@@ -29,6 +29,10 @@ service:type: optional<string>allow-multiple: truedocs: Optional filter for metrics where traces include all of these tags+ environment:+ type: optional<string>+ allow-multiple: true+ docs: Optional filter for metrics where events include any of these environmentsfromTimestamp:type: optional<datetime>docs: Optional filter to only include traces and observations on or after a certain datetime (ISO 8601)diff --git a/fern/apis/server/definition/observations.yml b/fern/apis/server/definition/observations.ymlindex fc37d53951..7d9297852a 100644--- a/fern/apis/server/definition/observations.yml+++ b/fern/apis/server/definition/observations.yml@@ -33,6 +33,10 @@ service:type: optional<string>traceId: optional<string>parentObservationId: optional<string>+ environment:+ type: optional<string>+ allow-multiple: true+ docs: Optional filter for observations where the environment is one of the provided values.fromStartTime:type: optional<datetime>docs: Retrieve only observations with a start_time or or after this datetime (ISO 8601).diff --git a/fern/apis/server/definition/score.yml b/fern/apis/server/definition/score.ymlindex 4f6828a2a6..0c034f864a 100644--- a/fern/apis/server/definition/score.yml+++ b/fern/apis/server/definition/score.yml@@ -37,6 +37,10 @@ service: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.@@ -91,6 +95,9 @@ types:docs: 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>+ environment:+ type: optional<string>+ docs: The environment of the score. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.dataType:type: optional<commons.ScoreDataType>docs: 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.@@ -113,10 +120,12 @@ types:dataType: "NUMERIC"configId: "9203-4567-89ab-cdef"traceId: "cdef-1234-5678-90ab"+ environment: "test"- value:name: "toxicity"value: "not toxic"traceId: "cdef-1234-5678-90ab"+ environment: "production"- value:name: "correctness"value: "partially correct"@@ -147,6 +156,9 @@ types: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 scoreGetScoresResponseDataNumeric:extends: commons.NumericScorediff --git a/fern/apis/server/definition/sessions.yml b/fern/apis/server/definition/sessions.ymlindex b8a33ee284..5e06b2c355 100644--- a/fern/apis/server/definition/sessions.yml+++ b/fern/apis/server/definition/sessions.yml@@ -25,6 +25,10 @@ service:toTimestamp:type: optional<datetime>docs: Optional filter to only include sessions created before a certain datetime (ISO 8601)+ environment:+ type: optional<string>+ allow-multiple: true+ docs: Optional filter for sessions where the environment is one of the provided values.response: PaginatedSessionsget:docs: Get a session. Please note that `traces` on this endpoint are not paginated, if you plan to fetch large sessions, consider `GET /api/public/traces?sessionId=<sessionId>`diff --git a/fern/apis/server/definition/trace.yml b/fern/apis/server/definition/trace.ymlindex 203eb8215a..8bc311b101 100644--- a/fern/apis/server/definition/trace.yml+++ b/fern/apis/server/definition/trace.yml@@ -50,6 +50,10 @@ service:release:type: optional<string>docs: Optional filter to only include traces with a certain release.+ environment:+ type: optional<string>+ allow-multiple: true+ docs: Optional filter for traces where the environment is one of the provided values.response: Tracestypes:diff --git a/packages/shared/src/features/scores/scoreTypes.ts b/packages/shared/src/features/scores/scoreTypes.tsindex 208c66c87e..752cfd4bc0 100644--- a/packages/shared/src/features/scores/scoreTypes.ts+++ b/packages/shared/src/features/scores/scoreTypes.ts@@ -64,6 +64,7 @@ const BaseScoreBody = z.object({traceId: z.string(),observationId: z.string().nullish(),comment: z.string().nullish(),+ environment: z.string().default("default"),});/**@@ -237,6 +238,7 @@ export const GetScoresQuery = z.object({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,@@ -259,6 +261,7 @@ const LegacyGetScoreResponseDataV1 = z.intersection(trace: z.object({userId: z.string().nullish(),tags: z.array(z.string()).nullish(),+ environment: z.string().nullish(),}),}),);diff --git a/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts b/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.tsindex ea944158c6..8ea0eebce1 100644--- a/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts@@ -383,6 +383,10 @@ export class FilterList {return this.filters.find(predicate);}+ filter(predicate: (filter: Filter) => boolean) {+ return new FilterList(this.filters.filter(predicate));+ }+some(predicate: (filter: Filter) => boolean) {return this.filters.some(predicate);}diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.tsindex 1d23346645..0e125c0b13 100644--- a/packages/shared/src/server/repositories/scores.ts+++ b/packages/shared/src/server/repositories/scores.ts@@ -459,8 +459,9 @@ export const getScoresUiGeneric = async <T>(props: {}): Promise<T[]> => {const { select, projectId, filter, orderBy, limit, offset } = props;- const { tracesFilter, scoresFilter, observationsFilter } =- getProjectIdDefaultFilter(projectId, { tracesPrefix: "t" });+ const { scoresFilter } = getProjectIdDefaultFilter(projectId, {+ tracesPrefix: "t",+ });scoresFilter.push(...createFilterFromFilterState(filter, scoresTableUiColumnDefinitions),diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.ymlindex 6453eb0dee..e5cd159535 100644--- a/web/public/generated/api/openapi.yml+++ b/web/public/generated/api/openapi.yml@@ -840,6 +840,7 @@ paths:body:id: abcdef-1234-5678-90abtimestamp: '2022-01-01T00:00:00.000Z'+ environment: productionname: My TraceuserId: 1234-5678-90ab-cdefinput: My input@@ -862,6 +863,7 @@ paths:id: abcdef-1234-5678-90abtraceId: 1234-5678-90ab-cdefstartTime: '2022-01-01T00:00:00.000Z'+ environment: testExample3:value:batch:@@ -873,6 +875,7 @@ paths:traceId: 1234-5678-90ab-cdefname: My Scorevalue: 0.9+ environment: default/api/public/media/{mediaId}:get:description: Get a media record@@ -1059,6 +1062,17 @@ paths:items:type: stringnullable: true+ - name: environment+ in: query+ description: >-+ Optional filter for metrics where events include any of these+ environments+ required: false+ schema:+ type: array+ items:+ type: string+ nullable: true- name: fromTimestampin: querydescription: >-@@ -1406,6 +1420,17 @@ paths:schema:type: stringnullable: true+ - name: environment+ in: query+ description: >-+ Optional filter for observations where the environment is one of the+ provided values.+ required: false+ schema:+ type: array+ items:+ type: string+ nullable: true- name: fromStartTimein: querydescription: >-@@ -2035,6 +2060,17 @@ paths:type: stringformat: date-timenullable: true+ - name: environment+ in: query+ description: >-+ Optional filter for scores where the environment is one of the+ provided values.+ required: false+ schema:+ type: array+ items:+ type: string+ nullable: true- name: sourcein: querydescription: Retrieve only scores from a specific source.@@ -2262,6 +2298,17 @@ paths:type: stringformat: date-timenullable: true+ - name: environment+ in: query+ description: >-+ Optional filter for sessions where the environment is one of the+ provided values.+ required: false+ schema:+ type: array+ items:+ type: string+ nullable: trueresponses:'200':description: ''@@ -2487,6 +2534,17 @@ paths:schema:type: stringnullable: true+ - name: environment+ in: query+ description: >-+ Optional filter for traces where the environment is one of the+ provided values.+ required: false+ schema:+ type: array+ items:+ type: string+ nullable: trueresponses:'200':description: ''@@ -2715,6 +2773,10 @@ components:format: date-timeprojectId:type: string+ environment:+ type: string+ nullable: true+ description: The environment from which this session originated.required:- id- createdAt@@ -4842,6 +4904,13 @@ components:comment:type: stringnullable: 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@@ -4883,6 +4952,10 @@ components:type: stringnullable: truedescription: A list of tags associated with the trace referenced by score+ environment:+ type: string+ nullable: true+ description: The environment of the trace referenced by scoreGetScoresResponseDataNumeric:title: GetScoresResponseDataNumerictype: objectdiff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.jsonindex eb040897df..3ddf8f592d 100644--- a/web/public/generated/postman/collection.json+++ b/web/public/generated/postman/collection.json@@ -583,7 +583,7 @@"auth": null,"body": {"mode": "raw",- "raw": "{\n \"batch\": [\n {\n \"id\": \"abcdef-1234-5678-90ab\",\n \"timestamp\": \"2022-01-01T00:00:00.000Z\",\n \"type\": \"trace-create\",\n \"body\": {\n \"id\": \"abcdef-1234-5678-90ab\",\n \"timestamp\": \"2022-01-01T00:00:00.000Z\",\n \"name\": \"My Trace\",\n \"userId\": \"1234-5678-90ab-cdef\",\n \"input\": \"My input\",\n \"output\": \"My output\",\n \"sessionId\": \"1234-5678-90ab-cdef\",\n \"release\": \"1.0.0\",\n \"version\": \"1.0.0\",\n \"metadata\": \"My metadata\",\n \"tags\": [\n \"tag1\",\n \"tag2\"\n ],\n \"public\": true\n }\n }\n ]\n}",+ "raw": "{\n \"batch\": [\n {\n \"id\": \"abcdef-1234-5678-90ab\",\n \"timestamp\": \"2022-01-01T00:00:00.000Z\",\n \"type\": \"trace-create\",\n \"body\": {\n \"id\": \"abcdef-1234-5678-90ab\",\n \"timestamp\": \"2022-01-01T00:00:00.000Z\",\n \"environment\": \"production\",\n \"name\": \"My Trace\",\n \"userId\": \"1234-5678-90ab-cdef\",\n \"input\": \"My input\",\n \"output\": \"My output\",\n \"sessionId\": \"1234-5678-90ab-cdef\",\n \"release\": \"1.0.0\",\n \"version\": \"1.0.0\",\n \"metadata\": \"My metadata\",\n \"tags\": [\n \"tag1\",\n \"tag2\"\n ],\n \"public\": true\n }\n }\n ]\n}","options": {"raw": {"language": "json"@@ -622,7 +622,7 @@"auth": null,"body": {"mode": "raw",- "raw": "{\n \"batch\": [\n {\n \"id\": \"abcdef-1234-5678-90ab\",\n \"timestamp\": \"2022-01-01T00:00:00.000Z\",\n \"type\": \"trace-create\",\n \"body\": {\n \"id\": \"abcdef-1234-5678-90ab\",\n \"timestamp\": \"2022-01-01T00:00:00.000Z\",\n \"name\": \"My Trace\",\n \"userId\": \"1234-5678-90ab-cdef\",\n \"input\": \"My input\",\n \"output\": \"My output\",\n \"sessionId\": \"1234-5678-90ab-cdef\",\n \"release\": \"1.0.0\",\n \"version\": \"1.0.0\",\n \"metadata\": \"My metadata\",\n \"tags\": [\n \"tag1\",\n \"tag2\"\n ],\n \"public\": true\n }\n }\n ]\n}",+ "raw": "{\n \"batch\": [\n {\n \"id\": \"abcdef-1234-5678-90ab\",\n \"timestamp\": \"2022-01-01T00:00:00.000Z\",\n \"type\": \"trace-create\",\n \"body\": {\n \"id\": \"abcdef-1234-5678-90ab\",\n \"timestamp\": \"2022-01-01T00:00:00.000Z\",\n \"environment\": \"production\",\n \"name\": \"My Trace\",\n \"userId\": \"1234-5678-90ab-cdef\",\n \"input\": \"My input\",\n \"output\": \"My output\",\n \"sessionId\": \"1234-5678-90ab-cdef\",\n \"release\": \"1.0.0\",\n \"version\": \"1.0.0\",\n \"metadata\": \"My metadata\",\n \"tags\": [\n \"tag1\",\n \"tag2\"\n ],\n \"public\": true\n }\n }\n ]\n}","options": {"raw": {"language": "json"@@ -664,7 +664,7 @@"auth": null,"body": {"mode": "raw",- "raw": "{\n \"batch\": [\n {\n \"id\": \"abcdef-1234-5678-90ab\",\n \"timestamp\": \"2022-01-01T00:00:00.000Z\",\n \"type\": \"span-create\",\n \"body\": {\n \"id\": \"abcdef-1234-5678-90ab\",\n \"traceId\": \"1234-5678-90ab-cdef\",\n \"startTime\": \"2022-01-01T00:00:00.000Z\"\n }\n }\n ]\n}",+ "raw": "{\n \"batch\": [\n {\n \"id\": \"abcdef-1234-5678-90ab\",\n \"timestamp\": \"2022-01-01T00:00:00.000Z\",\n \"type\": \"span-create\",\n \"body\": {\n \"id\": \"abcdef-1234-5678-90ab\",\n \"traceId\": \"1234-5678-90ab-cdef\",\n \"startTime\": \"2022-01-01T00:00:00.000Z\",\n \"environment\": \"test\"\n }\n }\n ]\n}","options": {"raw": {"language": "json"@@ -706,7 +706,7 @@"auth": null,"body": {"mode": "raw",- "raw": "{\n \"batch\": [\n {\n \"id\": \"abcdef-1234-5678-90ab\",\n \"timestamp\": \"2022-01-01T00:00:00.000Z\",\n \"type\": \"score-create\",\n \"body\": {\n \"id\": \"abcdef-1234-5678-90ab\",\n \"traceId\": \"1234-5678-90ab-cdef\",\n \"name\": \"My Score\",\n \"value\": 0.9\n }\n }\n ]\n}",+ "raw": "{\n \"batch\": [\n {\n \"id\": \"abcdef-1234-5678-90ab\",\n \"timestamp\": \"2022-01-01T00:00:00.000Z\",\n \"type\": \"score-create\",\n \"body\": {\n \"id\": \"abcdef-1234-5678-90ab\",\n \"traceId\": \"1234-5678-90ab-cdef\",\n \"name\": \"My Score\",\n \"value\": 0.9,\n \"environment\": \"default\"\n }\n }\n ]\n}","options": {"raw": {"language": "json"@@ -845,7 +845,7 @@"request": {"description": "Get daily metrics of the Langfuse project","url": {- "raw": "{{baseUrl}}/api/public/metrics/daily?page=&limit=&traceName=&userId=&tags=&fromTimestamp=&toTimestamp=",+ "raw": "{{baseUrl}}/api/public/metrics/daily?page=&limit=&traceName=&userId=&tags=&environment=&fromTimestamp=&toTimestamp=","host": ["{{baseUrl}}"],@@ -881,6 +881,11 @@"value": "","description": "Optional filter for metrics where traces include all of these tags"},+ {+ "key": "environment",+ "value": "",+ "description": "Optional filter for metrics where events include any of these environments"+ },{"key": "fromTimestamp","value": "",@@ -1086,7 +1091,7 @@"request": {"description": "Get a list of observations","url": {- "raw": "{{baseUrl}}/api/public/observations?page=&limit=&name=&userId=&type=&traceId=&parentObservationId=&fromStartTime=&toStartTime=&version=",+ "raw": "{{baseUrl}}/api/public/observations?page=&limit=&name=&userId=&type=&traceId=&parentObservationId=&environment=&fromStartTime=&toStartTime=&version=","host": ["{{baseUrl}}"],@@ -1131,6 +1136,11 @@"value": "","description": null},+ {+ "key": "environment",+ "value": "",+ "description": "Optional filter for observations where the environment is one of the provided values."+ },{"key": "fromStartTime","value": "",@@ -1544,7 +1554,7 @@"request": {"description": "Get a list of scores","url": {- "raw": "{{baseUrl}}/api/public/scores?page=&limit=&userId=&name=&fromTimestamp=&toTimestamp=&source=&operator=&value=&scoreIds=&configId=&queueId=&dataType=&traceTags=",+ "raw": "{{baseUrl}}/api/public/scores?page=&limit=&userId=&name=&fromTimestamp=&toTimestamp=&environment=&source=&operator=&value=&scoreIds=&configId=&queueId=&dataType=&traceTags=","host": ["{{baseUrl}}"],@@ -1584,6 +1594,11 @@"value": "","description": "Optional filter to only include scores created before a certain datetime (ISO 8601)"},+ {+ "key": "environment",+ "value": "",+ "description": "Optional filter for scores where the environment is one of the provided values."+ },{"key": "source","value": "",@@ -1711,7 +1726,7 @@"request": {"description": "Get sessions","url": {- "raw": "{{baseUrl}}/api/public/sessions?page=&limit=&fromTimestamp=&toTimestamp=",+ "raw": "{{baseUrl}}/api/public/sessions?page=&limit=&fromTimestamp=&toTimestamp=&environment=","host": ["{{baseUrl}}"],@@ -1740,6 +1755,11 @@"key": "toTimestamp","value": "","description": "Optional filter to only include sessions created before a certain datetime (ISO 8601)"+ },+ {+ "key": "environment",+ "value": "",+ "description": "Optional filter for sessions where the environment is one of the provided values."}],"variable": []@@ -1828,7 +1848,7 @@"request": {"description": "Get list of traces","url": {- "raw": "{{baseUrl}}/api/public/traces?page=&limit=&userId=&name=&sessionId=&fromTimestamp=&toTimestamp=&orderBy=&tags=&version=&release=",+ "raw": "{{baseUrl}}/api/public/traces?page=&limit=&userId=&name=&sessionId=&fromTimestamp=&toTimestamp=&orderBy=&tags=&version=&release=&environment=","host": ["{{baseUrl}}"],@@ -1892,6 +1912,11 @@"key": "release","value": "","description": "Optional filter to only include traces with a certain release."+ },+ {+ "key": "environment",+ "value": "",+ "description": "Optional filter for traces where the environment is one of the provided values."}],"variable": []diff --git a/web/src/__tests__/async/daily-metrics-api.servertest.ts b/web/src/__tests__/async/daily-metrics-api.servertest.tsindex 8521ac5d58..8801444bd1 100644--- a/web/src/__tests__/async/daily-metrics-api.servertest.ts+++ b/web/src/__tests__/async/daily-metrics-api.servertest.ts@@ -81,4 +81,92 @@ describe("/api/public/metrics/daily API Endpoint", () => {expect(usage.totalCost).toBe(600);}});++ it("should filter daily metrics by environment", async () => {+ const testEnvironment = randomUUID();+ const traces = [+ createTrace({+ user_id: "user-1",+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ metadata: { key: "value" },+ release: "1.0.0",+ version: "2.0.0",+ environment: testEnvironment,+ }),+ createTrace({+ user_id: "user-1",+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ metadata: { key: "value" },+ release: "1.0.0",+ version: "2.0.0",+ environment: "default",+ }),+ ];++ const observations = [+ createObservation({+ trace_id: traces[0].id,+ project_id: traces[0].project_id,+ name: "observation-name-1",+ end_time: new Date().getTime(),+ start_time: new Date().getTime() - 1000,+ provided_model_name: "model-1",+ environment: testEnvironment,+ }),+ createObservation({+ trace_id: traces[0].id,+ project_id: traces[0].project_id,+ name: "observation-name-3",+ end_time: new Date().getTime(),+ start_time: new Date().getTime() - 100000,+ provided_model_name: "model-2",+ environment: testEnvironment,+ }),+ createObservation({+ trace_id: traces[1].id,+ project_id: traces[1].project_id,+ name: "observation-name-1",+ end_time: new Date().getTime(),+ start_time: new Date().getTime() - 1000,+ provided_model_name: "model-1",+ environment: "default",+ }),+ createObservation({+ trace_id: traces[1].id,+ project_id: traces[1].project_id,+ name: "observation-name-3",+ end_time: new Date().getTime(),+ start_time: new Date().getTime() - 100000,+ provided_model_name: "model-2",+ environment: "default",+ }),+ ];++ await createTracesCh(traces);+ await createObservationsCh(observations);++ const metrics = await makeZodVerifiedAPICall(+ GetMetricsDailyV1Response,+ "GET",+ `/api/public/metrics/daily?environment=${testEnvironment}`,+ );++ expect(metrics.body.meta.totalItems).toBe(1);+ expect(metrics.body.meta.totalPages).toBe(1);++ const metric = metrics.body.data[0];+ expect(metric.countTraces).toBe(1);+ expect(metric.countObservations).toBe(2);+ expect(metric.usage).toHaveLength(2);+ expect(metric.totalCost).toBe(600);+ for (const usage of metric.usage) {+ expect(usage.model).toMatch(/model-\d/g);+ expect(usage.inputUsage).toBe(1234);+ expect(usage.outputUsage).toBe(5678);+ expect(usage.totalUsage).toBe(6912);+ expect(usage.countObservations).toBe(1);+ expect(usage.countTraces).toBe(1);+ expect(usage.totalCost).toBe(300);+ }+ });});diff --git a/web/src/__tests__/async/observation-api.servertest.ts b/web/src/__tests__/async/observation-api.servertest.tsindex f0de07cce3..b697351d05 100644--- a/web/src/__tests__/async/observation-api.servertest.ts+++ b/web/src/__tests__/async/observation-api.servertest.ts@@ -46,261 +46,286 @@ describe("/api/public/observations API Endpoint", () => {});});});-});-describe("/api/public/observations API Endpoint", () => {- it("should fetch all observations", async () => {- const traceId = uuidv4();-- const observation = createObservationObject({- id: uuidv4(),- trace_id: traceId,- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- internal_model_id: "clrkwk4cb000408l576jl7koo",- provided_model_name: "gpt-3.5-turbo",- input: JSON.stringify({ key: "input" }),- output: JSON.stringify({ key: "output" }),- usage_details: {- input: 10,- output: 20,- total: 30,- },- version: "2.0.0",- type: "GENERATION",- });+ describe("GET /api/public/observations", () => {+ it("should fetch all observations", async () => {+ const traceId = uuidv4();- await createObservationsInClickhouse([observation]);+ const observation = createObservationObject({+ id: uuidv4(),+ trace_id: traceId,+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ internal_model_id: "clrkwk4cb000408l576jl7koo",+ provided_model_name: "gpt-3.5-turbo",+ input: JSON.stringify({ key: "input" }),+ output: JSON.stringify({ key: "output" }),+ usage_details: {+ input: 10,+ output: 20,+ total: 30,+ },+ version: "2.0.0",+ type: "GENERATION",+ });- const fetchedObservations = await makeZodVerifiedAPICall(- GetObservationsV1Response,- "GET",- "/api/public/observations?traceId=" + traceId,- undefined,- );+ await createObservationsInClickhouse([observation]);- expect(fetchedObservations.status).toBe(200);+ const fetchedObservations = await makeZodVerifiedAPICall(+ GetObservationsV1Response,+ "GET",+ "/api/public/observations?traceId=" + traceId,+ undefined,+ );- expect(fetchedObservations.body.data.length).toBe(1);- expect(fetchedObservations.body.data[0]?.traceId).toBe(traceId);- expect(fetchedObservations.body.data[0]?.input).toEqual({ key: "input" });- expect(fetchedObservations.body.data[0]?.output).toEqual({ key: "output" });- expect(fetchedObservations.body.data[0]?.model).toEqual("gpt-3.5-turbo");- expect(fetchedObservations.body.data[0]?.modelId).toEqual(- "clrkwk4cb000408l576jl7koo",- );- expect(- fetchedObservations.body.data[0]?.calculatedInputCost,- ).toBeGreaterThan(0);- expect(- fetchedObservations.body.data[0]?.calculatedOutputCost,- ).toBeGreaterThan(0);- expect(- fetchedObservations.body.data[0]?.calculatedTotalCost,- ).toBeGreaterThan(0);- });+ expect(fetchedObservations.status).toBe(200);- it("should fetch all observations, filtered by generations", async () => {- const traceId = uuidv4();-- const generationObservation = createObservationObject({- id: uuidv4(),- trace_id: traceId,- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- internal_model_id: "model-1",- provided_model_name: "gpt-3.5-turbo",- input: JSON.stringify({ key: "input" }),- output: JSON.stringify({ key: "output" }),- usage_details: {- input: 10,- output: 20,- total: 30,- },- version: "2.0.0",- type: "GENERATION",+ expect(fetchedObservations.body.data.length).toBe(1);+ expect(fetchedObservations.body.data[0]?.traceId).toBe(traceId);+ expect(fetchedObservations.body.data[0]?.input).toEqual({ key: "input" });+ expect(fetchedObservations.body.data[0]?.output).toEqual({+ key: "output",+ });+ expect(fetchedObservations.body.data[0]?.model).toEqual("gpt-3.5-turbo");+ expect(fetchedObservations.body.data[0]?.modelId).toEqual(+ "clrkwk4cb000408l576jl7koo",+ );+ expect(+ fetchedObservations.body.data[0]?.calculatedInputCost,+ ).toBeGreaterThan(0);+ expect(+ fetchedObservations.body.data[0]?.calculatedOutputCost,+ ).toBeGreaterThan(0);+ expect(+ fetchedObservations.body.data[0]?.calculatedTotalCost,+ ).toBeGreaterThan(0);});- const spanObservation = createObservationObject({- id: uuidv4(),- trace_id: traceId,- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- input: JSON.stringify({ key: "input" }),- output: JSON.stringify({ key: "output" }),- version: "2.0.0",- type: "SPAN",- });+ it("should fetch all observations, filtered by generations", async () => {+ const traceId = uuidv4();- await createObservationsInClickhouse([- generationObservation,- spanObservation,- ]);+ const generationObservation = createObservationObject({+ id: uuidv4(),+ trace_id: traceId,+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ internal_model_id: "model-1",+ provided_model_name: "gpt-3.5-turbo",+ input: JSON.stringify({ key: "input" }),+ output: JSON.stringify({ key: "output" }),+ usage_details: {+ input: 10,+ output: 20,+ total: 30,+ },+ version: "2.0.0",+ type: "GENERATION",+ });- const fetchedObservations = await makeZodVerifiedAPICall(- GetObservationsV1Response,- "GET",- "/api/public/observations?type=GENERATION&traceId=" + traceId,- undefined,- );+ const spanObservation = createObservationObject({+ id: uuidv4(),+ trace_id: traceId,+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ input: JSON.stringify({ key: "input" }),+ output: JSON.stringify({ key: "output" }),+ version: "2.0.0",+ type: "SPAN",+ });- expect(fetchedObservations.status).toBe(200);+ await createObservationsInClickhouse([+ generationObservation,+ spanObservation,+ ]);- expect(fetchedObservations.body.data.length).toBe(1);- expect(fetchedObservations.body.data[0]?.traceId).toBe(traceId);- expect(fetchedObservations.body.data[0]?.input).toEqual({ key: "input" });- expect(fetchedObservations.body.data[0]?.output).toEqual({ key: "output" });- expect(fetchedObservations.body.data[0]?.type).toEqual("GENERATION");- });+ const fetchedObservations = await makeZodVerifiedAPICall(+ GetObservationsV1Response,+ "GET",+ "/api/public/observations?type=GENERATION&traceId=" + traceId,+ undefined,+ );- it.each([- ["userId", uuidv4()],- ["traceId", uuidv4()],- ["name", uuidv4()],- ["version", uuidv4()],- ])(- "should fetch all observations filtered by a value (%s, %s)",- async (prop: string, value: string) => {- const traceId = uuidv4();+ expect(fetchedObservations.status).toBe(200);- if (prop === "userId") {- const createdTrace = createTrace({- id: traceId,- [snakeCase(prop)]: value,+ expect(fetchedObservations.body.data.length).toBe(1);+ expect(fetchedObservations.body.data[0]?.traceId).toBe(traceId);+ expect(fetchedObservations.body.data[0]?.input).toEqual({ key: "input" });+ expect(fetchedObservations.body.data[0]?.output).toEqual({+ key: "output",+ });+ expect(fetchedObservations.body.data[0]?.type).toEqual("GENERATION");+ });++ it.each([+ ["userId", uuidv4()],+ ["traceId", uuidv4()],+ ["name", uuidv4()],+ ["version", uuidv4()],+ ["environment", uuidv4()],+ ])(+ "should fetch all observations filtered by a value (%s, %s)",+ async (prop: string, value: string) => {+ const traceId = uuidv4();++ if (prop === "userId" || prop === "environment") {+ const createdTrace = createTrace({+ id: traceId,+ [snakeCase(prop)]: value,+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ });++ await createTracesCh([createdTrace]);+ }++ const observation = createObservationObject({+ id: uuidv4(),+ trace_id: traceId,+ start_time: new Date("2021-01-01T00:00:00.000Z").getTime(),+ end_time: new Date("2021-01-01T00:00:00.000Z").getTime(),project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ type: "GENERATION",+ [snakeCase(prop)]: value,});- await createTracesCh([createdTrace]);- }+ await createObservationsInClickhouse([observation]);++ const observations = await makeZodVerifiedAPICall(+ GetObservationsV1Response,+ "GET",+ `/api/public/observations?${prop}=${value}`,+ );++ expect(observations.body.meta.totalItems).toBe(1);+ expect(observations.body.data.length).toBe(1);+ const obsResult = observations.body.data[0];+ expect(obsResult.projectId).toBe(+ "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ );+ if (prop === "userId") return;+ expect((obsResult as any)[prop]).toBe(value);+ },+ );- const observation = createObservationObject({- id: uuidv4(),+ it("GET /observations with timestamp filters and pagination", async () => {+ const traceId = uuidv4();+ const obs1 = createObservationObject({+ id: "observation-2021-01-01",trace_id: traceId,+ name: "generation-name",start_time: new Date("2021-01-01T00:00:00.000Z").getTime(),+ event_ts: new Date("2021-01-01T00:00:00.000Z").getTime(),end_time: new Date("2021-01-01T00:00:00.000Z").getTime(),project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",type: "GENERATION",- [snakeCase(prop)]: value,});- await createObservationsInClickhouse([observation]);+ const obs2 = createObservationObject({+ id: "observation-2021-02-01",+ trace_id: traceId,+ name: "generation-name",+ start_time: new Date("2021-02-01T00:00:00.000Z").getTime(),+ event_ts: new Date("2021-02-01T00:00:00.000Z").getTime(),+ end_time: new Date("2021-02-01T00:00:00.000Z").getTime(),+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ type: "SPAN",+ });+ const obs3 = createObservationObject({+ id: "observation-2021-03-01",+ trace_id: traceId,+ name: "generation-name",+ start_time: new Date("2021-03-01T00:00:00.000Z").getTime(),+ event_ts: new Date("2021-03-01T00:00:00.000Z").getTime(),+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ type: "EVENT",+ });+ const obs4 = createObservationObject({+ id: "observation-2021-04-01",+ trace_id: traceId,+ name: "generation-name",+ start_time: new Date("2021-04-01T00:00:00.000Z").getTime(),+ event_ts: new Date("2021-04-01T00:00:00.000Z").getTime(),+ end_time: new Date("2021-04-01T00:00:00.000Z").getTime(),+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ type: "GENERATION",+ });++ await createObservationsInClickhouse([obs1, obs2, obs3, obs4]);- const observations = await makeZodVerifiedAPICall(+ const fromTimestamp = "2021-02-01T00:00:00.000Z";+ const toTimestamp = "2021-04-01T00:00:00.000Z";++ // Test with both fromTimestamp and toTimestamp+ let fetchedObservations = await makeZodVerifiedAPICall(GetObservationsV1Response,"GET",- `/api/public/observations?${prop}=${value}`,+ `/api/public/observations?fromStartTime=${fromTimestamp}&toStartTime=${toTimestamp}&traceId=${traceId}`,+ undefined,);- expect(observations.body.meta.totalItems).toBe(1);- expect(observations.body.data.length).toBe(1);- const obsResult = observations.body.data[0];- expect(obsResult.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");- if (prop === "userId") return;- expect((obsResult as any)[prop]).toBe(value);- },- );-- it("GET /observations with timestamp filters and pagination", async () => {- const traceId = uuidv4();- const obs1 = createObservationObject({- id: "observation-2021-01-01",- trace_id: traceId,- name: "generation-name",- start_time: new Date("2021-01-01T00:00:00.000Z").getTime(),- event_ts: new Date("2021-01-01T00:00:00.000Z").getTime(),- end_time: new Date("2021-01-01T00:00:00.000Z").getTime(),- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- type: "GENERATION",- });-- const obs2 = createObservationObject({- id: "observation-2021-02-01",- trace_id: traceId,- name: "generation-name",- start_time: new Date("2021-02-01T00:00:00.000Z").getTime(),- event_ts: new Date("2021-02-01T00:00:00.000Z").getTime(),- end_time: new Date("2021-02-01T00:00:00.000Z").getTime(),- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- type: "SPAN",- });- const obs3 = createObservationObject({- id: "observation-2021-03-01",- trace_id: traceId,- name: "generation-name",- start_time: new Date("2021-03-01T00:00:00.000Z").getTime(),- event_ts: new Date("2021-03-01T00:00:00.000Z").getTime(),- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- type: "EVENT",- });- const obs4 = createObservationObject({- id: "observation-2021-04-01",- trace_id: traceId,- name: "generation-name",- start_time: new Date("2021-04-01T00:00:00.000Z").getTime(),- event_ts: new Date("2021-04-01T00:00:00.000Z").getTime(),- end_time: new Date("2021-04-01T00:00:00.000Z").getTime(),- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- type: "GENERATION",- });-- await createObservationsInClickhouse([obs1, obs2, obs3, obs4]);+ expect(fetchedObservations.body.data.length).toBe(2);+ expect(fetchedObservations.body.data[0]?.id).toBe(+ "observation-2021-03-01",+ );+ expect(fetchedObservations.body.data[1]?.id).toBe(+ "observation-2021-02-01",+ );+ expect(fetchedObservations.body.meta.totalItems).toBe(2);- const fromTimestamp = "2021-02-01T00:00:00.000Z";- const toTimestamp = "2021-04-01T00:00:00.000Z";+ // Test with only fromTimestamp+ fetchedObservations = await makeZodVerifiedAPICall(+ GetObservationsV1Response,+ "GET",+ `/api/public/observations?fromStartTime=${fromTimestamp}&traceId=${traceId}`,+ undefined,+ );- // Test with both fromTimestamp and toTimestamp- let fetchedObservations = await makeZodVerifiedAPICall(- GetObservationsV1Response,- "GET",- `/api/public/observations?fromStartTime=${fromTimestamp}&toStartTime=${toTimestamp}&traceId=${traceId}`,- undefined,- );+ expect(fetchedObservations.body.data.length).toBe(3);+ expect(fetchedObservations.body.data[0]?.id).toBe(+ "observation-2021-04-01",+ );+ expect(fetchedObservations.body.data[1]?.id).toBe(+ "observation-2021-03-01",+ );+ expect(fetchedObservations.body.data[2]?.id).toBe(+ "observation-2021-02-01",+ );+ expect(fetchedObservations.body.meta.totalItems).toBe(3);- expect(fetchedObservations.body.data.length).toBe(2);- expect(fetchedObservations.body.data[0]?.id).toBe("observation-2021-03-01");- expect(fetchedObservations.body.data[1]?.id).toBe("observation-2021-02-01");- expect(fetchedObservations.body.meta.totalItems).toBe(2);-- // Test with only fromTimestamp- fetchedObservations = await makeZodVerifiedAPICall(- GetObservationsV1Response,- "GET",- `/api/public/observations?fromStartTime=${fromTimestamp}&traceId=${traceId}`,- undefined,- );+ // Test with only toTimestamp+ fetchedObservations = await makeZodVerifiedAPICall(+ GetObservationsV1Response,+ "GET",+ `/api/public/observations?toStartTime=${toTimestamp}&traceId=${traceId}`,+ undefined,+ );- expect(fetchedObservations.body.data.length).toBe(3);- expect(fetchedObservations.body.data[0]?.id).toBe("observation-2021-04-01");- expect(fetchedObservations.body.data[1]?.id).toBe("observation-2021-03-01");- expect(fetchedObservations.body.data[2]?.id).toBe("observation-2021-02-01");- expect(fetchedObservations.body.meta.totalItems).toBe(3);-- // Test with only toTimestamp- fetchedObservations = await makeZodVerifiedAPICall(- GetObservationsV1Response,- "GET",- `/api/public/observations?toStartTime=${toTimestamp}&traceId=${traceId}`,- undefined,- );+ expect(fetchedObservations.body.data.length).toBe(3);+ expect(fetchedObservations.body.data[0]?.id).toBe(+ "observation-2021-03-01",+ );+ expect(fetchedObservations.body.data[1]?.id).toBe(+ "observation-2021-02-01",+ );+ expect(fetchedObservations.body.data[2]?.id).toBe(+ "observation-2021-01-01",+ );+ expect(fetchedObservations.body.meta.totalItems).toBe(3);- expect(fetchedObservations.body.data.length).toBe(3);- expect(fetchedObservations.body.data[0]?.id).toBe("observation-2021-03-01");- expect(fetchedObservations.body.data[1]?.id).toBe("observation-2021-02-01");- expect(fetchedObservations.body.data[2]?.id).toBe("observation-2021-01-01");- expect(fetchedObservations.body.meta.totalItems).toBe(3);-- // test pagination only- fetchedObservations = await makeZodVerifiedAPICall(- GetObservationsV1Response,- "GET",- `/api/public/observations?limit=1&page=2&traceId=${traceId}`,- undefined,- );+ // test pagination only+ fetchedObservations = await makeZodVerifiedAPICall(+ GetObservationsV1Response,+ "GET",+ `/api/public/observations?limit=1&page=2&traceId=${traceId}`,+ undefined,+ );- expect(fetchedObservations.body.data.length).toBe(1);- expect(fetchedObservations.body.data[0]?.id).toBe("observation-2021-03-01");- expect(fetchedObservations.body.meta).toMatchObject({- totalItems: 4,- totalPages: 4,- page: 2,- limit: 1,+ expect(fetchedObservations.body.data.length).toBe(1);+ expect(fetchedObservations.body.data[0]?.id).toBe(+ "observation-2021-03-01",+ );+ expect(fetchedObservations.body.meta).toMatchObject({+ totalItems: 4,+ totalPages: 4,+ page: 2,+ limit: 1,+ });});});});diff --git a/web/src/__tests__/async/scores-api.servertest.ts b/web/src/__tests__/async/scores-api.servertest.tsindex 0195f352f2..280a31908b 100644--- a/web/src/__tests__/async/scores-api.servertest.ts+++ b/web/src/__tests__/async/scores-api.servertest.ts@@ -61,547 +61,675 @@ describe("/api/public/scores API Endpoint", () => {dataType: "NUMERIC",});});- });-});--describe("/api/public/scores API Endpoint", () => {- it("should create score for a trace", async () => {- const traceId = v4();-- const { projectId: projectId, auth } = await createOrgProjectAndApiKey();-- const trace = createTrace({- id: traceId,- project_id: projectId,- });- await createTracesCh([trace]);-- const scoreId = v4();-- const score = createScore({- id: scoreId,- project_id: projectId,- trace_id: traceId,- name: "score-name",- value: 100.5,- source: "API",- comment: "comment",- observation_id: null,- });- await createScoresCh([score]);-- const fetchedScore = await makeZodVerifiedAPICall(- GetScoreResponse,- "GET",- `/api/public/scores/${scoreId}`,- undefined,- auth,- );-- expect(fetchedScore.body?.id).toBe(scoreId);- expect(fetchedScore.body?.traceId).toBe(traceId);- expect(fetchedScore.body?.name).toBe("score-name");- expect(fetchedScore.body?.value).toBe(100.5);- expect(fetchedScore.body?.observationId).toBeNull();- expect(fetchedScore.body?.comment).toBe("comment");- expect(fetchedScore.body?.source).toBe("API");- expect(fetchedScore.body?.projectId).toBe(projectId);- });- 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 = createScore({- 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(- GetScoreResponse,- "GET",- `/api/public/scores/${minimalScoreId}`,- undefined,- auth,- );-- expect(fetchedScore.status).toBe(200);- });-- 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 scoreId_1 = v4();- const scoreId_2 = v4();- const scoreId_3 = v4();- const scoreId_4 = v4();- const scoreId_5 = v4();- let authentication: string;- let newProjectId: string;-- beforeEach(async () => {+ it("should GET score with minimal score data and minimal trace data", async () => {const { projectId, auth } = await createOrgProjectAndApiKey();- authentication = auth;- newProjectId = projectId;++ const minimalTraceId = v4();const trace = createTrace({- id: traceId,- project_id: newProjectId,- user_id: userId,- tags: traceTags,+ id: minimalTraceId,+ project_id: projectId,});+ await createTracesCh([trace]);- const trace_2 = createTrace({- id: traceId_2,- project_id: newProjectId,- user_id: userId,- tags: traceTags_2,- });+ const minimalScoreId = v4();- const trace_3 = createTrace({- id: traceId_3,- project_id: newProjectId,- user_id: userId,- tags: ["staging"],+ const score = createScore({+ id: minimalScoreId,+ project_id: projectId,+ trace_id: minimalTraceId,+ name: "score-name",+ value: 100.5,+ source: "API",+ comment: null,+ observation_id: null,});+ await createScoresCh([score]);- await createTracesCh([trace, trace_2, trace_3]);-- const generation = createObservation({- id: generationId,- project_id: newProjectId,- type: "GENERATION",- });+ const fetchedScore = await makeZodVerifiedAPICall(+ GetScoreResponse,+ "GET",+ `/api/public/scores/${minimalScoreId}`,+ undefined,+ auth,+ );- await createObservationsCh([generation]);+ expect(fetchedScore.status).toBe(200);+ });+ });- const config = await prisma.scoreConfig.create({- data: {- name: scoreName,- dataType: "NUMERIC",- maxValue: 100,- projectId: newProjectId,- },- });+ describe("POST /api/public/scores", () => {+ it("should create score for a trace", async () => {+ const traceId = v4();- configId = config.id;+ const { projectId: projectId, auth } = await createOrgProjectAndApiKey();- const score1 = createScore({- 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 trace = createTrace({+ id: traceId,+ project_id: projectId,});+ await createTracesCh([trace]);- const score2 = createScore({- id: scoreId_2,- project_id: newProjectId,- trace_id: traceId,- name: scoreName,- value: 50.5,- data_type: "NUMERIC",- observation_id: generationId,- comment: "comment",- });+ const scoreId = v4();- const score3 = createScore({- id: scoreId_3,- project_id: newProjectId,+ const score = createScore({+ id: scoreId,+ project_id: projectId,trace_id: traceId,- name: scoreName,- value: 100.8,- data_type: "NUMERIC",- observation_id: generationId,- comment: "comment",- });-- const score4 = createScore({- 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 = createScore({- id: scoreId_5,- project_id: newProjectId,- trace_id: traceId_3,- name: "other-score-name",- value: 0,- data_type: "CATEGORICAL",- string_value: "test",+ name: "score-name",+ value: 100.5,+ source: "API",comment: "comment",+ observation_id: null,+ environment: "production",});+ await createScoresCh([score]);- await createScoresCh([score1, score2, score3, score4, score5]);- });-- it("get all scores", async () => {- const getAllScore = await makeZodVerifiedAPICall(- GetScoresResponse,+ const fetchedScore = await makeZodVerifiedAPICall(+ GetScoreResponse,"GET",- `/api/public/scores?${queryUserName}`,+ `/api/public/scores/${scoreId}`,undefined,- authentication,+ auth,);- 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,- observationId: generationId,- });- }- });- it("get all scores for config", async () => {- const getAllScore = await makeZodVerifiedAPICall(- GetScoresResponse,- "GET",- `/api/public/scores?configId=${configId}`,- undefined,- authentication,- );+ expect(fetchedScore.body?.id).toBe(scoreId);+ expect(fetchedScore.body?.traceId).toBe(traceId);+ expect(fetchedScore.body?.name).toBe("score-name");+ expect(fetchedScore.body?.value).toBe(100.5);+ expect(fetchedScore.body?.observationId).toBeNull();+ expect(fetchedScore.body?.comment).toBe("comment");+ expect(fetchedScore.body?.source).toBe("API");+ expect(fetchedScore.body?.projectId).toBe(projectId);+ expect(fetchedScore.body?.environment).toBe("production");+ });+ });- 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,+ 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 scoreId_1 = v4();+ const scoreId_2 = v4();+ const scoreId_3 = v4();+ const scoreId_4 = v4();+ const scoreId_5 = 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,});- }- });- it("get all scores for numeric data type", async () => {- const getAllScore = await makeZodVerifiedAPICall(- GetScoresResponse,- "GET",- `/api/public/scores?dataType=NUMERIC`,- undefined,- authentication,- );+ const trace_2 = createTrace({+ id: traceId_2,+ project_id: newProjectId,+ user_id: userId,+ tags: traceTags_2,+ });- 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,- observationId: generationId,- dataType: "NUMERIC",+ const trace_3 = createTrace({+ id: traceId_3,+ project_id: newProjectId,+ user_id: userId,+ tags: ["staging"],+ environment: "production",});- }- });- it("get all scores for trace tag 'prod'", async () => {- const getAllScore = await makeZodVerifiedAPICall(- GetScoresResponse,- "GET",- `/api/public/scores?traceTags=prod`,- undefined,- authentication,- );+ await createTracesCh([trace, trace_2, trace_3]);- 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" },+ const generation = createObservation({+ id: generationId,+ project_id: newProjectId,+ type: "GENERATION",});- }- });- it("get all scores for trace tags 'staging' and 'dev'", async () => {- const getAllScore = await makeZodVerifiedAPICall(- GetScoresResponse,- "GET",- `/api/public/scores?traceTags=${["staging", "dev"]}`,- undefined,- authentication,- );+ await createObservationsCh([generation]);- 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",+ const config = await prisma.scoreConfig.create({+ data: {+ name: scoreName,+ dataType: "NUMERIC",+ maxValue: 100,+ projectId: newProjectId,},});- }- });- describe("should Filter scores by queueId", () => {- describe("queueId filtering", () => {- let queueId: string;-- beforeEach(async () => {- queueId = v4();- const score = createScore({- 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 = createScore({- id: v4(),- project_id: newProjectId,- trace_id: traceId,- name: "score-name",- value: 75.0,- source: "ANNOTATION",- comment: "comment",- observation_id: generationId,- queue_id: queueId,- });+ configId = config.id;- await createScoresCh([score, score2]);+ const score1 = createScore({+ 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",});- it("get all scores for queueId", async () => {- const getAllScore = await makeZodVerifiedAPICall(- GetScoresResponse,- "GET",- `/api/public/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",- });- }+ const score2 = createScore({+ id: scoreId_2,+ project_id: newProjectId,+ trace_id: traceId,+ name: scoreName,+ value: 50.5,+ data_type: "NUMERIC",+ observation_id: generationId,+ comment: "comment",+ });++ const score3 = createScore({+ id: scoreId_3,+ project_id: newProjectId,+ trace_id: traceId,+ name: scoreName,+ value: 100.8,+ data_type: "NUMERIC",+ observation_id: generationId,+ comment: "comment",});++ const score4 = createScore({+ 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 = createScore({+ 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",+ });++ await createScoresCh([score1, score2, score3, score4, score5]);});- });- describe("should use score operators correctly", () => {- it("test only operator", async () => {- const getScore = await makeZodVerifiedAPICall(+ it("get all scores", async () => {+ const getAllScore = await makeZodVerifiedAPICall(GetScoresResponse,"GET",- `/api/public/scores?${queryUserName}&operator=<`,+ `/api/public/scores?${queryUserName}`,undefined,authentication,);- expect(getScore.status).toBe(200);- expect(getScore.body.meta).toMatchObject({+ 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,+ observationId: generationId,+ });+ }});- it("test only value", async () => {- const getScore = await makeZodVerifiedAPICall(+ it("get all scores for config", async () => {+ const getAllScore = await makeZodVerifiedAPICall(GetScoresResponse,"GET",- `/api/public/scores?${queryUserName}&value=0.8`,+ `/api/public/scores?configId=${configId}`,undefined,authentication,);- expect(getScore.status).toBe(200);- expect(getScore.body.meta).toMatchObject({++ expect(getAllScore.status).toBe(200);+ expect(getAllScore.body.meta).toMatchObject({page: 1,limit: 50,- totalItems: 3,+ totalItems: 1,totalPages: 1,});+ for (const val of getAllScore.body.data) {+ expect(val).toMatchObject({+ traceId: traceId,+ observationId: generationId,+ configId: configId,+ });+ }});- it("test operator <", async () => {- const getScore = await makeZodVerifiedAPICall(+ it("get all scores for numeric data type", async () => {+ const getAllScore = await makeZodVerifiedAPICall(GetScoresResponse,"GET",- `/api/public/scores?${queryUserName}&operator=<&value=50`,+ `/api/public/scores?dataType=NUMERIC`,undefined,authentication,);- expect(getScore.status).toBe(200);- expect(getScore.body.meta).toMatchObject({++ expect(getAllScore.status).toBe(200);+ expect(getAllScore.body.meta).toMatchObject({page: 1,limit: 50,- totalItems: 1,+ totalItems: 3,totalPages: 1,});- expect(getScore.body.data).toMatchObject([- {- id: scoreId_1,- name: scoreName,- value: 10.5,- },- ]);+ for (const val of getAllScore.body.data) {+ expect(val).toMatchObject({+ traceId: traceId,+ observationId: generationId,+ dataType: "NUMERIC",+ });+ }});- it("test operator >", async () => {- const getScore = await makeZodVerifiedAPICall(+ it("get all scores for trace tag 'prod'", async () => {+ const getAllScore = await makeZodVerifiedAPICall(GetScoresResponse,"GET",- `/api/public/scores?${queryUserName}&operator=>&value=100`,+ `/api/public/scores?traceTags=prod`,undefined,authentication,);- expect(getScore.status).toBe(200);- expect(getScore.body.meta).toMatchObject({++ expect(getAllScore.status).toBe(200);+ expect(getAllScore.body.meta).toMatchObject({page: 1,limit: 50,- totalItems: 1,+ totalItems: 3,totalPages: 1,});- expect(getScore.body.data).toMatchObject([- {- id: scoreId_3,- name: scoreName,- value: 100.8,- },- ]);+ for (const val of getAllScore.body.data) {+ expect(val).toMatchObject({+ traceId: traceId,+ trace: { tags: ["prod", "test"], userId: "user-name" },+ });+ }});- it("test operator <=", async () => {- const getScore = await makeZodVerifiedAPICall(+ it("get all scores for environment 'production'", async () => {+ const getAllScore = await makeZodVerifiedAPICall(GetScoresResponse,"GET",- `/api/public/scores?${queryUserName}&operator=<=&value=50.5`,+ `/api/public/scores?environment=production`,undefined,authentication,);- expect(getScore.status).toBe(200);- expect(getScore.body.meta).toMatchObject({++ expect(getAllScore.status).toBe(200);+ expect(getAllScore.body.meta).toMatchObject({page: 1,limit: 50,- totalItems: 2,+ totalItems: 1,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,- }),- ]),- );+ for (const val of getAllScore.body.data) {+ expect(val).toMatchObject({+ traceId: traceId_3,+ trace: {+ userId: "user-name",+ tags: ["staging"],+ environment: "production",+ },+ environment: "production",+ });+ }});- it("test operator >=", async () => {- const getScore = await makeZodVerifiedAPICall(+ it("get all scores for trace tags 'staging' and 'dev'", async () => {+ const getAllScore = await makeZodVerifiedAPICall(GetScoresResponse,"GET",- `/api/public/scores?${queryUserName}&operator=>=&value=50.5`,+ `/api/public/scores?traceTags=${["staging", "dev"]}`,undefined,authentication,);- expect(getScore.status).toBe(200);- expect(getScore.body.meta).toMatchObject({++ expect(getAllScore.status).toBe(200);+ expect(getAllScore.body.meta).toMatchObject({page: 1,limit: 50,- totalItems: 2,+ totalItems: 1,totalPages: 1,});- expect(getScore.body.data).toEqual(- expect.arrayContaining([- expect.objectContaining({+ 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 = createScore({+ 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 = createScore({+ 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(+ GetScoresResponse,+ "GET",+ `/api/public/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(+ GetScoresResponse,+ "GET",+ `/api/public/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(+ GetScoresResponse,+ "GET",+ `/api/public/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(+ GetScoresResponse,+ "GET",+ `/api/public/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(+ GetScoresResponse,+ "GET",+ `/api/public/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,- }),- expect.objectContaining({+ },+ ]);+ });++ it("test operator <=", async () => {+ const getScore = await makeZodVerifiedAPICall(+ GetScoresResponse,+ "GET",+ `/api/public/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(+ GetScoresResponse,+ "GET",+ `/api/public/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(+ GetScoresResponse,+ "GET",+ `/api/public/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(+ GetScoresResponse,+ "GET",+ `/api/public/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/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/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("test operator !=", async () => {+ it("should filter scores by score IDs", async () => {const getScore = await makeZodVerifiedAPICall(GetScoresResponse,"GET",- `/api/public/scores?${queryUserName}&operator=!=&value=50.5`,+ `/api/public/scores?scoreIds=${scoreId_1},${scoreId_2}`,undefined,authentication,);@@ -615,9 +743,9 @@ describe("/api/public/scores API Endpoint", () => {expect(getScore.body.data).toEqual(expect.arrayContaining([expect.objectContaining({- id: scoreId_3,+ id: scoreId_2,name: scoreName,- value: 100.8,+ value: 50.5,}),expect.objectContaining({id: scoreId_1,@@ -627,99 +755,6 @@ describe("/api/public/scores API Endpoint", () => {]),);});-- it("test operator =", async () => {- const getScore = await makeZodVerifiedAPICall(- GetScoresResponse,- "GET",- `/api/public/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/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/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(- GetScoresResponse,- "GET",- `/api/public/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/sessions-api.servertest.ts b/web/src/__tests__/async/sessions-api.servertest.tsindex ec5542b5d1..1190326993 100644--- a/web/src/__tests__/async/sessions-api.servertest.ts+++ b/web/src/__tests__/async/sessions-api.servertest.ts@@ -42,6 +42,7 @@ describe("/api/public/sessions API Endpoint", () => {expect(getScore.body).toMatchObject({id: sessionId,projectId,+ environment: "default",createdAt: expect.any(String),});@@ -50,6 +51,7 @@ describe("/api/public/sessions API Endpoint", () => {);});});+describe("GET /api/public/sessions API Endpoint", () => {let projectId: string;let auth: string;@@ -86,6 +88,7 @@ describe("/api/public/sessions API Endpoint", () => {id: "session-2021-05-01",createdAt: new Date("2021-05-01T00:00:00Z"),projectId: projectId,+ environment: "production",},],});@@ -111,6 +114,38 @@ describe("/api/public/sessions API Endpoint", () => {);});+ it("should return sessions with environment", async () => {+ const sessions = await makeZodVerifiedAPICall(+ GetSessionsV1Response,+ "GET",+ "/api/public/sessions",+ undefined,+ auth,+ );+ expect(sessions.body.data.length).toEqual(5);+ expect(sessions.body.data.map((session) => session.environment)).toEqual(+ expect.arrayContaining([+ "default",+ "default",+ "default",+ "default",+ "production",+ ]),+ );+ });++ it("should filter sessions by environment", async () => {+ const sessions = await makeZodVerifiedAPICall(+ GetSessionsV1Response,+ "GET",+ "/api/public/sessions?environment=production",+ undefined,+ auth,+ );+ expect(sessions.body.data.length).toEqual(1);+ expect(sessions.body.data[0].environment).toEqual("production");+ });+it("should return paginated sessions with limit and page number", async () => {const limit = 2;const page = 2;diff --git a/web/src/__tests__/async/traces-api.servertest.ts b/web/src/__tests__/async/traces-api.servertest.tsindex cb046b942a..59dbfb4f87 100644--- a/web/src/__tests__/async/traces-api.servertest.ts+++ b/web/src/__tests__/async/traces-api.servertest.ts@@ -1,4 +1,9 @@-import { createObservation, createTrace } from "@langfuse/shared/src/server";+import {+ createObservation,+ createScore,+ createScoresCh,+ createTrace,+} from "@langfuse/shared/src/server";import {createObservationsCh,createTracesCh,@@ -147,6 +152,7 @@ describe("/api/public/traces API Endpoint", () => {["release", randomUUID()],["version", randomUUID()],["name", randomUUID()],+ ["environment", randomUUID()],])("should fetch all traces filtered by a value (%s, %s)",async (prop: string, value: string) => {@@ -156,7 +162,13 @@ describe("/api/public/traces API Endpoint", () => {metadata: { key: "value" },});- await createTracesCh([createdTrace]);+ // Create a trace in the project that should not be returned+ const dummyTrace = createTrace({+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ metadata: { key: "value" },+ });++ await createTracesCh([createdTrace, dummyTrace]);const traces = await makeZodVerifiedAPICall(GetTracesV1Response,@@ -172,6 +184,61 @@ describe("/api/public/traces API Endpoint", () => {},);+ it("should fetch all traces, observations, and scores filtered by environment", async () => {+ const environment = randomUUID();+ const traceId = randomUUID();+ const createdTrace = createTrace({+ id: traceId,+ name: "trace-name",+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ metadata: { key: "value" },+ environment,+ });++ await createTracesCh([createdTrace]);++ await createObservationsCh([+ createObservation({+ trace_id: traceId,+ environment,+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ }),+ // Create one that does not belong to the same environment+ createObservation({+ trace_id: traceId,+ environment: "default",+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ }),+ ]);++ await createScoresCh([+ createScore({+ trace_id: traceId,+ environment,+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ }),+ // Create one that does not belong to the same environment+ createScore({+ trace_id: traceId,+ environment: "default",+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ }),+ ]);++ 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("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");+ expect(trace.observations.length).toBe(1);+ expect(trace.scores.length).toBe(1);+ });+it("should fetch all traces filtered by a tag", async () => {const tag = randomUUID();const createdTrace = createTrace({diff --git a/web/src/features/public-api/server/dailyMetrics.ts b/web/src/features/public-api/server/dailyMetrics.tsindex 60df0fcc3c..81f1a937f1 100644--- a/web/src/features/public-api/server/dailyMetrics.ts+++ b/web/src/features/public-api/server/dailyMetrics.ts@@ -22,7 +22,10 @@ export const generateDailyMetrics = async (props: QueryType) => {props,filterParams,);+ const hasTracesFilter = filter.some((f) => f.clickhouseTable === "traces");+ const tracesFilter = filter.filter((f) => f.clickhouseTable === "traces");const appliedFilter = filter.apply();+ const appliedTracesFilter = tracesFilter.apply();const timeFilter = filter.find((f) =>@@ -71,7 +74,7 @@ export const generateDailyMetrics = async (props: QueryType) => {count(t.id) as countTracesFROM traces t FINALWHERE t.project_id = {projectId: String}- ${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}+ ${hasTracesFilter ? `AND ${appliedTracesFilter.query}` : ""}GROUP BY date)@@ -96,6 +99,7 @@ export const generateDailyMetrics = async (props: QueryType) => {}>({query,params: {+ ...appliedTracesFilter.params,...appliedFilter.params,projectId: props.projectId,...(props.limit !== undefined ? { limit: props.limit } : {}),@@ -135,7 +139,9 @@ export const getDailyMetricsCount = async (props: QueryType) => {props,filterParams,);- const appliedFilter = filter.apply();+ const appliedFilter = filter+ .filter((f) => f.clickhouseTable === "traces")+ .apply();const query = `SELECT count(distinct toDate(timestamp)) as count@@ -173,6 +179,20 @@ const filterParams = [clickhouseTable: "traces",clickhousePrefix: "t",},+ {+ id: "traceEnvironment",+ clickhouseSelect: "environment",+ filterType: "StringOptionsFilter",+ clickhouseTable: "traces",+ clickhousePrefix: "t",+ },+ {+ id: "observationEnvironment",+ clickhouseSelect: "environment",+ filterType: "StringOptionsFilter",+ clickhouseTable: "observations",+ clickhousePrefix: "o",+ },{id: "fromTimestamp",clickhouseSelect: "timestamp",diff --git a/web/src/features/public-api/server/observations.ts b/web/src/features/public-api/server/observations.tsindex 21d5777ec7..34f9f9a234 100644--- a/web/src/features/public-api/server/observations.ts+++ b/web/src/features/public-api/server/observations.ts@@ -182,6 +182,13 @@ const filterParams = [clickhouseTable: "observations",clickhousePrefix: "o",},+ {+ id: "environment",+ clickhouseSelect: "environment",+ filterType: "StringFilter",+ clickhouseTable: "observations",+ clickhousePrefix: "o",+ },];const generateFilter = (filter: QueryType) => {diff --git a/web/src/features/public-api/server/scores.ts b/web/src/features/public-api/server/scores.tsindex 3dd9b4c731..3efb8a86b8 100644--- a/web/src/features/public-api/server/scores.ts+++ b/web/src/features/public-api/server/scores.ts@@ -38,6 +38,7 @@ export const generateScoresForPublicApi = async (props: ScoreQueryType) => {SELECTt.user_id as user_id,t.tags as tags,+ t.environment as trace_environment,s.id as id,s.project_id as project_id,s.timestamp as timestamp,@@ -82,7 +83,11 @@ export const generateScoresForPublicApi = async (props: ScoreQueryType) => {`;const records = await queryClickhouse<- ScoreRecordReadType & { tags: string[]; user_id: string }+ ScoreRecordReadType & {+ tags: string[];+ user_id: string;+ trace_environment: string;+ }>({query,params: {@@ -98,7 +103,11 @@ export const generateScoresForPublicApi = async (props: ScoreQueryType) => {return records.map((record) => ({...convertToScore(record),- trace: { userId: record.user_id, tags: record.tags },+ trace: {+ userId: record.user_id,+ tags: record.tags,+ environment: record.trace_environment,+ },}));};@@ -213,7 +222,13 @@ const secureScoreFilterOptions: ApiColumnMapping[] = [filterType: "StringFilter",clickhousePrefix: "s",},-+ {+ id: "environment",+ clickhouseSelect: "environment",+ clickhouseTable: "scores",+ filterType: "StringOptionsFilter",+ clickhousePrefix: "s",+ },{id: "dataType",clickhouseSelect: "data_type",@@ -238,6 +253,13 @@ const secureTraceFilterOptions = [filterType: "StringFilter",clickhousePrefix: "t",},+ {+ id: "traceEnvironment",+ clickhouseSelect: "environment",+ clickhouseTable: "traces",+ filterType: "StringOptionsFilter",+ clickhousePrefix: "t",+ },];const generateScoreFilter = (filter: ScoreQueryType) => {diff --git a/web/src/features/public-api/server/traces.ts b/web/src/features/public-api/server/traces.tsindex ec72dc0f1b..283e00b3d7 100644--- a/web/src/features/public-api/server/traces.ts+++ b/web/src/features/public-api/server/traces.ts@@ -23,6 +23,7 @@ type QueryType = {version?: string;release?: string;tags?: string | string[];+ environment?: string | string[];fromTimestamp?: string;toTimestamp?: string;};@@ -44,6 +45,9 @@ export const generateTracesForPublicApi = async ((f.operator === ">=" || f.operator === ">"),) as DateTimeFilter | undefined;+ const environmentFilter = filter.filter((f) => f.field === "environment");+ const appliedEnvironmentFilter = environmentFilter.apply();+// This _must_ be updated if we add a new skip index column to the traces table.// Otherwise, we will ignore it in most cases due to `FINAL`.const shouldUseSkipIndexes = filter.some(@@ -75,6 +79,7 @@ export const generateTracesForPublicApi = async (FROM observations FINALWHERE project_id = {projectId: String}${timeFilter ? `AND start_time >= {cteTimeFilter: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}+ ${environmentFilter.length() > 0 ? `AND ${appliedEnvironmentFilter.query}` : ""}GROUP BY project_id, trace_id), score_stats AS (SELECT@@ -84,6 +89,7 @@ export const generateTracesForPublicApi = async (FROM scoresWHERE project_id = {projectId: String}${timeFilter ? `AND timestamp >= {cteTimeFilter: DateTime64(3)}` : ""}+ ${environmentFilter.length() > 0 ? `AND ${appliedEnvironmentFilter.query}` : ""}GROUP BY project_id, trace_id)@@ -131,6 +137,7 @@ export const generateTracesForPublicApi = async (>({query,params: {+ ...appliedEnvironmentFilter.params,...appliedFilter.params,projectId: props.projectId,...(props.limit !== undefined ? { limit: props.limit } : {}),@@ -237,6 +244,14 @@ const filterParams = [clickhouseTable: "traces",clickhousePrefix: "t",},+ {+ id: "environment",+ clickhouseSelect: "environment",+ filterType: "StringOptionsFilter",+ clickhouseTable: "traces",+ // Skip the clickhousePrefix as this makes it work for all tables.+ // Risk: If there is a conflict we may have to start using separate filters for each table.+ },{id: "fromTimestamp",clickhouseSelect: "timestamp",diff --git a/web/src/features/public-api/types/metrics.ts b/web/src/features/public-api/types/metrics.tsindex 06a2afd5ed..6b17dec163 100644--- a/web/src/features/public-api/types/metrics.ts+++ b/web/src/features/public-api/types/metrics.ts@@ -15,6 +15,7 @@ export const GetMetricsDailyV1Query = z.object({traceName: z.string().nullish(),userId: z.string().nullish(),tags: z.union([z.array(z.string()), z.string()]).nullish(),+ environment: z.union([z.array(z.string()), z.string()]).nullish(),fromTimestamp: stringDateTime,toTimestamp: stringDateTime,});diff --git a/web/src/features/public-api/types/observations.ts b/web/src/features/public-api/types/observations.tsindex 8800dfa0cb..2a42ce4d33 100644--- a/web/src/features/public-api/types/observations.ts+++ b/web/src/features/public-api/types/observations.ts@@ -127,6 +127,7 @@ export const GetObservationsV1Query = z.object({traceId: z.string().nullish(),version: z.string().nullish(),parentObservationId: z.string().nullish(),+ environment: z.union([z.array(z.string()), z.string()]).nullish(),fromStartTime: stringDateTime,toStartTime: stringDateTime,});diff --git a/web/src/features/public-api/types/sessions.ts b/web/src/features/public-api/types/sessions.tsindex 40c1500b3b..cb11fc38da 100644--- a/web/src/features/public-api/types/sessions.ts+++ b/web/src/features/public-api/types/sessions.ts@@ -16,6 +16,7 @@ const APISession = zid: z.string(),createdAt: z.coerce.date(),projectId: z.string(),+ environment: z.string(),}).strict();@@ -28,6 +29,7 @@ export const GetSessionsV1Query = z.object({...publicApiPaginationZod,fromTimestamp: stringDateTime,toTimestamp: stringDateTime,+ environment: z.union([z.array(z.string()), z.string()]).nullish(),});export const GetSessionsV1Response = z.object({diff --git a/web/src/features/public-api/types/traces.ts b/web/src/features/public-api/types/traces.tsindex 394e324f7f..766a57623d 100644--- a/web/src/features/public-api/types/traces.ts+++ b/web/src/features/public-api/types/traces.ts@@ -53,6 +53,7 @@ export const GetTracesV1Query = z.object({userId: z.string().nullish(),name: z.string().nullish(),tags: z.union([z.array(z.string()), z.string()]).nullish(),+ environment: z.union([z.array(z.string()), z.string()]).nullish(),sessionId: z.string().nullish(),version: z.string().nullish(),release: z.string().nullish(),diff --git a/web/src/pages/api/public/metrics/daily.ts b/web/src/pages/api/public/metrics/daily.tsindex 18b26da93f..d7e408a277 100644--- a/web/src/pages/api/public/metrics/daily.ts+++ b/web/src/pages/api/public/metrics/daily.ts@@ -23,6 +23,9 @@ export default withMiddlewares({traceName: query.traceName ?? undefined,userId: query.userId ?? undefined,tags: query.tags ?? undefined,+ // We need to map environment to both keys to propagate the filter to all tables.+ traceEnvironment: query.environment ?? undefined,+ observationEnvironment: query.environment ?? undefined,fromTimestamp: query.fromTimestamp ?? undefined,toTimestamp: query.toTimestamp ?? undefined,};diff --git a/web/src/pages/api/public/observations/index.ts b/web/src/pages/api/public/observations/index.tsindex dbc37c64a9..306bc28302 100644--- a/web/src/pages/api/public/observations/index.ts+++ b/web/src/pages/api/public/observations/index.ts@@ -27,6 +27,7 @@ export default withMiddlewares({userId: query.userId ?? undefined,name: query.name ?? undefined,type: query.type ?? undefined,+ environment: query.environment ?? undefined,parentObservationId: query.parentObservationId ?? undefined,fromStartTime: query.fromStartTime ?? undefined,toStartTime: query.toStartTime ?? undefined,diff --git a/web/src/pages/api/public/scores/index.ts b/web/src/pages/api/public/scores/index.tsindex 8d46421cd9..8b9d88be91 100644--- a/web/src/pages/api/public/scores/index.ts+++ b/web/src/pages/api/public/scores/index.ts@@ -54,41 +54,28 @@ export default withMiddlewares({querySchema: GetScoresQuery,responseSchema: GetScoresResponse,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 [items, count] = await Promise.all([- generateScoresForPublicApi({- 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,- source: query.source ?? undefined,- value: query.value ?? undefined,- operator: query.operator ?? undefined,- scoreIds: query.scoreIds ?? undefined,- }),- getScoresCountForPublicApi({- 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,- source: query.source ?? undefined,- value: query.value ?? undefined,- operator: query.operator ?? undefined,- scoreIds: query.scoreIds ?? undefined,- }),+ generateScoresForPublicApi(scoreParams),+ getScoresCountForPublicApi(scoreParams),]);const finalCount = count ? count : 0;diff --git a/web/src/pages/api/public/sessions/[sessionId].ts b/web/src/pages/api/public/sessions/[sessionId].tsindex 15345e8ab5..ff6d28af62 100644--- a/web/src/pages/api/public/sessions/[sessionId].ts+++ b/web/src/pages/api/public/sessions/[sessionId].ts@@ -26,6 +26,7 @@ export default withMiddlewares({id: true,createdAt: true,projectId: true,+ environment: true,},});diff --git a/web/src/pages/api/public/sessions/index.ts b/web/src/pages/api/public/sessions/index.tsindex 250782ccf5..1cd4f366e7 100644--- a/web/src/pages/api/public/sessions/index.ts+++ b/web/src/pages/api/public/sessions/index.ts@@ -12,13 +12,14 @@ export default withMiddlewares({querySchema: GetSessionsV1Query,responseSchema: GetSessionsV1Response,fn: async ({ query, auth }) => {- const { fromTimestamp, toTimestamp, limit, page } = query;+ const { fromTimestamp, toTimestamp, limit, page, environment } = query;const sessions = await prisma.traceSession.findMany({select: {id: true,createdAt: true,projectId: true,+ environment: true,},where: {projectId: auth.scope.projectId,@@ -26,6 +27,11 @@ export default withMiddlewares({...(fromTimestamp && { gte: new Date(fromTimestamp) }),...(toTimestamp && { lt: new Date(toTimestamp) }),},+ environment: environment+ ? Array.isArray(environment)+ ? { in: environment }+ : environment+ : undefined,},orderBy: { createdAt: "desc" },take: limit,diff --git a/web/src/pages/api/public/traces/index.ts b/web/src/pages/api/public/traces/index.tsindex bba7c5ef61..f2e41d4ffe 100644--- a/web/src/pages/api/public/traces/index.ts+++ b/web/src/pages/api/public/traces/index.ts@@ -62,6 +62,7 @@ export default withMiddlewares({userId: query.userId ?? undefined,name: query.name ?? undefined,tags: query.tags ?? undefined,+ environment: query.environment ?? undefined,sessionId: query.sessionId ?? undefined,version: query.version ?? undefined,release: query.release ?? undefined,