Skip to content

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

feat: adds server-side caching to prompts (#2741)

Hassieb Pakzad1ff58377f1d6
diff --git a/.env.prod.example b/.env.prod.example
index 0db0c7adbb..b4c3d4cfac 100644
--- a/.env.prod.example
+++ b/.env.prod.example
@@ -160,6 +160,7 @@ LANGFUSE_CSP_ENFORCE_HTTPS="true"
# Cache configuration
# LANGFUSE_CACHE_API_KEY_ENABLED=
# LANGFUSE_CACHE_API_KEY_TTL=
-
+# LANGFUSE_CACHE_PROMPT_ENABLED=
+# LANGFUSE_CACHE_PROMPT_TTL_SECONDS=
### END Langfuse Cloud Config
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index ca24787754..53908af687 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -23,6 +23,8 @@ const EnvSchema = z.object({
"ENCRYPTION_KEY must be 256 bits, 64 string characters in hex format, generate via: openssl rand -hex 32"
)
.optional(),
+ LANGFUSE_CACHE_PROMPT_ENABLED: z.enum(["true", "false"]).default("false"),
+ LANGFUSE_CACHE_PROMPT_TTL_SECONDS: z.number().default(60 * 60),
});
export const env = EnvSchema.parse(process.env);
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index a0a164d540..5bb2acfe8f 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -2,6 +2,7 @@ export * from "./services/S3StorageService";
export * from "./services/email/projectInvitation/sendProjectInvitationEmail";
export * from "./services/email/batchExportSuccess/sendBatchExportSuccessEmail";
export * from "./services/email/passwordReset/sendResetPasswordVerificationRequest";
+export * from "./services/PromptService";
export * from "./auth";
export * from "./llm/fetchLLMCompletion";
export * from "./llm/types";
diff --git a/packages/shared/src/server/redis/trace-upsert.ts b/packages/shared/src/server/redis/trace-upsert.ts
index 807c8c53ac..8d3a6ebd44 100644
--- a/packages/shared/src/server/redis/trace-upsert.ts
+++ b/packages/shared/src/server/redis/trace-upsert.ts
@@ -8,11 +8,20 @@ import {
import { Queue } from "bullmq";
import { redis } from "./redis";
-export const traceUpsertQueue = redis
- ? new Queue<TQueueJobTypes[QueueName.TraceUpsert]>(QueueName.TraceUpsert, {
- connection: redis,
- })
- : null;
+let traceUpsertQueue: Queue<TQueueJobTypes[QueueName.TraceUpsert]> | null =
+ null;
+
+export const getTraceUpsertQueue = () => {
+ if (traceUpsertQueue) return traceUpsertQueue;
+
+ traceUpsertQueue = redis
+ ? new Queue<TQueueJobTypes[QueueName.TraceUpsert]>(QueueName.TraceUpsert, {
+ connection: redis,
+ })
+ : null;
+
+ return traceUpsertQueue;
+};
export function convertTraceUpsertEventsToRedisEvents(
events: TraceUpsertEventType[]
diff --git a/packages/shared/src/server/services/PromptService.ts b/packages/shared/src/server/services/PromptService.ts
new file mode 100644
index 0000000000..30ded8b9ac
--- /dev/null
+++ b/packages/shared/src/server/services/PromptService.ts
@@ -0,0 +1,229 @@
+import { Prompt, PrismaClient } from "@prisma/client";
+import { Redis } from "ioredis";
+import { env } from "../../env";
+
+export class PromptService {
+ private cacheEnabled: boolean;
+ private ttlSeconds: number;
+
+ constructor(
+ private prisma: PrismaClient,
+ private redis: Redis | null,
+ private metricIncrementer?: // used for Sentry metrics
+ (name: string, value?: number) => void,
+ cacheEnabled?: boolean // used for testing
+ ) {
+ this.cacheEnabled =
+ Boolean(redis) &&
+ (cacheEnabled || env.LANGFUSE_CACHE_PROMPT_ENABLED === "true");
+
+ this.ttlSeconds = env.LANGFUSE_CACHE_PROMPT_TTL_SECONDS;
+ }
+
+ public async getPrompt(params: PromptParams): Promise<Prompt | null> {
+ if (await this.shouldUseCache(params)) {
+ const cachedPrompt = await this.getCachedPrompt(params);
+
+ this.incrementMetric(
+ cachedPrompt ? Metrics.PromptCacheHit : Metrics.PromptCacheMiss
+ );
+
+ if (cachedPrompt) return cachedPrompt;
+ }
+
+ const dbPrompt = await this.getDbPrompt(params);
+
+ if ((await this.shouldUseCache(params)) && dbPrompt) {
+ await this.cachePrompt({ ...params, prompt: dbPrompt });
+ }
+
+ return dbPrompt;
+ }
+
+ private async getDbPrompt(params: PromptParams): Promise<Prompt | null> {
+ const { projectId, promptName, version, label } = params;
+
+ if (version) {
+ return await this.prisma.prompt.findFirst({
+ where: {
+ projectId,
+ name: promptName,
+ version,
+ },
+ });
+ }
+
+ if (label) {
+ return await this.prisma.prompt.findFirst({
+ where: {
+ projectId,
+ name: promptName,
+ labels: {
+ has: label,
+ },
+ },
+ });
+ }
+
+ this.logError("Invalid prompt params", params);
+
+ return null;
+ }
+
+ private async shouldUseCache(params: PromptParams): Promise<boolean> {
+ if (!this.cacheEnabled) return false;
+
+ const isLocked = await this.isCacheLocked(params);
+
+ return !isLocked;
+ }
+
+ private async getCachedPrompt(params: PromptParams): Promise<Prompt | null> {
+ try {
+ const key = this.getCacheKey(params);
+ const value = await this.redis?.getex(key, "EX", this.ttlSeconds);
+
+ if (value) return JSON.parse(value) as Prompt;
+ } catch (e) {
+ this.logError("Error getting cached prompt", e);
+ }
+
+ return null;
+ }
+
+ private async cachePrompt(params: PromptParams & { prompt: Prompt }) {
+ try {
+ const key = this.getCacheKey(params);
+ const value = JSON.stringify(params.prompt);
+
+ await this.redis?.set(key, value, "EX", this.ttlSeconds);
+ } catch (e) {
+ this.logError("Error caching prompt", e);
+ }
+ }
+
+ public async lockCache(
+ params: Pick<PromptParams, "projectId" | "promptName">
+ ): Promise<void> {
+ if (!this.cacheEnabled) return;
+
+ const lockKey = this.getLockKey(params);
+
+ try {
+ await this.redis?.setex(lockKey, 30, "locked");
+ } catch (e) {
+ this.logError("Error locking cache key prefix", lockKey, e);
+
+ throw e;
+ }
+ }
+
+ public async unlockCache(
+ params: Pick<PromptParams, "projectId" | "promptName">
+ ): Promise<void> {
+ if (!this.cacheEnabled) return;
+
+ const lockKey = this.getLockKey(params);
+
+ try {
+ await this.redis?.del(lockKey);
+ } catch (e) {
+ this.logError("Error unlocking cache key prefix", lockKey, e);
+
+ // Don't re-throw error as lock TTL is short and it's not critical
+ }
+ }
+
+ private async isCacheLocked(
+ params: Pick<PromptParams, "projectId" | "promptName">
+ ): Promise<boolean> {
+ const lockKey = this.getLockKey(params);
+
+ try {
+ return Boolean(await this.redis?.exists(lockKey));
+ } catch (e) {
+ this.logError("Error checking if cache is locked", lockKey, e);
+
+ return false;
+ }
+ }
+
+ private getLockKey(
+ params: Pick<PromptParams, "projectId" | "promptName">
+ ): string {
+ // Important to *pre*fix LOCK as otherwise it would be deleted by deleteKeysByPrefix
+ return `LOCK:${this.getCacheKeyPrefix(params)}`;
+ }
+
+ public async invalidateCache(
+ params: Pick<PromptParams, "projectId" | "promptName">
+ ): Promise<void> {
+ if (!this.cacheEnabled) return;
+
+ const cacheKeyPrefix = this.getCacheKeyPrefix(params);
+
+ try {
+ await this.deleteKeysByPrefix(cacheKeyPrefix);
+ } catch (e) {
+ this.logError("Error deleting keys for prefix", cacheKeyPrefix, e);
+
+ throw e;
+ }
+ }
+
+ private getCacheKey(params: PromptParams): string {
+ const prefix = this.getCacheKeyPrefix(params);
+
+ return `${prefix}:${params.version ?? params.label}`;
+ }
+
+ private getCacheKeyPrefix(
+ params: Pick<PromptParams, "projectId" | "promptName">
+ ): string {
+ return `prompt:${params.projectId}:${params.promptName}`;
+ }
+
+ private async deleteKeysByPrefix(prefix: string): Promise<void> {
+ const script = `
+ local cursor = "0"
+ repeat
+ local result = redis.call("SCAN", cursor, "MATCH", ARGV[1] .. "*", "COUNT", 100)
+
+ cursor = result[1]
+ local keys = result[2]
+
+ if #keys > 0 then
+ redis.call("DEL", unpack(keys))
+ end
+
+ until cursor == "0"
+ `;
+
+ await this.redis?.eval(script, 0, prefix);
+ }
+
+ private logError(message: string, ...args: any[]) {
+ console.error(`[PromptService] ${message}`, ...args);
+ }
+
+ private incrementMetric(name: Metrics, value: number = 1) {
+ try {
+ this.metricIncrementer?.(name, value);
+ } catch (e) {
+ this.logError("Error incrementing metric", name, e);
+ }
+ }
+}
+
+type PromptParams = {
+ projectId: string;
+ promptName: string;
+} & (
+ | { version: number; label: undefined }
+ | { version: null | undefined; label: string }
+);
+
+enum Metrics {
+ PromptCacheHit = "prompt_cache_hit",
+ PromptCacheMiss = "prompt_cache_miss",
+}
diff --git a/web/src/__tests__/promptCache.servertest.ts b/web/src/__tests__/promptCache.servertest.ts
new file mode 100644
index 0000000000..28ee3f7b0c
--- /dev/null
+++ b/web/src/__tests__/promptCache.servertest.ts
@@ -0,0 +1,309 @@
+import { type PrismaClient, type Prompt } from "@prisma/client";
+import { PromptService, type redis } from "@langfuse/shared/src/server"; // Adjust the import path as needed
+
+type Redis = NonNullable<typeof redis>;
+
+// Mocks
+jest.mock("@prisma/client");
+jest.mock("ioredis");
+jest.mock("@langfuse/shared", () => ({
+ env: {
+ LANGFUSE_CACHE_PROMPT_ENABLED: "true",
+ LANGFUSE_CACHE_PROMPT_TTL_SECONDS: 300,
+ },
+}));
+
+describe("PromptService", () => {
+ let promptService: PromptService;
+ let mockPrisma: jest.Mocked<PrismaClient>;
+ let mockRedis: jest.Mocked<Redis>;
+ let mockMetricIncrementer: jest.Mock;
+
+ const mockPrompt: Omit<Prompt, "updatedAt" | "createdAt"> = {
+ id: "1",
+ projectId: "project1",
+ name: "testPrompt",
+ version: 1,
+ prompt: "Test prompt content",
+ labels: ["test"],
+ createdBy: "API",
+ type: "text",
+ isActive: null,
+ config: {},
+ tags: [],
+ };
+
+ beforeEach(() => {
+ mockPrisma = {
+ prompt: {
+ findFirst: jest.fn(),
+ },
+ } as unknown as jest.Mocked<PrismaClient>;
+
+ mockRedis = {
+ getex: jest.fn(),
+ set: jest.fn(),
+ setex: jest.fn(),
+ del: jest.fn(),
+ exists: jest.fn(),
+ eval: jest.fn(),
+ } as unknown as jest.Mocked<Redis>;
+
+ mockMetricIncrementer = jest.fn();
+
+ promptService = new PromptService(
+ mockPrisma,
+ mockRedis,
+ mockMetricIncrementer,
+ true,
+ );
+ });
+
+ describe("getPrompt", () => {
+ it("should return cached prompt if available", async () => {
+ mockRedis.exists.mockResolvedValue(0);
+ mockRedis.getex.mockResolvedValue(JSON.stringify(mockPrompt));
+
+ const result = await promptService.getPrompt({
+ projectId: "project1",
+ promptName: "testPrompt",
+ version: 1,
+ label: undefined,
+ });
+
+ expect(result).toEqual(mockPrompt);
+ expect(mockMetricIncrementer).toHaveBeenCalledWith("prompt_cache_hit", 1);
+ });
+
+ it("should fetch from database if not in cache", async () => {
+ mockRedis.exists.mockResolvedValue(0);
+ mockRedis.getex.mockResolvedValue(null);
+ mockPrisma.prompt.findFirst.mockResolvedValue(mockPrompt);
+
+ const result = await promptService.getPrompt({
+ projectId: "project1",
+ promptName: "testPrompt",
+ version: 1,
+ label: undefined,
+ });
+
+ expect(result).toEqual(mockPrompt);
+ expect(mockPrisma.prompt.findFirst).toHaveBeenCalled();
+ expect(mockMetricIncrementer).toHaveBeenCalledWith(
+ "prompt_cache_miss",
+ 1,
+ );
+ });
+
+ it("should not use cache if locked", async () => {
+ mockRedis.exists.mockResolvedValue(1);
+ mockPrisma.prompt.findFirst.mockResolvedValue(mockPrompt);
+
+ const result = await promptService.getPrompt({
+ projectId: "project1",
+ promptName: "testPrompt",
+ version: 1,
+ label: undefined,
+ });
+
+ expect(result).toEqual(mockPrompt);
+ expect(mockRedis.getex).not.toHaveBeenCalled();
+ expect(mockPrisma.prompt.findFirst).toHaveBeenCalled();
+ });
+ });
+
+ describe("lockCache", () => {
+ it("should set a lock in Redis", async () => {
+ await promptService.lockCache({
+ projectId: "project1",
+ promptName: "testPrompt",
+ });
+
+ expect(mockRedis.setex).toHaveBeenCalledWith(
+ "LOCK:prompt:project1:testPrompt",
+ 30,
+ "locked",
+ );
+ });
+ });
+
+ describe("unlockCache", () => {
+ it("should remove the lock from Redis", async () => {
+ await promptService.unlockCache({
+ projectId: "project1",
+ promptName: "testPrompt",
+ });
+
+ expect(mockRedis.del).toHaveBeenCalledWith(
+ "LOCK:prompt:project1:testPrompt",
+ );
+ });
+ });
+
+ describe("invalidateCache", () => {
+ it("should call deleteKeysByPrefix with correct prefix", async () => {
+ await promptService.invalidateCache({
+ projectId: "project1",
+ promptName: "testPrompt",
+ });
+
+ expect(mockRedis.eval).toHaveBeenCalledWith(
+ expect.any(String),
+ 0,
+ "prompt:project1:testPrompt",
+ );
+ });
+ });
+
+ describe("caching disabled", () => {
+ beforeEach(() => {
+ promptService = new PromptService(
+ mockPrisma,
+ mockRedis,
+ mockMetricIncrementer,
+ false,
+ );
+ });
+
+ it("should not use cache when disabled", async () => {
+ mockPrisma.prompt.findFirst.mockResolvedValue(mockPrompt);
+
+ const result = await promptService.getPrompt({
+ projectId: "project1",
+ promptName: "testPrompt",
+ version: 1,
+ label: undefined,
+ });
+
+ expect(result).toEqual(mockPrompt);
+ expect(mockRedis.getex).not.toHaveBeenCalled();
+ expect(mockPrisma.prompt.findFirst).toHaveBeenCalled();
+ expect(mockMetricIncrementer).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("null Redis instance", () => {
+ beforeEach(() => {
+ promptService = new PromptService(
+ mockPrisma,
+ null,
+ mockMetricIncrementer,
+ true,
+ );
+ });
+
+ it("should not use cache with null Redis instance", async () => {
+ mockPrisma.prompt.findFirst.mockResolvedValue(mockPrompt);
+
+ const result = await promptService.getPrompt({
+ projectId: "project1",
+ promptName: "testPrompt",
+ version: 1,
+ label: undefined,
+ });
+
+ expect(result).toEqual(mockPrompt);
+ expect(mockPrisma.prompt.findFirst).toHaveBeenCalled();
+ expect(mockMetricIncrementer).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("getPrompt with Redis errors", () => {
+ it("should fallback to database if Redis.exists throws an error", async () => {
+ mockRedis.exists.mockRejectedValue(new Error("Redis error"));
+ mockPrisma.prompt.findFirst.mockResolvedValue(mockPrompt);
+
+ const result = await promptService.getPrompt({
+ projectId: "project1",
+ promptName: "testPrompt",
+ version: 1,
+ label: undefined,
+ });
+
+ expect(result).toEqual(mockPrompt);
+ expect(mockPrisma.prompt.findFirst).toHaveBeenCalled();
+ expect(mockMetricIncrementer).toHaveBeenCalledWith(
+ "prompt_cache_miss",
+ 1,
+ );
+ });
+
+ it("should fallback to database if Redis.getex throws an error", async () => {
+ mockRedis.exists.mockResolvedValue(0);
+ mockRedis.getex.mockRejectedValue(new Error("Redis error"));
+ mockPrisma.prompt.findFirst.mockResolvedValue(mockPrompt);
+
+ const result = await promptService.getPrompt({
+ projectId: "project1",
+ promptName: "testPrompt",
+ version: 1,
+ label: undefined,
+ });
+
+ expect(result).toEqual(mockPrompt);
+ expect(mockPrisma.prompt.findFirst).toHaveBeenCalled();
+ expect(mockMetricIncrementer).toHaveBeenCalledWith(
+ "prompt_cache_miss",
+ 1,
+ );
+ });
+
+ it("should not cache if Redis.set throws an error after database fetch", async () => {
+ mockRedis.exists.mockResolvedValue(0);
+ mockRedis.getex.mockResolvedValue(null);
+ mockPrisma.prompt.findFirst.mockResolvedValue(mockPrompt);
+ mockRedis.set.mockRejectedValue(new Error("Redis error"));
+
+ const result = await promptService.getPrompt({
+ projectId: "project1",
+ promptName: "testPrompt",
+ version: 1,
+ label: undefined,
+ });
+
+ expect(result).toEqual(mockPrompt);
+ expect(mockPrisma.prompt.findFirst).toHaveBeenCalled();
+ expect(mockMetricIncrementer).toHaveBeenCalledWith(
+ "prompt_cache_miss",
+ 1,
+ );
+ });
+ });
+
+ describe("lockCache with Redis errors", () => {
+ it("should throw an error if Redis.setex fails", async () => {
+ mockRedis.setex.mockRejectedValue(new Error("Redis error"));
+
+ await expect(
+ promptService.lockCache({
+ projectId: "project1",
+ promptName: "testPrompt",
+ }),
+ ).rejects.toThrow("Redis error");
+ });
+ });
+
+ describe("unlockCache with Redis errors", () => {
+ it("should log error but not throw if Redis.del fails", async () => {
+ mockRedis.del.mockRejectedValue(new Error("Redis error"));
+
+ await promptService.unlockCache({
+ projectId: "project1",
+ promptName: "testPrompt",
+ });
+ });
+ });
+
+ describe("invalidateCache with Redis errors", () => {
+ it("should throw an error if Redis.eval fails", async () => {
+ mockRedis.eval.mockRejectedValue(new Error("Redis error"));
+
+ await expect(
+ promptService.invalidateCache({
+ projectId: "project1",
+ promptName: "testPrompt",
+ }),
+ ).rejects.toThrow("Redis error");
+ });
+ });
+});
diff --git a/web/src/features/prompts/server/actions/createPrompt.ts b/web/src/features/prompts/server/actions/createPrompt.ts
index a6dc29ccbf..6fba4cee46 100644
--- a/web/src/features/prompts/server/actions/createPrompt.ts
+++ b/web/src/features/prompts/server/actions/createPrompt.ts
@@ -8,6 +8,7 @@ import { type PrismaClient } from "@langfuse/shared/src/db";
import { LATEST_PROMPT_LABEL } from "@/src/features/prompts/constants";
import { removeLabelsFromPreviousPromptVersions } from "@/src/features/prompts/server/utils/updatePromptLabels";
import { updatePromptTagsOnAllVersions } from "@/src/features/prompts/server/utils/updatePromptTags";
+import { PromptService, redis } from "@langfuse/shared/src/server";
export type CreatePromptParams = CreatePromptTRPCType & {
createdBy: string;
@@ -82,7 +83,16 @@ export const createPrompt = async ({
})),
);
+ // Lock and invalidate cache for _all_ versions and labels of the prompt name
+ const promptService = new PromptService(prisma, redis);
+ await promptService.lockCache({ projectId, promptName: name });
+ await promptService.invalidateCache({ projectId, promptName: name });
+
+ // Create prompt and update previous prompt versions
const [createdPrompt] = await prisma.$transaction(create);
+ // Unlock cache
+ await promptService.unlockCache({ projectId, promptName: name });
+
return createdPrompt;
};
diff --git a/web/src/features/prompts/server/actions/getPromptByName.ts b/web/src/features/prompts/server/actions/getPromptByName.ts
index b1727b3827..68434d4b65 100644
--- a/web/src/features/prompts/server/actions/getPromptByName.ts
+++ b/web/src/features/prompts/server/actions/getPromptByName.ts
@@ -1,10 +1,8 @@
import { PRODUCTION_LABEL } from "@/src/features/prompts/constants";
-import {
- LangfuseNotFoundError,
- InvalidRequestError,
- type Prompt,
-} from "@langfuse/shared";
+import { InvalidRequestError, type Prompt } from "@langfuse/shared";
+import { PromptService, redis } from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
+import * as Sentry from "@sentry/nextjs";
type GetPromptByNameParams = {
promptName: string;
@@ -17,90 +15,35 @@ export const getPromptByName = async (
params: GetPromptByNameParams,
): Promise<Prompt | null> => {
const { promptName, projectId, version, label } = params;
+ const promptService = new PromptService(
+ prisma,
+ redis,
+ Sentry.metrics.increment,
+ );
if (version && label)
throw new InvalidRequestError("Cannot specify both version and label");
- if (version) return getPromptByVersion({ projectId, promptName, version });
-
- if (label) return getPromptByLabel({ projectId, promptName, label });
-
- return getProductionPrompt(params);
-};
-
-const getProductionPrompt = async ({
- promptName,
- projectId,
-}: {
- promptName: string;
- projectId: string;
-}): Promise<Prompt> => {
- const productionPrompt = await prisma.prompt.findFirst({
- where: {
- projectId: projectId,
- name: promptName,
- labels: {
- has: PRODUCTION_LABEL,
- },
- },
- });
-
- if (!productionPrompt)
- throw new LangfuseNotFoundError(
- `No production-labeled prompt found with name '${promptName}' in project ${projectId}`,
- );
-
- return productionPrompt;
-};
-
-const getPromptByVersion = async ({
- promptName,
- projectId,
- version,
-}: {
- promptName: string;
- projectId: string;
- version: number;
-}): Promise<Prompt> => {
- const prompt = await prisma.prompt.findFirst({
- where: {
- projectId: projectId,
- name: promptName,
- version: version,
- },
+ if (version)
+ return promptService.getPrompt({
+ projectId,
+ promptName,
+ version,
+ label: undefined,
+ });
+
+ if (label)
+ return promptService.getPrompt({
+ projectId,
+ promptName,
+ label,
+ version: undefined,
+ });
+
+ return promptService.getPrompt({
+ projectId,
+ promptName,
+ label: PRODUCTION_LABEL,
+ version: undefined,
});
-
- if (!prompt)
- throw new LangfuseNotFoundError(
- `No prompt found with name '${promptName}' in project ${projectId} with version ${version}`,
- );
-
- return prompt;
-};
-
-const getPromptByLabel = async ({
- promptName,
- projectId,
- label,
-}: {
- promptName: string;
- projectId: string;
- label: string;
-}): Promise<Prompt> => {
- const prompt = await prisma.prompt.findFirst({
- where: {
- projectId: projectId,
- name: promptName,
- labels: {
- has: label,
- },
- },
- });
-
- if (!prompt)
- throw new LangfuseNotFoundError(
- `No prompt found with name '${promptName}' in project ${projectId} with label ${label}`,
- );
-
- return prompt;
};
diff --git a/web/src/features/prompts/server/handlers/promptNameHandler.ts b/web/src/features/prompts/server/handlers/promptNameHandler.ts
index f67a3ade2a..10a3d68d16 100644
--- a/web/src/features/prompts/server/handlers/promptNameHandler.ts
+++ b/web/src/features/prompts/server/handlers/promptNameHandler.ts
@@ -5,6 +5,8 @@ import { GetPromptByNameSchema } from "@/src/features/prompts/server/utils/valid
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
import { authorizePromptRequestOrThrow } from "../utils/authorizePromptRequest";
+import { LangfuseNotFoundError } from "@langfuse/shared";
+import { PRODUCTION_LABEL } from "@/src/features/prompts/constants";
const getPromptNameHandler = async (
req: NextApiRequest,
@@ -20,6 +22,18 @@ const getPromptNameHandler = async (
label,
});
+ if (!prompt) {
+ let errorMessage = `Prompt not found: '${promptName}'`;
+
+ if (version) {
+ errorMessage += ` with version ${version}`;
+ } else {
+ errorMessage += ` with label '${label ?? PRODUCTION_LABEL}'`;
+ }
+
+ throw new LangfuseNotFoundError(errorMessage);
+ }
+
return res.status(200).json(prompt);
};
diff --git a/web/src/features/prompts/server/routers/promptRouter.ts b/web/src/features/prompts/server/routers/promptRouter.ts
index 7c436373ca..86062d31b4 100644
--- a/web/src/features/prompts/server/routers/promptRouter.ts
+++ b/web/src/features/prompts/server/routers/promptRouter.ts
@@ -19,6 +19,7 @@ import {
tableColumnsToSqlFilterAndPrefix,
} from "@langfuse/shared";
import { LATEST_PROMPT_LABEL } from "@/src/features/prompts/constants";
+import { PromptService, redis } from "@langfuse/shared/src/server";
const PromptFilterOptions = z.object({
projectId: z.string(), // Required for protectedProjectProcedure
@@ -248,16 +249,18 @@ export const promptRouter = createTRPCRouter({
)
.mutation(async ({ input, ctx }) => {
try {
+ const { projectId, promptName } = input;
+
throwIfNoAccess({
session: ctx.session,
- projectId: input.projectId,
+ projectId,
scope: "prompts:CUD",
});
// fetch prompts before deletion to enable audit logging
const prompts = await ctx.prisma.prompt.findMany({
where: {
- projectId: input.projectId,
+ projectId,
name: input.promptName,
},
});
@@ -275,14 +278,23 @@ export const promptRouter = createTRPCRouter({
);
}
+ // Lock and invalidate cache for _all_ versions and labels of the prompt
+ const promptService = new PromptService(ctx.prisma, redis);
+ await promptService.lockCache({ projectId, promptName });
+ await promptService.invalidateCache({ projectId, promptName });
+
+ // Delete all prompts with the given name
await ctx.prisma.prompt.deleteMany({
where: {
- projectId: input.projectId,
+ projectId,
id: {
in: prompts.map((p) => p.id),
},
},
});
+
+ // Unlock cache
+ await promptService.unlockCache({ projectId, promptName });
} catch (e) {
console.log(e);
throw e;
@@ -296,19 +308,22 @@ export const promptRouter = createTRPCRouter({
}),
)
.mutation(async ({ input, ctx }) => {
+ const { projectId } = input;
+
try {
throwIfNoAccess({
session: ctx.session,
- projectId: input.projectId,
+ projectId,
scope: "prompts:CUD",
});
const promptVersion = await ctx.prisma.prompt.findFirstOrThrow({
where: {
id: input.promptVersionId,
- projectId: input.projectId,
+ projectId,
},
});
+ const { name: promptName } = promptVersion;
await auditLog(
{
@@ -325,7 +340,7 @@ export const promptRouter = createTRPCRouter({
ctx.prisma.prompt.delete({
where: {
id: input.promptVersionId,
- projectId: input.projectId,
+ projectId,
},
}),
];
@@ -334,8 +349,8 @@ export const promptRouter = createTRPCRouter({
if (promptVersion.labels.includes(LATEST_PROMPT_LABEL)) {
const newLatestPrompt = await ctx.prisma.prompt.findFirst({
where: {
- projectId: input.projectId,
- name: promptVersion.name,
+ projectId,
+ name: promptName,
id: { not: input.promptVersionId },
},
orderBy: [{ version: "desc" }],
@@ -358,7 +373,16 @@ export const promptRouter = createTRPCRouter({
}
}
+ // Lock and invalidate cache for _all_ versions and labels of the prompt
+ const promptService = new PromptService(ctx.prisma, redis);
+ await promptService.lockCache({ projectId, promptName });
+ await promptService.invalidateCache({ projectId, promptName });
+
+ // Execute transaction
await ctx.prisma.$transaction(transaction);
+
+ // Unlock cache
+ await promptService.unlockCache({ projectId, promptName });
} catch (e) {
console.log(e);
throw e;
@@ -374,19 +398,22 @@ export const promptRouter = createTRPCRouter({
)
.mutation(async ({ input, ctx }) => {
try {
+ const { projectId } = input;
+
throwIfNoAccess({
session: ctx.session,
- projectId: input.projectId,
+ projectId,
scope: "prompts:CUD",
});
const toBeLabeledPrompt = await ctx.prisma.prompt.findUniqueOrThrow({
where: {
id: input.promptId,
- projectId: input.projectId,
+ projectId,
},
});
+ const { name: promptName } = toBeLabeledPrompt;
const newLabels = [...new Set(input.labels)];
await auditLog(
@@ -405,8 +432,8 @@ export const promptRouter = createTRPCRouter({
const previousLabeledPrompts = await ctx.prisma.prompt.findMany({
where: {
- projectId: input.projectId,
- name: toBeLabeledPrompt.name,
+ projectId,
+ name: promptName,
labels: { hasSome: newLabels },
id: { not: input.promptId },
},
@@ -417,7 +444,7 @@ export const promptRouter = createTRPCRouter({
ctx.prisma.prompt.update({
where: {
id: toBeLabeledPrompt.id,
- projectId: input.projectId,
+ projectId,
},
data: {
labels: newLabels,
@@ -431,7 +458,7 @@ export const promptRouter = createTRPCRouter({
ctx.prisma.prompt.update({
where: {
id: prevPrompt.id,
- projectId: input.projectId,
+ projectId,
},
data: {
labels: prevPrompt.labels.filter((l) => !newLabels.includes(l)),
@@ -439,7 +466,17 @@ export const promptRouter = createTRPCRouter({
}),
);
});
+
+ // Lock and invalidate cache for _all_ versions and labels of the prompt
+ const promptService = new PromptService(ctx.prisma, redis);
+ await promptService.lockCache({ projectId, promptName });
+ await promptService.invalidateCache({ projectId, promptName });
+
+ // Execute transaction
await ctx.prisma.$transaction(toBeExecuted);
+
+ // Unlock cache
+ await promptService.unlockCache({ projectId, promptName });
} catch (e) {
console.log(e);
throw e;
diff --git a/web/src/pages/api/public/prompts.ts b/web/src/pages/api/public/prompts.ts
index f2dbe5875b..3f59fd679b 100644
--- a/web/src/pages/api/public/prompts.ts
+++ b/web/src/pages/api/public/prompts.ts
@@ -15,10 +15,11 @@ import {
BaseError,
MethodNotAllowedError,
ForbiddenError,
+ type Prompt,
} from "@langfuse/shared";
+import { PromptService, redis } from "@langfuse/shared/src/server";
import { PRODUCTION_LABEL } from "@/src/features/prompts/constants";
import * as Sentry from "@sentry/node";
-import { redis } from "@langfuse/shared/src/server";
export default async function handler(
req: NextApiRequest,
@@ -42,18 +43,33 @@ export default async function handler(
// Handle GET requests
if (req.method === "GET") {
const searchParams = GetPromptSchema.parse(req.query);
- const prompt = await prisma.prompt.findFirst({
- where: {
- projectId: authCheck.scope.projectId,
- name: searchParams.name,
- version: searchParams.version ?? undefined, // if no version is given, we take the latest active prompt
- labels: !searchParams.version
- ? {
- has: PRODUCTION_LABEL,
- }
- : undefined, // if no prompt is active, there will be no prompt available
- },
- });
+ const projectId = authCheck.scope.projectId;
+ const promptName = searchParams.name;
+ const version = searchParams.version ?? undefined;
+
+ const promptService = new PromptService(
+ prisma,
+ redis,
+ Sentry.metrics.increment,
+ );
+
+ let prompt: Prompt | null = null;
+
+ if (version) {
+ prompt = await promptService.getPrompt({
+ projectId,
+ promptName,
+ version,
+ label: undefined,
+ });
+ } else {
+ prompt = await promptService.getPrompt({
+ projectId,
+ promptName,
+ label: PRODUCTION_LABEL,
+ version: undefined,
+ });
+ }
if (!prompt) throw new LangfuseNotFoundError("Prompt not found");
diff --git a/worker/src/__tests__/redis-consumer.test.ts b/worker/src/__tests__/redis-consumer.test.ts
index a25f471d03..ffdc90adee 100644
--- a/worker/src/__tests__/redis-consumer.test.ts
+++ b/worker/src/__tests__/redis-consumer.test.ts
@@ -4,7 +4,7 @@ import { randomUUID } from "crypto";
import { z } from "zod";
import logger from "../logger";
import { evalJobCreator } from "../queues/evalQueue";
-import { traceUpsertQueue } from "@langfuse/shared/src/server";
+import { getTraceUpsertQueue } from "@langfuse/shared/src/server";
describe.sequential("handle redis events", () => {
test("handle redis job succeeding", async () => {
@@ -23,6 +23,8 @@ describe.sequential("handle redis events", () => {
logger.info(`Eval Job with id ${job?.id} completed`);
});
+ const traceUpsertQueue = getTraceUpsertQueue();
+
expect(traceUpsertQueue).toBeDefined();
const job = await traceUpsertQueue?.add(QueueJobs.TraceUpsert, {
diff --git a/worker/src/api/index.ts b/worker/src/api/index.ts
index 667f1f86be..89531d838f 100644
--- a/worker/src/api/index.ts
+++ b/worker/src/api/index.ts
@@ -4,7 +4,7 @@ import * as Sentry from "@sentry/node";
import { EventBodySchema, EventName, QueueJobs } from "@langfuse/shared";
import {
convertTraceUpsertEventsToRedisEvents,
- traceUpsertQueue,
+ getTraceUpsertQueue,
} from "@langfuse/shared/src/server";
import { env } from "../env";
import logger from "../logger";
@@ -52,6 +52,8 @@ router
// Find set of traces per project. There might be two events for the same trace in one API call.
// If we don't deduplicate, we will end up processing the same trace twice on two different workers in parallel.
const jobs = convertTraceUpsertEventsToRedisEvents(event.data.payload);
+ const traceUpsertQueue = getTraceUpsertQueue();
+
await traceUpsertQueue?.addBulk(jobs); // add all jobs as bulk
if (traceUpsertQueue) {