🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat: SDK API for observations by id (#4295)
Max Deichmannc29cf3855f93
diff --git a/packages/shared/src/server/repositories/index.ts b/packages/shared/src/server/repositories/index.tsindex f6028dc91c..909a6b2e96 100644--- a/packages/shared/src/server/repositories/index.ts+++ b/packages/shared/src/server/repositories/index.ts@@ -5,4 +5,5 @@ export * from "./types";export * from "./dashboards";export * from "./traces_converters";export * from "./scores_converters";+export * from "./observations_converters";export * from "./clickhouse";diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.tsindex f3b3e5f192..ddbe122229 100644--- a/packages/shared/src/server/repositories/observations.ts+++ b/packages/shared/src/server/repositories/observations.ts@@ -3,7 +3,7 @@ import {parseClickhouseUTCDateTimeFormat,queryClickhouse,} from "./clickhouse";-import { Observation, ObservationLevel } from "@prisma/client";+import { ObservationLevel } from "@prisma/client";import { logger } from "../logger";import { InternalServerError, LangfuseNotFoundError } from "../../errors";import { prisma } from "../../db";@@ -98,6 +98,60 @@ export const getObservationById = async (id: string,projectId: string,fetchWithInputOutput: boolean = false,+) => {+ const records = await getObservationByIdInternal(+ id,+ projectId,+ fetchWithInputOutput,+ );+ const mapped = records.map(convertObservation);++ if (mapped.length === 0) {+ throw new LangfuseNotFoundError(`Observation with id ${id} not found`);+ }++ if (mapped.length > 1) {+ logger.error(+ `Multiple observations found for id ${id} and project ${projectId}`,+ );+ throw new InternalServerError(+ `Multiple observations found for id ${id} and project ${projectId}`,+ );+ }+ return mapped.shift();+};++export const getObservationViewById = async (+ id: string,+ projectId: string,+ fetchWithInputOutput: boolean = false,+) => {+ const records = await getObservationByIdInternal(+ id,+ projectId,+ fetchWithInputOutput,+ );+ const mapped = records.map(convertObservationToView);++ if (mapped.length === 0) {+ throw new LangfuseNotFoundError(`Observation with id ${id} not found`);+ }++ if (mapped.length > 1) {+ logger.error(+ `Multiple observations found for id ${id} and project ${projectId}`,+ );+ throw new InternalServerError(+ `Multiple observations found for id ${id} and project ${projectId}`,+ );+ }+ return mapped.shift();+};++const getObservationByIdInternal = async (+ id: string,+ projectId: string,+ fetchWithInputOutput: boolean = false,) => {const query = `SELECT@@ -134,26 +188,10 @@ export const getObservationById = async (AND project_id = {projectId: String}ORDER BY event_ts descLIMIT 1 by id, project_id`;- const records = await queryClickhouse<ObservationRecordReadType>({+ return await queryClickhouse<ObservationRecordReadType>({query,params: { id, projectId },});-- const mapped = records.map(convertObservation);-- if (mapped.length === 0) {- throw new LangfuseNotFoundError(`Observation with id ${id} not found`);- }-- if (mapped.length > 1) {- logger.error(- `Multiple observations found for id ${id} and project ${projectId}`,- );- throw new InternalServerError(- `Multiple observations found for id ${id} and project ${projectId}`,- );- }- return mapped.shift() as Observation;};export type ObservationTableQuery = {diff --git a/packages/shared/src/server/repositories/observations_converters.ts b/packages/shared/src/server/repositories/observations_converters.tsindex 9c7d80f7de..53c6cb81c1 100644--- a/packages/shared/src/server/repositories/observations_converters.ts+++ b/packages/shared/src/server/repositories/observations_converters.ts@@ -35,7 +35,12 @@ export const convertObservationToView = (export const convertObservation = (record: ObservationRecordReadType,-): Omit<Observation, "internalModel"> => {+): Omit<Observation, "internalModel"> & {+ promptName: string | null;+ promptVersion: number | null;+ latency: number | null;+ timeToFirstToken: number | null;+} => {return {id: record.id,traceId: record.trace_id ?? null,@@ -90,5 +95,15 @@ export const convertObservation = (model: record.provided_model_name ?? null,internalModelId: record.internal_model_id ?? null,unit: "TOKENS", // to be removed.+ promptName: record.prompt_name ?? null,+ promptVersion: record.prompt_version ?? null,+ latency: record.end_time+ ? parseClickhouseUTCDateTimeFormat(record.end_time).getTime() -+ parseClickhouseUTCDateTimeFormat(record.start_time).getTime()+ : null,+ timeToFirstToken: record.completion_start_time+ ? parseClickhouseUTCDateTimeFormat(record.start_time).getTime() -+ parseClickhouseUTCDateTimeFormat(record.completion_start_time).getTime()+ : null,};};diff --git a/web/src/__tests__/async/dataset-service.servertest.ts b/web/src/__tests__/async/dataset-service.servertest.tsindex 67c9aa2bdd..df6391ad48 100644--- a/web/src/__tests__/async/dataset-service.servertest.ts+++ b/web/src/__tests__/async/dataset-service.servertest.ts@@ -144,7 +144,7 @@ describe("dataset service", () => {start_time: new Date().getTime() - 1000,end_time: new Date().getTime(),});- createObservations([+ await createObservations([observation,observation2,observation3,@@ -158,7 +158,7 @@ describe("dataset service", () => {project_id: projectId,name: scoreName,});- createScores([score]);+ await createScores([score]);const runs = await createDatasetRunsTable({projectId,diff --git a/web/src/__tests__/async/observation-api.servertest.ts b/web/src/__tests__/async/observation-api.servertest.tsnew file mode 100644index 0000000000..48c10123e3--- /dev/null+++ b/web/src/__tests__/async/observation-api.servertest.ts@@ -0,0 +1,39 @@+import { createObservation } from "@/src/__tests__/fixtures/tracing-factory";+import { createObservations } from "@/src/__tests__/server/repositories/clickhouse-helpers";+import { makeZodVerifiedAPICall } from "@/src/__tests__/test-utils";+import { GetObservationV1Response } from "@/src/features/public-api/types/observations";+import { v4 } from "uuid";++const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";++describe("/api/public/observations API Endpoint", () => {+ describe("GET /api/public/observations/:id", () => {+ it("should GET an observation", async () => {+ const observationId = v4();+ const traceId = v4();++ const observation = createObservation({+ id: observationId,+ project_id: projectId,+ trace_id: traceId,+ internal_model_id: "b9854a5c92dc496b997d99d21",+ provided_model_name: "gpt-4o-2024-05-13",+ });++ await createObservations([observation]);++ const getEventRes = await makeZodVerifiedAPICall(+ GetObservationV1Response,+ "GET",+ "/api/public/observations/" + observationId,+ );+ expect(getEventRes.body).toMatchObject({+ id: observationId,+ traceId: traceId,+ type: observation.type,+ modelId: observation.internal_model_id,+ inputPrice: 0.000005,+ });+ });+ });+});diff --git a/web/src/__tests__/observations.servertest.ts b/web/src/__tests__/observations.servertest.tsindex 9a28baf96a..be5b93dcf0 100644--- a/web/src/__tests__/observations.servertest.ts+++ b/web/src/__tests__/observations.servertest.ts@@ -1,17 +1,13 @@/** @jest-environment node */import { v4 as uuidv4 } from "uuid";-import {makeZodVerifiedAPICall,pruneDatabase,} from "@/src/__tests__/test-utils";import { ModelUsageUnit } from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";-import {- GetObservationV1Response,- GetObservationsV1Response,-} from "@/src/features/public-api/types/observations";+import { GetObservationsV1Response } from "@/src/features/public-api/types/observations";describe("/api/public/observations API Endpoint", () => {beforeEach(async () => await pruneDatabase());@@ -315,127 +311,3 @@ it("GET /observations with timestamp filters and pagination", async () => {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",- },- });-- 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/pages/api/public/observations/[observationId].ts b/web/src/pages/api/public/observations/[observationId].tsindex 9bfd938a40..ffbc30ee11 100644--- a/web/src/pages/api/public/observations/[observationId].ts+++ b/web/src/pages/api/public/observations/[observationId].ts@@ -7,6 +7,8 @@ import {import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";import { LangfuseNotFoundError } from "@langfuse/shared";+import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";+import { getObservationViewById } from "@langfuse/shared/src/server";export default withMiddlewares({GET: createAuthedAPIRoute({@@ -15,12 +17,76 @@ export default withMiddlewares({responseSchema: GetObservationV1Response,fn: async ({ query, auth }) => {const { observationId } = query;- const observation = await prisma.observationView.findFirst({- where: {- id: observationId,- projectId: auth.scope.projectId,+ const observation = await measureAndReturnApi({+ input: { projectId: auth.scope.projectId, queryClickhouse: false },+ operation: "api/public/observations/[observationId]",+ user: null,+ pgExecution: async () => {+ return await prisma.observationView.findFirst({+ where: {+ id: observationId,+ projectId: auth.scope.projectId,+ },+ });+ },+ clickhouseExecution: async () => {+ const observation = await getObservationViewById(+ observationId,+ auth.scope.projectId,+ );+ if (!observation) {+ throw new LangfuseNotFoundError(+ "Observation not found within authorized project",+ );+ }++ const model = observation.modelId+ ? await prisma.model.findFirst({+ where: {+ AND: [+ {+ id: observation.modelId,+ },+ {+ OR: [+ {+ projectId: auth.scope.projectId,+ },+ {+ projectId: null,+ },+ ],+ },+ ],+ },+ include: {+ Price: true,+ },+ orderBy: {+ projectId: {+ sort: "desc",+ nulls: "last",+ },+ },+ })+ : undefined;++ // eslint-disable-next-line @typescript-eslint/no-unused-vars++ return {+ ...observation,+ modelId: model?.id ?? null,+ inputPrice:+ model?.Price?.find((m) => m.usageType === "input")?.price ?? null,+ outputPrice:+ model?.Price?.find((m) => m.usageType === "output")?.price ??+ null,+ totalPrice:+ model?.Price?.find((m) => m.usageType === "total")?.price ?? null,+ };},});+if (!observation) {throw new LangfuseNotFoundError("Observation not found within authorized project",diff --git a/web/src/server/api/routers/observations.ts b/web/src/server/api/routers/observations.tsindex 05485e0454..e585c162bf 100644--- a/web/src/server/api/routers/observations.ts+++ b/web/src/server/api/routers/observations.ts@@ -3,50 +3,10 @@ import {protectedGetTraceProcedure,} from "@/src/server/api/trpc";import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";-import {- type jsonSchema,- type ObservationLevel,- type ObservationType,-} from "@langfuse/shared";import { getObservationById } from "@langfuse/shared/src/server";-import type Decimal from "decimal.js";+import { TRPCError } from "@trpc/server";import { z } from "zod";-export type SingleObservationReturnType = {- name: string | null;- id: string;- createdAt: Date;- updatedAt: Date;- type: ObservationType;- traceId: string | null;- projectId: string;- input: z.infer<typeof jsonSchema> | null;- startTime: Date;- endTime: Date | null;- metadata: z.infer<typeof jsonSchema> | null;- parentObservationId: string | null;- level: ObservationLevel;- statusMessage: string | null;- version: string | null;- model: string | null;- internalModel: string | null;- internalModelId: string | null;- modelParameters: z.infer<typeof jsonSchema> | null;- output: z.infer<typeof jsonSchema> | null;- promptTokens: number;- completionTokens: number;- totalTokens: number;- unit: string | null;- inputCost: Decimal | null;- outputCost: Decimal | null;- totalCost: Decimal | null;- calculatedInputCost: Decimal | null;- calculatedOutputCost: Decimal | null;- calculatedTotalCost: Decimal | null;- completionStartTime: Date | null;- promptId: string | null;-};-export const observationsRouter = createTRPCRouter({byId: protectedGetTraceProcedure.input(@@ -63,7 +23,7 @@ export const observationsRouter = createTRPCRouter({operation: "observations.byId",user: ctx.session.user,pgExecution: async () => {- return ctx.prisma.observation.findFirstOrThrow({+ return await ctx.prisma.observation.findFirstOrThrow({where: {id: input.observationId,traceId: input.traceId,@@ -72,7 +32,21 @@ export const observationsRouter = createTRPCRouter({});},clickhouseExecution: async () => {- return getObservationById(input.observationId, input.projectId, true);+ const obs = await getObservationById(+ input.observationId,+ input.projectId,+ true,+ );+ if (!obs) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Observation not found within authorized project",+ });+ }+ return {+ ...obs,+ internalModel: obs?.internalModelId,+ };},});}),