Skip to content

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

move generations endpoint (#303)

Maximilian Deichmanne78f389a7385
diff --git a/fern/server/definition/commons.yml b/fern/server/definition/commons.yml
index 28334893e1..cc5f364447 100644
--- a/fern/server/definition/commons.yml
+++ b/fern/server/definition/commons.yml
@@ -66,10 +66,10 @@ types:
completionStartTime: optional<datetime>
model: optional<string>
modelParameters: optional<map<string, MapValue>>
- prompt: optional<unknown>
+ input: optional<unknown>
version: optional<string>
metadata: optional<unknown>
- completion: optional<string>
+ output: optional<unknown>
promptTokens: integer
completionTokens: integer
totalTokens: integer
diff --git a/fern/server/definition/generations.yml b/fern/server/definition/generations.yml
index d957e4a256..73692537d2 100644
--- a/fern/server/definition/generations.yml
+++ b/fern/server/definition/generations.yml
@@ -16,18 +16,6 @@ service:
path: /generations
request: UpdateGenerationRequest
response: commons.Observation
- get:
- docs: Get a list of generations
- method: GET
- path: /generations
- request:
- name: GetGenerationsRequest
- query-parameters:
- page: optional<integer>
- limit: optional<integer>
- name: optional<string>
- userId: optional<string>
- response: Generations
types:
UpdateGenerationRequest:
@@ -46,7 +34,3 @@ types:
usage: optional<commons.LLMUsage>
level: optional<commons.ObservationLevel>
statusMessage: optional<string>
- Generations:
- properties:
- data: list<commons.Observation>
- meta: pagination.MetaResponse
diff --git a/fern/server/definition/observations.yml b/fern/server/definition/observations.yml
index dcfabf849f..8eee91270b 100644
--- a/fern/server/definition/observations.yml
+++ b/fern/server/definition/observations.yml
@@ -15,3 +15,22 @@ service:
type: string
docs: The unique langfuse identifier of an observation, can be an event, span or generation
response: commons.Observation
+ getMany:
+ docs: Get a list of observations
+ method: GET
+ path: /observations
+ request:
+ name: GetObservationsRequest
+ query-parameters:
+ page: optional<integer>
+ limit: optional<integer>
+ name: optional<string>
+ userId: optional<string>
+ type: optional<string>
+ response: Observations
+
+types:
+ Observations:
+ properties:
+ data: list<commons.Observation>
+ meta: pagination.MetaResponse
diff --git a/generated/openapi-server/openapi.yml b/generated/openapi-server/openapi.yml
index 747887e92c..a4af39b50f 100644
--- a/generated/openapi-server/openapi.yml
+++ b/generated/openapi-server/openapi.yml
@@ -412,43 +412,28 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/UpdateGenerationRequest'
+ /api/public/observations/{observationId}:
get:
- description: Get a list of generations
- operationId: generations_get
+ description: Get a specific observation
+ operationId: observations_get
tags:
- - Generations
+ - Observations
parameters:
- - name: page
- in: query
- required: false
- schema:
- type: integer
- nullable: true
- - name: limit
- in: query
- required: false
- schema:
- type: integer
- nullable: true
- - name: name
- in: query
- required: false
- schema:
- type: string
- nullable: true
- - name: userId
- in: query
- required: false
+ - name: observationId
+ in: path
+ description: >-
+ The unique langfuse identifier of an observation, can be an event,
+ span or generation
+ required: true
schema:
type: string
- nullable: true
responses:
'200':
description: ''
content:
application/json:
schema:
- $ref: '#/components/schemas/Generations'
+ $ref: '#/components/schemas/Observation'
'400':
description: ''
content:
@@ -480,28 +465,50 @@ paths:
schema:
type: string
security: *ref_0
- /api/public/observations/{observationId}:
+ /api/public/observations:
get:
- description: Get a specific observation
- operationId: observations_get
+ description: Get a list of observations
+ operationId: observations_getMany
tags:
- Observations
parameters:
- - name: observationId
- in: path
- description: >-
- The unique langfuse identifier of an observation, can be an event,
- span or generation
- required: true
+ - name: page
+ in: query
+ required: false
+ schema:
+ type: integer
+ nullable: true
+ - name: limit
+ in: query
+ required: false
+ schema:
+ type: integer
+ nullable: true
+ - name: name
+ in: query
+ required: false
+ schema:
+ type: string
+ nullable: true
+ - name: userId
+ in: query
+ required: false
schema:
type: string
+ nullable: true
+ - name: type
+ in: query
+ required: false
+ schema:
+ type: string
+ nullable: true
responses:
'200':
description: ''
content:
application/json:
schema:
- $ref: '#/components/schemas/Observation'
+ $ref: '#/components/schemas/Observations'
'400':
description: ''
content:
@@ -1098,15 +1105,14 @@ components:
additionalProperties:
$ref: '#/components/schemas/MapValue'
nullable: true
- prompt:
+ input:
nullable: true
version:
type: string
nullable: true
metadata:
nullable: true
- completion:
- type: string
+ output:
nullable: true
promptTokens:
type: integer
@@ -1399,8 +1405,8 @@ components:
nullable: true
required:
- generationId
- Generations:
- title: Generations
+ Observations:
+ title: Observations
type: object
properties:
data:
diff --git a/src/__tests__/observations.servertest.ts b/src/__tests__/observations.servertest.ts
new file mode 100644
index 0000000000..82f8164ef9
--- /dev/null
+++ b/src/__tests__/observations.servertest.ts
@@ -0,0 +1,93 @@
+/** @jest-environment node */
+
+import { prisma } from "@/src/server/db";
+import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
+import { v4 as uuidv4 } from "uuid";
+import { type Observation } from "@prisma/client";
+
+describe("/api/public/generations API Endpoint", () => {
+ beforeEach(async () => await pruneDatabase());
+ afterEach(async () => await pruneDatabase());
+
+ it("should create generation after trace", async () => {
+ await pruneDatabase();
+
+ const traceId = uuidv4();
+
+ await prisma.trace.create({
+ data: {
+ 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 prisma.observation.create({
+ data: {
+ id: uuidv4(),
+ traceId: traceId,
+ name: "generation-name",
+ startTime: new Date("2021-01-01T00:00:00.000Z"),
+ endTime: new Date("2021-01-01T00:00:00.000Z"),
+ model: "model-name",
+ modelParameters: { key: "value" },
+ input: { key: "input" },
+ output: { key: "output" },
+ version: "2.0.0",
+ type: "GENERATION",
+ project: {
+ connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },
+ },
+ },
+ });
+
+ const fetchedObservations = await makeAPICall(
+ "GET",
+ "/api/public/observations",
+ undefined,
+ );
+
+ 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" });
+ expect(fetchedObservations.body.data[0]?.output).toEqual({ key: "output" });
+ });
+});
+
+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,
+ )
+ );
+};
+
+type ObservationResponse = {
+ data: Observation[];
+};
diff --git a/src/pages/api/public/generations.ts b/src/pages/api/public/generations.ts
index 97ea2eff34..cc76fed9bc 100644
--- a/src/pages/api/public/generations.ts
+++ b/src/pages/api/public/generations.ts
@@ -1,9 +1,7 @@
import { prisma } from "@/src/server/db";
import {
- type Observation,
ObservationLevel,
ObservationType,
- Prisma,
type PrismaClient,
} from "@prisma/client";
import { type NextApiRequest, type NextApiResponse } from "next";
@@ -14,13 +12,6 @@ import { tokenCount } from "@/src/features/ingest/lib/usage";
import { v4 as uuidv4 } from "uuid";
import { backOff } from "exponential-backoff";
import { RessourceNotFoundError } from "../../../utils/exceptions";
-import { paginationZod } from "@/src/utils/zod";
-
-const GenerationsGetSchema = z.object({
- ...paginationZod,
- name: z.string().nullish(),
- userId: z.string().nullish(),
-});
export const GenerationsCreateSchema = z.object({
id: z.string().nullish(),
@@ -294,59 +285,6 @@ export default async function handler(
});
}
- const errorMessage =
- error instanceof Error ? error.message : "An unknown error occurred";
- res.status(400).json({
- success: false,
- message: "Invalid request data",
- error: errorMessage,
- });
- }
- } else if (req.method === "GET") {
- try {
- console.log(
- "trying to get generation, project ",
- authCheck.scope.projectId,
- ", body:",
- JSON.stringify(req.query, null, 2),
- );
-
- if (authCheck.scope.accessLevel !== "all") {
- return res.status(401).json({
- success: false,
- message:
- "Access denied - need to use basic auth with secret key to GET generations",
- });
- }
-
- const searchParams = GenerationsGetSchema.parse(req.query);
-
- const [generations, totalGenerations] = await getGenerations(
- prisma,
- authCheck.scope.projectId,
- searchParams,
- );
- return res.status(200).json({
- data: generations.map((generation) => {
- const { input, output, ...otherFields } = generation;
- return {
- ...otherFields,
- prompt: input,
- completion:
- output && typeof output === "object" && "completion" in output
- ? output.completion
- : null,
- };
- }),
- meta: {
- page: searchParams.page,
- limit: searchParams.limit,
- totalItems: totalGenerations,
- totalPages: Math.ceil(totalGenerations / searchParams.limit),
- },
- });
- } catch (error: unknown) {
- console.error(error);
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
res.status(400).json({
@@ -360,59 +298,6 @@ export default async function handler(
}
}
-const getGenerations = async (
- prisma: PrismaClient,
- authenticatedProjectId: string,
- query: z.infer<typeof GenerationsGetSchema>,
-) => {
- 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 [observations, count] = await Promise.all([
- prisma.$queryRaw<Observation[]>`
- SELECT
- o.*,
- o."trace_id" AS "traceId",
- o."project_id" AS "projectId",
- o."start_time" AS "startTime",
- o."end_time" AS "endTime",
- o."parent_observation_id" AS "parentObservationId",
- o."status_message" AS "statusMessage",
- o."prompt_tokens" AS "promptTokens",
- o."completion_tokens" AS "completionTokens",
- o."completion_start_time" AS "completionStartTime"
- FROM observations o LEFT JOIN traces ON o."trace_id" = traces."id"
- WHERE o."project_id" = ${authenticatedProjectId}
- AND o."type" = 'GENERATION'
- ${nameCondition}
- ${userIdCondition}
- ORDER by o."start_time" DESC
- OFFSET ${(query.page - 1) * query.limit}
- LIMIT ${query.limit}
- `,
- prisma.$queryRaw<{ count: bigint }[]>`
- SELECT COUNT(*) FROM observations o LEFT JOIN traces ON o."trace_id" = traces."id"
- WHERE o."project_id" = ${authenticatedProjectId}
- AND type = 'GENERATION'
- ${nameCondition}
- ${userIdCondition}
- `,
- ]);
-
- if (!count || 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;
- }
-};
-
const patchGeneration = async (
prisma: PrismaClient,
generationPatch: z.infer<typeof GenerationPatchSchema>,
diff --git a/src/pages/api/public/observations/index.ts b/src/pages/api/public/observations/index.ts
new file mode 100644
index 0000000000..fbdfa51575
--- /dev/null
+++ b/src/pages/api/public/observations/index.ts
@@ -0,0 +1,147 @@
+import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
+import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
+import { prisma } from "@/src/server/db";
+import { paginationZod } from "@/src/utils/zod";
+import { Prisma, type PrismaClient, type Observation } from "@prisma/client";
+import { type NextApiRequest, type NextApiResponse } from "next";
+import { z } from "zod";
+
+const ObservationsGetSchema = z.object({
+ ...paginationZod,
+ type: z.enum(["GENERATION", "SPAN", "EVENT"]).nullish(),
+ name: z.string().nullish(),
+ userId: z.string().nullish(),
+});
+
+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" });
+ }
+
+ // CHECK AUTH
+ const authCheck = await verifyAuthHeaderAndReturnScope(
+ req.headers.authorization,
+ );
+ if (!authCheck.validKey)
+ return res.status(401).json({
+ success: false,
+ message: authCheck.error,
+ });
+ // END CHECK AUTH
+
+ try {
+ 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({
+ success: false,
+ message:
+ "Access denied - need to use basic auth with secret key to GET generations",
+ });
+ }
+
+ const searchParams = ObservationsGetSchema.parse(req.query);
+
+ const [observations, totalObservations] = await getObservation(
+ prisma,
+ authCheck.scope.projectId,
+ searchParams,
+ );
+ console.log(observations);
+ return res.status(200).json({
+ data: observations,
+ meta: {
+ page: searchParams.page,
+ limit: searchParams.limit,
+ totalItems: totalObservations,
+ totalPages: Math.ceil(totalObservations / searchParams.limit),
+ },
+ });
+ } catch (error: unknown) {
+ console.error(error);
+ const errorMessage =
+ error instanceof Error ? error.message : "An unknown error occurred";
+ res.status(400).json({
+ success: false,
+ message: "Invalid request data",
+ error: errorMessage,
+ });
+ }
+}
+
+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 [observations, count] = await Promise.all([
+ prisma.$queryRaw<Observation[]>`
+ 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."version",
+ o."project_id" AS "projectId",
+ o."trace_id" AS "traceId"
+ FROM observations o LEFT JOIN traces ON o."trace_id" = traces."id"
+ WHERE o."project_id" = ${authenticatedProjectId}
+ ${nameCondition}
+ ${userIdCondition}
+ ${observationTypeCondition}
+ ORDER by o."start_time" DESC
+ OFFSET ${(query.page - 1) * query.limit}
+ LIMIT ${query.limit}
+ `,
+ 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}
+ `,
+ ]);
+
+ if (!count || 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;
+ }
+};