Skip to content

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

chore: refactor observations domain (#6353)

Max Deichmann4c6e8964e311
diff --git a/packages/shared/src/domain.ts b/packages/shared/src/domain.ts
index cce6afa3e1..9c72af0625 100644
--- a/packages/shared/src/domain.ts
+++ b/packages/shared/src/domain.ts
@@ -28,3 +28,76 @@ export const TraceDomain = z.object({
});
export type TraceDomain = z.infer<typeof TraceDomain>;
+
+export const ObservationType = {
+ SPAN: "SPAN",
+ EVENT: "EVENT",
+ GENERATION: "GENERATION",
+} as const;
+export const ObservationTypeDomain = z.enum(["SPAN", "EVENT", "GENERATION"]);
+export type ObservationType = z.infer<typeof ObservationTypeDomain>;
+
+export const ObservationLevel = {
+ DEBUG: "DEBUG",
+ DEFAULT: "DEFAULT",
+ WARNING: "WARNING",
+ ERROR: "ERROR",
+} as const;
+export const ObservationLevelDomain = z.enum([
+ "DEBUG",
+ "DEFAULT",
+ "WARNING",
+ "ERROR",
+]);
+export type ObservationLevelType = z.infer<typeof ObservationLevelDomain>;
+
+export const ObservationDomain = z.object({
+ id: z.string(),
+ name: z.string(),
+ timestamp: z.date(),
+ environment: z.string(),
+ tags: z.array(z.string()),
+});
+export type ObservationDomain = z.infer<typeof ObservationDomain>;
+
+export const ObservationSchema = z.object({
+ id: z.string(),
+ traceId: z.string().nullable(),
+ projectId: z.string(),
+ environment: z.string(),
+ type: ObservationTypeDomain,
+ startTime: z.date(),
+ endTime: z.date().nullable(),
+ name: z.string().nullable(),
+ metadata: MetadataDomain,
+ parentObservationId: z.string().nullable(),
+ level: ObservationLevelDomain,
+ statusMessage: z.string().nullable(),
+ version: z.string().nullable(),
+ createdAt: z.date(),
+ updatedAt: z.date(),
+ model: z.string().nullable(),
+ internalModelId: z.string().nullable(),
+ modelParameters: jsonSchema.nullable(),
+ input: jsonSchema.nullable(),
+ output: jsonSchema.nullable(),
+ completionStartTime: z.date().nullable(),
+ promptId: z.string().nullable(),
+ promptName: z.string().nullable(),
+ promptVersion: z.number().nullable(),
+ latency: z.number().nullable(),
+ timeToFirstToken: z.number().nullable(),
+ usageDetails: z.record(z.string(), z.number()),
+ costDetails: z.record(z.string(), z.number()),
+ providedCostDetails: z.record(z.string(), z.number()),
+ // aggregated data from cost_details
+ inputCost: z.number().nullable(),
+ outputCost: z.number().nullable(),
+ totalCost: z.number().nullable(),
+ // aggregated data from usage_details
+ inputUsage: z.number(),
+ outputUsage: z.number(),
+ totalUsage: z.number(),
+});
+
+export type Observation = z.infer<typeof ObservationSchema>;
diff --git a/packages/shared/src/observationsTable.ts b/packages/shared/src/observationsTable.ts
index f73a21d62c..bea62b5e5b 100644
--- a/packages/shared/src/observationsTable.ts
+++ b/packages/shared/src/observationsTable.ts
@@ -1,8 +1,8 @@
+import { ObservationLevelType } from "./domain";
import {
type OptionsDefinition,
type ColumnDefinition,
} from "./tableDefinitions";
-import { ObservationLevelType } from "./server";
// to be used server side
export const observationsTableCols: ColumnDefinition[] = [
diff --git a/packages/shared/src/server/queries/createGenerationsQuery.ts b/packages/shared/src/server/queries/createGenerationsQuery.ts
index 9d67de3a7c..a9c8a86862 100644
--- a/packages/shared/src/server/queries/createGenerationsQuery.ts
+++ b/packages/shared/src/server/queries/createGenerationsQuery.ts
@@ -1,21 +1,14 @@
-import { ObservationView } from "../repositories";
+import { Observation } from "../../domain";
type AdditionalObservationFields = {
traceName: string | null;
traceTags: Array<string>;
- usageDetails: Record<string, number>;
- costDetails: Record<string, number>;
};
-export type FullObservation = AdditionalObservationFields & ObservationView;
+export type FullObservation = AdditionalObservationFields & Observation;
export type FullObservations = Array<FullObservation>;
export type FullObservationsWithScores = Array<
FullObservation & { scores?: Record<string, string[] | number[]> | null }
>;
-
-export type IOAndMetadataOmittedObservations = Array<
- Omit<ObservationView, "input" | "output" | "metadata"> &
- AdditionalObservationFields
->;
diff --git a/packages/shared/src/server/queries/index.ts b/packages/shared/src/server/queries/index.ts
index 6a1f220f09..b64e05b237 100644
--- a/packages/shared/src/server/queries/index.ts
+++ b/packages/shared/src/server/queries/index.ts
@@ -2,7 +2,6 @@ export { createSessionsAllQuery } from "./createSessionsAllQuery";
export {
type FullObservations,
type FullObservationsWithScores,
- type IOAndMetadataOmittedObservations,
} from "./createGenerationsQuery";
export {
FilterList,
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index f61bece3a3..f0f6dc9d63 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -26,10 +26,7 @@ import { TableCount } from "./types";
import { OrderByState } from "../../interfaces/orderBy";
import { getTracesByIds } from "./traces";
import { convertDateToClickhouseDateTime } from "../clickhouse/client";
-import {
- convertObservationToView,
- convertObservation,
-} from "./observations_converters";
+import { convertObservation } from "./observations_converters";
import { clickhouseSearchCondition } from "../queries/clickhouse-sql/search";
import {
OBSERVATIONS_TO_TRACE_INTERVAL,
@@ -101,7 +98,7 @@ export const upsertObservation = async (
});
};
-export const getObservationsViewForTrace = async (
+export const getObservationsForTrace = async (
traceId: string,
projectId: string,
timestamp?: Date,
@@ -161,7 +158,7 @@ export const getObservationsViewForTrace = async (
},
});
- return records.map(convertObservationToView);
+ return records.map(convertObservation);
};
export const getObservationForTraceIdByName = async (
@@ -227,7 +224,7 @@ export const getObservationForTraceIdByName = async (
},
});
- return records.map(convertObservationToView);
+ return records.map(convertObservation);
};
export const getObservationById = async (
@@ -306,33 +303,6 @@ export const getObservationsById = async (
return records.map(convertObservation);
};
-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,
@@ -467,7 +437,7 @@ export const getObservationsTableWithModelData = async (
const trace = traces.find((t) => t.id === o.trace_id);
const model = models.find((m) => m.id === o.internal_model_id);
return {
- ...convertObservationToView(o),
+ ...convertObservation(o),
latency: o.latency ? Number(o.latency) / 1000 : null,
timeToFirstToken: o.time_to_first_token
? Number(o.time_to_first_token) / 1000
diff --git a/packages/shared/src/server/repositories/observations_converters.ts b/packages/shared/src/server/repositories/observations_converters.ts
index 409515624a..d67ce8e509 100644
--- a/packages/shared/src/server/repositories/observations_converters.ts
+++ b/packages/shared/src/server/repositories/observations_converters.ts
@@ -1,54 +1,17 @@
-import { Prisma } from "@prisma/client";
-import Decimal from "decimal.js";
import { parseClickhouseUTCDateTimeFormat } from "./clickhouse";
import { ObservationRecordReadType } from "./definitions";
import { parseJsonPrioritised } from "../../utils/json";
import {
Observation,
- ObservationView,
- ObservationType,
ObservationLevelType,
-} from "./types";
-
-export const convertObservationToView = (
- record: ObservationRecordReadType,
-): Omit<ObservationView, "inputPrice" | "outputPrice" | "totalPrice"> & {
- usageDetails: Record<string, number>;
- costDetails: Record<string, number>;
-} => {
- // 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 {
- ...rest,
- latency: record.end_time
- ? parseClickhouseUTCDateTimeFormat(record.end_time).getTime() -
- parseClickhouseUTCDateTimeFormat(record.start_time).getTime()
- : null,
-
- promptName: record.prompt_name ?? null,
- promptVersion: record.prompt_version ?? null,
- modelId: record.internal_model_id ?? null,
- };
-};
+ ObservationType,
+} from "../../domain";
export const convertObservation = (
record: ObservationRecordReadType,
-): Omit<Observation, "internalModel"> & {
- promptName: string | null;
- promptVersion: number | null;
- latency: number | null;
- timeToFirstToken: number | null;
- usageDetails: Record<string, number>;
- costDetails: Record<string, number>;
-} => {
- const reducedUsageDetails = reduceUsageOrCostDetails(record.usage_details);
+): Observation => {
const reducedCostDetails = reduceUsageOrCostDetails(record.cost_details);
- const reducedProvidedCostDetails = reduceUsageOrCostDetails(
- record.provided_cost_details,
- );
+ const reducedUsageDetails = reduceUsageOrCostDetails(record.usage_details);
return {
id: record.id,
@@ -73,14 +36,12 @@ export const convertObservation = (
level: record.level as ObservationLevelType,
statusMessage: record.status_message ?? null,
version: record.version ?? null,
- input: (record.input
- ? parseJsonPrioritised(record.input)
- : null) as Prisma.JsonValue | null,
- output: (record.output
- ? parseJsonPrioritised(record.output)
- : null) as Prisma.JsonValue | null,
+ input: record.input ? (parseJsonPrioritised(record.input) ?? null) : null,
+ output: record.output
+ ? (parseJsonPrioritised(record.output) ?? null)
+ : null,
modelParameters: record.model_parameters
- ? JSON.parse(record.model_parameters)
+ ? (JSON.parse(record.model_parameters) ?? null)
: null,
completionStartTime: record.completion_start_time
? parseClickhouseUTCDateTimeFormat(record.completion_start_time)
@@ -88,29 +49,6 @@ export const convertObservation = (
promptId: record.prompt_id ?? null,
createdAt: parseClickhouseUTCDateTimeFormat(record.created_at),
updatedAt: parseClickhouseUTCDateTimeFormat(record.updated_at),
- promptTokens: reducedUsageDetails.input ?? 0,
- completionTokens: reducedUsageDetails.output ?? 0,
- totalTokens: reducedUsageDetails.total ?? 0,
- calculatedInputCost:
- reducedCostDetails.input != null
- ? new Decimal(reducedCostDetails.input)
- : null,
- calculatedOutputCost:
- reducedCostDetails.output != null
- ? new Decimal(reducedCostDetails.output)
- : null,
- calculatedTotalCost: record.cost_details?.total
- ? new Decimal(record.cost_details.total)
- : null,
- inputCost:
- reducedProvidedCostDetails.input != null
- ? new Decimal(reducedProvidedCostDetails.input)
- : null,
- outputCost:
- reducedProvidedCostDetails.output != null
- ? new Decimal(reducedProvidedCostDetails.output)
- : null,
- totalCost: record.total_cost ? new Decimal(record.total_cost) : null,
usageDetails: Object.fromEntries(
Object.entries(record.usage_details ?? {}).map(([key, value]) => [
key,
@@ -123,9 +61,14 @@ export const convertObservation = (
Number(value),
]),
),
+ providedCostDetails: Object.fromEntries(
+ Object.entries(record.provided_cost_details ?? {}).map(([key, value]) => [
+ key,
+ Number(value),
+ ]),
+ ),
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
@@ -139,6 +82,12 @@ export const convertObservation = (
parseClickhouseUTCDateTimeFormat(record.start_time).getTime()) /
1000
: null,
+ inputCost: reducedCostDetails.input,
+ outputCost: reducedCostDetails.output,
+ totalCost: reducedCostDetails.total,
+ inputUsage: reducedUsageDetails.input ?? 0,
+ outputUsage: reducedUsageDetails.output ?? 0,
+ totalUsage: reducedUsageDetails.total ?? 0,
};
};
diff --git a/packages/shared/src/server/repositories/types.ts b/packages/shared/src/server/repositories/types.ts
index 380cc37b6b..f54f47ad84 100644
--- a/packages/shared/src/server/repositories/types.ts
+++ b/packages/shared/src/server/repositories/types.ts
@@ -1,106 +1,15 @@
-import { Prisma, ScoreDataType } from "@prisma/client";
-import Decimal from "decimal.js";
+import { ScoreDataType } from "@prisma/client";
export type TableCount = {
count: number;
};
-
-export const ObservationType = {
- SPAN: "SPAN",
- EVENT: "EVENT",
- GENERATION: "GENERATION",
-} as const;
-export type ObservationType =
- (typeof ObservationType)[keyof typeof ObservationType];
-export const ObservationLevel = {
- DEBUG: "DEBUG",
- DEFAULT: "DEFAULT",
- WARNING: "WARNING",
- ERROR: "ERROR",
-} as const;
-export type ObservationLevelType =
- (typeof ObservationLevel)[keyof typeof ObservationLevel];
export const ScoreSource = {
ANNOTATION: "ANNOTATION",
API: "API",
EVAL: "EVAL",
} as const;
-export type ScoreSourceType = (typeof ScoreSource)[keyof typeof ScoreSource];
-
-export type Observation = {
- id: string;
- traceId: string | null;
- projectId: string;
- environment: string;
- type: ObservationType;
- startTime: Date;
- endTime: Date | null;
- name: string | null;
- metadata: Prisma.JsonValue | null;
- parentObservationId: string | null;
- level: ObservationLevelType;
- statusMessage: string | null;
- version: string | null;
- createdAt: Date;
- updatedAt: Date;
- model: string | null;
- internalModel: string | null;
- internalModelId: string | null;
- modelParameters: unknown | null;
- input: unknown | null;
- output: unknown | 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 type ObservationView = {
- id: string;
- traceId: string | null;
- projectId: string;
- type: ObservationType;
- startTime: Date;
- endTime: Date | null;
- environment: string;
- name: string | null;
- metadata: Prisma.JsonValue | null;
- parentObservationId: string | null;
- level: ObservationLevelType;
- statusMessage: string | null;
- version: string | null;
- createdAt: Date;
- updatedAt: Date;
- model: string | null;
- modelParameters: unknown | null;
- input: unknown | null;
- output: unknown | null;
- promptTokens: number;
- completionTokens: number;
- totalTokens: number;
- unit: string | null;
- completionStartTime: Date | null;
- promptId: string | null;
- promptName: string | null;
- promptVersion: number | null;
- modelId: string | null;
- inputPrice: Decimal | null;
- outputPrice: Decimal | null;
- totalPrice: Decimal | null;
- calculatedInputCost: Decimal | null;
- calculatedOutputCost: Decimal | null;
- calculatedTotalCost: Decimal | null;
- latency: number | null;
- timeToFirstToken: number | null;
-};
+export type ScoreSourceType = (typeof ScoreSource)[keyof typeof ScoreSource];
export type Score = {
id: string;
diff --git a/packages/shared/src/server/services/traces-ui-table-service.ts b/packages/shared/src/server/services/traces-ui-table-service.ts
index c58629d243..ad30bcd4a2 100644
--- a/packages/shared/src/server/services/traces-ui-table-service.ts
+++ b/packages/shared/src/server/services/traces-ui-table-service.ts
@@ -18,12 +18,11 @@ import { ScoreAggregate } from "../../features/scores";
import {
OBSERVATIONS_TO_TRACE_INTERVAL,
SCORE_TO_TRACE_OBSERVATIONS_INTERVAL,
- ObservationLevelType,
- reduceUsageOrCostDetails,
parseClickhouseUTCDateTimeFormat,
queryClickhouse,
+ reduceUsageOrCostDetails,
} from "../repositories";
-import { TraceDomain } from "../../domain";
+import { ObservationLevelType, TraceDomain } from "../../domain";
export type TracesTableReturnType = Pick<
TraceRecordReadType,
diff --git a/packages/shared/src/tableDefinitions/tracesTable.ts b/packages/shared/src/tableDefinitions/tracesTable.ts
index 760a362057..85d1015316 100644
--- a/packages/shared/src/tableDefinitions/tracesTable.ts
+++ b/packages/shared/src/tableDefinitions/tracesTable.ts
@@ -1,5 +1,4 @@
-import { ObservationLevelType } from "../server";
-import { ColumnDefinition, OptionsDefinition } from "..";
+import { ColumnDefinition, ObservationLevelType, OptionsDefinition } from "..";
export const tracesOnlyCols: ColumnDefinition[] = [
{
diff --git a/web/src/__tests__/async/repositories/observation-repository.servertest.ts b/web/src/__tests__/async/repositories/observation-repository.servertest.ts
index 1c33074ddc..0f7f0db737 100644
--- a/web/src/__tests__/async/repositories/observation-repository.servertest.ts
+++ b/web/src/__tests__/async/repositories/observation-repository.servertest.ts
@@ -1,10 +1,12 @@
-import { createObservationsCh } from "@langfuse/shared/src/server";
+import {
+ createObservation,
+ createObservationsCh,
+} from "@langfuse/shared/src/server";
import { pruneDatabase } from "@/src/__tests__/test-utils";
import {
getObservationById,
- getObservationsViewForTrace,
+ getObservationsForTrace,
} from "@langfuse/shared/src/server";
-import Decimal from "decimal.js";
import { v4 } from "uuid";
const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
@@ -22,7 +24,7 @@ describe("Clickhouse Observations Repository Test", () => {
const observationId = v4();
const traceId = v4();
- const observation = {
+ const observation = createObservation({
id: observationId,
trace_id: traceId,
project_id: projectId,
@@ -52,7 +54,7 @@ describe("Clickhouse Observations Repository Test", () => {
prompt_version: 1,
end_time: Date.now(),
completion_start_time: Date.now(),
- };
+ });
await createObservationsCh([observation]);
@@ -77,20 +79,20 @@ describe("Clickhouse Observations Repository Test", () => {
expect(result.internalModelId).toEqual(observation.internal_model_id);
expect(result.modelParameters).toEqual({ something: "sample_param" });
expect(result.promptId).toEqual(observation.prompt_id);
- expect(result.endTime).toEqual(new Date(observation.end_time));
+ expect(result.endTime).toEqual(new Date(observation.end_time!));
expect(result.completionStartTime).toEqual(
- new Date(observation.completion_start_time),
+ new Date(observation.completion_start_time!),
);
- expect(result.totalCost).toEqual(new Decimal(observation.total_cost));
- expect(result.promptTokens).toEqual(1234);
- expect(result.completionTokens).toEqual(5678);
- expect(result.totalTokens).toEqual(6912);
+ expect(result.totalCost).toEqual(observation.total_cost!);
+ expect(result.inputUsage).toEqual(1234);
+ expect(result.outputUsage).toEqual(5678);
+ expect(result.totalUsage).toEqual(6912);
});
it("should return an observation view", async () => {
const observationId = v4();
const traceId = v4();
- const observation = {
+ const observation = createObservation({
id: observationId,
trace_id: traceId,
project_id: projectId,
@@ -120,11 +122,11 @@ describe("Clickhouse Observations Repository Test", () => {
prompt_version: 1,
end_time: Date.now(),
completion_start_time: Date.now() + 1000,
- };
+ });
await createObservationsCh([observation]);
- const result = await getObservationsViewForTrace(traceId, projectId);
+ const result = await getObservationsForTrace(traceId, projectId);
if (!result || result.length === 0) {
throw new Error("Observation not found");
}
@@ -152,18 +154,22 @@ describe("Clickhouse Observations Repository Test", () => {
something: "sample_param",
});
expect(firstObservation.promptId).toEqual(observation.prompt_id);
- expect(firstObservation.endTime).toEqual(new Date(observation.end_time));
+ expect(firstObservation.endTime).toEqual(new Date(observation.end_time!));
expect(firstObservation.timeToFirstToken).toEqual(
- (new Date(observation.completion_start_time).getTime() -
+ (new Date(observation.completion_start_time!).getTime() -
new Date(observation.start_time).getTime()) /
1000,
);
expect(firstObservation.timeToFirstToken).toBeGreaterThan(0);
- expect(firstObservation.calculatedTotalCost).toEqual(
- new Decimal(observation.total_cost),
+ expect(firstObservation.inputCost).toEqual(
+ observation.cost_details!.input!,
+ );
+ expect(firstObservation.outputCost).toEqual(
+ observation.cost_details!.output!,
);
- expect(firstObservation.promptTokens).toEqual(1234);
- expect(firstObservation.completionTokens).toEqual(5678);
- expect(firstObservation.totalTokens).toEqual(6912);
+ expect(firstObservation.totalCost).toEqual(observation.total_cost!);
+ expect(firstObservation.inputUsage).toEqual(1234);
+ expect(firstObservation.outputUsage).toEqual(5678);
+ expect(firstObservation.totalUsage).toEqual(6912);
});
});
diff --git a/web/src/__tests__/async/scores-api.servertest.ts b/web/src/__tests__/async/scores-api.servertest.ts
index 5f0b666a21..bf687e0c5f 100644
--- a/web/src/__tests__/async/scores-api.servertest.ts
+++ b/web/src/__tests__/async/scores-api.servertest.ts
@@ -28,7 +28,7 @@ describe("/api/public/scores API Endpoint", () => {
const scoreId = v4();
const traceId = v4();
- const score = {
+ const score = createScore({
id: scoreId,
project_id: projectId,
trace_id: traceId,
@@ -43,7 +43,7 @@ describe("/api/public/scores API Endpoint", () => {
updated_at: Date.now(),
event_ts: Date.now(),
is_deleted: 0,
- };
+ });
await createScoresCh([score]);
diff --git a/web/src/components/table/use-cases/observations.tsx b/web/src/components/table/use-cases/observations.tsx
index 54adc418e2..d53b6053bd 100644
--- a/web/src/components/table/use-cases/observations.tsx
+++ b/web/src/components/table/use-cases/observations.tsx
@@ -27,7 +27,6 @@ import { LevelColors } from "@/src/components/level-colors";
import { numberFormatter, usdFormatter } from "@/src/utils/numbers";
import { observationsTableColsWithOptions } from "@langfuse/shared";
import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
-import type Decimal from "decimal.js";
import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";
import { IOTableCell } from "@/src/components/ui/CodeJsonViewer";
import {
@@ -70,14 +69,14 @@ export type ObservationsTableRow = {
input?: unknown;
output?: unknown;
metadata?: unknown;
- inputCost?: Decimal;
- outputCost?: Decimal;
- totalCost?: Decimal;
+ inputCost?: number;
+ outputCost?: number;
+ totalCost?: number;
traceName?: string;
usage: {
- promptTokens: number;
- completionTokens: number;
- totalTokens: number;
+ inputUsage: number;
+ outputUsage: number;
+ totalUsage: number;
};
usageDetails: Record<string, number>;
costDetails: Record<string, number>;
@@ -443,10 +442,10 @@ export default function ObservationsTable({
header: "Input Cost",
size: 120,
cell: ({ row }) => {
- const value: Decimal | undefined = row.getValue("inputCost");
+ const value: number | undefined = row.getValue("inputCost");
return value !== undefined ? (
- <span>{usdFormatter(value.toNumber())}</span>
+ <span>{usdFormatter(value)}</span>
) : undefined;
},
enableHiding: true,
@@ -459,10 +458,10 @@ export default function ObservationsTable({
header: "Output Cost",
size: 120,
cell: ({ row }) => {
- const value: Decimal | undefined = row.getValue("outputCost");
+ const value: number | undefined = row.getValue("outputCost");
return value !== undefined ? (
- <span>{usdFormatter(value.toNumber())}</span>
+ <span>{usdFormatter(value)}</span>
) : undefined;
},
enableHiding: true,
@@ -475,12 +474,12 @@ export default function ObservationsTable({
id: "totalCost",
size: 120,
cell: ({ row }) => {
- const value: Decimal | undefined = row.getValue("totalCost");
+ const value: number | undefined = row.getValue("totalCost");
return value !== undefined ? (
<BreakdownTooltip details={row.original.costDetails} isCost>
<div className="flex items-center gap-1">
- <span>{usdFormatter(value.toNumber())}</span>
+ <span>{usdFormatter(value)}</span>
<InfoIcon className="h-3 w-3" />
</div>
</BreakdownTooltip>
@@ -642,17 +641,17 @@ export default function ObservationsTable({
size: 150,
cell: ({ row }) => {
const value: {
- promptTokens: number;
- completionTokens: number;
- totalTokens: number;
+ inputUsage: number;
+ outputUsage: number;
+ totalUsage: number;
} = row.getValue("usage");
return (
<BreakdownTooltip details={row.original.usageDetails}>
<div className="flex items-center gap-1">
<TokenUsageBadge
- promptTokens={value.promptTokens}
- completionTokens={value.completionTokens}
- totalTokens={value.totalTokens}
+ inputUsage={value.inputUsage}
+ outputUsage={value.outputUsage}
+ totalUsage={value.totalUsage}
inline
/>
<InfoIcon className="h-3 w-3" />
@@ -822,19 +821,19 @@ export default function ObservationsTable({
generation.scores,
),
latency: generation.latency ?? undefined,
- totalCost: generation.calculatedTotalCost ?? undefined,
- inputCost: generation.calculatedInputCost ?? undefined,
- outputCost: generation.calculatedOutputCost ?? undefined,
+ totalCost: generation.totalCost ?? undefined,
+ inputCost: generation.inputCost ?? undefined,
+ outputCost: generation.outputCost ?? undefined,
name: generation.name ?? undefined,
version: generation.version ?? "",
model: generation.model ?? "",
- modelId: generation.modelId ?? undefined,
+ modelId: generation.internalModelId ?? undefined,
level: generation.level,
statusMessage: generation.statusMessage ?? undefined,
usage: {
- promptTokens: generation.promptTokens,
- completionTokens: generation.completionTokens,
- totalTokens: generation.totalTokens,
+ inputUsage: generation.inputUsage,
+ outputUsage: generation.outputUsage,
+ totalUsage: generation.totalUsage,
},
promptId: generation.promptId ?? undefined,
promptName: generation.promptName ?? undefined,
diff --git a/web/src/components/table/use-cases/sessions.tsx b/web/src/components/table/use-cases/sessions.tsx
index 60f04216aa..5fc64f8d57 100644
--- a/web/src/components/table/use-cases/sessions.tsx
+++ b/web/src/components/table/use-cases/sessions.tsx
@@ -468,9 +468,9 @@ export default function SessionsTable({
}
return (
<TokenUsageBadge
- promptTokens={Number(promptTokens)}
- completionTokens={Number(completionTokens)}
- totalTokens={Number(totalTokens)}
+ inputUsage={Number(promptTokens ?? 0)}
+ outputUsage={Number(completionTokens ?? 0)}
+ totalUsage={Number(totalTokens ?? 0)}
inline
/>
);
diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsx
index 6ae7107b0e..f25de825e8 100644
--- a/web/src/components/table/use-cases/traces.tsx
+++ b/web/src/components/table/use-cases/traces.tsx
@@ -110,9 +110,9 @@ export type TracesTableRow = {
metadata?: unknown;
tags: string[];
usage: {
- promptTokens?: bigint;
- completionTokens?: bigint;
- totalTokens?: bigint;
+ inputUsage?: bigint;
+ outputUsage?: bigint;
+ totalUsage?: bigint;
};
usageDetails?: Record<string, number>;
costDetails?: Record<string, number>;
@@ -551,7 +551,7 @@ export default function TracesTable({
cell: ({ row }) => {
const value: TracesTableRow["usage"] = row.getValue("usage");
if (!traceMetrics.data) return <Skeleton className="h-3 w-1/2" />;
- return <span>{numberFormatter(value.promptTokens, 0)}</span>;
+ return <span>{numberFormatter(value.inputUsage, 0)}</span>;
},
enableHiding: true,
defaultHidden: true,
@@ -565,7 +565,7 @@ export default function TracesTable({
cell: ({ row }) => {
const value: TracesTableRow["usage"] = row.getValue("usage");
if (!traceMetrics.data) return <Skeleton className="h-3 w-1/2" />;
- return <span>{numberFormatter(value.completionTokens, 0)}</span>;
+ return <span>{numberFormatter(value.outputUsage, 0)}</span>;
},
enableHiding: true,
defaultHidden: true,
@@ -579,7 +579,7 @@ export default function TracesTable({
cell: ({ row }) => {
const value: TracesTableRow["usage"] = row.getValue("usage");
if (!traceMetrics.data) return <Skeleton className="h-3 w-1/2" />;
- return <span>{numberFormatter(value.totalTokens, 0)}</span>;
+ return <span>{numberFormatter(value.totalUsage, 0)}</span>;
},
enableHiding: true,
defaultHidden: true,
@@ -597,9 +597,9 @@ export default function TracesTable({
<BreakdownTooltip details={row.original.usageDetails ?? []}>
<div className="flex items-center gap-1">
<TokenUsageBadge
- promptTokens={value.promptTokens ?? 0}
- completionTokens={value.completionTokens ?? 0}
- totalTokens={value.totalTokens ?? 0}
+ inputUsage={Number(value.inputUsage ?? 0)}
+ outputUsage={Number(value.outputUsage ?? 0)}
+ totalUsage={Number(value.totalUsage ?? 0)}
inline
/>
<InfoIcon className="h-3 w-3" />
@@ -937,9 +937,9 @@ export default function TracesTable({
latency: trace.latency === null ? undefined : trace.latency,
tags: trace.tags,
usage: {
- promptTokens: trace.promptTokens,
- completionTokens: trace.completionTokens,
- totalTokens: trace.totalTokens,
+ inputUsage: trace.promptTokens,
+ outputUsage: trace.completionTokens,
+ totalUsage: trace.totalTokens,
},
levelCounts: {
errorCount: trace.errorCount,
diff --git a/web/src/components/token-usage-badge.tsx b/web/src/components/token-usage-badge.tsx
index bd82364455..ad1d658981 100644
--- a/web/src/components/token-usage-badge.tsx
+++ b/web/src/components/token-usage-badge.tsx
@@ -9,14 +9,14 @@ export const AggUsageBadge = (props: {
variant?: "default" | "secondary" | "destructive" | "outline" | "tertiary";
}) => {
const usage = {
- promptTokens: props.observations
- .map((o) => o.promptTokens)
+ inputUsage: props.observations
+ .map((o) => o.inputUsage)
.reduce((a, b) => a + b, 0),
- completionTokens: props.observations
- .map((o) => o.completionTokens)
+ outputUsage: props.observations
+ .map((o) => o.outputUsage)
.reduce((a, b) => a + b, 0),
- totalTokens: props.observations
- .map((o) => o.totalTokens)
+ totalUsage: props.observations
+ .map((o) => o.totalUsage)
.reduce((a, b) => a + b, 0),
};
return (
@@ -34,9 +34,9 @@ export const TokenUsageBadge = (
observation: Observation;
}
| {
- promptTokens: number | bigint;
- completionTokens: number | bigint;
- totalTokens: number | bigint;
+ inputUsage: number;
+ outputUsage: number;
+ totalUsage: number;
}
) & {
inline?: boolean;
@@ -47,20 +47,20 @@ export const TokenUsageBadge = (
const usage =
"observation" in props
? {
- promptTokens: props.observation.promptTokens,
- completionTokens: props.observation.completionTokens,
- totalTokens: props.observation.totalTokens,
+ inputUsage: props.observation.inputUsage,
+ outputUsage: props.observation.outputUsage,
+ totalUsage: props.observation.totalUsage,
}
: props;
if (
- usage.promptTokens === 0 &&
- usage.completionTokens === 0 &&
- usage.totalTokens === 0
+ usage.inputUsage === 0 &&
+ usage.outputUsage === 0 &&
+ usage.totalUsage === 0
)
return <></>;
- const content = `${numberFormatter(usage.promptTokens, 0)} → ${numberFormatter(usage.completionTokens, 0)} (∑ ${numberFormatter(usage.totalTokens, 0)})`;
+ const content = `${numberFormatter(usage.inputUsage, 0)} → ${numberFormatter(usage.outputUsage, 0)} (∑ ${numberFormatter(usage.totalUsage, 0)})`;
if (props.inline)
return (
diff --git a/web/src/components/trace/ObservationPreview.tsx b/web/src/components/trace/ObservationPreview.tsx
index 2f04c3e38c..1efaaea6ce 100644
--- a/web/src/components/trace/ObservationPreview.tsx
+++ b/web/src/components/trace/ObservationPreview.tsx
@@ -256,9 +256,9 @@ export const ObservationPreview = ({
className="flex items-center gap-1"
>
<span>
- {preloadedObservation.promptTokens} prompt →{" "}
- {preloadedObservation.completionTokens} completion (∑{" "}
- {preloadedObservation.totalTokens})
+ {preloadedObservation.inputUsage} prompt →{" "}
+ {preloadedObservation.outputUsage} completion (∑{" "}
+ {preloadedObservation.totalUsage})
</span>
<InfoIcon className="h-3 w-3" />
</Badge>
@@ -270,10 +270,10 @@ export const ObservationPreview = ({
</Badge>
) : undefined}
{preloadedObservation.model ? (
- preloadedObservation.modelId ? (
+ preloadedObservation.internalModelId ? (
<Badge>
<Link
- href={`/project/${preloadedObservation.projectId}/settings/models/${preloadedObservation.modelId}`}
+ href={`/project/${preloadedObservation.projectId}/settings/models/${preloadedObservation.internalModelId}`}
className="flex items-center"
title="View model details"
>
diff --git a/web/src/components/trace/ObservationTree.tsx b/web/src/components/trace/ObservationTree.tsx
index c9fe543185..3f6cfa2bd4 100644
--- a/web/src/components/trace/ObservationTree.tsx
+++ b/web/src/components/trace/ObservationTree.tsx
@@ -45,8 +45,8 @@ export const ObservationTree = ({
expandAll: () => void;
trace: Omit<TraceDomain, "input" | "output"> & {
latency?: number;
- input: string | undefined;
- output: string | undefined;
+ input: string | null;
+ output: string | null;
};
scores: APIScore[];
currentObservationId: string | undefined;
@@ -130,8 +130,8 @@ export const ObservationTree = ({
const ObservationTreeTraceNode = (props: {
trace: Omit<TraceDomain, "input" | "output"> & {
- input: string | undefined;
- output: string | undefined;
+ input: string | null;
+ output: string | null;
latency?: number;
};
expandAll: () => void;
@@ -415,9 +415,9 @@ const ObservationTreeNodeCard = ({
{/* Metrics on their own line */}
{showMetrics && (
<>
- {(observation.promptTokens ||
- observation.completionTokens ||
- observation.totalTokens ||
+ {(observation.inputUsage ||
+ observation.outputUsage ||
+ observation.totalUsage ||
duration ||
totalCost) && (
<div className="flex w-full flex-wrap gap-2">
@@ -436,13 +436,12 @@ const ObservationTreeNodeCard = ({
{formatIntervalSeconds(duration / 1000)}
</span>
) : null}
- {observation.promptTokens ||
- observation.completionTokens ||
- observation.totalTokens ? (
+ {observation.inputUsage ||
+ observation.outputUsage ||
+ observation.totalUsage ? (
<span className="text-xs text-muted-foreground">
- {observation.promptTokens} →{" "}
- {observation.completionTokens} (∑{" "}
- {observation.totalTokens})
+ {observation.inputUsage} → {observation.outputUsage} (∑{" "}
+ {observation.totalUsage})
</span>
) : null}
{totalCost ? (
diff --git a/web/src/components/trace/TracePreview.tsx b/web/src/components/trace/TracePreview.tsx
index 5d93c9e6e9..8201494323 100644
--- a/web/src/components/trace/TracePreview.tsx
+++ b/web/src/components/trace/TracePreview.tsx
@@ -46,8 +46,8 @@ export const TracePreview = ({
}: {
trace: Omit<TraceDomain, "input" | "output"> & {
latency?: number;
- input: string | undefined;
- output: string | undefined;
+ input: string | null;
+ output: string | null;
};
observations: ObservationReturnTypeWithMetadata[];
scores: APIScore[];
diff --git a/web/src/components/trace/TraceTimelineView.tsx b/web/src/components/trace/TraceTimelineView.tsx
index 9ee33438db..5c3eff0324 100644
--- a/web/src/components/trace/TraceTimelineView.tsx
+++ b/web/src/components/trace/TraceTimelineView.tsx
@@ -414,8 +414,8 @@ export function TraceTimelineView({
}: {
trace: Omit<TraceDomain, "input" | "output"> & {
latency?: number;
- input: string | undefined;
- output: string | undefined;
+ input: string | null;
+ output: string | null;
};
observations: Array<ObservationReturnTypeWithMetadata>;
projectId: string;
diff --git a/web/src/components/trace/index.tsx b/web/src/components/trace/index.tsx
index 4c8b1b0ecb..56be25f012 100644
--- a/web/src/components/trace/index.tsx
+++ b/web/src/components/trace/index.tsx
@@ -54,8 +54,8 @@ const getNestedObservationKeys = (
export function Trace(props: {
observations: Array<ObservationReturnTypeWithMetadata>;
trace: Omit<TraceDomain, "input" | "output"> & {
- input: string | undefined;
- output: string | undefined;
+ input: string | null;
+ output: string | null;
};
scores: APIScore[];
projectId: string;
diff --git a/web/src/components/trace/lib/helpers.ts b/web/src/components/trace/lib/helpers.ts
index 3cf15c0e73..444f77f17c 100644
--- a/web/src/components/trace/lib/helpers.ts
+++ b/web/src/components/trace/lib/helpers.ts
@@ -103,39 +103,34 @@ export function calculateDisplayTotalCost(p: {
}
}
- const totalCost = observations.reduce(
+ const totalCost = observations.reduce<Decimal | undefined>(
(prev: Decimal | undefined, curr: ObservationReturnType) => {
// if we don't have any calculated costs, we can't do anything
- if (
- !curr.calculatedTotalCost &&
- !curr.calculatedInputCost &&
- !curr.calculatedOutputCost
- )
- return prev;
+ if (!curr.totalCost && !curr.inputCost && !curr.outputCost) return prev;
// if we have either input or output cost, but not total cost, we can use that
- if (
- !curr.calculatedTotalCost &&
- (curr.calculatedInputCost || curr.calculatedOutputCost)
- ) {
+ if (!curr.totalCost && (curr.inputCost || curr.outputCost)) {
+ const inputCost =
+ curr.inputCost != null ? new Decimal(curr.inputCost) : new Decimal(0);
+
+ const outputCost =
+ curr.outputCost != null
+ ? new Decimal(curr.outputCost)
+ : new Decimal(0);
+
+ const combinedCost = inputCost.plus(outputCost);
+
return prev
- ? prev.plus(
- curr.calculatedInputCost ??
- new Decimal(0).plus(
- curr.calculatedOutputCost ?? new Decimal(0),
- ),
- )
- : (curr.calculatedInputCost ??
- curr.calculatedOutputCost ??
- undefined);
+ ? prev.plus(combinedCost)
+ : combinedCost.isZero()
+ ? undefined
+ : combinedCost;
}
- if (!curr.calculatedTotalCost) return prev;
+ if (!curr.totalCost) return prev;
// if we have total cost, we can use that
- return prev
- ? prev.plus(curr.calculatedTotalCost)
- : curr.calculatedTotalCost;
+ return prev ? prev.plus(curr.totalCost) : new Decimal(curr.totalCost);
},
undefined,
);
diff --git a/web/src/ee/features/playground/page/components/JumpToPlaygroundButton.tsx b/web/src/ee/features/playground/page/components/JumpToPlaygroundButton.tsx
index 11278af5ca..b2340113fd 100644
--- a/web/src/ee/features/playground/page/components/JumpToPlaygroundButton.tsx
+++ b/web/src/ee/features/playground/page/components/JumpToPlaygroundButton.tsx
@@ -40,8 +40,8 @@ type JumpToPlaygroundButtonProps = (
| {
source: "generation";
generation: Omit<Observation, "input" | "output"> & {
- input: string | undefined;
- output: string | undefined;
+ input: string | null;
+ output: string | null;
};
analyticsEventName: "trace_detail:test_in_playground_button_click";
}
@@ -226,8 +226,8 @@ const parsePrompt = (prompt: Prompt): PlaygroundCache => {
const parseGeneration = (
generation: Omit<Observation, "input" | "output"> & {
- input: string | undefined;
- output: string | undefined;
+ input: string | null;
+ output: string | null;
},
): PlaygroundCache => {
if (generation.type !== "GENERATION") return null;
diff --git a/web/src/features/datasets/components/NewDatasetItemFromExistingObject.tsx b/web/src/features/datasets/components/NewDatasetItemFromExistingObject.tsx
index d48d7221c4..da42370ef5 100644
--- a/web/src/features/datasets/components/NewDatasetItemFromExistingObject.tsx
+++ b/web/src/features/datasets/components/NewDatasetItemFromExistingObject.tsx
@@ -39,8 +39,8 @@ export const NewDatasetItemFromExistingObject = (props: {
traceId?: string;
observationId?: string;
fromDatasetId?: string;
- input: string | undefined;
- output: string | undefined;
+ input: string | null;
+ output: string | null;
metadata: Prisma.JsonValue;
isCopyItem?: boolean;
}) => {
diff --git a/web/src/features/public-api/server/observations.ts b/web/src/features/public-api/server/observations.ts
index 9aaf8a001a..104c9affd5 100644
--- a/web/src/features/public-api/server/observations.ts
+++ b/web/src/features/public-api/server/observations.ts
@@ -3,7 +3,7 @@ import {
StringFilter,
type ObservationRecordReadType,
queryClickhouse,
- convertObservationToView,
+ convertObservation,
} from "@langfuse/shared/src/server";
type QueryType = {
@@ -88,7 +88,7 @@ export const generateObservationsForPublicApi = async (props: QueryType) => {
: {}),
},
});
- return result.map(convertObservationToView);
+ return result.map(convertObservation);
};
export const getObservationsCountForPublicApi = async (props: QueryType) => {
diff --git a/web/src/features/public-api/types/observations.ts b/web/src/features/public-api/types/observations.ts
index 2a42ce4d33..0cdc2339a6 100644
--- a/web/src/features/public-api/types/observations.ts
+++ b/web/src/features/public-api/types/observations.ts
@@ -1,10 +1,14 @@
import {
- type ObservationView,
+ type Observation,
paginationMetaResponseZod,
publicApiPaginationZod,
} from "@langfuse/shared";
-import { stringDateTime } from "@langfuse/shared/src/server";
+import {
+ reduceUsageOrCostDetails,
+ stringDateTime,
+} from "@langfuse/shared/src/server";
+import type Decimal from "decimal.js";
import { z } from "zod";
/**
@@ -86,25 +90,56 @@ export const APIObservation = z
* @returns API Observation as defined in the public API
*/
export const transformDbToApiObservation = (
- observation: ObservationView,
+ observation: Observation & {
+ inputPrice: Decimal | null;
+ outputPrice: Decimal | null;
+ totalPrice: Decimal | null;
+ },
): z.infer<typeof APIObservation> => {
- const { promptTokens, completionTokens, totalTokens, unit, ...rest } =
- observation;
+ const reducedUsageDetails = reduceUsageOrCostDetails(
+ observation.usageDetails,
+ );
+ const reducedCostDetails = reduceUsageOrCostDetails(observation.costDetails);
+
+ const unit = "TOKENS";
+
+ const promptTokens = reducedUsageDetails.input ?? 0;
+ const completionTokens = reducedUsageDetails.output ?? 0;
+ const totalTokens = reducedUsageDetails.total ?? 0;
+
+ const {
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ providedCostDetails,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ internalModelId,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ inputCost,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ outputCost,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ totalCost,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ inputUsage,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ outputUsage,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ totalUsage,
+ ...rest
+ } = observation;
return {
- usageDetails: {}, // Important: order matters here, in PG there are no usageDetails but in CH there are and will be written by rest
- costDetails: {}, // Important: order matters here, in PG there are no costDetails but in CH there are and will be written by rest
...rest,
- unit,
- promptTokens,
- completionTokens,
- totalTokens,
+ calculatedInputCost: reducedCostDetails.input,
+ calculatedOutputCost: reducedCostDetails.output,
+ calculatedTotalCost: reducedCostDetails.total,
+ unit: unit,
inputPrice: observation.inputPrice?.toNumber() ?? null,
outputPrice: observation.outputPrice?.toNumber() ?? null,
totalPrice: observation.totalPrice?.toNumber() ?? null,
- calculatedInputCost: observation.calculatedInputCost?.toNumber() ?? null,
- calculatedOutputCost: observation.calculatedOutputCost?.toNumber() ?? null,
- calculatedTotalCost: observation.calculatedTotalCost?.toNumber() ?? null,
+ promptTokens,
+ completionTokens,
+ totalTokens,
+ modelId: observation.internalModelId ?? null,
usage: {
unit,
input: promptTokens,
diff --git a/web/src/features/trace-graph-view/components/TraceGraphView.tsx b/web/src/features/trace-graph-view/components/TraceGraphView.tsx
index c1242ead65..d471675eb1 100644
--- a/web/src/features/trace-graph-view/components/TraceGraphView.tsx
+++ b/web/src/features/trace-graph-view/components/TraceGraphView.tsx
@@ -15,8 +15,8 @@ import {
type TraceGraphViewProps = {
observations: ObservationReturnTypeWithMetadata[];
trace: Omit<TraceDomain, "input" | "output"> & {
- input: string | undefined;
- output: string | undefined;
+ input: string | null;
+ output: string | null;
};
scores: APIScore[];
projectId: string;
diff --git a/web/src/pages/api/public/observations/[observationId].ts b/web/src/pages/api/public/observations/[observationId].ts
index bc269935fd..19aa79de1f 100644
--- a/web/src/pages/api/public/observations/[observationId].ts
+++ b/web/src/pages/api/public/observations/[observationId].ts
@@ -7,7 +7,7 @@ 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 { getObservationViewById } from "@langfuse/shared/src/server";
+import { getObservationById } from "@langfuse/shared/src/server";
export default withMiddlewares({
GET: createAuthedAPIRoute({
@@ -15,7 +15,7 @@ export default withMiddlewares({
querySchema: GetObservationV1Query,
responseSchema: GetObservationV1Response,
fn: async ({ query, auth }) => {
- const clickhouseObservation = await getObservationViewById(
+ const clickhouseObservation = await getObservationById(
query.observationId,
auth.scope.projectId,
true,
@@ -26,12 +26,12 @@ export default withMiddlewares({
);
}
- const model = clickhouseObservation.modelId
+ const model = clickhouseObservation.internalModelId
? await prisma.model.findFirst({
where: {
AND: [
{
- id: clickhouseObservation.modelId,
+ id: clickhouseObservation.internalModelId,
},
{
OR: [
diff --git a/web/src/pages/api/public/observations/index.ts b/web/src/pages/api/public/observations/index.ts
index 306bc28302..b4a8e1a7c8 100644
--- a/web/src/pages/api/public/observations/index.ts
+++ b/web/src/pages/api/public/observations/index.ts
@@ -39,7 +39,9 @@ export default withMiddlewares({
]);
const uniqueModels: string[] = Array.from(
new Set(
- items.map((r) => r.modelId).filter((r): r is string => Boolean(r)),
+ items
+ .map((r) => r.internalModelId)
+ .filter((r): r is string => Boolean(r)),
),
);
@@ -62,7 +64,7 @@ export default withMiddlewares({
return {
data: items
.map((i) => {
- const model = models.find((m) => m.id === i.modelId);
+ const model = models.find((m) => m.id === i.internalModelId);
return {
...i,
modelId: model?.id ?? null,
diff --git a/web/src/pages/api/public/traces/[traceId].ts b/web/src/pages/api/public/traces/[traceId].ts
index f84e628e46..ca4f5206b3 100644
--- a/web/src/pages/api/public/traces/[traceId].ts
+++ b/web/src/pages/api/public/traces/[traceId].ts
@@ -13,7 +13,7 @@ import {
} from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import {
- getObservationsViewForTrace,
+ getObservationsForTrace,
getScoresForTraces,
getTraceById,
traceException,
@@ -34,7 +34,7 @@ export default withMiddlewares({
const { traceId } = query;
const trace = await getTraceById(traceId, auth.scope.projectId);
const [observations, scores] = await Promise.all([
- getObservationsViewForTrace(
+ getObservationsForTrace(
traceId,
auth.scope.projectId,
trace?.timestamp,
@@ -50,7 +50,7 @@ export default withMiddlewares({
const uniqueModels: string[] = Array.from(
new Set(
observations
- .map((r) => r.modelId)
+ .map((r) => r.internalModelId)
.filter((r): r is string => Boolean(r)),
),
);
@@ -71,7 +71,7 @@ export default withMiddlewares({
: [];
const observationsView = observations.map((o) => {
- const model = models.find((m) => m.id === o.modelId);
+ const model = models.find((m) => m.id === o.internalModelId);
const inputPrice =
model?.Price.find((p) => p.usageType === "input")?.price ??
new Decimal(0);
@@ -126,7 +126,7 @@ export default withMiddlewares({
latency: latencyMs !== undefined ? latencyMs / 1000 : 0,
observations: outObservations,
htmlPath: `/project/${auth.scope.projectId}/traces/${traceId}`,
- totalCost: observations
+ totalCost: outObservations
.reduce(
(acc, obs) => acc.add(obs.calculatedTotalCost ?? new Decimal(0)),
new Decimal(0),
diff --git a/web/src/server/api/routers/observations.ts b/web/src/server/api/routers/observations.ts
index 0a2fec88a1..16502592d3 100644
--- a/web/src/server/api/routers/observations.ts
+++ b/web/src/server/api/routers/observations.ts
@@ -33,8 +33,8 @@ export const observationsRouter = createTRPCRouter({
}
return {
...obs,
- input: obs.input ? JSON.stringify(obs.input) : undefined,
- output: obs.output ? JSON.stringify(obs.output) : undefined,
+ input: obs.input ? JSON.stringify(obs.input) : null,
+ output: obs.output ? JSON.stringify(obs.output) : null,
internalModel: obs?.internalModelId,
};
} catch (e) {
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index 7bef323dac..c92d428728 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -17,8 +17,8 @@ import {
singleFilter,
timeFilter,
tracesTableUiColumnDefinitions,
+ type Observation,
} from "@langfuse/shared";
-import { type ObservationView } from "@langfuse/shared";
import {
traceException,
getTracesTable,
@@ -27,7 +27,7 @@ import {
getScoresGroupedByName,
getTracesGroupedByName,
getTracesGroupedByTags,
- getObservationsViewForTrace,
+ getObservationsForTrace,
getTraceById,
logger,
upsertTrace,
@@ -51,17 +51,17 @@ const TraceFilterOptions = z.object({
});
type TraceFilterOptions = z.infer<typeof TraceFilterOptions>;
-export type ObservationReturnType = Omit<
- ObservationView,
- "input" | "output" | "inputPrice" | "outputPrice" | "totalPrice" | "metadata"
+export type ObservationReturnTypeWithMetadata = Omit<
+ Observation,
+ "input" | "output"
> & {
traceId: string;
- usageDetails: Record<string, number>;
- costDetails: Record<string, number>;
};
-export type ObservationReturnTypeWithMetadata = ObservationReturnType &
- Pick<ObservationView, "metadata">;
+export type ObservationReturnType = Omit<
+ ObservationReturnTypeWithMetadata,
+ "metadata"
+>;
export const traceRouter = createTRPCRouter({
hasAny: protectedProjectProcedure
@@ -202,7 +202,7 @@ export const traceRouter = createTRPCRouter({
input.projectId,
input.timestamp ?? undefined,
),
- getObservationsViewForTrace(
+ getObservationsForTrace(
input.traceId,
input.projectId,
input.timestamp ?? undefined,
@@ -246,8 +246,8 @@ export const traceRouter = createTRPCRouter({
return {
...trace,
- input: trace.input ? JSON.stringify(trace.input) : undefined,
- output: trace.output ? JSON.stringify(trace.output) : undefined,
+ input: trace.input ? JSON.stringify(trace.input) : null,
+ output: trace.output ? JSON.stringify(trace.output) : null,
scores: validatedScores,
latency: latencyMs !== undefined ? latencyMs / 1000 : undefined,
observations: observations.map((o) => ({
diff --git a/worker/src/__tests__/traceDeletion.test.ts b/worker/src/__tests__/traceDeletion.test.ts
index 5f6c3720bf..c7e1b03ec8 100644
--- a/worker/src/__tests__/traceDeletion.test.ts
+++ b/worker/src/__tests__/traceDeletion.test.ts
@@ -9,7 +9,7 @@ import {
createTrace,
createTracesCh,
getEventLogByProjectId,
- getObservationsViewForTrace,
+ getObservationsForTrace,
getScoresForTraces,
getTracesByIds,
StorageService,
@@ -37,7 +37,7 @@ describe("trace deletion", () => {
mediaStorageService = StorageServiceFactory.getInstance({
accessKeyId: env.LANGFUSE_S3_MEDIA_UPLOAD_ACCESS_KEY_ID,
secretAccessKey: env.LANGFUSE_S3_MEDIA_UPLOAD_SECRET_ACCESS_KEY,
- bucketName: env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET,
+ bucketName: String(env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET),
endpoint: env.LANGFUSE_S3_MEDIA_UPLOAD_ENDPOINT,
region: env.LANGFUSE_S3_MEDIA_UPLOAD_REGION,
forcePathStyle: env.LANGFUSE_S3_MEDIA_UPLOAD_FORCE_PATH_STYLE === "true",
@@ -50,8 +50,8 @@ describe("trace deletion", () => {
const traceId = randomUUID();
await createTracesCh([createTrace({ id: traceId })]);
- await createObservationsCh([createObservation({ traceId })]);
- await createScoresCh([createScore({ traceId })]);
+ await createObservationsCh([createObservation({ trace_id: traceId })]);
+ await createScoresCh([createScore({ trace_id: traceId })]);
// When
await processClickhouseTraceDelete("projectId", [traceId]);
@@ -60,7 +60,7 @@ describe("trace deletion", () => {
const traces = await getTracesByIds([traceId], projectId);
expect(traces).toHaveLength(0);
- const observations = await getObservationsViewForTrace(traceId, projectId);
+ const observations = await getObservationsForTrace(traceId, projectId);
expect(observations).toHaveLength(0);
const scores = await getScoresForTraces({
@@ -112,7 +112,7 @@ describe("trace deletion", () => {
projectId,
createdAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 3), // 3 days in the past
bucketPath: `${projectId}/trace-${traceId}.txt`,
- bucketName: env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET,
+ bucketName: String(env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET),
contentType: fileType,
contentLength: 0,
},
@@ -135,7 +135,7 @@ describe("trace deletion", () => {
projectId,
createdAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 3), // 3 days in the past
bucketPath: `${projectId}/observation-${observationId}.txt`,
- bucketName: env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET,
+ bucketName: String(env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET),
contentType: fileType,
contentLength: 0,
},
@@ -198,7 +198,7 @@ describe("trace deletion", () => {
projectId,
createdAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 3), // 3 days in the past
bucketPath: `${projectId}/trace-${traceId1}.txt`,
- bucketName: env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET,
+ bucketName: String(env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET),
contentType: fileType,
contentLength: 0,
},
diff --git a/worker/src/features/database-read-stream/types.ts b/worker/src/features/database-read-stream/types.ts
index 61699771e8..13a7518700 100644
--- a/worker/src/features/database-read-stream/types.ts
+++ b/worker/src/features/database-read-stream/types.ts
@@ -1,4 +1,4 @@
-import { ObservationLevelType } from "@langfuse/shared/src/server";
+import { ObservationLevelType } from "@langfuse/shared";
import Decimal from "decimal.js";
export type BatchExportSessionsRow = {