Skip to content

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

fix(model-prices): upsert if prices are missing (#4312)

Hassieb Pakzadc99a43559d1c
diff --git a/worker/src/scripts/upsertDefaultModelPrices.ts b/worker/src/scripts/upsertDefaultModelPrices.ts
index 142b1442ce..740e2ce3e5 100644
--- a/worker/src/scripts/upsertDefaultModelPrices.ts
+++ b/worker/src/scripts/upsertDefaultModelPrices.ts
@@ -13,6 +13,14 @@ const DefaultModelPriceSchema = z.object({
tokenizer_config: z.record(z.union([z.string(), z.number()])).nullish(),
tokenizer_id: z.string().nullish(),
});
+type DefaultModelPrice = z.infer<typeof DefaultModelPriceSchema>;
+
+const ExistingModelPriceSchema = z.object({
+ modelId: z.string(),
+ modelUpdatedAt: z.coerce.date(),
+ usageType: z.string(),
+ price: z.coerce.number(),
+});
/**
* Upserts default model prices into the database into models and prices tables.
@@ -46,21 +54,49 @@ export const upsertDefaultModelPrices = async (force = false) => {
.array(DefaultModelPriceSchema)
.parse(defaultModelPrices);
- // Fetch existing default models. Store in a map for O(1) lookup.
- const existingModelUpdateDates = new Map(
- (
- await prisma.model.findMany({
- where: {
- projectId: null,
- },
- select: {
- id: true,
- updatedAt: true,
- },
- })
- ).map((model) => [model.id, model.updatedAt])
+ const existingModelPricesQuery = await prisma.$queryRaw`
+ SELECT
+ m.id AS "modelId",
+ m.updated_at "modelUpdatedAt",
+ p.usage_type "usageType",
+ p.price "price"
+ FROM
+ prices p
+ LEFT JOIN models m ON m.id = p.model_id
+ WHERE
+ m.project_id IS NULL
+ `;
+
+ const existingModelPrices = ExistingModelPriceSchema.array().parse(
+ existingModelPricesQuery,
);
+ // Store in a map for O(1) lookup.
+ const existingModelPricesMap = new Map<
+ string,
+ { updatedAt: Date; prices: Record<string, number> }
+ >(
+ existingModelPrices.map((em) => [
+ em.modelId,
+ {
+ updatedAt: em.modelUpdatedAt,
+ prices: {},
+ },
+ ]),
+ );
+
+ for (const existingModelPrice of existingModelPrices) {
+ const mapRecord = existingModelPricesMap.get(existingModelPrice.modelId);
+ if (mapRecord) {
+ mapRecord.prices[existingModelPrice.usageType] =
+ existingModelPrice.price;
+ } else {
+ logger.error(
+ `Existing model price for ${existingModelPrice.modelId} not found in map.`,
+ );
+ }
+ }
+
// Upsert in batches
const batchSize = 10;
const numBatches = Math.ceil(parsedDefaultModelPrices.length / batchSize);
@@ -70,39 +106,27 @@ export const upsertDefaultModelPrices = async (force = false) => {
const batch = parsedDefaultModelPrices.slice(
i * batchSize,
- (i + 1) * batchSize
+ (i + 1) * batchSize,
);
const promises = [];
for (const defaultModelPrice of batch) {
- const existingModelUpdateDate = existingModelUpdateDates.get(
- defaultModelPrice.id
+ const existingModelUpdateDate = existingModelPricesMap.get(
+ defaultModelPrice.id,
);
if (
!force &&
existingModelUpdateDate &&
- existingModelUpdateDate.getTime() ===
- defaultModelPrice.updated_at.getTime()
+ isExistingModelUpToDate(defaultModelPrice, existingModelUpdateDate)
) {
logger.debug(
- `Default model ${defaultModelPrice.model_name} (${defaultModelPrice.id}) already up to date. Skipping.`
+ `Default model ${defaultModelPrice.model_name} (${defaultModelPrice.id}) already up to date. Skipping.`,
);
continue;
}
- if (
- !force &&
- existingModelUpdateDate &&
- existingModelUpdateDate.getTime() >
- defaultModelPrice.updated_at.getTime()
- ) {
- logger.error(
- `Model drift detected for default model ${defaultModelPrice.model_name} (${defaultModelPrice.id}). updatedAt ${existingModelUpdateDate.toISOString()} after ${defaultModelPrice.updated_at.toISOString()}. Upserting model and prices.`
- );
- }
-
// Upsert model and prices in a transaction
promises.push(
prisma
@@ -136,7 +160,7 @@ export const upsertDefaultModelPrices = async (force = false) => {
const pricesToUpsert = [];
for (const [usageType, price] of Object.entries(
- defaultModelPrice.prices
+ defaultModelPrice.prices,
)) {
pricesToUpsert.push(
tx.price.upsert({
@@ -157,14 +181,14 @@ export const upsertDefaultModelPrices = async (force = false) => {
createdAt: defaultModelPrice.created_at,
updatedAt: defaultModelPrice.updated_at,
},
- })
+ }),
);
}
await Promise.all(pricesToUpsert);
logger.info(
- `Upserted default model ${defaultModelPrice.model_name} (${defaultModelPrice.id})`
+ `Upserted default model ${defaultModelPrice.model_name} (${defaultModelPrice.id})`,
);
})
.catch((error) => {
@@ -172,9 +196,9 @@ export const upsertDefaultModelPrices = async (force = false) => {
`Error upserting default model ${defaultModelPrice.model_name} (${defaultModelPrice.id}): ${error.message}`,
{
error,
- }
+ },
);
- })
+ }),
);
}
@@ -183,7 +207,7 @@ export const upsertDefaultModelPrices = async (force = false) => {
}
logger.info(
- `Finished upserting default model prices in ${Date.now() - startTime}ms`
+ `Finished upserting default model prices in ${Date.now() - startTime}ms`,
);
} catch (error) {
logger.error(
@@ -192,7 +216,25 @@ export const upsertDefaultModelPrices = async (force = false) => {
}`,
{
error,
- }
+ },
);
}
};
+
+function isExistingModelUpToDate(
+ defaultModelPrice: DefaultModelPrice,
+ existingModelPrices: { updatedAt: Date; prices: Record<string, number> },
+) {
+ const isUpdatedAtSame =
+ existingModelPrices.updatedAt.getTime() ===
+ defaultModelPrice.updated_at.getTime();
+
+ const isPriceSame =
+ Object.keys(defaultModelPrice.prices).length ===
+ Object.keys(existingModelPrices.prices).length &&
+ Object.entries(existingModelPrices.prices).every(([usageType, price]) => {
+ return price === defaultModelPrice.prices[usageType];
+ });
+
+ return isUpdatedAtSame && isPriceSame;
+}