Skip to content

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

feat(cost-tracking): allow additional cost and usage keys (#4536)

Hassieb Pakzad6c4482ff56c8
diff --git a/fern/apis/server/definition/commons.yml b/fern/apis/server/definition/commons.yml
index aff797aa34..4b96724ca7 100644
--- a/fern/apis/server/definition/commons.yml
+++ b/fern/apis/server/definition/commons.yml
@@ -126,7 +126,7 @@ types:
docs: The output data of the observation
usage:
type: optional<Usage>
- docs: The usage data of the observation
+ docs: (Deprecated. Use usageDetails and costDetails instead.) The usage data of the observation
level:
type: ObservationLevel
docs: The level of the observation
@@ -139,6 +139,12 @@ types:
promptId:
type: optional<string>
docs: The prompt ID associated with the observation
+ usageDetails:
+ type: optional<map<string, integer>>
+ docs: The usage details of the observation. Key is the name of the usage metric, value is the number of units consumed. The total key is the sum of all (non-total) usage metrics or the total value ingested.
+ costDetails:
+ type: optional<map<string, double>>
+ docs: The cost details of the observation. Key is the name of the cost metric, value is the cost in USD. The total key is the sum of all (non-total) cost metrics or the total value ingested.
ObservationsView:
extends: Observation
@@ -163,13 +169,13 @@ types:
docs: The total price in USD.
calculatedInputCost:
type: optional<double>
- docs: The calculated cost of the input in USD
+ docs: (Deprecated. Use usageDetails and costDetails instead.) The calculated cost of the input in USD
calculatedOutputCost:
type: optional<double>
- docs: The calculated cost of the output in USD
+ docs: (Deprecated. Use usageDetails and costDetails instead.) The calculated cost of the output in USD
calculatedTotalCost:
type: optional<double>
- docs: The calculated total cost in USD
+ docs: (Deprecated. Use usageDetails and costDetails instead.) The calculated total cost in USD
latency:
type: optional<double>
docs: The latency in seconds.
@@ -178,7 +184,7 @@ types:
docs: The time to the first token in seconds
Usage:
- docs: Standard interface for usage and cost
+ docs: (Deprecated. Use usageDetails and costDetails instead.) Standard interface for usage and cost
properties:
input:
docs: Number of input units (e.g. tokens)
diff --git a/fern/apis/server/definition/ingestion.yml b/fern/apis/server/definition/ingestion.yml
index b5093f1c52..ed8f7c507c 100644
--- a/fern/apis/server/definition/ingestion.yml
+++ b/fern/apis/server/definition/ingestion.yml
@@ -126,6 +126,8 @@ types:
model: optional<string>
modelParameters: optional<map<string, commons.MapValue>>
usage: optional<IngestionUsage>
+ usageDetails: optional<UsageDetails>
+ costDetails: optional<map<string, float>>
promptName: optional<string>
promptVersion: optional<integer>
@@ -137,6 +139,8 @@ types:
modelParameters: optional<map<string, commons.MapValue>>
usage: optional<IngestionUsage>
promptName: optional<string>
+ usageDetails: optional<UsageDetails>
+ costDetails: optional<map<string, float>>
promptVersion: optional<integer>
ObservationBody:
@@ -312,3 +316,17 @@ types:
properties:
successes: list<IngestionSuccess>
errors: list<IngestionError>
+
+ OpenAIUsageSchema:
+ properties:
+ prompt_tokens: integer
+ completion_tokens: integer
+ total_tokens: integer
+ prompt_tokens_details: optional<map<string, integer>>
+ completion_tokens_details: optional<map<string, integer>>
+
+ UsageDetails:
+ discriminated: false
+ union:
+ - map<string, integer>
+ - OpenAIUsageSchema
diff --git a/packages/shared/src/server/ingestion/legacy/EventProcessor.ts b/packages/shared/src/server/ingestion/legacy/EventProcessor.ts
index a1e3d8f6fe..eebe829d97 100644
--- a/packages/shared/src/server/ingestion/legacy/EventProcessor.ts
+++ b/packages/shared/src/server/ingestion/legacy/EventProcessor.ts
@@ -136,7 +136,7 @@ export class ObservationProcessor implements EventProcessor {
// Token counts
const [newInputCount, newOutputCount] =
- "usage" in this.event.body
+ "usage" in this.event.body || "usageDetails" in this.event.body
? await this.calculateTokenCounts(
apiScope.projectId,
this.event.body,
@@ -147,8 +147,9 @@ export class ObservationProcessor implements EventProcessor {
: [undefined, undefined];
const newTotalCount =
- "usage" in this.event.body
+ "usage" in this.event.body || "usageDetails" in this.event.body
? (this.event.body.usage?.total ??
+ this.event.body.usageDetails?.total ??
(newInputCount != null || newOutputCount != null
? (newInputCount ?? 0) + (newOutputCount ?? 0)
: undefined))
@@ -158,15 +159,24 @@ export class ObservationProcessor implements EventProcessor {
inputCost:
"usage" in this.event.body && this.event.body.usage?.inputCost != null // inputCost can be explicitly 0. Note only one equal sign to capture null AND undefined
? new Decimal(this.event.body.usage?.inputCost)
- : existingObservation?.inputCost,
+ : "costDetails" in this.event.body &&
+ this.event.body.costDetails?.input != null
+ ? new Decimal(this.event.body.costDetails?.input)
+ : existingObservation?.inputCost,
outputCost:
"usage" in this.event.body && this.event.body.usage?.outputCost != null // outputCost can be explicitly 0. Note only one equal sign to capture null AND undefined
? new Decimal(this.event.body.usage?.outputCost)
- : existingObservation?.outputCost,
+ : "costDetails" in this.event.body &&
+ this.event.body.costDetails?.output != null
+ ? new Decimal(this.event.body.costDetails?.output)
+ : existingObservation?.outputCost,
totalCost:
"usage" in this.event.body && this.event.body.usage?.totalCost != null // totalCost can be explicitly 0. Note only one equal sign to capture null AND undefined
? new Decimal(this.event.body.usage?.totalCost)
- : existingObservation?.totalCost,
+ : "costDetails" in this.event.body &&
+ this.event.body.costDetails?.total != null
+ ? new Decimal(this.event.body.costDetails?.total)
+ : existingObservation?.totalCost,
};
const tokenCounts = {
@@ -384,7 +394,7 @@ export class ObservationProcessor implements EventProcessor {
model?: Model,
existingObservation?: Omit<Observation, "input" | "output">,
) {
- let newPromptTokens = body.usage?.input;
+ let newPromptTokens = body.usage?.input || body.usageDetails?.input;
if (newPromptTokens === undefined && model && model.tokenizerId) {
if (body.input) {
newPromptTokens = calculateTokenDelegate({
@@ -409,7 +419,7 @@ export class ObservationProcessor implements EventProcessor {
}
}
- let newCompletionTokens = body.usage?.output;
+ let newCompletionTokens = body.usage?.output || body.usageDetails?.output;
if (newCompletionTokens === undefined && model && model.tokenizerId) {
if (body.output) {
diff --git a/packages/shared/src/server/ingestion/types.ts b/packages/shared/src/server/ingestion/types.ts
index 689ca9f458..ff7ec3a42f 100644
--- a/packages/shared/src/server/ingestion/types.ts
+++ b/packages/shared/src/server/ingestion/types.ts
@@ -56,6 +56,62 @@ export const usage = MixedUsage.nullish()
// ensure output is always of new usage model
.pipe(Usage.nullish());
+const RawUsageOrCostDetails = z.record(
+ z.string(),
+ z.number().nonnegative().nullish(),
+);
+
+const OpenAIUsageSchema = z
+ .object({
+ prompt_tokens: z.number().nonnegative(),
+ completion_tokens: z.number().nonnegative(),
+ total_tokens: z.number().nonnegative(),
+ prompt_tokens_details: z.record(z.string(), z.number().nonnegative()),
+ completion_tokens_details: z.record(z.string(), z.number().nonnegative()),
+ })
+ .strict()
+ .transform((v) => {
+ if (!v) return;
+
+ const {
+ prompt_tokens,
+ completion_tokens,
+ total_tokens,
+ prompt_tokens_details,
+ completion_tokens_details,
+ } = v;
+ const result: z.infer<typeof RawUsageOrCostDetails> & {
+ input: number;
+ output: number;
+ total: number;
+ } = {
+ input: prompt_tokens,
+ output: completion_tokens,
+ total: total_tokens,
+ };
+
+ if (prompt_tokens_details) {
+ for (const [key, value] of Object.entries(prompt_tokens_details)) {
+ result[`input_${key}`] = value;
+ result.input = Math.max(result.input - (value ?? 0), 0);
+ }
+ }
+
+ if (completion_tokens_details) {
+ for (const [key, value] of Object.entries(completion_tokens_details)) {
+ result[`output_${key}`] = value;
+ result.output = Math.max(result.output - (value ?? 0), 0);
+ }
+ }
+
+ return result;
+ })
+ .pipe(RawUsageOrCostDetails);
+
+export const UsageOrCostDetails = z
+ .union([OpenAIUsageSchema, RawUsageOrCostDetails])
+ .nullish();
+
export const TraceBody = z.object({
id: z.string().nullish(),
timestamp: stringDateTime,
@@ -119,6 +175,8 @@ export const CreateGenerationBody = CreateSpanBody.extend({
)
.nullish(),
usage: usage,
+ usageDetails: UsageOrCostDetails,
+ costDetails: UsageOrCostDetails,
promptName: z.string().nullish(),
promptVersion: z.number().int().nullish(),
}).refine((value) => {
@@ -147,6 +205,8 @@ export const UpdateGenerationBody = UpdateSpanBody.extend({
)
.nullish(),
usage: usage,
+ usageDetails: UsageOrCostDetails,
+ costDetails: UsageOrCostDetails,
promptName: z.string().nullish(),
promptVersion: z.number().int().nullish(),
}).refine((value) => {
@@ -298,6 +358,8 @@ export const LegacyObservationBody = z.object({
input: jsonSchema.nullish(),
output: jsonSchema.nullish(),
usage: usage,
+ usageDetails: UsageOrCostDetails,
+ costDetails: UsageOrCostDetails,
metadata: jsonSchema.nullish(),
parentObservationId: z.string().nullish(),
level: z.nativeEnum(ObservationLevel).nullish(),
diff --git a/packages/shared/src/server/queries/createGenerationsQuery.ts b/packages/shared/src/server/queries/createGenerationsQuery.ts
index 8047672504..16de76eabd 100644
--- a/packages/shared/src/server/queries/createGenerationsQuery.ts
+++ b/packages/shared/src/server/queries/createGenerationsQuery.ts
@@ -10,6 +10,8 @@ import { TableFilters } from "./types";
type AdditionalObservationFields = {
traceName: string | null;
traceTags: Array<string>;
+ usageDetails: Record<string, number>;
+ costDetails: Record<string, number>;
};
export type FullObservation = AdditionalObservationFields & ObservationView;
diff --git a/packages/shared/src/server/repositories/dashboards.ts b/packages/shared/src/server/repositories/dashboards.ts
index 606a67d497..8cbc57fe5c 100644
--- a/packages/shared/src/server/repositories/dashboards.ts
+++ b/packages/shared/src/server/repositories/dashboards.ts
@@ -203,8 +203,8 @@ export const getObservationUsageByTime = async (
const query = `
SELECT
${selectTimeseriesColumn(groupBy, "start_time", "start_time")},
- sumMap(usage_details)['total'] as sum_usage_details,
- sumMap(cost_details)['total'] as sum_cost_details,
+ sumMap(usage_details) as units,
+ sumMap(cost_details) as cost,
provided_model_name
FROM observations o FINAL
${tracesFilter ? "LEFT JOIN traces t ON o.trace_id = t.id AND o.project_id = t.project_id" : ""}
@@ -217,8 +217,8 @@ export const getObservationUsageByTime = async (
const result = await queryClickhouse<{
start_time: string;
- sum_usage_details: string;
- sum_cost_details: number;
+ units: Record<string, number>;
+ cost: Record<string, number>;
provided_model_name: string;
}>({
query,
@@ -233,8 +233,18 @@ export const getObservationUsageByTime = async (
return result.map((row) => ({
start_time: new Date(row.start_time),
- sum_usage_details: Number(row.sum_usage_details),
- sum_cost_details: row.sum_cost_details,
+ units: Object.fromEntries(
+ Object.entries(row.units ?? {}).map(([key, value]) => [
+ key,
+ Number(value),
+ ]),
+ ),
+ cost: Object.fromEntries(
+ Object.entries(row.cost ?? {}).map(([key, value]) => [
+ key,
+ Number(value),
+ ]),
+ ),
provided_model_name: row.provided_model_name,
}));
};
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index 6323ceb8c5..c0948fd7a1 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -977,8 +977,8 @@ export const getObservationMetricsForPrompts = async (
prompt_version,
min(start_time) AS first_observation,
max(start_time) AS last_observation,
- medianExact(usage_details['input']) AS median_input_usage,
- medianExact(usage_details['output']) AS median_output_usage,
+ medianExact(arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, usage_details)))) AS median_input_usage,
+ medianExact(arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, usage_details)))) AS median_output_usage,
medianExact(cost_details['total']) AS median_total_cost,
medianExact(latency_ms) AS median_latency_ms
FROM latencies
diff --git a/packages/shared/src/server/repositories/observations_converters.ts b/packages/shared/src/server/repositories/observations_converters.ts
index 5787a0e7ca..2ba15c021d 100644
--- a/packages/shared/src/server/repositories/observations_converters.ts
+++ b/packages/shared/src/server/repositories/observations_converters.ts
@@ -13,7 +13,10 @@ import { jsonSchema } from "../../utils/zod";
export const convertObservationToView = (
record: ObservationRecordReadType,
-): Omit<ObservationView, "inputPrice" | "outputPrice" | "totalPrice"> => {
+): 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
@@ -39,7 +42,15 @@ export const convertObservation = (
promptVersion: number | null;
latency: number | null;
timeToFirstToken: number | null;
+ usageDetails: Record<string, number>;
+ costDetails: Record<string, number>;
} => {
+ const reducedUsageDetails = reduceUsageOrCostDetails(record.usage_details);
+ const reducedCostDetails = reduceUsageOrCostDetails(record.cost_details);
+ const reducedProvidedCostDetails = reduceUsageOrCostDetails(
+ record.provided_cost_details,
+ );
+
return {
id: record.id,
traceId: record.trace_id ?? null,
@@ -70,31 +81,41 @@ export const convertObservation = (
promptId: record.prompt_id ?? null,
createdAt: parseClickhouseUTCDateTimeFormat(record.created_at),
updatedAt: parseClickhouseUTCDateTimeFormat(record.updated_at),
- promptTokens: record.usage_details?.input
- ? Number(record.usage_details?.input)
- : 0,
- completionTokens: record.usage_details?.output
- ? Number(record.usage_details?.output)
- : 0,
- totalTokens: record.usage_details?.total
- ? Number(record.usage_details?.total)
- : 0,
- calculatedInputCost: record.cost_details?.input
- ? new Decimal(record.cost_details.input)
- : null,
- calculatedOutputCost: record.cost_details?.output
- ? new Decimal(record.cost_details.output)
- : null,
+ 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: record.cost_details?.input
- ? new Decimal(record.cost_details?.input)
- : null,
- outputCost: record.cost_details?.output
- ? new Decimal(record.cost_details?.output)
- : 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,
+ Number(value),
+ ]),
+ ),
+ costDetails: Object.fromEntries(
+ Object.entries(record.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.
@@ -112,3 +133,27 @@ export const convertObservation = (
: null,
};
};
+
+export const reduceUsageOrCostDetails = (
+ details: Record<string, number> | null | undefined,
+): {
+ input: number | null;
+ output: number | null;
+ total: number | null;
+} => {
+ return {
+ input: Object.entries(details ?? {})
+ .filter(([usageType]) => usageType.startsWith("input"))
+ .reduce(
+ (acc, [_, value]) => (acc ?? 0) + Number(value),
+ null as number | null, // default to null if no input usage is found
+ ),
+ output: Object.entries(details ?? {})
+ .filter(([usageType]) => usageType.startsWith("output"))
+ .reduce(
+ (acc, [_, value]) => (acc ?? 0) + Number(value),
+ null as number | null, // default to null if no output usage is found
+ ),
+ total: Number(details?.total ?? 0),
+ };
+};
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index 02f5e84aff..dd31350e97 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -529,11 +529,11 @@ const getSessionsTableGeneric = async <T>(props: FetchSessionsTableProps) => {
date_diff('milliseconds', min(min_start_time), max(max_end_time)) as duration,
sumMap(o.sum_usage_details) as session_usage_details,
sumMap(o.sum_cost_details) as session_cost_details,
- sumMap(o.sum_cost_details)['input'] as session_input_cost,
- sumMap(o.sum_cost_details)['output'] as session_output_cost,
- sumMap(o.sum_cost_details)['total'] as session_total_cost,
- sumMap(o.sum_usage_details)['input'] as session_input_usage,
- sumMap(o.sum_usage_details)['output'] as session_output_usage,
+ arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, sumMap(o.sum_cost_details)))) as session_input_cost,
+ arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, sumMap(o.sum_cost_details)))) as session_output_cost,
+ sumMap(o.sum_cost_details)['total'] as session_total_cost,
+ arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, sumMap(o.sum_usage_details)))) as session_input_usage,
+ arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, sumMap(o.sum_usage_details)))) as session_output_usage,
sumMap(o.sum_usage_details)['total'] as session_total_usage
FROM traces t FINAL
LEFT JOIN observations_agg o
@@ -749,8 +749,8 @@ export const getUserMetrics = async (projectId: string, userIds: string[]) => {
t.user_id
)
SELECT
- sum_usage_details [ 'input' ] as input_usage,
- sum_usage_details [ 'output' ] as output_usage,
+ arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, sum_usage_details))) as input_usage,
+ arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, sum_usage_details))) as output_usage,
sum_usage_details [ 'total' ] as total_usage,
obs_count,
trace_count,
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 d5216ed955..9d3546181a 100644
--- a/packages/shared/src/server/services/traces-ui-table-service.ts
+++ b/packages/shared/src/server/services/traces-ui-table-service.ts
@@ -24,6 +24,7 @@ import {
} from "../repositories/constants";
import Decimal from "decimal.js";
import { ScoreAggregate } from "../../features/scores";
+import { reduceUsageOrCostDetails } from "../repositories";
export type TracesTableReturnType = Pick<
TraceRecordReadType,
@@ -67,6 +68,8 @@ export type TracesMetricsUiReturnType = {
calculatedInputCost: Decimal | null;
calculatedOutputCost: Decimal | null;
scores: ScoreAggregate;
+ usageDetails: Record<string, number>;
+ costDetails: Record<string, number>;
};
export const convertToUiTableRows = (
@@ -90,13 +93,27 @@ export const convertToUiTableRows = (
export const convertToUITableMetrics = (
row: TracesTableMetricsClickhouseReturnType,
): Omit<TracesMetricsUiReturnType, "scores"> => {
+ const usageDetails = reduceUsageOrCostDetails(row.usage_details);
+
return {
id: row.id,
projectId: row.project_id,
latency: Number(row.latency),
- promptTokens: BigInt(row.usage_details?.input ?? 0),
- completionTokens: BigInt(row.usage_details?.output ?? 0),
- totalTokens: BigInt(row.usage_details?.total ?? 0),
+ promptTokens: BigInt(usageDetails.input ?? 0),
+ completionTokens: BigInt(usageDetails.output ?? 0),
+ totalTokens: BigInt(usageDetails.total ?? 0),
+ usageDetails: Object.fromEntries(
+ Object.entries(row.usage_details).map(([key, value]) => [
+ key,
+ Number(value),
+ ]),
+ ),
+ costDetails: Object.fromEntries(
+ Object.entries(row.cost_details).map(([key, value]) => [
+ key,
+ Number(value),
+ ]),
+ ),
observationCount: BigInt(row.observation_count ?? 0),
calculatedTotalCost: row.cost_details?.total
? new Decimal(row.cost_details.total)
diff --git a/packages/shared/src/tableDefinitions/mapDashboards.ts b/packages/shared/src/tableDefinitions/mapDashboards.ts
index 52520c4e28..69f2d6daee 100644
--- a/packages/shared/src/tableDefinitions/mapDashboards.ts
+++ b/packages/shared/src/tableDefinitions/mapDashboards.ts
@@ -85,4 +85,10 @@ export const dashboardColumnDefinitions: UiColumnMapping[] = [
uiTableId: "version",
uiTableName: "Version",
},
+ {
+ clickhouseTableName: "observations",
+ clickhouseSelect: "provided_model_name",
+ uiTableId: "model",
+ uiTableName: "Model",
+ },
];
diff --git a/packages/shared/src/tableDefinitions/mapObservationsTable.ts b/packages/shared/src/tableDefinitions/mapObservationsTable.ts
index 3fdb6bd59c..4231939f43 100644
--- a/packages/shared/src/tableDefinitions/mapObservationsTable.ts
+++ b/packages/shared/src/tableDefinitions/mapObservationsTable.ts
@@ -68,7 +68,7 @@ export const observationsTableUiColumnDefinitions: UiColumnMapping[] = [
uiTableId: "timeToFirstToken",
clickhouseTableName: "observations",
clickhouseSelect:
- "if(isNull(completion_start_time), NULL, date_diff('milliseconds', start_time, completion_start_time))",
+ "if(isNull(completion_start_time), NULL, date_diff('milliseconds', start_time, completion_start_time) / 1000)",
// If we use the default of Decimal64(12), we cannot filter for more than ~40min due to an overflow
clickhouseTypeOverwrite: "Decimal64(3)",
},
@@ -77,7 +77,7 @@ export const observationsTableUiColumnDefinitions: UiColumnMapping[] = [
uiTableId: "latency",
clickhouseTableName: "observations",
clickhouseSelect:
- "if(isNull(end_time), NULL, date_diff('milliseconds', start_time, end_time))",
+ "if(isNull(end_time), NULL, date_diff('milliseconds', start_time, end_time) / 1000)",
// If we use the default of Decimal64(12), we cannot filter for more than ~40min due to an overflow
clickhouseTypeOverwrite: "Decimal64(3)",
},
@@ -86,21 +86,21 @@ export const observationsTableUiColumnDefinitions: UiColumnMapping[] = [
uiTableId: "tokensPerSecond",
clickhouseTableName: "observations",
clickhouseSelect:
- "(usage_details['input'] / date_diff('milliseconds', start_time, end_time))",
+ "(arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, usage_details))) / (date_diff('milliseconds', start_time, end_time) / 1000))",
},
{
uiTableName: "Input Cost ($)",
uiTableId: "inputCost",
clickhouseTableName: "observations",
clickhouseSelect:
- "if(mapExists((k, v) -> (k = 'input'), cost_details), cost_details['input'], NULL)",
+ "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, cost_details)))",
},
{
uiTableName: "Output Cost ($)",
uiTableId: "outputCost",
clickhouseTableName: "observations",
clickhouseSelect:
- "if(mapExists((k, v) -> (k = 'output'), cost_details), cost_details['output'], NULL)",
+ "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, cost_details)))",
},
{
uiTableName: "Total Cost ($)",
@@ -132,14 +132,14 @@ export const observationsTableUiColumnDefinitions: UiColumnMapping[] = [
uiTableId: "inputTokens",
clickhouseTableName: "observations",
clickhouseSelect:
- "if(mapExists((k, v) -> (k = 'input'), usage_details), usage_details['input'], NULL)",
+ "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, usage_details)))",
},
{
uiTableName: "Output Tokens",
uiTableId: "outputTokens",
clickhouseTableName: "observations",
clickhouseSelect:
- "if(mapExists((k, v) -> (k = 'output'), usage_details), usage_details['output'], NULL)",
+ "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, usage_details)))",
},
{
uiTableName: "Total Tokens",
diff --git a/packages/shared/src/tableDefinitions/mapTracesTable.ts b/packages/shared/src/tableDefinitions/mapTracesTable.ts
index c41786a8c7..ade034ab0c 100644
--- a/packages/shared/src/tableDefinitions/mapTracesTable.ts
+++ b/packages/shared/src/tableDefinitions/mapTracesTable.ts
@@ -73,14 +73,14 @@ export const tracesTableUiColumnDefinitions: UiColumnMapping[] = [
uiTableId: "inputTokens",
clickhouseTableName: "observations",
clickhouseSelect:
- "if(mapExists((k, v) -> (k = 'input'), usage_details), usage_details['input'], NULL)",
+ "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, usage_details)))",
},
{
uiTableName: "Output Tokens",
uiTableId: "outputTokens",
clickhouseTableName: "observations",
clickhouseSelect:
- "if(mapExists((k, v) -> (k = 'output'), usage_details), usage_details['output'], NULL)",
+ "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, usage_details)))",
},
{
uiTableName: "Total Tokens",
@@ -114,13 +114,15 @@ export const tracesTableUiColumnDefinitions: UiColumnMapping[] = [
uiTableName: "Input Cost ($)",
uiTableId: "inputCost",
clickhouseTableName: "observations",
- clickhouseSelect: "cost_details['input']",
+ clickhouseSelect:
+ "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, cost_details)))",
},
{
uiTableName: "Output Cost ($)",
uiTableId: "outputCost",
clickhouseTableName: "observations",
- clickhouseSelect: "cost_details['output']",
+ clickhouseSelect:
+ "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, cost_details)))",
},
{
uiTableName: "Total Cost ($)",
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index bc0c7d4a3a..9e40794aa5 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -2627,7 +2627,9 @@ components:
usage:
$ref: '#/components/schemas/Usage'
nullable: true
- description: The usage data of the observation
+ description: >-
+ (Deprecated. Use usageDetails and costDetails instead.) The usage
+ data of the observation
level:
$ref: '#/components/schemas/ObservationLevel'
description: The level of the observation
@@ -2643,6 +2645,25 @@ components:
type: string
nullable: true
description: The prompt ID associated with the observation
+ usageDetails:
+ type: object
+ additionalProperties:
+ type: integer
+ nullable: true
+ description: >-
+ The usage details of the observation. Key is the name of the usage
+ metric, value is the number of units consumed. The total key is the
+ sum of all (non-total) usage metrics or the total value ingested.
+ costDetails:
+ type: object
+ additionalProperties:
+ type: number
+ format: double
+ nullable: true
+ description: >-
+ The cost details of the observation. Key is the name of the cost
+ metric, value is the cost in USD. The total key is the sum of all
+ (non-total) cost metrics or the total value ingested.
required:
- id
- type
@@ -2683,17 +2704,23 @@ components:
type: number
format: double
nullable: true
- description: The calculated cost of the input in USD
+ description: >-
+ (Deprecated. Use usageDetails and costDetails instead.) The
+ calculated cost of the input in USD
calculatedOutputCost:
type: number
format: double
nullable: true
- description: The calculated cost of the output in USD
+ description: >-
+ (Deprecated. Use usageDetails and costDetails instead.) The
+ calculated cost of the output in USD
calculatedTotalCost:
type: number
format: double
nullable: true
- description: The calculated total cost in USD
+ description: >-
+ (Deprecated. Use usageDetails and costDetails instead.) The
+ calculated total cost in USD
latency:
type: number
format: double
@@ -2709,7 +2736,9 @@ components:
Usage:
title: Usage
type: object
- description: Standard interface for usage and cost
+ description: >-
+ (Deprecated. Use usageDetails and costDetails instead.) Standard
+ interface for usage and cost
properties:
input:
type: integer
@@ -3608,6 +3637,15 @@ components:
usage:
$ref: '#/components/schemas/IngestionUsage'
nullable: true
+ usageDetails:
+ $ref: '#/components/schemas/UsageDetails'
+ nullable: true
+ costDetails:
+ type: object
+ additionalProperties:
+ type: number
+ format: double
+ nullable: true
promptName:
type: string
nullable: true
@@ -3638,6 +3676,15 @@ components:
promptName:
type: string
nullable: true
+ usageDetails:
+ $ref: '#/components/schemas/UsageDetails'
+ nullable: true
+ costDetails:
+ type: object
+ additionalProperties:
+ type: number
+ format: double
+ nullable: true
promptVersion:
type: integer
nullable: true
@@ -3955,6 +4002,37 @@ components:
required:
- successes
- errors
+ OpenAIUsageSchema:
+ title: OpenAIUsageSchema
+ type: object
+ properties:
+ prompt_tokens:
+ type: integer
+ completion_tokens:
+ type: integer
+ total_tokens:
+ type: integer
+ prompt_tokens_details:
+ type: object
+ additionalProperties:
+ type: integer
+ nullable: true
+ completion_tokens_details:
+ type: object
+ additionalProperties:
+ type: integer
+ nullable: true
+ required:
+ - prompt_tokens
+ - completion_tokens
+ - total_tokens
+ UsageDetails:
+ title: UsageDetails
+ oneOf:
+ - type: object
+ additionalProperties:
+ type: integer
+ - $ref: '#/components/schemas/OpenAIUsageSchema'
GetMediaResponse:
title: GetMediaResponse
type: object
diff --git a/web/src/components/table/use-cases/generations.tsx b/web/src/components/table/use-cases/generations.tsx
index a507609c5e..cbd0b6649e 100644
--- a/web/src/components/table/use-cases/generations.tsx
+++ b/web/src/components/table/use-cases/generations.tsx
@@ -41,6 +41,8 @@ import TagList from "@/src/features/tag/components/TagList";
import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";
import { BatchExportTableButton } from "@/src/components/BatchExportTableButton";
import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";
+import { BreakdownTooltip } from "@/src/components/trace/BreakdownToolTip";
+import { InfoIcon } from "lucide-react";
export type GenerationsTableRow = {
id: string;
@@ -69,6 +71,8 @@ export type GenerationsTableRow = {
completionTokens: number;
totalTokens: number;
};
+ usageDetails: Record<string, number>;
+ costDetails: Record<string, number>;
promptId?: string;
promptName?: string;
promptVersion?: string;
@@ -385,7 +389,12 @@ export default function GenerationsTable({
const value: Decimal | undefined = row.getValue("totalCost");
return value !== undefined ? (
- <span>{usdFormatter(value.toNumber())}</span>
+ <BreakdownTooltip details={row.original.costDetails} isCost>
+ <div className="flex items-center gap-1">
+ <span>{usdFormatter(value.toNumber())}</span>
+ <InfoIcon className="h-3 w-3" />
+ </div>
+ </BreakdownTooltip>
) : undefined;
},
enableHiding: true,
@@ -502,12 +511,17 @@ export default function GenerationsTable({
totalTokens: number;
} = row.getValue("usage");
return (
- <TokenUsageBadge
- promptTokens={value.promptTokens}
- completionTokens={value.completionTokens}
- totalTokens={value.totalTokens}
- inline
- />
+ <BreakdownTooltip details={row.original.usageDetails}>
+ <div className="flex items-center gap-1">
+ <TokenUsageBadge
+ promptTokens={value.promptTokens}
+ completionTokens={value.completionTokens}
+ totalTokens={value.totalTokens}
+ inline
+ />
+ <InfoIcon className="h-3 w-3" />
+ </div>
+ </BreakdownTooltip>
);
},
enableHiding: true,
@@ -688,6 +702,8 @@ export default function GenerationsTable({
promptName: generation.promptName ?? undefined,
promptVersion: generation.promptVersion?.toString() ?? undefined,
traceTags: generation.traceTags ?? undefined,
+ usageDetails: generation.usageDetails ?? {},
+ costDetails: generation.costDetails ?? {},
};
})
: [];
diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsx
index 449d59bf76..99805e44c6 100644
--- a/web/src/components/table/use-cases/traces.tsx
+++ b/web/src/components/table/use-cases/traces.tsx
@@ -50,6 +50,8 @@ import { Skeleton } from "@/src/components/ui/skeleton";
import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";
import { BatchExportTableButton } from "@/src/components/BatchExportTableButton";
import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";
+import { BreakdownTooltip } from "@/src/components/trace/BreakdownToolTip";
+import { InfoIcon } from "lucide-react";
export type TracesTableRow = {
bookmarked: boolean;
@@ -75,6 +77,8 @@ export type TracesTableRow = {
completionTokens?: bigint;
totalTokens?: bigint;
};
+ usageDetails?: Record<string, number>;
+ costDetails?: Record<string, number>;
inputCost?: Decimal;
outputCost?: Decimal;
totalCost?: Decimal;
@@ -444,12 +448,17 @@ export default function TracesTable({
const value: TracesTableRow["usage"] = row.getValue("usage");
if (!traceMetrics.data) return <Skeleton className="h-3 w-1/2" />;
return (
- <TokenUsageBadge
- promptTokens={value.promptTokens ?? 0}
- completionTokens={value.completionTokens ?? 0}
- totalTokens={value.totalTokens ?? 0}
- inline
- />
+ <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}
+ inline
+ />
+ <InfoIcon className="h-3 w-3" />
+ </div>
+ </BreakdownTooltip>
);
},
enableSorting: true,
@@ -511,15 +520,18 @@ export default function TracesTable({
cell: ({ row }) => {
const cost: TracesTableRow["totalCost"] = row.getValue("totalCost");
if (!traceMetrics.data) return <Skeleton className="h-3 w-1/2" />;
- return (
- <div>
- {cost ? (
- <span>{usdFormatter(cost.toNumber())}</span>
- ) : (
- <span>-</span>
- )}
- </div>
- );
+ return cost != null ? (
+ <BreakdownTooltip details={row.original.costDetails ?? []} isCost>
+ <div className="flex items-center gap-1">
+ {cost ? (
+ <span>{usdFormatter(cost.toNumber())}</span>
+ ) : (
+ <span>-</span>
+ )}
+ <InfoIcon className="h-3 w-3" />
+ </div>
+ </BreakdownTooltip>
+ ) : null;
},
enableHiding: true,
enableSorting: true,
@@ -742,6 +754,8 @@ export default function TracesTable({
completionTokens: trace.completionTokens,
totalTokens: trace.totalTokens,
},
+ usageDetails: trace.usageDetails,
+ costDetails: trace.costDetails,
scores: trace.scores
? verifyAndPrefixScoreDataAgainstKeys(
scoreKeysAndProps,
diff --git a/web/src/components/token-usage-badge.tsx b/web/src/components/token-usage-badge.tsx
index a1826ef4e9..9d2ff354a2 100644
--- a/web/src/components/token-usage-badge.tsx
+++ b/web/src/components/token-usage-badge.tsx
@@ -5,6 +5,7 @@ import { type Observation } from "@langfuse/shared";
export const AggUsageBadge = (props: {
observations: ObservationReturnType[];
+ rightIcon?: React.ReactNode;
}) => {
const usage = {
promptTokens: props.observations
@@ -17,7 +18,7 @@ export const AggUsageBadge = (props: {
.map((o) => o.totalTokens)
.reduce((a, b) => a + b, 0),
};
- return <TokenUsageBadge {...usage} />;
+ return <TokenUsageBadge {...usage} rightIcon={props.rightIcon} />;
};
export const TokenUsageBadge = (
@@ -32,6 +33,7 @@ export const TokenUsageBadge = (
}
) & {
inline?: boolean;
+ rightIcon?: React.ReactNode;
},
) => {
const usage =
@@ -50,16 +52,22 @@ export const TokenUsageBadge = (
)
return <></>;
+ const content = `${numberFormatter(usage.promptTokens, 0)} → ${numberFormatter(usage.completionTokens, 0)} (∑ ${numberFormatter(usage.totalTokens, 0)})`;
+
if (props.inline)
return (
- <span>
- {`${numberFormatter(usage.promptTokens, 0)} → ${numberFormatter(usage.completionTokens, 0)} (∑ ${numberFormatter(usage.totalTokens, 0)})`}
+ <span className="flex items-center gap-1">
+ {content}
+ {props.rightIcon}
</span>
);
return (
<Badge variant="outline">
- {`${numberFormatter(usage.promptTokens, 0)} → ${numberFormatter(usage.completionTokens, 0)} (∑ ${numberFormatter(usage.totalTokens, 0)})`}
+ <span className="flex items-center gap-1">
+ {content}
+ {props.rightIcon}
+ </span>
</Badge>
);
};
diff --git a/web/src/components/trace/BreakdownToolTip.tsx b/web/src/components/trace/BreakdownToolTip.tsx
new file mode 100644
index 0000000000..e77b09c09e
--- /dev/null
+++ b/web/src/components/trace/BreakdownToolTip.tsx
@@ -0,0 +1,201 @@
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/src/components/ui/tooltip";
+import { useState } from "react";
+import Decimal from "decimal.js";
+
+interface Details {
+ [key: string]: number | undefined;
+}
+
+interface BreakdownTooltipProps {
+ details: Details | Details[];
+ children: React.ReactNode;
+ isCost?: boolean;
+}
+
+export const BreakdownTooltip = ({
+ details,
+ children,
+ isCost = false,
+}: BreakdownTooltipProps) => {
+ const [isOpen, setIsOpen] = useState(false);
+
+ // Aggregate details if array is provided
+ const aggregatedDetails = Array.isArray(details)
+ ? details.reduce<Details>((acc, curr) => {
+ Object.entries(curr).forEach(([key, value]) => {
+ acc[key] = new Decimal(acc[key] || 0)
+ .plus(new Decimal(value || 0))
+ .toNumber();
+ });
+ return acc;
+ }, {})
+ : details;
+
+ // For costs, calculate the maximum number of decimal places needed
+ const getMaxDecimals = (value: number | undefined): number => {
+ if (!value) return 0;
+ const parts = value.toString().split(".");
+
+ // If no decimal point, return 0, else return length of decimal part
+ return parts.length === 1 ? 0 : parts[1].length;
+ };
+
+ const formatValueWithPadding = (value: number, maxDecimals: number) => {
+ return !value
+ ? "0"
+ : isCost
+ ? `$${value.toFixed(maxDecimals)}`
+ : value.toLocaleString();
+ };
+
+ const maxDecimals = isCost
+ ? Math.max(...Object.values(aggregatedDetails).map(getMaxDecimals))
+ : 0;
+
+ return (
+ <TooltipProvider>
+ <Tooltip open={isOpen} onOpenChange={setIsOpen}>
+ <TooltipTrigger
+ className="cursor-pointer"
+ onClick={() => setIsOpen(!isOpen)}
+ >
+ {children}
+ </TooltipTrigger>
+ <TooltipContent className="w-64 p-4">
+ <div className="flex flex-col gap-4">
+ <div className="flex flex-col gap-1">
+ <span className="font-semibold">
+ {isCost ? "Cost breakdown" : "Usage breakdown"}
+ </span>
+ {Array.isArray(details) && details.length > 0 && (
+ <span className="text-xs italic text-muted-foreground">
+ Aggregate across {details.length}{" "}
+ {details.length === 1 ? "generation" : "generations"}
+ </span>
+ )}
+ </div>
+
+ {/* Input Section */}
+ <Section
+ title={isCost ? "Input cost" : "Input usage"}
+ details={aggregatedDetails}
+ filterFn={(key) => key.includes("input")}
+ formatValue={(v) => formatValueWithPadding(v, maxDecimals)}
+ />
+
+ {/* Output Section */}
+ <Section
+ title={isCost ? "Output cost" : "Output usage"}
+ details={aggregatedDetails}
+ filterFn={(key) => key.includes("output")}
+ formatValue={(v) => formatValueWithPadding(v, maxDecimals)}
+ />
+
+ {/* Other Section */}
+ <OtherSection
+ details={aggregatedDetails}
+ isCost={isCost}
+ formatValue={(v) => formatValueWithPadding(v, maxDecimals)}
+ />
+
+ {/* Total */}
+ <div className="flex justify-between border-b-4 border-t border-double py-1">
+ <span className="text-xs font-semibold">
+ {isCost ? "Total cost" : "Total usage"}
+ </span>
+ <span className="font-mono text-xs font-semibold">
+ {formatValueWithPadding(
+ aggregatedDetails.total ?? 0,
+ maxDecimals,
+ )}
+ </span>
+ </div>
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
+};
+
+interface SectionProps {
+ title: string;
+ details: Details;
+ filterFn: (key: string) => boolean;
+ formatValue: (value: number) => string;
+}
+
+const Section = ({ title, details, filterFn, formatValue }: SectionProps) => {
+ const filteredEntries = Object.entries(details)
+ .filter(([key]) => filterFn(key))
+ .sort(([, a], [, b]) => (b ?? 0) - (a ?? 0));
+
+ const sectionTotal = filteredEntries.reduce(
+ (sum, [_, value]) =>
+ new Decimal(sum).plus(new Decimal(value ?? 0)).toNumber(),
+ 0,
+ );
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex justify-between border-b pb-1">
+ <span className="text-xs font-semibold">{title}</span>
+ <span className="text-right font-mono text-xs font-semibold">
+ {formatValue(sectionTotal)}
+ </span>
+ </div>
+ {filteredEntries.map(([key, value]) => (
+ <div
+ key={key}
+ className="flex justify-between text-xs text-muted-foreground"
+ >
+ <span className="mr-4">{key}</span>
+ <span className="font-mono">{formatValue(value ?? 0)}</span>
+ </div>
+ ))}
+ </div>
+ );
+};
+
+interface OtherSectionProps {
+ details: Details;
+ isCost: boolean;
+ formatValue: (value: number) => string;
+}
+
+const OtherSection = ({ details, isCost, formatValue }: OtherSectionProps) => {
+ const otherEntries = Object.entries(details)
+ .filter(
+ ([key]) =>
+ !key.includes("input") && !key.includes("output") && key !== "total",
+ )
+ .sort(([, a], [, b]) => (b ?? 0) - (a ?? 0));
+
+ if (otherEntries.length === 0) return null;
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex justify-between border-b pb-2">
+ <span className="text-xs font-medium">
+ {isCost ? "Other cost" : "Other usage"}
+ </span>
+ <span className="text-right font-mono text-xs font-medium">
+ {formatValue(details.total ?? 0)}
+ </span>
+ </div>
+ {otherEntries.map(([key, value]) => (
+ <div
+ key={key}
+ className="flex justify-between text-xs text-muted-foreground"
+ >
+ <span className="mr-4">{key}</span>
+ <span className="font-mono">{formatValue(value ?? 0)}</span>
+ </div>
+ ))}
+ </div>
+ );
+};
diff --git a/web/src/components/trace/IOPreview.tsx b/web/src/components/trace/IOPreview.tsx
index 37acdb5b7e..dc01a66add 100644
--- a/web/src/components/trace/IOPreview.tsx
+++ b/web/src/components/trace/IOPreview.tsx
@@ -152,7 +152,7 @@ export const IOPreview: React.FC<{
// If there are additional input fields beyond the messages, render them
const additionalInput =
- typeof input === "object" && input !== null
+ typeof input === "object" && input !== null && !Array.isArray(input)
? Object.fromEntries(
Object.entries(input as object).filter(([key]) => key !== "messages"),
)
diff --git a/web/src/components/trace/ObservationPreview.tsx b/web/src/components/trace/ObservationPreview.tsx
index 5a737abea0..04cd7f552b 100644
--- a/web/src/components/trace/ObservationPreview.tsx
+++ b/web/src/components/trace/ObservationPreview.tsx
@@ -38,6 +38,8 @@ import {
TabsBarTrigger,
} from "@/src/components/ui/tabs-bar";
import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";
+import { BreakdownTooltip } from "./BreakdownToolTip";
+import { InfoIcon } from "lucide-react";
export const ObservationPreview = ({
observations,
@@ -185,11 +187,22 @@ export const ObservationPreview = ({
</Badge>
) : null}
{preloadedObservation.type === "GENERATION" && (
- <Badge variant="outline">
- {preloadedObservation.promptTokens} prompt →{" "}
- {preloadedObservation.completionTokens} completion (∑{" "}
- {preloadedObservation.totalTokens})
- </Badge>
+ <BreakdownTooltip
+ details={preloadedObservation.usageDetails}
+ isCost={false}
+ >
+ <Badge
+ variant="outline"
+ className="flex items-center gap-1"
+ >
+ <span>
+ {preloadedObservation.promptTokens} prompt →{" "}
+ {preloadedObservation.completionTokens} completion (∑{" "}
+ {preloadedObservation.totalTokens})
+ </span>
+ <InfoIcon className="h-3 w-3" />
+ </Badge>
+ </BreakdownTooltip>
)}
{preloadedObservation.version ? (
<Badge variant="outline">
@@ -200,9 +213,18 @@ export const ObservationPreview = ({
<Badge variant="outline">{preloadedObservation.model}</Badge>
) : null}
{thisCost ? (
- <Badge variant="outline">
- {usdFormatter(thisCost.toNumber())}
- </Badge>
+ <BreakdownTooltip
+ details={preloadedObservation.costDetails}
+ isCost={true}
+ >
+ <Badge
+ variant="outline"
+ className="flex items-center gap-1"
+ >
+ <span>{usdFormatter(thisCost.toNumber())}</span>
+ <InfoIcon className="h-3 w-3" />
+ </Badge>
+ </BreakdownTooltip>
) : undefined}
{totalCost && totalCost !== thisCost ? (
<Badge variant="outline">
diff --git a/web/src/components/trace/TracePreview.tsx b/web/src/components/trace/TracePreview.tsx
index 8810dfd13a..a5a110540b 100644
--- a/web/src/components/trace/TracePreview.tsx
+++ b/web/src/components/trace/TracePreview.tsx
@@ -38,6 +38,8 @@ import {
TabsBarList,
TabsBarTrigger,
} from "@/src/components/ui/tabs-bar";
+import { BreakdownTooltip } from "@/src/components/trace/BreakdownToolTip";
+import { InfoIcon } from "lucide-react";
export const TracePreview = ({
trace,
@@ -133,7 +135,16 @@ export const TracePreview = ({
{formatIntervalSeconds(trace.latency)}
</Badge>
)}
- <AggUsageBadge observations={observations} />
+ <BreakdownTooltip
+ details={observations
+ .filter((o) => o.type === "GENERATION")
+ .map((o) => o.usageDetails)}
+ >
+ <AggUsageBadge
+ observations={observations}
+ rightIcon={<InfoIcon className="h-3 w-3" />}
+ />
+ </BreakdownTooltip>
{!!trace.release && (
<Badge variant="outline">Release: {trace.release}</Badge>
)}
@@ -141,9 +152,19 @@ export const TracePreview = ({
<Badge variant="outline">Version: {trace.version}</Badge>
)}
{totalCost && (
- <Badge variant="outline">
- ∑ {usdFormatter(totalCost.toNumber())}
- </Badge>
+ <BreakdownTooltip
+ details={observations
+ .filter((o) => o.type === "GENERATION")
+ .map((o) => o.costDetails)}
+ isCost
+ >
+ <Badge variant="outline">
+ <span className="flex items-center gap-1">
+ Total Cost: {usdFormatter(totalCost.toNumber())}
+ <InfoIcon className="h-3 w-3" />
+ </span>
+ </Badge>
+ </BreakdownTooltip>
)}
</div>
)}
diff --git a/web/src/features/dashboard/components/ModelUsageChart.tsx b/web/src/features/dashboard/components/ModelUsageChart.tsx
index 4f9d3b952b..2de39120e3 100644
--- a/web/src/features/dashboard/components/ModelUsageChart.tsx
+++ b/web/src/features/dashboard/components/ModelUsageChart.tsx
@@ -1,26 +1,43 @@
-import { api } from "@/src/utils/api";
-
-import { type FilterState } from "@langfuse/shared";
+import { Check, ChevronsUpDown } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";
+import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";
+import { Button } from "@/src/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+ CommandSeparator,
+} from "@/src/components/ui/command";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/src/components/ui/popover";
+import { env } from "@/src/env.mjs";
+import { BaseTimeSeriesChart } from "@/src/features/dashboard/components/BaseTimeSeriesChart";
+import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";
import {
- getAllModels,
extractTimeSeriesData,
fillMissingValuesAndTransform,
+ getAllModels,
isEmptyTimeSeries,
} from "@/src/features/dashboard/components/hooks";
-import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";
-import { compactNumberFormatter } from "@/src/utils/numbers";
import { TabComponent } from "@/src/features/dashboard/components/TabsComponent";
-import { BaseTimeSeriesChart } from "@/src/features/dashboard/components/BaseTimeSeriesChart";
import { TotalMetric } from "@/src/features/dashboard/components/TotalMetric";
import { totalCostDashboardFormatted } from "@/src/features/dashboard/lib/dashboard-utils";
+import { api } from "@/src/utils/api";
import {
- dashboardDateRangeAggregationSettings,
type DashboardDateRangeAggregationOption,
+ dashboardDateRangeAggregationSettings,
} from "@/src/utils/date-range-utils";
-import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";
-import { env } from "@/src/env.mjs";
-import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";
+import { compactNumberFormatter } from "@/src/utils/numbers";
+import { cn } from "@/src/utils/tailwind";
+import { type FilterState } from "@langfuse/shared";
export const ModelUsageChart = ({
className,
@@ -33,7 +50,23 @@ export const ModelUsageChart = ({
globalFilterState: FilterState;
agg: DashboardDateRangeAggregationOption;
}) => {
- const tokens = api.dashboard.chart.useQuery(
+ const clickhouse = useClickhouse();
+ const allModels = getAllModels(projectId, globalFilterState, clickhouse);
+
+ const [selectedModels, setSelectedModels] = useState<string[]>([]);
+ const [open, setOpen] = useState(false);
+ const [firstAllModelUpdate, setFirstAllModelUpdate] = useState(true);
+
+ const isAllSelected = selectedModels.length === allModels.length;
+ const buttonText = isAllSelected
+ ? "All models"
+ : `${selectedModels.length} selected`;
+
+ const handleSelectAll = () => {
+ setSelectedModels(isAllSelected ? [] : [...allModels]);
+ };
+
+ const queryResult = api.dashboard.chart.useQuery(
{
projectId,
from: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION // Langfuse Cloud has already completed the cost backfill job, thus cost can be pulled directly from obs. table
@@ -47,6 +80,16 @@ export const ModelUsageChart = ({
filter: [
...globalFilterState,
{ type: "string", column: "type", operator: "=", value: "GENERATION" },
+ ...(!isAllSelected
+ ? [
+ {
+ type: "stringOptions",
+ column: "model",
+ operator: "any of",
+ value: selectedModels,
+ } as const,
+ ]
+ : []),
],
groupBy: [
{
@@ -62,10 +105,11 @@ export const ModelUsageChart = ({
orderBy: [
{ column: "calculatedTotalCost", direction: "DESC", agg: "SUM" },
],
- queryClickhouse: useClickhouse(),
+ queryClickhouse: clickhouse,
queryName: "observations-usage-timeseries",
},
{
+ enabled: selectedModels.length > 0,
trpc: {
context: {
skipBatch: true,
@@ -74,41 +118,102 @@ export const ModelUsageChart = ({
},
);
- const allModels = getAllModels(projectId, globalFilterState, useClickhouse());
+ useEffect(() => {
+ if (firstAllModelUpdate && allModels.length > 0) {
+ setSelectedModels(allModels);
+ setFirstAllModelUpdate(false);
+ }
+ }, [allModels, firstAllModelUpdate]);
- const transformedTotalTokens =
- tokens.data && allModels.length > 0
+ const usageTypeMap = new Map<
+ string,
+ {
+ units: number;
+ cost: number;
+ usageType: string;
+ model: string;
+ }[]
+ >();
+
+ queryResult.data?.forEach((row) => {
+ for (const [key, value] of Object.entries(row.units ?? {})) {
+ usageTypeMap.set(key, [
+ ...(usageTypeMap.get(key) ?? []),
+ {
+ ...row,
+ units: value,
+ cost: Number(row.cost?.[key as keyof typeof row.cost]),
+ usageType: key,
+ model: row.model as string,
+ },
+ ]);
+ }
+ });
+
+ const usageData = Array.from(usageTypeMap.values()).flat();
+ const currentModels = [...new Set(usageData.map((row) => row.model))];
+
+ const unitsByType =
+ usageData && allModels.length > 0
+ ? fillMissingValuesAndTransform(
+ extractTimeSeriesData(usageData, "startTime", [
+ {
+ uniqueIdentifierColumns: [{ accessor: "usageType" }],
+ valueColumn: "units",
+ },
+ ]),
+ Array.from(usageTypeMap.keys()),
+ )
+ : [];
+
+ const unitsByModel =
+ usageData && allModels.length > 0
? fillMissingValuesAndTransform(
- extractTimeSeriesData(tokens.data, "startTime", [
+ extractTimeSeriesData(usageData, "startTime", [
{
uniqueIdentifierColumns: [{ accessor: "model" }],
- valueColumn: "sumTotalTokens",
+ valueColumn: "units",
+ },
+ ]),
+ currentModels,
+ )
+ : [];
+
+ const costByType =
+ usageData && allModels.length > 0
+ ? fillMissingValuesAndTransform(
+ extractTimeSeriesData(usageData, "startTime", [
+ {
+ uniqueIdentifierColumns: [{ accessor: "usageType" }],
+ valueColumn: "cost",
},
]),
- allModels,
+ Array.from(usageTypeMap.keys()),
)
: [];
- const transformedModelCost =
- tokens.data && allModels.length > 0
+ const costByModel =
+ usageData && allModels.length > 0
? fillMissingValuesAndTransform(
- extractTimeSeriesData(tokens.data, "startTime", [
+ extractTimeSeriesData(usageData, "startTime", [
{
uniqueIdentifierColumns: [{ accessor: "model" }],
- valueColumn: "sumCalculatedTotalCost",
+ valueColumn: "cost",
},
]),
- allModels,
+ currentModels,
)
: [];
- const totalCost = tokens.data?.reduce(
- (acc, curr) => acc + (curr.sumCalculatedTotalCost as number),
+ const totalCost = usageData?.reduce(
+ (acc, curr) =>
+ acc + (curr.usageType === "total" ? (curr.cost as number) : 0),
0,
);
- const totalTokens = tokens.data?.reduce(
- (acc, curr) => acc + (curr.sumTotalTokens as number),
+ const totalTokens = usageData?.reduce(
+ (acc, curr) =>
+ acc + (curr.usageType === "total" ? (curr.units as number) : 0),
0,
);
@@ -120,19 +225,34 @@ export const ModelUsageChart = ({
const data = [
{
- tabTitle: "Total cost",
- data: transformedModelCost,
+ tabTitle: "Cost by model",
+ data: costByModel,
+ totalMetric: totalCostDashboardFormatted(totalCost),
+ metricDescription: `Cost`,
+ formatter: oneValueUsdFormatter,
+ },
+ {
+ tabTitle: "Cost by type",
+ data: costByType,
totalMetric: totalCostDashboardFormatted(totalCost),
- metricDescription: `Token cost`,
+ metricDescription: `Cost`,
formatter: oneValueUsdFormatter,
},
{
- tabTitle: "Total tokens",
- data: transformedTotalTokens,
+ tabTitle: "Units by model",
+ data: unitsByModel,
+ totalMetric: totalTokens
+ ? compactNumberFormatter(totalTokens)
+ : compactNumberFormatter(0),
+ metricDescription: `Units`,
+ },
+ {
+ tabTitle: "Units by type",
+ data: unitsByType,
totalMetric: totalTokens
? compactNumberFormatter(totalTokens)
: compactNumberFormatter(0),
- metricDescription: `Token count`,
+ metricDescription: `Units`,
},
];
@@ -140,7 +260,69 @@ export const ModelUsageChart = ({
<DashboardCard
className={className}
title="Model Usage"
- isLoading={tokens.isLoading}
+ isLoading={queryResult.isLoading && selectedModels.length > 0}
+ headerRight={
+ <div className="flex items-center justify-end">
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ role="combobox"
+ aria-expanded={open}
+ className="w-56 justify-between"
+ >
+ {buttonText}
+ <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-56 p-0">
+ <Command>
+ <CommandInput placeholder="Search models..." />
+ <CommandEmpty>No model found.</CommandEmpty>
+ <CommandGroup>
+ <CommandItem
+ onSelect={handleSelectAll}
+ className="border-b border-gray-200 bg-gray-50 font-medium hover:bg-gray-100"
+ >
+ <Check
+ className={cn(
+ "mr-2 h-4 w-4",
+ isAllSelected ? "opacity-100" : "opacity-0",
+ )}
+ />
+ <span>Select All</span>
+ </CommandItem>
+ <CommandSeparator />
+ <CommandList>
+ {allModels.map((model) => (
+ <CommandItem
+ key={model}
+ onSelect={() => {
+ setSelectedModels((prev) =>
+ prev.includes(model)
+ ? prev.filter((m) => m !== model)
+ : [...prev, model],
+ );
+ }}
+ >
+ <Check
+ className={cn(
+ "mr-2 h-4 w-4",
+ selectedModels.includes(model)
+ ? "opacity-100"
+ : "opacity-0",
+ )}
+ />
+ {model}
+ </CommandItem>
+ ))}
+ </CommandList>
+ </CommandGroup>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ </div>
+ }
>
<TabComponent
tabs={data.map((item) => {
@@ -153,8 +335,9 @@ export const ModelUsageChart = ({
description={item.metricDescription}
className="mb-4"
/>
- {isEmptyTimeSeries({ data: item.data }) || tokens.isLoading ? (
- <NoDataOrLoading isLoading={tokens.isLoading} />
+ {isEmptyTimeSeries({ data: item.data }) ||
+ queryResult.isLoading ? (
+ <NoDataOrLoading isLoading={queryResult.isLoading} />
) : (
<BaseTimeSeriesChart
agg={agg}
diff --git a/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx b/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx
index 36608a9317..8ee5b318ce 100644
--- a/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx
+++ b/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx
@@ -101,29 +101,29 @@ export const TracesAndObservationsTimeSeriesChart = ({
const transformedObservations = observations.data
? Object.values(
- observations.data.reduce(
- (acc, item) => {
- const ts = (item.start_time_bucket as Date).getTime();
- if (!acc[ts]) {
- acc[ts] = {
- ts,
- values: [],
- };
- }
- acc[ts].values.push({
- label: item.level as string,
- value: typeof item.count === "number" ? item.count : undefined,
- });
- return acc;
- },
- {} as Record<
+ observations.data.reduce<
+ Record<
number,
{
ts: number;
values: { label: string; value: number | undefined }[];
}
- >,
- ),
+ >
+ >((acc, item) => {
+ const ts = (item.start_time_bucket as Date).getTime();
+ if (!acc[ts]) {
+ acc[ts] = {
+ ts,
+ values: [],
+ };
+ }
+ acc[ts].values.push({
+ label: item.level as string,
+ value: typeof item.count === "number" ? item.count : undefined,
+ });
+
+ return acc;
+ }, {}),
)
: [];
diff --git a/web/src/features/dashboard/components/cards/DashboardCard.tsx b/web/src/features/dashboard/components/cards/DashboardCard.tsx
index c359b96a25..357c947950 100644
--- a/web/src/features/dashboard/components/cards/DashboardCard.tsx
+++ b/web/src/features/dashboard/components/cards/DashboardCard.tsx
@@ -18,6 +18,7 @@ export type DashboardCardProps = {
headerChildren?: ReactNode;
cardContentClassName?: string;
headerClassName?: string;
+ headerRight?: ReactNode;
};
export const DashboardCard = ({
@@ -29,19 +30,23 @@ export const DashboardCard = ({
headerChildren,
cardContentClassName,
headerClassName,
+ headerRight,
}: DashboardCardProps) => {
return (
<Card className={cn("flex flex-col", className)}>
<CardHeader className={cn("relative", headerClassName)}>
- <div className="flex flex-col gap-1.5">
- <CardTitle>{title}</CardTitle>
- {description ? (
- <CardDescription>{description}</CardDescription>
- ) : undefined}
+ <div className="items-top flex justify-between">
+ <div className="flex flex-col gap-1.5">
+ <CardTitle>{title}</CardTitle>
+ {description ? (
+ <CardDescription>{description}</CardDescription>
+ ) : undefined}
+ </div>
+ {headerRight}
</div>
- {headerChildren ?? undefined}
+ {headerChildren}
{isLoading ? (
- <div className="absolute right-5 top-5 ">
+ <div className="absolute right-5 top-5">
<Loader className="h-5 w-5 animate-spin" />
</div>
) : null}
diff --git a/web/src/features/dashboard/lib/score-analytics-utils.ts b/web/src/features/dashboard/lib/score-analytics-utils.ts
index b425d4dd56..72aab7bc1e 100644
--- a/web/src/features/dashboard/lib/score-analytics-utils.ts
+++ b/web/src/features/dashboard/lib/score-analytics-utils.ts
@@ -111,7 +111,9 @@ function groupCategoricalScoreDataByTimestamp(
if (row[scoreTimestampAccessor] === null) {
return acc;
}
- const timestamp = new Date(row[scoreTimestampAccessor] ?? new Date());
+ const timestamp = new Date(
+ (row[scoreTimestampAccessor] as string) ?? new Date(),
+ );
const key = convertDateToStringTimestamp(timestamp);
if (!acc[key]) {
acc[key] = [];
diff --git a/web/src/features/dashboard/server/dashboard-router.ts b/web/src/features/dashboard/server/dashboard-router.ts
index 5763a2e74b..f547add740 100644
--- a/web/src/features/dashboard/server/dashboard-router.ts
+++ b/web/src/features/dashboard/server/dashboard-router.ts
@@ -150,8 +150,8 @@ export const dashboardRouter = createTRPCRouter({
return rowsObs.map((row) => ({
startTime: row.start_time,
- sumTotalTokens: row.sum_usage_details,
- sumCalculatedTotalCost: row.sum_cost_details,
+ units: row.units,
+ cost: row.cost,
model: row.provided_model_name,
})) as DatabaseRow[];
diff --git a/web/src/features/public-api/server/dailyMetrics.ts b/web/src/features/public-api/server/dailyMetrics.ts
index 9b83a595ab..008bb0ee1c 100644
--- a/web/src/features/public-api/server/dailyMetrics.ts
+++ b/web/src/features/public-api/server/dailyMetrics.ts
@@ -38,8 +38,8 @@ export const generateDailyMetrics = async (props: QueryType) => {
o.provided_model_name as model,
count(o.id) as countObservations,
count(distinct t.id) as countTraces,
- sumMap(o.usage_details)['input'] as inputUsage,
- sumMap(o.usage_details)['output'] as outputUsage,
+ arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, o.usage_details))) as inputUsage,
+ arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, o.usage_details))) as outputUsage,
sumMap(o.usage_details)['total'] as totalUsage,
sum(coalesce(o.total_cost, 0)) as totalCost
FROM traces t FINAL
@@ -48,7 +48,7 @@ export const generateDailyMetrics = async (props: QueryType) => {
AND t.project_id = {projectId: String}
${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}
${timeFilter ? `AND start_time >= {cteTimeFilter: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
- GROUP BY date, model
+ GROUP BY date, model, usage_details
), daily_model_usage AS (
SELECT
"date",
diff --git a/web/src/features/public-api/types/observations.ts b/web/src/features/public-api/types/observations.ts
index 6537aad323..b5988b8ee9 100644
--- a/web/src/features/public-api/types/observations.ts
+++ b/web/src/features/public-api/types/observations.ts
@@ -43,12 +43,14 @@ export const APIObservation = z
promptVersion: z.number().int().positive().nullable(),
// usage
+ usageDetails: z.record(z.string(), z.number().nonnegative()),
+ costDetails: z.record(z.string(), z.number().nonnegative()),
usage: z.object({
unit: z.string().nullable(),
input: z.number(),
output: z.number(),
total: z.number(),
- }),
+ }), // backwards compatibility
unit: z.string().nullable(), // backwards compatibility
promptTokens: z.number(), // backwards compatibility
completionTokens: z.number(), // backwards compatibility
@@ -89,6 +91,8 @@ export const transformDbToApiObservation = (
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,
diff --git a/web/src/pages/api/public/traces/[traceId].ts b/web/src/pages/api/public/traces/[traceId].ts
index 383307caf5..aac044c428 100644
--- a/web/src/pages/api/public/traces/[traceId].ts
+++ b/web/src/pages/api/public/traces/[traceId].ts
@@ -9,7 +9,6 @@ import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
import {
filterAndValidateDbScoreList,
LangfuseNotFoundError,
- type ObservationView,
} from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import {
@@ -125,7 +124,7 @@ export default withMiddlewares({
})
: [];
- const observationsView: ObservationView[] = observations.map((o) => {
+ const observationsView = observations.map((o) => {
const model = models.find((m) => m.id === o.modelId);
const inputPrice =
model?.Price.find((p) => p.usageType === "input")?.price ??
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index 1a458b8252..82716915ae 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -73,6 +73,8 @@ export type ObservationReturnType = Omit<
| "metadata"
> & {
traceId: string;
+ usageDetails: Record<string, number>;
+ costDetails: Record<string, number>;
};
export const traceRouter = createTRPCRouter({
@@ -561,7 +563,11 @@ export const traceRouter = createTRPCRouter({
...trace,
scores: validatedScores,
latency: latencyMs !== undefined ? latencyMs / 1000 : undefined,
- observations: observations as ObservationReturnType[],
+ observations: observations.map((o) => ({
+ ...o,
+ usageDetails: {}, // no usageDetails in legacy postgres
+ costDetails: {}, // no costDetails in legacy postgres
+ })) as ObservationReturnType[],
};
},
clickhouseExecution: async () => {
diff --git a/web/src/server/api/services/queryBuilder.ts b/web/src/server/api/services/queryBuilder.ts
index 90e5fb9323..acfcfdeb49 100644
--- a/web/src/server/api/services/queryBuilder.ts
+++ b/web/src/server/api/services/queryBuilder.ts
@@ -20,7 +20,7 @@ export type InternalDatabaseRow = {
};
export type DatabaseRow = {
- [key: string]: string | number | Date | null;
+ [key: string]: string | number | Date | Record<string, unknown> | null;
};
export const executeQuery = async (
diff --git a/worker/src/constants/default-model-prices.json b/worker/src/constants/default-model-prices.json
index 7716a00caa..f60079d84d 100644
--- a/worker/src/constants/default-model-prices.json
+++ b/worker/src/constants/default-model-prices.json
@@ -4,10 +4,11 @@
"model_name": "gpt-4o",
"match_pattern": "(?i)^(gpt-4o)$",
"created_at": "2024-05-13T23:15:07.670Z",
- "updated_at": "2024-05-13T23:15:07.670Z",
+ "updated_at": "2024-12-03T10:12:31.000Z",
"prices": {
- "input": 0.000005,
- "output": 0.000015
+ "input": 2.5e-6,
+ "input_cached_tokens": 1.25e-6,
+ "output": 10e-6
},
"tokenizer_config": {
"tokensPerName": 1,
@@ -836,10 +837,14 @@
"model_name": "claude-3-sonnet-20240229",
"match_pattern": "(?i)^(claude-3-sonnet-20240229|anthropic\\.claude-3-sonnet-20240229-v1:0|claude-3-sonnet@20240229)$",
"created_at": "2024-03-07T17:55:38.139Z",
- "updated_at": "2024-03-07T17:55:38.139Z",
+ "updated_at": "2024-12-03T12:20:04.000Z",
"prices": {
- "input": 0.000003,
- "output": 0.000015
+ "input": 3e-6,
+ "input_tokens": 3e-6,
+ "output": 15e-6,
+ "output_tokens": 15e-6,
+ "cache_creation_input_tokens": 3.75e-6,
+ "cache_read_input_tokens": 0.3e-6
},
"tokenizer_config": null,
"tokenizer_id": "claude"
@@ -998,10 +1003,14 @@
"model_name": "claude-3-5-sonnet-20240620",
"match_pattern": "(?i)^(claude-3-5-sonnet-20240620|anthropic\\.claude-3-5-sonnet-20240620-v1:0|claude-3-5-sonnet@20240620)$",
"created_at": "2024-06-25T11:47:24.475Z",
- "updated_at": "2024-06-25T11:47:24.475Z",
+ "updated_at": "2024-12-03T12:20:59.000Z",
"prices": {
- "input": 0.000003,
- "output": 0.000015
+ "input": 3e-6,
+ "input_tokens": 3e-6,
+ "output": 15e-6,
+ "output_tokens": 15e-6,
+ "cache_creation_input_tokens": 3.75e-6,
+ "cache_read_input_tokens": 0.3e-6
},
"tokenizer_config": null,
"tokenizer_id": "claude"
@@ -1011,10 +1020,11 @@
"model_name": "gpt-4o-mini",
"match_pattern": "(?i)^(gpt-4o-mini)$",
"created_at": "2024-07-18T17:56:09.591Z",
- "updated_at": "2024-07-18T17:56:09.591Z",
+ "updated_at": "2024-12-03T10:28:30.000Z",
"prices": {
- "input": 1.5e-7,
- "output": 6e-7
+ "input": 0.15e-6,
+ "output": 0.6e-6,
+ "input_cached_tokens": 0.075e-6
},
"tokenizer_config": {
"tokensPerName": 1,
@@ -1028,10 +1038,11 @@
"model_name": "gpt-4o-mini-2024-07-18",
"match_pattern": "(?i)^(gpt-4o-mini-2024-07-18)$",
"created_at": "2024-07-18T17:56:09.591Z",
- "updated_at": "2024-07-18T17:56:09.591Z",
+ "updated_at": "2024-12-03T10:31:11.000Z",
"prices": {
- "input": 1.5e-7,
- "output": 6e-7
+ "input": 0.15e-6,
+ "input_cached_tokens": 0.075e-6,
+ "output": 0.6e-6
},
"tokenizer_config": {
"tokensPerName": 1,
@@ -1045,10 +1056,11 @@
"model_name": "gpt-4o-2024-08-06",
"match_pattern": "(?i)^(gpt-4o-2024-08-06)$",
"created_at": "2024-08-07T11:54:31.298Z",
- "updated_at": "2024-08-07T11:54:31.298Z",
+ "updated_at": "2024-12-03T10:15:18.000Z",
"prices": {
- "input": 0.0000025,
- "output": 0.00001
+ "input": 2.5e-6,
+ "input_cached_tokens": 1.25e-6,
+ "output": 10e-6
},
"tokenizer_config": {
"tokensPerName": 1,
@@ -1062,10 +1074,12 @@
"model_name": "o1-preview",
"match_pattern": "(?i)^(o1-preview)$",
"created_at": "2024-09-13T10:01:35.373Z",
- "updated_at": "2024-09-13T10:01:35.373Z",
+ "updated_at": "2024-12-03T10:34:05.000Z",
"prices": {
- "input": 0.000015,
- "output": 0.00006
+ "input": 15e-6,
+ "input_cached_tokens": 7.5e-6,
+ "output": 60e-6,
+ "output_reasoning_tokens": 60e-6
},
"tokenizer_config": null,
"tokenizer_id": null
@@ -1075,10 +1089,12 @@
"model_name": "o1-preview-2024-09-12",
"match_pattern": "(?i)^(o1-preview-2024-09-12)$",
"created_at": "2024-09-13T10:01:35.373Z",
- "updated_at": "2024-09-13T10:01:35.373Z",
+ "updated_at": "2024-12-03T10:38:51.000Z",
"prices": {
- "input": 0.000015,
- "output": 0.00006
+ "input": 15e-6,
+ "input_cached_tokens": 7.5e-6,
+ "output": 60e-6,
+ "output_reasoning_tokens": 60e-6
},
"tokenizer_config": null,
"tokenizer_id": null
@@ -1088,10 +1104,12 @@
"model_name": "o1-mini",
"match_pattern": "(?i)^(o1-mini)$",
"created_at": "2024-09-13T10:01:35.373Z",
- "updated_at": "2024-09-13T10:01:35.373Z",
+ "updated_at": "2024-12-03T10:41:55.000Z",
"prices": {
- "input": 0.000003,
- "output": 0.000012
+ "input": 3e-6,
+ "input_cached_tokens": 1.5e-6,
+ "output": 12e-6,
+ "output_reasoning_tokens": 12e-6
},
"tokenizer_config": null,
"tokenizer_id": null
@@ -1101,10 +1119,12 @@
"model_name": "o1-mini-2024-09-12",
"match_pattern": "(?i)^(o1-mini-2024-09-12)$",
"created_at": "2024-09-13T10:01:35.373Z",
- "updated_at": "2024-09-13T10:01:35.373Z",
+ "updated_at": "2024-12-03T10:43:16.000Z",
"prices": {
- "input": 0.000003,
- "output": 0.000012
+ "input": 3e-6,
+ "input_cached_tokens": 1.5e-6,
+ "output": 12e-6,
+ "output_reasoning_tokens": 12e-6
},
"tokenizer_config": null,
"tokenizer_id": null
@@ -1114,10 +1134,14 @@
"model_name": "claude-3.5-sonnet-20241022",
"match_pattern": "(?i)^(claude-3-5-sonnet-20241022|anthropic\\.claude-3-5-sonnet-20241022-v2:0|claude-3-5-sonnet-V2@20241022)$",
"created_at": "2024-10-22T18:48:01.676Z",
- "updated_at": "2024-10-22T18:48:01.676Z",
+ "updated_at": "2024-12-03T12:21:10.000Z",
"prices": {
- "input": 0.000003,
- "output": 0.000015
+ "input": 3e-6,
+ "input_tokens": 3e-6,
+ "output": 15e-6,
+ "output_tokens": 15e-6,
+ "cache_creation_input_tokens": 3.75e-6,
+ "cache_read_input_tokens": 0.3e-6
},
"tokenizer_config": null,
"tokenizer_id": "claude"
@@ -1127,10 +1151,14 @@
"model_name": "claude-3.5-sonnet-latest",
"match_pattern": "(?i)^(claude-3-5-sonnet-latest)$",
"created_at": "2024-10-22T18:48:01.676Z",
- "updated_at": "2024-10-22T18:48:01.676Z",
+ "updated_at": "2024-12-03T12:22:03.000Z",
"prices": {
- "input": 0.000003,
- "output": 0.000015
+ "input": 3e-6,
+ "input_tokens": 3e-6,
+ "output": 15e-6,
+ "output_tokens": 15e-6,
+ "cache_creation_input_tokens": 3.75e-6,
+ "cache_read_input_tokens": 0.3e-6
},
"tokenizer_config": null,
"tokenizer_id": "claude"
@@ -1140,10 +1168,14 @@
"model_name": "claude-3-5-haiku-20241022",
"match_pattern": "(?i)^(claude-3-5-haiku-20241022|anthropic\\.claude-3-5-haiku-20241022-v1:0|claude-3-5-haiku-V1@20241022)$",
"created_at": "2024-11-05T10:30:50.566Z",
- "updated_at": "2024-11-05T10:30:50.566Z",
+ "updated_at": "2024-12-03T12:24:24.000Z",
"prices": {
- "input": 0.000001,
- "output": 0.000005
+ "input": 0.8e-6,
+ "input_tokens": 0.8e-6,
+ "output": 4e-6,
+ "output_tokens": 4e-6,
+ "cache_creation_input_tokens": 1e-6,
+ "cache_read_input_tokens": 0.08e-6
},
"tokenizer_config": null,
"tokenizer_id": "claude"
@@ -1153,10 +1185,14 @@
"model_name": "claude-3.5-haiku-latest",
"match_pattern": "(?i)^(claude-3-5-haiku-latest)$",
"created_at": "2024-11-05T10:30:50.566Z",
- "updated_at": "2024-11-05T10:30:50.566Z",
+ "updated_at": "2024-12-03T12:26:33.000Z",
"prices": {
- "input": 0.000001,
- "output": 0.000005
+ "input": 0.8e-6,
+ "input_tokens": 0.8e-6,
+ "output": 4e-6,
+ "output_tokens": 4e-6,
+ "cache_creation_input_tokens": 1e-6,
+ "cache_read_input_tokens": 0.08e-6
},
"tokenizer_config": null,
"tokenizer_id": "claude"
@@ -1186,6 +1222,7 @@
"updated_at": "2024-12-03T10:06:12.000Z",
"prices": {
"input": 2.5e-6,
+ "input_cached_tokens": 1.25e-6,
"output": 10e-6
},
"tokenizer_config": {
@@ -1194,5 +1231,69 @@
"tokensPerMessage": 3
},
"tokenizer_id": "openai"
+ },
+ {
+ "id": "cm48b2ksh000008l0hn3u0hl3",
+ "model_name": "gpt-4o-audio-preview",
+ "match_pattern": "(?i)^(gpt-4o-audio-preview)$",
+ "created_at": "2024-12-03T10:19:56.000Z",
+ "updated_at": "2024-12-03T10:19:56.000Z",
+ "prices": {
+ "input_text_tokens": 2.5e-6,
+ "output_text_tokens": 10e-6,
+ "input_audio_tokens": 100e-6,
+ "output_audio_tokens": 200e-6
+ },
+ "tokenizer_config": null,
+ "tokenizer_id": null
+ },
+ {
+ "id": "cm48bbm0k000008l69nsdakwf",
+ "model_name": "gpt-4o-audio-preview-2024-10-01",
+ "match_pattern": "(?i)^(gpt-4o-audio-preview-2024-10-01)$",
+ "created_at": "2024-12-03T10:19:56.000Z",
+ "updated_at": "2024-12-03T10:19:56.000Z",
+ "prices": {
+ "input_text_tokens": 2.5e-6,
+ "output_text_tokens": 10e-6,
+ "input_audio_tokens": 100e-6,
+ "output_audio_tokens": 200e-6
+ },
+ "tokenizer_config": null,
+ "tokenizer_id": null
+ },
+ {
+ "id": "cm48c2qh4000008mhgy4mg2qc",
+ "model_name": "gpt-4o-realtime-preview",
+ "match_pattern": "(?i)^(gpt-4o-realtime-preview)$",
+ "created_at": "2024-12-03T10:19:56.000Z",
+ "updated_at": "2024-12-03T10:19:56.000Z",
+ "prices": {
+ "input_text_tokens": 5e-6,
+ "input_cached_text_tokens": 2.5e-6,
+ "output_text_tokens": 20e-6,
+ "input_audio_tokens": 100e-6,
+ "input_cached_audio_tokens": 20e-6,
+ "output_audio_tokens": 200e-6
+ },
+ "tokenizer_config": null,
+ "tokenizer_id": null
+ },
+ {
+ "id": "cm48cjxtc000008jrcsso3avv",
+ "model_name": "gpt-4o-realtime-preview-2024-10-01",
+ "match_pattern": "(?i)^(gpt-4o-realtime-preview-2024-10-01)$",
+ "created_at": "2024-12-03T10:19:56.000Z",
+ "updated_at": "2024-12-03T10:19:56.000Z",
+ "prices": {
+ "input_text_tokens": 5e-6,
+ "input_cached_text_tokens": 2.5e-6,
+ "output_text_tokens": 20e-6,
+ "input_audio_tokens": 100e-6,
+ "input_cached_audio_tokens": 20e-6,
+ "output_audio_tokens": 200e-6
+ },
+ "tokenizer_config": null,
+ "tokenizer_id": null
}
]
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index 95db176b4b..d61851729a 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -647,8 +647,16 @@ export class IngestionService {
return { usage_details, provided_usage_details: providedUsageDetails };
}
+ const usageDetails = { ...providedUsageDetails };
+ if (Object.keys(usageDetails).length > 0 && !("total" in usageDetails)) {
+ usageDetails.total = Object.values(providedUsageDetails).reduce(
+ (acc, value) => acc + value,
+ 0,
+ );
+ }
+
return {
- usage_details: providedUsageDetails,
+ usage_details: usageDetails,
provided_usage_details: providedUsageDetails,
};
}
@@ -931,21 +939,33 @@ export class IngestionService {
const newTotalCount =
("usage" in obs.body ? obs.body.usage?.total : undefined) ||
- (newInputCount !== undefined &&
- newOutputCount !== undefined &&
- newInputCount &&
- newOutputCount
- ? newInputCount + newOutputCount
- : (newInputCount ?? newOutputCount));
+ (Object.keys(
+ "usageDetails" in obs.body ? (obs.body.usageDetails ?? {}) : {},
+ ).length === 0
+ ? newInputCount && newOutputCount
+ ? newInputCount + newOutputCount
+ : (newInputCount ?? newOutputCount)
+ : undefined);
- const provided_usage_details: Record<string, number> = {};
+ let provided_usage_details: Record<string, number> = {};
if (newInputCount != null) provided_usage_details.input = newInputCount;
if (newOutputCount != null)
provided_usage_details.output = newOutputCount;
if (newTotalCount != null) provided_usage_details.total = newTotalCount;
- const provided_cost_details: Record<string, number> = {};
+ provided_usage_details = {
+ ...provided_usage_details,
+ ...("usageDetails" in obs.body
+ ? (Object.fromEntries(
+ Object.entries(obs.body.usageDetails ?? {}).filter(
+ ([_, val]) => val != null,
+ ),
+ ) as Record<string, number>)
+ : {}),
+ };
+
+ let provided_cost_details: Record<string, number> = {};
if ("usage" in obs.body) {
const { inputCost, outputCost, totalCost } = obs.body.usage ?? {};
@@ -955,6 +975,17 @@ export class IngestionService {
if (totalCost != null) provided_cost_details.total = totalCost;
}
+ provided_cost_details = {
+ ...provided_cost_details,
+ ...("costDetails" in obs.body
+ ? (Object.fromEntries(
+ Object.entries(obs.body.costDetails ?? {}).filter(
+ ([_, val]) => val != null,
+ ),
+ ) as Record<string, number>)
+ : {}),
+ };
+
if (obs.type?.endsWith("-create") && !obs.body?.startTime) {
logger.warn(
`Observation ${entityId} in project ${projectId} does not have a startTime, using event time`,
diff --git a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
index 320bed30bd..0075ed99a8 100644
--- a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
+++ b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
@@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
+import { z } from "zod";
import { prisma } from "@langfuse/shared/src/db";
import {
clickhouseClient,
@@ -14,6 +14,7 @@ import {
TraceEventType,
traceRecordReadSchema,
TraceRecordReadType,
+ ingestionEvent,
} from "@langfuse/shared/src/server";
import { pruneDatabase } from "../../../__tests__/utils";
@@ -22,6 +23,7 @@ import { IngestionService } from "../../IngestionService";
import { ModelUsageUnit, ScoreSource } from "@langfuse/shared";
const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+const IngestionEventBatchSchema = z.array(ingestionEvent);
describe("Ingestion end-to-end tests", () => {
let ingestionService: IngestionService;
@@ -108,29 +110,29 @@ describe("Ingestion end-to-end tests", () => {
outputCost: 456,
totalCost: 789,
},
- expectedInputUnits: 100,
- expectedOutputUnits: 200,
- expectedTotalUnits: 100,
+ expectedUsageDetails: {
+ input: 100,
+ output: 200,
+ total: 100,
+ },
},
{
usage: {
total: 100,
unit: ModelUsageUnit.Characters,
},
-
- expectedInputUnits: undefined,
- expectedOutputUnits: undefined,
- expectedTotalUnits: 100,
+ expectedUsageDetails: {
+ total: 100,
+ },
},
{
usage: {
total: 100,
unit: ModelUsageUnit.Milliseconds,
},
-
- expectedInputUnits: undefined,
- expectedOutputUnits: undefined,
- expectedTotalUnits: 100,
+ expectedUsageDetails: {
+ total: 100,
+ },
},
{
usage: {
@@ -138,10 +140,11 @@ describe("Ingestion end-to-end tests", () => {
output: 2,
unit: ModelUsageUnit.Images,
},
-
- expectedInputUnits: 1,
- expectedOutputUnits: 2,
- expectedTotalUnits: 3,
+ expectedUsageDetails: {
+ input: 1,
+ output: 2,
+ total: 3,
+ },
},
{
usage: {
@@ -149,10 +152,11 @@ describe("Ingestion end-to-end tests", () => {
output: 2,
unit: ModelUsageUnit.Requests,
},
-
- expectedInputUnits: 1,
- expectedOutputUnits: 2,
- expectedTotalUnits: 3,
+ expectedUsageDetails: {
+ input: 1,
+ output: 2,
+ total: 3,
+ },
},
{
usage: {
@@ -160,37 +164,183 @@ describe("Ingestion end-to-end tests", () => {
output: 10,
unit: ModelUsageUnit.Seconds,
},
-
- expectedInputUnits: 30,
- expectedOutputUnits: 10,
- expectedTotalUnits: 40,
+ expectedUsageDetails: {
+ input: 30,
+ output: 10,
+ total: 40,
+ },
},
{
usage: {
total: 100,
},
-
- expectedInputUnits: undefined,
- expectedOutputUnits: undefined,
- expectedTotalUnits: 100,
+ expectedUsageDetails: {
+ total: 100,
+ },
},
{
usage: undefined,
- expectedInputUnits: undefined,
- expectedOutputUnits: undefined,
- expectedTotalUnits: undefined,
+ expectedUsageDetails: {},
+ },
+ {
+ usage: null,
+ expectedUsageDetails: {},
+ },
+ {
+ usage: {},
+ expectedUsageDetails: {},
+ },
+ {
+ usage: {},
+ usageDetails: {
+ input: 1,
+ output: 2,
+ total: 3,
+ cached: 1,
+ },
+ expectedUsageDetails: {
+ input: 1,
+ output: 2,
+ total: 3,
+ cached: 1,
+ },
+ },
+ {
+ usage: {
+ input: 1,
+ output: 2,
+ total: 3,
+ },
+ usageDetails: {
+ cached: 1,
+ },
+ expectedUsageDetails: {
+ input: 1,
+ output: 2,
+ total: 3,
+ cached: 1,
+ },
+ },
+ {
+ usage: {
+ input: 1,
+ output: 2,
+ total: 3,
+ },
+ usageDetails: {
+ input: 2,
+ output: 3,
+ total: 5,
+ cached: 1,
+ },
+ expectedUsageDetails: {
+ input: 2,
+ output: 3,
+ total: 5,
+ cached: 1,
+ },
+ },
+ {
+ usage: {
+ input: 1,
+ output: 2,
+ total: 3,
+ },
+ costDetails: {
+ input: 123,
+ output: 456,
+ total: 789,
+ },
+ expectedUsageDetails: {
+ input: 1,
+ output: 2,
+ total: 3,
+ },
+ expectedCostDetails: {
+ input: 123,
+ output: 456,
+ total: 789,
+ },
+ },
+ {
+ usage: {},
+ usageDetails: {},
+ costDetails: {},
+ expectedUsageDetails: {},
+ expectedCostDetails: {},
},
{
usage: null,
- expectedInputUnits: undefined,
- expectedOutputUnits: undefined,
- expectedTotalUnits: undefined,
+ usageDetails: null,
+ costDetails: null,
+ expectedUsageDetails: {},
+ expectedCostDetails: {},
+ },
+ {
+ usage: undefined,
+ usageDetails: undefined,
+ costDetails: undefined,
+ expectedUsageDetails: {},
+ expectedCostDetails: {},
+ },
+ {
+ usage: { input: 1 },
+ usageDetails: { input: 2 },
+ costDetails: { input: 3 },
+ expectedUsageDetails: { input: 2, total: 2 },
+ expectedCostDetails: { input: 3, total: 3 },
+ },
+ {
+ usage: { input: 1 },
+ usageDetails: {
+ input: 1,
+ cached: 2,
+ reasoning: 3,
+ },
+ expectedUsageDetails: { input: 1, cached: 2, reasoning: 3, total: 6 },
},
{
usage: {},
- expectedInputUnits: undefined,
- expectedOutputUnits: undefined,
- expectedTotalUnits: undefined,
+ usageDetails: {
+ input: 1,
+ output: null,
+ total: undefined,
+ },
+ expectedUsageDetails: { input: 1, total: 1 },
+ costDetails: {
+ input: 123,
+ output: null,
+ cached: undefined,
+ },
+ expectedCostDetails: { input: 123, total: 123 },
+ },
+ // OpenAI format
+ {
+ usage: null,
+ usageDetails: {
+ prompt_tokens: 5,
+ completion_tokens: 11,
+ total_tokens: 16,
+ prompt_tokens_details: {
+ cached_tokens: 2,
+ audio_tokens: 3,
+ },
+ completion_tokens_details: {
+ text_tokens: 3,
+ audio_tokens: 4,
+ reasoning_tokens: 4,
+ },
+ },
+ expectedUsageDetails: {
+ input: 0,
+ output: 0,
+ total: 16,
+ input_cached_tokens: 2,
+ input_audio_tokens: 3,
+ output_text_tokens: 3,
+ output_audio_tokens: 4,
+ output_reasoning_tokens: 4,
+ },
},
].forEach((testConfig) => {
it(`should create trace, generation and score without matching models ${JSON.stringify(
@@ -221,36 +371,37 @@ describe("Ingestion end-to-end tests", () => {
},
];
- const generationEventList: ObservationEvent[] = [
- {
- id: randomUUID(),
- type: "observation-create",
- timestamp: new Date().toISOString(),
- body: {
- id: generationId,
- traceId: traceId,
- type: "GENERATION",
- name: "generation-name",
- startTime: "2021-01-01T00:00:00.000Z",
- endTime: "2021-01-01T00:00:00.000Z",
- modelParameters: { key: "value" },
- input: { key: "value" },
- metadata: { key: "value" },
- version: "2.0.0",
+ const generationEventList: ObservationEvent[] =
+ IngestionEventBatchSchema.parse([
+ {
+ id: randomUUID(),
+ type: "generation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ traceId: traceId,
+ name: "generation-name",
+ startTime: "2021-01-01T00:00:00.000Z",
+ endTime: "2021-01-01T00:00:00.000Z",
+ modelParameters: { key: "value" },
+ input: { key: "value" },
+ metadata: { key: "value" },
+ version: "2.0.0",
+ },
},
- },
- {
- id: randomUUID(),
- type: "observation-update",
- timestamp: new Date().toISOString(),
- body: {
- id: generationId,
- type: "GENERATION",
- output: { key: "this is a great gpt output" },
- usage: testConfig.usage,
+ {
+ id: randomUUID(),
+ type: "generation-update",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ output: { key: "this is a great gpt output" },
+ usage: testConfig.usage,
+ usageDetails: testConfig.usageDetails,
+ costDetails: testConfig.costDetails,
+ },
},
- },
- ];
+ ]);
const spanEventList: ObservationEvent[] = [
{
@@ -340,14 +491,8 @@ describe("Ingestion end-to-end tests", () => {
expect(generation.metadata).toEqual({ key: "value" });
expect(generation.version).toBe("2.0.0");
expect(generation.internal_model_id).toBeNull();
- expect(generation.usage_details.input).toEqual(
- testConfig.expectedInputUnits,
- );
- expect(generation.usage_details.output).toEqual(
- testConfig.expectedOutputUnits,
- );
- expect(generation.usage_details.total).toEqual(
- testConfig.expectedTotalUnits,
+ expect(generation.usage_details).toMatchObject(
+ testConfig.expectedUsageDetails,
);
expect(generation.output).toEqual(
JSON.stringify({
@@ -383,8 +528,10 @@ describe("Ingestion end-to-end tests", () => {
observationStartTime: new Date("2021-01-01T00:00:00.000Z"),
modelUnit: ModelUsageUnit.Tokens,
expectedInternalModelId: "custom-model-id",
- expectedInputUnits: 5,
- expectedOutputUnits: 7,
+ expectedUsageDetails: {
+ input: 5,
+ output: 7,
+ },
models: [
{
id: "custom-model-id",
@@ -401,8 +548,10 @@ describe("Ingestion end-to-end tests", () => {
observationStartTime: new Date("2021-01-01T00:00:00.000Z"),
modelUnit: ModelUsageUnit.Tokens,
expectedInternalModelId: "custom-model-id",
- expectedInputUnits: 5,
- expectedOutputUnits: 7,
+ expectedUsageDetails: {
+ input: 5,
+ output: 7,
+ },
models: [
{
id: "custom-model-id",
@@ -419,8 +568,10 @@ describe("Ingestion end-to-end tests", () => {
observationStartTime: new Date("2021-01-01T00:00:00.000Z"),
modelUnit: ModelUsageUnit.Tokens,
expectedInternalModelId: "custom-model-id",
- expectedInputUnits: 5,
- expectedOutputUnits: 7,
+ expectedUsageDetails: {
+ input: 5,
+ output: 7,
+ },
models: [
{
id: "custom-model-id",
@@ -437,8 +588,10 @@ describe("Ingestion end-to-end tests", () => {
observationStartTime: new Date("2021-01-01T00:00:00.000Z"),
modelUnit: ModelUsageUnit.Tokens,
expectedInternalModelId: "custom-model-id-2",
- expectedInputUnits: 5,
- expectedOutputUnits: 7,
+ expectedUsageDetails: {
+ input: 5,
+ output: 7,
+ },
models: [
{
id: "custom-model-id-1",
@@ -464,8 +617,10 @@ describe("Ingestion end-to-end tests", () => {
observationStartTime: new Date("2021-01-02T00:00:00.000Z"),
modelUnit: ModelUsageUnit.Tokens,
expectedInternalModelId: "custom-model-id-2",
- expectedInputUnits: 5,
- expectedOutputUnits: 7,
+ expectedUsageDetails: {
+ input: 5,
+ output: 7,
+ },
models: [
{
id: "custom-model-id-1",
@@ -491,8 +646,7 @@ describe("Ingestion end-to-end tests", () => {
observationStartTime: new Date("2022-01-01T10:00:00.000Z"),
modelUnit: ModelUsageUnit.Tokens,
expectedInternalModelId: "custom-model-id-1",
- expectedInputUnits: undefined,
- expectedOutputUnits: undefined,
+ expectedUsageDetails: {},
models: [
{
id: "custom-model-id-1",
@@ -509,8 +663,7 @@ describe("Ingestion end-to-end tests", () => {
observationStartTime: new Date("2022-01-01T10:00:00.000Z"),
modelUnit: ModelUsageUnit.Tokens,
expectedInternalModelId: "custom-model-id-1",
- expectedInputUnits: undefined,
- expectedOutputUnits: undefined,
+ expectedUsageDetails: {},
models: [
{
id: "custom-model-id-1",
@@ -527,8 +680,7 @@ describe("Ingestion end-to-end tests", () => {
observationStartTime: new Date("2021-01-01T00:00:00.000Z"),
modelUnit: ModelUsageUnit.Tokens,
expectedInternalModelId: null,
- expectedInputUnits: undefined,
- expectedOutputUnits: undefined,
+ expectedUsageDetails: {},
models: [
{
id: "custom-model-id-1",
@@ -545,8 +697,7 @@ describe("Ingestion end-to-end tests", () => {
observationStartTime: new Date("2021-01-01T00:00:00.000Z"),
modelUnit: ModelUsageUnit.Characters,
expectedInternalModelId: null,
- expectedInputUnits: undefined,
- expectedOutputUnits: undefined,
+ expectedUsageDetails: {},
models: [
{
id: "custom-model-id-1",
@@ -652,10 +803,10 @@ describe("Ingestion end-to-end tests", () => {
testConfig.observationExternalModel,
);
expect(generation.usage_details.input).toBe(
- testConfig.expectedInputUnits,
+ testConfig.expectedUsageDetails.input,
);
expect(generation.usage_details.output).toBe(
- testConfig.expectedOutputUnits,
+ testConfig.expectedUsageDetails.output,
);
expect(generation.internal_model_id).toBe(
testConfig.expectedInternalModelId,
@@ -1027,6 +1178,7 @@ describe("Ingestion end-to-end tests", () => {
body: {
id: scoreId,
dataType: "NUMERIC",
+ source: ScoreSource.API,
name: "score-name",
traceId: traceId,
value: 100.5,
@@ -1238,6 +1390,7 @@ describe("Ingestion end-to-end tests", () => {
});
expect(observation.usage_details).toStrictEqual({
input: 4,
+ total: 4,
});
expect(observation.provided_cost_details).toStrictEqual({});
expect(observation.cost_details).toStrictEqual({