Skip to content

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

feat: write token costs at ingestion time (#2414)

Hassieb Pakzad5a9f47faef15
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index b3466ab9cc..ad058a4a7d 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -264,6 +264,7 @@ export type Observation = {
updated_at: Generated<Timestamp>;
model: string | null;
internal_model: string | null;
+ internal_model_id: string | null;
modelParameters: unknown | null;
input: unknown | null;
output: unknown | null;
@@ -274,6 +275,9 @@ export type Observation = {
input_cost: string | null;
output_cost: string | null;
total_cost: string | null;
+ calculated_input_cost: string | null;
+ calculated_output_cost: string | null;
+ calculated_total_cost: string | null;
completion_start_time: Timestamp | null;
prompt_id: string | null;
};
diff --git a/packages/shared/prisma/migrations/20240625103957_observations_add_calculated_cost_columns/migration.sql b/packages/shared/prisma/migrations/20240625103957_observations_add_calculated_cost_columns/migration.sql
new file mode 100644
index 0000000000..c3ba234d1e
--- /dev/null
+++ b/packages/shared/prisma/migrations/20240625103957_observations_add_calculated_cost_columns/migration.sql
@@ -0,0 +1,5 @@
+-- AlterTable
+ALTER TABLE "observations" ADD COLUMN "calculated_input_cost" DECIMAL(65,30),
+ADD COLUMN "calculated_output_cost" DECIMAL(65,30),
+ADD COLUMN "calculated_total_cost" DECIMAL(65,30),
+ADD COLUMN "internal_model_id" TEXT;
diff --git a/packages/shared/prisma/migrations/20240625103958_fix_model_match_gpt4_vision/migration.sql b/packages/shared/prisma/migrations/20240625103958_fix_model_match_gpt4_vision/migration.sql
new file mode 100644
index 0000000000..aa68262767
--- /dev/null
+++ b/packages/shared/prisma/migrations/20240625103958_fix_model_match_gpt4_vision/migration.sql
@@ -0,0 +1,17 @@
+/*
+Previously, the pattern did not allow for model specifications like "1106" or any other 4-digit block.
+This led to missing models on the generation-update call where the exact model name that was used was provided (including the 4-digit block).
+The new pattern allows for:
+
+- "gpt-4-vision-preview" as set on generation-create
+- "gpt-4-1106-vision-preview" as set on generation-update
+
+*/
+
+UPDATE
+ "models"
+SET
+ "match_pattern" = '(?i)^(gpt-4(-\d{4})?-vision-preview)$'
+WHERE
+ "id" = 'clrkvx5gp000108juaogs54ea'
+ AND "model_name" = 'gpt-4-turbo-vision';
\ No newline at end of file
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 55b5e8b624..58eeaa9ef6 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -299,18 +299,28 @@ model Observation {
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
// GENERATION ONLY
- model String?
- internalModel String? @map("internal_model")
- modelParameters Json?
- input Json?
- output Json?
- promptTokens Int @default(0) @map("prompt_tokens")
- completionTokens Int @default(0) @map("completion_tokens")
- totalTokens Int @default(0) @map("total_tokens")
- unit String?
- inputCost Decimal? @map("input_cost")
- outputCost Decimal? @map("output_cost")
- totalCost Decimal? @map("total_cost")
+ model String?
+ internalModel String? @map("internal_model")
+ internalModelId String? @map("internal_model_id")
+
+ modelParameters Json?
+ input Json?
+ output Json?
+ promptTokens Int @default(0) @map("prompt_tokens")
+ completionTokens Int @default(0) @map("completion_tokens")
+ totalTokens Int @default(0) @map("total_tokens")
+ unit String?
+
+ // User provided cost at ingestion
+ inputCost Decimal? @map("input_cost")
+ outputCost Decimal? @map("output_cost")
+ totalCost Decimal? @map("total_cost")
+
+ // Calculated cost
+ calculatedInputCost Decimal? @map("calculated_input_cost")
+ calculatedOutputCost Decimal? @map("calculated_output_cost")
+ calculatedTotalCost Decimal? @map("calculated_total_cost")
+
completionStartTime DateTime? @map("completion_start_time")
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
derivedDatasetItems DatasetItem[]
diff --git a/web/src/__tests__/test-utils.ts b/web/src/__tests__/test-utils.ts
index d9fad967c1..321cd8858b 100644
--- a/web/src/__tests__/test-utils.ts
+++ b/web/src/__tests__/test-utils.ts
@@ -1,8 +1,14 @@
+import { hash } from "bcryptjs";
+
+import { env } from "@/src/env.mjs";
import { getDisplaySecretKey, hashSecretKey } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
-import { hash } from "bcryptjs";
export const pruneDatabase = async () => {
+ if (!env.DATABASE_URL.includes("localhost:5432")) {
+ throw new Error("You cannot prune database unless running on localhost.");
+ }
+
await prisma.score.deleteMany();
await prisma.scoreConfig.deleteMany();
await prisma.observation.deleteMany();
diff --git a/web/src/__tests__/tokenCost.servertest.ts b/web/src/__tests__/tokenCost.servertest.ts
new file mode 100644
index 0000000000..322b2e3b61
--- /dev/null
+++ b/web/src/__tests__/tokenCost.servertest.ts
@@ -0,0 +1,1091 @@
+import { nanoid } from "ai";
+import Decimal from "decimal.js";
+import { v4 as uuidv4 } from "uuid";
+
+import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
+import { ObservationProcessor } from "@/src/server/api/services/EventProcessor";
+import { ModelUsageUnit } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+
+describe("Token Cost Calculation", () => {
+ const modelName = "gpt-test-" + nanoid();
+ const matchPattern = `(?i)^(${modelName})$`;
+ const traceId = uuidv4();
+ const generationId = uuidv4();
+ const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+
+ const tokenModelData = {
+ id: uuidv4(),
+ modelName,
+ matchPattern,
+ inputPrice: 0.01,
+ outputPrice: 0.02,
+ totalPrice: 0.03,
+ unit: ModelUsageUnit.Tokens,
+ };
+
+ const imageModelData = {
+ id: uuidv4(),
+ modelName,
+ matchPattern,
+ inputPrice: 1,
+ outputPrice: 2,
+ totalPrice: 3,
+ unit: ModelUsageUnit.Images,
+ };
+
+ beforeEach(async () => {
+ await pruneDatabase();
+ await Promise.all([
+ prisma.model.create({
+ data: tokenModelData,
+ }),
+ prisma.model.create({
+ data: imageModelData,
+ }),
+ prisma.trace.create({
+ data: {
+ id: traceId,
+ projectId,
+ },
+ }),
+ ]);
+ });
+
+ it("should correctly calculate token costs with provided model prices", async () => {
+ const model = {
+ inputPrice: new Decimal(0.01),
+ outputPrice: new Decimal(0.02),
+ totalPrice: new Decimal(0.03),
+ };
+
+ const tokenCounts = {
+ input: 100,
+ output: 200,
+ total: 300,
+ };
+
+ const userProvidedCosts = {
+ inputCost: null,
+ outputCost: null,
+ totalCost: null,
+ };
+
+ const costs = ObservationProcessor.calculateTokenCosts(
+ model as any,
+ userProvidedCosts,
+ tokenCounts,
+ );
+
+ expect(costs.inputCost?.toNumber()).toBe(1.0); // 100 tokens * 0.01
+ expect(costs.outputCost?.toNumber()).toBe(4.0); // 200 tokens * 0.02
+ expect(costs.totalCost?.toNumber()).toBe(9.0); // 300 tokens * 0.03
+ });
+
+ it("should correctly calculate token costs with user provided costs", async () => {
+ const model = {
+ inputPrice: new Decimal(0.01),
+ outputPrice: new Decimal(0.02),
+ totalPrice: new Decimal(0.03),
+ };
+
+ const tokenCounts = {
+ input: 100,
+ output: 200,
+ total: 300,
+ };
+
+ const userProvidedCosts = {
+ inputCost: new Decimal(2.0),
+ outputCost: new Decimal(3.0),
+ totalCost: new Decimal(5.0),
+ };
+
+ const costs = ObservationProcessor.calculateTokenCosts(
+ model as any,
+ userProvidedCosts,
+ tokenCounts,
+ );
+
+ expect(costs.inputCost?.toNumber()).toBe(2.0); // Overridden by user provided cost
+ expect(costs.outputCost?.toNumber()).toBe(3.0); // Overridden by user provided cost
+ expect(costs.totalCost?.toNumber()).toBe(5.0); // Overridden by user provided cost
+ });
+
+ it("should correctly calculate token costs when only some user provided costs are given", async () => {
+ const model = {
+ inputPrice: new Decimal(0.01),
+ outputPrice: new Decimal(0.02),
+ totalPrice: new Decimal(0.03),
+ };
+
+ const tokenCounts = {
+ input: 100,
+ output: 200,
+ total: undefined,
+ };
+
+ const userProvidedCosts = {
+ inputCost: null,
+ outputCost: new Decimal(3.0),
+ totalCost: null,
+ };
+
+ const costs = ObservationProcessor.calculateTokenCosts(
+ model as any,
+ userProvidedCosts,
+ tokenCounts,
+ );
+
+ expect(costs.inputCost?.toNumber()).toBe(1.0); // Calculated based on model price
+ expect(costs.outputCost?.toNumber()).toBe(3.0); // Overridden by user provided cost
+ expect(costs.totalCost?.toNumber()).toBe(4.0); // Sum of input and output costs
+ });
+
+ it("should return empty costs if no model is provided", async () => {
+ const tokenCounts = {
+ input: 100,
+ output: 200,
+ total: 300,
+ };
+
+ const userProvidedCosts = {
+ inputCost: null,
+ outputCost: null,
+ totalCost: null,
+ };
+
+ const costs = ObservationProcessor.calculateTokenCosts(
+ null,
+ userProvidedCosts,
+ tokenCounts,
+ );
+
+ expect(costs.inputCost?.toNumber()).toBeUndefined();
+ expect(costs.outputCost?.toNumber()).toBeUndefined();
+ expect(costs.totalCost?.toNumber()).toBeUndefined();
+ });
+
+ it("should handle zero token counts correctly", async () => {
+ const model = {
+ inputPrice: new Decimal(0.01),
+ outputPrice: new Decimal(0.02),
+ totalPrice: new Decimal(0.03),
+ };
+
+ const tokenCounts = {
+ input: 0,
+ output: 0,
+ total: 0,
+ };
+
+ const userProvidedCosts = {
+ inputCost: null,
+ outputCost: null,
+ totalCost: null,
+ };
+
+ const costs = ObservationProcessor.calculateTokenCosts(
+ model as any,
+ userProvidedCosts,
+ tokenCounts,
+ );
+
+ expect(costs.inputCost?.toNumber()).toBe(0); // 0 tokens * 0.01
+ expect(costs.outputCost?.toNumber()).toBe(0); // 0 tokens * 0.02
+ expect(costs.totalCost?.toNumber()).toBe(0); // 0 tokens * 0.03
+ });
+
+ it("should handle missing token counts correctly", async () => {
+ const model = {
+ inputPrice: new Decimal(0.01),
+ outputPrice: new Decimal(0.02),
+ totalPrice: new Decimal(0.03),
+ };
+
+ const tokenCounts = {
+ input: undefined,
+ output: undefined,
+ total: undefined,
+ };
+
+ const userProvidedCosts = {
+ inputCost: null,
+ outputCost: null,
+ totalCost: null,
+ };
+
+ const costs = ObservationProcessor.calculateTokenCosts(
+ model as any,
+ userProvidedCosts,
+ tokenCounts,
+ );
+
+ expect(costs.inputCost?.toNumber()).toBeUndefined();
+ expect(costs.outputCost?.toNumber()).toBeUndefined();
+ expect(costs.totalCost?.toNumber()).toBeUndefined();
+ });
+
+ it("should handle fractional token counts correctly", async () => {
+ const model = {
+ inputPrice: new Decimal(0.01),
+ outputPrice: new Decimal(0.02),
+ totalPrice: new Decimal(0.03),
+ };
+
+ const tokenCounts = {
+ input: 150.5,
+ output: 250.25,
+ total: 400.75,
+ };
+
+ const userProvidedCosts = {
+ inputCost: null,
+ outputCost: null,
+ totalCost: null,
+ };
+
+ const costs = ObservationProcessor.calculateTokenCosts(
+ model as any,
+ userProvidedCosts,
+ tokenCounts,
+ );
+
+ expect(costs.inputCost?.toNumber()).toBeCloseTo(1.505); // 150.5 tokens * 0.01
+ expect(costs.outputCost?.toNumber()).toBeCloseTo(5.005); // 250.25 tokens * 0.02
+ expect(costs.totalCost?.toNumber()).toBeCloseTo(12.0225); // 400.75 tokens * 0.03
+ });
+
+ it("should handle large token counts correctly", async () => {
+ const model = {
+ inputPrice: new Decimal(0.01),
+ outputPrice: new Decimal(0.02),
+ totalPrice: new Decimal(0.03),
+ };
+
+ const tokenCounts = {
+ input: 1e6,
+ output: 2e6,
+ total: 3e6,
+ };
+
+ const userProvidedCosts = {
+ inputCost: null,
+ outputCost: null,
+ totalCost: null,
+ };
+
+ const costs = ObservationProcessor.calculateTokenCosts(
+ model as any,
+ userProvidedCosts,
+ tokenCounts,
+ );
+
+ expect(costs.inputCost?.toNumber()).toBe(10000); // 1e6 tokens * 0.01
+ expect(costs.outputCost?.toNumber()).toBe(40000); // 2e6 tokens * 0.02
+ expect(costs.totalCost?.toNumber()).toBe(90000); // 3e6 tokens * 0.03
+ });
+
+ it("should correctly match model prices from the database", async () => {
+ const generationUsage = {
+ model: modelName,
+ usage: {
+ input: 100,
+ output: 200,
+ total: 300,
+ unit: ModelUsageUnit.Tokens,
+ },
+ };
+ const events = [
+ {
+ id: uuidv4(),
+ type: "generation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ ...generationUsage,
+ },
+ },
+ ];
+
+ const response = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: events,
+ });
+
+ expect(response.status).toBe(207);
+ const generation = await prisma.observation.findFirst({
+ where: {
+ id: generationId,
+ },
+ });
+
+ expect(generation).toBeDefined();
+ expect(generation?.type).toBe("GENERATION");
+
+ // Model name should be matched
+ expect(generation?.internalModel).toBe(tokenModelData.modelName);
+ expect(generation?.unit).toEqual(tokenModelData.unit);
+ expect(generation?.internalModelId).toBe(tokenModelData.id);
+
+ // No user provided cost
+ expect(generation?.inputCost).toBeNull();
+ expect(generation?.outputCost).toBeNull();
+ expect(generation?.totalCost).toBeNull();
+
+ // Calculated cost
+ expect(generation?.calculatedInputCost?.toNumber()).toBe(
+ generationUsage.usage.input * tokenModelData.inputPrice,
+ );
+ expect(generation?.calculatedOutputCost?.toNumber()).toBe(
+ generationUsage.usage.output * tokenModelData.outputPrice,
+ );
+ expect(generation?.calculatedTotalCost?.toNumber()).toBe(
+ generationUsage.usage.total * tokenModelData.totalPrice,
+ );
+ expect(generation?.promptTokens).toBe(generationUsage.usage.input);
+ expect(generation?.completionTokens).toBe(generationUsage.usage.output);
+ expect(generation?.totalTokens).toBe(generationUsage.usage.total);
+ });
+
+ it("should overwrite costs for a generation without previous user provided costs", async () => {
+ const generationUsage1 = {
+ model: modelName,
+ usage: {
+ input: 1,
+ output: 2,
+ total: 3,
+ unit: ModelUsageUnit.Tokens,
+ },
+ };
+
+ const generationUsage2 = {
+ model: modelName,
+ usage: {
+ input: 100,
+ output: 200,
+ total: 300,
+ unit: ModelUsageUnit.Tokens,
+ },
+ };
+
+ const events = [
+ {
+ id: uuidv4(),
+ type: "generation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ ...generationUsage1,
+ },
+ },
+ {
+ id: uuidv4(),
+ type: "generation-update",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ ...generationUsage2,
+ },
+ },
+ ];
+
+ const response = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: events,
+ });
+
+ expect(response.status).toBe(207);
+ const generation = await prisma.observation.findFirst({
+ where: {
+ id: generationId,
+ },
+ });
+
+ expect(generation).toBeDefined();
+ expect(generation?.type).toBe("GENERATION");
+
+ // Model name should be matched
+ expect(generation?.internalModel).toBe(tokenModelData.modelName);
+ expect(generation?.unit).toEqual(tokenModelData.unit);
+ expect(generation?.internalModelId).toBe(tokenModelData.id);
+
+ // No user provided cost
+ expect(generation?.inputCost).toBeNull();
+ expect(generation?.outputCost).toBeNull();
+ expect(generation?.totalCost).toBeNull();
+
+ // Calculated cost
+ expect(generation?.calculatedInputCost?.toNumber()).toBe(
+ generationUsage2.usage.input * tokenModelData.inputPrice,
+ );
+ expect(generation?.calculatedOutputCost?.toNumber()).toBe(
+ generationUsage2.usage.output * tokenModelData.outputPrice,
+ );
+ expect(generation?.calculatedTotalCost?.toNumber()).toBe(
+ generationUsage2.usage.total * tokenModelData.totalPrice,
+ );
+ expect(generation?.promptTokens).toBe(generationUsage2.usage.input);
+ expect(generation?.completionTokens).toBe(generationUsage2.usage.output);
+ expect(generation?.totalTokens).toBe(generationUsage2.usage.total);
+ });
+
+ it("should use the matched model of the previous generation call to calculate costs", async () => {
+ const generationUsage1 = {
+ model: modelName,
+ usage: {
+ input: 1,
+ output: 2,
+ total: 3,
+ unit: ModelUsageUnit.Tokens,
+ },
+ };
+
+ const generationUsage2 = {
+ model: undefined, // No model provided
+ usage: {
+ input: 100,
+ output: 200,
+ total: 300,
+ unit: ModelUsageUnit.Tokens,
+ },
+ };
+
+ const events = [
+ {
+ id: uuidv4(),
+ type: "generation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ ...generationUsage1,
+ },
+ },
+ {
+ id: uuidv4(),
+ type: "generation-update",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ ...generationUsage2,
+ },
+ },
+ ];
+
+ const response = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: events,
+ });
+
+ expect(response.status).toBe(207);
+ const generation = await prisma.observation.findFirst({
+ where: {
+ id: generationId,
+ },
+ });
+
+ expect(generation).toBeDefined();
+ expect(generation?.type).toBe("GENERATION");
+
+ // Model name should be matched
+ expect(generation?.internalModel).toBe(tokenModelData.modelName);
+ expect(generation?.unit).toEqual(tokenModelData.unit);
+ expect(generation?.internalModelId).toBe(tokenModelData.id);
+
+ // No user provided cost
+ expect(generation?.inputCost).toBeNull();
+ expect(generation?.outputCost).toBeNull();
+ expect(generation?.totalCost).toBeNull();
+
+ // Calculated cost
+ expect(generation?.calculatedInputCost?.toNumber()).toBe(
+ generationUsage2.usage.input * tokenModelData.inputPrice,
+ );
+ expect(generation?.calculatedOutputCost?.toNumber()).toBe(
+ generationUsage2.usage.output * tokenModelData.outputPrice,
+ );
+ expect(generation?.calculatedTotalCost?.toNumber()).toBe(
+ generationUsage2.usage.total * tokenModelData.totalPrice,
+ );
+ expect(generation?.promptTokens).toBe(generationUsage2.usage.input);
+ expect(generation?.completionTokens).toBe(generationUsage2.usage.output);
+ expect(generation?.totalTokens).toBe(generationUsage2.usage.total);
+ });
+
+ it("should overwrite costs if new costs are user provided", async () => {
+ const generationUsage1 = {
+ model: modelName,
+ usage: {
+ input: 1,
+ output: 2,
+ total: 3,
+ unit: ModelUsageUnit.Tokens,
+ },
+ };
+
+ const generationUsage2 = {
+ model: modelName,
+ usage: {
+ input: 100,
+ output: 200,
+ total: 300,
+ inputCost: 1234,
+ outputCost: 23523,
+ totalCost: 5354,
+ unit: ModelUsageUnit.Tokens,
+ },
+ };
+
+ const events = [
+ {
+ id: uuidv4(),
+ type: "generation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ ...generationUsage1,
+ },
+ },
+ {
+ id: uuidv4(),
+ type: "generation-update",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ ...generationUsage2,
+ },
+ },
+ ];
+
+ const response = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: events,
+ });
+
+ expect(response.status).toBe(207);
+ const generation = await prisma.observation.findFirst({
+ where: {
+ id: generationId,
+ },
+ });
+
+ expect(generation).toBeDefined();
+ expect(generation?.type).toBe("GENERATION");
+
+ // Model name should be matched
+ expect(generation?.internalModel).toBe(tokenModelData.modelName);
+ expect(generation?.unit).toEqual(tokenModelData.unit);
+ expect(generation?.internalModelId).toBe(tokenModelData.id);
+
+ // User provided cost
+ expect(generation?.inputCost?.toNumber()).toBe(
+ generationUsage2.usage.inputCost,
+ );
+ expect(generation?.outputCost?.toNumber()).toBe(
+ generationUsage2.usage.outputCost,
+ );
+ expect(generation?.totalCost?.toNumber()).toBe(
+ generationUsage2.usage.totalCost,
+ );
+
+ // Calculated cost
+ expect(generation?.calculatedInputCost?.toNumber()).toBe(
+ generationUsage2.usage.inputCost,
+ );
+ expect(generation?.calculatedOutputCost?.toNumber()).toBe(
+ generationUsage2.usage.outputCost,
+ );
+ expect(generation?.calculatedTotalCost?.toNumber()).toBe(
+ generationUsage2.usage.totalCost,
+ );
+ expect(generation?.promptTokens).toBe(generationUsage2.usage.input);
+ expect(generation?.completionTokens).toBe(generationUsage2.usage.output);
+ expect(generation?.totalTokens).toBe(generationUsage2.usage.total);
+ });
+
+ it("should overwrite costs if new costs are user provided and zero", async () => {
+ const generationUsage1 = {
+ model: modelName,
+ usage: {
+ input: 1,
+ output: 2,
+ total: 3,
+ unit: ModelUsageUnit.Tokens,
+ },
+ };
+
+ const generationUsage2 = {
+ model: modelName,
+ usage: {
+ input: 100,
+ output: 200,
+ total: 300,
+ inputCost: 0,
+ outputCost: 0,
+ totalCost: 0,
+ unit: ModelUsageUnit.Tokens,
+ },
+ };
+
+ const events = [
+ {
+ id: uuidv4(),
+ type: "generation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ ...generationUsage1,
+ },
+ },
+ {
+ id: uuidv4(),
+ type: "generation-update",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ ...generationUsage2,
+ },
+ },
+ ];
+
+ const response = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: events,
+ });
+
+ expect(response.status).toBe(207);
+ const generation = await prisma.observation.findFirst({
+ where: {
+ id: generationId,
+ },
+ });
+
+ expect(generation).toBeDefined();
+ expect(generation?.type).toBe("GENERATION");
+
+ // Model name should be matched
+ expect(generation?.internalModel).toBe(tokenModelData.modelName);
+ expect(generation?.unit).toEqual(tokenModelData.unit);
+ expect(generation?.internalModelId).toBe(tokenModelData.id);
+
+ // User provided cost
+ expect(generation?.inputCost?.toNumber()).toBe(
+ generationUsage2.usage.inputCost,
+ );
+ expect(generation?.outputCost?.toNumber()).toBe(
+ generationUsage2.usage.outputCost,
+ );
+ expect(generation?.totalCost?.toNumber()).toBe(
+ generationUsage2.usage.totalCost,
+ );
+
+ // Calculated cost
+ expect(generation?.calculatedInputCost?.toNumber()).toBe(
+ generationUsage2.usage.inputCost,
+ );
+ expect(generation?.calculatedOutputCost?.toNumber()).toBe(
+ generationUsage2.usage.outputCost,
+ );
+ expect(generation?.calculatedTotalCost?.toNumber()).toBe(
+ generationUsage2.usage.totalCost,
+ );
+ expect(generation?.promptTokens).toBe(generationUsage2.usage.input);
+ expect(generation?.completionTokens).toBe(generationUsage2.usage.output);
+ expect(generation?.totalTokens).toBe(generationUsage2.usage.total);
+ });
+
+ it("should not overwrite costs if previous cost were user provided", async () => {
+ const generationUsage1 = {
+ model: modelName,
+ usage: {
+ input: 1,
+ output: 2,
+ total: 3,
+ inputCost: 1234,
+ outputCost: 23523,
+ totalCost: 5354,
+ unit: ModelUsageUnit.Tokens,
+ },
+ };
+
+ const generationUsage2 = {
+ model: modelName,
+ usage: {
+ input: 100,
+ output: 200,
+ total: 300,
+ unit: ModelUsageUnit.Tokens,
+ },
+ };
+
+ const events = [
+ {
+ id: uuidv4(),
+ type: "generation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ ...generationUsage1,
+ },
+ },
+ {
+ id: uuidv4(),
+ type: "generation-update",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ ...generationUsage2,
+ },
+ },
+ ];
+
+ const response = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: events,
+ });
+
+ expect(response.status).toBe(207);
+ const generation = await prisma.observation.findFirst({
+ where: {
+ id: generationId,
+ },
+ });
+
+ expect(generation).toBeDefined();
+ expect(generation?.type).toBe("GENERATION");
+
+ // Model name should be matched
+ expect(generation?.internalModel).toBe(tokenModelData.modelName);
+ expect(generation?.unit).toEqual(tokenModelData.unit);
+ expect(generation?.internalModelId).toBe(tokenModelData.id);
+
+ // User provided cost
+ expect(generation?.inputCost?.toNumber()).toBe(
+ generationUsage1.usage.inputCost,
+ );
+ expect(generation?.outputCost?.toNumber()).toBe(
+ generationUsage1.usage.outputCost,
+ );
+ expect(generation?.totalCost?.toNumber()).toBe(
+ generationUsage1.usage.totalCost,
+ );
+
+ // Calculated cost
+ expect(generation?.calculatedInputCost?.toNumber()).toBe(
+ generationUsage1.usage.inputCost,
+ );
+ expect(generation?.calculatedOutputCost?.toNumber()).toBe(
+ generationUsage1.usage.outputCost,
+ );
+ expect(generation?.calculatedTotalCost?.toNumber()).toBe(
+ generationUsage1.usage.totalCost,
+ );
+ expect(generation?.promptTokens).toBe(generationUsage2.usage.input);
+ expect(generation?.completionTokens).toBe(generationUsage2.usage.output);
+ expect(generation?.totalTokens).toBe(generationUsage2.usage.total);
+ });
+
+ it("should not calculate anything if no costs are provided and no model is matched", async () => {
+ const generationUsage1 = {
+ model: undefined, // No model provided
+ usage: {
+ input: 1,
+ output: 2,
+ total: 3,
+ unit: ModelUsageUnit.Tokens,
+ },
+ };
+
+ const generationUsage2 = {
+ model: undefined, // No model provided
+ usage: {
+ input: 100,
+ output: 200,
+ total: 300,
+ unit: ModelUsageUnit.Tokens,
+ },
+ };
+
+ const events = [
+ {
+ id: uuidv4(),
+ type: "generation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ ...generationUsage1,
+ },
+ },
+ {
+ id: uuidv4(),
+ type: "generation-update",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ ...generationUsage2,
+ },
+ },
+ ];
+
+ const response = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: events,
+ });
+
+ expect(response.status).toBe(207);
+ const generation = await prisma.observation.findFirst({
+ where: {
+ id: generationId,
+ },
+ });
+
+ expect(generation).toBeDefined();
+ expect(generation?.type).toBe("GENERATION");
+
+ // Model name should not be matched
+ expect(generation?.internalModel).toBeNull();
+ expect(generation?.unit).toEqual(tokenModelData.unit);
+ expect(generation?.internalModelId).toBeNull();
+
+ // No user provided cost
+ expect(generation?.inputCost).toBeNull();
+ expect(generation?.outputCost).toBeNull();
+ expect(generation?.totalCost).toBeNull();
+
+ // No calculated cost
+ expect(generation?.calculatedInputCost).toBeNull();
+ expect(generation?.calculatedOutputCost).toBeNull();
+ expect(generation?.calculatedTotalCost).toBeNull();
+
+ expect(generation?.promptTokens).toBe(generationUsage2.usage.input);
+ expect(generation?.completionTokens).toBe(generationUsage2.usage.output);
+ expect(generation?.totalTokens).toBe(generationUsage2.usage.total);
+ });
+
+ it("should handle different model usage units correctly", async () => {
+ const generationUsage1 = {
+ model: modelName,
+ usage: {
+ input: 1,
+ output: 2,
+ total: 3,
+ unit: ModelUsageUnit.Tokens,
+ },
+ };
+
+ const generationUsage2 = {
+ model: modelName,
+ usage: {
+ input: 100,
+ output: 200,
+ total: 300,
+ unit: ModelUsageUnit.Images, // Different unit
+ },
+ };
+
+ const events = [
+ {
+ id: uuidv4(),
+ type: "generation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ ...generationUsage1,
+ },
+ },
+ {
+ id: uuidv4(),
+ type: "generation-update",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ ...generationUsage2,
+ },
+ },
+ ];
+
+ const response = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: events,
+ });
+
+ expect(response.status).toBe(207);
+ const generation = await prisma.observation.findFirst({
+ where: {
+ id: generationId,
+ },
+ });
+
+ expect(generation).toBeDefined();
+ expect(generation?.type).toBe("GENERATION");
+
+ // Model name should be matched
+ expect(generation?.internalModel).toBe(imageModelData.modelName);
+ expect(generation?.unit).toEqual(imageModelData.unit);
+ expect(generation?.internalModelId).toBe(imageModelData.id);
+
+ // No user provided cost
+ expect(generation?.inputCost).toBeNull();
+ expect(generation?.outputCost).toBeNull();
+ expect(generation?.totalCost).toBeNull();
+
+ // Calculated cost
+ expect(generation?.calculatedInputCost?.toNumber()).toBe(
+ generationUsage2.usage.input * imageModelData.inputPrice,
+ );
+ expect(generation?.calculatedOutputCost?.toNumber()).toBe(
+ generationUsage2.usage.output * imageModelData.outputPrice,
+ );
+ expect(generation?.calculatedTotalCost?.toNumber()).toBe(
+ generationUsage2.usage.total * imageModelData.totalPrice,
+ );
+ expect(generation?.promptTokens).toBe(generationUsage2.usage.input);
+ expect(generation?.completionTokens).toBe(generationUsage2.usage.output);
+ expect(generation?.totalTokens).toBe(generationUsage2.usage.total);
+ });
+
+ it("should take the latest user provided model for matching", async () => {
+ // Create a new model with the same name but different prices
+ const newModelData = {
+ id: uuidv4(),
+ modelName,
+ matchPattern,
+ startDate: new Date().toISOString(),
+ inputPrice: tokenModelData.inputPrice * 2,
+ outputPrice: tokenModelData.outputPrice * 2,
+ totalPrice: tokenModelData.totalPrice * 2,
+ unit: ModelUsageUnit.Tokens,
+ };
+
+ await prisma.model.create({
+ data: newModelData,
+ });
+
+ const generationUsage = {
+ model: modelName,
+ usage: {
+ input: 100,
+ output: 200,
+ total: 300,
+ unit: ModelUsageUnit.Tokens,
+ },
+ };
+
+ const events = [
+ {
+ id: uuidv4(),
+ type: "generation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ ...generationUsage,
+ },
+ },
+ ];
+
+ const response = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: events,
+ });
+
+ expect(response.status).toBe(207);
+ const generation = await prisma.observation.findFirst({
+ where: {
+ id: generationId,
+ },
+ });
+
+ expect(generation).toBeDefined();
+ expect(generation?.type).toBe("GENERATION");
+
+ // Model name should be matched
+ expect(generation?.internalModel).toBe(newModelData.modelName);
+ expect(generation?.unit).toEqual(newModelData.unit);
+ expect(generation?.internalModelId).toBe(newModelData.id);
+
+ // No user provided cost
+ expect(generation?.inputCost).toBeNull();
+ expect(generation?.outputCost).toBeNull();
+ expect(generation?.totalCost).toBeNull();
+
+ // Calculated cost
+ expect(generation?.calculatedInputCost?.toNumber()).toBe(
+ generationUsage.usage.input * newModelData.inputPrice,
+ );
+ expect(generation?.calculatedOutputCost?.toNumber()).toBe(
+ generationUsage.usage.output * newModelData.outputPrice,
+ );
+ expect(generation?.calculatedTotalCost?.toNumber()).toBe(
+ generationUsage.usage.total * newModelData.totalPrice,
+ );
+ expect(generation?.promptTokens).toBe(generationUsage.usage.input);
+ expect(generation?.completionTokens).toBe(generationUsage.usage.output);
+ expect(generation?.totalTokens).toBe(generationUsage.usage.total);
+ });
+
+ it("should use the tokens of the previous call without model if model comes with following call", async () => {
+ const generationUsage1 = {
+ model: undefined, // No model provided
+ usage: {
+ input: 1,
+ output: 2,
+ total: 3,
+ unit: ModelUsageUnit.Tokens,
+ },
+ };
+
+ const generationUsage2 = {
+ model: modelName,
+ };
+
+ const events = [
+ {
+ id: uuidv4(),
+ type: "generation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ ...generationUsage1,
+ },
+ },
+ {
+ id: uuidv4(),
+ type: "generation-update",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ ...generationUsage2,
+ },
+ },
+ ];
+
+ const response = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: events,
+ });
+
+ expect(response.status).toBe(207);
+ const generation = await prisma.observation.findFirst({
+ where: {
+ id: generationId,
+ },
+ });
+
+ expect(generation).toBeDefined();
+ expect(generation?.type).toBe("GENERATION");
+
+ // Model name should be matched
+ expect(generation?.internalModel).toBe(tokenModelData.modelName);
+ expect(generation?.unit).toEqual(tokenModelData.unit);
+ expect(generation?.internalModelId).toBe(tokenModelData.id);
+
+ // No user provided cost
+ expect(generation?.inputCost).toBeNull();
+ expect(generation?.outputCost).toBeNull();
+ expect(generation?.totalCost).toBeNull();
+
+ // Calculated cost
+ expect(generation?.calculatedInputCost?.toNumber()).toBe(
+ generationUsage1.usage.input * tokenModelData.inputPrice,
+ );
+ expect(generation?.calculatedOutputCost?.toNumber()).toBe(
+ generationUsage1.usage.output * tokenModelData.outputPrice,
+ );
+ expect(generation?.calculatedTotalCost?.toNumber()).toBe(
+ generationUsage1.usage.total * tokenModelData.totalPrice,
+ );
+ expect(generation?.promptTokens).toBe(generationUsage1.usage.input);
+ expect(generation?.completionTokens).toBe(generationUsage1.usage.output);
+ expect(generation?.totalTokens).toBe(generationUsage1.usage.total);
+ });
+});
diff --git a/web/src/server/api/services/EventProcessor.ts b/web/src/server/api/services/EventProcessor.ts
index e1fd1aad12..1481677339 100644
--- a/web/src/server/api/services/EventProcessor.ts
+++ b/web/src/server/api/services/EventProcessor.ts
@@ -29,6 +29,7 @@ import { jsonSchema } from "@langfuse/shared";
import { sendToBetterstack } from "@/src/features/betterstack/server/betterstack-webhook";
import { ForbiddenError } from "@langfuse/shared";
import { instrument } from "@/src/utils/instrumentation";
+import Decimal from "decimal.js";
export interface EventProcessor {
process(
@@ -88,7 +89,7 @@ export async function findModel(p: {
}::timestamp with time zone at time zone 'UTC')
ORDER BY
project_id ASC,
- start_date DESC
+ start_date DESC NULLS LAST
LIMIT 1
`;
@@ -182,6 +183,7 @@ export class ObservationProcessor implements EventProcessor {
).id
: this.event.body.traceId;
+ // Token counts
const [newInputCount, newOutputCount] =
"usage" in this.event.body
? this.calculateTokenCounts(
@@ -191,6 +193,41 @@ export class ObservationProcessor implements EventProcessor {
)
: [undefined, undefined];
+ const newTotalCount =
+ "usage" in this.event.body
+ ? this.event.body.usage?.total ??
+ (newInputCount != null || newOutputCount != null
+ ? (newInputCount ?? 0) + (newOutputCount ?? 0)
+ : undefined)
+ : undefined;
+
+ const userProvidedTokenCosts = {
+ 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,
+ 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,
+ 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,
+ };
+
+ const tokenCounts = {
+ input: newInputCount ?? existingObservation?.promptTokens,
+ output: newOutputCount ?? existingObservation?.completionTokens,
+ total: newTotalCount || existingObservation?.totalTokens,
+ };
+
+ const calculatedCosts = ObservationProcessor.calculateTokenCosts(
+ internalModel,
+ userProvidedTokenCosts,
+ tokenCounts,
+ );
+
// merge metadata from existingObservation.metadata and metadata
const mergedMetadata = mergeJson(
existingObservation?.metadata
@@ -250,11 +287,7 @@ export class ObservationProcessor implements EventProcessor {
output: this.event.body.output ?? undefined,
promptTokens: newInputCount,
completionTokens: newOutputCount,
- totalTokens:
- "usage" in this.event.body
- ? this.event.body.usage?.total ??
- (newInputCount ?? 0) + (newOutputCount ?? 0)
- : undefined,
+ totalTokens: newTotalCount,
unit:
"usage" in this.event.body
? this.event.body.usage?.unit ?? internalModel?.unit
@@ -280,6 +313,10 @@ export class ObservationProcessor implements EventProcessor {
"usage" in this.event.body
? this.event.body.usage?.totalCost
: undefined,
+ calculatedInputCost: calculatedCosts?.inputCost,
+ calculatedOutputCost: calculatedCosts?.outputCost,
+ calculatedTotalCost: calculatedCosts?.totalCost,
+ internalModelId: internalModel?.id,
},
update: {
name: this.event.body.name ?? undefined,
@@ -305,11 +342,7 @@ export class ObservationProcessor implements EventProcessor {
output: this.event.body.output ?? undefined,
promptTokens: newInputCount,
completionTokens: newOutputCount,
- totalTokens:
- "usage" in this.event.body
- ? this.event.body.usage?.total ??
- (newInputCount ?? 0) + (newOutputCount ?? 0)
- : undefined,
+ totalTokens: newTotalCount,
unit:
"usage" in this.event.body
? this.event.body.usage?.unit ?? internalModel?.unit
@@ -334,6 +367,10 @@ export class ObservationProcessor implements EventProcessor {
"usage" in this.event.body
? this.event.body.usage?.totalCost
: undefined,
+ calculatedInputCost: calculatedCosts?.inputCost,
+ calculatedOutputCost: calculatedCosts?.outputCost,
+ calculatedTotalCost: calculatedCosts?.totalCost,
+ internalModelId: internalModel?.id,
},
};
}
@@ -372,6 +409,50 @@ export class ObservationProcessor implements EventProcessor {
});
}
+ static calculateTokenCosts(
+ model: Model | null | undefined,
+ userProvidedCosts: {
+ inputCost?: Decimal | null;
+ outputCost?: Decimal | null;
+ totalCost?: Decimal | null;
+ },
+ tokenCounts: { input?: number; output?: number; total?: number },
+ ): {
+ inputCost?: Decimal;
+ outputCost?: Decimal;
+ totalCost?: Decimal;
+ } {
+ if (!model) return {};
+
+ const finalInputCost =
+ userProvidedCosts.inputCost ??
+ (tokenCounts.input !== undefined && model.inputPrice
+ ? model.inputPrice.mul(tokenCounts.input)
+ : undefined);
+
+ const finalOutputCost =
+ userProvidedCosts.outputCost ??
+ (tokenCounts.output !== undefined && model.outputPrice
+ ? model.outputPrice.mul(tokenCounts.output)
+ : finalInputCost
+ ? new Decimal(0)
+ : undefined);
+
+ const finalTotalCost =
+ userProvidedCosts.totalCost ??
+ (tokenCounts.total !== undefined && model.totalPrice
+ ? model.totalPrice.mul(tokenCounts.total)
+ : finalInputCost ?? finalOutputCost
+ ? new Decimal(finalInputCost ?? 0).add(finalOutputCost ?? 0)
+ : undefined);
+
+ return {
+ inputCost: finalInputCost,
+ outputCost: finalOutputCost,
+ totalCost: finalTotalCost,
+ };
+ }
+
async process(apiScope: ApiAccessScope): Promise<Observation> {
if (apiScope.accessLevel !== "all")
throw new ForbiddenError("Access denied for observation creation");