🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
perf: add caching for model price lookups (#9737)
Steffen Schmitz84598cfbbf7c
diff --git a/packages/shared/src/server/ingestion/modelMatch.ts b/packages/shared/src/server/ingestion/modelMatch.tsindex 88b725eb4e..cffa43691b 100644--- a/packages/shared/src/server/ingestion/modelMatch.ts+++ b/packages/shared/src/server/ingestion/modelMatch.ts@@ -1,4 +1,4 @@-import { Model, Prisma } from "../../";+import { Model, Price, Prisma } from "../../";import {instrumentAsync,logger,@@ -16,9 +16,14 @@ export type ModelMatchProps = {model: string;};+export type ModelWithPrices = {+ model: Model | null;+ prices: Price[];+};+const MODEL_MATCH_CACHE_LOCKED_KEY = "LOCK:model-match-clear";-export async function findModel(p: ModelMatchProps): Promise<Model | null> {+export async function findModel(p: ModelMatchProps): Promise<ModelWithPrices> {return instrumentAsync({name: "model-match",@@ -26,35 +31,47 @@ export async function findModel(p: ModelMatchProps): Promise<Model | null> {},async (span) => {logger.debug(`Finding model for ${JSON.stringify(p)}`);- const redisModel = await getModelFromRedis(p);- if (redisModel) {+ const cachedResult = await getModelWithPricesFromRedis(p);+ if (cachedResult) {span.setAttribute("model_match_source", "redis");- if (redisModel === NOT_FOUND_TOKEN) {- return null;+ if (cachedResult.model === null) {+ return { model: null, prices: [] };} else {logger.debug(- `Found model name ${redisModel?.modelName} (id: ${redisModel?.id}) for project ${p.projectId} and model ${p.model}`,+ `Found model name ${cachedResult.model?.modelName} (id: ${cachedResult.model?.id}) for project ${p.projectId} and model ${p.model}`,);- span.setAttribute("matched_model_id", redisModel.id);+ span.setAttribute("matched_model_id", cachedResult.model.id);}- return redisModel;+ return cachedResult;}// try to find model in Postgresconst postgresModel = await findModelInPostgres(p);if (postgresModel && env.LANGFUSE_CACHE_MODEL_MATCH_ENABLED === "true") {- await addModelToRedis(p, postgresModel);+ const prices = await findPricesForModel(postgresModel.id);+ await addModelWithPricesToRedis(p, postgresModel, prices);span.setAttribute("matched_model_id", postgresModel.id);span.setAttribute("model_match_source", "postgres");span.setAttribute("model_cache_set", "true");++ logger.debug(+ `Found model name ${postgresModel?.modelName} (id: ${postgresModel?.id}) for project ${p.projectId} and model ${p.model}`,+ );+ return { model: postgresModel, prices };} else if (postgresModel) {+ const prices = await findPricesForModel(postgresModel.id);span.setAttribute("matched_model_id", postgresModel.id);span.setAttribute("model_match_source", "postgres");span.setAttribute("model_cache_set", "false");++ logger.debug(+ `Found model name ${postgresModel?.modelName} (id: ${postgresModel?.id}) for project ${p.projectId} and model ${p.model}`,+ );+ return { model: postgresModel, prices };} else {span.setAttribute("model_match_source", "none");@@ -62,19 +79,19 @@ export async function findModel(p: ModelMatchProps): Promise<Model | null> {await addModelNotFoundTokenToRedis(p);span.setAttribute("model_cache_set", "true");}- }- logger.debug(- `Found model name ${postgresModel?.modelName} (id: ${postgresModel?.id}) for project ${p.projectId} and model ${p.model}`,- );- return postgresModel;+ logger.debug(+ `Model not found for project ${p.projectId} and model ${p.model}`,+ );+ return { model: null, prices: [] };+ }},);}-const getModelFromRedis = async (+const getModelWithPricesFromRedis = async (p: ModelMatchProps,-): Promise<Model | typeof NOT_FOUND_TOKEN | null> => {+): Promise<ModelWithPrices | null> => {if (env.LANGFUSE_CACHE_MODEL_MATCH_ENABLED === "false") {return null;}@@ -89,17 +106,50 @@ const getModelFromRedis = async (}const key = getRedisModelKey(p);- const redisModel = await redis?.get(key);- if (redisModel) {- recordIncrement("langfuse.model_match.cache_hit", 1);- if (redisModel === NOT_FOUND_TOKEN) {- return NOT_FOUND_TOKEN;- }- const model = redisModelToPrismaModel(redisModel);- return model;+ const redisValue = await redis?.get(key);+ if (!redisValue) {+ recordIncrement("langfuse.model_match.cache_miss", 1);+ return null;}- recordIncrement("langfuse.model_match.cache_miss", 1);- return null;++ recordIncrement("langfuse.model_match.cache_hit", 1);++ if (redisValue === NOT_FOUND_TOKEN) {+ return { model: null, prices: [] };+ }++ const parsed = JSON.parse(redisValue);++ // NEW FORMAT: { model: {...}, prices: [...] }+ if (parsed.model !== undefined && parsed.prices !== undefined) {+ const model = redisModelToPrismaModel(JSON.stringify(parsed.model));+ const prices = parsed.prices.map(+ (p: any): Price => ({+ ...p,+ price: new Decimal(p.price),+ createdAt: new Date(p.createdAt),+ updatedAt: new Date(p.updatedAt),+ }),+ );+ return { model, prices };+ }++ // OLD FORMAT: just the model (backwards compatible)+ // Fetch prices and update cache+ const model = redisModelToPrismaModel(redisValue);+ const prices = await findPricesForModel(model.id);++ // Update cache with new format asynchronously (don't await)+ if (env.LANGFUSE_CACHE_MODEL_MATCH_ENABLED === "true") {+ addModelWithPricesToRedis(p, model, prices).catch((error) => {+ logger.error(+ `Error updating cache with prices for ${JSON.stringify(p)}`,+ error,+ );+ });+ }++ return { model, prices };} catch (error) {logger.error(`Error getting model for ${JSON.stringify(p)} from Redis`,@@ -109,6 +159,10 @@ const getModelFromRedis = async (}};+export async function findPricesForModel(modelId: string): Promise<Price[]> {+ return (await prisma.price.findMany({ where: { modelId } })) ?? [];+}+export async function findModelInPostgres(p: ModelMatchProps,): Promise<Model | null> {@@ -132,7 +186,7 @@ export async function findModelInPostgres(input_price AS "inputPrice",output_price AS "outputPrice",total_price AS "totalPrice",- unit,+ unit,tokenizer_id AS "tokenizerId",tokenizer_config AS "tokenizerConfig"FROM@@ -170,17 +224,24 @@ const addModelNotFoundTokenToRedis = async (p: ModelMatchProps) => {}};-const addModelToRedis = async (p: ModelMatchProps, model: Model) => {+const addModelWithPricesToRedis = async (+ p: ModelMatchProps,+ model: Model,+ prices: Price[],+) => {try {const key = getRedisModelKey(p);await redis?.set(key,- JSON.stringify(model),+ JSON.stringify({ model, prices }),"EX",env.LANGFUSE_CACHE_MODEL_MATCH_TTL_SECONDS,);} catch (error) {- logger.error(`Error adding model for ${JSON.stringify(p)} to Redis`, error);+ logger.error(+ `Error adding model with prices for ${JSON.stringify(p)} to Redis`,+ error,+ );}};diff --git a/worker/src/__tests__/modelMatch.test.ts b/worker/src/__tests__/modelMatch.test.tsindex 6f334ad0dd..58486a2896 100644--- a/worker/src/__tests__/modelMatch.test.ts+++ b/worker/src/__tests__/modelMatch.test.ts@@ -10,7 +10,7 @@ import {describe("modelMatch", () => {describe("findModel", () => {- it("should return model from Redis if available", async () => {+ it("should return model with prices from Redis if available", async () => {const { projectId } = await createOrgProjectAndApiKey();// First create a model in Postgresconst mockModel = await prisma.model.create({@@ -23,6 +23,15 @@ describe("modelMatch", () => {},});+ // Create prices for the model+ const mockPrice = await prisma.price.create({+ data: {+ modelId: mockModel.id,+ usageType: "input",+ price: "0.03",+ },+ });+// Find it once to cache in Redisawait findModel({projectId,@@ -35,36 +44,43 @@ describe("modelMatch", () => {model: "gpt-4",});- expect(result).not.toBeNull();- if (!result) {- throw new Error("Result is null");+ expect(result.model).not.toBeNull();+ if (!result.model) {+ throw new Error("Result model is null");}- expect(result.id).toEqual(mockModel.id);- expect(result.projectId).toEqual(mockModel.projectId);- expect(result.modelName).toEqual(mockModel.modelName);- expect(result.matchPattern).toEqual(mockModel.matchPattern);- expect(result.unit).toEqual(mockModel.unit);- expect(result.inputPrice?.toString()).toEqual(+ expect(result.model.id).toEqual(mockModel.id);+ expect(result.model.projectId).toEqual(mockModel.projectId);+ expect(result.model.modelName).toEqual(mockModel.modelName);+ expect(result.model.matchPattern).toEqual(mockModel.matchPattern);+ expect(result.model.unit).toEqual(mockModel.unit);+ expect(result.model.inputPrice?.toString()).toEqual(mockModel.inputPrice?.toString(),);- expect(result.outputPrice?.toString()).toEqual(+ expect(result.model.outputPrice?.toString()).toEqual(mockModel.outputPrice?.toString(),);- expect(result.totalPrice?.toString()).toEqual(+ expect(result.model.totalPrice?.toString()).toEqual(mockModel.totalPrice?.toString(),);- // Verify the model exists in Redis+ // Verify prices are included+ expect(result.prices).toHaveLength(1);+ expect(result.prices[0].id).toEqual(mockPrice.id);+ expect(result.prices[0].usageType).toEqual(mockPrice.usageType);++ // Verify the model with prices exists in Redisconst redisKey = getRedisModelKey({projectId,model: "gpt-4",});- const cachedModel = await redis?.get(redisKey);- expect(cachedModel).not.toBeNull();- const parsedModel = JSON.parse(cachedModel!);- expect(parsedModel.id).toEqual(mockModel.id);- expect(parsedModel.projectId).toEqual(mockModel.projectId);+ const cachedValue = await redis?.get(redisKey);+ expect(cachedValue).not.toBeNull();+ const parsed = JSON.parse(cachedValue!);+ expect(parsed.model.id).toEqual(mockModel.id);+ expect(parsed.model.projectId).toEqual(mockModel.projectId);+ expect(parsed.prices).toHaveLength(1);+ expect(parsed.prices[0].id).toEqual(mockPrice.id);});it("should query Postgres if Redis cache misses", async () => {@@ -83,7 +99,8 @@ describe("modelMatch", () => {model: "gpt-4",});- expect(result).toEqual(mockModel);+ expect(result.model).toEqual(mockModel);+ expect(result.prices).toEqual([]);});it("should cache not found models in Redis", async () => {@@ -95,14 +112,16 @@ describe("modelMatch", () => {projectId,model: nonExistentModel,});- expect(result1).toBeNull();+ expect(result1.model).toBeNull();+ expect(result1.prices).toEqual([]);// Second lookup should use the cached not-found resultconst result2 = await findModel({projectId,model: nonExistentModel,});- expect(result2).toBeNull();+ expect(result2.model).toBeNull();+ expect(result2.prices).toEqual([]);// Verify the not-found token exists in Redisconst redisKey = getRedisModelKey({diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex 34e6ec5515..a0ba51d1a3 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -1005,18 +1005,18 @@ export class IngestionService {| {}> {const { projectId, observationRecord } = params;- const internalModel = observationRecord.provided_model_name- ? await findModel({- projectId,- model: observationRecord.provided_model_name,- })- : null;+ const { model: internalModel, prices: modelPrices } =+ observationRecord.provided_model_name+ ? await findModel({+ projectId,+ model: observationRecord.provided_model_name,+ })+ : { model: null, prices: [] };const final_usage_details = await this.getUsageUnits(observationRecord,internalModel,);- const modelPrices = await this.getModelPrices(internalModel?.id);const final_cost_details = IngestionService.calculateUsageCosts(modelPrices,@@ -1039,12 +1039,6 @@ export class IngestionService {};}- private async getModelPrices(modelId?: string): Promise<Price[]> {- return modelId- ? ((await this.prisma.price.findMany({ where: { modelId } })) ?? [])- : [];- }-private async getUsageUnits(observationRecord: ObservationRecordInsertType,model: Model | null | undefined,