Skip to content

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

refactor: refactor observations by id repo function (#6768)

Max Deichmannf478bb576301
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index eb605d86ba..6c43c6f2fb 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -34,6 +34,7 @@ import {
import { env } from "../../env";
import { TracingSearchType } from "../../interfaces/search";
import { ClickHouseClientConfigOptions } from "@clickhouse/client";
+import { ObservationType } from "../../domain";
/**
* Checks if observation exists in clickhouse.
@@ -278,18 +279,26 @@ export const getObservationForTraceIdByName = async (
return records.map(convertObservation);
};
-export const getObservationById = async (
- id: string,
- projectId: string,
- fetchWithInputOutput: boolean = false,
- startTime?: Date,
-) => {
- const records = await getObservationByIdInternal(
+export const getObservationById = async ({
+ id,
+ projectId,
+ fetchWithInputOutput = false,
+ startTime,
+ type,
+}: {
+ id: string;
+ projectId: string;
+ fetchWithInputOutput?: boolean;
+ startTime?: Date;
+ type?: ObservationType;
+}) => {
+ const records = await getObservationByIdInternal({
id,
projectId,
fetchWithInputOutput,
startTime,
- );
+ type,
+ });
const mapped = records.map(convertObservation);
if (mapped.length === 0) {
@@ -354,12 +363,19 @@ export const getObservationsById = async (
return records.map(convertObservation);
};
-const getObservationByIdInternal = async (
- id: string,
- projectId: string,
- fetchWithInputOutput: boolean = false,
- startTime?: Date,
-) => {
+const getObservationByIdInternal = async ({
+ id,
+ projectId,
+ fetchWithInputOutput = false,
+ startTime,
+ type,
+}: {
+ id: string;
+ projectId: string;
+ fetchWithInputOutput?: boolean;
+ startTime?: Date;
+ type?: ObservationType;
+}) => {
const query = `
SELECT
id,
@@ -395,6 +411,7 @@ const getObservationByIdInternal = async (
WHERE id = {id: String}
AND project_id = {projectId: String}
${startTime ? `AND toDate(start_time) = toDate({startTime: DateTime64(3)})` : ""}
+ ${type ? `AND type = {type: String}` : ""}
ORDER BY event_ts desc
LIMIT 1 by id, project_id`;
return await queryClickhouse<ObservationRecordReadType>({
diff --git a/web/src/__e2e__/api.servertest.ts b/web/src/__e2e__/api.servertest.ts
index df8d8f2d07..70d3eadb1a 100644
--- a/web/src/__e2e__/api.servertest.ts
+++ b/web/src/__e2e__/api.servertest.ts
@@ -115,7 +115,10 @@ describe("Ingestion Pipeline", () => {
expect(trace).not.toBeNull();
expect(trace?.name).toBe("test trace");
- const observation = await getObservationById(spanId, projectId);
+ const observation = await getObservationById({
+ id: spanId,
+ projectId,
+ });
expect(observation).not.toBeNull();
expect(observation?.name).toBe("test span");
diff --git a/web/src/__tests__/async/ingestion-api.servertest.ts b/web/src/__tests__/async/ingestion-api.servertest.ts
index 3ed69fb9d9..bef7c6e97f 100644
--- a/web/src/__tests__/async/ingestion-api.servertest.ts
+++ b/web/src/__tests__/async/ingestion-api.servertest.ts
@@ -94,7 +94,10 @@ describe("/api/public/ingestion API Endpoint", () => {
expect(response.status).toBe(207);
await waitForExpect(async () => {
- const trace = await getTraceById({ traceId: entity.body.id, projectId });
+ const trace = await getTraceById({
+ traceId: entity.body.id,
+ projectId,
+ });
expect(trace).toBeDefined();
expect(trace!.id).toBe(entity.body.id);
expect(trace!.projectId).toBe(projectId);
@@ -212,11 +215,11 @@ describe("/api/public/ingestion API Endpoint", () => {
expect(response.status).toBe(207);
await waitForExpect(async () => {
- const observation = await getObservationById(
- entity.body.id,
+ const observation = await getObservationById({
+ id: entity.body.id,
projectId,
- true,
- );
+ fetchWithInputOutput: true,
+ });
expect(observation).toBeDefined();
expect(observation!.id).toBe(entity.body.id);
expect(observation!.projectId).toBe(projectId);
@@ -333,7 +336,10 @@ describe("/api/public/ingestion API Endpoint", () => {
expect(response.status).toBe(207);
await waitForExpect(async () => {
- const trace = await getTraceById({ traceId: `${traceId}-${char}-test`, projectId });
+ const trace = await getTraceById({
+ traceId: `${traceId}-${char}-test`,
+ projectId,
+ });
expect(trace).toBeDefined();
expect(trace!.id).toBe(`${traceId}-${char}-test`);
expect(trace!.projectId).toBe(projectId);
@@ -569,11 +575,11 @@ describe("/api/public/ingestion API Endpoint", () => {
expect(response.status).toBe(207);
await waitForExpect(async () => {
- const observation = await getObservationById(
- observationId,
+ const observation = await getObservationById({
+ id: observationId,
projectId,
- true,
- );
+ fetchWithInputOutput: true,
+ });
expect(observation).toBeDefined();
expect(observation!.id).toBe(observationId);
expect(JSON.stringify(observation!.metadata)).toBe(
diff --git a/web/src/__tests__/async/repositories/observation-repository.servertest.ts b/web/src/__tests__/async/repositories/observation-repository.servertest.ts
index be97b33fde..c60e304da0 100644
--- a/web/src/__tests__/async/repositories/observation-repository.servertest.ts
+++ b/web/src/__tests__/async/repositories/observation-repository.servertest.ts
@@ -17,7 +17,12 @@ describe("Clickhouse Observations Repository Test", () => {
});
it("should throw if no observations are found", async () => {
- await expect(getObservationById(v4(), v4())).rejects.toThrow();
+ await expect(
+ getObservationById({
+ id: v4(),
+ projectId: v4(),
+ }),
+ ).rejects.toThrow();
});
it("should return an observation if exists", async () => {
@@ -58,7 +63,11 @@ describe("Clickhouse Observations Repository Test", () => {
await createObservationsCh([observation]);
- const result = await getObservationById(observationId, projectId, true);
+ const result = await getObservationById({
+ id: observationId,
+ projectId,
+ fetchWithInputOutput: true,
+ });
if (!result) {
throw new Error("Observation not found");
}
diff --git a/web/src/__tests__/prompts.v1.servertest.ts b/web/src/__tests__/prompts.v1.servertest.ts
index f355add0d2..c53a9f8cdc 100644
--- a/web/src/__tests__/prompts.v1.servertest.ts
+++ b/web/src/__tests__/prompts.v1.servertest.ts
@@ -464,7 +464,10 @@ describe("/api/public/prompts API Endpoint", () => {
// Delay to allow for async processing
await new Promise((resolve) => setTimeout(resolve, 500));
- const dbGeneration = await getObservationById(generationId, projectId);
+ const dbGeneration = await getObservationById({
+ id: generationId,
+ projectId,
+ });
expect(dbGeneration?.id).toBe(generationId);
expect(dbGeneration?.promptId).toBe(promptId);
@@ -523,7 +526,10 @@ describe("/api/public/prompts API Endpoint", () => {
expect(response.status).toBe(207);
expect(
- getObservationById(generationId, "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a"),
+ getObservationById({
+ id: generationId,
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ }),
).rejects.toThrow("not found");
});
diff --git a/web/src/__tests__/prompts.v2.servertest.ts b/web/src/__tests__/prompts.v2.servertest.ts
index 57886b442b..186c6a388c 100644
--- a/web/src/__tests__/prompts.v2.servertest.ts
+++ b/web/src/__tests__/prompts.v2.servertest.ts
@@ -405,7 +405,10 @@ describe("/api/public/v2/prompts API Endpoint", () => {
// Delay to allow for async processing
await new Promise((resolve) => setTimeout(resolve, 500));
- const dbGeneration = await getObservationById(generationId, projectId);
+ const dbGeneration = await getObservationById({
+ id: generationId,
+ projectId,
+ });
expect(dbGeneration?.id).toBe(generationId);
expect(dbGeneration?.promptId).toBe(promptId);
diff --git a/web/src/ee/features/annotation-queues/server/annotationQueueItems.ts b/web/src/ee/features/annotation-queues/server/annotationQueueItems.ts
index 3750e26237..0242d19776 100644
--- a/web/src/ee/features/annotation-queues/server/annotationQueueItems.ts
+++ b/web/src/ee/features/annotation-queues/server/annotationQueueItems.ts
@@ -82,10 +82,10 @@ export const queueItemRouter = createTRPCRouter({
};
if (item.objectType === AnnotationQueueObjectType.OBSERVATION) {
- const clickhouseObservation = await getObservationById(
- item.objectId,
- input.projectId,
- );
+ const clickhouseObservation = await getObservationById({
+ id: item.objectId,
+ projectId: input.projectId,
+ });
return {
...inflatedItem,
parentTraceId: clickhouseObservation?.traceId,
diff --git a/web/src/ee/features/annotation-queues/server/annotationQueues.ts b/web/src/ee/features/annotation-queues/server/annotationQueues.ts
index cdfc4f9914..3f14bbdd56 100644
--- a/web/src/ee/features/annotation-queues/server/annotationQueues.ts
+++ b/web/src/ee/features/annotation-queues/server/annotationQueues.ts
@@ -558,10 +558,10 @@ export const queueRouter = createTRPCRouter({
};
if (item.objectType === AnnotationQueueObjectType.OBSERVATION) {
- const clickhouseObservation = await getObservationById(
- item.objectId,
- input.projectId,
- );
+ const clickhouseObservation = await getObservationById({
+ id: item.objectId,
+ projectId: input.projectId,
+ });
return {
...inflatedUpdatedItem,
parentTraceId: clickhouseObservation?.traceId,
diff --git a/web/src/features/comments/validateCommentReferenceObject.ts b/web/src/features/comments/validateCommentReferenceObject.ts
index 8011794aa9..c0de40d9df 100644
--- a/web/src/features/comments/validateCommentReferenceObject.ts
+++ b/web/src/features/comments/validateCommentReferenceObject.ts
@@ -21,7 +21,10 @@ export const validateCommentReferenceObject = async ({
if (isObservationOrTrace(objectType)) {
let clickhouseObject;
if (objectType === CommentObjectType.OBSERVATION) {
- clickhouseObject = await getObservationById(objectId, projectId);
+ clickhouseObject = await getObservationById({
+ id: objectId,
+ projectId,
+ });
} else {
clickhouseObject = await getTraceById({
traceId: objectId,
diff --git a/web/src/pages/api/public/dataset-run-items.ts b/web/src/pages/api/public/dataset-run-items.ts
index dfcc25d187..351ade2c45 100644
--- a/web/src/pages/api/public/dataset-run-items.ts
+++ b/web/src/pages/api/public/dataset-run-items.ts
@@ -50,11 +50,11 @@ export default withMiddlewares({
// Backwards compatibility: historically, dataset run items were linked to observations, not traces
if (!traceId && observationId) {
- const observation = await getObservationById(
- observationId,
- auth.scope.projectId,
- true,
- );
+ const observation = await getObservationById({
+ id: observationId,
+ projectId: auth.scope.projectId,
+ fetchWithInputOutput: true,
+ });
if (observationId && !observation) {
throw new LangfuseNotFoundError("Observation not found");
}
diff --git a/web/src/pages/api/public/observations/[observationId].ts b/web/src/pages/api/public/observations/[observationId].ts
index 7f56d3a336..b5167339d4 100644
--- a/web/src/pages/api/public/observations/[observationId].ts
+++ b/web/src/pages/api/public/observations/[observationId].ts
@@ -15,11 +15,11 @@ export default withMiddlewares({
querySchema: GetObservationV1Query,
responseSchema: GetObservationV1Response,
fn: async ({ query, auth }) => {
- const clickhouseObservation = await getObservationById(
- query.observationId,
- auth.scope.projectId,
- true,
- );
+ const clickhouseObservation = await getObservationById({
+ id: query.observationId,
+ projectId: auth.scope.projectId,
+ fetchWithInputOutput: true,
+ });
if (!clickhouseObservation) {
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.ts
index d5f09a520c..61264316e0 100644
--- a/web/src/server/api/routers/observations.ts
+++ b/web/src/server/api/routers/observations.ts
@@ -19,12 +19,12 @@ export const observationsRouter = createTRPCRouter({
)
.query(async ({ input }) => {
try {
- const obs = await getObservationById(
- input.observationId,
- input.projectId,
- true,
- input.startTime ?? undefined,
- );
+ const obs = await getObservationById({
+ id: input.observationId,
+ projectId: input.projectId,
+ fetchWithInputOutput: true,
+ startTime: input.startTime ?? undefined,
+ });
if (!obs) {
throw new TRPCError({
code: "NOT_FOUND",
diff --git a/worker/src/__tests__/dataRetentionProcessing.test.ts b/worker/src/__tests__/dataRetentionProcessing.test.ts
index 8505e0c2de..b87f9fdd9c 100644
--- a/worker/src/__tests__/dataRetentionProcessing.test.ts
+++ b/worker/src/__tests__/dataRetentionProcessing.test.ts
@@ -270,9 +270,15 @@ describe("DataRetentionProcessingJob", () => {
} as Job);
// Then
- const traceOld = await getTraceById({ traceId: `${baseId}-trace-old`, projectId });
+ const traceOld = await getTraceById({
+ traceId: `${baseId}-trace-old`,
+ projectId,
+ });
expect(traceOld).toBeUndefined();
- const traceNew = await getTraceById({ traceId: `${baseId}-trace-new`, projectId });
+ const traceNew = await getTraceById({
+ traceId: `${baseId}-trace-new`,
+ projectId,
+ });
expect(traceNew).toBeDefined();
});
@@ -298,12 +304,12 @@ describe("DataRetentionProcessingJob", () => {
// Then
expect(() =>
- getObservationById(`${baseId}-observation-old`, projectId),
+ getObservationById({ id: `${baseId}-observation-old`, projectId }),
).rejects.toThrowError("not found");
- const observationNew = await getObservationById(
- `${baseId}-observation-new`,
+ const observationNew = await getObservationById({
+ id: `${baseId}-observation-new`,
projectId,
- );
+ });
expect(observationNew).toBeDefined();
});
diff --git a/worker/src/__tests__/projectDeletionProcessing.test.ts b/worker/src/__tests__/projectDeletionProcessing.test.ts
index b2c4b466af..af27b5f59f 100644
--- a/worker/src/__tests__/projectDeletionProcessing.test.ts
+++ b/worker/src/__tests__/projectDeletionProcessing.test.ts
@@ -135,12 +135,18 @@ describe("ProjectDeletionProcessingJob", () => {
} as Job);
// Then
- const trace = await getTraceById({ traceId: `${baseId}-trace`, projectId });
+ const trace = await getTraceById({
+ traceId: `${baseId}-trace`,
+ projectId,
+ });
expect(trace).toBeUndefined();
expect(() =>
- getObservationById(`${baseId}-observation`, projectId),
+ getObservationById({ id: `${baseId}-observation`, projectId }),
).rejects.toThrowError("not found");
- const score = await getScoreById({ projectId, scoreId: `${baseId}-score` });
+ const score = await getScoreById({
+ projectId,
+ scoreId: `${baseId}-score`,
+ });
expect(score).toBeUndefined();
});