Skip to content

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

fix(tokenCost): carryover user provided cost even if no model match (#2441)

Hassieb Pakzad23efeb69cdea
diff --git a/web/src/__tests__/tokenCost.servertest.ts b/web/src/__tests__/tokenCost.servertest.ts
index 322b2e3b61..67a808adda 100644
--- a/web/src/__tests__/tokenCost.servertest.ts
+++ b/web/src/__tests__/tokenCost.servertest.ts
@@ -22,6 +22,12 @@ describe("Token Cost Calculation", () => {
outputPrice: 0.02,
totalPrice: 0.03,
unit: ModelUsageUnit.Tokens,
+ tokenizerId: "openai",
+ tokenizerConfig: {
+ tokensPerName: 1,
+ tokenizerModel: "gpt-4o",
+ tokensPerMessage: 3,
+ },
};
const imageModelData = {
@@ -32,6 +38,12 @@ describe("Token Cost Calculation", () => {
outputPrice: 2,
totalPrice: 3,
unit: ModelUsageUnit.Images,
+ tokenizerId: "openai",
+ tokenizerConfig: {
+ tokensPerName: 1,
+ tokenizerModel: "gpt-4o",
+ tokensPerMessage: 3,
+ },
};
beforeEach(async () => {
@@ -428,6 +440,84 @@ describe("Token Cost Calculation", () => {
expect(generation?.totalTokens).toBe(generationUsage2.usage.total);
});
+ it("should correctly handle first manual tokenization and then provided tokens", async () => {
+ const generationUsage1 = {
+ model: modelName,
+ input: "hello world",
+ output: "",
+ usage: null,
+ };
+
+ const generationUsage2 = {
+ output: "whassup",
+ 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,
@@ -509,6 +599,69 @@ describe("Token Cost Calculation", () => {
expect(generation?.totalTokens).toBe(generationUsage2.usage.total);
});
+ it("should discard model if following event has different unit", async () => {
+ const generationUsage1 = {
+ model: modelName,
+ };
+
+ const generationUsage2 = {
+ model: modelName,
+ usage: {
+ totalCost: 10,
+ unit: ModelUsageUnit.Characters, // Different unit for which model is not matched
+ },
+ };
+
+ 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(ModelUsageUnit.Characters);
+
+ // No user provided cost
+ expect(generation?.inputCost).toBeNull();
+ expect(generation?.outputCost).toBeNull();
+ expect(generation?.totalCost?.toNumber()).toBe(10);
+
+ // Calculated cost
+ expect(generation?.calculatedInputCost).toBeNull();
+ expect(generation?.calculatedOutputCost).toBeNull();
+ expect(generation?.calculatedTotalCost?.toNumber()).toBe(10);
+ });
+
it("should overwrite costs if new costs are user provided", async () => {
const generationUsage1 = {
model: modelName,
diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.ts
index ff1552b348..3a250c806b 100644
--- a/web/src/pages/api/public/ingestion.ts
+++ b/web/src/pages/api/public/ingestion.ts
@@ -285,7 +285,7 @@ const handleSingleEvent = async (
restEvent = rest;
}
console.log(
- `handling single event ${event.id} ${JSON.stringify({ body: restEvent })}`,
+ `handling single event ${event.id} of type ${event.type}: ${JSON.stringify({ body: restEvent })}`,
);
const cleanedEvent = ingestionEvent.parse(cleanEvent(event));
diff --git a/web/src/server/api/services/EventProcessor.ts b/web/src/server/api/services/EventProcessor.ts
index 1481677339..0a3e0272bc 100644
--- a/web/src/server/api/services/EventProcessor.ts
+++ b/web/src/server/api/services/EventProcessor.ts
@@ -422,17 +422,15 @@ export class ObservationProcessor implements EventProcessor {
outputCost?: Decimal;
totalCost?: Decimal;
} {
- if (!model) return {};
-
const finalInputCost =
userProvidedCosts.inputCost ??
- (tokenCounts.input !== undefined && model.inputPrice
+ (tokenCounts.input !== undefined && model?.inputPrice
? model.inputPrice.mul(tokenCounts.input)
: undefined);
const finalOutputCost =
userProvidedCosts.outputCost ??
- (tokenCounts.output !== undefined && model.outputPrice
+ (tokenCounts.output !== undefined && model?.outputPrice
? model.outputPrice.mul(tokenCounts.output)
: finalInputCost
? new Decimal(0)
@@ -440,7 +438,7 @@ export class ObservationProcessor implements EventProcessor {
const finalTotalCost =
userProvidedCosts.totalCost ??
- (tokenCounts.total !== undefined && model.totalPrice
+ (tokenCounts.total !== undefined && model?.totalPrice
? model.totalPrice.mul(tokenCounts.total)
: finalInputCost ?? finalOutputCost
? new Decimal(finalInputCost ?? 0).add(finalOutputCost ?? 0)