🪢 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
fix(prompts): don't allow placeholders and variable with same name on same prompt version (#7598)
Nimar0f2d2b8850ae
diff --git a/web/src/__tests__/prompts.v2.servertest.ts b/web/src/__tests__/prompts.v2.servertest.tsindex 2b972da0b2..923aacdfef 100644--- a/web/src/__tests__/prompts.v2.servertest.ts+++ b/web/src/__tests__/prompts.v2.servertest.ts@@ -911,6 +911,65 @@ describe("/api/public/v2/prompts API Endpoint", () => {"This is a prompt in a folder structure",);});++ it("should prevent creating a prompt with both a variable and placeholder with the same name", async () => {+ const promptName = "prompt-same-name-conflict-" + nanoid();++ // Try to create a prompt where the same name is used as both a variable and a placeholder+ const response = await makeAPICall("POST", baseURI, {+ name: promptName,+ prompt: [+ { role: "system", content: "Hello {{userName}}" },+ { type: ChatMessageType.Placeholder, name: "userName" },+ { role: "user", content: "How are you?" }+ ],+ type: "chat",+ });++ // This should fail with a 400 error+ expect(response.status).toBe(400);+ expect(response.body).toHaveProperty("error");+ expect(response.body).toHaveProperty("message");+ // @ts-expect-error+ expect(response.body.message).toContain("variables and placeholders must be unique");+ // @ts-expect-error+ expect(response.body.message).toContain("userName");+ });++ it("should allow creating a new version of a prompt with placeholder names that conflict a variable name in a previous version", async () => {+ const promptName = "prompt-with-variable-conflict-" + nanoid();++ // First, create a chat prompt with a message variable+ const v1Response = await makeAPICall("POST", baseURI, {+ name: promptName,+ prompt: [+ { role: "system", content: "You are a helpful {{conversationHistory}}" },+ { role: "user", content: "Continue our conversation" }+ ],+ type: "chat",+ labels: ["production"],+ });++ expect(v1Response.status).toBe(201);++ // Try to create a new version with a text variable that has the same name as the placeholder+ const v2Response = await makeAPICall("POST", baseURI, {+ name: promptName,+ prompt: [+ { role: "system", content: "You are a helpful assistant with context: {{newHistory}}" },+ { type: "placeholder", name: "conversationHistory" },+ { role: "user", content: "Continue our conversation" }+ ],+ type: "chat"+ });++ // This should succeed, we allow cross-version name reuse+ expect(v2Response.status).toBe(201);+ expect(v2Response.body).toHaveProperty("id");+ expect(v2Response.body).toHaveProperty("version");+ // @ts-expect-error - Response body type is flexible for testing+ expect(v2Response.body.version).toBe(2);+ });});describe("when fetching a prompt list", () => {diff --git a/web/src/features/playground/page/components/MessagePlaceholderComponent.tsx b/web/src/features/playground/page/components/MessagePlaceholderComponent.tsxindex 4f9cd82e68..33c0ea8431 100644--- a/web/src/features/playground/page/components/MessagePlaceholderComponent.tsx+++ b/web/src/features/playground/page/components/MessagePlaceholderComponent.tsx@@ -6,14 +6,17 @@ import { type ChatMessage, PromptChatMessageListSchema } from "@langfuse/shared"import { usePlaygroundContext } from "../context";import { type PlaceholderMessageFillIn } from "../types";+import { useNamingConflicts } from "../hooks/useNamingConflicts";export const MessagePlaceholderComponent: React.FC<{messagePlaceholder: PlaceholderMessageFillIn;}> = ({ messagePlaceholder }) => {- const { updateMessagePlaceholderValue, deleteMessagePlaceholder } =+ const { updateMessagePlaceholderValue, deleteMessagePlaceholder, promptVariables, messagePlaceholders } =usePlaygroundContext();const { name, value, isUsed } = messagePlaceholder;const [error, setError] = useState<string | null>(null);+ const { isPlaceholderConflicting } = useNamingConflicts(promptVariables, messagePlaceholders);+ const hasConflict = isPlaceholderConflicting(name);const handleInputChange = useCallback((jsonString: string) => {try {@@ -39,7 +42,7 @@ export const MessagePlaceholderComponent: React.FC<{<div className="mb-1 flex flex-row items-center"><span className="flex flex-1 flex-row space-x-2 text-xs"><UsedIcon size={16} color={iconColor} />- <p className="min-w-[90px] truncate font-mono" title={name}>+ <p className={`min-w-[90px] truncate font-mono ${hasConflict ? 'text-red-500' : ''}`} title={name}>{name ? name : "Unnamed placeholder"}</p></span>@@ -60,12 +63,17 @@ export const MessagePlaceholderComponent: React.FC<{onChange={handleInputChange}mode="json"minHeight="none"- className="max-h-[15rem] w-full resize-y p-1 font-mono text-xs focus:outline-none"+ className={`max-h-[15rem] w-full resize-y p-1 font-mono text-xs focus:outline-none ${hasConflict ? 'border border-red-500' : ''}`}editable={true}lineNumbers={false}placeholder={`[\n {\n "role": "user",\n "content": "Hello!"\n },\n {\n "role": "assistant",\n "content": "Hi there!"\n }\n]`}/>+ {hasConflict && (+ <p className="mt-1 text-xs text-red-500">+ Placeholder name conflicts with variable. Names must be unique.+ </p>+ )}{error && (<p className="mt-1 text-xs text-red-500">{error}</p>)}diff --git a/web/src/features/playground/page/components/PromptVariableComponent.tsx b/web/src/features/playground/page/components/PromptVariableComponent.tsxindex b357b157b4..27ae81c388 100644--- a/web/src/features/playground/page/components/PromptVariableComponent.tsx+++ b/web/src/features/playground/page/components/PromptVariableComponent.tsx@@ -4,13 +4,16 @@ import { type PromptVariable } from "@langfuse/shared";import { CodeMirrorEditor } from "@/src/components/editor";import { usePlaygroundContext } from "../context";+import { useNamingConflicts } from "../hooks/useNamingConflicts";export const PromptVariableComponent: React.FC<{promptVariable: PromptVariable;}> = ({ promptVariable }) => {- const { updatePromptVariableValue, deletePromptVariable } =+ const { updatePromptVariableValue, deletePromptVariable, promptVariables, messagePlaceholders } =usePlaygroundContext();const { name, value, isUsed } = promptVariable;+ const { isVariableConflicting } = useNamingConflicts(promptVariables, messagePlaceholders);+ const hasConflict = isVariableConflicting(name);const handleInputChange = (value: string) => {updatePromptVariableValue(name, value);@@ -32,7 +35,7 @@ export const PromptVariableComponent: React.FC<{<div className="mb-1 flex flex-row items-center"><span className="flex flex-1 flex-row space-x-2 text-xs"><p title={isUsedTooltip}>{isUsedIcon}</p>- <p className="min-w-[90px] truncate font-mono" title={name}>+ <p className={`min-w-[90px] truncate font-mono ${hasConflict ? 'text-red-500' : ''}`} title={name}>{name}</p></span>@@ -53,11 +56,17 @@ export const PromptVariableComponent: React.FC<{onChange={(e) => handleInputChange(e)}mode="prompt"minHeight="none"- className="max-h-[10rem] w-full resize-y p-1 font-mono text-xs focus:outline-none"+ className={`max-h-[10rem] w-full resize-y p-1 font-mono text-xs focus:outline-none ${hasConflict ? 'border border-red-500' : ''}`}editable={true}lineNumbers={false}placeholder={name}/>++ {hasConflict && (+ <p className="mt-1 text-xs text-red-500">+ Variable name conflicts with placeholder. Names must be unique.+ </p>+ )}</div>);};diff --git a/web/src/features/playground/page/hooks/useNamingConflicts.ts b/web/src/features/playground/page/hooks/useNamingConflicts.tsnew file mode 100644index 0000000000..9029379cde--- /dev/null+++ b/web/src/features/playground/page/hooks/useNamingConflicts.ts@@ -0,0 +1,43 @@+import { useMemo } from "react";+import { type PromptVariable } from "@langfuse/shared";+import { type PlaceholderMessageFillIn } from "../types";++export interface NamingConflictInfo {+ hasConflicts: boolean;+ conflictingNames: string[];+ isVariableConflicting: (variableName: string) => boolean;+ isPlaceholderConflicting: (placeholderName: string) => boolean;+}++/**+ * Detects naming conflicts between variables and placeholders in the playground.+ * Returns names of conflicting variables and placeholders.+ */+export const useNamingConflicts = (+ variables: PromptVariable[],+ placeholders: PlaceholderMessageFillIn[]+): NamingConflictInfo => {+ return useMemo(() => {+ const variableNames = variables.map(v => v.name);+ const placeholderNames = placeholders.map(p => p.name);++ const conflictingNames = variableNames.filter(name =>+ placeholderNames.includes(name)+ );++ const hasConflicts = conflictingNames.length > 0;++ const isVariableConflicting = (variableName: string) =>+ conflictingNames.includes(variableName);++ const isPlaceholderConflicting = (placeholderName: string) =>+ conflictingNames.includes(placeholderName);++ return {+ hasConflicts,+ conflictingNames,+ isVariableConflicting,+ isPlaceholderConflicting,+ };+ }, [variables, placeholders]);+};diff --git a/web/src/features/prompts/server/actions/createPrompt.ts b/web/src/features/prompts/server/actions/createPrompt.tsindex 75e2642400..7711cfcc36 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 CreatePromptTRPCType,LATEST_PROMPT_LABEL,PromptType,+ extractVariables,} from "@langfuse/shared";import { type PrismaClient } from "@langfuse/shared/src/db";import { removeLabelsFromPreviousPromptVersions } from "@/src/features/prompts/server/utils/updatePromptLabels";@@ -16,6 +17,7 @@ import {PromptContentSchema,PromptService,redis,+ extractPlaceholderNames,} from "@langfuse/shared/src/server";export type CreatePromptParams = CreatePromptTRPCType & {@@ -32,6 +34,22 @@ type DuplicatePromptParams = {prisma: PrismaClient;};+const extractChatVariableAndPlaceholderNames = (+ chatPrompt: Array<any>,+): { variables: string[], placeholders: string[] } => {+ const placeholders = extractPlaceholderNames(chatPrompt);++ const variables: string[] = [];+ for (const message of chatPrompt) {+ if (message && 'content' in message && typeof message.content === 'string') {+ variables.push(...extractVariables(message.content));+ }+ }++ return { variables: [...new Set(variables)], placeholders: [...new Set(placeholders)] };+};++export const createPrompt = async ({projectId,name,@@ -55,6 +73,17 @@ export const createPrompt = async ({);}+ // Prevent naming collisions between variables and placeholders+ if (type === PromptType.Chat && Array.isArray(prompt)) {+ const { variables, placeholders } = extractChatVariableAndPlaceholderNames(prompt);+ const conflictingNames = variables.filter(v => placeholders.includes(v));+ if (conflictingNames.length > 0) {+ throw new InvalidRequestError(+ `Cannot create prompt, variables and placeholders must be unique, the following are not: ${conflictingNames.join(", ")}`+ );+ }+ }+const finalLabels = [...labels, LATEST_PROMPT_LABEL]; // Newly created prompts are always labeled as 'latest'// If tags are undefined, use the tags from the latest prompt version@@ -185,7 +214,7 @@ export const duplicatePrompt = async ({});if (!existingPrompt) {- throw new Error(`Existing prompt not found: ${promptId}`);+ throw new InvalidRequestError(`Existing prompt not found: ${promptId}`);}// if defined as single version, duplicate current prompt as new prompt v1@@ -253,7 +282,7 @@ export const duplicatePrompt = async ({return promptResult;});- // If you need the created prompt, fetch it separately since createMany doesn't return created records+ // Fetch the created prompt to returnconst createdPrompt = await prisma.prompt.findFirst({where: {name,