Skip to content

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

feat(api): add GET /sessions, more time cursors to list endpoints, use withMiddleware and strict zod types for many existing api routes (#2551)

Marc Klingend045869dc4d0
diff --git a/fern/apis/server/definition/commons.yml b/fern/apis/server/definition/commons.yml
index 5220e57f7d..a7983a2914 100644
--- a/fern/apis/server/definition/commons.yml
+++ b/fern/apis/server/definition/commons.yml
@@ -42,11 +42,18 @@ types:
htmlPath:
type: string
docs: Path of trace in Langfuse UI
+ latency:
+ type: double
+ docs: Latency of trace in seconds
totalCost:
type: double
docs: Cost of trace in USD
- observations: list<ObservationsView>
- scores: list<Score>
+ observations:
+ type: list<ObservationsView>
+ docs: List of observations
+ scores:
+ type: list<Score>
+ docs: List of scores
Session:
properties:
id: string
@@ -88,6 +95,7 @@ types:
calculatedOutputCost: optional<double>
calculatedTotalCost: optional<double>
latency: optional<double>
+ timeToFirstToken: optional<double>
Usage:
docs: Standard interface for usage and cost
diff --git a/fern/apis/server/definition/observations.yml b/fern/apis/server/definition/observations.yml
index e4288ec5ac..7f3a7fef8e 100644
--- a/fern/apis/server/definition/observations.yml
+++ b/fern/apis/server/definition/observations.yml
@@ -35,7 +35,10 @@ service:
parentObservationId: optional<string>
fromStartTime:
type: optional<datetime>
- docs: Retrieve only observations with a start_time greater than this datetime (ISO 8601).
+ docs: Retrieve only observations with a start_time or or after this datetime (ISO 8601).
+ toStartTime:
+ type: optional<datetime>
+ docs: Retrieve only observations with a start_time before this datetime (ISO 8601).
response: ObservationsViews
types:
diff --git a/fern/apis/server/definition/score.yml b/fern/apis/server/definition/score.yml
index ab23f66193..9d0e7106f2 100644
--- a/fern/apis/server/definition/score.yml
+++ b/fern/apis/server/definition/score.yml
@@ -11,7 +11,7 @@ service:
method: POST
path: /scores
request: CreateScoreRequest
- response: commons.Score
+ response: CreateScoreResponse
get:
docs: Get a list of scores
method: GET
@@ -33,7 +33,10 @@ service:
docs: Retrieve only scores with this name.
fromTimestamp:
type: optional<datetime>
- docs: Retrieve only scores newer than this datetime (ISO 8601).
+ docs: Optional filter to only include scores created on or after a certain datetime (ISO 8601)
+ toTimestamp:
+ type: optional<datetime>
+ docs: Optional filter to only include scores created before a certain datetime (ISO 8601)
source:
type: optional<commons.ScoreSource>
docs: Retrieve only scores from a specific source.
@@ -124,7 +127,11 @@ types:
dataType: "BOOLEAN"
configId: "1234-5678-90ab-cdef"
traceId: "cdef-1234-5678-90ab"
-
+ CreateScoreResponse:
+ properties:
+ id:
+ type: string
+ docs: The id of the created object in Langfuse
Scores:
properties:
data: list<commons.Score>
diff --git a/fern/apis/server/definition/sessions.yml b/fern/apis/server/definition/sessions.yml
index 7aea2d74c4..c3888da10e 100644
--- a/fern/apis/server/definition/sessions.yml
+++ b/fern/apis/server/definition/sessions.yml
@@ -6,6 +6,26 @@ service:
auth: true
base-path: /api/public
endpoints:
+ list:
+ docs: Get sessions.
+ method: GET
+ path: /sessions
+ request:
+ name: GetSessionsRequest
+ query-parameters:
+ page:
+ type: optional<integer>
+ docs: Page number, starts at 1
+ limit:
+ type: optional<integer>
+ docs: Limit of items per page. If you encounter api issues due to too large page sizes, try to reduce the limit.
+ fromTimestamp:
+ type: optional<datetime>
+ docs: Optional filter to only include sessions created on or after a certain datetime (ISO 8601)
+ toTimestamp:
+ type: optional<datetime>
+ docs: Optional filter to only include sessions created before a certain datetime (ISO 8601)
+ response: PaginatedSessions
get:
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>`
method: GET
@@ -15,3 +35,8 @@ service:
type: string
docs: The unique id of a session
response: commons.SessionWithTraces
+types:
+ PaginatedSessions:
+ properties:
+ data: list<commons.Session>
+ meta: pagination.MetaResponse
diff --git a/fern/apis/server/definition/trace.yml b/fern/apis/server/definition/trace.yml
index 1c16c27d9b..d173f7d3e4 100644
--- a/fern/apis/server/definition/trace.yml
+++ b/fern/apis/server/definition/trace.yml
@@ -33,7 +33,10 @@ service:
sessionId: optional<string>
fromTimestamp:
type: optional<datetime>
- docs: Retrieve only traces newer than this datetime (ISO 8601).
+ docs: Optional filter to only include traces with a trace.timestamp on or after a certain datetime (ISO 8601)
+ toTimestamp:
+ type: optional<datetime>
+ docs: Optional filter to only include traces with a trace.timestamp before a certain datetime (ISO 8601)
orderBy:
type: optional<string>
docs: "Format of the string [field].[asc/desc]. Fields: id, timestamp, name, userId, release, version, public, bookmarked, sessionId. Example: timestamp.asc"
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index feb1412284..d58677b7cb 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -301,9 +301,9 @@ model Observation {
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
// GENERATION ONLY
- model String?
- internalModel String? @map("internal_model")
- internalModelId String? @map("internal_model_id")
+ model String? // user-provided model attribute
+ internalModel String? @map("internal_model") // matched model.name that is matched at ingestion time, to be deprecated
+ internalModelId String? @map("internal_model_id") // matched model.id that is matched at ingestion time
modelParameters Json?
input Json?
diff --git a/packages/shared/src/features/ingestion/types.ts b/packages/shared/src/features/ingestion/types.ts
index e154d91e62..36a38610cf 100644
--- a/packages/shared/src/features/ingestion/types.ts
+++ b/packages/shared/src/features/ingestion/types.ts
@@ -28,7 +28,7 @@ const MixedUsage = z.object({
totalCost: z.number().nullish(),
});
-export const stringDate = z.string().datetime({ offset: true }).nullish();
+export const stringDateTime = z.string().datetime({ offset: true }).nullish();
export const usage = MixedUsage.nullish()
// transform mixed usage model input to new one
@@ -58,7 +58,7 @@ export const usage = MixedUsage.nullish()
export const TraceBody = z.object({
id: z.string().nullish(),
- timestamp: stringDate,
+ timestamp: stringDateTime,
name: z.string().nullish(),
externalId: z.string().nullish(),
input: jsonSchema.nullish(),
@@ -75,7 +75,7 @@ export const TraceBody = z.object({
export const OptionalObservationBody = z.object({
traceId: z.string().nullish(),
name: z.string().nullish(),
- startTime: stringDate,
+ startTime: stringDateTime,
metadata: jsonSchema.nullish(),
input: jsonSchema.nullish(),
output: jsonSchema.nullish(),
@@ -94,15 +94,15 @@ export const UpdateEventEvent = OptionalObservationBody.extend({
});
export const CreateSpanBody = CreateEventEvent.extend({
- endTime: stringDate,
+ endTime: stringDateTime,
});
export const UpdateSpanBody = UpdateEventEvent.extend({
- endTime: stringDate,
+ endTime: stringDateTime,
});
export const CreateGenerationBody = CreateSpanBody.extend({
- completionStartTime: stringDate,
+ completionStartTime: stringDateTime,
model: z.string().nullish(),
modelParameters: z
.record(
@@ -130,7 +130,7 @@ export const CreateGenerationBody = CreateSpanBody.extend({
});
export const UpdateGenerationBody = UpdateSpanBody.extend({
- completionStartTime: stringDate,
+ completionStartTime: stringDateTime,
model: z.string().nullish(),
modelParameters: z
.record(
@@ -231,8 +231,8 @@ export const LegacySpanPostSchema = z.object({
id: z.string().nullish(),
traceId: z.string().nullish(),
name: z.string().nullish(),
- startTime: stringDate,
- endTime: stringDate,
+ startTime: stringDateTime,
+ endTime: stringDateTime,
metadata: jsonSchema.nullish(),
input: jsonSchema.nullish(),
output: jsonSchema.nullish(),
@@ -246,8 +246,8 @@ export const LegacySpanPatchSchema = z.object({
spanId: z.string(),
traceId: z.string().nullish(),
name: z.string().nullish(),
- startTime: stringDate,
- endTime: stringDate,
+ startTime: stringDateTime,
+ endTime: stringDateTime,
metadata: jsonSchema.nullish(),
input: jsonSchema.nullish(),
output: jsonSchema.nullish(),
@@ -260,9 +260,9 @@ export const LegacyGenerationsCreateSchema = z.object({
id: z.string().nullish(),
traceId: z.string().nullish(),
name: z.string().nullish(),
- startTime: stringDate,
- endTime: stringDate,
- completionStartTime: stringDate,
+ startTime: stringDateTime,
+ endTime: stringDateTime,
+ completionStartTime: stringDateTime,
model: z.string().nullish(),
modelParameters: z
.record(
@@ -284,9 +284,9 @@ export const LegacyGenerationPatchSchema = z.object({
generationId: z.string(),
traceId: z.string().nullish(),
name: z.string().nullish(),
- startTime: stringDate,
- endTime: stringDate,
- completionStartTime: stringDate,
+ startTime: stringDateTime,
+ endTime: stringDateTime,
+ completionStartTime: stringDateTime,
model: z.string().nullish(),
modelParameters: z
.record(
@@ -308,9 +308,9 @@ export const LegacyObservationBody = z.object({
traceId: z.string().nullish(),
type: z.enum(["GENERATION", "SPAN", "EVENT"]),
name: z.string().nullish(),
- startTime: stringDate,
- endTime: stringDate,
- completionStartTime: stringDate,
+ startTime: stringDateTime,
+ endTime: stringDateTime,
+ completionStartTime: stringDateTime,
model: z.string().nullish(),
modelParameters: z
.record(
diff --git a/web/src/__tests__/datasets.servertest.ts b/web/src/__tests__/datasets.servertest.ts
index a3fab671b1..e51b1ecbf2 100644
--- a/web/src/__tests__/datasets.servertest.ts
+++ b/web/src/__tests__/datasets.servertest.ts
@@ -95,7 +95,8 @@ describe("/api/public/datasets and /api/public/dataset-items API Endpoints", ()
expect(dbDataset.length).toBeGreaterThan(0);
// get dataset (v1) excluding items and runs
- const getDatasetV1 = await makeAPICall(
+ const getDatasetV1 = await makeZodVerifiedAPICall(
+ GetDatasetV1Response,
"GET",
`/api/public/datasets/${encodeURIComponent("dataset + name")}`,
);
diff --git a/web/src/__tests__/events.servertest.ts b/web/src/__tests__/events.servertest.ts
index 0fde5e596c..21552ca502 100644
--- a/web/src/__tests__/events.servertest.ts
+++ b/web/src/__tests__/events.servertest.ts
@@ -1,8 +1,13 @@
/** @jest-environment node */
import { prisma } from "@langfuse/shared/src/db";
-import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
+import {
+ makeZodVerifiedAPICall,
+ pruneDatabase,
+} from "@/src/__tests__/test-utils";
import { v4 as uuidv4 } from "uuid";
+import { PostTracesV1Response } from "@/src/features/public-api/types/traces";
+import { PostEventsV1Response } from "@/src/features/public-api/types/events";
describe("/api/public/events API Endpoint", () => {
beforeEach(async () => await pruneDatabase());
@@ -12,15 +17,22 @@ describe("/api/public/events API Endpoint", () => {
const traceId = uuidv4();
- await makeAPICall("POST", "/api/public/traces", {
- id: traceId,
- name: "trace-name",
- userId: "user-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- metadata: { key: "value" },
- release: "1.0.0",
- version: "2.0.0",
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ id: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
const dbTrace = await prisma.trace.findMany({
where: {
@@ -32,16 +44,23 @@ describe("/api/public/events API Endpoint", () => {
expect(dbTrace[0]?.id).toBe(traceId);
const eventId = uuidv4();
- const createEvent = await makeAPICall("POST", "/api/public/events", {
- id: eventId,
- traceId: traceId,
- name: "event-name",
- startTime: "2021-01-01T00:00:00.000Z",
- input: { input: "value" },
- output: { output: "value" },
- metadata: { meta: "value" },
- version: "2.0.0",
- });
+ const createEvent = await makeZodVerifiedAPICall(
+ PostEventsV1Response,
+ "POST",
+ "/api/public/events",
+ {
+ id: eventId,
+ traceId: traceId,
+ name: "event-name",
+ startTime: "2021-01-01T00:00:00.000Z",
+ input: { input: "value" },
+ output: { output: "value" },
+ metadata: { meta: "value" },
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
expect(createEvent.status).toBe(200);
const dbEvent = await prisma.observation.findUnique({
@@ -66,16 +85,23 @@ describe("/api/public/events API Endpoint", () => {
const traceId = uuidv4();
const eventId = uuidv4();
- const createEvent = await makeAPICall("POST", "/api/public/events", {
- id: eventId,
- traceId: traceId,
- name: "event-name",
- startTime: "2021-01-01T00:00:00.000Z",
- input: { input: "value" },
- output: { output: "value" },
- metadata: { meta: "value" },
- version: "2.0.0",
- });
+ const createEvent = await makeZodVerifiedAPICall(
+ PostEventsV1Response,
+ "POST",
+ "/api/public/events",
+ {
+ id: eventId,
+ traceId: traceId,
+ name: "event-name",
+ startTime: "2021-01-01T00:00:00.000Z",
+ input: { input: "value" },
+ output: { output: "value" },
+ metadata: { meta: "value" },
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
expect(createEvent.status).toBe(200);
const dbEvent = await prisma.observation.findUnique({
@@ -93,15 +119,22 @@ describe("/api/public/events API Endpoint", () => {
expect(dbEvent?.metadata).toEqual({ meta: "value" });
expect(dbEvent?.version).toBe("2.0.0");
- await makeAPICall("POST", "/api/public/traces", {
- id: traceId,
- name: "trace-name",
- userId: "user-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- metadata: { key: "value" },
- release: "1.0.0",
- version: "2.0.0",
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ id: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
const dbTrace = await prisma.trace.findMany({
where: {
@@ -118,15 +151,22 @@ describe("/api/public/events API Endpoint", () => {
const traceId = uuidv4();
- const response = await makeAPICall("POST", "/api/public/traces", {
- externalId: traceId,
- name: "trace-name",
- userId: "user-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- metadata: { key: "value" },
- release: "1.0.0",
- version: "2.0.0",
- });
+ const response = await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ externalId: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
expect(response.status).toBe(200);
@@ -141,17 +181,24 @@ describe("/api/public/events API Endpoint", () => {
expect(dbTrace[0]?.id).not.toBe(traceId);
const eventId = uuidv4();
- const createEvent = await makeAPICall("POST", "/api/public/events", {
- id: eventId,
- traceIdType: "EXTERNAL",
- traceId: dbTrace[0]?.id,
- name: "event-name",
- startTime: "2021-01-01T00:00:00.000Z",
- input: { input: "value" },
- output: { output: "value" },
- metadata: { meta: "value" },
- version: "2.0.0",
- });
+ const createEvent = await makeZodVerifiedAPICall(
+ PostEventsV1Response,
+ "POST",
+ "/api/public/events",
+ {
+ id: eventId,
+ traceIdType: "EXTERNAL",
+ traceId: dbTrace[0]?.id,
+ name: "event-name",
+ startTime: "2021-01-01T00:00:00.000Z",
+ input: { input: "value" },
+ output: { output: "value" },
+ metadata: { meta: "value" },
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
expect(createEvent.status).toBe(200);
const dbEvent = await prisma.observation.findUnique({
@@ -174,16 +221,23 @@ describe("/api/public/events API Endpoint", () => {
const eventName = uuidv4();
const spanId = uuidv4();
- const createEvent = await makeAPICall("POST", "/api/public/events", {
- id: spanId,
- name: eventName,
- startTime: "2021-01-01T00:00:00.000Z",
- endTime: "2021-01-01T00:00:00.000Z",
- input: { input: "value" },
- output: { output: "value" },
- metadata: { meta: "value" },
- version: "2.0.0",
- });
+ const createEvent = await makeZodVerifiedAPICall(
+ PostEventsV1Response,
+ "POST",
+ "/api/public/events",
+ {
+ id: spanId,
+ name: eventName,
+ startTime: "2021-01-01T00:00:00.000Z",
+ endTime: "2021-01-01T00:00:00.000Z",
+ input: { input: "value" },
+ output: { output: "value" },
+ metadata: { meta: "value" },
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
const dbTrace = await prisma.trace.findMany({
where: {
@@ -215,14 +269,21 @@ describe("/api/public/events API Endpoint", () => {
const generationName = uuidv4();
const spanId = uuidv4();
- const createSpan = await makeAPICall("POST", "/api/public/events", {
- id: spanId,
- name: generationName,
- startTime: "2021-01-01T00:00:00.000Z",
- input: { key: "value" },
- metadata: { key: "value" },
- version: "2.0.0",
- });
+ const createSpan = await makeZodVerifiedAPICall(
+ PostEventsV1Response,
+ "POST",
+ "/api/public/events",
+ {
+ id: spanId,
+ name: generationName,
+ startTime: "2021-01-01T00:00:00.000Z",
+ input: { key: "value" },
+ metadata: { key: "value" },
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
const dbEvent = await prisma.observation.findFirstOrThrow({
where: {
diff --git a/web/src/__tests__/generations.servertest.ts b/web/src/__tests__/generations.servertest.ts
index 895a400f7a..0ced7e7d9d 100644
--- a/web/src/__tests__/generations.servertest.ts
+++ b/web/src/__tests__/generations.servertest.ts
@@ -2,9 +2,19 @@
import { v4 as uuidv4 } from "uuid";
-import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
+import {
+ makeAPICall,
+ makeZodVerifiedAPICall,
+ pruneDatabase,
+} from "@/src/__tests__/test-utils";
import { ModelUsageUnit } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
+import { PostTracesV1Response } from "@/src/features/public-api/types/traces";
+import {
+ PatchGenerationsV1Response,
+ PostGenerationsV1Body,
+ PostGenerationsV1Response,
+} from "@/src/features/public-api/types/generations";
describe("/api/public/generations API Endpoint", () => {
beforeEach(async () => await pruneDatabase());
@@ -90,15 +100,22 @@ describe("/api/public/generations API Endpoint", () => {
const traceId = uuidv4();
- await makeAPICall("POST", "/api/public/traces", {
- id: traceId,
- name: "trace-name",
- userId: "user-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- metadata: { key: "value" },
- release: "1.0.0",
- version: "2.0.0",
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ id: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
const dbTrace = await prisma.trace.findMany({
where: {
@@ -110,7 +127,8 @@ describe("/api/public/generations API Endpoint", () => {
expect(dbTrace[0]?.id).toBe(traceId);
const generationId = uuidv4();
- const createGeneration = await makeAPICall(
+ const createGeneration = await makeZodVerifiedAPICall(
+ PostGenerationsV1Response,
"POST",
"/api/public/generations",
{
@@ -126,6 +144,8 @@ describe("/api/public/generations API Endpoint", () => {
version: "2.0.0",
usage: testConfig.usage,
},
+ undefined,
+ false,
);
expect(createGeneration.status).toBe(200);
@@ -164,7 +184,8 @@ describe("/api/public/generations API Endpoint", () => {
const traceId = uuidv4();
const generationId = uuidv4();
- const createGeneration = await makeAPICall(
+ const createGeneration = await makeZodVerifiedAPICall(
+ PostGenerationsV1Body,
"POST",
"/api/public/generations",
{
@@ -179,6 +200,8 @@ describe("/api/public/generations API Endpoint", () => {
metadata: { key: "value" },
version: "2.0.0",
},
+ undefined,
+ false,
);
expect(createGeneration.status).toBe(200);
@@ -201,15 +224,22 @@ describe("/api/public/generations API Endpoint", () => {
expect(dbGeneration?.metadata).toEqual({ key: "value" });
expect(dbGeneration?.version).toBe("2.0.0");
- await makeAPICall("POST", "/api/public/traces", {
- id: traceId,
- name: "trace-name",
- userId: "user-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- metadata: { key: "value" },
- release: "1.0.0",
- version: "2.0.0",
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ id: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
const dbTrace = await prisma.trace.findMany({
where: {
@@ -224,15 +254,22 @@ describe("/api/public/generations API Endpoint", () => {
it("should create generation after trace ignoring externalId", async () => {
const traceId = uuidv4();
- const response = await makeAPICall("POST", "/api/public/traces", {
- externalId: traceId,
- name: "trace-name",
- userId: "user-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- metadata: { key: "value" },
- release: "1.0.0",
- version: "2.0.0",
- });
+ const response = await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ externalId: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
expect(response.status).toBe(200);
@@ -247,7 +284,8 @@ describe("/api/public/generations API Endpoint", () => {
expect(dbTrace[0]?.id).not.toBe(traceId);
const generationId = uuidv4();
- const createGeneration = await makeAPICall(
+ const createGeneration = await makeZodVerifiedAPICall(
+ PostGenerationsV1Body,
"POST",
"/api/public/generations",
{
@@ -263,6 +301,8 @@ describe("/api/public/generations API Endpoint", () => {
metadata: { key: "value" },
version: "2.0.0",
},
+ undefined,
+ false,
);
expect(createGeneration.status).toBe(200);
@@ -290,7 +330,8 @@ describe("/api/public/generations API Endpoint", () => {
const generationName = uuidv4();
const generationId = uuidv4();
- const createGeneration = await makeAPICall(
+ const createGeneration = await makeZodVerifiedAPICall(
+ PostGenerationsV1Body,
"POST",
"/api/public/generations",
{
@@ -304,6 +345,8 @@ describe("/api/public/generations API Endpoint", () => {
metadata: { key: "value" },
version: "2.0.0",
},
+ undefined,
+ false,
);
const dbTrace = await prisma.trace.findMany({
@@ -340,7 +383,8 @@ describe("/api/public/generations API Endpoint", () => {
const generationName = uuidv4();
const generationId = uuidv4();
- const createGeneration = await makeAPICall(
+ const createGeneration = await makeZodVerifiedAPICall(
+ PostGenerationsV1Body,
"POST",
"/api/public/generations",
{
@@ -354,6 +398,8 @@ describe("/api/public/generations API Endpoint", () => {
metadata: { key: "value" },
version: "2.0.0",
},
+ undefined,
+ false,
);
expect(createGeneration.status).toBe(200);
@@ -368,7 +414,8 @@ describe("/api/public/generations API Endpoint", () => {
const generationId2 = uuidv4();
const generationName2 = uuidv4();
- const createGeneration2 = await makeAPICall(
+ const createGeneration2 = await makeZodVerifiedAPICall(
+ PostGenerationsV1Body,
"POST",
"/api/public/generations",
{
@@ -383,6 +430,8 @@ describe("/api/public/generations API Endpoint", () => {
version: "2.0.0",
parentObservationId: generationId,
},
+ undefined,
+ false,
);
expect(createGeneration2.status).toBe(200);
@@ -401,7 +450,8 @@ describe("/api/public/generations API Endpoint", () => {
const generationId = uuidv4();
const externalTraceId = uuidv4();
- const createGeneration = await makeAPICall(
+ const createGeneration = await makeZodVerifiedAPICall(
+ PostGenerationsV1Body,
"POST",
"/api/public/generations",
{
@@ -417,6 +467,8 @@ describe("/api/public/generations API Endpoint", () => {
metadata: { key: "value" },
version: "2.0.0",
},
+ undefined,
+ false,
);
expect(createGeneration.status).toBe(200);
@@ -437,7 +489,8 @@ describe("/api/public/generations API Endpoint", () => {
const generationName = uuidv4();
const generationId = uuidv4();
- const createGeneration = await makeAPICall(
+ const createGeneration = await makeZodVerifiedAPICall(
+ PostGenerationsV1Body,
"POST",
"/api/public/generations",
{
@@ -451,6 +504,8 @@ describe("/api/public/generations API Endpoint", () => {
metadata: { key: "value" },
version: "2.0.0",
},
+ undefined,
+ false,
);
const dbGeneration = await prisma.observation.findFirstOrThrow({
@@ -488,7 +543,8 @@ describe("/api/public/generations API Endpoint", () => {
const generationName = uuidv4();
const generationId = uuidv4();
- const createGeneration = await makeAPICall(
+ const createGeneration = await makeZodVerifiedAPICall(
+ PostGenerationsV1Body,
"POST",
"/api/public/generations",
{
@@ -502,17 +558,22 @@ describe("/api/public/generations API Endpoint", () => {
metadata: { key: "value" },
version: "2.0.0",
},
+ undefined,
+ false,
);
expect(createGeneration.status).toBe(200);
- const updateGeneration = await makeAPICall(
+ const updateGeneration = await makeZodVerifiedAPICall(
+ PatchGenerationsV1Response,
"PATCH",
"/api/public/generations",
{
generationId: generationId,
completion: "this is a great gpt response",
},
+ undefined,
+ false,
);
expect(updateGeneration.status).toBe(200);
@@ -540,7 +601,8 @@ describe("/api/public/generations API Endpoint", () => {
const generationName = uuidv4();
const generationId = uuidv4();
- const createGeneration = await makeAPICall(
+ const createGeneration = await makeZodVerifiedAPICall(
+ PostGenerationsV1Body,
"POST",
"/api/public/generations",
{
@@ -558,6 +620,8 @@ describe("/api/public/generations API Endpoint", () => {
},
],
},
+ undefined,
+ false,
);
expect(createGeneration.status).toBe(200);
diff --git a/web/src/__tests__/metrics-api.servertest.ts b/web/src/__tests__/metrics-api.servertest.ts
index 4c58bd7512..ec8b522c86 100644
--- a/web/src/__tests__/metrics-api.servertest.ts
+++ b/web/src/__tests__/metrics-api.servertest.ts
@@ -1,4 +1,10 @@
-import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
+import {
+ makeZodVerifiedAPICall,
+ pruneDatabase,
+} from "@/src/__tests__/test-utils";
+import { PostGenerationsV1Response } from "@/src/features/public-api/types/generations";
+import { GetMetricsDailyV1Response } from "@/src/features/public-api/types/metrics";
+import { PostTracesV1Response } from "@/src/features/public-api/types/traces";
import { v4 as uuidv4 } from "uuid";
describe("/api/public/metrics/daily API Endpoint", () => {
@@ -6,53 +12,101 @@ describe("/api/public/metrics/daily API Endpoint", () => {
afterEach(async () => await pruneDatabase());
it("should handle daily metrics correctly", async () => {
- await pruneDatabase();
-
// Create traces with observations on different days
const traceId1 = uuidv4();
const traceId2 = uuidv4();
- await makeAPICall("POST", "/api/public/traces", {
- id: traceId1,
- timestamp: "2021-01-01T00:00:00.000Z",
- name: "trace-day-1",
- userId: "user-daily-metrics",
- projectId: "project-daily-metrics",
- });
- await makeAPICall("POST", "/api/public/traces", {
- id: traceId2,
- timestamp: "2021-01-02T00:00:00.000Z",
- name: "trace-day-2",
- userId: "user-daily-metrics",
- projectId: "project-daily-metrics",
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ id: traceId1,
+ timestamp: "2021-01-01T00:00:00.000Z",
+ name: "trace-day-1",
+ userId: "user-daily-metrics",
+ projectId: "project-daily-metrics",
+ },
+ undefined,
+ false,
+ );
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ id: traceId2,
+ timestamp: "2021-01-02T00:00:00.000Z",
+ name: "trace-day-2",
+ userId: "user-daily-metrics",
+ projectId: "project-daily-metrics",
+ },
+ undefined,
+ false,
+ );
// Simulate observations with usage metrics on different days
- await makeAPICall("POST", "/api/public/generations", {
- traceId: traceId1,
- model: "modelA",
- usage: { input: 100, output: 200, total: 300 },
- startTime: "2021-01-01T00:00:00.000Z",
- endTime: "2021-01-01T00:01:00.000Z",
- });
- await makeAPICall("POST", "/api/public/generations", {
- traceId: traceId2,
- model: "modelB",
- usage: { input: 333 },
- startTime: "2021-01-02T00:00:00.000Z",
- endTime: "2021-01-02T00:02:00.000Z",
- });
- await makeAPICall("POST", "/api/public/generations", {
- traceId: traceId2,
- model: "modelC",
- usage: { input: 666, output: 777, totalCost: 1024.22 },
- startTime: "2021-01-02T00:00:00.000Z",
- endTime: "2021-01-02T00:04:00.000Z",
- });
+ await makeZodVerifiedAPICall(
+ PostGenerationsV1Response,
+ "POST",
+ "/api/public/generations",
+ {
+ traceId: traceId1,
+ model: "modelA",
+ usage: { input: 100, output: 200, total: 300 },
+ startTime: "2021-01-01T00:00:00.000Z",
+ endTime: "2021-01-01T00:01:00.000Z",
+ },
+ undefined,
+ false,
+ );
+ await makeZodVerifiedAPICall(
+ PostGenerationsV1Response,
+ "POST",
+ "/api/public/generations",
+ {
+ traceId: traceId2,
+ model: "modelB",
+ usage: { input: 333 },
+ startTime: "2021-01-02T00:00:00.000Z",
+ endTime: "2021-01-02T00:02:00.000Z",
+ },
+ undefined,
+ false,
+ );
+ await makeZodVerifiedAPICall(
+ PostGenerationsV1Response,
+ "POST",
+ "/api/public/generations",
+ {
+ traceId: traceId2,
+ model: "modelC",
+ usage: { input: 666, output: 777, totalCost: 1024.22 },
+ startTime: "2021-01-02T00:00:00.000Z",
+ endTime: "2021-01-02T00:04:00.000Z",
+ },
+ undefined,
+ false,
+ );
+ await makeZodVerifiedAPICall(
+ PostGenerationsV1Response,
+ "POST",
+ "/api/public/generations",
+ {
+ traceId: traceId2,
+ usage: { output: 300 },
+ startTime: "2021-01-02T00:00:00.000Z",
+ endTime: "2021-01-02T00:04:00.000Z",
+ },
+ undefined,
+ false,
+ );
// Retrieve the daily metrics
- const dailyMetricsResponse = await makeAPICall<{
- data: Array<Record<string, unknown>>;
- }>("GET", `/api/public/metrics/daily`);
+ const dailyMetricsResponse = await makeZodVerifiedAPICall(
+ GetMetricsDailyV1Response,
+ "GET",
+ `/api/public/metrics/daily`,
+ );
const dailyMetricsData = dailyMetricsResponse.body.data;
// Check if the daily metrics are calculated correctly
@@ -81,6 +135,15 @@ describe("/api/public/metrics/daily API Endpoint", () => {
countTraces: 1,
totalCost: 1024.22,
},
+ {
+ model: null,
+ countObservations: 1,
+ countTraces: 1,
+ inputUsage: 0,
+ outputUsage: 300,
+ totalCost: 0,
+ totalUsage: 300,
+ },
]);
if (!dailyMetricsData[1])
@@ -100,4 +163,50 @@ describe("/api/public/metrics/daily API Endpoint", () => {
},
]);
});
+
+ it("should handle daily metrics correctly when there is no data", async () => {
+ // Retrieve the daily metrics
+ const dailyMetricsResponse = await makeZodVerifiedAPICall(
+ GetMetricsDailyV1Response,
+ "GET",
+ `/api/public/metrics/daily`,
+ );
+ const dailyMetricsData = dailyMetricsResponse.body.data;
+
+ // Check if the daily metrics are calculated correctly
+ expect(dailyMetricsData).toHaveLength(0); // No data
+ });
+
+ it("should handle daily metrics correctly when there is just a trace", async () => {
+ const traceId1 = uuidv4();
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ id: traceId1,
+ timestamp: "2021-01-01T00:00:00.000Z",
+ name: "trace-day-1",
+ userId: "user-daily-metrics",
+ projectId: "project-daily-metrics",
+ },
+ undefined,
+ false,
+ );
+
+ // Retrieve the daily metrics
+ const dailyMetricsResponse = await makeZodVerifiedAPICall(
+ GetMetricsDailyV1Response,
+ "GET",
+ `/api/public/metrics/daily`,
+ );
+ const dailyMetricsData = dailyMetricsResponse.body.data;
+
+ // Check if the daily metrics are calculated correctly
+ expect(dailyMetricsData).toHaveLength(1);
+ expect(dailyMetricsData[0].date).toBe("2021-01-01");
+ expect(dailyMetricsData[0].countTraces).toBe(1);
+ expect(dailyMetricsData[0].totalCost).toEqual(0);
+ expect(dailyMetricsData[0].usage).toEqual([]);
+ });
});
diff --git a/web/src/__tests__/observations.servertest.ts b/web/src/__tests__/observations.servertest.ts
index 513f15de5b..39ce023ad9 100644
--- a/web/src/__tests__/observations.servertest.ts
+++ b/web/src/__tests__/observations.servertest.ts
@@ -2,10 +2,16 @@
import { v4 as uuidv4 } from "uuid";
-import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
+import {
+ makeZodVerifiedAPICall,
+ pruneDatabase,
+} from "@/src/__tests__/test-utils";
import { ModelUsageUnit } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
-import { type ObservationView } from "@langfuse/shared";
+import {
+ GetObservationV1Response,
+ GetObservationsV1Response,
+} from "@/src/features/public-api/types/observations";
describe("/api/public/observations API Endpoint", () => {
beforeEach(async () => await pruneDatabase());
@@ -79,7 +85,8 @@ describe("/api/public/observations API Endpoint", () => {
},
});
- const fetchedObservations = await makeAPICall(
+ const fetchedObservations = await makeZodVerifiedAPICall(
+ GetObservationsV1Response,
"GET",
"/api/public/observations",
undefined,
@@ -87,13 +94,6 @@ describe("/api/public/observations API Endpoint", () => {
expect(fetchedObservations.status).toBe(200);
- if (!isObservationList(fetchedObservations.body)) {
- throw new Error(
- "Expected body to be an array of observations" +
- JSON.stringify(fetchedObservations.body),
- );
- }
-
expect(fetchedObservations.body.data.length).toBe(1);
expect(fetchedObservations.body.data[0]?.traceId).toBe(traceId);
expect(fetchedObservations.body.data[0]?.input).toEqual({ key: "input" });
@@ -183,7 +183,8 @@ describe("/api/public/observations API Endpoint", () => {
},
});
- const fetchedObservations = await makeAPICall(
+ const fetchedObservations = await makeZodVerifiedAPICall(
+ GetObservationsV1Response,
"GET",
"/api/public/observations?type=GENERATION",
undefined,
@@ -193,10 +194,6 @@ describe("/api/public/observations API Endpoint", () => {
expect(fetchedObservations.status).toBe(200);
- if (!isObservationList(fetchedObservations.body)) {
- throw new Error("Expected body to be an array of observations");
- }
-
expect(fetchedObservations.body.data.length).toBe(1);
expect(fetchedObservations.body.data[0]?.traceId).toBe(traceId);
expect(fetchedObservations.body.data[0]?.input).toEqual({ key: "input" });
@@ -205,37 +202,236 @@ describe("/api/public/observations API Endpoint", () => {
});
});
-const isObservationList = (val: unknown): val is ObservationResponse => {
- return (
- typeof val === "object" &&
- val !== null &&
- "data" in val &&
- Array.isArray(val.data) &&
- val.data.every(
- (element) =>
- typeof element === "object" &&
- element !== null &&
- "id" in element &&
- "traceId" in element &&
- "name" in element &&
- "startTime" in element &&
- "endTime" in element &&
- "model" in element &&
- "input" in element &&
- "output" in element &&
- "metadata" in element &&
- "version" in element &&
- "modelId" in element &&
- "inputPrice" in element &&
- "outputPrice" in element &&
- "totalPrice" in element &&
- "calculatedInputCost" in element &&
- "calculatedOutputCost" in element &&
- "calculatedTotalCost" in element,
- )
+it("GET /observations with timestamp filters and pagination", async () => {
+ await prisma.trace.create({
+ data: {
+ id: "trace-id",
+ name: "trace-name",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ },
+ });
+ await prisma.observation.createMany({
+ data: [
+ {
+ id: "observation-2021-01-01",
+ traceId: "trace-id",
+ name: "generation-name",
+ startTime: new Date("2021-01-01T00:00:00.000Z"),
+ endTime: new Date("2021-01-01T00:00:00.000Z"),
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ type: "GENERATION",
+ },
+ {
+ id: "observation-2021-02-01",
+ traceId: "trace-id",
+ name: "generation-name",
+ startTime: new Date("2021-02-01T00:00:00.000Z"),
+ endTime: new Date("2021-02-01T00:00:00.000Z"),
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ type: "SPAN",
+ },
+ {
+ id: "observation-2021-03-01",
+ traceId: "trace-id",
+ name: "generation-name",
+ startTime: new Date("2021-03-01T00:00:00.000Z"),
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ type: "EVENT",
+ },
+ {
+ id: "observation-2021-04-01",
+ traceId: "trace-id",
+ name: "generation-name",
+ startTime: new Date("2021-04-01T00:00:00.000Z"),
+ endTime: new Date("2021-04-01T00:00:00.000Z"),
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ type: "GENERATION",
+ },
+ ],
+ });
+
+ 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?fromStartTime=${fromTimestamp}&toStartTime=${toTimestamp}`,
+ undefined,
+ );
+
+ 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}`,
+ 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}`,
+ 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);
+
+ // test pagination only
+ fetchedObservations = await makeZodVerifiedAPICall(
+ GetObservationsV1Response,
+ "GET",
+ `/api/public/observations?limit=1&page=2`,
+ 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,
+ });
+});
+
+it("Get a single EVENT from /observations/:id", async () => {
+ const traceId = uuidv4();
+ await prisma.trace.create({
+ data: {
+ id: traceId,
+ name: "trace-name",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ },
+ });
+
+ // EVENT
+ const eventId = uuidv4();
+ await prisma.observation.create({
+ data: {
+ id: eventId,
+ traceId: traceId,
+ name: "generation-name",
+ startTime: new Date("2021-01-01T00:00:00.000Z"),
+ type: "EVENT",
+ project: {
+ connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },
+ },
+ },
+ });
+ const getEventRes = await makeZodVerifiedAPICall(
+ GetObservationV1Response,
+ "GET",
+ "/api/public/observations/" + eventId,
+ );
+ expect(getEventRes.body).toMatchObject({
+ id: eventId,
+ traceId: traceId,
+ type: "EVENT",
+ });
+});
+it("Get a single GENERATION from /observations/:id", async () => {
+ const traceId = uuidv4();
+ await prisma.trace.create({
+ data: {
+ id: traceId,
+ name: "trace-name",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ },
+ });
+
+ const generationId = uuidv4();
+ await prisma.observation.create({
+ data: {
+ id: generationId,
+ traceId: traceId,
+ name: "generation-name",
+ startTime: new Date("2021-01-01T00:00:00.000Z"),
+ endTime: new Date("2021-01-01T00:00:00.000Z"),
+ model: "gpt-3.5-turbo",
+ internalModel: "gpt-3.5-turbo",
+ modelParameters: { key: "value" },
+ input: { key: "input" },
+ output: { key: "output" },
+ promptTokens: 10,
+ completionTokens: 20,
+ totalTokens: 30,
+ version: "2.0.0",
+ unit: ModelUsageUnit.Tokens,
+ type: "GENERATION",
+ project: {
+ connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },
+ },
+ },
+ });
+ const getGenerationRes = await makeZodVerifiedAPICall(
+ GetObservationV1Response,
+ "GET",
+ "/api/public/observations/" + generationId,
);
-};
+ expect(getGenerationRes.body).toMatchObject({
+ id: generationId,
+ traceId: traceId,
+ input: { key: "input" },
+ output: { key: "output" },
+ type: "GENERATION",
+ });
+});
+it("Get a single SPAN from /observations/:id", async () => {
+ const traceId = uuidv4();
+ await prisma.trace.create({
+ data: {
+ id: traceId,
+ name: "trace-name",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ },
+ });
-type ObservationResponse = {
- data: ObservationView[];
-};
+ const spanId = uuidv4();
+ await prisma.observation.create({
+ data: {
+ id: spanId,
+ traceId: traceId,
+ name: "generation-name",
+ startTime: new Date("2021-01-01T00:00:00.000Z"),
+ endTime: new Date("2021-01-01T00:00:00.000Z"),
+ modelParameters: { key: "value" },
+ input: { key: "input" },
+ output: { key: "output" },
+ version: "2.0.0",
+ type: "SPAN",
+ project: {
+ connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },
+ },
+ },
+ });
+ const getSpanRes = await makeZodVerifiedAPICall(
+ GetObservationV1Response,
+ "GET",
+ "/api/public/observations/" + spanId,
+ );
+ expect(getSpanRes.body).toMatchObject({
+ id: spanId,
+ traceId: traceId,
+ input: { key: "input" },
+ output: { key: "output" },
+ type: "SPAN",
+ });
+});
diff --git a/web/src/__tests__/scores.servertest.ts b/web/src/__tests__/scores.servertest.ts
index fb095c4a39..2384e34fce 100644
--- a/web/src/__tests__/scores.servertest.ts
+++ b/web/src/__tests__/scores.servertest.ts
@@ -13,6 +13,7 @@ import {
GetScoresResponse,
} from "@/src/features/public-api/types/scores";
import { z } from "zod";
+import { PostTracesV1Response } from "@/src/features/public-api/types/traces";
const traceId = "de98afa2-89dc-47e9-9924-33f1490fdaf4";
@@ -21,15 +22,22 @@ describe("/api/public/scores API Endpoint", () => {
beforeEach(async () => {
if (should_prune_db) await pruneDatabase();
- await makeAPICall("POST", "/api/public/traces", {
- id: traceId,
- name: "trace-name",
- userId: "user-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- metadata: { key: "value" },
- release: "1.0.0",
- version: "2.0.0",
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ id: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
});
afterEach(async () => {
if (should_prune_db) await pruneDatabase();
@@ -143,17 +151,24 @@ describe("/api/public/scores API Endpoint", () => {
const generationId = uuidv4();
- await makeAPICall("POST", "/api/public/generations", {
- id: generationId,
- name: "generation-name",
- startTime: "2021-01-01T00:00:00.000Z",
- endTime: "2021-01-01T00:00:00.000Z",
- model: "model-name",
- modelParameters: { key: "value" },
- prompt: { key: "value" },
- metadata: { key: "value" },
- version: "2.0.0",
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/generations",
+ {
+ id: generationId,
+ name: "generation-name",
+ startTime: "2021-01-01T00:00:00.000Z",
+ endTime: "2021-01-01T00:00:00.000Z",
+ model: "model-name",
+ modelParameters: { key: "value" },
+ prompt: { key: "value" },
+ metadata: { key: "value" },
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
const dbGeneration = await prisma.observation.findMany({
where: {
@@ -432,10 +447,8 @@ describe("/api/public/scores API Endpoint", () => {
expect(createScore.status).toBe(400);
expect(createScore.body).toMatchObject({
- message: "Invalid request data",
- errors: [
+ message:
"Data type mismatch based on config: expected NUMERIC, got CATEGORICAL",
- ],
});
});
@@ -484,10 +497,8 @@ describe("/api/public/scores API Endpoint", () => {
expect(createScore.status).toBe(400);
expect(createScore.body).toMatchObject({
- message: "Invalid request data",
- errors: [
+ message:
"Data type mismatch based on config: expected CATEGORICAL, got NUMERIC",
- ],
});
});
@@ -697,10 +708,8 @@ describe("/api/public/scores API Endpoint", () => {
expect(createScore.status).toBe(400);
expect(createScore.body).toMatchObject({
- message: "Invalid request data",
- errors: [
+ message:
"Ingested score body not valid against provided config: - Value exceeds maximum value of 0 defined in config",
- ],
});
});
@@ -715,18 +724,25 @@ describe("/api/public/scores API Endpoint", () => {
expect(dbTrace[0]?.id).toBe(traceId);
const generationId = uuidv4();
- await makeAPICall("POST", "/api/public/generations", {
- id: generationId,
- name: "generation-name",
- traceId,
- startTime: "2021-01-01T00:00:00.000Z",
- endTime: "2021-01-01T00:00:00.000Z",
- model: "model-name",
- modelParameters: { key: "value" },
- prompt: { key: "value" },
- metadata: { key: "value" },
- version: "2.0.0",
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/generations",
+ {
+ id: generationId,
+ name: "generation-name",
+ traceId,
+ startTime: "2021-01-01T00:00:00.000Z",
+ endTime: "2021-01-01T00:00:00.000Z",
+ model: "model-name",
+ modelParameters: { key: "value" },
+ prompt: { key: "value" },
+ metadata: { key: "value" },
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
const dbGeneration = await prisma.observation.findMany({
where: {
@@ -776,9 +792,16 @@ describe("/api/public/scores API Endpoint", () => {
const traceId = uuidv4();
- await makeAPICall("POST", "/api/public/traces", {
- id: traceId,
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ id: traceId,
+ },
+ undefined,
+ false,
+ );
const scoreId = uuidv4();
const createScore = await makeAPICall("POST", "/api/public/scores", {
@@ -816,13 +839,27 @@ describe("/api/public/scores API Endpoint", () => {
const traceId = uuidv4();
- await makeAPICall("POST", "/api/public/traces", {
- id: traceId,
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ id: traceId,
+ },
+ undefined,
+ false,
+ );
const generationId = uuidv4();
- await makeAPICall("POST", "/api/public/generations", {
- id: generationId,
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/generations",
+ {
+ id: generationId,
+ },
+ undefined,
+ false,
+ );
const scoreId = uuidv4();
await makeAPICall("POST", "/api/public/scores", {
@@ -868,13 +905,27 @@ describe("/api/public/scores API Endpoint", () => {
should_prune_db = false;
await pruneDatabase();
- await makeAPICall("POST", "/api/public/traces", {
- id: traceId,
- userId: userId,
- });
- await makeAPICall("POST", "/api/public/generations", {
- id: generationId,
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ id: traceId,
+ userId: userId,
+ },
+ undefined,
+ false,
+ );
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/generations",
+ {
+ id: generationId,
+ },
+ undefined,
+ false,
+ );
await makeAPICall("POST", "/api/public/score-configs", {
name: scoreName,
diff --git a/web/src/__tests__/sessions.servertest.ts b/web/src/__tests__/sessions.servertest.ts
index d36d175696..8c0349cdaa 100644
--- a/web/src/__tests__/sessions.servertest.ts
+++ b/web/src/__tests__/sessions.servertest.ts
@@ -1,20 +1,35 @@
/** @jest-environment node */
-import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
+import {
+ makeZodVerifiedAPICall,
+ pruneDatabase,
+} from "@/src/__tests__/test-utils";
+import {
+ GetSessionV1Response,
+ GetSessionsV1Response,
+} from "@/src/features/public-api/types/sessions";
+import { PostTracesV1Response } from "@/src/features/public-api/types/traces";
import { prisma } from "@langfuse/shared/src/db";
-describe("/api/public/traces API Endpoint", () => {
+describe("Create and get sessions", () => {
beforeEach(async () => await pruneDatabase());
afterEach(async () => await pruneDatabase());
it("should create a session via a trace", async () => {
await pruneDatabase();
- await makeAPICall("POST", "/api/public/traces", {
- name: "trace-name",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- sessionId: "session-id",
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ name: "trace-name",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ sessionId: "session-id",
+ },
+ undefined,
+ false,
+ );
const dbSession = await prisma.traceSession.findFirst({
where: {
@@ -32,16 +47,24 @@ describe("/api/public/traces API Endpoint", () => {
it("should get session including traces", async () => {
await pruneDatabase();
- await makeAPICall("POST", "/api/public/traces", {
- name: "trace-name",
- id: "trace-id",
- input: { hello: "world" },
- output: "hi",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- sessionId: "session-id",
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ name: "trace-name",
+ id: "trace-id",
+ input: { hello: "world" },
+ output: "hi",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ sessionId: "session-id",
+ },
+ undefined,
+ false,
+ );
- const response = await makeAPICall(
+ const response = await makeZodVerifiedAPICall(
+ GetSessionV1Response,
"GET",
"/api/public/sessions/session-id",
);
@@ -60,3 +83,122 @@ describe("/api/public/traces API Endpoint", () => {
});
});
});
+
+describe("GET /api/public/sessions API Endpoint", () => {
+ beforeEach(async () => {
+ await pruneDatabase();
+ await prisma.traceSession.createMany({
+ data: [
+ {
+ id: "session-2021-01-01",
+ createdAt: new Date("2021-01-01T00:00:00Z"),
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ },
+ {
+ id: "session-2021-02-01",
+ createdAt: new Date("2021-02-01T00:00:00Z"),
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ },
+ {
+ id: "session-2021-03-01",
+ createdAt: new Date("2021-03-01T00:00:00Z"),
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ },
+ {
+ id: "session-2021-04-01",
+ createdAt: new Date("2021-04-01T00:00:00Z"),
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ },
+ {
+ id: "session-2021-05-01",
+ createdAt: new Date("2021-05-01T00:00:00Z"),
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ },
+ ],
+ });
+ });
+ afterEach(async () => await pruneDatabase());
+
+ it("should return all sessions", async () => {
+ const sessions = await makeZodVerifiedAPICall(
+ GetSessionsV1Response,
+ "GET",
+ "/api/public/sessions",
+ );
+ expect(sessions.body.data).toHaveLength(5);
+ });
+
+ it("should return paginated sessions with limit and page number", async () => {
+ const limit = 2;
+ const page = 2;
+
+ const sessions = await makeZodVerifiedAPICall(
+ GetSessionsV1Response,
+ "GET",
+ `/api/public/sessions?limit=${limit}&page=${page}`,
+ );
+
+ expect(sessions.body.data).toHaveLength(2);
+ expect(sessions.body.data.map((session) => session.id)).toEqual([
+ "session-2021-03-01",
+ "session-2021-02-01",
+ ]);
+ expect(sessions.body.meta.totalItems).toBe(5);
+ expect(sessions.body.meta.totalPages).toBe(3);
+ expect(sessions.body.meta.page).toBe(page);
+ expect(sessions.body.meta.limit).toBe(limit);
+ });
+
+ it("should return sessions within a specific date range", async () => {
+ const fromTimestamp = "2021-02-01T00:00:00Z";
+ const toTimestamp = "2021-04-01T00:00:00Z";
+
+ const sessions = await makeZodVerifiedAPICall(
+ GetSessionsV1Response,
+ "GET",
+ `/api/public/sessions?fromTimestamp=${fromTimestamp}&toTimestamp=${toTimestamp}`,
+ );
+
+ expect(sessions.body.data).toHaveLength(2);
+ expect(sessions.body.data.map((session) => session.id)).toEqual([
+ "session-2021-03-01",
+ "session-2021-02-01",
+ ]);
+ expect(sessions.body.meta.totalItems).toBe(2);
+ });
+
+ it("should return sessions from a specific date onwards (including the date)", async () => {
+ const fromTimestamp = "2021-03-01T00:00:00Z";
+
+ const sessions = await makeZodVerifiedAPICall(
+ GetSessionsV1Response,
+ "GET",
+ `/api/public/sessions?fromTimestamp=${fromTimestamp}`,
+ );
+
+ expect(sessions.body.data).toHaveLength(3);
+ expect(sessions.body.data.map((session) => session.id)).toEqual([
+ "session-2021-05-01",
+ "session-2021-04-01",
+ "session-2021-03-01",
+ ]);
+ expect(sessions.body.meta.totalItems).toBe(3);
+ });
+
+ it("should return sessions up to a specific date (excluding it)", async () => {
+ const toTimestamp = "2021-03-01T00:00:00Z";
+
+ const sessions = await makeZodVerifiedAPICall(
+ GetSessionsV1Response,
+ "GET",
+ `/api/public/sessions?toTimestamp=${toTimestamp}`,
+ );
+
+ expect(sessions.body.data).toHaveLength(2);
+ expect(sessions.body.data.map((session) => session.id)).toEqual([
+ "session-2021-02-01",
+ "session-2021-01-01",
+ ]);
+ expect(sessions.body.meta.totalItems).toBe(2);
+ });
+});
diff --git a/web/src/__tests__/spans.servertest.ts b/web/src/__tests__/spans.servertest.ts
index e5d5bb6a23..afedac900b 100644
--- a/web/src/__tests__/spans.servertest.ts
+++ b/web/src/__tests__/spans.servertest.ts
@@ -1,27 +1,41 @@
/** @jest-environment node */
import { prisma } from "@langfuse/shared/src/db";
-import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
+import {
+ makeAPICall,
+ makeZodVerifiedAPICall,
+ pruneDatabase,
+} from "@/src/__tests__/test-utils";
import { v4 as uuidv4 } from "uuid";
+import { PostTracesV1Response } from "@/src/features/public-api/types/traces";
+import {
+ PatchSpansV1Response,
+ PostSpansV1Response,
+} from "@/src/features/public-api/types/spans";
describe("/api/public/spans API Endpoint", () => {
beforeEach(async () => await pruneDatabase());
afterEach(async () => await pruneDatabase());
it("should create span after trace", async () => {
- await pruneDatabase();
-
const traceId = uuidv4();
- await makeAPICall("POST", "/api/public/traces", {
- id: traceId,
- name: "trace-name",
- userId: "user-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- metadata: { key: "value" },
- release: "1.0.0",
- version: "2.0.0",
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ id: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
const dbTrace = await prisma.trace.findMany({
where: {
@@ -33,16 +47,23 @@ describe("/api/public/spans API Endpoint", () => {
expect(dbTrace[0]?.id).toBe(traceId);
const spanId = uuidv4();
- const createSpan = await makeAPICall("POST", "/api/public/spans", {
- id: spanId,
- traceId: traceId,
- name: "span-name",
- startTime: "2021-01-01T00:00:00.000Z",
- endTime: "2021-01-01T00:00:00.000Z",
- input: { input: "value" },
- metadata: { meta: "value" },
- version: "2.0.0",
- });
+ const createSpan = await makeZodVerifiedAPICall(
+ PostSpansV1Response,
+ "POST",
+ "/api/public/spans",
+ {
+ id: spanId,
+ traceId: traceId,
+ name: "span-name",
+ startTime: "2021-01-01T00:00:00.000Z",
+ endTime: "2021-01-01T00:00:00.000Z",
+ input: { input: "value" },
+ metadata: { meta: "value" },
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
expect(createSpan.status).toBe(200);
const dbSpan = await prisma.observation.findUnique({
@@ -62,21 +83,26 @@ describe("/api/public/spans API Endpoint", () => {
});
it("should create span before trace", async () => {
- await pruneDatabase();
-
const traceId = uuidv4();
const spanId = uuidv4();
- const createSpan = await makeAPICall("POST", "/api/public/spans", {
- id: spanId,
- traceId: traceId,
- name: "span-name",
- startTime: "2021-01-01T00:00:00.000Z",
- endTime: "2021-01-01T00:00:00.000Z",
- input: { input: "value" },
- metadata: { meta: "value" },
- version: "2.0.0",
- });
+ const createSpan = await makeZodVerifiedAPICall(
+ PostSpansV1Response,
+ "POST",
+ "/api/public/spans",
+ {
+ id: spanId,
+ traceId: traceId,
+ name: "span-name",
+ startTime: "2021-01-01T00:00:00.000Z",
+ endTime: "2021-01-01T00:00:00.000Z",
+ input: { input: "value" },
+ metadata: { meta: "value" },
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
expect(createSpan.status).toBe(200);
const dbSpan = await prisma.observation.findUnique({
@@ -94,15 +120,22 @@ describe("/api/public/spans API Endpoint", () => {
expect(dbSpan?.metadata).toEqual({ meta: "value" });
expect(dbSpan?.version).toBe("2.0.0");
- await makeAPICall("POST", "/api/public/traces", {
- id: traceId,
- name: "trace-name",
- userId: "user-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- metadata: { key: "value" },
- release: "1.0.0",
- version: "2.0.0",
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ id: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
const dbTrace = await prisma.trace.findMany({
where: {
@@ -118,21 +151,35 @@ describe("/api/public/spans API Endpoint", () => {
const traceId = uuidv4();
const spanId = uuidv4();
- const response = await makeAPICall("POST", "/api/public/traces", {
- externalId: uuidv4(),
- id: traceId,
- name: "trace-name",
- userId: "user-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- });
+ const response = await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ externalId: uuidv4(),
+ id: traceId,
+ name: "trace-name",
+ userId: "user-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ },
+ undefined,
+ false,
+ );
expect(response.status).toBe(200);
- const createSpan = await makeAPICall("POST", "/api/public/spans", {
- id: spanId,
- name: "spanName",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- traceId: traceId,
- externalTraceIdType: "EXTERNAL",
- });
+ const createSpan = await makeZodVerifiedAPICall(
+ PostSpansV1Response,
+ "POST",
+ "/api/public/spans",
+ {
+ id: spanId,
+ name: "spanName",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ traceId: traceId,
+ externalTraceIdType: "EXTERNAL",
+ },
+ undefined,
+ false,
+ );
expect(createSpan.status).toBe(200);
const dbSpan = await prisma.observation.findFirstOrThrow({
@@ -148,15 +195,22 @@ describe("/api/public/spans API Endpoint", () => {
const spanName = uuidv4();
const spanId = uuidv4();
- const createSpan = await makeAPICall("POST", "/api/public/spans", {
- id: spanId,
- name: spanName,
- startTime: "2021-01-01T00:00:00.000Z",
- endTime: "2021-01-01T00:00:00.000Z",
- input: { input: "value" },
- metadata: { meta: "value" },
- version: "2.0.0",
- });
+ const createSpan = await makeZodVerifiedAPICall(
+ PostSpansV1Response,
+ "POST",
+ "/api/public/spans",
+ {
+ id: spanId,
+ name: spanName,
+ startTime: "2021-01-01T00:00:00.000Z",
+ endTime: "2021-01-01T00:00:00.000Z",
+ input: { input: "value" },
+ metadata: { meta: "value" },
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
const dbTrace = await prisma.trace.findMany({
where: {
@@ -189,17 +243,24 @@ describe("/api/public/spans API Endpoint", () => {
const spanId = uuidv4();
const traceId = uuidv4();
- const createSpan = await makeAPICall("POST", "/api/public/spans", {
- id: spanId,
- traceIdType: "EXTERNAL",
- traceId: traceId,
- name: spanName,
- startTime: "2021-01-01T00:00:00.000Z",
- endTime: "2021-01-01T00:00:00.000Z",
- input: { input: "value" },
- metadata: { meta: "value" },
- version: "2.0.0",
- });
+ const createSpan = await makeZodVerifiedAPICall(
+ PostSpansV1Response,
+ "POST",
+ "/api/public/spans",
+ {
+ id: spanId,
+ traceIdType: "EXTERNAL",
+ traceId: traceId,
+ name: spanName,
+ startTime: "2021-01-01T00:00:00.000Z",
+ endTime: "2021-01-01T00:00:00.000Z",
+ input: { input: "value" },
+ metadata: { meta: "value" },
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
expect(createSpan.status).toBe(200);
@@ -221,15 +282,22 @@ describe("/api/public/spans API Endpoint", () => {
const generationName = uuidv4();
const spanId = uuidv4();
- const createSpan = await makeAPICall("POST", "/api/public/spans", {
- id: spanId,
- name: generationName,
- startTime: "2021-01-01T00:00:00.000Z",
- endTime: "2021-01-01T00:00:00.000Z",
- input: { key: "value" },
- metadata: { key: "value" },
- version: "2.0.0",
- });
+ const createSpan = await makeZodVerifiedAPICall(
+ PostSpansV1Response,
+ "POST",
+ "/api/public/spans",
+ {
+ id: spanId,
+ name: generationName,
+ startTime: "2021-01-01T00:00:00.000Z",
+ endTime: "2021-01-01T00:00:00.000Z",
+ input: { key: "value" },
+ metadata: { key: "value" },
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
const dbSpan = await prisma.observation.findFirstOrThrow({
where: {
@@ -262,22 +330,36 @@ describe("/api/public/spans API Endpoint", () => {
const spanName = uuidv4();
const spanId = uuidv4();
- const createSpan = await makeAPICall("POST", "/api/public/spans", {
- id: spanId,
- name: spanName,
- startTime: "2021-01-01T00:00:00.000Z",
- endTime: "2021-01-01T00:00:00.000Z",
- input: { input: "value" },
- metadata: { meta: "value" },
- version: "2.0.0",
- });
+ const createSpan = await makeZodVerifiedAPICall(
+ PostSpansV1Response,
+ "POST",
+ "/api/public/spans",
+ {
+ id: spanId,
+ name: spanName,
+ startTime: "2021-01-01T00:00:00.000Z",
+ endTime: "2021-01-01T00:00:00.000Z",
+ input: { input: "value" },
+ metadata: { meta: "value" },
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
expect(createSpan.status).toBe(200);
- const updatedSpan = await makeAPICall("PATCH", "/api/public/spans", {
- spanId: spanId,
- output: { key: "this is a great gpt output" },
- });
+ const updatedSpan = await makeZodVerifiedAPICall(
+ PatchSpansV1Response,
+ "PATCH",
+ "/api/public/spans",
+ {
+ spanId: spanId,
+ output: { key: "this is a great gpt output" },
+ },
+ undefined,
+ false,
+ );
expect(updatedSpan.status).toBe(200);
const dbSpan = await prisma.observation.findUnique({
diff --git a/web/src/__tests__/test-utils.ts b/web/src/__tests__/test-utils.ts
index 46814b8dbd..4467fe6042 100644
--- a/web/src/__tests__/test-utils.ts
+++ b/web/src/__tests__/test-utils.ts
@@ -14,6 +14,7 @@ export const pruneDatabase = async () => {
await prisma.scoreConfig.deleteMany();
await prisma.observation.deleteMany();
await prisma.trace.deleteMany();
+ await prisma.traceSession.deleteMany();
await prisma.datasetItem.deleteMany();
await prisma.dataset.deleteMany();
await prisma.datasetRuns.deleteMany();
@@ -80,6 +81,7 @@ export async function makeZodVerifiedAPICall<T extends z.ZodTypeAny>(
url: string,
body?: unknown,
auth?: string,
+ strictTypeCheck: boolean = true,
): Promise<{ body: z.infer<T>; status: number }> {
const { body: resBody, status } = await makeAPICall(method, url, body, auth);
if (status !== 200) {
@@ -88,7 +90,7 @@ export async function makeZodVerifiedAPICall<T extends z.ZodTypeAny>(
);
}
try {
- if (responseZodSchema instanceof ZodObject) {
+ if (responseZodSchema instanceof ZodObject && strictTypeCheck) {
responseZodSchema.strict().parse(resBody);
} else {
responseZodSchema.parse(resBody);
diff --git a/web/src/__tests__/traces.servertest.ts b/web/src/__tests__/traces.servertest.ts
index 738f58637a..a258092513 100644
--- a/web/src/__tests__/traces.servertest.ts
+++ b/web/src/__tests__/traces.servertest.ts
@@ -1,58 +1,74 @@
/** @jest-environment node */
-import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
+import {
+ makeZodVerifiedAPICall,
+ pruneDatabase,
+} from "@/src/__tests__/test-utils";
+import { PostGenerationsV1Response } from "@/src/features/public-api/types/generations";
+import { PostScoresResponse } from "@/src/features/public-api/types/scores";
+import {
+ GetTraceV1Response,
+ GetTracesV1Response,
+ PostTracesV1Response,
+} from "@/src/features/public-api/types/traces";
import { prisma } from "@langfuse/shared/src/db";
import { v4 as uuidv4 } from "uuid";
-interface GetTracesAPIResponse {
- data: Array<{
- id: string;
- [key: string]: unknown;
- }>;
-}
-
describe("/api/public/traces API Endpoint", () => {
beforeEach(async () => await pruneDatabase());
afterEach(async () => await pruneDatabase());
- it("should create", async () => {
+ it("should create and get a trace via /traces", async () => {
await pruneDatabase();
- await makeAPICall("POST", "/api/public/traces", {
- name: "trace-name",
- userId: "user-1",
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- metadata: { key: "value" },
- release: "1.0.0",
- version: "2.0.0",
- });
-
- const dbTrace = await prisma.trace.findMany({
- where: {
+ const traceCreate = await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
name: "trace-name",
+ userId: "user-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
},
- });
+ undefined,
+ false,
+ );
- expect(dbTrace.length).toBeGreaterThan(0);
- expect(dbTrace[0]?.name).toBe("trace-name");
- expect(dbTrace[0]?.release).toBe("1.0.0");
- expect(dbTrace[0]?.externalId).toBeNull();
- expect(dbTrace[0]?.version).toBe("2.0.0");
- expect(dbTrace[0]?.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+ const trace = await makeZodVerifiedAPICall(
+ GetTraceV1Response,
+ "GET",
+ "/api/public/traces/" + traceCreate.body.id,
+ );
+
+ expect(trace.body.name).toBe("trace-name");
+ expect(trace.body.release).toBe("1.0.0");
+ expect(trace.body.externalId).toBeNull();
+ expect(trace.body.version).toBe("2.0.0");
+ expect(trace.body.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
});
it("should upsert second trace", async () => {
await pruneDatabase();
- await makeAPICall("POST", "/api/public/traces", {
- id: "trace-id",
- name: "trace-name",
- userId: "user-1",
- metadata: { key: "value" },
- release: "1.0.0",
- version: "2.0.0",
- public: true,
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ id: "trace-id",
+ name: "trace-name",
+ userId: "user-1",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ public: true,
+ },
+ undefined,
+ false,
+ );
const dbTrace1 = await prisma.trace.findFirst({
where: {
@@ -70,14 +86,21 @@ describe("/api/public/traces API Endpoint", () => {
userId: "user-1",
});
- await makeAPICall("POST", "/api/public/traces", {
- id: "trace-id",
- metadata: { key: "value" },
- timestamp: "2021-01-01T00:00:00.000Z",
- release: "1.0.0",
- version: "5.0.0",
- public: false,
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ id: "trace-id",
+ metadata: { key: "value" },
+ timestamp: "2021-01-01T00:00:00.000Z",
+ release: "1.0.0",
+ version: "5.0.0",
+ public: false,
+ },
+ undefined,
+ false,
+ );
const dbTrace2 = await prisma.trace.findFirst({
where: {
@@ -100,23 +123,45 @@ describe("/api/public/traces API Endpoint", () => {
it("should use tags correctly on POST and GET", async () => {
await pruneDatabase();
- await makeAPICall("POST", "/api/public/traces", {
- id: "trace-1",
- tags: ["tag-1", "tag-2", "tag-3"],
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ id: "trace-1",
+ tags: ["tag-1", "tag-2", "tag-3"],
+ },
+ undefined,
+ false,
+ );
- await makeAPICall("POST", "/api/public/traces", {
- id: "trace-2",
- tags: ["tag-1"],
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ id: "trace-2",
+ tags: ["tag-1"],
+ },
+ undefined,
+ false,
+ );
- await makeAPICall("POST", "/api/public/traces", {
- id: "trace-3",
- tags: ["tag-2", "tag-3"],
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ id: "trace-3",
+ tags: ["tag-2", "tag-3"],
+ },
+ undefined,
+ false,
+ );
// multiple tags
- const traces = await makeAPICall<GetTracesAPIResponse>(
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
"GET",
"/api/public/traces?tags=tag-2&tags=tag-3",
);
@@ -125,7 +170,8 @@ describe("/api/public/traces API Endpoint", () => {
expect(traceIds).toEqual(["trace-3", "trace-1"]);
// single tag
- const traces2 = await makeAPICall<GetTracesAPIResponse>(
+ const traces2 = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
"GET",
"/api/public/traces?tags=tag-1",
);
@@ -134,7 +180,8 @@ describe("/api/public/traces API Endpoint", () => {
expect(traceIds2).toEqual(["trace-2", "trace-1"]);
// wrong tag
- const traces3 = await makeAPICall<GetTracesAPIResponse>(
+ const traces3 = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
"GET",
"/api/public/traces?tags=tag-10",
);
@@ -143,7 +190,8 @@ describe("/api/public/traces API Endpoint", () => {
expect(traceIds3).toEqual([]);
// no tag
- const traces4 = await makeAPICall<GetTracesAPIResponse>(
+ const traces4 = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
"GET",
"/api/public/traces?tags=",
);
@@ -157,60 +205,106 @@ describe("/api/public/traces API Endpoint", () => {
// Create a trace with some observations that have costs and latencies
const traceId = uuidv4();
- await makeAPICall("POST", "/api/public/traces", {
- id: traceId,
- name: "trace-with-costs",
- userId: "user-costs",
- projectId: "project-costs",
- metadata: { key: "value" },
- release: "1.0.0",
- version: "2.0.0",
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ id: traceId,
+ name: "trace-with-costs",
+ userId: "user-costs",
+ projectId: "project-costs",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ },
+ undefined,
+ false,
+ );
console.log(traceId);
// Simulate observations with costs and latencies
- await makeAPICall("POST", "/api/public/generations", {
- traceId: traceId,
- usage: { totalCost: 10.5 },
- startTime: "2021-01-01T00:00:00.000Z",
- endTime: "2021-01-01T00:10:00.000Z",
- });
- await makeAPICall("POST", "/api/public/generations", {
- traceId: traceId,
- usage: { totalCost: 5.25 },
- startTime: "2021-01-01T00:10:00.000Z",
- endTime: "2021-01-01T00:20:00.000Z",
- });
+ const generationId = uuidv4();
+ await makeZodVerifiedAPICall(
+ PostGenerationsV1Response,
+ "POST",
+ "/api/public/generations",
+ {
+ traceId: traceId,
+ id: generationId,
+ name: "Generation1",
+ usage: { totalCost: 10.5 },
+ startTime: "2021-01-01T00:00:00.000Z",
+ endTime: "2021-01-01T00:10:00.000Z",
+ },
+ undefined,
+ false,
+ );
+ await makeZodVerifiedAPICall(
+ PostGenerationsV1Response,
+ "POST",
+ "/api/public/generations",
+ {
+ traceId: traceId,
+ usage: { totalCost: 5.25 },
+ startTime: "2021-01-01T00:10:00.000Z",
+ endTime: "2021-01-01T00:20:00.000Z",
+ },
+ undefined,
+ false,
+ );
// Simulate scores on the trace
const scoreId1 = uuidv4();
- await makeAPICall("POST", "/api/public/scores", {
- id: scoreId1,
- name: "score-1",
- value: 75.0,
- traceId: traceId,
- comment: "First score",
- });
+ await makeZodVerifiedAPICall(
+ PostScoresResponse,
+ "POST",
+ "/api/public/scores",
+ {
+ id: scoreId1,
+ name: "score-1",
+ value: 75.0,
+ traceId: traceId,
+ comment: "First score",
+ },
+ undefined,
+ false,
+ );
const scoreId2 = uuidv4();
- await makeAPICall("POST", "/api/public/scores", {
- id: scoreId2,
- name: "score-2",
- value: 85.5,
- traceId: traceId,
- comment: "Second score",
- });
+ await makeZodVerifiedAPICall(
+ PostScoresResponse,
+ "POST",
+ "/api/public/scores",
+ {
+ id: scoreId2,
+ name: "score-2",
+ value: 85.5,
+ traceId: traceId,
+ comment: "Second score",
+ },
+ undefined,
+ false,
+ );
const scoreId3 = uuidv4();
- await makeAPICall("POST", "/api/public/scores", {
- id: scoreId3,
- name: "score-3",
- value: 95.0,
- traceId: traceId,
- comment: "Third score",
- });
+ await makeZodVerifiedAPICall(
+ PostScoresResponse,
+ "POST",
+ "/api/public/scores",
+ {
+ id: scoreId3,
+ name: "score-3",
+ value: 95.0,
+ traceId: traceId,
+ comment: "Third score",
+ },
+ undefined,
+ false,
+ );
// GET traces
// Retrieve the trace with totalCost and latency
- const traces = await makeAPICall<GetTracesAPIResponse>(
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
"GET",
`/api/public/traces`,
);
@@ -226,17 +320,23 @@ describe("/api/public/traces API Endpoint", () => {
// GET trace
// Retrieve the trace with total
- const trace = await makeAPICall<{
- id: string;
- totalCost: number;
- htmlPath: string;
- }>("GET", `/api/public/traces/${traceId}`);
+ const trace = await makeZodVerifiedAPICall(
+ GetTraceV1Response,
+ "GET",
+ `/api/public/traces/${traceId}`,
+ );
console.log(trace.body);
expect(trace.body.totalCost).toBeCloseTo(15.75);
expect(trace.body.id).toBe(traceId);
expect(trace.body.id).toBe(traceId);
expect(trace.body.htmlPath).toContain(`/traces/${traceId}`);
expect(trace.body.htmlPath).toContain(`/project/`); // do not know the projectId
+ expect(trace.body.scores).toHaveLength(3);
+ expect(trace.body.scores[0].id).toBe(scoreId3);
+ expect(trace.body.scores[0].name).toBe("score-3");
+ expect(trace.body.observations).toHaveLength(2);
+ expect(trace.body.observations[0].id).toBe(generationId);
+ expect(trace.body.observations[0].name).toBe("Generation1");
});
it("should filter traces by session ID", async () => {
@@ -244,30 +344,45 @@ describe("/api/public/traces API Endpoint", () => {
const anotherSessionId = "another-session-id";
// Create traces with different session IDs
- await makeAPICall("POST", "/api/public/traces", {
- id: "trace-1",
- name: "test-trace-1",
- sessionId,
- userId: "user-1",
- projectId: "project-1",
- metadata: { key: "value" },
- release: "1.0.0",
- version: "1.0.0",
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ id: "trace-1",
+ name: "test-trace-1",
+ sessionId,
+ userId: "user-1",
+ projectId: "project-1",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "1.0.0",
+ },
+ undefined,
+ false,
+ );
- await makeAPICall("POST", "/api/public/traces", {
- id: "trace-2",
- name: "test-trace-2",
- sessionId: anotherSessionId,
- userId: "user-2",
- projectId: "project-1",
- metadata: { key: "value" },
- release: "1.0.0",
- version: "1.0.0",
- });
+ await makeZodVerifiedAPICall(
+ PostTracesV1Response,
+ "POST",
+ "/api/public/traces",
+ {
+ id: "trace-2",
+ name: "test-trace-2",
+ sessionId: anotherSessionId,
+ userId: "user-2",
+ projectId: "project-1",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "1.0.0",
+ },
+ undefined,
+ false,
+ );
// Filter by session ID
- const tracesBySessionId = await makeAPICall<GetTracesAPIResponse>(
+ const tracesBySessionId = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
"GET",
`/api/public/traces?sessionId=${sessionId}`,
);
@@ -277,7 +392,8 @@ describe("/api/public/traces API Endpoint", () => {
expect(tracesBySessionId.body.data[0].id).toBe("trace-1");
// Filter by another session ID
- const tracesByAnotherSessionId = await makeAPICall<GetTracesAPIResponse>(
+ const tracesByAnotherSessionId = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
"GET",
`/api/public/traces?sessionId=${anotherSessionId}`,
);
@@ -287,11 +403,11 @@ describe("/api/public/traces API Endpoint", () => {
expect(tracesByAnotherSessionId.body.data[0].id).toBe("trace-2");
// Filter by non-existent session ID
- const tracesByNonExistentSessionId =
- await makeAPICall<GetTracesAPIResponse>(
- "GET",
- `/api/public/traces?sessionId=non-existent-session-id`,
- );
+ const tracesByNonExistentSessionId = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ `/api/public/traces?sessionId=non-existent-session-id`,
+ );
expect(tracesByNonExistentSessionId.status).toBe(200);
expect(tracesByNonExistentSessionId.body.data).toHaveLength(0);
diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsx
index 7ce1fbec05..ffd7aff55f 100644
--- a/web/src/components/table/use-cases/traces.tsx
+++ b/web/src/components/table/use-cases/traces.tsx
@@ -38,7 +38,7 @@ import {
import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";
import { IOTableCell } from "@/src/components/ui/CodeJsonViewer";
import { useLookBackDays } from "@/src/hooks/useLookBackDays";
-import { type ValidatedScore } from "@/src/features/public-api/types/scores";
+import { type APIScore } from "@/src/features/public-api/types/scores";
export type TracesTableRow = {
bookmarked: boolean;
@@ -56,7 +56,7 @@ export type TracesTableRow = {
input?: unknown;
output?: unknown;
metadata?: unknown;
- scores: ValidatedScore[];
+ scores: APIScore[];
tags: string[];
usage: {
promptTokens: number;
@@ -463,7 +463,7 @@ export default function TracesTable({
header: "Scores",
enableColumnFilter: !omittedFilter.find((f) => f === "scores"),
cell: ({ row }) => {
- const values: ValidatedScore[] = row.getValue("scores");
+ const values: APIScore[] = row.getValue("scores");
return <GroupedScoreBadges scores={values} variant="headings" />;
},
enableHiding: true,
diff --git a/web/src/components/trace/ObservationPreview.tsx b/web/src/components/trace/ObservationPreview.tsx
index cf22452035..1dbec9be1a 100644
--- a/web/src/components/trace/ObservationPreview.tsx
+++ b/web/src/components/trace/ObservationPreview.tsx
@@ -22,12 +22,12 @@ import ScoresTable from "@/src/components/table/use-cases/scores";
import { ScoresPreview } from "@/src/components/trace/ScoresPreview";
import { JumpToPlaygroundButton } from "@/src/ee/features/playground/page/components/JumpToPlaygroundButton";
import { AnnotateDrawer } from "@/src/features/manual-scoring/components/AnnotateDrawer";
-import { type ValidatedScore } from "@/src/features/public-api/types/scores";
+import { type APIScore } from "@/src/features/public-api/types/scores";
export const ObservationPreview = (props: {
observations: Array<ObservationReturnType>;
projectId: string;
- scores: ValidatedScore[];
+ scores: APIScore[];
currentObservationId: string;
traceId: string;
}) => {
@@ -60,7 +60,7 @@ export const ObservationPreview = (props: {
}
acc.get(score.source)?.push(score);
return acc;
- }, new Map<ScoreSource, ValidatedScore[]>());
+ }, new Map<ScoreSource, APIScore[]>());
return (
<Card className="col-span-2 flex max-h-full flex-col overflow-hidden">
diff --git a/web/src/components/trace/ObservationTree.tsx b/web/src/components/trace/ObservationTree.tsx
index 13d6fd2f83..bce0c7ef6b 100644
--- a/web/src/components/trace/ObservationTree.tsx
+++ b/web/src/components/trace/ObservationTree.tsx
@@ -1,7 +1,7 @@
import { type NestedObservation } from "@/src/utils/types";
import { cn } from "@/src/utils/tailwind";
import { type Trace, type $Enums } from "@langfuse/shared";
-import { type ValidatedScore } from "@/src/features/public-api/types/scores";
+import { type APIScore } from "@/src/features/public-api/types/scores";
import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
import { Fragment } from "react";
import { type ObservationReturnType } from "@/src/server/api/routers/traces";
@@ -23,7 +23,7 @@ export const ObservationTree = (props: {
collapseAll: () => void;
expandAll: () => void;
trace: Trace;
- scores: ValidatedScore[];
+ scores: APIScore[];
currentObservationId: string | undefined;
setCurrentObservationId: (id: string | undefined) => void;
showMetrics: boolean;
@@ -62,7 +62,7 @@ const ObservationTreeTraceNode = (props: {
trace: Trace & { latency?: number };
expandAll: () => void;
collapseAll: () => void;
- scores: ValidatedScore[];
+ scores: APIScore[];
currentObservationId: string | undefined;
setCurrentObservationId: (id: string | undefined) => void;
showMetrics?: boolean;
@@ -120,7 +120,7 @@ const ObservationTreeNode = (props: {
observations: NestedObservation[];
collapsedObservations: string[];
toggleCollapsedObservation: (id: string) => void;
- scores: ValidatedScore[];
+ scores: APIScore[];
indentationLevel: number;
currentObservationId: string | undefined;
setCurrentObservationId: (id: string | undefined) => void;
diff --git a/web/src/components/trace/ScoresPreview.tsx b/web/src/components/trace/ScoresPreview.tsx
index ef2613765d..9b85ea73f5 100644
--- a/web/src/components/trace/ScoresPreview.tsx
+++ b/web/src/components/trace/ScoresPreview.tsx
@@ -1,10 +1,10 @@
import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
-import { type ValidatedScore } from "@/src/features/public-api/types/scores";
+import { type APIScore } from "@/src/features/public-api/types/scores";
export const ScoresPreview = ({
itemScoresBySource,
}: {
- itemScoresBySource: Map<string, ValidatedScore[]>;
+ itemScoresBySource: Map<string, APIScore[]>;
}) => {
if (!Boolean(itemScoresBySource.size)) return null;
diff --git a/web/src/components/trace/TracePreview.tsx b/web/src/components/trace/TracePreview.tsx
index 62087ddedd..44cb1c4a30 100644
--- a/web/src/components/trace/TracePreview.tsx
+++ b/web/src/components/trace/TracePreview.tsx
@@ -19,7 +19,7 @@ import { withDefault, StringParam, useQueryParam } from "use-query-params";
import ScoresTable from "@/src/components/table/use-cases/scores";
import { ScoresPreview } from "@/src/components/trace/ScoresPreview";
import { AnnotateDrawer } from "@/src/features/manual-scoring/components/AnnotateDrawer";
-import { type ValidatedScore } from "@/src/features/public-api/types/scores";
+import { type APIScore } from "@/src/features/public-api/types/scores";
export const TracePreview = ({
trace,
@@ -28,7 +28,7 @@ export const TracePreview = ({
}: {
trace: Trace & { latency?: number };
observations: ObservationReturnType[];
- scores: ValidatedScore[];
+ scores: APIScore[];
}) => {
const [selectedTab, setSelectedTab] = useQueryParam(
"view",
@@ -42,7 +42,7 @@ export const TracePreview = ({
}
acc.get(score.source)?.push(score);
return acc;
- }, new Map<ScoreSource, ValidatedScore[]>());
+ }, new Map<ScoreSource, APIScore[]>());
return (
<Card className="col-span-2 flex max-h-full flex-col overflow-hidden">
diff --git a/web/src/components/trace/TraceTimelineView.tsx b/web/src/components/trace/TraceTimelineView.tsx
index cdd21d32d1..92081b5495 100644
--- a/web/src/components/trace/TraceTimelineView.tsx
+++ b/web/src/components/trace/TraceTimelineView.tsx
@@ -1,7 +1,7 @@
import { Card } from "@/src/components/ui/card";
import { type ObservationReturnType } from "@/src/server/api/routers/traces";
import { type Trace } from "@langfuse/shared";
-import { type ValidatedScore } from "@/src/features/public-api/types/scores";
+import { type APIScore } from "@/src/features/public-api/types/scores";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { SimpleTreeView } from "@mui/x-tree-view/SimpleTreeView";
@@ -188,7 +188,7 @@ function TraceTreeItem({
traceStartTime: Date;
totalScaleSpan: number;
projectId: string;
- scores: ValidatedScore[];
+ scores: APIScore[];
observations: Array<ObservationReturnType>;
cardWidth: number;
}) {
@@ -267,7 +267,7 @@ export function TraceTimelineView({
trace: Trace & { latency?: number };
observations: Array<ObservationReturnType>;
projectId: string;
- scores: ValidatedScore[];
+ scores: APIScore[];
}) {
const { latency, name, id } = trace;
const [backgroundColor, setBackgroundColor] = useState("");
diff --git a/web/src/components/trace/index.tsx b/web/src/components/trace/index.tsx
index 2e9f8aa942..407021bc8a 100644
--- a/web/src/components/trace/index.tsx
+++ b/web/src/components/trace/index.tsx
@@ -34,12 +34,12 @@ import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePos
import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
import { TraceTimelineView } from "@/src/components/trace/TraceTimelineView";
import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";
-import { type ValidatedScore } from "@/src/features/public-api/types/scores";
+import { type APIScore } from "@/src/features/public-api/types/scores";
export function Trace(props: {
observations: Array<ObservationReturnType>;
trace: Trace;
- scores: ValidatedScore[];
+ scores: APIScore[];
projectId: string;
}) {
const capture = usePostHogClientCapture();
diff --git a/web/src/features/datasets/components/DatasetRunItemsTable.tsx b/web/src/features/datasets/components/DatasetRunItemsTable.tsx
index 8edd2f421b..820c0364fa 100644
--- a/web/src/features/datasets/components/DatasetRunItemsTable.tsx
+++ b/web/src/features/datasets/components/DatasetRunItemsTable.tsx
@@ -7,7 +7,7 @@ import { formatIntervalSeconds } from "@/src/utils/dates";
import { type RouterOutput } from "@/src/utils/types";
import { useQueryParams, withDefault, NumberParam } from "use-query-params";
-import { type ValidatedScore } from "@/src/features/public-api/types/scores";
+import { type APIScore } from "@/src/features/public-api/types/scores";
import { usdFormatter } from "../../../utils/numbers";
import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
@@ -30,7 +30,7 @@ type RowData = {
output?: unknown;
expectedOutput?: unknown;
- scores: ValidatedScore[];
+ scores: APIScore[];
latency?: number;
totalCost?: string;
};
diff --git a/web/src/features/manual-scoring/components/AnnotateDrawer.tsx b/web/src/features/manual-scoring/components/AnnotateDrawer.tsx
index 4f08d378fd..5ca5b95f2d 100644
--- a/web/src/features/manual-scoring/components/AnnotateDrawer.tsx
+++ b/web/src/features/manual-scoring/components/AnnotateDrawer.tsx
@@ -35,7 +35,7 @@ import {
CreateAnnotationScoreData,
UpdateAnnotationScoreData,
} from "@langfuse/shared";
-import { type ValidatedScore } from "@/src/features/public-api/types/scores";
+import { type APIScore } from "@/src/features/public-api/types/scores";
import {
type ValidatedScoreConfig,
type ConfigCategory,
@@ -137,7 +137,7 @@ export function AnnotateDrawer({
source = "TraceDetail",
}: {
traceId: string;
- scores: ValidatedScore[];
+ scores: APIScore[];
observationId?: string;
projectId: string;
variant?: "button" | "badge";
@@ -214,7 +214,7 @@ export function AnnotateDrawer({
const utils = api.useUtils();
- const onSettledUpsert = async (data?: ValidatedScore, error?: unknown) => {
+ const onSettledUpsert = async (data?: APIScore, error?: unknown) => {
if (!data || error) return;
const { id, value, stringValue, name, dataType, configId, comment } = data;
diff --git a/web/src/features/manual-scoring/lib/getDefaultScoreData.ts b/web/src/features/manual-scoring/lib/getDefaultScoreData.ts
index 6d30dce9f5..fa5f21fe52 100644
--- a/web/src/features/manual-scoring/lib/getDefaultScoreData.ts
+++ b/web/src/features/manual-scoring/lib/getDefaultScoreData.ts
@@ -1,5 +1,5 @@
import { ScoreSource } from "@langfuse/shared";
-import { type ValidatedScore } from "@/src/features/public-api/types/scores";
+import { type APIScore } from "@/src/features/public-api/types/scores";
import { type ValidatedScoreConfig } from "@/src/features/public-api/types/score-configs";
export const getDefaultScoreData = ({
@@ -9,7 +9,7 @@ export const getDefaultScoreData = ({
traceId,
observationId,
}: {
- scores: ValidatedScore[];
+ scores: APIScore[];
emptySelectedConfigIds: string[];
configs: ValidatedScoreConfig[];
traceId: string;
diff --git a/web/src/features/public-api/server/outputSchemaConversion.ts b/web/src/features/public-api/server/outputSchemaConversion.ts
deleted file mode 100644
index e584b52f07..0000000000
--- a/web/src/features/public-api/server/outputSchemaConversion.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { type ObservationView } from "@langfuse/shared";
-
-// This function exists to endure backwards compatibility with GET API consumers
-// Old APIs expect to return promptTokens, completionTokens, totalTokens
-// New APIs expect to return usage: { input, output, total, unit }
-// We decided to return both formats to not break anything. In the future, this function
-// will take a variable passed from a query param to determine which API version to return.
-export const mapUsageOutput = (observation: ObservationView) => {
- const { promptTokens, completionTokens, totalTokens, unit } = observation;
- return {
- ...observation,
- inputPrice: observation.inputPrice?.toNumber(),
- outputPrice: observation.outputPrice?.toNumber(),
- totalPrice: observation.totalPrice?.toNumber(),
- calculatedInputCost: observation.calculatedInputCost?.toNumber(),
- calculatedOutputCost: observation.calculatedOutputCost?.toNumber(),
- calculatedTotalCost: observation.calculatedTotalCost?.toNumber(),
- usage: {
- unit,
- input: promptTokens,
- output: completionTokens,
- total: totalTokens,
- },
- };
-};
diff --git a/web/src/features/public-api/server/withMiddlewares.ts b/web/src/features/public-api/server/withMiddlewares.ts
index 9740ae67ae..0cec317319 100644
--- a/web/src/features/public-api/server/withMiddlewares.ts
+++ b/web/src/features/public-api/server/withMiddlewares.ts
@@ -5,7 +5,7 @@ import { z } from "zod";
import { BaseError, MethodNotAllowedError } from "@langfuse/shared";
import * as Sentry from "@sentry/node";
-const httpMethods = ["GET", "POST", "PUT", "DELETE"] as const;
+const httpMethods = ["GET", "POST", "PUT", "DELETE", "PATCH"] as const;
export type HttpMethod = (typeof httpMethods)[number];
type Handlers = {
[Method in HttpMethod]?: (
@@ -32,6 +32,7 @@ export function withMiddlewares(handlers: Handlers) {
POST: defaultHandler,
PUT: defaultHandler,
DELETE: defaultHandler,
+ PATCH: defaultHandler,
},
...handlers,
};
diff --git a/web/src/features/public-api/types/events.ts b/web/src/features/public-api/types/events.ts
new file mode 100644
index 0000000000..b15c058aef
--- /dev/null
+++ b/web/src/features/public-api/types/events.ts
@@ -0,0 +1,35 @@
+import { z } from "zod";
+import {
+ CreateEventEvent,
+ eventTypes,
+ type ingestionApiSchema,
+} from "@langfuse/shared";
+import { v4 as uuidv4 } from "uuid";
+
+/**
+ * Transforms
+ */
+
+export const transformEventToIngestionBatch = (
+ event: z.infer<typeof CreateEventEvent>,
+): z.infer<typeof ingestionApiSchema>["batch"] => {
+ return [
+ {
+ id: uuidv4(),
+ type: eventTypes.OBSERVATION_CREATE,
+ timestamp: new Date().toISOString(),
+ body: {
+ ...event,
+ type: "EVENT",
+ },
+ },
+ ];
+};
+
+/**
+ * Endpoints
+ */
+
+// POST /events
+export const PostEventsV1Body = CreateEventEvent;
+export const PostEventsV1Response = z.object({ id: z.string() });
diff --git a/web/src/features/public-api/types/generations.ts b/web/src/features/public-api/types/generations.ts
new file mode 100644
index 0000000000..b180ba7cd3
--- /dev/null
+++ b/web/src/features/public-api/types/generations.ts
@@ -0,0 +1,72 @@
+// src/features/public-api/types/generations.ts
+
+import { z } from "zod";
+import {
+ LegacyGenerationsCreateSchema,
+ LegacyGenerationPatchSchema,
+ eventTypes,
+ type ingestionApiSchema,
+} from "@langfuse/shared";
+import { v4 as uuidv4 } from "uuid";
+
+/**
+ * Transforms
+ */
+
+export const transformGenerationPostToIngestionBatch = ({
+ prompt,
+ completion,
+ ...generation
+}: z.infer<typeof LegacyGenerationsCreateSchema>): z.infer<
+ typeof ingestionApiSchema
+>["batch"] => {
+ return [
+ {
+ id: uuidv4(),
+ type: eventTypes.OBSERVATION_CREATE,
+ timestamp: new Date().toISOString(),
+ body: {
+ ...generation,
+ type: "GENERATION",
+ input: prompt,
+ output: completion,
+ },
+ },
+ ];
+};
+
+export const transformGenerationPatchToIngestionBatch = ({
+ generationId,
+ prompt,
+ completion,
+ ...generation
+}: z.infer<typeof LegacyGenerationPatchSchema>): z.infer<
+ typeof ingestionApiSchema
+>["batch"] => {
+ return [
+ {
+ id: uuidv4(),
+ type: eventTypes.OBSERVATION_UPDATE,
+ timestamp: new Date().toISOString(),
+ body: {
+ ...generation,
+ id: generationId,
+ type: "GENERATION",
+ input: prompt,
+ output: completion,
+ },
+ },
+ ];
+};
+
+/**
+ * Endpoints
+ */
+
+// POST /generations
+export const PostGenerationsV1Body = LegacyGenerationsCreateSchema;
+export const PostGenerationsV1Response = z.object({ id: z.string() });
+
+// PATCH /generations
+export const PatchGenerationsV1Body = LegacyGenerationPatchSchema;
+export const PatchGenerationsV1Response = z.object({ id: z.string() });
diff --git a/web/src/features/public-api/types/metrics.ts b/web/src/features/public-api/types/metrics.ts
new file mode 100644
index 0000000000..5aa31dc8a5
--- /dev/null
+++ b/web/src/features/public-api/types/metrics.ts
@@ -0,0 +1,41 @@
+import {
+ paginationMetaResponseZod,
+ paginationZod,
+ stringDateTime,
+} from "@langfuse/shared";
+import { z } from "zod";
+
+/**
+ * Endpoints
+ */
+
+// Get /metrics/daily
+export const GetMetricsDailyV1Query = z.object({
+ ...paginationZod,
+ traceName: z.string().nullish(),
+ userId: z.string().nullish(),
+ tags: z.union([z.array(z.string()), z.string()]).nullish(),
+ fromTimestamp: stringDateTime,
+ toTimestamp: stringDateTime,
+});
+export const GetMetricsDailyV1Response = z.object({
+ data: z.array(
+ z.object({
+ date: z.string().date(),
+ countTraces: z.number(),
+ totalCost: z.number(),
+ usage: z.array(
+ z.object({
+ model: z.string().nullable(),
+ inputUsage: z.number(),
+ outputUsage: z.number(),
+ totalUsage: z.number(),
+ countObservations: z.number(),
+ countTraces: z.number(),
+ totalCost: z.number(),
+ }),
+ ),
+ }),
+ ),
+ meta: paginationMetaResponseZod,
+});
diff --git a/web/src/features/public-api/types/observations.ts b/web/src/features/public-api/types/observations.ts
new file mode 100644
index 0000000000..e8ed3c7d1b
--- /dev/null
+++ b/web/src/features/public-api/types/observations.ts
@@ -0,0 +1,129 @@
+import {
+ type ObservationView,
+ paginationMetaResponseZod,
+ paginationZod,
+ stringDateTime,
+} from "@langfuse/shared";
+import { z } from "zod";
+
+/**
+ * Objects
+ */
+
+const ObservationType = z.enum(["GENERATION", "SPAN", "EVENT"]);
+
+export const APIObservation = z.strictObject({
+ id: z.string(),
+ projectId: z.string(),
+ traceId: z.string().nullable(),
+ parentObservationId: z.string().nullable(),
+ name: z.string().nullable(),
+ type: ObservationType,
+ startTime: z.coerce.date(),
+ endTime: z.coerce.date().nullable(),
+ version: z.string().nullable(),
+ createdAt: z.coerce.date(),
+ updatedAt: z.coerce.date(),
+ input: z.any(),
+ output: z.any(),
+ metadata: z.any(),
+ level: z.enum(["DEBUG", "DEFAULT", "WARNING", "ERROR"]),
+ statusMessage: z.string().nullable(),
+
+ // GENERATION only
+ model: z.string().nullable(),
+ modelParameters: z.any(),
+ completionStartTime: z.coerce.date().nullable(),
+ promptId: z.string().nullable(),
+
+ // usage
+ usage: z.object({
+ unit: z.string().nullable(),
+ input: z.number(),
+ output: z.number(),
+ total: z.number(),
+ }),
+ unit: z.string().nullable(), // backwards compatibility
+ promptTokens: z.number(), // backwards compatibility
+ completionTokens: z.number(), // backwards compatibility
+ totalTokens: z.number(), // backwards compatibility
+
+ // matched model
+ modelId: z.string().nullable(),
+ inputPrice: z.number().nullable(),
+ outputPrice: z.number().nullable(),
+ totalPrice: z.number().nullable(),
+
+ // costs
+ calculatedInputCost: z.number().nullable(),
+ calculatedOutputCost: z.number().nullable(),
+ calculatedTotalCost: z.number().nullable(),
+
+ // metrics
+ latency: z.number().nullable(),
+
+ // generation metrics
+ timeToFirstToken: z.number().nullable(),
+});
+
+/**
+ * Transforms
+ */
+
+/**
+ *
+ * @param observation - DB Observation
+ * @returns API Observation as defined in the public API
+ */
+export const transformDbToApiObservation = (
+ observation: ObservationView,
+): z.infer<typeof APIObservation> => {
+ const { promptTokens, completionTokens, totalTokens, unit, ...rest } =
+ observation;
+
+ return {
+ ...rest,
+ unit,
+ promptTokens,
+ completionTokens,
+ totalTokens,
+ inputPrice: observation.inputPrice?.toNumber() ?? null,
+ outputPrice: observation.outputPrice?.toNumber() ?? null,
+ totalPrice: observation.totalPrice?.toNumber() ?? null,
+ calculatedInputCost: observation.calculatedInputCost?.toNumber() ?? null,
+ calculatedOutputCost: observation.calculatedOutputCost?.toNumber() ?? null,
+ calculatedTotalCost: observation.calculatedTotalCost?.toNumber() ?? null,
+ usage: {
+ unit,
+ input: promptTokens,
+ output: completionTokens,
+ total: totalTokens,
+ },
+ };
+};
+
+/**
+ * Endpoints
+ */
+
+// GET /observations
+export const GetObservationsV1Query = z.object({
+ ...paginationZod,
+ type: ObservationType.nullish(),
+ name: z.string().nullish(),
+ userId: z.string().nullish(),
+ traceId: z.string().nullish(),
+ parentObservationId: z.string().nullish(),
+ fromStartTime: stringDateTime,
+ toStartTime: stringDateTime,
+});
+export const GetObservationsV1Response = z.object({
+ data: z.array(APIObservation),
+ meta: paginationMetaResponseZod,
+});
+
+// GET /observations/{observationId}
+export const GetObservationV1Query = z.object({
+ observationId: z.string(),
+});
+export const GetObservationV1Response = APIObservation;
diff --git a/web/src/features/public-api/types/scores.ts b/web/src/features/public-api/types/scores.ts
index 9325a4ee2e..fabedff927 100644
--- a/web/src/features/public-api/types/scores.ts
+++ b/web/src/features/public-api/types/scores.ts
@@ -4,6 +4,7 @@ import {
paginationMetaResponseZod,
NonEmptyString,
type Score,
+ stringDateTime,
} from "@langfuse/shared";
import { z } from "zod";
import { isPresent } from "@/src/utils/typeChecks";
@@ -12,10 +13,10 @@ import { Category as ConfigCategory } from "./score-configs";
/**
* Types to use across codebase
*/
-export type ValidatedScore = z.infer<typeof ValidatedScoreSchema>;
+export type APIScore = z.infer<typeof APIScore>;
/**
- * Objects
+ * Helpers
*/
const ScoreSource = ["API", "EVAL", "ANNOTATION"] as const;
@@ -64,7 +65,11 @@ const BaseScoreBody = z.object({
comment: z.string().nullish(),
});
-const ValidatedScoreSchema = z.discriminatedUnion("dataType", [
+/**
+ * Objects
+ */
+
+export const APIScore = z.discriminatedUnion("dataType", [
ScoreBase.merge(NumericData),
ScoreBase.merge(CategoricalData),
ScoreBase.merge(BooleanData),
@@ -154,11 +159,9 @@ export const ScorePropsAgainstConfig = z.union([
* @param scores
* @returns list of validated scores
*/
-export const filterAndValidateDbScoreList = (
- scores: Score[],
-): ValidatedScore[] =>
+export const filterAndValidateDbScoreList = (scores: Score[]): APIScore[] =>
scores.reduce((acc, ts) => {
- const result = ValidatedScoreSchema.safeParse(ts);
+ const result = APIScore.safeParse(ts);
if (result.success) {
acc.push(result.data);
} else {
@@ -166,7 +169,7 @@ export const filterAndValidateDbScoreList = (
Sentry.captureException(result.error);
}
return acc;
- }, [] as ValidatedScore[]);
+ }, [] as APIScore[]);
/**
* Use this function when pulling a single score from the database before using in the application to ensure type safety.
@@ -175,8 +178,8 @@ export const filterAndValidateDbScoreList = (
* @returns validated score
* @throws error if score fails validation
*/
-export const validateDbScore = (score: Score): ValidatedScore =>
- ValidatedScoreSchema.parse(score);
+export const validateDbScore = (score: Score): APIScore =>
+ APIScore.parse(score);
/**
* Endpoints
@@ -244,7 +247,7 @@ export const PostScoresBody = z
}
});
-export const PostScoresResponse = z.void();
+export const PostScoresResponse = z.object({ id: z.string() });
// GET /scores
export const GetScoresQuery = z.object({
@@ -253,7 +256,8 @@ export const GetScoresQuery = z.object({
dataType: z.enum(ScoreDataType).nullish(),
configId: z.string().nullish(),
name: z.string().nullish(),
- fromTimestamp: z.coerce.date().nullish(),
+ fromTimestamp: stringDateTime,
+ toTimestamp: stringDateTime,
source: z.enum(ScoreSource).nullish(),
value: z.coerce.number().nullish(),
operator: z.enum(operators).nullish(),
@@ -268,7 +272,7 @@ export const GetScoresQuery = z.object({
// LegacyGetScoreResponseDataV1 is only used for response of GET /scores list endpoint
const LegacyGetScoreResponseDataV1 = z.intersection(
- ValidatedScoreSchema,
+ APIScore,
z.object({
trace: z.object({
userId: z.string().nullish(),
@@ -302,7 +306,7 @@ export const GetScoreQuery = z.object({
scoreId: z.string(),
});
-export const GetScoreResponse = ValidatedScoreSchema;
+export const GetScoreResponse = APIScore;
// DELETE /scores/{scoreId}
export const DeleteScoreQuery = z.object({
diff --git a/web/src/features/public-api/types/sessions.ts b/web/src/features/public-api/types/sessions.ts
new file mode 100644
index 0000000000..85861a821d
--- /dev/null
+++ b/web/src/features/public-api/types/sessions.ts
@@ -0,0 +1,40 @@
+import { APITrace } from "@/src/features/public-api/types/traces";
+import {
+ paginationMetaResponseZod,
+ paginationZod,
+ stringDateTime,
+} from "@langfuse/shared";
+import { z } from "zod";
+
+/**
+ * Objects
+ */
+
+const APISession = z.strictObject({
+ id: z.string(),
+ createdAt: z.coerce.date(),
+ projectId: z.string(),
+});
+
+/**
+ * Endpoints
+ */
+
+// GET /sessions
+export const GetSessionsV1Query = z.object({
+ ...paginationZod,
+ fromTimestamp: stringDateTime,
+ toTimestamp: stringDateTime,
+});
+export const GetSessionsV1Response = z.object({
+ data: z.array(APISession),
+ meta: paginationMetaResponseZod,
+});
+
+// GET /sessions/:id
+export const GetSessionV1Query = z.object({
+ sessionId: z.string(),
+});
+export const GetSessionV1Response = APISession.extend({
+ traces: z.array(APITrace),
+});
diff --git a/web/src/features/public-api/types/spans.ts b/web/src/features/public-api/types/spans.ts
new file mode 100644
index 0000000000..d6c9fe9f70
--- /dev/null
+++ b/web/src/features/public-api/types/spans.ts
@@ -0,0 +1,64 @@
+import { z } from "zod";
+import {
+ LegacySpanPatchSchema,
+ LegacySpanPostSchema,
+ eventTypes,
+ type ingestionApiSchema,
+} from "@langfuse/shared";
+import { v4 } from "uuid";
+
+/**
+ * Objects
+ */
+
+/**
+ * Transforms
+ */
+
+export const transformLegacySpanPostToIngestionBatch = (
+ span: z.infer<typeof LegacySpanPostSchema>,
+): z.infer<typeof ingestionApiSchema>["batch"] => {
+ return [
+ {
+ id: v4(),
+ type: eventTypes.OBSERVATION_CREATE,
+ timestamp: new Date().toISOString(),
+ body: {
+ ...span,
+ type: "SPAN",
+ },
+ },
+ ];
+};
+
+export const transformLegacySpanPatchToIngestionBatch = ({
+ spanId,
+ ...span
+}: z.infer<typeof LegacySpanPatchSchema>): z.infer<
+ typeof ingestionApiSchema
+>["batch"] => {
+ return [
+ {
+ id: v4(),
+ type: eventTypes.OBSERVATION_UPDATE,
+ timestamp: new Date().toISOString(),
+ body: {
+ ...span,
+ id: spanId,
+ type: "SPAN",
+ },
+ },
+ ];
+};
+
+/**
+ * Endpoints
+ */
+
+// POST /spans
+export const PostSpansV1Body = LegacySpanPostSchema;
+export const PostSpansV1Response = z.object({ id: z.string() });
+
+// PATCH /spans
+export const PatchSpansV1Body = LegacySpanPatchSchema;
+export const PatchSpansV1Response = z.object({ id: z.string() });
diff --git a/web/src/features/public-api/types/traces.ts b/web/src/features/public-api/types/traces.ts
new file mode 100644
index 0000000000..c1e52e0667
--- /dev/null
+++ b/web/src/features/public-api/types/traces.ts
@@ -0,0 +1,84 @@
+import { APIObservation } from "@/src/features/public-api/types/observations";
+import { APIScore } from "@/src/features/public-api/types/scores";
+import {
+ paginationZod,
+ paginationMetaResponseZod,
+ stringDateTime,
+ orderBy,
+ TraceBody,
+} from "@langfuse/shared";
+import { z } from "zod";
+
+/**
+ * Objects
+ */
+
+export const APITrace = z.strictObject({
+ id: z.string(),
+ externalId: z.string().nullable(),
+ timestamp: z.coerce.date(),
+ name: z.string().nullable(),
+ userId: z.string().nullable(),
+ metadata: z.any(), // Prisma JSON
+ release: z.string().nullable(),
+ version: z.string().nullable(),
+ projectId: z.string(),
+ public: z.boolean(),
+ bookmarked: z.boolean(),
+ tags: z.array(z.string()),
+ input: z.any(), // Prisma JSON
+ output: z.any(), // Prisma JSON
+ sessionId: z.string().nullable(),
+ createdAt: z.coerce.date(),
+ updatedAt: z.coerce.date(),
+});
+
+const APIExtendedTrace = APITrace.extend({
+ observations: z.array(z.string()),
+ scores: z.array(z.string()),
+ totalCost: z.number(),
+ latency: z.number(),
+ htmlPath: z.string(),
+});
+
+/**
+ * Endpoints
+ */
+
+// GET /api/public/traces
+export const GetTracesV1Query = z.object({
+ ...paginationZod,
+ userId: z.string().nullish(),
+ name: z.string().nullish(),
+ tags: z.union([z.array(z.string()), z.string()]).nullish(),
+ sessionId: z.string().nullish(),
+ fromTimestamp: stringDateTime,
+ toTimestamp: stringDateTime,
+ orderBy: z
+ .string() // orderBy=timestamp.asc
+ .nullish()
+ .transform((v) => {
+ if (!v) return null;
+ const [column, order] = v.split(".");
+ return { column, order: order?.toUpperCase() };
+ })
+ .pipe(orderBy.nullish()),
+});
+
+export const GetTracesV1Response = z.object({
+ data: z.array(APIExtendedTrace),
+ meta: paginationMetaResponseZod,
+});
+
+// POST /api/public/traces
+export const PostTracesV1Body = TraceBody;
+export const PostTracesV1Response = z.object({ id: z.string() });
+
+// GET /api/public/traces/{traceId}
+export const GetTraceV1Query = z.object({
+ traceId: z.string(),
+});
+export const GetTraceV1Response = APIExtendedTrace.extend({
+ scores: z.array(APIScore),
+ observations: z.array(APIObservation),
+});
diff --git a/web/src/pages/api/public/dataset-items.ts b/web/src/pages/api/public/dataset-items/index.ts
similarity index 100%
rename from web/src/pages/api/public/dataset-items.ts
rename to web/src/pages/api/public/dataset-items/index.ts
diff --git a/web/src/pages/api/public/events.ts b/web/src/pages/api/public/events.ts
index 92794cb1ff..3622097e23 100644
--- a/web/src/pages/api/public/events.ts
+++ b/web/src/pages/api/public/events.ts
@@ -1,88 +1,29 @@
-import { type NextApiRequest, type NextApiResponse } from "next";
-import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
-import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
-import { v4 as uuidv4 } from "uuid";
import {
- CreateEventEvent,
- eventTypes,
- ingestionBatchEvent,
-} from "@langfuse/shared";
+ PostEventsV1Body,
+ PostEventsV1Response,
+ transformEventToIngestionBatch,
+} from "@/src/features/public-api/types/events";
+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
import {
handleBatch,
- handleSingleIngestionObject,
+ parseSingleTypedIngestionApiResponse,
} from "@/src/pages/api/public/ingestion";
-import { z } from "zod";
-import { isPrismaException } from "@/src/utils/exceptions";
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- await runMiddleware(req, res, cors);
-
- if (req.method !== "POST") {
- return res.status(405).json({ message: "Method not allowed" });
- }
-
- // CHECK AUTH
- const authCheck = await verifyAuthHeaderAndReturnScope(
- req.headers.authorization,
- );
- if (!authCheck.validKey)
- return res.status(401).json({
- message: authCheck.error,
- });
- // END CHECK AUTH
-
- console.log(
- "trying to create observation for event, project ",
- authCheck.scope.projectId,
- ", body:",
- JSON.stringify(req.body, null, 2),
- );
-
- try {
- const convertToObservation = (
- generation: z.infer<typeof CreateEventEvent>,
- ) => {
- return {
- ...generation,
- type: "EVENT",
- };
- };
-
- const event = {
- id: uuidv4(),
- type: eventTypes.OBSERVATION_CREATE,
- timestamp: new Date().toISOString(),
- body: convertToObservation(CreateEventEvent.parse(req.body)),
- };
-
- const result = await handleBatch(
- ingestionBatchEvent.parse([event]),
- {},
- req,
- authCheck,
- );
- handleSingleIngestionObject(result.errors, result.results, res);
- } catch (error: unknown) {
- console.error(error);
- if (error instanceof z.ZodError) {
- return res.status(400).json({
- message: "Invalid request data",
- error: error.errors,
- });
- }
- if (isPrismaException(error)) {
- return res.status(500).json({
- error: "Internal Server Error",
- });
- }
- const errorMessage =
- error instanceof Error ? error.message : "An unknown error occurred";
- res.status(500).json({
- message: "Invalid request data",
- error: errorMessage,
- });
- }
-}
+export default withMiddlewares({
+ POST: createAuthedAPIRoute({
+ name: "Create Event",
+ bodySchema: PostEventsV1Body,
+ responseSchema: PostEventsV1Response,
+ fn: async ({ body, auth, req }) => {
+ const ingestionBatch = transformEventToIngestionBatch(body);
+ const result = await handleBatch(ingestionBatch, {}, req, auth);
+ const response = parseSingleTypedIngestionApiResponse(
+ result.errors,
+ result.results,
+ PostEventsV1Response,
+ );
+ return response;
+ },
+ }),
+});
diff --git a/web/src/pages/api/public/generations.ts b/web/src/pages/api/public/generations.ts
index 3c379aa94d..e07b6ee50b 100644
--- a/web/src/pages/api/public/generations.ts
+++ b/web/src/pages/api/public/generations.ts
@@ -1,167 +1,47 @@
-import { type NextApiRequest, type NextApiResponse } from "next";
-import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
-import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
-import { v4 as uuidv4 } from "uuid";
-import { ResourceNotFoundError } from "../../../utils/exceptions";
import {
- LegacyGenerationPatchSchema,
- LegacyGenerationsCreateSchema,
- eventTypes,
- ingestionBatchEvent,
-} from "@langfuse/shared";
+ PostGenerationsV1Body,
+ PostGenerationsV1Response,
+ PatchGenerationsV1Body,
+ PatchGenerationsV1Response,
+ transformGenerationPostToIngestionBatch,
+ transformGenerationPatchToIngestionBatch,
+} from "@/src/features/public-api/types/generations";
+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
import {
handleBatch,
- handleSingleIngestionObject,
+ parseSingleTypedIngestionApiResponse,
} from "@/src/pages/api/public/ingestion";
-import { z } from "zod";
-import { isPrismaException } from "@/src/utils/exceptions";
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- await runMiddleware(req, res, cors);
-
- // POST endpoint defined for backwards compatibility only. Observations should be created via the ingestion endpoint
- if (req.method === "POST") {
- try {
- // CHECK AUTH
- const authCheck = await verifyAuthHeaderAndReturnScope(
- req.headers.authorization,
- );
- if (!authCheck.validKey)
- return res.status(401).json({
- message: authCheck.error,
- });
- // END CHECK AUTH
- console.log(
- "trying to create observation for generation, project ",
- authCheck.scope.projectId,
- ", body:",
- JSON.stringify(req.body, null, 2),
- );
-
- const convertToObservation = (
- generation: z.infer<typeof LegacyGenerationsCreateSchema>,
- ) => {
- return {
- ...generation,
- type: "GENERATION",
- input: generation.prompt,
- output: generation.completion,
- };
- };
-
- const event = {
- id: uuidv4(),
- type: eventTypes.OBSERVATION_CREATE,
- timestamp: new Date().toISOString(),
- body: convertToObservation(
- LegacyGenerationsCreateSchema.parse(req.body),
- ),
- };
-
- const result = await handleBatch(
- ingestionBatchEvent.parse([event]),
- {},
- req,
- authCheck,
- );
-
- handleSingleIngestionObject(result.errors, result.results, res);
- } catch (error: unknown) {
- console.error(error);
- if (error instanceof z.ZodError) {
- return res.status(400).json({
- message: "Invalid request data",
- error: error.errors,
- });
- }
- if (isPrismaException(error)) {
- return res.status(500).json({
- error: "Internal Server Error",
- });
- }
- const errorMessage =
- error instanceof Error ? error.message : "An unknown error occurred";
- res.status(500).json({
- message: "Invalid request data",
- error: errorMessage,
- });
- }
- } else if (req.method === "PATCH") {
- try {
- // CHECK AUTH
- const authCheck = await verifyAuthHeaderAndReturnScope(
- req.headers.authorization,
+export default withMiddlewares({
+ POST: createAuthedAPIRoute({
+ name: "Create Generation (Legacy)",
+ bodySchema: PostGenerationsV1Body,
+ responseSchema: PostGenerationsV1Response,
+ fn: async ({ body, auth, req }) => {
+ const ingestionBatch = transformGenerationPostToIngestionBatch(body);
+ const result = await handleBatch(ingestionBatch, {}, req, auth);
+ const response = parseSingleTypedIngestionApiResponse(
+ result.errors,
+ result.results,
+ PostGenerationsV1Response,
);
- if (!authCheck.validKey)
- return res.status(401).json({
- message: authCheck.error,
- });
- // END CHECK AUTH
- console.log(
- "trying to update observation for generation, project ",
- authCheck.scope.projectId,
- ", body:",
- JSON.stringify(req.body, null, 2),
+ return response;
+ },
+ }),
+ PATCH: createAuthedAPIRoute({
+ name: "Patch Generation (Legacy)",
+ bodySchema: PatchGenerationsV1Body,
+ responseSchema: PatchGenerationsV1Response,
+ fn: async ({ body, auth, req }) => {
+ const ingestionBatch = transformGenerationPatchToIngestionBatch(body);
+ const result = await handleBatch(ingestionBatch, {}, req, auth);
+ const response = parseSingleTypedIngestionApiResponse(
+ result.errors,
+ result.results,
+ PatchGenerationsV1Response,
);
-
- const convertToObservation = (
- generation: z.infer<typeof LegacyGenerationPatchSchema>,
- ) => {
- return {
- ...generation,
- id: generation.generationId,
- type: "GENERATION",
- input: generation.prompt,
- output: generation.completion,
- };
- };
-
- const event = {
- id: uuidv4(),
- type: eventTypes.OBSERVATION_UPDATE,
- timestamp: new Date().toISOString(),
- body: convertToObservation(LegacyGenerationPatchSchema.parse(req.body)),
- };
-
- const result = await handleBatch(
- ingestionBatchEvent.parse([event]),
- {},
- req,
- authCheck,
- );
-
- handleSingleIngestionObject(result.errors, result.results, res);
- } catch (error: unknown) {
- console.error(error);
- if (error instanceof z.ZodError) {
- return res.status(400).json({
- message: "Invalid request data",
- error: error.errors,
- });
- }
- if (isPrismaException(error)) {
- return res.status(500).json({
- error: "Internal Server Error",
- });
- }
-
- if (error instanceof ResourceNotFoundError) {
- return res.status(404).json({
- message: "Observation not found",
- });
- }
-
- const errorMessage =
- error instanceof Error ? error.message : "An unknown error occurred";
- res.status(500).json({
- message: "Invalid request data",
- error: errorMessage,
- });
- }
- } else {
- return res.status(405).json({ message: "Method not allowed" });
- }
-}
+ return response;
+ },
+ }),
+});
diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.ts
index b46c22212f..5c30ccae8c 100644
--- a/web/src/pages/api/public/ingestion.ts
+++ b/web/src/pages/api/public/ingestion.ts
@@ -13,6 +13,8 @@ import {
type TraceUpsertEventType,
type EventBodyType,
EventName,
+ LangfuseNotFoundError,
+ InternalServerError,
} from "@langfuse/shared";
import { type ApiAccessScope } from "@/src/features/public-api/server/types";
import { persistEventMiddleware } from "@/src/server/api/services/event-service";
@@ -401,37 +403,79 @@ export const handleBatchResult = (
return res.status(207).send({ errors: returnedErrors, successes });
};
+/**
+ * Handle single event which is usually send via /ingestion endpoint. Returns errors and results via `res` directly.
+ *
+ * Use `parseSingleTypedIngestionApiResponse` for a typed version of this function that throws `BaseError`.
+ */
export const handleSingleIngestionObject = (
errors: Array<{ id: string; error: unknown }>,
results: Array<{ id: string; result: unknown }>,
res: NextApiResponse,
) => {
- const unknownErrors = errors.map((error) => error.error);
+ try {
+ // use method untyped for backwards compatibility
+ const parsedResult = parseSingleTypedIngestionApiResponse(errors, results);
- const badRequestErrors = getBadRequestError(unknownErrors);
- if (badRequestErrors.length > 0) {
- console.log("Bad request errors", badRequestErrors);
- return res.status(400).json({
- message: "Invalid request data",
- errors: badRequestErrors.map((error) => error.message),
+ return res.status(200).json(parsedResult);
+ } catch (error) {
+ if (error instanceof BaseError) {
+ return res.status(error.httpCode).json({
+ message: error.message,
+ error: error.name,
+ });
+ }
+ return res.status(500).json({
+ message: "Internal Server Error",
+ error:
+ error instanceof Error ? error.message : "An unknown error occurred",
});
}
+};
+/**
+ * Parses the response from the ingestion batch API event processor and throws an error of `BaserError` if the response is not as expected.
+ *
+ * @param errors - Array of errors from `handleBatch()`
+ * @param results - Array of results from `handleBatch()`
+ * @param object - Zod object to parse the result, if not provided, the result is returned as is without parsing
+ * @returns - Parsed result
+ * @throws - Throws an error of type `BaseError` if there are errors in the arguments
+ */
+
+export const parseSingleTypedIngestionApiResponse = <T extends z.ZodTypeAny>(
+ errors: Array<{ id: string; error: unknown }>,
+ results: Array<{ id: string; result: unknown }>,
+ object?: T,
+): T extends z.ZodTypeAny ? z.infer<T> : unknown => {
+ const unknownErrors = errors.map((error) => error.error);
+ const badRequestErrors = getBadRequestError(unknownErrors);
+ if (badRequestErrors.length > 0) {
+ throw new InvalidRequestError(badRequestErrors[0].message);
+ }
const ResourceNotFoundError = getResourceNotFoundError(unknownErrors);
if (ResourceNotFoundError.length > 0) {
- return res.status(404).json({
- message: "Resource not found",
- errors: ResourceNotFoundError.map((error) => error.message),
- });
+ throw new LangfuseNotFoundError(ResourceNotFoundError[0].message);
}
-
if (errors.length > 0) {
- console.log("Error processing events", unknownErrors);
- return res.status(500).json({
- errors: ["Internal Server Error"],
- });
+ throw new InternalServerError("Internal Server Error");
+ }
+
+ if (results.length === 0) {
+ throw new InternalServerError("No results returned");
+ }
+
+ if (object === undefined) {
+ return results[0].result as T extends z.ZodTypeAny ? z.infer<T> : unknown;
+ }
+
+ const parsedObj = object.safeParse(results[0].result);
+ if (!parsedObj.success) {
+ console.error("Error parsing response", parsedObj.error);
+ Sentry.captureException(parsedObj.error);
}
- return res.status(200).send(results.length > 0 ? results[0]?.result : {});
+ // should not fail in prod but just log an exception, see above
+ return results[0].result as z.infer<T>;
};
// cleans NULL characters from the event
diff --git a/web/src/pages/api/public/metrics/daily.ts b/web/src/pages/api/public/metrics/daily.ts
index 1521fff801..ddb13a195e 100644
--- a/web/src/pages/api/public/metrics/daily.ts
+++ b/web/src/pages/api/public/metrics/daily.ts
@@ -1,196 +1,145 @@
-import { type NextApiRequest, type NextApiResponse } from "next";
-import { z } from "zod";
-import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
import { Prisma, prisma } from "@langfuse/shared/src/db";
-import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
-import { paginationZod } from "@langfuse/shared";
-import { isPrismaException } from "@/src/utils/exceptions";
-import { stringDate } from "@langfuse/shared";
+import {
+ GetMetricsDailyV1Query,
+ GetMetricsDailyV1Response,
+} from "@/src/features/public-api/types/metrics";
+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
+import { type z } from "zod";
-const GetUsageSchema = z.object({
- ...paginationZod,
- traceName: z.string().nullish(),
- userId: z.string().nullish(),
- tags: z.union([z.array(z.string()), z.string()]).nullish(),
- fromTimestamp: stringDate,
- toTimestamp: stringDate,
-});
-
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- await runMiddleware(req, res, cors);
-
- try {
- if (req.method === "GET") {
- // CHECK AUTH
- const authCheck = await verifyAuthHeaderAndReturnScope(
- req.headers.authorization,
- );
- if (!authCheck.validKey)
- return res.status(401).json({
- message: authCheck.error,
- });
- // END CHECK AUTH
-
- if (authCheck.scope.accessLevel !== "all") {
- return res.status(401).json({
- message: "Access denied - need to use basic auth with secret key",
- });
- }
- const obj = GetUsageSchema.parse(req.query); // uses query and not body
-
- const traceNameCondition = obj.traceName
- ? Prisma.sql`AND t.name = ${obj.traceName}`
+export default withMiddlewares({
+ GET: createAuthedAPIRoute({
+ name: "Get Daily Metrics",
+ querySchema: GetMetricsDailyV1Query,
+ responseSchema: GetMetricsDailyV1Response,
+ fn: async ({ query, auth }) => {
+ const traceNameCondition = query.traceName
+ ? Prisma.sql`AND t.name = ${query.traceName}`
: Prisma.empty;
- const userCondition = obj.userId
- ? Prisma.sql`AND t."user_id" = ${obj.userId}`
+ const userCondition = query.userId
+ ? Prisma.sql`AND t."user_id" = ${query.userId}`
: Prisma.empty;
- const tagsCondition = obj.tags
+ const tagsCondition = query.tags
? Prisma.sql`AND ARRAY[${Prisma.join(
- (Array.isArray(obj.tags) ? obj.tags : [obj.tags]).map(
+ (Array.isArray(query.tags) ? query.tags : [query.tags]).map(
(v) => Prisma.sql`${v}`,
),
", ",
)}] <@ t."tags"`
: Prisma.empty;
- const fromTimestampCondition = obj.fromTimestamp
- ? Prisma.sql`AND t."timestamp" >= ${obj.fromTimestamp}::timestamp with time zone at time zone 'UTC'`
+ const fromTimestampCondition = query.fromTimestamp
+ ? Prisma.sql`AND t."timestamp" >= ${query.fromTimestamp}::timestamp with time zone at time zone 'UTC'`
: Prisma.empty;
- const toTimestampCondition = obj.toTimestamp
- ? Prisma.sql`AND t."timestamp" < ${obj.toTimestamp}::timestamp with time zone at time zone 'UTC'`
+ const toTimestampCondition = query.toTimestamp
+ ? Prisma.sql`AND t."timestamp" < ${query.toTimestamp}::timestamp with time zone at time zone 'UTC'`
: Prisma.empty;
- const usage = await prisma.$queryRaw`
- WITH model_usage AS (
+ const [usage, totalItemsRes] = await Promise.all([
+ prisma.$queryRaw`
+ WITH model_usage AS (
+ SELECT
+ DATE_TRUNC('DAY', o.start_time) "date",
+ o.model,
+ count(distinct o.id)::integer as "countObservations",
+ count(distinct t.id)::integer as "countTraces",
+ SUM(o.prompt_tokens) "inputUsage",
+ SUM(o.completion_tokens) "outputUsage",
+ SUM(o.total_tokens) "totalUsage",
+ COALESCE(SUM(o.calculated_total_cost), 0)::DOUBLE PRECISION as "totalCost"
+ FROM
+ traces t
+ LEFT JOIN observations_view o ON o.trace_id = t.id AND o.project_id = t.project_id
+ WHERE o.start_time IS NOT NULL
+ AND t.project_id = ${auth.scope.projectId}
+ ${traceNameCondition}
+ ${userCondition}
+ ${tagsCondition}
+ ${fromTimestampCondition}
+ ${toTimestampCondition}
+ GROUP BY
+ 1,
+ 2
+ ORDER BY
+ 1,
+ 2
+ ),
+ daily_model_usage AS (
+ SELECT
+ "date",
+ json_agg(json_build_object('model',
+ model,
+ 'inputUsage',
+ "inputUsage",
+ 'outputUsage',
+ "outputUsage",
+ 'totalUsage',
+ "totalUsage",
+ 'totalCost',
+ "totalCost",
+ 'countObservations',
+ "countObservations",
+ 'countTraces',
+ "countTraces")) daily_usage_json
+ FROM
+ model_usage
+ GROUP BY
+ 1
+ ),
+ daily_stats AS (
+ SELECT
+ DATE_TRUNC('DAY', t.timestamp) "date",
+ count(distinct t.id)::integer count_traces,
+ count(distinct o.id)::integer count_observations,
+ SUM(o.calculated_total_cost)::DOUBLE PRECISION total_cost
+ FROM traces t
+ LEFT JOIN observations_view o ON o.project_id = t.project_id AND t.id = o.trace_id
+ WHERE t.project_id = ${auth.scope.projectId}
+ ${traceNameCondition}
+ ${userCondition}
+ ${tagsCondition}
+ ${fromTimestampCondition}
+ ${toTimestampCondition}
+ GROUP BY 1
+ )
SELECT
- DATE_TRUNC('DAY',
- o.start_time) "date",
- o.model,
- count(distinct o.id)::integer as "countObservations",
- count(distinct t.id)::integer as "countTraces",
- SUM(o.prompt_tokens) "inputUsage",
- SUM(o.completion_tokens) "outputUsage",
- SUM(o.total_tokens) "totalUsage",
- COALESCE(SUM(o.calculated_total_cost), 0)::DOUBLE PRECISION as "totalCost"
+ TO_CHAR(COALESCE(ds.date, daily_model_usage.date), 'YYYY-MM-DD') AS "date",
+ COALESCE(count_traces, 0) "countTraces",
+ COALESCE(count_observations, 0) "countObservations",
+ COALESCE(total_cost, 0) "totalCost",
+ COALESCE(daily_usage_json, '[]'::JSON) usage
FROM
- traces t
- LEFT JOIN observations_view o ON o.trace_id = t.id AND o.project_id = t.project_id
- WHERE o.start_time IS NOT NULL
- AND t.project_id = ${authCheck.scope.projectId}
- ${traceNameCondition}
- ${userCondition}
- ${tagsCondition}
- ${fromTimestampCondition}
- ${toTimestampCondition}
- GROUP BY
- 1,
- 2
+ daily_stats ds
+ FULL OUTER JOIN
+ daily_model_usage ON daily_model_usage.date = ds.date
ORDER BY
- 1,
- 2
- ),
- daily_model_usage AS (
+ 1 DESC
+ LIMIT ${query.limit} OFFSET ${(query.page - 1) * query.limit}
+ `,
+ prisma.$queryRaw<{ count: number }[]>`
SELECT
- "date",
- json_agg(json_build_object('model',
- model,
- 'inputUsage',
- "inputUsage",
- 'outputUsage',
- "outputUsage",
- 'totalUsage',
- "totalUsage",
- 'totalCost',
- "totalCost",
- 'countObservations',
- "countObservations",
- 'countTraces',
- "countTraces")) daily_usage_json
- FROM
- model_usage
- GROUP BY
- 1
- ),
- daily_stats AS (
- SELECT
- DATE_TRUNC('DAY', t.timestamp) "date",
- count(distinct t.id)::integer count_traces,
- count(distinct o.id)::integer count_observations,
- SUM(o.calculated_total_cost)::DOUBLE PRECISION total_cost
+ COUNT(DISTINCT DATE_TRUNC('DAY', t.timestamp))::integer
FROM traces t
- LEFT JOIN observations_view o ON o.project_id = t.project_id AND t.id = o.trace_id
- WHERE t.project_id = ${authCheck.scope.projectId}
+ WHERE t.project_id = ${auth.scope.projectId}
${traceNameCondition}
${userCondition}
${tagsCondition}
${fromTimestampCondition}
${toTimestampCondition}
- GROUP BY 1
- )
- SELECT
- TO_CHAR(COALESCE(ds.date, daily_model_usage.date), 'YYYY-MM-DD') AS "date",
- COALESCE(count_traces, 0) "countTraces",
- COALESCE(count_observations, 0) "countObservations",
- COALESCE(total_cost, 0) "totalCost",
- COALESCE(daily_usage_json, '[]'::JSON) usage
- FROM
- daily_stats ds
- FULL OUTER JOIN
- daily_model_usage ON daily_model_usage.date = ds.date
- ORDER BY
- 1 DESC
- LIMIT ${obj.limit} OFFSET ${(obj.page - 1) * obj.limit}
- `;
-
- const totalItemsRes = await prisma.$queryRaw<{ count: number }[]>`
- SELECT
- COUNT(DISTINCT DATE_TRUNC('DAY', t.timestamp))::integer
- FROM traces t
- WHERE t.project_id = ${authCheck.scope.projectId}
- ${traceNameCondition}
- ${userCondition}
- ${tagsCondition}
- ${fromTimestampCondition}
- ${toTimestampCondition}
- `;
+ `,
+ ]);
- const totalItems =
- totalItemsRes[0] !== undefined ? totalItemsRes[0].count : 0;
+ const totalItems = totalItemsRes[0]?.count ?? 0;
- return res.status(200).json({
- data: usage,
+ return {
+ // cannot use type warnings due to query raw, covered by tests
+ data: usage as z.infer<typeof GetMetricsDailyV1Response>["data"],
meta: {
- page: obj.page,
- limit: obj.limit,
+ page: query.page,
+ limit: query.limit,
totalItems,
- totalPages: Math.ceil(totalItems / obj.limit),
+ totalPages: Math.ceil(totalItems / query.limit),
},
- });
- } else {
- console.error(req.method, req.body);
- return res.status(405).json({ message: "Method not allowed" });
- }
- } catch (error: unknown) {
- console.error(error);
- if (isPrismaException(error)) {
- return res.status(500).json({
- message: "Error processing request",
- error: "Internal Server Error",
- });
- }
- if (error instanceof z.ZodError) {
- return res.status(400).json({
- message: "Invalid request data",
- error: error.errors,
- });
- }
- const errorMessage =
- error instanceof Error ? error.message : "An unknown error occurred";
- res.status(500).json({
- message: "Invalid request data",
- error: errorMessage,
- });
- }
-}
+ };
+ },
+ }),
+});
diff --git a/web/src/pages/api/public/observations/[observationId].ts b/web/src/pages/api/public/observations/[observationId].ts
index d053e128f0..9bfd938a40 100644
--- a/web/src/pages/api/public/observations/[observationId].ts
+++ b/web/src/pages/api/public/observations/[observationId].ts
@@ -1,78 +1,32 @@
-import { type NextApiRequest, type NextApiResponse } from "next";
-import { z } from "zod";
-import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
import { prisma } from "@langfuse/shared/src/db";
-import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
-import { mapUsageOutput } from "@/src/features/public-api/server/outputSchemaConversion";
-import { isPrismaException } from "@/src/utils/exceptions";
+import {
+ GetObservationV1Query,
+ GetObservationV1Response,
+ transformDbToApiObservation,
+} from "@/src/features/public-api/types/observations";
+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
+import { LangfuseNotFoundError } from "@langfuse/shared";
-const GetObservationSchema = z.object({
- observationId: z.string(),
-});
-
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- await runMiddleware(req, res, cors);
-
- if (req.method !== "GET") {
- console.error(req.method, req.body, req.query);
- return res.status(405).json({ message: "Method not allowed" });
- }
-
- try {
- // CHECK AUTH
- const authCheck = await verifyAuthHeaderAndReturnScope(
- req.headers.authorization,
- );
- if (!authCheck.validKey)
- return res.status(401).json({
- message: authCheck.error,
- });
- // END CHECK AUTH
- console.log("Trying to get observation:", req.body, req.query);
-
- const { observationId } = GetObservationSchema.parse(req.query);
-
- // CHECK ACCESS SCOPE
- if (authCheck.scope.accessLevel !== "all") {
- return res.status(401).json({
- message: "Access denied - need to use basic auth with secret key",
- });
- }
- // END CHECK ACCESS SCOPE
-
- const observation = await prisma.observationView.findFirst({
- where: {
- id: observationId,
- projectId: authCheck.scope.projectId,
- },
- });
- if (!observation) {
- return res.status(404).json({
- message: "Observation not found within authorized project",
+export default withMiddlewares({
+ GET: createAuthedAPIRoute({
+ name: "Get Observation",
+ querySchema: GetObservationV1Query,
+ responseSchema: GetObservationV1Response,
+ fn: async ({ query, auth }) => {
+ const { observationId } = query;
+ const observation = await prisma.observationView.findFirst({
+ where: {
+ id: observationId,
+ projectId: auth.scope.projectId,
+ },
});
- }
- return res.status(200).json(mapUsageOutput(observation));
- } catch (error: unknown) {
- console.error(error);
- if (isPrismaException(error)) {
- return res.status(500).json({
- error: "Internal Server Error",
- });
- }
- if (error instanceof z.ZodError) {
- return res.status(400).json({
- message: "Invalid request data",
- error: error.errors,
- });
- }
- const errorMessage =
- error instanceof Error ? error.message : "An unknown error occurred";
- res.status(500).json({
- message: "Invalid request data",
- error: errorMessage,
- });
- }
-}
+ if (!observation) {
+ throw new LangfuseNotFoundError(
+ "Observation not found within authorized project",
+ );
+ }
+ return transformDbToApiObservation(observation);
+ },
+ }),
+});
diff --git a/web/src/pages/api/public/observations/index.ts b/web/src/pages/api/public/observations/index.ts
index 50b3fb4eab..4fb14c0f35 100644
--- a/web/src/pages/api/public/observations/index.ts
+++ b/web/src/pages/api/public/observations/index.ts
@@ -1,190 +1,125 @@
-import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
-import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
-import { mapUsageOutput } from "@/src/features/public-api/server/outputSchemaConversion";
import { prisma } from "@langfuse/shared/src/db";
-import { paginationZod } from "@langfuse/shared";
-import {
- Prisma,
- type PrismaClient,
- type ObservationView,
-} from "@langfuse/shared/src/db";
-import { type NextApiRequest, type NextApiResponse } from "next";
-import { z } from "zod";
-import { isPrismaException } from "@/src/utils/exceptions";
-import { stringDate } from "@langfuse/shared";
-
-const ObservationsGetSchema = z.object({
- ...paginationZod,
- type: z.enum(["GENERATION", "SPAN", "EVENT"]).nullish(),
- name: z.string().nullish(),
- userId: z.string().nullish(),
- traceId: z.string().nullish(),
- parentObservationId: z.string().nullish(),
- fromStartTime: stringDate,
-});
-
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- await runMiddleware(req, res, cors);
-
- if (req.method !== "GET") {
- console.error(req.method, req.body, req.query);
- return res.status(405).json({ message: "Method not allowed" });
- }
-
- try {
- // CHECK AUTH
- const authCheck = await verifyAuthHeaderAndReturnScope(
- req.headers.authorization,
- );
- if (!authCheck.validKey)
- return res.status(401).json({
- message: authCheck.error,
- });
- // END CHECK AUTH
- console.log(
- "trying to get observations, project ",
- authCheck.scope.projectId,
- ", body:",
- JSON.stringify(req.query, null, 2),
- );
-
- if (authCheck.scope.accessLevel !== "all") {
- return res.status(401).json({
- message: "Access denied - need to use basic auth with secret key",
- });
- }
-
- const searchParams = ObservationsGetSchema.parse(req.query);
-
- const [observations, totalObservations] = await getObservation(
- prisma,
- authCheck.scope.projectId,
- searchParams,
- );
- return res.status(200).json({
- data: observations.map(mapUsageOutput),
- meta: {
- page: searchParams.page,
- limit: searchParams.limit,
- totalItems: totalObservations,
- totalPages: Math.ceil(totalObservations / searchParams.limit),
- },
- });
- } catch (error: unknown) {
- console.error(error);
- if (isPrismaException(error)) {
- return res.status(500).json({
- error: "Internal Server Error",
- });
- }
- if (error instanceof z.ZodError) {
- return res.status(400).json({
- message: "Invalid request data",
- error: error.errors,
- });
- }
- const errorMessage =
- error instanceof Error ? error.message : "An unknown error occurred";
- res.status(500).json({
- message: "Invalid request data",
- error: errorMessage,
- });
- }
-}
+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
+import { Prisma, type ObservationView } from "@langfuse/shared/src/db";
-const getObservation = async (
- prisma: PrismaClient,
- authenticatedProjectId: string,
- query: z.infer<typeof ObservationsGetSchema>,
-) => {
- const userIdCondition = query.userId
- ? Prisma.sql`AND traces."user_id" = ${query.userId}`
- : Prisma.empty;
-
- const nameCondition = query.name
- ? Prisma.sql`AND o."name" = ${query.name}`
- : Prisma.empty;
-
- const observationTypeCondition = query.type
- ? Prisma.sql`AND o."type" = ${query.type}::"ObservationType"`
- : Prisma.empty;
-
- const traceIdCondition = query.traceId
- ? Prisma.sql`AND o."trace_id" = ${query.traceId}`
- : Prisma.empty;
-
- const parentObservationIdCondition = query.parentObservationId
- ? Prisma.sql`AND o."parent_observation_id" = ${query.parentObservationId}`
- : Prisma.empty;
-
- const fromStartTimeCondition = query.fromStartTime
- ? Prisma.sql`AND o."start_time" >= ${query.fromStartTime}::timestamp with time zone at time zone 'UTC'`
- : Prisma.empty;
-
- const observations = await prisma.$queryRaw<ObservationView[]>`
- SELECT
- o."id",
- o."name",
- o."start_time" AS "startTime",
- o."end_time" AS "endTime",
- o."parent_observation_id" AS "parentObservationId",
- o."type",
- o."metadata",
- o."model",
- o."input",
- o."output",
- o."level",
- o."status_message" AS "statusMessage",
- o."completion_start_time" AS "completionStartTime",
- o."completion_tokens" AS "completionTokens",
- o."prompt_tokens" AS "promptTokens",
- o."total_tokens" AS "totalTokens",
- o."unit" AS "unit",
- o."version",
- o."project_id" AS "projectId",
- o."trace_id" AS "traceId",
- o."modelParameters" AS "modelParameters",
- o."model_id" as "modelId",
- o."input_price" as "inputPrice",
- o."output_price" as "outputPrice",
- o."total_price" as "totalPrice",
- o."calculated_input_cost" as "calculatedInputCost",
- o."calculated_output_cost" as "calculatedOutputCost",
- o."calculated_total_cost" as "calculatedTotalCost",
- o."latency",
- o."prompt_id" as "promptId"
- FROM observations_view o LEFT JOIN traces ON o."trace_id" = traces."id" AND traces."project_id" = o."project_id"
- WHERE o."project_id" = ${authenticatedProjectId}
- ${nameCondition}
- ${userIdCondition}
- ${observationTypeCondition}
- ${traceIdCondition}
- ${parentObservationIdCondition}
- ${fromStartTimeCondition}
- ORDER by o."start_time" DESC
- OFFSET ${(query.page - 1) * query.limit}
- LIMIT ${query.limit}
- `;
- const count = await prisma.$queryRaw<{ count: bigint }[]>`
- SELECT COUNT(*) FROM observations o LEFT JOIN traces ON o."trace_id" = traces."id"
- WHERE o."project_id" = ${authenticatedProjectId}
- ${observationTypeCondition}
- ${nameCondition}
- ${userIdCondition}
- ${traceIdCondition}
- ${parentObservationIdCondition}
- ${fromStartTimeCondition}
- `;
-
- if (count.length !== 1) {
- throw new Error(
- `Unexpected number of results for count query: ${JSON.stringify(count)}`,
- );
- } else {
- return [observations, Number(count[0]?.count)] as const;
- }
-};
+import { InternalServerError } from "@langfuse/shared";
+import {
+ GetObservationsV1Query,
+ GetObservationsV1Response,
+ transformDbToApiObservation,
+} from "@/src/features/public-api/types/observations";
+
+export default withMiddlewares({
+ GET: createAuthedAPIRoute({
+ name: "Get Observations",
+ querySchema: GetObservationsV1Query,
+ responseSchema: GetObservationsV1Response,
+ fn: async ({ query, auth }) => {
+ const userIdCondition = query.userId
+ ? Prisma.sql`AND traces."user_id" = ${query.userId}`
+ : Prisma.empty;
+
+ const nameCondition = query.name
+ ? Prisma.sql`AND o."name" = ${query.name}`
+ : Prisma.empty;
+
+ const observationTypeCondition = query.type
+ ? Prisma.sql`AND o."type" = ${query.type}::"ObservationType"`
+ : Prisma.empty;
+
+ const traceIdCondition = query.traceId
+ ? Prisma.sql`AND o."trace_id" = ${query.traceId}`
+ : Prisma.empty;
+
+ const parentObservationIdCondition = query.parentObservationId
+ ? Prisma.sql`AND o."parent_observation_id" = ${query.parentObservationId}`
+ : Prisma.empty;
+
+ const fromStartTimeCondition = query.fromStartTime
+ ? Prisma.sql`AND o."start_time" >= ${query.fromStartTime}::timestamp with time zone at time zone 'UTC'`
+ : Prisma.empty;
+
+ const toStartTimeCondition = query.toStartTime
+ ? Prisma.sql`AND o."start_time" < ${query.toStartTime}::timestamp with time zone at time zone 'UTC'`
+ : Prisma.empty;
+
+ const observations = await prisma.$queryRaw<ObservationView[]>`
+ SELECT
+ o."id",
+ o."name",
+ o."start_time" AS "startTime",
+ o."end_time" AS "endTime",
+ o."parent_observation_id" AS "parentObservationId",
+ o."type",
+ o."metadata",
+ o."model",
+ o."input",
+ o."output",
+ o."level",
+ o."status_message" AS "statusMessage",
+ o."completion_start_time" AS "completionStartTime",
+ o."completion_tokens" AS "completionTokens",
+ o."prompt_tokens" AS "promptTokens",
+ o."total_tokens" AS "totalTokens",
+ o."unit" AS "unit",
+ o."version",
+ o."project_id" AS "projectId",
+ o."trace_id" AS "traceId",
+ o."modelParameters" AS "modelParameters",
+ o."model_id" as "modelId",
+ o."input_price" as "inputPrice",
+ o."output_price" as "outputPrice",
+ o."total_price" as "totalPrice",
+ o."calculated_input_cost" as "calculatedInputCost",
+ o."calculated_output_cost" as "calculatedOutputCost",
+ o."calculated_total_cost" as "calculatedTotalCost",
+ o."latency",
+ o."prompt_id" as "promptId",
+ o."created_at" as "createdAt",
+ o."updated_at" as "updatedAt",
+ o."time_to_first_token" as "timeToFirstToken"
+ FROM observations_view o LEFT JOIN traces ON o."trace_id" = traces."id" AND traces."project_id" = o."project_id"
+ WHERE o."project_id" = ${auth.scope.projectId}
+ ${nameCondition}
+ ${userIdCondition}
+ ${observationTypeCondition}
+ ${traceIdCondition}
+ ${parentObservationIdCondition}
+ ${fromStartTimeCondition}
+ ${toStartTimeCondition}
+ ORDER by o."start_time" DESC
+ OFFSET ${(query.page - 1) * query.limit}
+ LIMIT ${query.limit}
+ `;
+ const countRes = await prisma.$queryRaw<{ count: bigint }[]>`
+ SELECT COUNT(*) FROM observations o LEFT JOIN traces ON o."trace_id" = traces."id"
+ WHERE o."project_id" = ${auth.scope.projectId}
+ ${observationTypeCondition}
+ ${nameCondition}
+ ${userIdCondition}
+ ${traceIdCondition}
+ ${parentObservationIdCondition}
+ ${fromStartTimeCondition}
+ ${toStartTimeCondition}
+ `;
+ if (countRes.length !== 1) {
+ throw new InternalServerError("Unexpected totalItems result");
+ }
+ const totalItems = Number(countRes[0].count);
+
+ console.log(observations);
+
+ return {
+ data: observations.map(transformDbToApiObservation),
+ meta: {
+ page: query.page,
+ limit: query.limit,
+ totalItems,
+ totalPages: Math.ceil(totalItems / query.limit),
+ },
+ };
+ },
+ }),
+});
diff --git a/web/src/pages/api/public/score-configs.ts b/web/src/pages/api/public/score-configs/index.ts
similarity index 100%
rename from web/src/pages/api/public/score-configs.ts
rename to web/src/pages/api/public/score-configs/index.ts
diff --git a/web/src/pages/api/public/scores.ts b/web/src/pages/api/public/scores/index.ts
similarity index 90%
rename from web/src/pages/api/public/scores.ts
rename to web/src/pages/api/public/scores/index.ts
index 1c3d96a843..e9eab0db62 100644
--- a/web/src/pages/api/public/scores.ts
+++ b/web/src/pages/api/public/scores/index.ts
@@ -4,7 +4,7 @@ import { eventTypes, ingestionBatchEvent } from "@langfuse/shared";
import { v4 } from "uuid";
import {
handleBatch,
- handleSingleIngestionObject,
+ parseSingleTypedIngestionApiResponse,
} from "@/src/pages/api/public/ingestion";
import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
@@ -21,7 +21,7 @@ export default withMiddlewares({
name: "Create Score",
bodySchema: PostScoresBody,
responseSchema: PostScoresResponse,
- fn: async ({ body, auth, req, res }) => {
+ fn: async ({ body, auth, req }) => {
const event = {
id: v4(),
type: eventTypes.SCORE_CREATE,
@@ -34,7 +34,12 @@ export default withMiddlewares({
req,
auth,
);
- handleSingleIngestionObject(result.errors, result.results, res);
+ const response = parseSingleTypedIngestionApiResponse(
+ result.errors,
+ result.results,
+ PostScoresResponse,
+ );
+ return response;
},
}),
GET: createAuthedAPIRoute({
@@ -49,6 +54,7 @@ export default withMiddlewares({
userId,
name,
fromTimestamp,
+ toTimestamp,
source,
operator,
value,
@@ -72,6 +78,9 @@ export default withMiddlewares({
const fromTimestampCondition = fromTimestamp
? Prisma.sql`AND s."timestamp" >= ${fromTimestamp}::timestamp with time zone at time zone 'UTC'`
: Prisma.empty;
+ const toTimestampCondition = toTimestamp
+ ? Prisma.sql`AND s."timestamp" < ${toTimestamp}::timestamp with time zone at time zone 'UTC'`
+ : Prisma.empty;
const sourceCondition = source
? Prisma.sql`AND s."source" = ${source}`
: Prisma.empty;
@@ -110,6 +119,7 @@ export default withMiddlewares({
${nameCondition}
${sourceCondition}
${fromTimestampCondition}
+ ${toTimestampCondition}
${valueCondition}
${scoreIdCondition}
ORDER BY s."timestamp" DESC
@@ -128,6 +138,7 @@ export default withMiddlewares({
${nameCondition}
${sourceCondition}
${fromTimestampCondition}
+ ${toTimestampCondition}
${valueCondition}
${scoreIdCondition}
`,
diff --git a/web/src/pages/api/public/sessions/[sessionId].ts b/web/src/pages/api/public/sessions/[sessionId].ts
index 4ac3f0ba32..28b93bd31a 100644
--- a/web/src/pages/api/public/sessions/[sessionId].ts
+++ b/web/src/pages/api/public/sessions/[sessionId].ts
@@ -1,84 +1,42 @@
-import { type NextApiRequest, type NextApiResponse } from "next";
-import { z } from "zod";
-import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
import { prisma } from "@langfuse/shared/src/db";
-import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
-import { isPrismaException } from "@/src/utils/exceptions";
-
-const GetSessionSchema = z.object({
- sessionId: z.string(),
-});
-
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- await runMiddleware(req, res, cors);
-
- if (req.method !== "GET") {
- console.error(req.method, req.body, req.query);
- return res.status(405).json({ message: "Method not allowed" });
- }
-
- try {
- // CHECK AUTH
- const authCheck = await verifyAuthHeaderAndReturnScope(
- req.headers.authorization,
- );
- if (!authCheck.validKey)
- return res.status(401).json({
- message: authCheck.error,
- });
- // END CHECK AUTH
- console.log("Trying to get session:", req.body, req.query);
-
- const { sessionId } = GetSessionSchema.parse(req.query);
-
- // CHECK ACCESS SCOPE
- if (authCheck.scope.accessLevel !== "all") {
- return res.status(401).json({
- message: "Access denied - need to use basic auth with secret key",
- });
- }
- // END CHECK ACCESS SCOPE
-
- const session = await prisma.traceSession.findUnique({
- where: {
- id_projectId: {
- id: sessionId,
- projectId: authCheck.scope.projectId,
+import {
+ GetSessionV1Query,
+ GetSessionV1Response,
+} from "@/src/features/public-api/types/sessions";
+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
+import { LangfuseNotFoundError } from "@langfuse/shared";
+
+export default withMiddlewares({
+ GET: createAuthedAPIRoute({
+ name: "Get Session",
+ querySchema: GetSessionV1Query,
+ responseSchema: GetSessionV1Response,
+ fn: async ({ query, auth }) => {
+ const { sessionId } = query;
+
+ const session = await prisma.traceSession.findUnique({
+ where: {
+ id_projectId: {
+ id: sessionId,
+ projectId: auth.scope.projectId,
+ },
+ },
+ select: {
+ id: true,
+ createdAt: true,
+ projectId: true,
+ traces: true,
},
- },
- include: {
- traces: true,
- },
- });
-
- if (!session) {
- return res.status(404).json({
- message: "Session not found within authorized project",
});
- }
- return res.status(200).json(session);
- } catch (error: unknown) {
- console.error(error);
- if (isPrismaException(error)) {
- return res.status(500).json({
- error: "Internal Server Error",
- });
- }
- if (error instanceof z.ZodError) {
- return res.status(400).json({
- message: "Invalid request data",
- error: error.errors,
- });
- }
- const errorMessage =
- error instanceof Error ? error.message : "An unknown error occurred";
- res.status(500).json({
- message: "Invalid request data",
- error: errorMessage,
- });
- }
-}
+ if (!session) {
+ throw new LangfuseNotFoundError(
+ "Session not found within authorized project",
+ );
+ }
+
+ return session;
+ },
+ }),
+});
diff --git a/web/src/pages/api/public/sessions/index.ts b/web/src/pages/api/public/sessions/index.ts
new file mode 100644
index 0000000000..250782ccf5
--- /dev/null
+++ b/web/src/pages/api/public/sessions/index.ts
@@ -0,0 +1,56 @@
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ GetSessionsV1Query,
+ GetSessionsV1Response,
+} from "@/src/features/public-api/types/sessions";
+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
+
+export default withMiddlewares({
+ GET: createAuthedAPIRoute({
+ name: "Get Sessions",
+ querySchema: GetSessionsV1Query,
+ responseSchema: GetSessionsV1Response,
+ fn: async ({ query, auth }) => {
+ const { fromTimestamp, toTimestamp, limit, page } = query;
+
+ const sessions = await prisma.traceSession.findMany({
+ select: {
+ id: true,
+ createdAt: true,
+ projectId: true,
+ },
+ where: {
+ projectId: auth.scope.projectId,
+ createdAt: {
+ ...(fromTimestamp && { gte: new Date(fromTimestamp) }),
+ ...(toTimestamp && { lt: new Date(toTimestamp) }),
+ },
+ },
+ orderBy: { createdAt: "desc" },
+ take: limit,
+ skip: (page - 1) * limit,
+ });
+
+ const totalItems = await prisma.traceSession.count({
+ where: {
+ projectId: auth.scope.projectId,
+ createdAt: {
+ ...(fromTimestamp && { gte: new Date(fromTimestamp) }),
+ ...(toTimestamp && { lt: new Date(toTimestamp) }),
+ },
+ },
+ });
+
+ return {
+ data: sessions,
+ meta: {
+ totalItems,
+ totalPages: Math.ceil(totalItems / limit),
+ page,
+ limit,
+ },
+ };
+ },
+ }),
+});
diff --git a/web/src/pages/api/public/spans.ts b/web/src/pages/api/public/spans.ts
index 3173fa04b3..5d4726077e 100644
--- a/web/src/pages/api/public/spans.ts
+++ b/web/src/pages/api/public/spans.ts
@@ -1,151 +1,47 @@
-import { type NextApiRequest, type NextApiResponse } from "next";
-import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
-import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
-import { v4 } from "uuid";
-import { ResourceNotFoundError } from "../../../utils/exceptions";
import {
- LegacySpanPatchSchema,
- LegacySpanPostSchema,
- eventTypes,
- ingestionBatchEvent,
-} from "@langfuse/shared";
+ PatchSpansV1Body,
+ PatchSpansV1Response,
+ PostSpansV1Body,
+ PostSpansV1Response,
+ transformLegacySpanPatchToIngestionBatch,
+ transformLegacySpanPostToIngestionBatch,
+} from "@/src/features/public-api/types/spans";
+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
import {
handleBatch,
- handleSingleIngestionObject,
+ parseSingleTypedIngestionApiResponse,
} from "@/src/pages/api/public/ingestion";
-import { z } from "zod";
-import { isPrismaException } from "@/src/utils/exceptions";
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- await runMiddleware(req, res, cors);
-
- // CHECK AUTH
- const authCheck = await verifyAuthHeaderAndReturnScope(
- req.headers.authorization,
- );
- if (!authCheck.validKey)
- return res.status(401).json({
- message: authCheck.error,
- });
- // END CHECK AUTH
-
- // POST endpoint defined for backwards compatibility only. Spans should be created via the ingestion endpoint
- if (req.method === "POST") {
- try {
- console.log(
- "Trying to generate span, project ",
- authCheck.scope.projectId,
- ", body:",
- JSON.stringify(req.body, null, 2),
- );
-
- const convertToObservation = (
- span: z.infer<typeof LegacySpanPostSchema>,
- ) => {
- return {
- ...span,
- type: "SPAN",
- };
- };
-
- const event = {
- id: v4(),
- type: eventTypes.OBSERVATION_CREATE,
- timestamp: new Date().toISOString(),
- body: convertToObservation(LegacySpanPostSchema.parse(req.body)),
- };
-
- const result = await handleBatch(
- ingestionBatchEvent.parse([event]),
- {},
- req,
- authCheck,
+export default withMiddlewares({
+ POST: createAuthedAPIRoute({
+ name: "Create Span (Legacy)",
+ bodySchema: PostSpansV1Body,
+ responseSchema: PostSpansV1Response,
+ fn: async ({ body, auth, req }) => {
+ const ingestionBatch = transformLegacySpanPostToIngestionBatch(body);
+ const result = await handleBatch(ingestionBatch, {}, req, auth);
+ const response = parseSingleTypedIngestionApiResponse(
+ result.errors,
+ result.results,
+ PostSpansV1Response,
);
- handleSingleIngestionObject(result.errors, result.results, res);
- } catch (error: unknown) {
- if (isPrismaException(error)) {
- return res.status(500).json({
- error: "Internal Server Error",
- });
- }
- if (error instanceof z.ZodError) {
- return res.status(400).json({
- message: "Invalid request data",
- error: error.errors,
- });
- }
- const errorMessage =
- error instanceof Error ? error.message : "An unknown error occurred";
- console.error(error, req.body);
- res.status(500).json({
- message: "Invalid request data",
- error: errorMessage,
- });
- }
- } else if (req.method === "PATCH") {
- try {
- console.log(
- "Trying to update span, project ",
- authCheck.scope.projectId,
- ", body:",
- JSON.stringify(req.body, null, 2),
+ return response;
+ },
+ }),
+ PATCH: createAuthedAPIRoute({
+ name: "Update Span (Legacy)",
+ bodySchema: PatchSpansV1Body,
+ responseSchema: PatchSpansV1Response,
+ fn: async ({ body, auth, req }) => {
+ const ingestionBatch = transformLegacySpanPatchToIngestionBatch(body);
+ const result = await handleBatch(ingestionBatch, {}, req, auth);
+ const response = parseSingleTypedIngestionApiResponse(
+ result.errors,
+ result.results,
+ PatchSpansV1Response,
);
-
- const convertToObservation = (
- span: z.infer<typeof LegacySpanPatchSchema>,
- ) => {
- return {
- ...span,
- id: span.spanId,
- type: "SPAN",
- };
- };
-
- const event = {
- id: v4(),
- type: eventTypes.OBSERVATION_UPDATE,
- timestamp: new Date().toISOString(),
- body: convertToObservation(LegacySpanPatchSchema.parse(req.body)),
- };
-
- const result = await handleBatch(
- ingestionBatchEvent.parse([event]),
- {},
- req,
- authCheck,
- );
-
- handleSingleIngestionObject(result.errors, result.results, res);
- } catch (error: unknown) {
- console.error(error);
-
- if (isPrismaException(error)) {
- return res.status(500).json({
- error: "Internal Server Error",
- });
- }
- if (error instanceof z.ZodError) {
- return res.status(400).json({
- message: "Invalid request data",
- error: error.errors,
- });
- }
- if (error instanceof ResourceNotFoundError) {
- return res.status(404).json({
- message: "Span not found",
- });
- }
- const errorMessage =
- error instanceof Error ? error.message : "An unknown error occurred";
- res.status(500).json({
- message: "Invalid request data",
- error: errorMessage,
- });
- }
- } else {
- res.status(405).json({ message: "Method not allowed" });
- }
-}
+ return response;
+ },
+ }),
+});
diff --git a/web/src/pages/api/public/traces.ts b/web/src/pages/api/public/traces.ts
deleted file mode 100644
index ea2a0dbb64..0000000000
--- a/web/src/pages/api/public/traces.ts
+++ /dev/null
@@ -1,217 +0,0 @@
-import { type NextApiRequest, type NextApiResponse } from "next";
-import { z } from "zod";
-import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
-import { prisma } from "@langfuse/shared/src/db";
-import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
-import { Prisma, type Trace } from "@langfuse/shared/src/db";
-import { paginationZod } from "@langfuse/shared";
-import {
- handleBatch,
- handleSingleIngestionObject,
-} from "@/src/pages/api/public/ingestion";
-import { TraceBody, eventTypes, stringDate } from "@langfuse/shared";
-import { v4 } from "uuid";
-import { telemetry } from "@/src/features/telemetry";
-import { tracesTableCols, orderBy, orderByToPrismaSql } from "@langfuse/shared";
-import { isPrismaException } from "@/src/utils/exceptions";
-
-const GetTracesSchema = z.object({
- ...paginationZod,
- userId: z.string().nullish(),
- name: z.string().nullish(),
- tags: z.union([z.array(z.string()), z.string()]).nullish(),
- sessionId: z.string().nullish(),
- fromTimestamp: stringDate,
- orderBy: z
- .string() // orderBy=timestamp.asc
- .nullish()
- .transform((v) => {
- if (!v) return null;
- const [column, order] = v.split(".");
- return { column, order: order?.toUpperCase() };
- })
- .pipe(orderBy.nullish()),
-});
-
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- await runMiddleware(req, res, cors);
-
- // CHECK AUTH
- const authCheck = await verifyAuthHeaderAndReturnScope(
- req.headers.authorization,
- );
- if (!authCheck.validKey)
- return res.status(401).json({
- message: authCheck.error,
- });
- // END CHECK AUTH
-
- try {
- // POST endpoint defined for backwards compatibility only. Traces should be created via the ingestion endpoint
- if (req.method === "POST") {
- console.log(
- "Trying to create trace, project ",
- authCheck.scope.projectId,
- ", body:",
- JSON.stringify(req.body, null, 2),
- );
-
- if (authCheck.scope.accessLevel !== "all") {
- return res.status(401).json({
- message: "Access denied - need to use basic auth with secret key",
- });
- }
-
- const body = TraceBody.parse(req.body);
-
- await telemetry();
-
- const event = {
- id: v4(),
- type: eventTypes.TRACE_CREATE,
- timestamp: new Date().toISOString(),
- body: body,
- };
-
- const result = await handleBatch([event], {}, req, authCheck);
- handleSingleIngestionObject(result.errors, result.results, res);
- } else if (req.method === "GET") {
- if (authCheck.scope.accessLevel !== "all") {
- return res.status(401).json({
- message: "Access denied - need to use basic auth with secret key",
- });
- }
-
- const obj = GetTracesSchema.parse(req.query); // uses query and not body
-
- const skipValue = (obj.page - 1) * obj.limit;
- const userCondition = obj.userId
- ? Prisma.sql`AND t."user_id" = ${obj.userId}`
- : Prisma.empty;
- const nameCondition = obj.name
- ? Prisma.sql`AND t."name" = ${obj.name}`
- : Prisma.empty;
- const tagsCondition = obj.tags
- ? Prisma.sql`AND ARRAY[${Prisma.join(
- (Array.isArray(obj.tags) ? obj.tags : [obj.tags]).map(
- (v) => Prisma.sql`${v}`,
- ),
- ", ",
- )}] <@ t."tags"`
- : Prisma.empty;
- const sessionCondition = obj.sessionId
- ? Prisma.sql`AND t."session_id" = ${obj.sessionId}`
- : Prisma.empty;
- const fromTimestampCondition = obj.fromTimestamp
- ? Prisma.sql`AND t."timestamp" >= ${obj.fromTimestamp}::timestamp with time zone at time zone 'UTC'`
- : Prisma.empty;
-
- const orderByCondition = orderByToPrismaSql(
- obj.orderBy ?? null,
- tracesTableCols,
- );
-
- const traces = await prisma.$queryRaw<
- Array<Trace & { observations: string[]; scores: string[] }>
- >(Prisma.sql`
- SELECT
- t.id,
- CONCAT('/project/', t.project_id,'/traces/',t.id) as "htmlPath",
- t.timestamp,
- t.name,
- t.input,
- t.output,
- t.project_id as "projectId",
- t.session_id as "sessionId",
- t.metadata,
- t.external_id as "externalId",
- t.user_id as "userId",
- t.release,
- t.version,
- t.public,
- t.tags,
- COALESCE(o."totalCost", 0)::DOUBLE PRECISION AS "totalCost",
- COALESCE(o."latency", 0)::double precision AS "latency",
- COALESCE(o."observations", ARRAY[]::text[]) AS "observations",
- COALESCE(s."scores", ARRAY[]::text[]) AS "scores"
- FROM (
- SELECT *
- FROM "traces" t
- WHERE project_id = ${authCheck.scope.projectId}
- ${fromTimestampCondition}
- ${userCondition}
- ${nameCondition}
- ${tagsCondition}
- ${sessionCondition}
- ${orderByCondition}
- LIMIT ${obj.limit} OFFSET ${skipValue}
- ) AS t
- LEFT JOIN LATERAL (
- SELECT
- SUM(o.calculated_total_cost)::DOUBLE PRECISION AS "totalCost",
- EXTRACT(EPOCH FROM COALESCE(MAX(o."end_time"), MAX(o."start_time"))) - EXTRACT(EPOCH FROM MIN(o."start_time"))::DOUBLE PRECISION AS "latency",
- ARRAY_AGG(DISTINCT o.id) FILTER (WHERE o.id IS NOT NULL) AS "observations"
- FROM "observations_view" AS o
- WHERE o.trace_id = t.id AND o.project_id = ${authCheck.scope.projectId}
- ) AS o ON true
- LEFT JOIN LATERAL (
- SELECT
- ARRAY_AGG(DISTINCT s.id) FILTER (WHERE s.id IS NOT NULL) AS "scores"
- FROM "scores" AS s
- WHERE s.trace_id = t.id AND s.project_id = ${authCheck.scope.projectId}
- ) AS s ON true
- `);
- const totalItems = await prisma.trace.count({
- where: {
- projectId: authCheck.scope.projectId,
- name: obj.name ? obj.name : undefined,
- userId: obj.userId ? obj.userId : undefined,
- sessionId: obj.sessionId ? obj.sessionId : undefined,
- timestamp: obj.fromTimestamp
- ? { gte: new Date(obj.fromTimestamp) }
- : undefined,
- tags: obj.tags
- ? {
- hasEvery: Array.isArray(obj.tags) ? obj.tags : [obj.tags],
- }
- : undefined,
- },
- });
-
- return res.status(200).json({
- data: traces,
- meta: {
- page: obj.page,
- limit: obj.limit,
- totalItems,
- totalPages: Math.ceil(totalItems / obj.limit),
- },
- });
- } else {
- console.error(req.method, req.body);
- return res.status(405).json({ message: "Method not allowed" });
- }
- } catch (error: unknown) {
- console.error(error);
- if (isPrismaException(error)) {
- return res.status(500).json({
- errors: ["Internal Server Error"],
- });
- }
- if (error instanceof z.ZodError) {
- return res.status(400).json({
- message: "Invalid request data",
- error: error.errors,
- });
- }
- const errorMessage =
- error instanceof Error ? error.message : "An unknown error occurred";
- res.status(500).json({
- message: "Invalid request data",
- error: errorMessage,
- });
- }
-}
diff --git a/web/src/pages/api/public/traces/[traceId].ts b/web/src/pages/api/public/traces/[traceId].ts
index 2eeedaa1cb..0b901f7bd5 100644
--- a/web/src/pages/api/public/traces/[traceId].ts
+++ b/web/src/pages/api/public/traces/[traceId].ts
@@ -1,106 +1,68 @@
-import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
-import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
-import { mapUsageOutput } from "@/src/features/public-api/server/outputSchemaConversion";
import { prisma } from "@langfuse/shared/src/db";
-import { isPrismaException } from "@/src/utils/exceptions";
-import { type NextApiRequest, type NextApiResponse } from "next";
-import { z } from "zod";
+import {
+ GetTraceV1Query,
+ GetTraceV1Response,
+} from "@/src/features/public-api/types/traces";
+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
import { filterAndValidateDbScoreList } from "@/src/features/public-api/types/scores";
+import { transformDbToApiObservation } from "@/src/features/public-api/types/observations";
+import { LangfuseNotFoundError } from "@langfuse/shared";
-const GetTraceSchema = z.object({
- traceId: z.string(),
-});
-
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- await runMiddleware(req, res, cors);
-
- if (req.method !== "GET") {
- console.error(req.method, req.body, req.query);
- return res.status(405).json({ message: "Method not allowed" });
- }
+export default withMiddlewares({
+ GET: createAuthedAPIRoute({
+ name: "Get Single Trace",
+ querySchema: GetTraceV1Query,
+ responseSchema: GetTraceV1Response,
+ fn: async ({ query, auth }) => {
+ const { traceId } = query;
- try {
- // CHECK AUTH
- const authCheck = await verifyAuthHeaderAndReturnScope(
- req.headers.authorization,
- );
- if (!authCheck.validKey)
- return res.status(401).json({
- message: authCheck.error,
+ const trace = await prisma.traceView.findFirst({
+ where: {
+ id: traceId,
+ projectId: auth.scope.projectId,
+ },
});
- // END CHECK AUTH
- console.log("Trying to get trace:", req.body, req.query);
- const { traceId } = GetTraceSchema.parse(req.query);
+ if (!trace) {
+ throw new LangfuseNotFoundError(
+ "Trace not found within authorized project",
+ );
+ }
- // CHECK ACCESS SCOPE
- if (authCheck.scope.accessLevel !== "all") {
- return res.status(401).json({
- message: "Access denied - need to use basic auth with secret key",
- });
- }
- // END CHECK ACCESS SCOPE
-
- const trace = await prisma.trace.findFirst({
- where: {
- id: traceId,
- projectId: authCheck.scope.projectId,
- },
- });
+ const [scores, observations] = await Promise.all([
+ prisma.score.findMany({
+ where: {
+ traceId: traceId,
+ projectId: auth.scope.projectId,
+ },
+ orderBy: { timestamp: "desc" },
+ }),
+ prisma.observationView.findMany({
+ where: {
+ traceId: traceId,
+ projectId: auth.scope.projectId,
+ },
+ orderBy: { startTime: "asc" },
+ }),
+ ]);
- if (!trace) {
- return res.status(404).json({
- message: "Trace not found within authorized project",
- });
- }
+ const outObservations = observations.map(transformDbToApiObservation);
+ const validatedScores = filterAndValidateDbScoreList(scores);
- const scores = await prisma.score.findMany({
- where: {
- traceId: traceId,
- projectId: authCheck.scope.projectId,
- },
- });
+ const { duration, ...restOfTrace } = trace;
- const observations = await prisma.observationView.findMany({
- where: {
- traceId: traceId,
- projectId: authCheck.scope.projectId,
- },
- });
-
- const outObservations = observations.map(mapUsageOutput);
-
- return res.status(200).json({
- ...trace,
- scores: filterAndValidateDbScoreList(scores),
- htmlPath: `/project/${authCheck.scope.projectId}/traces/${traceId}`,
- totalCost: outObservations.reduce(
- (acc, obs) => acc + (obs.calculatedTotalCost ?? 0),
- 0,
- ),
- observations: outObservations,
- });
- } catch (error: unknown) {
- console.error(error);
- if (isPrismaException(error)) {
- return res.status(500).json({
- error: "Internal Server Error",
- });
- }
- if (error instanceof z.ZodError) {
- return res.status(400).json({
- message: "Invalid request data",
- error: error.errors,
- });
- }
- const errorMessage =
- error instanceof Error ? error.message : "An unknown error occurred";
- res.status(500).json({
- message: "Invalid request data",
- error: errorMessage,
- });
- }
-}
+ return {
+ ...restOfTrace,
+ scores: validatedScores,
+ htmlPath: `/project/${auth.scope.projectId}/traces/${traceId}`,
+ totalCost: outObservations.reduce(
+ (acc, obs) => acc + (obs.calculatedTotalCost ?? 0),
+ 0,
+ ),
+ latency: duration ?? 0,
+ observations: outObservations,
+ };
+ },
+ }),
+});
diff --git a/web/src/pages/api/public/traces/index.ts b/web/src/pages/api/public/traces/index.ts
new file mode 100644
index 0000000000..58b741f97c
--- /dev/null
+++ b/web/src/pages/api/public/traces/index.ts
@@ -0,0 +1,174 @@
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ PostTracesV1Body,
+ GetTracesV1Query,
+ GetTracesV1Response,
+ PostTracesV1Response,
+} from "@/src/features/public-api/types/traces";
+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
+import { Prisma } from "@langfuse/shared/src/db";
+import {
+ handleBatch,
+ parseSingleTypedIngestionApiResponse,
+} from "@/src/pages/api/public/ingestion";
+import { type Trace, eventTypes } from "@langfuse/shared";
+import { v4 } from "uuid";
+import { telemetry } from "@/src/features/telemetry";
+import { tracesTableCols, orderByToPrismaSql } from "@langfuse/shared";
+
+export default withMiddlewares({
+ POST: createAuthedAPIRoute({
+ name: "Create Trace",
+ bodySchema: PostTracesV1Body,
+ responseSchema: PostTracesV1Response, // Adjust this if you have a specific response schema
+ fn: async ({ body, auth, req }) => {
+ await telemetry();
+
+ const event = {
+ id: v4(),
+ type: eventTypes.TRACE_CREATE,
+ timestamp: new Date().toISOString(),
+ body: body,
+ };
+
+ const result = await handleBatch([event], {}, req, auth);
+ const response = parseSingleTypedIngestionApiResponse(
+ result.errors,
+ result.results,
+ PostTracesV1Response,
+ );
+ return response;
+ },
+ }),
+
+ GET: createAuthedAPIRoute({
+ name: "Get Traces",
+ querySchema: GetTracesV1Query,
+ responseSchema: GetTracesV1Response,
+ fn: async ({ query, auth }) => {
+ const skipValue = (query.page - 1) * query.limit;
+ const userCondition = query.userId
+ ? Prisma.sql`AND t."user_id" = ${query.userId}`
+ : Prisma.empty;
+ const nameCondition = query.name
+ ? Prisma.sql`AND t."name" = ${query.name}`
+ : Prisma.empty;
+ const tagsCondition = query.tags
+ ? Prisma.sql`AND ARRAY[${Prisma.join(
+ (Array.isArray(query.tags) ? query.tags : [query.tags]).map(
+ (v) => Prisma.sql`${v}`,
+ ),
+ ", ",
+ )}] <@ t."tags"`
+ : Prisma.empty;
+ const sessionCondition = query.sessionId
+ ? Prisma.sql`AND t."session_id" = ${query.sessionId}`
+ : Prisma.empty;
+ const fromTimestampCondition = query.fromTimestamp
+ ? Prisma.sql`AND t."timestamp" >= ${query.fromTimestamp}::timestamp with time zone at time zone 'UTC'`
+ : Prisma.empty;
+ const toTimestampCondition = query.toTimestamp
+ ? Prisma.sql`AND t."timestamp" < ${query.toTimestamp}::timestamp with time zone at time zone 'UTC'`
+ : Prisma.empty;
+
+ const orderByCondition = orderByToPrismaSql(
+ query.orderBy ?? null,
+ tracesTableCols,
+ );
+
+ const traces = await prisma.$queryRaw<
+ Array<
+ Trace & {
+ observations: string[];
+ scores: string[];
+ totalCost: number;
+ latency: number;
+ htmlPath: string;
+ }
+ >
+ >(Prisma.sql`
+ SELECT
+ t.id,
+ CONCAT('/project/', t.project_id,'/traces/',t.id) as "htmlPath",
+ t.timestamp,
+ t.name,
+ t.input,
+ t.output,
+ t.project_id as "projectId",
+ t.session_id as "sessionId",
+ t.metadata,
+ t.external_id as "externalId",
+ t.user_id as "userId",
+ t.release,
+ t.version,
+ t.bookmarked,
+ t.created_at as "createdAt",
+ t.updated_at as "updatedAt",
+ t.public,
+ t.tags,
+ COALESCE(o."totalCost", 0)::DOUBLE PRECISION AS "totalCost",
+ COALESCE(o."latency", 0)::double precision AS "latency",
+ COALESCE(o."observations", ARRAY[]::text[]) AS "observations",
+ COALESCE(s."scores", ARRAY[]::text[]) AS "scores"
+ FROM (
+ SELECT *
+ FROM "traces" t
+ WHERE project_id = ${auth.scope.projectId}
+ ${fromTimestampCondition}
+ ${toTimestampCondition}
+ ${userCondition}
+ ${nameCondition}
+ ${tagsCondition}
+ ${sessionCondition}
+ ${orderByCondition}
+ LIMIT ${query.limit} OFFSET ${skipValue}
+ ) AS t
+ LEFT JOIN LATERAL (
+ SELECT
+ SUM(o.calculated_total_cost)::DOUBLE PRECISION AS "totalCost",
+ EXTRACT(EPOCH FROM COALESCE(MAX(o."end_time"), MAX(o."start_time"))) - EXTRACT(EPOCH FROM MIN(o."start_time"))::DOUBLE PRECISION AS "latency",
+ ARRAY_AGG(DISTINCT o.id) FILTER (WHERE o.id IS NOT NULL) AS "observations"
+ FROM "observations_view" AS o
+ WHERE o.trace_id = t.id AND o.project_id = ${auth.scope.projectId}
+ ) AS o ON true
+ LEFT JOIN LATERAL (
+ SELECT
+ ARRAY_AGG(DISTINCT s.id) FILTER (WHERE s.id IS NOT NULL) AS "scores"
+ FROM "scores" AS s
+ WHERE s.trace_id = t.id AND s.project_id = ${auth.scope.projectId}
+ ) AS s ON true
+ `);
+
+ const totalItems = await prisma.trace.count({
+ where: {
+ projectId: auth.scope.projectId,
+ name: query.name ? query.name : undefined,
+ userId: query.userId ? query.userId : undefined,
+ sessionId: query.sessionId ? query.sessionId : undefined,
+ timestamp: {
+ gte: query.fromTimestamp
+ ? new Date(query.fromTimestamp)
+ : undefined,
+ lt: query.toTimestamp ? new Date(query.toTimestamp) : undefined,
+ },
+ tags: query.tags
+ ? {
+ hasEvery: Array.isArray(query.tags) ? query.tags : [query.tags],
+ }
+ : undefined,
+ },
+ });
+
+ return {
+ data: traces,
+ meta: {
+ page: query.page,
+ limit: query.limit,
+ totalItems,
+ totalPages: Math.ceil(totalItems / query.limit),
+ },
+ };
+ },
+ }),
+});
diff --git a/web/src/pages/api/public/users.ts b/web/src/pages/api/public/users.ts
index 96794edb58..0162986313 100644
--- a/web/src/pages/api/public/users.ts
+++ b/web/src/pages/api/public/users.ts
@@ -1,3 +1,8 @@
+/**
+ * LEGACY API, NOT DOCUMENTED AND WILL BE DEPRECATED
+ * THE /metrics/daily endpoint is to be used instead
+ */
+
import { type NextApiRequest, type NextApiResponse } from "next";
import { z } from "zod";
import { cors, runMiddleware } from "@/src/features/public-api/server/cors";