Skip to content

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

perf(worker): skip tokenization when cost details are provided (#15638)

Steffen Schmitz37aed899f743
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index f1c05433b4..d9fee0aa02 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -1229,12 +1229,18 @@ export class IngestionService {
internalModel,
);
- // Match pricing tier based on usage_details
+ // Match pricing tier based on usage_details. Skip when usage is empty
+ // (e.g. tokenization skipped because costs were provided, or ERROR-level
+ // generations): matching {} would stamp a tier chosen against a fabricated
+ // all-zero usage vector instead of leaving the tier unset.
let modelPrices: Array<{ usageType: string; price: Decimal }> = [];
let usage_pricing_tier_id: string | null = null;
let usage_pricing_tier_name: string | null = null;
- if (pricingTiers.length > 0 && final_usage_details.usage_details) {
+ if (
+ pricingTiers.length > 0 &&
+ Object.keys(final_usage_details.usage_details ?? {}).length > 0
+ ) {
const matchedTier = matchPricingTier(
pricingTiers,
final_usage_details.usage_details,
@@ -1283,6 +1289,7 @@ export class IngestionService {
ObservationRecordInsertType,
| "project_id"
| "provided_usage_details"
+ | "provided_cost_details"
| "level"
| "input"
| "output"
@@ -1299,10 +1306,19 @@ export class IngestionService {
observationRecord.provided_usage_details,
);
+ // Provided costs are authoritative: calculateUsageCosts ignores computed
+ // usage once any cost point is provided, so tokenised counts could never
+ // affect costs — leave usage_details blank instead of paying for
+ // tokenisation.
+ const hasProvidedCostDetails = Object.values(
+ observationRecord.provided_cost_details ?? {},
+ ).some((value) => value != null);
+
if (
- // Manual tokenisation when no user provided usage and generation has not status ERROR
+ // Manual tokenisation when no user provided usage or cost and generation has not status ERROR
model &&
Object.keys(providedUsageDetails).length === 0 &&
+ !hasProvidedCostDetails &&
observationRecord.level !== ObservationLevel.ERROR
) {
try {
diff --git a/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts b/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts
index 17ffdb4ba3..59b038e21a 100644
--- a/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts
+++ b/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts
@@ -1328,6 +1328,62 @@ describe("Token Cost Calculation", () => {
expect(generation.usage_details.total).toBeUndefined();
});
+ it("should skip tokenization and leave usage details blank when cost details are provided", async () => {
+ const generationUsage1 = {
+ model: modelName,
+ input: "hello world",
+ output: "whassup",
+ usage: null,
+ costDetails: {
+ input: 1,
+ output: 2,
+ },
+ };
+
+ const events = [
+ {
+ id: uuidv4(),
+ type: "generation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ startTime: new Date().toISOString(),
+ ...generationUsage1,
+ },
+ },
+ ];
+
+ await (mockIngestionService as any).processObservationEventList({
+ projectId,
+ entityId: generationId,
+ createdAtTimestamp: new Date(),
+ observationEventList: events,
+ });
+
+ expect(mockAddToClickhouseWriter).toHaveBeenCalled();
+ const args = mockAddToClickhouseWriter.mock.calls[0];
+ const tableName = args[0];
+ const generation = args[1];
+
+ expect(tableName).toBe("observations");
+ expect(generation.type).toBe("GENERATION");
+ expect(generation.internal_model_id).toBe(tokenModelData.id);
+
+ // Provided costs are authoritative (calculateUsageCosts ignores computed
+ // usage once any cost point is provided)
+ expect(generation.provided_cost_details).toEqual({ input: 1, output: 2 });
+ expect(generation.cost_details).toEqual({ input: 1, output: 2, total: 3 });
+ expect(generation.total_cost).toBe(3);
+
+ // Tokenization must not run: usage details stay blank
+ expect(generation.usage_details).toEqual({});
+ expect(generation.provided_usage_details).toEqual({});
+
+ // No pricing tier gets stamped from an empty usage vector
+ expect(generation.usage_pricing_tier_id).toBeNull();
+ expect(generation.usage_pricing_tier_name).toBeNull();
+ });
+
describe("string to number conversion in getUsageUnits", () => {
// These tests verify that usage_details values are correctly converted to numbers
// even when they come in as strings (which can happen when reading from ClickHouse,