Skip to content

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

feat: cache LLM models in Redis (#6129)

Max Deichmann62fa43aa78da
diff --git a/.env.prod.example b/.env.prod.example
index 4c4579c78d..48e1920bc5 100644
--- a/.env.prod.example
+++ b/.env.prod.example
@@ -266,6 +266,8 @@ OTEL_SERVICE_NAME="langfuse"
# Admin API
# ADMIN_API_KEY=
+# LANGFUSE_CACHE_MODEL_MATCH_ENABLED=
+# LANGFUSE_CACHE_MODEL_MATCH_TTL_SECONDS=
# Rate limiting
# LANGFUSE_RATE_LIMITS_ENABLED=
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index b9a1f99cc6..62c475a451 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -10,7 +10,7 @@ const EnvSchema = z.object({
REDIS_PORT: z.coerce
.number({
description:
- ".env files convert numbers to strings, therefoore we have to enforce them to be numbers",
+ ".env files convert numbers to strings, therefore we have to enforce them to be numbers",
})
.positive()
.max(65536, `options.port should be >= 0 and < 65536`)
@@ -32,6 +32,8 @@ const EnvSchema = z.object({
.optional(),
LANGFUSE_CACHE_PROMPT_ENABLED: z.enum(["true", "false"]).default("false"),
LANGFUSE_CACHE_PROMPT_TTL_SECONDS: z.coerce.number().default(60 * 60),
+ LANGFUSE_CACHE_MODEL_MATCH_ENABLED: z.enum(["true", "false"]).default("true"),
+ LANGFUSE_CACHE_MODEL_MATCH_TTL_SECONDS: z.coerce.number().default(30),
CLICKHOUSE_URL: z.string().url(),
CLICKHOUSE_CLUSTER_NAME: z.string().default("default"),
CLICKHOUSE_DB: z.string().default("default"),
@@ -50,10 +52,7 @@ const EnvSchema = z.object({
ENABLE_AWS_CLOUDWATCH_METRIC_PUBLISHING: z
.enum(["true", "false"])
.default("false"),
- LANGFUSE_S3_CONCURRENT_WRITES: z.coerce
- .number()
- .positive()
- .default(50),
+ LANGFUSE_S3_CONCURRENT_WRITES: z.coerce.number().positive().default(50),
LANGFUSE_S3_EVENT_UPLOAD_BUCKET: z.string({
required_error: "Langfuse requires a bucket name for S3 Event Uploads.",
}),
@@ -75,9 +74,9 @@ const EnvSchema = z.object({
.enum(["true", "false"])
.default("false"),
- LANGFUSE_CUSTOM_SSO_EMAIL_CLAIM: z.string().default('email'),
- LANGFUSE_CUSTOM_SSO_NAME_CLAIM: z.string().default('name'),
- LANGFUSE_CUSTOM_SSO_SUB_CLAIM: z.string().default('sub'),
+ LANGFUSE_CUSTOM_SSO_EMAIL_CLAIM: z.string().default("email"),
+ LANGFUSE_CUSTOM_SSO_NAME_CLAIM: z.string().default("name"),
+ LANGFUSE_CUSTOM_SSO_SUB_CLAIM: z.string().default("sub"),
});
export const env: z.infer<typeof EnvSchema> =
diff --git a/packages/shared/src/server/ingestion/modelMatch.ts b/packages/shared/src/server/ingestion/modelMatch.ts
index 62226aa4cd..d4ede08af9 100644
--- a/packages/shared/src/server/ingestion/modelMatch.ts
+++ b/packages/shared/src/server/ingestion/modelMatch.ts
@@ -1,33 +1,74 @@
+import { env } from "../../env";
import { Model, Prisma } from "@prisma/client";
import { prisma } from "../../db";
-import { Observation } from "../repositories";
+import { recordIncrement } from "../instrumentation";
+import { logger } from "../logger";
+import { redis } from "../redis/redis";
+import Decimal from "decimal.js";
-export async function findModel(p: {
- event: {
- projectId: string;
- model?: string;
- unit?: string;
- startTime?: Date;
- };
- existingDbObservation?: Omit<Observation, "input" | "output">;
-}): Promise<Model | null> {
- const { event, existingDbObservation } = p;
+export type ModelMatchProps = {
+ projectId: string;
+ model: string;
+};
+
+export async function findModel(p: ModelMatchProps): Promise<Model | null> {
+ logger.debug(`Finding model for ${JSON.stringify(p)}`);
+ const redisModel = await getModelFromRedis(p);
+ if (redisModel) {
+ logger.debug(
+ `Found model name ${redisModel?.modelName} (id: ${redisModel?.id}) for project ${p.projectId} and model ${p.model}`,
+ );
+ return redisModel;
+ }
+
+ // try to find model in Postgres
+ const postgresModel = await findModelInPostgres(p);
+
+ if (postgresModel && env.LANGFUSE_CACHE_MODEL_MATCH_ENABLED === "true") {
+ await addModelToRedis(p, postgresModel);
+ }
+
+ logger.debug(
+ `Found model name ${postgresModel?.modelName} (id: ${postgresModel?.id}) for project ${p.projectId} and model ${p.model}`,
+ );
+ return postgresModel;
+}
+
+const getModelFromRedis = async (p: ModelMatchProps): Promise<Model | null> => {
+ if (env.LANGFUSE_CACHE_MODEL_MATCH_ENABLED === "false") {
+ return null;
+ }
+
+ try {
+ const key = getRedisModelKey(p);
+ const redisModel = await redis?.get(key);
+ if (redisModel) {
+ recordIncrement("langfuse.model_match.cache_hit", 1);
+ const model = redisModelToPrismaModel(redisModel);
+ return model;
+ }
+ recordIncrement("langfuse.model_match.cache_miss", 1);
+ return null;
+ } catch (error) {
+ logger.error(
+ `Error getting model for ${JSON.stringify(p)} from Redis`,
+ error,
+ );
+ return null;
+ }
+};
+
+export async function findModelInPostgres(
+ p: ModelMatchProps,
+): Promise<Model | null> {
+ const { projectId, model } = p;
// either get the model from the existing observation
// or match pattern on the user provided model name
- const modelCondition = event.model
- ? Prisma.sql`AND ${event.model} ~ match_pattern`
- : existingDbObservation?.internalModel
- ? Prisma.sql`AND model_name = ${existingDbObservation.internalModel}`
- : undefined;
+ const modelCondition = model
+ ? Prisma.sql`AND ${model} ~ match_pattern`
+ : undefined;
if (!modelCondition) return null;
- // unit based on the current event or the existing observation, both can be undefined
- const mergedUnit = event.unit ?? existingDbObservation?.unit;
-
- const unitCondition = mergedUnit
- ? Prisma.sql`AND unit = ${mergedUnit}`
- : Prisma.empty;
-
const sql = Prisma.sql`
SELECT
id,
@@ -45,13 +86,9 @@ export async function findModel(p: {
tokenizer_config AS "tokenizerConfig"
FROM
models
- WHERE (project_id = ${event.projectId}
+ WHERE (project_id = ${projectId}
OR project_id IS NULL)
${modelCondition}
- ${unitCondition}
- AND (start_date IS NULL OR start_date <= ${
- event.startTime ? new Date(event.startTime) : new Date()
- }::timestamp with time zone at time zone 'UTC')
ORDER BY
project_id ASC,
start_date DESC NULLS LAST
@@ -62,3 +99,39 @@ export async function findModel(p: {
return foundModels[0] ?? null;
}
+
+const addModelToRedis = async (p: ModelMatchProps, model: Model) => {
+ try {
+ const key = getRedisModelKey(p);
+ await redis?.set(
+ key,
+ JSON.stringify(model),
+ "EX",
+ env.LANGFUSE_CACHE_MODEL_MATCH_TTL_SECONDS,
+ );
+ } catch (error) {
+ logger.error(`Error adding model for ${JSON.stringify(p)} to Redis`, error);
+ }
+};
+
+export const getRedisModelKey = (p: ModelMatchProps) => {
+ const uriEncodedModel = encodeURIComponent(p.model);
+ return `${getModelMatchKeyPrefix()}:${p.projectId}:${uriEncodedModel}`;
+};
+
+const getModelMatchKeyPrefix = () => {
+ return "model-match";
+};
+
+export const redisModelToPrismaModel = (redisModel: string): Model => {
+ const parsed = JSON.parse(redisModel);
+ return {
+ ...parsed,
+ createdAt: new Date(parsed.createdAt),
+ updatedAt: new Date(parsed.updatedAt),
+ inputPrice: new Decimal(parsed.inputPrice),
+ outputPrice: new Decimal(parsed.outputPrice),
+ totalPrice: new Decimal(parsed.totalPrice),
+ startDate: parsed.startDate ? new Date(parsed.startDate) : null,
+ };
+};
diff --git a/web/src/env.mjs b/web/src/env.mjs
index 06dd0d3e78..c08e4d8630 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -224,7 +224,7 @@ export const env = createEnv({
REDIS_PORT: z.coerce
.number({
description:
- ".env files convert numbers to strings, therefoore we have to enforce them to be numbers",
+ ".env files convert numbers to strings, therefore we have to enforce them to be numbers",
})
.positive()
.max(65536, `options.port should be >= 0 and < 65536`)
diff --git a/web/src/pages/api/public/models/[modelId]/index.ts b/web/src/pages/api/public/models/[modelId]/index.ts
index 81c524234c..d6cc5ef61f 100644
--- a/web/src/pages/api/public/models/[modelId]/index.ts
+++ b/web/src/pages/api/public/models/[modelId]/index.ts
@@ -73,6 +73,7 @@ export default withMiddlewares({
apiKeyId: auth.scope.apiKeyId,
before: model,
});
+
return {
message: "Model successfully deleted" as const,
};
diff --git a/worker/src/__tests__/modelMatch.test.ts b/worker/src/__tests__/modelMatch.test.ts
new file mode 100644
index 0000000000..dce9a54613
--- /dev/null
+++ b/worker/src/__tests__/modelMatch.test.ts
@@ -0,0 +1,121 @@
+import { expect, describe, it, beforeEach, afterEach } from "vitest";
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ createOrgProjectAndApiKey,
+ findModel,
+ findModelInPostgres,
+ getRedisModelKey,
+ redis,
+} from "@langfuse/shared/src/server";
+
+describe("modelMatch", () => {
+ describe("findModel", () => {
+ it("should return model from Redis if available", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ // First create a model in Postgres
+ const mockModel = await prisma.model.create({
+ data: {
+ projectId,
+ modelName: "gpt-4",
+ matchPattern: "gpt-4",
+ unit: "TOKENS",
+ inputPrice: "1.0123",
+ },
+ });
+
+ // Find it once to cache in Redis
+ await findModel({
+ projectId,
+ model: "gpt-4",
+ });
+
+ // Now find it again - should come from Redis
+ const result = await findModel({
+ projectId,
+ model: "gpt-4",
+ });
+
+ expect(result).toEqual(mockModel);
+ // Verify the model exists in Redis
+ const 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);
+ });
+
+ it("should query Postgres if Redis cache misses", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const mockModel = await prisma.model.create({
+ data: {
+ projectId,
+ modelName: "gpt-4",
+ matchPattern: "gpt-4",
+ unit: "TOKENS",
+ },
+ });
+
+ const result = await findModel({
+ projectId,
+ model: "gpt-4",
+ });
+
+ expect(result).toEqual(mockModel);
+ });
+ });
+
+ describe("findModelInPostgres", () => {
+ it("should find model by exact match pattern", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const mockModel = await prisma.model.create({
+ data: {
+ projectId,
+ modelName: "gpt-4",
+ matchPattern: "gpt-4",
+ unit: "TOKENS",
+ },
+ });
+
+ const result = await findModelInPostgres({
+ projectId,
+ model: "gpt-4",
+ });
+
+ expect(result).toEqual(mockModel);
+ });
+
+ it("should find model by regex match pattern", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const mockModel = await prisma.model.create({
+ data: {
+ projectId,
+ modelName: "gpt-4-turbo",
+ matchPattern: "gpt-4.*",
+ unit: "TOKENS",
+ },
+ });
+
+ const result = await findModelInPostgres({
+ projectId,
+ model: "gpt-4-turbo",
+ });
+
+ expect(result).toEqual(mockModel);
+ });
+
+ it("should return null when no model matches", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const result = await findModelInPostgres({
+ projectId,
+ model: "nonexistent-model",
+ });
+
+ expect(result).toBeNull();
+ });
+ });
+});
diff --git a/worker/src/env.ts b/worker/src/env.ts
index 1e6c9e4311..d9e9aa3a0e 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -11,7 +11,7 @@ const EnvSchema = z.object({
PORT: z.coerce
.number({
description:
- ".env files convert numbers to strings, therefoore we have to enforce them to be numbers",
+ ".env files convert numbers to strings, therefore we have to enforce them to be numbers",
})
.positive()
.max(65536, `options.port should be >= 0 and < 65536`)
@@ -78,7 +78,7 @@ const EnvSchema = z.object({
REDIS_PORT: z.coerce
.number({
description:
- ".env files convert numbers to strings, therefoore we have to enforce them to be numbers",
+ ".env files convert numbers to strings, therefore we have to enforce them to be numbers",
})
.positive()
.max(65536, `options.port should be >= 0 and < 65536`)
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index 4c79e8a900..1565333009 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -16,7 +16,6 @@ import {
convertScoreReadToInsert,
convertTraceReadToInsert,
eventTypes,
- findModel,
IngestionEventType,
instrumentAsync,
logger,
@@ -39,6 +38,7 @@ import {
TraceUpsertQueue,
QueueJobs,
recordIncrement,
+ findModel,
} from "@langfuse/shared/src/server";
import { tokenCount } from "../../features/tokenisation/usage";
@@ -606,16 +606,12 @@ export class IngestionService {
| {}
> {
const { projectId, observationRecord } = params;
- const internalModel = await findModel({
- event: {
- projectId,
- model: observationRecord.provided_model_name ?? undefined,
- },
- });
-
- logger.debug(
- `Found internal model name ${internalModel?.modelName} (id: ${internalModel?.id}) for observation ${observationRecord.id}`,
- );
+ const internalModel = observationRecord.provided_model_name
+ ? await findModel({
+ projectId,
+ model: observationRecord.provided_model_name,
+ })
+ : null;
const final_usage_details = this.getUsageUnits(
observationRecord,
diff --git a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
index 569a77b959..9ea8ae8532 100644
--- a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
+++ b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
@@ -33,6 +33,7 @@ describe("Ingestion end-to-end tests", () => {
beforeEach(async () => {
if (!redis) throw new Error("Redis not initialized");
await pruneDatabase();
+ await redis.flushall();
clickhouseWriter = ClickhouseWriter.getInstance();