Skip to content

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

feat: fetch observations via api from clickhouse (#4395)

Max Deichmann9b1746b7ed72
diff --git a/.env.dev.example b/.env.dev.example
index 5e2c40fe67..6fe7640cf5 100644
--- a/.env.dev.example
+++ b/.env.dev.example
@@ -11,7 +11,7 @@ CLICKHOUSE_MIGRATION_URL="clickhouse://localhost:9000"
CLICKHOUSE_URL="http://localhost:8123"
CLICKHOUSE_USER="clickhouse"
CLICKHOUSE_PASSWORD="clickhouse"
-CLICKHOUSE_MIGRATION_CLUSTER_DISABLED="true"
+CLICKHOUSE_CLUSTER_DISABLED="true"
# Next Auth
# You can generate a new secret on the command line with:
diff --git a/packages/shared/src/server/queries/index.ts b/packages/shared/src/server/queries/index.ts
index d7436e90a5..7c149a3270 100644
--- a/packages/shared/src/server/queries/index.ts
+++ b/packages/shared/src/server/queries/index.ts
@@ -7,3 +7,15 @@ export {
type FullObservationsWithScores,
type IOAndMetadataOmittedObservations,
} from "./createGenerationsQuery";
+export {
+ FilterList,
+ StringFilter,
+ DateTimeFilter,
+ StringOptionsFilter,
+ NumberFilter,
+ ArrayOptionsFilter,
+ BooleanFilter,
+ NumberObjectFilter,
+ StringObjectFilter,
+ NullFilter,
+} from "./clickhouse-sql/clickhouse-filter";
diff --git a/packages/shared/src/server/repositories/observations_converters.ts b/packages/shared/src/server/repositories/observations_converters.ts
index 53c6cb81c1..8026a7918e 100644
--- a/packages/shared/src/server/repositories/observations_converters.ts
+++ b/packages/shared/src/server/repositories/observations_converters.ts
@@ -3,11 +3,13 @@ import {
ObservationView,
ObservationType,
ObservationLevel,
+ Prisma,
} from "@prisma/client";
import Decimal from "decimal.js";
-import { jsonSchema } from "../../utils/zod";
import { parseClickhouseUTCDateTimeFormat } from "./clickhouse";
import { ObservationRecordReadType } from "./definitions";
+import { parseJsonPrioritised } from "../../utils/json";
+import { jsonSchema } from "../../utils/zod";
export const convertObservationToView = (
record: ObservationRecordReadType,
@@ -56,8 +58,12 @@ export const convertObservation = (
level: record.level as ObservationLevel,
statusMessage: record.status_message ?? null,
version: record.version ?? null,
- input: jsonSchema.nullish().parse(record.input) ?? null,
- output: jsonSchema.nullish().parse(record.output) ?? null,
+ input: (record.input
+ ? jsonSchema.parse(parseJsonPrioritised(record.input))
+ : null) as Prisma.JsonValue | null,
+ output: (record.output
+ ? jsonSchema.parse(parseJsonPrioritised(record.output))
+ : null) as Prisma.JsonValue | null,
modelParameters: record.model_parameters
? JSON.parse(record.model_parameters)
: null,
diff --git a/web/src/__tests__/async/observation-api.servertest.ts b/web/src/__tests__/async/observation-api.servertest.ts
index c1e1c30c26..ee3daa5d75 100644
--- a/web/src/__tests__/async/observation-api.servertest.ts
+++ b/web/src/__tests__/async/observation-api.servertest.ts
@@ -1,8 +1,10 @@
-import { createObservation } from "@/src/__tests__/fixtures/tracing-factory";
-import { createObservations } from "@/src/__tests__/server/repositories/clickhouse-helpers";
+import { createObservation as createObservationObject } from "@/src/__tests__/fixtures/tracing-factory";
+import { createObservations as createObservationsInClickhouse } 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";
+import { v4 as uuidv4 } from "uuid";
+import { GetObservationsV1Response } from "@/src/features/public-api/types/observations";
const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
@@ -12,7 +14,7 @@ describe("/api/public/observations API Endpoint", () => {
const observationId = v4();
const traceId = v4();
- const observation = createObservation({
+ const observation = createObservationObject({
id: observationId,
project_id: projectId,
trace_id: traceId,
@@ -22,7 +24,7 @@ describe("/api/public/observations API Endpoint", () => {
output: "output",
});
- await createObservations([observation]);
+ await createObservationsInClickhouse([observation]);
const getEventRes = await makeZodVerifiedAPICall(
GetObservationV1Response,
@@ -41,3 +43,211 @@ describe("/api/public/observations API Endpoint", () => {
});
});
});
+
+describe("/api/public/observations API Endpoint", () => {
+ it("should fetch all observations", async () => {
+ const traceId = uuidv4();
+
+ const observation = createObservationObject({
+ id: uuidv4(),
+ trace_id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ internal_model_id: "clrkwk4cb000408l576jl7koo",
+ provided_model_name: "gpt-3.5-turbo",
+ input: JSON.stringify({ key: "input" }),
+ output: JSON.stringify({ key: "output" }),
+ usage_details: {
+ input: 10,
+ output: 20,
+ total: 30,
+ },
+ version: "2.0.0",
+ type: "GENERATION",
+ });
+
+ await createObservationsInClickhouse([observation]);
+
+ const fetchedObservations = await makeZodVerifiedAPICall(
+ GetObservationsV1Response,
+ "GET",
+ "/api/public/observations?traceId=" + traceId,
+ undefined,
+ );
+
+ expect(fetchedObservations.status).toBe(200);
+
+ expect(fetchedObservations.body.data.length).toBe(1);
+ expect(fetchedObservations.body.data[0]?.traceId).toBe(traceId);
+ expect(fetchedObservations.body.data[0]?.input).toEqual({ key: "input" });
+ expect(fetchedObservations.body.data[0]?.output).toEqual({ key: "output" });
+ expect(fetchedObservations.body.data[0]?.model).toEqual("gpt-3.5-turbo");
+ expect(fetchedObservations.body.data[0]?.modelId).toEqual(
+ "clrkwk4cb000408l576jl7koo",
+ );
+ expect(
+ fetchedObservations.body.data[0]?.calculatedInputCost,
+ ).toBeGreaterThan(0);
+ expect(
+ fetchedObservations.body.data[0]?.calculatedOutputCost,
+ ).toBeGreaterThan(0);
+ expect(
+ fetchedObservations.body.data[0]?.calculatedTotalCost,
+ ).toBeGreaterThan(0);
+ });
+
+ it("should fetch all observations, filtered by generations", async () => {
+ const traceId = uuidv4();
+
+ const generationObservation = createObservationObject({
+ id: uuidv4(),
+ trace_id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ internal_model_id: "model-1",
+ provided_model_name: "gpt-3.5-turbo",
+ input: JSON.stringify({ key: "input" }),
+ output: JSON.stringify({ key: "output" }),
+ usage_details: {
+ input: 10,
+ output: 20,
+ total: 30,
+ },
+ version: "2.0.0",
+ type: "GENERATION",
+ });
+
+ const spanObservation = createObservationObject({
+ id: uuidv4(),
+ trace_id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ input: JSON.stringify({ key: "input" }),
+ output: JSON.stringify({ key: "output" }),
+ version: "2.0.0",
+ type: "SPAN",
+ });
+
+ await createObservationsInClickhouse([
+ generationObservation,
+ spanObservation,
+ ]);
+
+ const fetchedObservations = await makeZodVerifiedAPICall(
+ GetObservationsV1Response,
+ "GET",
+ "/api/public/observations?type=GENERATION&traceId=" + traceId,
+ undefined,
+ );
+
+ console.log(fetchedObservations.body);
+
+ expect(fetchedObservations.status).toBe(200);
+
+ expect(fetchedObservations.body.data.length).toBe(1);
+ expect(fetchedObservations.body.data[0]?.traceId).toBe(traceId);
+ expect(fetchedObservations.body.data[0]?.input).toEqual({ key: "input" });
+ expect(fetchedObservations.body.data[0]?.output).toEqual({ key: "output" });
+ expect(fetchedObservations.body.data[0]?.type).toEqual("GENERATION");
+ });
+
+ it("GET /observations with timestamp filters and pagination", async () => {
+ const traceId = v4();
+ const obs1 = createObservationObject({
+ id: "observation-2021-01-01",
+ trace_id: traceId,
+ name: "generation-name",
+ start_time: new Date("2021-01-01T00:00:00.000Z").getTime(),
+ end_time: new Date("2021-01-01T00:00:00.000Z").getTime(),
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ type: "GENERATION",
+ });
+
+ const obs2 = createObservationObject({
+ id: "observation-2021-02-01",
+ trace_id: traceId,
+ name: "generation-name",
+ start_time: new Date("2021-02-01T00:00:00.000Z").getTime(),
+ end_time: new Date("2021-02-01T00:00:00.000Z").getTime(),
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ type: "SPAN",
+ });
+ const obs3 = createObservationObject({
+ id: "observation-2021-03-01",
+ trace_id: traceId,
+ name: "generation-name",
+ start_time: new Date("2021-03-01T00:00:00.000Z").getTime(),
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ type: "EVENT",
+ });
+ const obs4 = createObservationObject({
+ id: "observation-2021-04-01",
+ trace_id: traceId,
+ name: "generation-name",
+ start_time: new Date("2021-04-01T00:00:00.000Z").getTime(),
+ end_time: new Date("2021-04-01T00:00:00.000Z").getTime(),
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ type: "GENERATION",
+ });
+
+ await createObservationsInClickhouse([obs1, obs2, obs3, obs4]);
+
+ const 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}&traceId=${traceId}`,
+ 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}&traceId=${traceId}`,
+ undefined,
+ );
+
+ expect(fetchedObservations.body.data.length).toBe(3);
+ expect(fetchedObservations.body.data[0]?.id).toBe("observation-2021-04-01");
+ expect(fetchedObservations.body.data[1]?.id).toBe("observation-2021-03-01");
+ expect(fetchedObservations.body.data[2]?.id).toBe("observation-2021-02-01");
+ expect(fetchedObservations.body.meta.totalItems).toBe(3);
+
+ // Test with only toTimestamp
+ fetchedObservations = await makeZodVerifiedAPICall(
+ GetObservationsV1Response,
+ "GET",
+ `/api/public/observations?toStartTime=${toTimestamp}&traceId=${traceId}`,
+ undefined,
+ );
+
+ expect(fetchedObservations.body.data.length).toBe(3);
+ expect(fetchedObservations.body.data[0]?.id).toBe("observation-2021-03-01");
+ expect(fetchedObservations.body.data[1]?.id).toBe("observation-2021-02-01");
+ expect(fetchedObservations.body.data[2]?.id).toBe("observation-2021-01-01");
+ expect(fetchedObservations.body.meta.totalItems).toBe(3);
+
+ // test pagination only
+ fetchedObservations = await makeZodVerifiedAPICall(
+ GetObservationsV1Response,
+ "GET",
+ `/api/public/observations?limit=1&page=2&traceId=${traceId}`,
+ undefined,
+ );
+
+ expect(fetchedObservations.body.data.length).toBe(1);
+ expect(fetchedObservations.body.data[0]?.id).toBe("observation-2021-03-01");
+ expect(fetchedObservations.body.meta).toMatchObject({
+ totalItems: 4,
+ totalPages: 4,
+ page: 2,
+ limit: 1,
+ });
+ });
+});
diff --git a/web/src/__tests__/observations.servertest.ts b/web/src/__tests__/observations.servertest.ts
deleted file mode 100644
index be5b93dcf0..0000000000
--- a/web/src/__tests__/observations.servertest.ts
+++ /dev/null
@@ -1,313 +0,0 @@
-/** @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 { GetObservationsV1Response } from "@/src/features/public-api/types/observations";
-
-describe("/api/public/observations API Endpoint", () => {
- beforeEach(async () => await pruneDatabase());
- afterEach(async () => await pruneDatabase());
-
- it("should fetch all observations", 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",
- },
- });
-
- const model = await prisma.model.create({
- data: {
- id: "model-1",
- modelName: "gpt-3.5-turbo",
- inputPrice: "0.0000010",
- outputPrice: "0.0000020",
- totalPrice: "0.1",
- matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
- projectId: null,
- unit: ModelUsageUnit.Tokens,
- },
- });
-
- const prompt = await prisma.prompt.create({
- data: {
- name: "prompt-name",
- prompt: "prompt-one",
- isActive: false,
- version: 1,
- project: {
- connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },
- },
- createdBy: "user-1",
- },
- });
-
- 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: "gpt-3.5-turbo",
- modelParameters: { key: "value" },
- input: { key: "input" },
- output: { key: "output" },
- promptTokens: 10,
- completionTokens: 20,
- totalTokens: 30,
- version: "2.0.0",
- type: "GENERATION",
- project: {
- connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },
- },
- internalModel: "gpt-3.5-turbo",
- unit: ModelUsageUnit.Tokens,
- promptId: prompt.id,
- },
- });
-
- const fetchedObservations = await makeZodVerifiedAPICall(
- GetObservationsV1Response,
- "GET",
- "/api/public/observations",
- undefined,
- );
-
- expect(fetchedObservations.status).toBe(200);
-
- expect(fetchedObservations.body.data.length).toBe(1);
- expect(fetchedObservations.body.data[0]?.traceId).toBe(traceId);
- expect(fetchedObservations.body.data[0]?.input).toEqual({ key: "input" });
- expect(fetchedObservations.body.data[0]?.output).toEqual({ key: "output" });
- expect(fetchedObservations.body.data[0]?.model).toEqual("gpt-3.5-turbo");
- expect(fetchedObservations.body.data[0]?.modelId).toEqual(model.id);
- expect(
- fetchedObservations.body.data[0]?.calculatedInputCost,
- ).toBeGreaterThan(0);
- expect(
- fetchedObservations.body.data[0]?.calculatedOutputCost,
- ).toBeGreaterThan(0);
- expect(
- fetchedObservations.body.data[0]?.calculatedTotalCost,
- ).toBeGreaterThan(0);
- expect(fetchedObservations.body.data[0]?.promptId).toBe(prompt.id);
- expect(fetchedObservations.body.data[0]?.promptName).toBe(prompt.name);
- expect(fetchedObservations.body.data[0]?.promptVersion).toBe(
- prompt.version,
- );
- });
- it("should fetch all observations, filtered by generations", 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.model.create({
- data: {
- id: "model-1",
- modelName: "gpt-3.5-turbo",
- inputPrice: "0.0000010",
- outputPrice: "0.0000020",
- totalPrice: "0.1",
- matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",
- projectId: null,
- unit: ModelUsageUnit.Tokens,
- },
- });
-
- 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: "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" },
- },
- },
- });
-
- 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"),
- modelParameters: { key: "value" },
- input: { key: "input" },
- output: { key: "output" },
- version: "2.0.0",
- type: "SPAN",
- project: {
- connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },
- },
- },
- });
-
- const fetchedObservations = await makeZodVerifiedAPICall(
- GetObservationsV1Response,
- "GET",
- "/api/public/observations?type=GENERATION",
- undefined,
- );
-
- console.log(fetchedObservations.body);
-
- expect(fetchedObservations.status).toBe(200);
-
- expect(fetchedObservations.body.data.length).toBe(1);
- expect(fetchedObservations.body.data[0]?.traceId).toBe(traceId);
- expect(fetchedObservations.body.data[0]?.input).toEqual({ key: "input" });
- expect(fetchedObservations.body.data[0]?.output).toEqual({ key: "output" });
- expect(fetchedObservations.body.data[0]?.type).toEqual("GENERATION");
- });
-});
-
-it("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,
- });
-});
diff --git a/web/src/features/public-api/server/observations.ts b/web/src/features/public-api/server/observations.ts
new file mode 100644
index 0000000000..95ca02981c
--- /dev/null
+++ b/web/src/features/public-api/server/observations.ts
@@ -0,0 +1,159 @@
+import {
+ FilterList,
+ StringFilter,
+ NumberFilter,
+ type ObservationRecordReadType,
+ queryClickhouse,
+ convertObservationToView,
+ DateTimeFilter,
+} from "@langfuse/shared/src/server";
+
+export type QueryType = {
+ page: number;
+ limit: number;
+ projectId: string;
+ traceId?: string;
+ userId?: string;
+ name?: string;
+ type?: string;
+ parentObservationId?: string;
+ fromStartTime?: string;
+ toStartTime?: string;
+ version?: string;
+};
+
+export const generateObservationsForPublicApi = async (props: QueryType) => {
+ const filter = generateFilter(props);
+ const appliedFilter = filter.apply();
+
+ const query = `
+ SELECT
+ id,
+ trace_id,
+ project_id,
+ type,
+ parent_observation_id,
+ start_time,
+ end_time,
+ name,
+ metadata,
+ level,
+ status_message,
+ version,
+ input,
+ output,
+ provided_model_name,
+ internal_model_id,
+ model_parameters,
+ provided_usage_details,
+ usage_details,
+ provided_cost_details,
+ cost_details,
+ total_cost,
+ completion_start_time,
+ prompt_id,
+ prompt_name,
+ prompt_version,
+ created_at,
+ updated_at,
+ event_ts
+ FROM observations o
+ WHERE project_id = {projectId: String}
+ AND ${appliedFilter.query}
+ ORDER BY start_time desc
+ LIMIT 1 by id, project_id
+ ${props.limit !== undefined && props.page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
+ `;
+
+ const records = await queryClickhouse<ObservationRecordReadType>({
+ query,
+ params: {
+ ...appliedFilter.params,
+ projectId: props.projectId,
+ ...(props.limit !== undefined ? { limit: props.limit } : {}),
+ ...(props.page !== undefined
+ ? { offset: (props.page - 1) * props.limit }
+ : {}),
+ },
+ });
+ return records.map(convertObservationToView);
+};
+
+export const getObservationsCountForPublicApi = async (props: QueryType) => {
+ const filter = generateFilter(props).apply();
+
+ const query = `
+ SELECT
+ count() as count
+ FROM observations
+ WHERE project_id = {projectId: String}
+ AND ${filter.query}
+ `;
+
+ const records = await queryClickhouse<{ count: string }>({
+ query,
+ params: { ...filter.params, projectId: props.projectId },
+ });
+ return records.map((record) => Number(record.count)).shift();
+};
+
+const generateFilter = (filter: QueryType) => {
+ const observationsFilter = new FilterList([
+ new StringFilter({
+ clickhouseTable: "observations",
+ field: "project_id",
+ operator: "=",
+ value: filter.projectId,
+ }),
+ ]);
+
+ const filterParams = [
+ { key: "userId", field: "user_id" },
+ { key: "traceId", field: "trace_id" },
+ { key: "name", field: "name" },
+ { key: "type", field: "type" },
+ { key: "parentObservationId", field: "parent_observation_id" },
+ {
+ key: "fromStartTime",
+ field: "start_time",
+ isDate: true,
+ operator: ">=" as const,
+ },
+ {
+ key: "toStartTime",
+ field: "start_time",
+ isDate: true,
+ operator: "<" as const,
+ },
+ { key: "version", field: "version" },
+ ];
+
+ filterParams.forEach((param) => {
+ const value = filter[param.key as keyof QueryType];
+ if (value) {
+ observationsFilter.push(
+ param.isDate
+ ? new DateTimeFilter({
+ clickhouseTable: "observations",
+ field: param.field,
+ operator: param.operator || ("=" as const),
+ value: new Date(value),
+ })
+ : typeof value === "string"
+ ? new StringFilter({
+ clickhouseTable: "observations",
+ field: param.field,
+ operator: "=",
+ value: value,
+ })
+ : new NumberFilter({
+ clickhouseTable: "observations",
+ field: param.field,
+ operator: "=",
+ value: value,
+ }),
+ );
+ }
+ });
+ return observationsFilter;
+};
diff --git a/web/src/pages/api/public/observations/index.ts b/web/src/pages/api/public/observations/index.ts
index 3bba19a63b..a020faba47 100644
--- a/web/src/pages/api/public/observations/index.ts
+++ b/web/src/pages/api/public/observations/index.ts
@@ -10,6 +10,11 @@ import {
GetObservationsV1Response,
transformDbToApiObservation,
} from "@/src/features/public-api/types/observations";
+import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
+import {
+ generateObservationsForPublicApi,
+ getObservationsCountForPublicApi,
+} from "@/src/features/public-api/server/observations";
export default withMiddlewares({
GET: createAuthedAPIRoute({
@@ -17,39 +22,44 @@ export default withMiddlewares({
querySchema: GetObservationsV1Query,
responseSchema: GetObservationsV1Response,
fn: async ({ query, auth }) => {
- const userIdCondition = query.userId
- ? Prisma.sql`AND traces."user_id" = ${query.userId}`
- : Prisma.empty;
+ return await measureAndReturnApi({
+ input: { projectId: auth.scope.projectId, queryClickhouse: false },
+ operation: "api/public/observations",
+ user: null,
+ pgExecution: async () => {
+ 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 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 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 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 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 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 toStartTimeCondition = query.toStartTime
+ ? Prisma.sql`AND o."start_time" < ${query.toStartTime}::timestamp with time zone at time zone 'UTC'`
+ : Prisma.empty;
- const versionCondition = query.version
- ? Prisma.sql`AND o."version" = ${query.version}`
- : Prisma.empty;
+ const versionCondition = query.version
+ ? Prisma.sql`AND o."version" = ${query.version}`
+ : Prisma.empty;
- const observations = await prisma.$queryRaw<ObservationView[]>`
+ const observations = await prisma.$queryRaw<ObservationView[]>`
SELECT
o."id",
o."name",
@@ -100,7 +110,7 @@ export default withMiddlewares({
OFFSET ${(query.page - 1) * query.limit}
LIMIT ${query.limit}
`;
- const countRes = await prisma.$queryRaw<{ count: bigint }[]>`
+ 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}
@@ -112,20 +122,104 @@ export default withMiddlewares({
${fromStartTimeCondition}
${toStartTimeCondition}
`;
- if (countRes.length !== 1) {
- throw new InternalServerError("Unexpected totalItems result");
- }
- const totalItems = Number(countRes[0].count);
+ if (countRes.length !== 1) {
+ throw new InternalServerError("Unexpected totalItems result");
+ }
+ const totalItems = Number(countRes[0].count);
+
+ return {
+ data: observations.map(transformDbToApiObservation),
+ meta: {
+ page: query.page,
+ limit: query.limit,
+ totalItems,
+ totalPages: Math.ceil(totalItems / query.limit),
+ },
+ };
+ },
+ clickhouseExecution: async () => {
+ const [items, count] = await Promise.all([
+ generateObservationsForPublicApi({
+ projectId: auth.scope.projectId,
+ page: query.page ?? undefined,
+ limit: query.limit ?? undefined,
+ traceId: query.traceId ?? undefined,
+ userId: query.userId ?? undefined,
+ name: query.name ?? undefined,
+ type: query.type ?? undefined,
+ parentObservationId: query.parentObservationId ?? undefined,
+ fromStartTime: query.fromStartTime ?? undefined,
+ toStartTime: query.toStartTime ?? undefined,
+ version: query.version ?? undefined,
+ }),
+ getObservationsCountForPublicApi({
+ projectId: auth.scope.projectId,
+ page: query.page ?? undefined,
+ limit: query.limit ?? undefined,
+ traceId: query.traceId ?? undefined,
+ userId: query.userId ?? undefined,
+ name: query.name ?? undefined,
+ type: query.type ?? undefined,
+ parentObservationId: query.parentObservationId ?? undefined,
+ fromStartTime: query.fromStartTime ?? undefined,
+ toStartTime: query.toStartTime ?? undefined,
+ version: query.version ?? undefined,
+ }),
+ ]);
+ const uniqueModels: string[] = Array.from(
+ new Set(
+ items
+ .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,
+ },
+ })
+ : [];
- return {
- data: observations.map(transformDbToApiObservation),
- meta: {
- page: query.page,
- limit: query.limit,
- totalItems,
- totalPages: Math.ceil(totalItems / query.limit),
+ return {
+ data: items
+ .map((i) => {
+ const model = models.find((m) => m.id === i.modelId);
+ return {
+ ...i,
+ 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,
+ };
+ })
+ .map(transformDbToApiObservation),
+ meta: {
+ page: query.page,
+ limit: query.limit,
+ totalItems: count ?? 0,
+ totalPages: Math.ceil(count ?? 0 / query.limit),
+ },
+ };
},
- };
+ });
},
}),
});