🪢 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: fetch single trace via API from clickhouse (#4344)
Max Deichmann74d1f7f7170a
diff --git a/.env.dev.example b/.env.dev.exampleindex bbd886ca57..5e2c40fe67 100644--- a/.env.dev.example+++ b/.env.dev.example@@ -85,3 +85,5 @@ LANGFUSE_RETURN_FROM_CLICKHOUSE=trueLANGFUSE_READ_DASHBOARDS_FROM_CLICKHOUSE=trueLANGFUSE_READ_FROM_CLICKHOUSE_ONLY=true+LANGFUSE_ASYNC_INGESTION_PROCESSING="true"+LANGFUSE_ASYNC_CLICKHOUSE_INGESTION_PROCESSING="true"diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.ymlindex 1b5b3bc3b5..447a629afa 100644--- a/.github/workflows/pipeline.yml+++ b/.github/workflows/pipeline.yml@@ -332,19 +332,40 @@ jobs:echo "LANGFUSE_ASYNC_INGESTION_PROCESSING=true" >> .envecho "LANGFUSE_CACHE_API_KEY_ENABLED=true" >> .envecho "LANGFUSE_CACHE_PROMPT_ENABLED=true" >> .env+ - name: Install golang-migrate for Clickhouse migrations+ run: |+ curl -L https://github.com/golang-migrate/migrate/releases/download/v4.16.2/migrate.linux-amd64.tar.gz | tar xvz+ sudo mv migrate /usr/bin/migrate+ which migrate+- name: Run + migraterun: |docker compose -f docker-compose.dev.yml up -ddocker compose pssleep 5 # Wait for PostgreSQL to accept connections+ - name: Ensure Docker dependencies are healthy+ run: |+ if docker-compose ps | grep "(unhealthy)"; then+ echo "One or more services are unhealthy"+ exit 1+ else+ echo "All services are healthy"+ fi- name: Seed DBrun: |pnpm run db:migrate+ pnpm --filter=shared run ch:uppnpm run db:seed:examples- name: Buildrun: pnpm run build- name: Run serverrun: (pnpm run start&)+ - name: Check worker health+ run: |+ timeout 10 bash -c 'until curl -f http://localhost:3030/api/health; do sleep 2; done'+ - name: Check server health+ run: |+ timeout 10 bash -c 'until curl -f http://localhost:3000/api/public/health; do sleep 2; done'- name: Run e2e testsrun: pnpm --filter=web run test:e2e:serverdiff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.tsindex 7698a8b12c..f3b3e5f192 100644--- a/packages/shared/src/server/repositories/observations.ts+++ b/packages/shared/src/server/repositories/observations.ts@@ -242,21 +242,19 @@ export const getObservationsTable = async (opts.projectId,);- return await Promise.all(- observationRecords.map(async (o) => {- const trace = traces.find((t) => t.id === o.trace_id);- return {- ...convertObservationToView({ ...o, type: "GENERATION" }),- latency: o.latency ? Number(o.latency) / 1000 : null,- timeToFirstToken: o.time_to_first_token- ? Number(o.time_to_first_token) / 1000- : null,- traceName: trace?.name ?? null,- traceTags: trace?.tags ?? [],- userId: trace?.userId ?? null,- };- }),- );+ return observationRecords.map((o) => {+ const trace = traces.find((t) => t.id === o.trace_id);+ return {+ ...convertObservationToView({ ...o, type: "GENERATION" }),+ latency: o.latency ? Number(o.latency) / 1000 : null,+ timeToFirstToken: o.time_to_first_token+ ? Number(o.time_to_first_token) / 1000+ : null,+ traceName: trace?.name ?? null,+ traceTags: trace?.tags ?? [],+ userId: trace?.userId ?? null,+ };+ });};export const getObservationsTableWithModelData = async (@@ -324,29 +322,27 @@ export const getObservationsTableWithModelData = async (),]);- return await Promise.all(- observationRecords.map(async (o) => {- const trace = traces.find((t) => t.id === o.trace_id);- const model = models.find((m) => m.id === o.internal_model_id);- return {- ...convertObservationToView({ ...o, type: "GENERATION" }),- latency: o.latency ? Number(o.latency) / 1000 : null,- timeToFirstToken: o.time_to_first_token- ? Number(o.time_to_first_token) / 1000- : null,- traceName: trace?.name ?? null,- traceTags: trace?.tags ?? [],- userId: trace?.userId ?? null,- 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,- };- }),- );+ return observationRecords.map((o) => {+ const trace = traces.find((t) => t.id === o.trace_id);+ const model = models.find((m) => m.id === o.internal_model_id);+ return {+ ...convertObservationToView({ ...o, type: "GENERATION" }),+ latency: o.latency ? Number(o.latency) / 1000 : null,+ timeToFirstToken: o.time_to_first_token+ ? Number(o.time_to_first_token) / 1000+ : null,+ traceName: trace?.name ?? null,+ traceTags: trace?.tags ?? [],+ userId: trace?.userId ?? null,+ 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,+ };+ });};const getObservationsTableInternal = async <T>(diff --git a/packages/shared/src/server/repositories/observations_converters.ts b/packages/shared/src/server/repositories/observations_converters.tsindex 550050b124..9c7d80f7de 100644--- a/packages/shared/src/server/repositories/observations_converters.ts+++ b/packages/shared/src/server/repositories/observations_converters.ts@@ -11,12 +11,14 @@ import { ObservationRecordReadType } from "./definitions";export const convertObservationToView = (record: ObservationRecordReadType,-): Omit<- ObservationView,- "inputPrice" | "outputPrice" | "totalPrice" | "modelId"-> => {+): Omit<ObservationView, "inputPrice" | "outputPrice" | "totalPrice"> => {+ // these cost are not used from the view. They are in the select statement but not in the+ // Prisma file. We will not clean this up but keep it as it is for now.+ // eslint-disable-next-line no-unused-vars+ const { inputCost, outputCost, totalCost, internalModelId, ...rest } =+ convertObservation(record ?? undefined);return {- ...convertObservation(record ?? undefined),+ ...rest,latency: record.end_time? parseClickhouseUTCDateTimeFormat(record.end_time).getTime() -parseClickhouseUTCDateTimeFormat(record.start_time).getTime()@@ -27,6 +29,7 @@ export const convertObservationToView = (: null,promptName: record.prompt_name ?? null,promptVersion: record.prompt_version ?? null,+ modelId: record.internal_model_id ?? null,};};diff --git a/web/src/__e2e__/api.servertest.ts b/web/src/__e2e__/api.servertest.tsindex 25a70326d5..82b321f33d 100644--- a/web/src/__e2e__/api.servertest.ts+++ b/web/src/__e2e__/api.servertest.ts@@ -1,6 +1,10 @@import { v4 } from "uuid";import { JobExecutionStatus, Prisma, prisma } from "@langfuse/shared/src/db";-import { OrgEnrichedApiKey, redis } from "@langfuse/shared/src/server";+import {+ clickhouseClient,+ OrgEnrichedApiKey,+ redis,+} from "@langfuse/shared/src/server";import waitForExpect from "wait-for-expect";const generateAuth = (username: string, password: string) => {@@ -86,70 +90,85 @@ describe("Ingestion Pipeline", () => {body: JSON.stringify(event),});- await waitForExpect(async () => {- // we need a second call to the public API with the API key, so that it is stored in redis- // first call (ingestion above) generates the new, fast API hash- // second call (below) stores the API key in redis- const traceUrl = `http://localhost:3000/api/public/traces/${traceId}`;+ await waitForExpect(+ async () => {+ // we need a second call to the public API with the API key, so that it is stored in redis+ // first call (ingestion above) generates the new, fast API hash+ // second call (below) stores the API key in redis+ const traceUrl = `http://localhost:3000/api/public/traces/${traceId}`;- const traceResponse = await fetch(traceUrl, {- headers: {- Authorization: userApiKeyAuth,- },- });-- expect(traceResponse.status).toBe(200);- expect(traceResponse.body).not.toBeNull();- expect((await traceResponse.json()).id).toBe(traceId);+ const traceResponse = await fetch(traceUrl, {+ headers: {+ Authorization: userApiKeyAuth,+ },+ });++ const traces = await clickhouseClient().query({+ query: "SELECT * FROM traces",+ format: "JSONEachRow",+ });+ console.log("traces", await traces.text());+ expect(traceResponse.status).toBe(200);+ expect(traceResponse.body).not.toBeNull();+ expect((await traceResponse.json()).id).toBe(traceId);++ const trace = await prisma.trace.findUnique({+ where: {+ id: traceId,+ },+ });+ expect(trace).not.toBeNull();+ expect(trace?.name).toBe("test trace");- const trace = await prisma.trace.findUnique({- where: {- id: traceId,- },- });- expect(trace).not.toBeNull();- expect(trace?.name).toBe("test trace");-- const observation = await prisma.observation.findUnique({- where: {- id: spanId,- traceId: traceId,- },- });- expect(observation).not.toBeNull();- expect(observation?.name).toBe("test span");+ const observation = await prisma.observation.findUnique({+ where: {+ id: spanId,+ traceId: traceId,+ },+ });+ expect(observation).not.toBeNull();+ expect(observation?.name).toBe("test span");- expect(redis).not.toBeNull();+ expect(redis).not.toBeNull();- const redisKeys = await redis?.keys(`api-key:*`);- expect(redisKeys?.length).toBe(1);- const redisValue = await redis?.get(redisKeys![0]);+ const redisKeys = await redis?.keys(`api-key:*`);+ expect(redisKeys?.length).toBe(1);+ const redisValue = await redis?.get(redisKeys![0]);- const llmApiKey = OrgEnrichedApiKey.parse(JSON.parse(redisValue!));- expect(llmApiKey.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");- });+ const llmApiKey = OrgEnrichedApiKey.parse(JSON.parse(redisValue!));+ expect(llmApiKey.projectId).toBe(+ "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ );+ },+ 40000,+ 1000,+ );// check for eval- await waitForExpect(async () => {- const evalExecution = await prisma.jobExecution.findFirst({- where: {- jobInputTraceId: traceId,- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- },- });+ await waitForExpect(+ async () => {+ const evalExecution = await prisma.jobExecution.findFirst({+ where: {+ jobInputTraceId: traceId,+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ },+ });- expect(evalExecution).not.toBeNull();+ expect(evalExecution).not.toBeNull();- if (!evalExecution) {- return;- }+ if (!evalExecution) {+ return;+ }- // failure due to missing openai key in the pipeline. Expected- expect(evalExecution.status).toBe(JobExecutionStatus.ERROR);- }, 20000);+ // failure due to missing openai key in the pipeline. Expected+ expect(evalExecution.status).toBe(JobExecutionStatus.ERROR);+ },+ 40000,+ 1000,+ );expect(response.status).toBe(207);- }, 25000);+ }, 50000);it("rate limit ingestion", async () => {// update the org in the database and set the rate limit to 1 for ingestiondiff --git a/web/src/__tests__/async/dataset-service.servertest.ts b/web/src/__tests__/async/dataset-service.servertest.tsindex 14703c26a5..67c9aa2bdd 100644--- a/web/src/__tests__/async/dataset-service.servertest.ts+++ b/web/src/__tests__/async/dataset-service.servertest.ts@@ -182,7 +182,7 @@ describe("dataset service", () => {expect(firstRun.run_description).toBeNull();expect(firstRun.run_metadata).toEqual({});- expect(firstRun.avgLatency).toEqual(10800);+ expect(firstRun.avgLatency).toBeGreaterThanOrEqual(10800);expect(firstRun.avgTotalCost.toString()).toStrictEqual("275");const expectedObject = JSON.stringify({diff --git a/web/src/__tests__/async/traces-api.servertest.ts b/web/src/__tests__/async/traces-api.servertest.tsnew file mode 100644index 0000000000..9aadbaf247--- /dev/null+++ b/web/src/__tests__/async/traces-api.servertest.ts@@ -0,0 +1,58 @@+import {+ createObservation,+ createTrace,+} from "@/src/__tests__/fixtures/tracing-factory";+import {+ createObservations,+ createTraces,+} from "@/src/__tests__/server/repositories/clickhouse-helpers";+import { makeZodVerifiedAPICall } from "@/src/__tests__/test-utils";+import { GetTraceV1Response } from "@/src/features/public-api/types/traces";++describe("/api/public/traces API Endpoint", () => {+ it("should create and get a trace via /traces", async () => {+ const createdTrace = createTrace({+ name: "trace-name",+ user_id: "user-1",+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ metadata: { key: "value" },+ release: "1.0.0",+ version: "2.0.0",+ });++ const observations = [+ createObservation({+ trace_id: createdTrace.id,+ project_id: createdTrace.project_id,+ name: "observation-name",+ end_time: new Date().getTime(),+ start_time: new Date().getTime() - 1000,+ }),+ createObservation({+ trace_id: createdTrace.id,+ project_id: createdTrace.project_id,+ name: "observation-name",+ end_time: new Date().getTime(),+ start_time: new Date().getTime() - 100000,+ }),+ ];++ await createTraces([createdTrace]);+ await createObservations(observations);++ const trace = await makeZodVerifiedAPICall(+ GetTraceV1Response,+ "GET",+ "/api/public/traces/" + createdTrace.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");+ expect(trace.body.latency).toBe(100);+ expect(trace.body.observations.length).toBe(2);+ expect(trace.body.scores.length).toBe(0);+ });+});diff --git a/web/src/__tests__/traces.servertest.ts b/web/src/__tests__/traces.servertest.tsindex 3c41a7ae90..8c752d3fc4 100644--- a/web/src/__tests__/traces.servertest.ts+++ b/web/src/__tests__/traces.servertest.ts@@ -19,36 +19,6 @@ describe("/api/public/traces API Endpoint", () => {beforeEach(async () => await pruneDatabase());afterEach(async () => await pruneDatabase());- it("should create and get a trace via /traces", async () => {- await pruneDatabase();-- 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",- },- );-- 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();diff --git a/web/src/pages/api/public/traces/[traceId].ts b/web/src/pages/api/public/traces/[traceId].tsindex d2cefc1fc1..ab666d5aaa 100644--- a/web/src/pages/api/public/traces/[traceId].ts+++ b/web/src/pages/api/public/traces/[traceId].ts@@ -5,12 +5,20 @@ import {GetTraceV1Query,GetTraceV1Response,} from "@/src/features/public-api/types/traces";+import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";import {filterAndValidateDbScoreList,LangfuseNotFoundError,+ type ObservationView,} from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";-import { traceException } from "@langfuse/shared/src/server";+import {+ getObservationsViewForTrace,+ getScoresForTraces,+ getTraceById,+ traceException,+} from "@langfuse/shared/src/server";+import Decimal from "decimal.js";export default withMiddlewares({GET: createAuthedAPIRoute({@@ -20,55 +28,161 @@ export default withMiddlewares({fn: async ({ query, auth }) => {const { traceId } = query;- const trace = await prisma.traceView.findFirst({- where: {- id: traceId,- projectId: auth.scope.projectId,+ return await measureAndReturnApi({+ input: { projectId: auth.scope.projectId, queryClickhouse: false },+ operation: "api/public/traces/[traceId]",+ user: null,+ pgExecution: async () => {+ const trace = await prisma.traceView.findFirst({+ where: {+ id: traceId,+ projectId: auth.scope.projectId,+ },+ });++ if (!trace) {+ throw new LangfuseNotFoundError(+ "Trace not found within authorized project",+ );+ }++ 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" },+ }),+ ]);++ const outObservations = observations.map(transformDbToApiObservation);+ const validatedScores = filterAndValidateDbScoreList(+ scores,+ traceException,+ );++ const { duration, ...restOfTrace } = trace;++ 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,+ };},- });+ clickhouseExecution: async () => {+ const [trace, observations, scores] = await Promise.all([+ getTraceById(traceId, auth.scope.projectId),+ getObservationsViewForTrace(traceId, auth.scope.projectId),+ getScoresForTraces(auth.scope.projectId, [traceId]),+ ]);++ const uniqueModels: string[] = Array.from(+ new Set(+ observations+ .map((r) => r.modelId)+ .filter((r): r is string => Boolean(r)),+ ),+ );++ const models =+ uniqueModels.length > 0+ ? await prisma.model.findMany({+ where: {+ id: {+ in: uniqueModels,+ },+ OR: [+ { projectId: auth.scope.projectId },+ { projectId: null },+ ],+ },+ include: {+ Price: true,+ },+ })+ : [];- if (!trace) {- throw new LangfuseNotFoundError(- "Trace not found within authorized project",- );- }+ const observationsView: ObservationView[] = observations.map((o) => {+ const model = models.find((m) => m.id === o.modelId);+ const inputPrice =+ model?.Price.find((p) => p.usageType === "input")?.price ??+ new Decimal(0);+ const outputPrice =+ model?.Price.find((p) => p.usageType === "output")?.price ??+ new Decimal(0);+ const totalPrice =+ model?.Price.find((p) => p.usageType === "total")?.price ??+ new Decimal(0);+ return {+ ...o,+ inputPrice,+ outputPrice,+ totalPrice,+ };+ });- 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) {+ throw new LangfuseNotFoundError(+ `Trace ${traceId} not found within authorized project`,+ );+ }- const outObservations = observations.map(transformDbToApiObservation);- const validatedScores = filterAndValidateDbScoreList(- scores,- traceException,- );+ const outObservations = observationsView.map(+ transformDbToApiObservation,+ );+ const validatedScores = filterAndValidateDbScoreList(+ scores,+ traceException,+ );- const { duration, ...restOfTrace } = trace;+ const obsStartTimes = observations+ .map((o) => o.startTime)+ .sort((a, b) => a.getTime() - b.getTime());+ const obsEndTimes = observations+ .map((o) => o.endTime)+ .filter((t) => t)+ .sort((a, b) => (a as Date).getTime() - (b as Date).getTime());- 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,- };+ const latencyMs =+ obsStartTimes.length > 0+ ? obsEndTimes.length > 0+ ? (obsEndTimes[obsEndTimes.length - 1] as Date).getTime() -+ obsStartTimes[0]!.getTime()+ : obsStartTimes.length > 1+ ? obsStartTimes[obsStartTimes.length - 1]!.getTime() -+ obsStartTimes[0]!.getTime()+ : undefined+ : undefined;+ return {+ ...trace,+ scores: validatedScores,+ latency: latencyMs !== undefined ? latencyMs / 1000 : 0,+ observations: outObservations,+ htmlPath: `/project/${auth.scope.projectId}/traces/${traceId}`,+ totalCost: observations+ .reduce(+ (acc, obs) =>+ acc.add(obs.calculatedTotalCost ?? new Decimal(0)),+ new Decimal(0),+ )+ .toNumber(),+ };+ },+ });},}),});